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
iamrajhans/RatingAppiOS
RatingApp/RatingApp/AppDelegate.swift
1
6099
// // AppDelegate.swift // RatingApp // // Created by Rajhans Jadhao on 11/09/16. // Copyright © 2016 Rajhans Jadhao. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.drone.RatingApp" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("RatingApp", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
0af6520c56d9bac22b763300175ff034
53.936937
291
0.719744
5.869105
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/CreateEntity.swift
2
2873
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** CreateEntity. */ public struct CreateEntity: Encodable { /// The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 64 characters. public var entity: String /// The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. public var description: String? /// Any metadata related to the value. public var metadata: [String: JSON]? /// An array of objects describing the entity values. public var values: [CreateValue]? /// Whether to use fuzzy matching for the entity. public var fuzzyMatch: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case entity = "entity" case description = "description" case metadata = "metadata" case values = "values" case fuzzyMatch = "fuzzy_match" } /** Initialize a `CreateEntity` with member variables. - parameter entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 64 characters. - parameter description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter metadata: Any metadata related to the value. - parameter values: An array of objects describing the entity values. - parameter fuzzyMatch: Whether to use fuzzy matching for the entity. - returns: An initialized `CreateEntity`. */ public init(entity: String, description: String? = nil, metadata: [String: JSON]? = nil, values: [CreateValue]? = nil, fuzzyMatch: Bool? = nil) { self.entity = entity self.description = description self.metadata = metadata self.values = values self.fuzzyMatch = fuzzyMatch } }
mit
7d0cfa6b56f8e6d85862c0579798db6a
43.2
280
0.708667
4.611557
false
false
false
false
jeffreybergier/udacity-animation
animation-playground.playground/Pages/Gesture Recognizers.xcplaygroundpage/Contents.swift
1
3261
//: [Previous](@previous) import UIKit import XCPlayground // MARK: Custom View Controller Subclass class SpringViewController: UIViewController { // MARK: Custom Properties let redView: UIView = { let view = UIView() view.backgroundColor = UIColor.redColor() view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var xConstraint: NSLayoutConstraint = { self.redView.centerXAnchor.constraintEqualToAnchor(vc.view.centerXAnchor, constant: 0) }() lazy var yConstraint: NSLayoutConstraint = { self.redView.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor, constant: 0) }() // MARK: Configure the View Controller override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.configureRedView() } // MARK: Add View to Animate // and configure constraints func configureRedView() { vc.view.addSubview(self.redView) NSLayoutConstraint.activateConstraints( [ self.xConstraint, self.yConstraint, self.redView.heightAnchor.constraintEqualToConstant(60), self.redView.widthAnchor.constraintEqualToConstant(60) ] ) } // MARK: Handle Animations from Gesture Recognizer func animateBackToCenter() { UIView.animateWithDuration( 0.6, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 1.5, options: [], animations: { self.xConstraint.constant = 0 self.yConstraint.constant = 0 vc.view.setNeedsLayout() }, completion: { finished in print("Snapped Back") } ) } func gestureFired(sender: UIPanGestureRecognizer) { switch sender.state { case .Began, .Possible: // don't need to do anything to start break case .Changed: // get the amount of change cause by the finger moving let translation = sender.translationInView(vc.view) // add that change to our autolayout constraints xConstraint.constant += translation.x yConstraint.constant += translation.y // tell the view to update vc.view.setNeedsLayout() // reset the translation in the gesture recognizer to 0 // try removing this line of code and see what happens when dragging sender.setTranslation(CGPoint.zero, inView: vc.view) case .Cancelled, .Ended, .Failed: // animate back to the center when done animateBackToCenter() } } } // MARK: Instantiate Spring View Controller let vc = SpringViewController() vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 600) XCPlaygroundPage.currentPage.liveView = vc.view // MARK: Configure Gesture Recognizer let panGestureRecognizer = UIPanGestureRecognizer(target: vc, action: #selector(vc.gestureFired(_:))) vc.redView.addGestureRecognizer(panGestureRecognizer)
mit
15cfea5ef80f3050a8364fada71290d7
30.970588
139
0.611469
5.40796
false
false
false
false
ruslanskorb/CoreStore
Sources/XcodeDataModelSchema.swift
2
9223
// // XcodeDataModelSchema.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - XcodeDataModelSchema /** The `XcodeDataModelSchema` describes a model version declared in a single *.xcdatamodeld file. ``` CoreStoreDefaults.dataStack = DataStack( XcodeDataModelSchema(modelName: "MyAppV1", bundle: .main) ) ``` */ public final class XcodeDataModelSchema: DynamicSchema { /** Creates a `XcodeDataModelSchema` for each of the models declared in the specified (.xcdatamodeld) model file. - parameter modelName: the name of the (.xcdatamodeld) model file. If not specified, the application name (CFBundleName) will be used if it exists, or "CoreData" if it the bundle name was not set. - parameter bundle: an optional bundle to load .xcdatamodeld models from. If not specified, the main bundle will be used. - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. - returns: a tuple containing all `XcodeDataModelSchema` for the models declared in the specified .xcdatamodeld file, and the current model version string declared or inferred from the file. */ public static func from(modelName: XcodeDataModelFileName, bundle: Bundle = Bundle.main, migrationChain: MigrationChain = nil) -> (allSchema: [XcodeDataModelSchema], currentModelVersion: ModelVersion) { guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else { // For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model. let foundModels = bundle .paths(forResourcesOfType: "momd", inDirectory: nil) .map({ ($0 as NSString).lastPathComponent }) Internals.abort("Could not find \"\(modelName).momd\" from the bundle \"\(bundle.bundleIdentifier ?? "<nil>")\". Other model files in bundle: \(foundModels.coreStoreDumpString)") } let modelFileURL = URL(fileURLWithPath: modelFilePath) let versionInfoPlistURL = modelFileURL.appendingPathComponent("VersionInfo.plist", isDirectory: false) guard let versionInfo = NSDictionary(contentsOf: versionInfoPlistURL), let versionHashes = versionInfo["NSManagedObjectModel_VersionHashes"] as? [String: AnyObject] else { Internals.abort("Could not load \(Internals.typeName(NSManagedObjectModel.self)) metadata from path \"\(versionInfoPlistURL)\".") } let modelVersions = Set(versionHashes.keys) let modelVersionHints = migrationChain.leafVersions let currentModelVersion: String if let plistModelVersion = versionInfo["NSManagedObjectModel_CurrentVersionName"] as? String, modelVersionHints.isEmpty || modelVersionHints.contains(plistModelVersion) { currentModelVersion = plistModelVersion } else if let resolvedVersion = modelVersions.intersection(modelVersionHints).first { Internals.log( .warning, message: "The \(Internals.typeName(MigrationChain.self)) leaf versions do not include the model file's current version. Resolving to version \"\(resolvedVersion)\"." ) currentModelVersion = resolvedVersion } else if let resolvedVersion = modelVersions.first ?? modelVersionHints.first { if !modelVersionHints.isEmpty { Internals.log( .warning, message: "The \(Internals.typeName(MigrationChain.self)) leaf versions do not include any of the model file's embedded versions. Resolving to version \"\(resolvedVersion)\"." ) } currentModelVersion = resolvedVersion } else { Internals.abort("No model files were found in URL \"\(modelFileURL)\".") } var allSchema: [XcodeDataModelSchema] = [] for modelVersion in modelVersions { let fileURL = modelFileURL.appendingPathComponent("\(modelVersion).mom", isDirectory: false) allSchema.append(XcodeDataModelSchema(modelName: modelVersion, modelVersionFileURL: fileURL)) } return (allSchema, currentModelVersion) } /** Initializes an `XcodeDataModelSchema` from an *.xcdatamodeld version name and its containing `Bundle`. ``` CoreStoreDefaults.dataStack = DataStack( XcodeDataModelSchema(modelName: "MyAppV1", bundle: .main) ) ``` - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter bundle: the `Bundle` that contains the .xcdatamodeld's "momd" file. If not specified, the `Bundle.main` will be searched. */ public convenience init(modelName: ModelVersion, bundle: Bundle = Bundle.main) { guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else { // For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model. let foundModels = bundle .paths(forResourcesOfType: "momd", inDirectory: nil) .map({ ($0 as NSString).lastPathComponent }) Internals.abort("Could not find \"\(modelName).momd\" from the bundle \"\(bundle.bundleIdentifier ?? "<nil>")\". Other model files in bundle: \(foundModels.coreStoreDumpString)") } let modelFileURL = URL(fileURLWithPath: modelFilePath) let fileURL = modelFileURL.appendingPathComponent("\(modelName).mom", isDirectory: false) self.init(modelName: modelName, modelVersionFileURL: fileURL) } /** Initializes an `XcodeDataModelSchema` from an *.xcdatamodeld file URL. ``` CoreStoreDefaults.dataStack = DataStack( XcodeDataModelSchema(modelName: "MyAppV1", modelVersionFileURL: fileURL) ) ``` - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter modelVersionFileURL: the file URL that points to the .xcdatamodeld's "momd" file. */ public required init(modelName: ModelVersion, modelVersionFileURL: URL) { Internals.assert( NSManagedObjectModel(contentsOf: modelVersionFileURL) != nil, "Could not find the \"\(modelName).mom\" version file for the model at URL \"\(modelVersionFileURL)\"." ) self.modelVersion = modelName self.modelVersionFileURL = modelVersionFileURL } // MARK: DynamicSchema public let modelVersion: ModelVersion public func rawModel() -> NSManagedObjectModel { if let cachedRawModel = self.cachedRawModel { return cachedRawModel } if let rawModel = NSManagedObjectModel(contentsOf: self.modelVersionFileURL) { self.cachedRawModel = rawModel return rawModel } Internals.abort("Could not create an \(Internals.typeName(NSManagedObjectModel.self)) from the model at URL \"\(self.modelVersionFileURL)\".") } // MARK: Internal internal let modelVersionFileURL: URL private lazy var rootModelFileURL: URL = Internals.with { [unowned self] in return self.modelVersionFileURL.deletingLastPathComponent() } // MARK: Private private weak var cachedRawModel: NSManagedObjectModel? }
mit
613c450bd0da9adf7b0c9504daff354f
47.793651
264
0.675125
5.272727
false
false
false
false
nsnull0/YWTopInputField
YWTopInputField/Classes/YWTopInputFieldLogic.swift
1
3248
// // YWTopInputFieldLogic.swift // YWTopInputField // // Created by Yoseph Wijaya on 2017/06/25. // Copyright © 2017 Yoseph Wijaya. All rights reserved. // import UIKit struct propertyVal { var correctionType:UITextAutocorrectionType = .no var spellCheckType:UITextSpellCheckingType = .no var keyboardType:UIKeyboardType = .default var keyboardAppearance:UIKeyboardAppearance = .default var containerEffectType:UIBlurEffectStyle = .dark var titleColorText:UIColor = .white var messageColorText:UIColor = .white var titleFontText:UIFont = .boldSystemFont(ofSize: 15.0) var messageFontText:UIFont = .systemFont(ofSize: 12.0) var heightContainerConstraint:CGFloat = 200 } public class YWTopInputFieldLogic { var propertyYW:propertyVal = propertyVal() public func setCorrectionType(_type:UITextAutocorrectionType) -> YWTopInputFieldLogic { self.propertyYW.correctionType = _type return self } public func setSpellCheckType(_type:UITextSpellCheckingType) -> YWTopInputFieldLogic { self.propertyYW.spellCheckType = _type return self } public func setKeyboardType(_type:UIKeyboardType) -> YWTopInputFieldLogic { self.propertyYW.keyboardType = _type return self } public func setKeyboardAppearance(_type:UIKeyboardAppearance) -> YWTopInputFieldLogic { self.propertyYW.keyboardAppearance = _type return self } public func setBlurStyleEffectContainer(_type:UIBlurEffectStyle) -> YWTopInputFieldLogic { self.propertyYW.containerEffectType = _type return self } public func setTitleColor(_color:UIColor) -> YWTopInputFieldLogic { self.propertyYW.titleColorText = _color return self } public func setMessageColor(_color:UIColor) -> YWTopInputFieldLogic { self.propertyYW.messageColorText = _color return self } public func setFontTitle(_font:UIFont) -> YWTopInputFieldLogic { self.propertyYW.titleFontText = _font return self } public func setMessageFont(_font:UIFont) -> YWTopInputFieldLogic { self.propertyYW.messageFontText = _font return self } public func setHeightTextContainer(_height:CGFloat) -> YWTopInputFieldLogic { guard _height >= 200 else { return self } self.propertyYW.heightContainerConstraint = _height return self } public func validate() { if self.propertyYW.heightContainerConstraint < 200 { self.propertyYW.heightContainerConstraint = 200 } } //MARK: Static Function static func checkValidate(_onContent targetStr:String, _defaultContent content:String) -> String { let strProcess = targetStr.replacingOccurrences(of: " ", with: "") guard strProcess.characters.count > 0 else { return content } return targetStr } }
mit
982a2492f159aae118ce8d72016fd922
25.185484
102
0.627656
5.041925
false
false
false
false
cuappdev/podcast-ios
old/Podcast/TopicsGridCollectionViewCell.swift
1
2352
// // TopicsGridCollectionViewCell.swift // Podcast // // Created by Mindy Lou on 12/22/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit class TopicsGridCollectionViewCell: UICollectionViewCell { var backgroundLabel: UILabel! var backgroundTileImageView: ImageView! var topicLabel: UILabel! let topicLabelHeight: CGFloat = 18 let topicTileAlpha: CGFloat = 0.25 let backgroundColors: [UIColor] = [.rosyPink, .sea, .duskyBlue, .dullYellow] override init(frame: CGRect) { super.init(frame: frame) backgroundLabel = UILabel(frame: frame) addSubview(backgroundLabel) backgroundLabel.snp.makeConstraints { make in make.top.equalToSuperview() make.width.height.equalTo(frame.width) make.leading.trailing.equalToSuperview() } backgroundTileImageView = ImageView(frame: .zero) addSubview(backgroundTileImageView) backgroundTileImageView.snp.makeConstraints { make in make.top.equalToSuperview() make.width.height.equalTo(frame.width) make.leading.trailing.equalToSuperview() } topicLabel = UILabel(frame: .zero) topicLabel.textAlignment = .center topicLabel.lineBreakMode = .byWordWrapping topicLabel.numberOfLines = 0 topicLabel.textColor = .offWhite topicLabel.font = ._12SemiboldFont() addSubview(topicLabel) topicLabel.snp.makeConstraints { make in make.center.equalTo(backgroundLabel.snp.center) make.leading.trailing.equalToSuperview() make.width.equalTo(backgroundLabel.snp.width) } } override func layoutSubviews() { super.layoutSubviews() backgroundTileImageView.addCornerRadius(height: frame.width) backgroundLabel.addCornerRadius(height: frame.width) } func configure(for topic: Topic, at index: Int) { topicLabel.text = topic.name backgroundLabel.backgroundColor = backgroundColors[index % 4] if let topicType = topic.topicType { backgroundTileImageView.image = topicType.tileImage.withAlpha(topicTileAlpha) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
f0f6707002afa64cb465e3aeae22189d
31.205479
89
0.669928
4.600783
false
false
false
false
playgroundscon/Playgrounds
Playgrounds/Protocol/Request/Requestable.swift
1
2891
// // ScheduleDay.swift // Playgrounds // // Created by Andyy Hope on 18/11/16. // Copyright © 2016 Andyy Hope. All rights reserved. // import Foundation import SwiftyJSON public typealias Parameters = [String: AnyObject] public protocol Requestable { static func request(url: URL, parameters: Parameters?, log: Bool, function: String, file: String, completion: @escaping RequestResponse<JSON>.Completion) } public extension Requestable { // MARK: - Requester public static func request(url: URL, parameters: Parameters? = nil, log: Bool = false, function: String = #function, file: String = #file, completion: @escaping RequestResponse<JSON>.Completion) { let session = URLSession.shared var request = URLRequest(url: url) request.httpBody = httpBody(for: parameters) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") session.dataTask(with: request) { data, response, error in if log { print(file) print(function) print(url) if let parameters = parameters { print(parameters) } } if let error = error { print(error) print(file) print(url) completion(.fail(.session(error as NSError))) } else if let data = data { self.parseRequest(data: data, response: response, log: log, completion: completion) } else { fatalError("An unknown network error occurred.") } } .resume() } // MARK: - Parser internal static func parseRequest(data: Data, response: URLResponse?, log: Bool, completion: @escaping RequestResponse<JSON>.Completion) { var error: NSError? let json = JSON(data: data, options: .mutableLeaves, error: &error) DispatchQueue.main.async { if let error = error { completion(.fail(.invalidData(error))) } else { if log { print(json) } completion(.success(json)) } } } // MARK: - Parameter Utilities private static func httpBody(for parameters: Parameters?) -> Data? { guard let parameters = parameters else { return nil } do { let httpBody = try JSONSerialization.data(withJSONObject: parameters) return httpBody } catch let error as NSError { print(error) assertionFailure() return nil } catch let data as Data { return data } } }
gpl-3.0
21320822e8f700c750ee2d2d92dbcb35
30.413043
200
0.558131
5.061296
false
false
false
false
thebnich/firefox-ios
SyncTests/MockSyncServerTests.swift
8
9197
/* 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 UIKit import XCTest import Shared import Storage import Sync private class MockBackoffStorage: BackoffStorage { var serverBackoffUntilLocalTimestamp: Timestamp? func clearServerBackoff() { serverBackoffUntilLocalTimestamp = nil } func isInBackoff(now: Timestamp) -> Timestamp? { return nil } } class MockSyncServerTests: XCTestCase { var server: MockSyncServer! var client: Sync15StorageClient! override func setUp() { server = MockSyncServer(username: "1234567") server.start() client = getClient(server) } private func getClient(server: MockSyncServer) -> Sync15StorageClient? { guard let url = server.baseURL.asURL else { XCTFail("Couldn't get URL.") return nil } let authorizer: Authorizer = identity let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) print("URL: \(url)") return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage()) } func testDeleteSpec() { // Deletion of a collection path itself, versus trailing slash, sets the right flags. let all = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: [:])! XCTAssertTrue(all.wholeCollection) XCTAssertNil(all.ids) let some = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef"])! XCTAssertFalse(some.wholeCollection) XCTAssertEqual(["123456", "abcdef"], some.ids!) let one = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks/123456", withQuery: [:])! XCTAssertFalse(one.wholeCollection) XCTAssertNil(one.ids) } func testInfoCollections() { server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords([], inCollection: "tabs", now: 1326252222500) server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000) let expectation = self.expectationWithDescription("Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! client.getInfoCollections().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! // JSON contents. XCTAssertEqual(response.value.collectionNames().sort(), ["bookmarks", "clients", "tabs"]) XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000) XCTAssertEqual(response.value.modified("clients"), 1326253333000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs. // X-Last-Modified, max of all collection modified timestamps. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000) expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } func testGet() { server.storeRecords([MockSyncServer.makeValidEnvelope("guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000) let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter()) let expectation = self.expectationWithDescription("Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! collectionClient.get("guid").upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! // JSON contents. XCTAssertEqual(response.value.id, "guid") XCTAssertEqual(response.value.modified, 1326251111000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000) expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) // And now a missing record, which should produce a 404. collectionClient.get("missing").upon { result in XCTAssertNotNil(result.failureValue) guard let response = result.failureValue else { expectation.fulfill() return } XCTAssertNotNil(response as? NotFound<NSHTTPURLResponse>) } } func testWipeStorage() { server.storeRecords([MockSyncServer.makeValidEnvelope("a", modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords([MockSyncServer.makeValidEnvelope("b", modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords([MockSyncServer.makeValidEnvelope("c", modified: 0)], inCollection: "clients", now: 1326253333000) server.storeRecords([], inCollection: "tabs") // For now, only testing wiping the storage root, which is the only thing we use in practice. let expectation = self.expectationWithDescription("Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! client.wipeStorage().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! // JSON contents: should be the empty object. XCTAssertEqual(response.value.toString(), "{}") // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really wiped the data. XCTAssertTrue(self.server.collections.isEmpty) expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } func testPut() { // For now, only test uploading crypto/keys. There's nothing special about this PUT, however. let expectation = self.expectationWithDescription("Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))! // Contents: should be just the record timestamp. XCTAssertLessThanOrEqual(before, response.value) XCTAssertLessThanOrEqual(response.value, after) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really uploaded the record. XCTAssertNotNil(self.server.collections["crypto"]) XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"]) expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } }
mpl-2.0
af16c657f6760c3e2e1d282684f62c15
44.083333
145
0.66837
5.57732
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Event/NotUse/BFEventView.swift
1
9865
// // BFEventView.swift // BeeFun // // Created by WengHengcong on 23/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit /* event类型1:pull request类型 5 days ago ashfurrow opened pull request AFNetworking/AFNetworking#4051 ╭┈┈┈╮ Exposes C function prototype | | ------------------------------------------------ ╰┈┈┈╯ | -0- 1 commit with 1 addition and 0 deletions | ------------------------------------------------ */ /* event类型2:push commit、release类型 --->>>>>>>> push类型 4 days ago davemachado pushed to master at toddmotto/public-apis ╭┈┈┈╮ ╭-╮ 2f9b6f0 Merge pull request #486 from DustyReagan/countio | | ╰—╯ ╰┈┈┈╯ ╭-╮ 4e79d6d Remove '... API' from Description ╰—╯ View comparison for these 2 commits » or 15 more commits » 注意:后面有两种类型,一种是查看这两个commit的对比,一个是查看更多的commit --->>>>>>>> release类型 4 days ago davemachado pushed to master at toddmotto/public-apis ╭┈┈┈╮ ╭-╮ Source code (zip) | | ╰—╯ ╰┈┈┈╯ 注意:点击source code中直接下载zip文件 */ /* event类型3:opened issue、commented on issue 等类型 5 days ago ashfurrow opened pull request AFNetworking/AFNetworking#4051 ╭┈┈┈╮ | | Format string warnings ╰┈┈┈╯ */ /* event类型4:starred、forked等类型 5 days ago Bogdan-Lyashenko starred byoungd/english-level-up-tips-for-Chinese */ class BFEventView: UIView { var contentView: UIView = UIView() ///整个视图的容器 /// event 左上角的Action 图标,固定 var actionImageView = UIImageView() var timeView: BFEventTimeView? /// 时间 var titleView: BFEventTitleView? /// title /// 内容区域 var actionContentView = UIView() /// 内容区域的容器 var actorImageView = UIImageView() /// event 执行者头像 var textView: BFEventTextView? /// 内容,见类型1、3、4部分的文字内容区域 var prDetailView: BFEventPRDetailView? /// pull request的部分内容区域,见类型1 var commitView: BFEventCommitView? /// push commit的内容区域,见类型2 var topLine: UIView = UIView() var bottomLine: UIView = UIView() //数据 var cell: BFEventCell? var layout: BFEventLayout? override init(frame: CGRect) { var newFrame = frame if frame.size.width == 0 && frame.size.height == 0 { newFrame.size.width = ScreenSize.width newFrame.size.height = 1 } super.init(frame: newFrame) isUserInteractionEnabled = true backgroundColor = .clear contentView.backgroundColor = .clear contentView.isUserInteractionEnabled = true contentView.width = ScreenSize.width contentView.height = 1.0 self.addSubview(contentView) //line let retinaPixelSize = 1.0 / (UIScreen.main.scale) topLine.backgroundColor = UIColor.bfLineBackgroundColor topLine.frame = CGRect(x: 0, y: 0, w: self.width, h: retinaPixelSize) contentView.addSubview(topLine) bottomLine.backgroundColor = UIColor.bfLineBackgroundColor bottomLine.frame = CGRect(x: 0, y: self.height-retinaPixelSize, w: self.width, h: retinaPixelSize) contentView.addSubview(bottomLine) //action image name actionImageView.frame = CGRect(x: BFEventConstants.ACTION_IMG_LEFT, y: BFEventConstants.ACTION_IMG_TOP, w: BFEventConstants.ACTION_IMG_WIDTH, h: BFEventConstants.ACTION_IMG_WIDTH) // actionImageView.isHidden = true actionImageView.image = UIImage(named: "git-comment-discussion_50") actionImageView.isUserInteractionEnabled = true contentView.addSubview(actionImageView) //time timeView = BFEventTimeView() // timeView?.isHidden = true contentView.addSubview(timeView!) //title titleView = BFEventTitleView() // titleView?.isHidden = true contentView.addSubview(titleView!) //内容区域 actionContentView.backgroundColor = .clear actionContentView.isUserInteractionEnabled = true // actionContentView.isHidden = true contentView.addSubview(actionContentView) //actor image view actorImageView.frame = CGRect(x: 0, y: 0, w: BFEventConstants.ACTOR_IMG_WIDTH, h: BFEventConstants.ACTOR_IMG_WIDTH) actorImageView.isHidden = true actionContentView.addSubview(actorImageView) //text view textView = BFEventTextView() textView?.isHidden = true actionContentView.addSubview(textView!) //pull request detail view prDetailView = BFEventPRDetailView() prDetailView?.isHidden = true actionContentView.addSubview(prDetailView!) //commit view commitView = BFEventCommitView() commitView?.isHidden = true actionContentView.addSubview(commitView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setLayout(layout: BFEventLayout) { self.layout = layout //contnet view的位置 contentView.top = layout.marginTop contentView.height = layout.totalHeight - layout.marginTop - layout.marginBottom contentView.left = layout.marginLeft contentView.right = ScreenSize.width - layout.marginLeft //action image if let actionImageName = layout.eventTypeActionImage { actionImageView.image = UIImage(named: actionImageName) } //time timeView?.origin = CGPoint(x: BFEventConstants.TIME_X, y: BFEventConstants.TIME_Y) // timeView?.backgroundColor = UIColor.red if layout.timeHeight > 0 { timeView?.isHidden = false timeView?.height = layout.timeHeight timeView?.setLayout(layout: layout) } else { timeView?.isHidden = true } //title titleView?.origin = CGPoint(x: timeView!.left, y: timeView!.bottom) // titleView?.backgroundColor = UIColor.green if layout.titleHeight > 0 { titleView?.isHidden = false titleView?.height = layout.titleHeight titleView?.setLayout(layout: layout) } else { titleView?.isHidden = true } //-------------->>>>>> actionContentView 内容区域 <<<<<<<------------- actionContentView.origin = CGPoint(x: titleView!.left, y: titleView!.bottom) // actionContentView.backgroundColor = UIColor.red actionContentView.width = BFEventConstants.ACTION_CONTENT_WIDTH actionContentView.height = layout.actionContentHeight //actor image if let avatarUrl = layout.event?.actor?.avatar_url, let url = URL(string: avatarUrl) { actorImageView.isHidden = false actorImageView.origin = CGPoint(x: BFEventConstants.ACTOR_IMG_LEFT, y: BFEventConstants.ACTOR_IMG_TOP) actorImageView.kf.setImage(with: url) } else { actorImageView.isHidden = true } if let type = layout.event?.type { if type == .watchEvent { actorImageView.isHidden = true } } if layout.prDetailHeight > 0 { //pull request 中,同样有text textView?.origin = CGPoint(x: BFEventConstants.TEXT_X, y: BFEventConstants.TEXT_Y) // textView?.backgroundColor = .red if layout.textHeight > 0 { textView?.isHidden = false textView?.height = layout.textHeight textView?.setLayout(layout: layout) } else { textView?.isHidden = true } commitView?.isHidden = true prDetailView?.isHidden = false prDetailView?.origin = CGPoint(x: textView!.left, y: textView!.bottom) prDetailView?.height = layout.prDetailHeight prDetailView?.setLayout(layout: layout) } else if layout.commitHeight > 0 { prDetailView?.isHidden = true textView?.isHidden = true commitView?.isHidden = false commitView?.origin = CGPoint(x: BFEventConstants.COMMIT_X, y: BFEventConstants.COMMIT_Y) commitView?.height = layout.commitHeight commitView?.setLayout(layout: layout) } else { prDetailView?.isHidden = true commitView?.isHidden = true //text textView?.origin = CGPoint(x: BFEventConstants.TEXT_X, y: BFEventConstants.TEXT_Y) if layout.textHeight > 0 { textView?.isHidden = false textView?.height = layout.textHeight textView?.setLayout(layout: layout) } else { textView?.isHidden = true } } switch layout.style { case .pullRequest: actionContentView.isHidden = false case .pushCommit: actionContentView.isHidden = false case .textPicture: actionContentView.isHidden = false case .text: actionContentView.isHidden = true break } } }
mit
9b6d4063ca43f3eef8fd56d4a451582a
33.166667
187
0.586426
4.629357
false
false
false
false
carabina/Butterfly
Example/Butterfly-Demo/ViewController.swift
1
1754
// // ViewController.swift // Butterfly-Demo // // Created by Wongzigii on 6/30/15. // Copyright (c) 2015 Wongzigii. All rights reserved. // import UIKit import Butterfly class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var objectArray: [String]? var titleArray: [String]? var dateArray: [String]? var root = [] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() root = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("data", ofType: "plist")!)! } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return root.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CustomSportCell", forIndexPath: indexPath) as! CustomCell cell.selectionStyle = .None let imgstr = root[indexPath.row]["bgimage"] as! String cell.backgroundImageView.image = UIImage(named: imgstr) let stadium = root[indexPath.row]["match"] as! String cell.stadiumLabel.text = stadium let date = root[indexPath.row]["date"] as! String cell.dateLabel.text = date let title = root[indexPath.row]["title"] as! String cell.titleLabel.text = title return cell } } public class CustomCell : UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var stadiumLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var backgroundImageView: UIImageView! }
mit
cc4dfbae74b7b05349938f23a8482622
28.233333
121
0.658495
4.831956
false
false
false
false
mcgraw/dojo-parse-tiiny
final/dojo-parse-tiiny/dojo-parse-tiiny/XMCTiinyViewController.swift
1
4962
// // XMCTiinyViewController.swift // dojo-parse-tiiny // // Created by David McGraw on 12/2/14. // Copyright (c) 2014 David McGraw. All rights reserved. // import UIKit class XMCTiinyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var photoCollectionView: UICollectionView! @IBOutlet weak var capturePhoto: UIButton! var cameraCellReference: XMCCameraCollectionViewCell? var images: NSMutableArray = NSMutableArray() override func viewDidLoad() { super.viewDidLoad() self.refreshLayout() } func refreshLayout() { let query = PFQuery(className: "XMCPhoto") query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in // jump back to the background process the results dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { for (index, value) in enumerate(objects) { let photoObj = value as PFObject let image: PFFile = photoObj["image"] as PFFile let imageData = image.getData() // be sure to send the results back to our main thread dispatch_async(dispatch_get_main_queue()) { self.images.addObject(UIImage(data: imageData)!) } } // refresh the collection dispatch_async(dispatch_get_main_queue()) { self.photoCollectionView.reloadData() } } } } // MARK: Collection View func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count + 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if indexPath.row == 0 { cameraCellReference = collectionView.dequeueReusableCellWithReuseIdentifier("cameraCellIdentifier", forIndexPath: indexPath) as? XMCCameraCollectionViewCell return cameraCellReference! } var cell: XMCPhotoCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCellIdentifier", forIndexPath: indexPath) as XMCPhotoCollectionViewCell var position = self.images.count - indexPath.row cell.setPhotoWithImage(self.images.objectAtIndex(position) as? UIImage) return cell } // MARK: Flow Layout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var value = UIScreen.mainScreen().bounds.width value = (value/3.0) - 4 return CGSizeMake(value, value) } // MARK: Actions @IBAction func takePhoto(sender: AnyObject) { cameraCellReference?.captureFrame { (image) -> Void in if let still = image { // assume success so that the user will not encounter more lag than needed self.images.addObject(still) self.photoCollectionView.insertItemsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)]) // send the image to parse var file: PFFile = PFFile(data: UIImageJPEGRepresentation(still, 0.7)) file.saveInBackgroundWithBlock({ (success, fileError) -> Void in if success { var object: PFObject = PFObject(className: "XMCPhoto") object["image"] = file object.saveInBackgroundWithBlock({ (success, objError) -> Void in if success { println("Photo object saved") } else { println("Unable to create a photo object: \(objError)") } }) } else { println("Unable to save file: \(fileError)") } }) /* NOTE: in the event that the code above fails, you want to revert our photo addition and then alert the user. OR, create an upload manager that will retry the upload attempt. */ } } } // MARK: Gesture Actions @IBAction func doubleTappedCollection(sender: AnyObject) { var point = sender.locationInView(self.photoCollectionView) var indexPath = self.photoCollectionView.indexPathForItemAtPoint(point) if indexPath?.row > 0 { println("Double Tapped Photo At Index \(indexPath!.row-1)") } } }
mit
6ba2937321774ce4621bc42b024fbe10
38.696
178
0.577993
5.851415
false
false
false
false
marko1503/Algorithms-and-Data-Structures-Swift
Sort/Insertion Sort/InsertionSort.playground/Contents.swift
1
1310
//: Playground - noun: a place where people can play import UIKit // MARK: - Insertion sort //func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { // var a = array // for x in 1..<a.count { // var y = x // let temp = a[y] // while y > 0 && isOrderedBefore(temp, a[y - 1]) { // a[y] = a[y - 1] // y -= 1 // } // a[y] = temp // } // return a //} //: ![Sort example](Insertion_sort_example.pdf) func insertionSort<Element>(array: [Element]) -> [Element] { // check for tirivial case // we have only 1 element in array guard array.count > 1 else { return array } var output: [Element] = array for primaryIndex in 1..<output.count { let primaryElement = output[primaryIndex] var tempIndex = primaryIndex - 1 while tempIndex > -1 { // primaryElement and element at tempIndex are not ordered. We need to change them // Then, remove primary element // tempIndex + 1 - primaryElement always after tempIndex output.remove(at: tempIndex + 1) // and insert primary element before tempElement output.insert(primaryElement, at: tempIndex) tempIndex -= 1 } } return output }
apache-2.0
c03a6110523493f3742f1869e87c2e95
26.87234
94
0.558779
3.89881
false
false
false
false
ReactiveX/RxSwift
RxSwift/Traits/Infallible/Infallible+Operators.swift
1
34638
// // Infallible+Operators.swift // RxSwift // // Created by Shai Mishali on 27/08/2020. // Copyright © 2020 Krunoslav Zaher. All rights reserved. // // MARK: - Static allocation extension InfallibleType { /** Returns an infallible sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting infallible sequence. - returns: An infallible sequence containing the single specified element. */ public static func just(_ element: Element) -> Infallible<Element> { Infallible(.just(element)) } /** Returns an infallible sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting infallible sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An infallible sequence containing the single specified element. */ public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> { Infallible(.just(element, scheduler: scheduler)) } /** Returns a non-terminating infallible sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An infallible sequence whose observers will never get called. */ public static func never() -> Infallible<Element> { Infallible(.never()) } /** Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An infallible sequence with no elements. */ public static func empty() -> Infallible<Element> { Infallible(.empty()) } /** Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes. - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>) -> Infallible<Element> { Infallible(.deferred { try observableFactory().asObservable() }) } } // MARK: From & Of extension Infallible { /** This method creates a new Infallible instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. - returns: The Infallible sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> { Infallible(Observable.from(elements, scheduler: scheduler)) } } extension Infallible { /** Converts an array to an Infallible sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The Infallible sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> { Infallible(Observable.from(array, scheduler: scheduler)) } /** Converts a sequence to an Infallible sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The Infallible sequence whose elements are pulled from the given enumerable sequence. */ public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> where Sequence.Element == Element { Infallible(Observable.from(sequence, scheduler: scheduler)) } } // MARK: - Filter extension InfallibleType { /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (Element) -> Bool) -> Infallible<Element> { Infallible(asObservable().filter(predicate)) } } // MARK: - Map extension InfallibleType { /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<Result>(_ transform: @escaping (Element) -> Result) -> Infallible<Result> { Infallible(asObservable().map(transform)) } /** Projects each element of an observable sequence into an optional form and filters all optional results. - parameter transform: A transform function to apply to each source element and which returns an element or nil. - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. */ public func compactMap<Result>(_ transform: @escaping (Element) -> Result?) -> Infallible<Result> { Infallible(asObservable().compactMap(transform)) } } // MARK: - Distinct extension InfallibleType where Element: Equatable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ public func distinctUntilChanged() -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged()) } } extension InfallibleType { /** Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key) -> Infallible<Element> { Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 })) } /** Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. */ public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) -> Infallible<Element> { Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer)) } /** Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - parameter keySelector: A function to compute the comparison key for each element. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. */ public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer)) } /** Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path */ public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) -> Infallible<Element> { Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] }) } } // MARK: - Throttle extension InfallibleType { /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers on. - returns: The throttled sequence. */ public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().debounce(dueTime, scheduler: scheduler)) } /** Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. This operator makes sure that no two elements are emitted in less then dueTime. - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) - parameter dueTime: Throttling duration for each element. - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. - parameter scheduler: Scheduler to run the throttle timers on. - returns: The throttled sequence. */ public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler)) } } // MARK: - FlatMap extension InfallibleType { /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMap(selector)) } /** Projects each element of an observable sequence into a new sequence of observable sequences and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. It is a combination of `map` + `switchLatest` operator - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMapLatest(selector)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. If element is received while there is some projected observable sequence being merged it will simply be ignored. - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. */ public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().flatMapFirst(selector)) } } // MARK: - Concat extension InfallibleType { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element { Infallible(Observable.concat([self.asObservable(), second.asObservable()])) } /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element> where Sequence.Element == Infallible<Element> { Infallible(Observable.concat(sequence.map { $0.asObservable() })) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> { Infallible(Observable.concat(collection.map { $0.asObservable() })) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> { Infallible(Observable.concat(sources.map { $0.asObservable() })) } /** Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source) -> Infallible<Source.Element> { Infallible(asObservable().concatMap(selector)) } } // MARK: - Merge extension InfallibleType { /** Merges elements from all observable sequences from collection into a single observable sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> { Infallible(Observable.concat(sources.map { $0.asObservable() })) } /** Merges elements from all infallible sequences from array into a single infallible sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Array of infallible sequences to merge. - returns: The infallible sequence that merges the elements of the infallible sequences. */ public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> { Infallible(Observable.merge(sources.map { $0.asObservable() })) } /** Merges elements from all infallible sequences into a single infallible sequence. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of infallible sequences to merge. - returns: The infallible sequence that merges the elements of the infallible sequences. */ public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> { Infallible(Observable.merge(sources.map { $0.asObservable() })) } } // MARK: - Do extension Infallible { /** Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> { Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose)) } } // MARK: - Scan extension InfallibleType { /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void) -> Infallible<Seed> { Infallible(asObservable().scan(into: seed, accumulator: accumulator)) } /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed) -> Infallible<Seed> { Infallible(asObservable().scan(seed, accumulator: accumulator)) } } // MARK: - Start with extension InfallibleType { /** Prepends a value to an observable sequence. - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) - parameter element: Element to prepend to the specified sequence. - returns: The source sequence prepended with the specified values. */ public func startWith(_ element: Element) -> Infallible<Element> { Infallible(asObservable().startWith(element)) } } // MARK: - Take and Skip { extension InfallibleType { /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func take<Source: InfallibleType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().take(until: other.asObservable())) } /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func take<Source: ObservableType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().take(until: other)) } /** Returns elements from an observable sequence until the specified condition is true. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter predicate: A function to test each element for a condition. - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. */ public func take(until predicate: @escaping (Element) throws -> Bool, behavior: TakeBehavior = .exclusive) -> Infallible<Element> { Infallible(asObservable().take(until: predicate, behavior: behavior)) } /** Returns elements from an observable sequence as long as a specified condition is true. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ public func take(while predicate: @escaping (Element) throws -> Bool, behavior: TakeBehavior = .exclusive) -> Infallible<Element> { Infallible(asObservable().take(while: predicate, behavior: behavior)) } /** Returns a specified number of contiguous elements from the start of an observable sequence. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter count: The number of elements to return. - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. */ public func take(_ count: Int) -> Infallible<Element> { Infallible(asObservable().take(count)) } /** Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence. */ public func take(for duration: RxTimeInterval, scheduler: SchedulerType) -> Infallible<Element> { Infallible(asObservable().take(for: duration, scheduler: scheduler)) } /** Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements. - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) - parameter predicate: A function to test each element for a condition. - returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> { Infallible(asObservable().skip(while: predicate)) } /** Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element. - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) - parameter other: Infallible sequence that starts propagation of elements of the source sequence. - returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. */ public func skip<Source: ObservableType>(until other: Source) -> Infallible<Element> { Infallible(asObservable().skip(until: other)) } } // MARK: - Share extension InfallibleType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Infallible<Element> { Infallible(asObservable().share(replay: replay, scope: scope)) } } // MARK: - withUnretained extension InfallibleType { /** Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. In the case the provided object cannot be retained successfully, the sequence will complete. - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. - parameter obj: The object to provide an unretained reference on. - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. */ public func withUnretained<Object: AnyObject, Out>( _ obj: Object, resultSelector: @escaping (Object, Element) -> Out ) -> Infallible<Out> { Infallible(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) } /** Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. In the case the provided object cannot be retained successfully, the sequence will complete. - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. - parameter obj: The object to provide an unretained reference on. - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. */ public func withUnretained<Object: AnyObject>(_ obj: Object) -> Infallible<(Object, Element)> { withUnretained(obj) { ($0, $1) } } } extension InfallibleType { // MARK: - withLatestFrom /** Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - note: Elements emitted by self before the second source has emitted any values will be omitted. - parameter second: Second observable source. - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<Source: InfallibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Infallible<ResultType> { Infallible(self.asObservable().withLatestFrom(second.asObservable(), resultSelector: resultSelector)) } /** Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - note: Elements emitted by self before the second source has emitted any values will be omitted. - parameter second: Second observable source. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<Source: InfallibleType>(_ second: Source) -> Infallible<Source.Element> { withLatestFrom(second) { $1 } } }
mit
c272b48e54b24dccc874dddca023fa0f
47.715893
320
0.725352
5.118516
false
false
false
false
louisdh/panelkit
PanelKit/Model/Constants.swift
1
964
// // Constants.swift // PanelKit // // Created by Louis D'hauwe on 07/03/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation import CoreGraphics import UIKit // Exposé let exposeOuterPadding: CGFloat = 44.0 let exposeExitDuration: TimeInterval = 0.3 let exposeEnterDuration: TimeInterval = 0.3 let exposePanelHorizontalSpacing: CGFloat = 20.0 let exposePanelVerticalSpacing: CGFloat = 20.0 // Pinned let pinnedPanelPreviewAlpha: CGFloat = 0.4 let pinnedPanelPreviewGrowDuration: TimeInterval = 0.3 let pinnedPanelPreviewFadeDuration: TimeInterval = 0.3 let panelGrowDuration: TimeInterval = 0.3 // Floating let panelPopDuration: TimeInterval = 0.2 let panelPopYOffset: CGFloat = 12.0 // PanelViewController let cornerRadius: CGFloat = 16.0 // Panel shadow let shadowRadius: CGFloat = 8.0 let shadowOpacity: Float = 0.3 let shadowOffset: CGSize = CGSize(width: 0, height: 10.0) let shadowColor = UIColor.black.cgColor
mit
536b299c6ea492242eab0424a1a079ed
21.904762
57
0.768191
3.602996
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/NewFeature(新特性)/Controller/KYNewFeatureController.swift
1
1779
// // KYNewFeatureController.swift // KYHandMade // // Created by Kerain on 2017/6/8. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import UIKit let featureCellId = "featureCell" class KYNewFeatureController: UICollectionViewController{ override func viewDidLoad() { super.viewDidLoad() collectionView?.register(UINib.init(nibName: "KYNewFeatureCell", bundle: nil), forCellWithReuseIdentifier: featureCellId) collectionView?.bounces = false collectionView?.showsHorizontalScrollIndicator = false collectionView?.isPagingEnabled = true } } extension KYNewFeatureController{ // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return 5 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let kyCell = (collectionView.dequeueReusableCell(withReuseIdentifier: featureCellId, for: indexPath)) as! KYNewFeatureCell kyCell.featureImageView.image = UIImage(named : "newfeature_0\(indexPath.item+1)_736") return kyCell } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){ if indexPath.item == 4 { UIApplication.shared.keyWindow?.rootViewController = KYAdViewController.loadFromNib() let anim = CATransition() anim.type = "rippleEffect" anim.duration = 1 UIApplication.shared.keyWindow?.layer.add(anim, forKey: nil) } } }
apache-2.0
cdb0ef3a539903326927a8113f7d8667
31.407407
130
0.686857
5.255255
false
false
false
false
jfosterdavis/FlashcardHero
FlashcardHero/MissionFeedbackViewController.swift
1
7986
// // MissionFeedbackViewController.swift // FlashcardHero // // Created by Jacob Foster Davis on 12/9/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import Foundation import CoreData import UIKit protocol MissionFeedbackDelegate { func setupWith(wasSuccess: Bool, numStars: Int, timeElapsedString time: String, totalPoints points: Int, accuracy: Double, customStats stats: [String:Any]?, senderVC sender: UIViewController, destinationVC:UIViewController?, vCCompletion: (() -> Void)?) } class MissionFeedbackViewController: CoreDataQuizletCollectionViewController, MissionFeedbackDelegate { @IBOutlet weak var summaryLabel: UILabel! @IBOutlet weak var star1: UIImageView! @IBOutlet weak var star2: UIImageView! @IBOutlet weak var star3: UIImageView! @IBOutlet weak var timeElapsedLabel: UILabel! @IBOutlet weak var accuracyLabel: UILabel! @IBOutlet weak var customLabel1: UILabel! @IBOutlet weak var customLabel2: UILabel! @IBOutlet weak var customStatLabel1: UILabel! @IBOutlet weak var customStatLabel2: UILabel! @IBOutlet weak var totalPointsLabel: UILabel! @IBOutlet weak var okButton: UIButton! var destinationVC: UIViewController! var senderVC: UIViewController! var destinationVCCompletion: (() -> Void)? var summaryLabelText = "" var numStars = 0 var timeElapsedLabelText = "" var totalPointsLabelText = "" var accuracyLabelText = "" var customLabel1Text = "" var customLabel2Text = "" var customStatLabel1Text = "" var customStatLabel2Text = "" /******************************************************/ /*******************///MARK: Life Cycle /******************************************************/ override func viewDidLoad() { super.viewDidLoad() summaryLabel.text = summaryLabelText switch numStars { case 0: //highlight 0 stars starHighlighter(0) case 1: //highlight 1 star starHighlighter(1) case 2: //highlight 2 stars starHighlighter(2) case 3: //highlight 3 stars starHighlighter(3) default: //highlight 0 stars starHighlighter(0) } timeElapsedLabel.text = timeElapsedLabelText totalPointsLabel.text = totalPointsLabelText accuracyLabel.text = accuracyLabelText customLabel1.text = customLabel1Text customLabel2.text = customLabel2Text customStatLabel1.text = customStatLabel1Text customStatLabel2.text = customStatLabel2Text //show or hide the custom stats if customLabel1.text != nil && customStatLabel1.text != nil { customLabel1.isHidden = false customStatLabel1.isHidden = false } else { customLabel1.isHidden = true customStatLabel1.isHidden = true } if customLabel2.text != nil && customStatLabel2.text != nil { customLabel2.isHidden = false customStatLabel2.isHidden = false } else { customLabel2.isHidden = true customStatLabel2.isHidden = true } } /******************************************************/ /*******************///MARK: MissionFeedbackDelegate /******************************************************/ /** Delegate method used by anything that calls this view, should do so with this method in closure. */ func setupWith(wasSuccess: Bool, numStars: Int, timeElapsedString time: String, totalPoints points: Int, accuracy: Double, customStats stats: [String:Any]? = nil, senderVC sender: UIViewController, destinationVC:UIViewController? = nil, vCCompletion: (() -> Void)? = nil){ if wasSuccess { summaryLabelText = "Success!" } else { summaryLabelText = "Failed!" } self.numStars = numStars timeElapsedLabelText = time totalPointsLabelText = String(describing: points) if accuracy.isNaN || accuracy.isInfinite { print("Incoming accuracy was NaN or infinate. \(accuracy)") accuracyLabelText = "--" } else { let aValue = Int(round(accuracy * 100)) accuracyLabelText = "\(aValue)%" } senderVC = sender //if didn't supply a destination, then assume destination is back to sender if let destinationVC = destinationVC { self.destinationVC = destinationVC } else { self.destinationVC = sender } self.destinationVCCompletion = vCCompletion //handle the first two custom stats if let stats = stats { customLabel1Text = "" for (statLabel, statValue) in stats { if customLabel1Text == "" { customLabel1Text = statLabel customStatLabel1Text = String(describing: statValue) } else { //if the first label is nil, do the second label customLabel2Text = statLabel customStatLabel2Text = String(describing: statValue) } } } } func starHighlighter(_ numStars: Int) { guard numStars <= 3 && numStars >= 0 else { print("Invalid number of stars to highlight \(numStars)") return } switch numStars { case 0: //don't highlight anything, keep all gray starHighlight(star: 1, doHighlight: false) starHighlight(star: 2, doHighlight: false) starHighlight(star: 3, doHighlight: false) case 1: starHighlight(star: 1, doHighlight: true) starHighlight(star: 2, doHighlight: false) starHighlight(star: 3, doHighlight: false) case 2: starHighlight(star: 1, doHighlight: true) starHighlight(star: 2, doHighlight: true) starHighlight(star: 3, doHighlight: false) case 3: starHighlight(star: 1, doHighlight: true) starHighlight(star: 2, doHighlight: true) starHighlight(star: 3, doHighlight: true) default: return } } func starHighlight(star:Int, doHighlight: Bool) { guard star <= 3 && star >= 1 else { print("Requested to highlight invalid star number \(star)") return } var starToHighlight: UIImageView switch star { case 1: starToHighlight = star1 case 2: starToHighlight = star2 case 3: starToHighlight = star3 default: return } if doHighlight { starToHighlight.image = #imageLiteral(resourceName: "Star") } else { starToHighlight.image = #imageLiteral(resourceName: "StarGray") } } /******************************************************/ /*******************///MARK: Actions /******************************************************/ @IBAction func okButtonPressed(_ sender: Any) { if senderVC == destinationVC { //TODO: Improve visuals of this transition self.senderVC.dismiss(animated: false, completion: self.destinationVCCompletion) self.dismiss(animated: true, completion: nil) } else { //needs to be send elsewhere //TODO: Improve this for user self.dismiss(animated: false, completion: { self.present(self.destinationVC, animated: false, completion: self.destinationVCCompletion)}) } } }
apache-2.0
9bd75558c33de8aea9681aefdb8bdc43
32.13278
277
0.556544
5.274108
false
false
false
false
TCA-Team/iOS
TUM Campus App/LecturesTableViewController.swift
1
3545
// // LecturesTableViewController.swift // TUM Campus App // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // 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, version 3. // // 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 Sweeft import UIKit private func mapped(lectures: [Lecture]) -> [(String, [Lecture])] { let ordered = lectures.map { $0.semester } let semesters = Set(ordered).sorted(ascending: { ordered.index(of: $0) ?? ordered.count }) return semesters.map { semester in return (semester, lectures.filter { $0.semester == semester }) } } class LecturesTableViewController: RefreshableTableViewController<Lecture>, DetailViewDelegate, DetailView { override var values: [Lecture] { get { return lectures.flatMap { $1 } } set { lectures = mapped(lectures: newValue) } } var lectures = [(String,[Lecture])]() { didSet { tableView.reloadData() } } weak var delegate: DetailViewDelegate? var currentLecture: DataElement? func dataManager() -> TumDataManager? { return delegate?.dataManager() } override func fetch(skipCache: Bool) -> Promise<[Lecture], APIError>? { return delegate?.dataManager()?.lecturesManager.fetch(skipCache: skipCache) } override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let mvc = segue.destination as? LectureDetailsTableViewController { mvc.lecture = currentLecture mvc.delegate = self } } override func numberOfSections(in tableView: UITableView) -> Int { return lectures.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lectures[section].1.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return lectures[section].0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = lectures[indexPath.section].1[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: item.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell() cell.setElement(item) return cell } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.contentView.backgroundColor = Constants.tumBlue header.textLabel?.textColor = UIColor.white } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { currentLecture = lectures[indexPath.section].1[indexPath.row] return indexPath } }
gpl-3.0
ca7f3a9bce38c74c39559dab89c22536
33.754902
135
0.665444
4.664474
false
false
false
false
lkzhao/Hero
Sources/Preprocessors/SourcePreprocessor.swift
1
3416
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) import UIKit class SourcePreprocessor: BasePreprocessor { override func process(fromViews: [UIView], toViews: [UIView]) { for fv in fromViews { guard let id = context[fv]?.source, let tv = context.destinationView(for: id) else { continue } prepareFor(view: fv, targetView: tv) } for tv in toViews { guard let id = context[tv]?.source, let fv = context.sourceView(for: id) else { continue } prepareFor(view: tv, targetView: fv) } } func prepareFor(view: UIView, targetView: UIView) { let targetPos = context.container.convert(targetView.layer.position, from: targetView.superview!) let targetTransform = context.container.layer.flatTransformTo(layer: targetView.layer) var state = context[view]! // use global coordinate space since over target position is converted from the global container state.coordinateSpace = .global state.position = targetPos state.transform = targetTransform // remove incompatible options state.size = nil if view.bounds.size != targetView.bounds.size { state.size = targetView.bounds.size } if state.cornerRadius == nil, view.layer.cornerRadius != targetView.layer.cornerRadius { state.cornerRadius = targetView.layer.cornerRadius } if view.layer.shadowColor != targetView.layer.shadowColor { state.shadowColor = targetView.layer.shadowColor } if view.layer.shadowOpacity != targetView.layer.shadowOpacity { state.shadowOpacity = targetView.layer.shadowOpacity } if view.layer.shadowOffset != targetView.layer.shadowOffset { state.shadowOffset = targetView.layer.shadowOffset } if view.layer.shadowRadius != targetView.layer.shadowRadius { state.shadowRadius = targetView.layer.shadowRadius } if view.layer.shadowPath != targetView.layer.shadowPath { state.shadowPath = targetView.layer.shadowPath } if view.layer.contentsRect != targetView.layer.contentsRect { state.contentsRect = targetView.layer.contentsRect } if view.layer.contentsScale != targetView.layer.contentsScale { state.contentsScale = targetView.layer.contentsScale } context[view] = state } } #endif
mit
6adcfbf052dc069a3461aa30b4898c77
37.818182
101
0.722775
4.530504
false
false
false
false
gb-6k-house/YsSwift
Sources/Rabbit/Manager.swift
1
7109
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: 管理类 ** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation #if YSSWIFT_DEBUG import YsSwift #endif import Result //网络图片加载管理类 //完成如下流程: 数据从网络中下载 ->数据缓存本地(硬盘+内存) -> 数据解析成图片 -> 返回上层应用 public final class Manager { public var loader: Loading public let cache: Cache<ImageCache.CachedImage>? public let defauleLoader : Loader = { return Loader.shared as! Loader }() /// A set of trusted hosts when receiving server trust challenges. //single instance public static let shared = Manager(loader: Loader.shared, cache: ImageCache.shared) // public init(loader: Loading, cache: Cache<ImageCache.CachedImage>? = nil) { self.loader = loader self.cache = cache } // MARK: Loading Images into Targets /// Loads an image into the given target. Cancels previous outstanding request /// associated with the target. /// /// If the image is stored in the memory cache, the image is displayed /// immediately. The image is loaded using the `loader` object otherwise. /// /// `Manager` keeps a weak reference to the target. If the target deallocates /// the associated request automatically gets cancelled. public func loadImage(with request: Request, into target: Target) { loadImage(with: request, into: target) { [weak target] in target?.handle(response: $0, isFromMemoryCache: $1) } } public typealias Handler = (Result<Image, YsSwift.RequestError>, _ isFromMemoryCache: Bool) -> Void /// 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. The handler gets called immediately /// if the image was stored in the memory cache. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Handler) { assert(Thread.isMainThread) // Cancel outstanding request if any cancelRequest(for: target) // Quick synchronous memory cache lookup if let image = cachedImage(for: request) { handler(.success(image), true) return } // Create context and associate it with a target let cts = CancellationTokenSource(lock: CancellationTokenSource.lock) let context = Context(cts) Manager.setContext(context, for: target) // Start the request loadImage(with: request, token: cts.token) { [weak context, weak target] in guard let context = context, let target = target else { return } guard Manager.getContext(for: target) === context else { return } handler($0, false) context.cts = nil // Avoid redundant cancellations on deinit } } // MARK: Loading Images w/o Targets /// Loads an image with a given request by using manager's cache and loader. /// /// - parameter completion: Gets called asynchronously on the main thread. public func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image, YsSwift.RequestError>) -> Void) { if token?.isCancelling == true { return } // Fast preflight check self._loadImage(with: request, token: token) { result in DispatchQueue.main.async { completion(result) } } } private func _loadImage(with request: Request, token: CancellationToken? = nil, completion: @escaping (Result<Image, YsSwift.RequestError>) -> Void) { // Check if image is in memory cache if let image = cachedImage(for: request) { completion(.success(image)) } else { // Use underlying loader to load an image and then store it in cache loader.loadImage(with: request, token: token) { [weak self] in if let image = $0.value { self?.store(image: image, for: request) } completion($0) } } } /// Cancels an outstanding request associated with the target. public func cancelRequest(for target: AnyObject) { assert(Thread.isMainThread) if let context = Manager.getContext(for: target) { context.cts?.cancel() Manager.setContext(nil, for: target) } } // MARK: Memory Cache Helpers private func cachedImage(for request: Request) -> Image? { return cache?[request]?.value as? Image } private func store(image: Image, for request: Request) { cache?[request] = ImageCache.CachedImage(value: image) } // MARK: Managing Context private static var contextAK = "com.github.YKit.Manager.Context.AssociatedKey" // Associated objects is a simplest way to bind Context and Target lifetimes // The implementation might change in the future. private static func getContext(for target: AnyObject) -> Context? { return objc_getAssociatedObject(target, &contextAK) as? Context } private static func setContext(_ context: Context?, for target: AnyObject) { objc_setAssociatedObject(target, &contextAK, context, .OBJC_ASSOCIATION_RETAIN) } private final class Context { var cts: CancellationTokenSource? init(_ cts: CancellationTokenSource) { self.cts = cts } // Automatically cancel the request when target deallocates. deinit { cts?.cancel() } } } public extension Manager { /// Loads an image into the given target. See the corresponding /// `loadImage(with:into)` method that takes `Request` for more info. public func loadImage(with url: URL, into target: Target) { loadImage(with: Request(url: url), 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. The handler gets called immediately /// if the image was stored in the memory cache. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Handler) { loadImage(with: Request(url: url), into: target, handler: handler) } }
mit
5f6f2808be6b9facbc5dc7af630b46a7
37.866667
154
0.621784
4.679599
false
false
false
false
hyp/SwiftDocDigger
SwiftDocDigger/DocXMLParser.swift
1
10484
// // DocXMLParser.swift // SwiftDocDigger // import Foundation public enum SwiftDocXMLError : Error { case unknownParseError /// An xml parse error. case parseError(Error) /// A required attribute is missing, e.g. <Link> without href attribute. case missingRequiredAttribute(element: String, attribute: String) /// A required child element is missing e.g. <Parameter> without the <Name>. case missingRequiredChildElement(element: String, childElement: String) /// More than one element is specified where just one is needed. case moreThanOneElement(element: String) /// An element is outside of its supposed parent. case elementNotInsideExpectedParentElement(element: String, expectedParentElement: String) } /// Parses swift's XML documentation. public func parseSwiftDocAsXML(_ source: String) throws -> Documentation? { guard !source.isEmpty else { return nil } guard let data = source.data(using: String.Encoding.utf8) else { assertionFailure() return nil } let delegate = SwiftXMLDocParser() do { let parser = XMLParser(data: data) parser.delegate = delegate guard parser.parse() else { guard let error = parser.parserError else { throw SwiftDocXMLError.unknownParseError } throw SwiftDocXMLError.parseError(error) } } if let error = delegate.parseError { throw error } assert(delegate.stack.isEmpty) return Documentation(declaration: delegate.declaration, abstract: delegate.abstract, discussion: delegate.discussion, parameters: delegate.parameters, resultDiscussion: delegate.resultDiscussion) } private class SwiftXMLDocParser: NSObject, XMLParserDelegate { enum StateKind { case root case declaration case abstract case discussion case parameters case parameter(name: NSMutableString, discussion: [DocumentationNode]?) case parameterName(NSMutableString) case parameterDiscussion case resultDiscussion case node(DocumentationNode.Element) // Some other node we don't really care about. case other } struct State { var kind: StateKind let elementName: String var nodes: [DocumentationNode] } var stack: [State] = [] var parameterDepth = 0 var hasFoundRoot = false var parseError: SwiftDocXMLError? // The results var declaration: [DocumentationNode]? var abstract: [DocumentationNode]? var discussion: [DocumentationNode]? var resultDiscussion: [DocumentationNode]? var parameters: [Documentation.Parameter]? func add(_ element: DocumentationNode.Element, children: [DocumentationNode] = []) { guard !stack.isEmpty else { assertionFailure() return } stack[stack.count - 1].nodes.append(DocumentationNode(element: element, children: children)) } func replaceTop(_ state: StateKind) { assert(!stack.isEmpty) stack[stack.count - 1].kind = state } func handleError(_ error: SwiftDocXMLError) { guard parseError == nil else { return } parseError = error } @objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { func push(_ state: StateKind) { stack.append(State(kind: state, elementName: elementName, nodes: [])) } if stack.isEmpty { // Root node. assert(!hasFoundRoot) assert(elementName == "Class" || elementName == "Function" || elementName == "Other") push(.root) hasFoundRoot = true return } if case .parameter? = stack.last?.kind { // Parameter information. switch elementName { case "Name": assert(parameterDepth > 0) push(.parameterName("")) case "Discussion": assert(parameterDepth > 0) push(.parameterDiscussion) default: // Don't really care about the other nodes here (like Direction). push(.other) } return } switch elementName { case "Declaration": push(.declaration) case "Abstract": push(.abstract) case "Discussion": push(.discussion) case "Parameters": push(.parameters) case "Parameter": assert(parameterDepth == 0) parameterDepth += 1 let last = stack.last push(.parameter(name: "", discussion: nil)) guard case .parameters? = last?.kind else { handleError(.elementNotInsideExpectedParentElement(element: elementName, expectedParentElement: "Parameters")) return } case "ResultDiscussion": push(.resultDiscussion) case "Para": push(.node(.paragraph)) case "rawHTML": push(.node(.rawHTML(""))) case "codeVoice": push(.node(.codeVoice)) case "Link": guard let href = attributeDict["href"] else { handleError(.missingRequiredAttribute(element: elementName, attribute: "href")) push(.other) return } push(.node(.link(href: href))) case "emphasis": push(.node(.emphasis)) case "strong": push(.node(.strong)) case "bold": push(.node(.bold)) case "List-Bullet": push(.node(.bulletedList)) case "List-Number": push(.node(.numberedList)) case "Item": push(.node(.listItem)) case "CodeListing": push(.node(.codeBlock(language: attributeDict["language"]))) case "zCodeLineNumbered": push(.node(.numberedCodeLine)) case "Complexity", "Note", "Requires", "Warning", "Postcondition", "Precondition": push(.node(.label(elementName))) case "See": push(.node(.label("See also"))) case "Name", "USR": guard case .root? = stack.last?.kind else { assertionFailure("This node is expected to be immediately inside the root node.") return } // Don't really need these ones. push(.other) default: push(.node(.other(elementName))) } } @objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { guard let top = stack.popLast() else { assertionFailure("Invalid XML") return } assert(top.elementName == elementName) switch top.kind { case .node(let element): add(element, children: top.nodes) case .abstract: guard abstract == nil else { handleError(.moreThanOneElement(element: elementName)) return } abstract = top.nodes case .declaration: guard declaration == nil else { handleError(.moreThanOneElement(element: elementName)) return } declaration = top.nodes case .discussion: // Docs can have multiple discussions. discussion = discussion.flatMap { $0 + top.nodes } ?? top.nodes case .parameter(let nameString, let discussion): assert(parameterDepth > 0) parameterDepth -= 1 let name = nameString as String guard !name.isEmpty else { handleError(.missingRequiredChildElement(element: "Parameter", childElement: "Name")) return } let p = Documentation.Parameter(name: name, discussion: discussion) parameters = parameters.flatMap { $0 + [ p ] } ?? [ p ] case .parameterName(let nameString): assert(parameterDepth > 0) let name = nameString as String guard !name.isEmpty else { handleError(.missingRequiredChildElement(element: "Parameter", childElement: "Name")) return } assert(top.nodes.isEmpty, "Other nodes present in parameter name") switch stack.last?.kind { case .parameter(let currentName, _)?: guard (currentName as String).isEmpty else { handleError(.moreThanOneElement(element: "Parameter.Name")) return } currentName.setString(name) default: assertionFailure() } case .parameterDiscussion: assert(parameterDepth > 0) switch stack.last?.kind { case .parameter(let name, let discussion)?: // Parameters can have multiple discussions. replaceTop(.parameter(name: name, discussion: discussion.flatMap { $0 + top.nodes } ?? top.nodes)) default: assertionFailure() } case .resultDiscussion: guard resultDiscussion == nil else { handleError(.moreThanOneElement(element: elementName)) return } resultDiscussion = top.nodes default: break } } @objc func parser(_ parser: XMLParser, foundCharacters string: String) { guard stack.count > 1 else { return } if case .parameterName(let name)? = stack.last?.kind { name.append(string) return } add(.text(string)) } @objc func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { guard let str = String(data: CDATABlock, encoding: String.Encoding.utf8) else { assertionFailure() return } switch stack.last?.kind { case .node(.rawHTML(let html))?: replaceTop(.node(.rawHTML(html + str))) break case .node(.numberedCodeLine)?: add(.text(str)) break default: assertionFailure("Unsupported data block") } } }
mit
0ca4218bcc8852f19f778922998adb57
34.181208
199
0.570584
5.146784
false
false
false
false
rizainuddin/ios-nd-alien-adventure-swift-3
Alien Adventure/InscriptionEternalStar.swift
1
814
// // InscriptionEternalStar.swift // Alien Adventure // // Created by Jarrod Parkes on 9/30/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func inscriptionEternalStar(inventory: [UDItem]) -> UDItem? { var theEternalStar: UDItem? let inscriptionText = "The Eternal Star" for item in inventory { if item.inscription?.contains(inscriptionText.uppercased()) == true { theEternalStar = item } } // print(theEternalStar) return theEternalStar } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 3"
mit
dd15ca43ad77e1b15257383bbbf21b7d
31.52
235
0.658057
4.106061
false
false
false
false
kristoferdoman/stormy-treehouse-weather-app
Stormy/BackgroundView.swift
2
1400
// // BackgroundView.swift // Stormy // // Created by Kristofer Doman on 2015-07-02. // Copyright (c) 2015 Kristofer Doman. All rights reserved. // import UIKit class BackgroundView: UIView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code // Background View //// Color Declarations let lightPurple: UIColor = UIColor(red: 0.377, green: 0.075, blue: 0.778, alpha: 1.000) let darkPurple: UIColor = UIColor(red: 0.060, green: 0.036, blue: 0.202, alpha: 1.000) let context = UIGraphicsGetCurrentContext() //// Gradient Declarations let purpleGradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [lightPurple.CGColor, darkPurple.CGColor], [0, 1]) //// Background Drawing let backgroundPath = UIBezierPath(rect: CGRectMake(0, 0, self.frame.width, self.frame.height)) CGContextSaveGState(context) backgroundPath.addClip() CGContextDrawLinearGradient(context, purpleGradient, CGPointMake(160, 0), CGPointMake(160, 568), UInt32(kCGGradientDrawsBeforeStartLocation) | UInt32(kCGGradientDrawsAfterEndLocation)) CGContextRestoreGState(context) } }
mit
34504ca65fefb6831c8499a2cedad5fc
35.842105
137
0.664286
4.590164
false
false
false
false
knutigro/AppReviews
AppReviews/NSImageView+Networking.swift
1
5938
// // NSImageView+Networking.swift // App Reviews // // Created by Knut Inge Grosland on 2015-04-13. // Copyright (c) 2015 Cocmoc. All rights reserved. // import AppKit protocol AFImageCacheProtocol:class{ func cachedImageForRequest(request:NSURLRequest) -> NSImage? func cacheImage(image:NSImage, forRequest request:NSURLRequest); } extension NSImageView { private struct AssociatedKeys { static var SharedImageCache = "SharedImageCache" static var RequestImageOperation = "RequestImageOperation" static var URLRequestImage = "UrlRequestImage" } class func setSharedImageCache(cache:AFImageCacheProtocol?) { objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } class func sharedImageCache() -> AFImageCacheProtocol { struct Static { static var token: dispatch_once_t = 0 static var defaultImageCache:AFImageCache? } dispatch_once(&Static.token, { () -> Void in Static.defaultImageCache = AFImageCache() }) return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCache ?? Static.defaultImageCache! } class func af_sharedImageRequestOperationQueue() -> NSOperationQueue { struct Static { static var token:dispatch_once_t = 0 static var queue:NSOperationQueue? } dispatch_once(&Static.token, { () -> Void in Static.queue = NSOperationQueue() Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount }) return Static.queue! } private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) { get { let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest return (operation, request) } set { objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func setImageWithUrl(url:NSURL, placeHolderImage:NSImage? = nil) { let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.addValue("image/*", forHTTPHeaderField: "Accept") setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil) } func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:NSImage? = nil, success:((request:NSURLRequest?, response:NSURLResponse?, image:NSImage) -> Void)?, failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?) { cancelImageRequestOperation() if let cachedImage = NSImageView.sharedImageCache().cachedImageForRequest(request) { if success != nil { success!(request: nil, response:nil, image: cachedImage) } else { image = cachedImage } return } if placeHolderImage != nil { image = placeHolderImage } af_requestImageOperation = (NSBlockOperation(block: { () -> Void in var response:NSURLResponse? var error:NSError? let data: NSData? do { data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) } catch let error1 as NSError { error = error1 data = nil } catch { fatalError() } dispatch_async(dispatch_get_main_queue(), { () -> Void in if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) { let image:NSImage? = (data != nil ? NSImage(data: data!): nil) if image != nil { if success != nil { success!(request: request, response: response, image: image!) } else { self.image = image! } } else { if failure != nil { failure!(request: request, response:response, error: error!) } } self.af_requestImageOperation = (nil, nil) } }) }), request) NSImageView.af_sharedImageRequestOperationQueue().addOperation(af_requestImageOperation.operation!) } private func cancelImageRequestOperation() { af_requestImageOperation.operation?.cancel() af_requestImageOperation = (nil, nil) } } func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String { return request.URL!.absoluteString } class AFImageCache: NSCache, AFImageCacheProtocol { func cachedImageForRequest(request: NSURLRequest) -> NSImage? { switch request.cachePolicy { case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData: return nil default: break } return objectForKey(AFImageCacheKeyFromURLRequest(request)) as? NSImage } func cacheImage(image: NSImage, forRequest request: NSURLRequest) { setObject(image, forKey: AFImageCacheKeyFromURLRequest(request)) } }
gpl-3.0
c8a1976e37f63cf6850e911f00e4a6ad
37.816993
159
0.611991
5.539179
false
false
false
false
linkedin/ConsistencyManager-iOS
SampleApp/ConsistencyManagerDemo/ViewControllers/DetailViewController.swift
2
2112
// © 2016 LinkedIn Corp. 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. import UIKit import ConsistencyManager class DetailViewController: UIViewController, ConsistencyManagerListener { var update: UpdateModel @IBOutlet weak var likeButton: UIButton! init(update: UpdateModel) { self.update = update super.init(nibName: "DetailViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge() title = update.id ConsistencyManager.sharedInstance.addListener(self) loadData() } func loadData() { likeButton.isHidden = false if update.liked { likeButton.setTitle("Unlike", for: UIControl.State()) } else { likeButton.setTitle("Like", for: UIControl.State()) } } @IBAction func deleteTapped(_ sender: UIButton) { ConsistencyManager.sharedInstance.deleteModel(update) _ = navigationController?.popViewController(animated: true) } @IBAction func likeButtonTapped(_ sender: UIButton) { UpdateHelper.likeUpdate(update, like: !update.liked) } // MARK - Consistency Manager Delegate func currentModel() -> ConsistencyManagerModel? { return update } func modelUpdated(_ model: ConsistencyManagerModel?, updates: ModelUpdates, context: Any?) { if let model = model as? UpdateModel { if model != update { update = model loadData() } } } }
apache-2.0
7607fd2b9cacd20c85650dc63f848fa8
28.732394
96
0.653719
4.852874
false
false
false
false
tanhuiya/ThPullRefresh
ThPullRefreshDemo/ExampleTableView.swift
1
2816
// // ExampleTableView.swift // PullRefresh // // Created by tanhui on 15/12/28. // Copyright © 2015年 tanhui. All rights reserved. // import Foundation import UIKit class ExampleTableView: UITableViewController { lazy var dataArr : NSMutableArray = { return NSMutableArray() }() var index = 0 //MARK:Methods func beginRefresh(){ self.tableView.headBeginRefresh() } override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "tableViewCell") self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 44 self.tableView.tableFooterView = UIView() self.tableView.addHeadRefresh(self) { () -> () in self.loadNewData() } self.tableView.addHeadRefresh(self, action: "loadNewData") self.tableView.head?.hideTimeLabel=true // self.tableView.addFootRefresh(self, action: "loadMoreData") self.tableView.addFootRefresh(self) { () -> () in self.loadMoreData() } } func loadNewData(){ //延时模拟刷新 self.index = 0 DeLayTime(2.0, closure: { () -> () in self.dataArr.removeAllObjects() for (var i = 0 ;i<5;i++){ let str = "最新5个cell,第\(self.index++)个" self.dataArr.addObject(str) } self.tableView.reloadData() self.tableView .tableHeadStopRefreshing() }) } func loadMoreData(){ //延时模拟刷新 DeLayTime(2.0, closure: { () -> () in for (var i = 0 ;i<10;i++){ let str = "上拉刷新10个cell,第\(self.index++)个" self.dataArr.addObject(str) } self.tableView.reloadData() self.tableView .tableFootStopRefreshing() }) } } extension ExampleTableView{ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row%2 == 0{ self.performSegueWithIdentifier("segue1", sender: nil) }else{ self.navigationController?.pushViewController(ExampleController_two(), animated: true) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCellWithIdentifier("tableViewCell", forIndexPath: indexPath) cell.textLabel?.text=self.dataArr[indexPath.row] as? String return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArr.count } }
mit
3bf136f950a227aba73d338eae07c50a
30.747126
118
0.612459
4.687606
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/CoreData/Relationship.swift
1
2982
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import Kanna extension CoreData { public struct Relationship { public typealias InverseRelationship = (name: String, entityName: String) public let name: String public let isIndexed: Bool public let isOptional: Bool public var isTransient: Bool public let isToMany: Bool public let isOrdered: Bool public let userInfo: [String: Any] public let destinationEntity: String public let inverseRelationship: InverseRelationship? } } private enum XML { fileprivate enum Attributes { static let name = "name" static let isIndexed = "indexed" static let isOptional = "optional" static let isTransient = "transient" static let isToMany = "toMany" static let isOrdered = "ordered" static let destinationEntity = "destinationEntity" static let inverseRelationshipName = "inverseName" static let inverseRelationshipEntityName = "inverseEntity" } static let userInfoPath = "userInfo" } extension CoreData.Relationship { init(with object: Kanna.XMLElement) throws { guard let name = object[XML.Attributes.name] else { throw CoreData.ParserError.invalidFormat(reason: "Missing required relationship name.") } guard let destinationEntity = object[XML.Attributes.destinationEntity] else { throw CoreData.ParserError.invalidFormat(reason: "Missing required destination entity name") } let isIndexed = object[XML.Attributes.isIndexed].flatMap(Bool.init(from:)) ?? false let isOptional = object[XML.Attributes.isOptional].flatMap(Bool.init(from:)) ?? false let isTransient = object[XML.Attributes.isTransient].flatMap(Bool.init(from:)) ?? false let isToMany = object[XML.Attributes.isToMany].flatMap(Bool.init(from:)) ?? false let isOrdered = object[XML.Attributes.isOrdered].flatMap(Bool.init(from:)) ?? false let inverseRelationshipName = object[XML.Attributes.inverseRelationshipName] let inverseRelationshipEntityName = object[XML.Attributes.inverseRelationshipEntityName] let inverseRelationship: InverseRelationship? switch (inverseRelationshipName, inverseRelationshipEntityName) { case (.none, .none): inverseRelationship = nil case (.none, _), (_, .none): throw CoreData.ParserError.invalidFormat( reason: "Both the name and entity name are required for inverse relationships" ) case let (.some(name), .some(entityName)): inverseRelationship = (name: name, entityName: entityName) } let userInfo = try object.at_xpath(XML.userInfoPath).map { try CoreData.UserInfo.parse(from: $0) } ?? [:] self.init( name: name, isIndexed: isIndexed, isOptional: isOptional, isTransient: isTransient, isToMany: isToMany, isOrdered: isOrdered, userInfo: userInfo, destinationEntity: destinationEntity, inverseRelationship: inverseRelationship ) } }
mit
5cb6b62fae0f69ac0bcb86281e723180
33.662791
109
0.719222
4.572086
false
false
false
false
roambotics/swift
stdlib/public/core/LifetimeManager.swift
4
9710
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Evaluates a closure while ensuring that the given instance is not destroyed /// before the closure returns. /// /// - Parameters: /// - x: An instance to preserve until the execution of `body` is completed. /// - body: A closure to execute that depends on the lifetime of `x` being /// extended. If `body` has a return value, that value is also used as the /// return value for the `withExtendedLifetime(_:_:)` method. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withExtendedLifetime<T, Result>( _ x: T, _ body: () throws -> Result ) rethrows -> Result { defer { _fixLifetime(x) } return try body() } /// Evaluates a closure while ensuring that the given instance is not destroyed /// before the closure returns. /// /// - Parameters: /// - x: An instance to preserve until the execution of `body` is completed. /// - body: A closure to execute that depends on the lifetime of `x` being /// extended. If `body` has a return value, that value is also used as the /// return value for the `withExtendedLifetime(_:_:)` method. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withExtendedLifetime<T, Result>( _ x: T, _ body: (T) throws -> Result ) rethrows -> Result { defer { _fixLifetime(x) } return try body(x) } // Fix the lifetime of the given instruction so that the ARC optimizer does not // shorten the lifetime of x to be before this point. @_transparent public func _fixLifetime<T>(_ x: T) { Builtin.fixLifetime(x) } /// Calls the given closure with a mutable pointer to the given argument. /// /// The `withUnsafeMutablePointer(to:_:)` function is useful for calling /// Objective-C APIs that take in/out parameters (and default-constructible /// out parameters) by pointer. /// /// The pointer argument to `body` is valid only during the execution of /// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for /// later use. /// /// - Parameters: /// - value: An instance to temporarily use via pointer. Note that the `inout` /// exclusivity rules mean that, like any other `inout` argument, `value` /// cannot be directly accessed by other code for the duration of `body`. /// Access must only occur through the pointer argument to `body` until /// `body` returns. /// - body: A closure that takes a mutable pointer to `value` as its sole /// argument. If the closure has a return value, that value is also used /// as the return value of the `withUnsafeMutablePointer(to:_:)` function. /// The pointer argument is valid only for the duration of the function's /// execution. /// - Returns: The return value, if any, of the `body` closure. @inlinable public func withUnsafeMutablePointer<T, Result>( to value: inout T, _ body: (UnsafeMutablePointer<T>) throws -> Result ) rethrows -> Result { return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value))) } /// Calls the given closure with a mutable pointer to the given argument. /// /// This function is similar to `withUnsafeMutablePointer`, except that it /// doesn't trigger stack protection for the pointer. @_alwaysEmitIntoClient public func _withUnprotectedUnsafeMutablePointer<T, Result>( to value: inout T, _ body: (UnsafeMutablePointer<T>) throws -> Result ) rethrows -> Result { #if $BuiltinUnprotectedAddressOf return try body(UnsafeMutablePointer<T>(Builtin.unprotectedAddressOf(&value))) #else return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value))) #endif } /// Invokes the given closure with a pointer to the given argument. /// /// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C /// APIs that take in parameters by const pointer. /// /// The pointer argument to `body` is valid only during the execution of /// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later /// use. /// /// - Parameters: /// - value: An instance to temporarily use via pointer. /// - body: A closure that takes a pointer to `value` as its sole argument. If /// the closure has a return value, that value is also used as the return /// value of the `withUnsafePointer(to:_:)` function. The pointer argument /// is valid only for the duration of the function's execution. /// It is undefined behavior to try to mutate through the pointer argument /// by converting it to `UnsafeMutablePointer` or any other mutable pointer /// type. If you need to mutate the argument through the pointer, use /// `withUnsafeMutablePointer(to:_:)` instead. /// - Returns: The return value, if any, of the `body` closure. @inlinable public func withUnsafePointer<T, Result>( to value: T, _ body: (UnsafePointer<T>) throws -> Result ) rethrows -> Result { return try body(UnsafePointer<T>(Builtin.addressOfBorrow(value))) } /// Invokes the given closure with a pointer to the given argument. /// /// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C /// APIs that take in parameters by const pointer. /// /// The pointer argument to `body` is valid only during the execution of /// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later /// use. /// /// - Parameters: /// - value: An instance to temporarily use via pointer. Note that the `inout` /// exclusivity rules mean that, like any other `inout` argument, `value` /// cannot be directly accessed by other code for the duration of `body`. /// Access must only occur through the pointer argument to `body` until /// `body` returns. /// - body: A closure that takes a pointer to `value` as its sole argument. If /// the closure has a return value, that value is also used as the return /// value of the `withUnsafePointer(to:_:)` function. The pointer argument /// is valid only for the duration of the function's execution. /// It is undefined behavior to try to mutate through the pointer argument /// by converting it to `UnsafeMutablePointer` or any other mutable pointer /// type. If you need to mutate the argument through the pointer, use /// `withUnsafeMutablePointer(to:_:)` instead. /// - Returns: The return value, if any, of the `body` closure. @inlinable public func withUnsafePointer<T, Result>( to value: inout T, _ body: (UnsafePointer<T>) throws -> Result ) rethrows -> Result { return try body(UnsafePointer<T>(Builtin.addressof(&value))) } /// Invokes the given closure with a pointer to the given argument. /// /// This function is similar to `withUnsafePointer`, except that it /// doesn't trigger stack protection for the pointer. @_alwaysEmitIntoClient public func _withUnprotectedUnsafePointer<T, Result>( to value: inout T, _ body: (UnsafePointer<T>) throws -> Result ) rethrows -> Result { #if $BuiltinUnprotectedAddressOf return try body(UnsafePointer<T>(Builtin.unprotectedAddressOf(&value))) #else return try body(UnsafePointer<T>(Builtin.addressof(&value))) #endif } extension String { /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of UTF-8 code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(_:)`. Do not store or return the pointer for /// later use. /// /// - Parameter body: A closure with a pointer parameter that points to a /// null-terminated sequence of UTF-8 code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(_:)` method. The pointer argument is valid only for the /// duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // fast-path: already C-string compatible public func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { return try _guts.withCString(body) } } /// Takes in a value at +0 and performs a Builtin.copy upon it. /// /// IMPLEMENTATION NOTES: During transparent inlining, Builtin.copy becomes the /// explicit_copy_value instruction if we are inlining into a context where the /// specialized type is loadable. If the transparent function is called in a /// context where the inlined function specializes such that the specialized /// type is still not loadable, the compiler aborts (a). Once we have opaque /// values, this restriction will be lifted since after that address only types /// at SILGen time will be loadable objects. /// /// (a). This is implemented by requiring that Builtin.copy only be called /// within a function marked with the semantic tag "lifetimemanagement.copy" /// which conveniently is only the function we are defining here: _copy. /// /// NOTE: We mark this _alwaysEmitIntoClient to ensure that we are not creating /// new ABI that the stdlib must maintain if a user calls this ignoring the '_' /// implying it is stdlib SPI. @_alwaysEmitIntoClient @inlinable @_transparent @_semantics("lifetimemanagement.copy") public func _copy<T>(_ value: T) -> T { #if $BuiltinCopy Builtin.copy(value) #else value #endif }
apache-2.0
1ac6774698b4138f76e7ec17547c36cd
41.217391
80
0.699897
4.275649
false
false
false
false
bkmunar/firefox-ios
Client/Frontend/Reader/ReaderModeHandlers.swift
1
4120
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation struct ReaderModeHandlers { static func register(webServer: WebServer, profile: Profile) { // Register our fonts, which we want to expose to web content that we present in the WebView webServer.registerMainBundleResourcesOfType("ttf", module: "reader-mode/fonts") // Register a handler that simply lets us know if a document is in the cache or not. This is called from the // reader view interstitial page to find out when it can stop showing the 'Loading...' page and instead load // the readerized content. webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page-exists") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in if let url = request.query["url"] as? String { if let url = NSURL(string: url) { if ReaderModeCache.sharedInstance.contains(url, error: nil) { return GCDWebServerResponse(statusCode: 200) } else { return GCDWebServerResponse(statusCode: 404) } } } return GCDWebServerResponse(statusCode: 500) } // Register the handler that accepts /reader-mode/page?url=http://www.example.com requests. webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in if let url = request.query["url"] as? String { if let url = NSURL(string: url) { if let readabilityResult = ReaderModeCache.sharedInstance.get(url, error: nil) { // We have this page in our cache, so we can display it. Just grab the correct style from the // profile and then generate HTML from the Readability results. var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } if let html = ReaderModeUtils.generateReaderContent(readabilityResult, initialStyle: readerModeStyle) { return GCDWebServerDataResponse(HTML: html) } } else { // This page has not been converted to reader mode yet. This happens when you for example add an // item via the app extension and the application has not yet had a change to readerize that // page in the background. // // What we do is simply queue the page in the ReadabilityService and then show our loading // screen, which will periodically call page-exists to see if the readerized content has // become available. ReadabilityService.sharedInstance.process(url) if let readerViewLoadingPath = NSBundle.mainBundle().pathForResource("ReaderViewLoading", ofType: "html") { if let readerViewLoading = NSMutableString(contentsOfFile: readerViewLoadingPath, encoding: NSUTF8StringEncoding, error: nil) { return GCDWebServerDataResponse(HTML: readerViewLoading as String) } } } } } let errorString = NSLocalizedString("There was an error converting the page", comment: "Error displayed when reader mode cannot be enabled") return GCDWebServerDataResponse(HTML: errorString) // TODO Needs a proper error page } } }
mpl-2.0
5ccf1302a22a4d53c217ceffdb58fca5
61.439394
159
0.585437
5.868946
false
false
false
false
wess/overlook
Sources/json/json.swift
1
3532
// // JSON.swift // JSON // // Created by Sam Soffes on 9/22/16. // Copyright © 2016 Sam Soffes. All rights reserved. // import Foundation /// JSON dictionary type alias. /// /// Strings must be keys. public typealias JSONDictionary = [String: Any] /// Protocol for things that can be deserialized with JSON. public protocol JSONDeserializable { /// Initialize with a JSON representation /// /// - parameter jsonRepresentation: JSON representation /// - throws: JSONError init(jsonRepresentation: JSONDictionary) throws } public protocol JSONSerializable { /// JSON representation var jsonRepresentation: JSONDictionary { get } } /// Errors for deserializing JSON representations public enum JSONDeserializationError: Error { /// A required attribute was missing case missingAttribute(key: String) /// An invalid type for an attribute was found case invalidAttributeType(key: String, expectedType: Any.Type, receivedValue: Any) /// An attribute was invalid case invalidAttribute(key: String) } /// Generically decode an value from a given JSON dictionary. /// /// - parameter dictionary: a JSON dictionary /// - parameter key: key in the dictionary /// - returns: The expected value /// - throws: JSONDeserializationError public func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T { guard let value = dictionary[key] else { throw JSONDeserializationError.missingAttribute(key: key) } guard let attribute = value as? T else { throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: value) } return attribute } /// Decode a date value from a given JSON dictionary. ISO8601 or Unix timestamps are supported. /// /// - parameter dictionary: a JSON dictionary /// - parameter key: key in the dictionary /// - returns: The expected value /// - throws: JSONDeserializationError public func decode(_ dictionary: JSONDictionary, key: String) throws -> Date { guard let value = dictionary[key] else { throw JSONDeserializationError.missingAttribute(key: key) } if let string = value as? String { guard let date = ISO8601DateFormatter().date(from: string) else { throw JSONDeserializationError.invalidAttribute(key: key) } return date } if let timeInterval = value as? TimeInterval { return Date(timeIntervalSince1970: timeInterval) } if let timeInterval = value as? Int { return Date(timeIntervalSince1970: TimeInterval(timeInterval)) } throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: String.self, receivedValue: value) } /// Decode a JSONDeserializable type from a given JSON dictionary. /// /// - parameter dictionary: a JSON dictionary /// - parameter key: key in the dictionary /// - returns: The expected JSONDeserializable value /// - throws: JSONDeserializationError public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary, key: String) throws -> T { let value: JSONDictionary = try decode(dictionary, key: key) return try decode(value) } /// Decode a JSONDeserializable type /// /// - parameter dictionary: a JSON dictionary /// - returns: the decoded type /// - throws: JSONDeserializationError public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary) throws -> T { return try T.init(jsonRepresentation: dictionary) } func ISO8601DateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }
mit
b269cbfef1517b2ffc5983ee35d40f35
27.707317
112
0.732937
4.544402
false
false
false
false
zhangxigithub/GIF
GIF/AppDelegate.swift
1
1869
// // AppDelegate.swift // GIF // // Created by zhangxi on 7/1/16. // Copyright © 2016 zhangxi.me. All rights reserved. // import Cocoa let thumbPath = NSHomeDirectory().stringByAppendingString("/Documents/thumb") let folderPath = NSHomeDirectory().stringByAppendingString("/Documents/gif") //let palettePath = NSHomeDirectory().stringByAppendingString("/Documents/palette.png") @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application let fm = NSFileManager.defaultManager() do{ try fm.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil) try fm.createDirectoryAtPath(thumbPath, withIntermediateDirectories: true, attributes: nil) }catch { } /* NSFileManager *fm = [NSFileManager defaultManager]; NSString *appGroupName = @"Z123456789.com.example.app-group"; /* For example */ NSURL *groupContainerURL = [fm containerURLForSecurityApplicationGroupIdentifier:appGroupName]; NSError* theError = nil; if (![fm createDirectoryAtURL: groupContainerURL withIntermediateDirectories:YES attributes:nil error:&theError]) { // Handle the error. } */ } func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if flag == false{ for window in sender.windows{ window.makeKeyAndOrderFront(self) } } return true } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
apache-2.0
5202fabf3187bfa83a95450068910fbd
28.650794
123
0.649893
5.510324
false
false
false
false
alex-d-fox/iDoubtIt
iDoubtIt/Code/Card.swift
1
4837
// // Card.swift // iDoubtIt // // Created by Alexander Fox on 8/30/16. // Copyright © 2016 // import Foundation import SpriteKit enum Suit :String { case Hearts, Spades, Clubs, Diamonds, NoSuit static let allValues = [ Hearts, Spades, Clubs, Diamonds, NoSuit ] } enum Value :Int { case Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Joker static let allValues = [ Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Joker ] } enum cardBack :String { case cardBack_blue1, cardBack_blue2, cardBack_blue3, cardBack_blue4, cardBack_blue5, cardBack_green1, cardBack_green2, cardBack_green3, cardBack_green4, cardBack_green5, cardBack_red1, cardBack_red2, cardBack_red3, cardBack_red4, cardBack_red5 static let allValues = [cardBack_blue1, cardBack_blue2, cardBack_blue3, cardBack_blue4, cardBack_blue5, cardBack_green1, cardBack_green2, cardBack_green3, cardBack_green4, cardBack_green5, cardBack_red1, cardBack_red2, cardBack_red3, cardBack_red4, cardBack_red5] } class Card : SKSpriteNode { let suit :Suit let frontTexture :SKTexture let backTexture :SKTexture let value :Value var cardName :String var facedUp :Bool var curTexture :SKTexture required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } init(suit: Suit, value: Value, faceUp: Bool) { self.suit = suit self.value = value if (value != .Joker || suit != .NoSuit) { cardName = "\(value)of\(suit)" } else { cardName = String(format: "Joker") } backTexture = SKTexture(imageNamed: cardCover) frontTexture = SKTexture(imageNamed: cardName) facedUp = faceUp if facedUp { curTexture = frontTexture } else { curTexture = backTexture } super.init(texture: curTexture, color: .clear, size: curTexture.size()) name = cardName } func flipOver() { if facedUp { texture = frontTexture } else { texture = backTexture } facedUp = !facedUp } func getIcon() -> String { let Cards = ["Ace": ["Hearts": "🂱", "Spades": "🂡", "Clubs": "🃑", "Diamonds": "🃁", "NoSuit": "❗️"], "Two": ["Hearts": "🂲", "Spades": "🂢", "Clubs": "🃒", "Diamonds": "🃂", "NoSuit": "❗️"], "Three": ["Hearts": "🂳", "Spades": "🂣", "Clubs": "🃓", "Diamonds": "🃃", "NoSuit": "❗️"], "Four": ["Hearts": "🂴", "Spades": "🂤", "Clubs": "🃔", "Diamonds": "🃄", "NoSuit": "❗️"], "Five": ["Hearts": "🂵", "Spades": "🂥", "Clubs": "🃕", "Diamonds": "🃅", "NoSuit": "❗️"], "Six": ["Hearts": "🂶", "Spades": "🂦", "Clubs": "🃖", "Diamonds": "🃆", "NoSuit": "❗️"], "Seven": ["Hearts": "🂷", "Spades": "🂧", "Clubs": "🃗", "Diamonds": "🃇", "NoSuit": "❗️"], "Eight": ["Hearts": "🂸", "Spades": "🂨", "Clubs": "🃘", "Diamonds": "🃈", "NoSuit": "❗️"], "Nine": ["Hearts": "🂹", "Spades": "🂩", "Clubs": "🃙", "Diamonds": "🃉", "NoSuit": "❗️"], "Ten": ["Hearts": "🂺", "Spades": "🂪", "Clubs": "🃚", "Diamonds": "🃊", "NoSuit": "❗️"], "Jack": ["Hearts": "🂻", "Spades": "🂫", "Clubs": "🃛", "Diamonds": "🃋", "NoSuit": "❗️"], "Queen": ["Hearts": "🂽", "Spades": "🂭", "Clubs": "🃝", "Diamonds": "🃍", "NoSuit": "❗️"], "King": ["Hearts": "🂾", "Spades": "🂮", "Clubs": "🃞", "Diamonds": "🃎", "NoSuit": "❗️"], "Joker": ["Hearts": "🃟", "Spades": "🃟", "Clubs": "🃟", "Diamonds": "🃟", "NoSuit": "❗️"]] let icon = Cards["\(value)"]?["\(suit)"] return icon! } }
gpl-3.0
580c2275bd50b100cb7f4f137f8bcc28
28.948052
103
0.419775
3.716358
false
false
false
false
adamcin/SwiftCJ
SwiftCJ/CJDataElem.swift
1
1224
import Foundation public struct CJDataElem { public let name: String public let prompt: String? public let value: AnyObject? func copyAndSet(value: AnyObject?) -> CJDataElem { if value == nil { return CJDataElem(name: name, prompt: prompt, value: nil) } else if NSJSONSerialization.isValidJSONObject(value!) { return CJDataElem(name: name, prompt: prompt, value: value!) } else { return CJDataElem(name: name, prompt: prompt, value: "\(value!)") } } func toSeri() -> [String: AnyObject] { var seri = [String: AnyObject]() seri["name"] = self.name if let prompt = self.prompt { seri["prompt"] = self.prompt } if let value: AnyObject = self.value { seri["value"] = self.value } return seri } static func elementFromDictionary(dict: [NSObject: AnyObject]) -> CJDataElem? { if let name = dict["name"] as? String { let prompt = dict["prompt"] as? String let value: AnyObject? = dict["value"] return CJDataElem(name: name, prompt: prompt, value: value) } return nil } }
mit
8fc7765dacebd6685e2e26491511c797
31.210526
83
0.564542
4.235294
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/AppFlowViewController.swift
1
23261
/* * Copyright 2019 Google LLC. 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 UIKit import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs /// The primary view controller for Science Journal which owns the navigation controller and manages /// all other flows and view controllers. class AppFlowViewController: UIViewController { /// The account user manager for the current account. Exposed for testing. If the current /// account's ID matches the existing accountUserManager account ID, this returns the existing /// manager. If not, a new manager is created for the current account and returned. var currentAccountUserManager: AccountUserManager? { guard let account = accountsManager.currentAccount else { return nil } if _currentAccountUserManager == nil || _currentAccountUserManager!.account.ID != account.ID { _currentAccountUserManager = AccountUserManager(fileSystemLayout: fileSystemLayout, account: account, driveConstructor: driveConstructor, networkAvailability: networkAvailability, sensorController: sensorController, analyticsReporter: analyticsReporter) } return _currentAccountUserManager } private var _currentAccountUserManager: AccountUserManager? /// The device preference manager. Exposed for testing. let devicePreferenceManager = DevicePreferenceManager() /// The root user manager. Exposed for testing. let rootUserManager: RootUserManager /// The accounts manager. Exposed so the AppDelegate can ask for reauthentication and related /// tasks, as well as testing. let accountsManager: AccountsManager private let analyticsReporter: AnalyticsReporter private let commonUIComponents: CommonUIComponents private let drawerConfig: DrawerConfig private let driveConstructor: DriveConstructor private var existingDataMigrationManager: ExistingDataMigrationManager? private var existingDataOptionsVC: ExistingDataOptionsViewController? private let feedbackReporter: FeedbackReporter private let fileSystemLayout: FileSystemLayout private let networkAvailability: NetworkAvailability private let queue = GSJOperationQueue() private let sensorController: SensorController private var shouldShowPreferenceMigrationMessage = false /// The current user flow view controller, if it exists. private weak var userFlowViewController: UserFlowViewController? #if FEATURE_FIREBASE_RC private var remoteConfigManager: RemoteConfigManager? /// Convenience initializer. /// /// - Parameters: /// - fileSystemLayout: The file system layout. /// - accountsManager: The accounts manager. /// - analyticsReporter: The analytics reporter. /// - commonUIComponents: Common UI components. /// - drawerConfig: The drawer config. /// - driveConstructor: The drive constructor. /// - feedbackReporter: The feedback reporter. /// - networkAvailability: Network availability. /// - remoteConfigManager: The remote config manager. /// - sensorController: The sensor controller. convenience init(fileSystemLayout: FileSystemLayout, accountsManager: AccountsManager, analyticsReporter: AnalyticsReporter, commonUIComponents: CommonUIComponents, drawerConfig: DrawerConfig, driveConstructor: DriveConstructor, feedbackReporter: FeedbackReporter, networkAvailability: NetworkAvailability, remoteConfigManager: RemoteConfigManager, sensorController: SensorController) { self.init(fileSystemLayout: fileSystemLayout, accountsManager: accountsManager, analyticsReporter: analyticsReporter, commonUIComponents: commonUIComponents, drawerConfig: drawerConfig, driveConstructor: driveConstructor, feedbackReporter: feedbackReporter, networkAvailability: networkAvailability, sensorController: sensorController) self.remoteConfigManager = remoteConfigManager } #endif /// Designated initializer. /// /// - Parameters: /// - fileSystemLayout: The file system layout. /// - accountsManager: The accounts manager. /// - analyticsReporter: The analytics reporter. /// - commonUIComponents: Common UI components. /// - drawerConfig: The drawer config. /// - driveConstructor: The drive constructor. /// - feedbackReporter: The feedback reporter. /// - networkAvailability: Network availability. /// - sensorController: The sensor controller. init(fileSystemLayout: FileSystemLayout, accountsManager: AccountsManager, analyticsReporter: AnalyticsReporter, commonUIComponents: CommonUIComponents, drawerConfig: DrawerConfig, driveConstructor: DriveConstructor, feedbackReporter: FeedbackReporter, networkAvailability: NetworkAvailability, sensorController: SensorController) { self.fileSystemLayout = fileSystemLayout self.accountsManager = accountsManager self.analyticsReporter = analyticsReporter self.commonUIComponents = commonUIComponents self.drawerConfig = drawerConfig self.driveConstructor = driveConstructor self.feedbackReporter = feedbackReporter self.networkAvailability = networkAvailability self.sensorController = sensorController rootUserManager = RootUserManager( fileSystemLayout: fileSystemLayout, sensorController: sensorController ) super.init(nibName: nil, bundle: nil) // Register as the delegate for AccountsManager. self.accountsManager.delegate = self // If a user should be forced to sign in from outside the sign in flow (e.g. their account was // invalid on foreground or they deleted an account), this notification will be fired. NotificationCenter.default.addObserver(self, selector: #selector(forceSignInViaNotification), name: .userWillBeSignedOut, object: nil) #if SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD // If we should create root user data to test the claim flow, this notification will be fired. NotificationCenter.default.addObserver(self, selector: #selector(debug_createRootUserData), name: .DEBUG_createRootUserData, object: nil) // If we should create root user data and force auth to test the migration flow, this // notification will be fired. NotificationCenter.default.addObserver(self, selector: #selector(debug_forceAuth), name: .DEBUG_forceAuth, object: nil) #endif // SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() func accountsSupported() { accountsManager.signInAsCurrentAccount() } func accountsNotSupported() { showNonAccountUser(animated: false) } if accountsManager.supportsAccounts { accountsSupported() } else { accountsNotSupported() } } override var preferredStatusBarStyle: UIStatusBarStyle { return children.last?.preferredStatusBarStyle ?? .lightContent } private func showCurrentUserOrSignIn() { guard let accountUserManager = currentAccountUserManager else { print("[AppFlowViewController] No current account user manager, must sign in.") showSignIn() return } let existingDataMigrationManager = ExistingDataMigrationManager(accountUserManager: accountUserManager, rootUserManager: rootUserManager) let accountUserFlow = UserFlowViewController( accountsManager: accountsManager, analyticsReporter: analyticsReporter, commonUIComponents: commonUIComponents, devicePreferenceManager: devicePreferenceManager, drawerConfig: drawerConfig, existingDataMigrationManager: existingDataMigrationManager, feedbackReporter: feedbackReporter, networkAvailability: networkAvailability, sensorController: sensorController, shouldShowPreferenceMigrationMessage: shouldShowPreferenceMigrationMessage, userManager: accountUserManager) accountUserFlow.delegate = self userFlowViewController = accountUserFlow transitionToViewControllerModally(accountUserFlow) // Set to false now so we don't accidently cache true and show it again when we don't want to. shouldShowPreferenceMigrationMessage = false } private func showNonAccountUser(animated: Bool) { let userFlow = UserFlowViewController(accountsManager: accountsManager, analyticsReporter: analyticsReporter, commonUIComponents: commonUIComponents, devicePreferenceManager: devicePreferenceManager, drawerConfig: drawerConfig, existingDataMigrationManager: nil, feedbackReporter: feedbackReporter, networkAvailability: networkAvailability, sensorController: sensorController, shouldShowPreferenceMigrationMessage: false, userManager: rootUserManager) userFlow.delegate = self userFlowViewController = userFlow transitionToViewControllerModally(userFlow, animated: animated) } // Transitions to the sign in flow with an optional completion block to fire when the flow // has been shown. private func showSignIn(completion: (() -> Void)? = nil) { let signInFlow = SignInFlowViewController(accountsManager: accountsManager, analyticsReporter: analyticsReporter, rootUserManager: rootUserManager, sensorController: sensorController) signInFlow.delegate = self transitionToViewControllerModally(signInFlow, completion: completion) } /// Handles a file import URL if possible. /// /// - Parameter url: A file URL. /// - Returns: True if the URL can be handled, otherwise false. func handleImportURL(_ url: URL) -> Bool { guard let userFlowViewController = userFlowViewController else { showSnackbar(withMessage: String.importSignInError) return false } return userFlowViewController.handleImportURL(url) } // MARK: - Private // Wrapper method for use with notifications, where notifications would attempt to push their // notification object into the completion argument of `forceUserSignIn` incorrectly. @objc func forceSignInViaNotification() { tearDownCurrentUser() showSignIn() } private func handlePermissionDenial() { // Remove the current account and force the user to sign in. accountsManager.signOutCurrentAccount() showSignIn { // Show an alert messaging that permission was denied if we can grab the top view controller. // The top view controller is required to present an alert. It should be the sign in flow view // controller. guard let topVC = self.children.last else { return } let alertController = MDCAlertController(title: String.serverPermissionDeniedTitle, message: String.serverPermissionDeniedMessage) alertController.addAction(MDCAlertAction(title: String.serverSwitchAccountsTitle, handler: { (_) in self.presentAccountSelector() })) alertController.addAction(MDCAlertAction(title: String.actionOk)) alertController.accessibilityViewIsModal = true topVC.present(alertController, animated: true) } analyticsReporter.track(.signInPermissionDenied) } /// Migrates preferences and removes bluetooth devices if this account is signing in for the first /// time. /// /// - Parameter accountID: The account ID. /// - Returns: Whether the user should be messaged saying that preferences were migrated. private func migratePreferencesAndRemoveBluetoothDevicesIfNeeded(forAccountID accountID: String) -> Bool { // If an account does not yet have a directory, this is its first time signing in. Each new // account should have preferences migrated from the root user. let shouldMigratePrefs = !fileSystemLayout.hasAccountDirectory(for: accountID) if shouldMigratePrefs, let accountUserManager = currentAccountUserManager { let existingDataMigrationManager = ExistingDataMigrationManager(accountUserManager: accountUserManager, rootUserManager: rootUserManager) existingDataMigrationManager.migratePreferences() existingDataMigrationManager.removeAllBluetoothDevices() } let wasAppUsedByRootUser = rootUserManager.hasExperimentsDirectory return wasAppUsedByRootUser && shouldMigratePrefs } private func performMigrationIfNeededAndContinueSignIn() { guard let accountID = accountsManager.currentAccount?.ID else { sjlog_error("Accounts manager does not have a current account after sign in flow completion.", category: .general) // This method should never be called if the current user doesn't exist but in case of error, // show sign in again. showSignIn() return } // Unwrapping `currentAccountUserManager` would initialize a new instance of the account manager // if a current account exists. This creates the account's directory. However, the migration // method checks to see if this directory exists or not, so we must not call it until after // migration. shouldShowPreferenceMigrationMessage = migratePreferencesAndRemoveBluetoothDevicesIfNeeded(forAccountID: accountID) // Show the migration options if a choice has never been selected. guard !devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption else { showCurrentUserOrSignIn() return } guard let accountUserManager = currentAccountUserManager else { // This delegate method should never be called if the current user doesn't exist but in case // of error, show sign in again. showSignIn() return } let existingDataMigrationManager = ExistingDataMigrationManager(accountUserManager: accountUserManager, rootUserManager: rootUserManager) if existingDataMigrationManager.hasExistingExperiments { self.existingDataMigrationManager = existingDataMigrationManager let existingDataOptionsVC = ExistingDataOptionsViewController( analyticsReporter: analyticsReporter, numberOfExistingExperiments: existingDataMigrationManager.numberOfExistingExperiments) self.existingDataOptionsVC = existingDataOptionsVC existingDataOptionsVC.delegate = self transitionToViewControllerModally(existingDataOptionsVC) } else { showCurrentUserOrSignIn() } } /// Prepares an existing user to be removed from memory. This is non-descrtuctive in terms of /// the user's local data. It should be called when a user is logging out, being removed, or /// changing to a new user. private func tearDownCurrentUser() { _currentAccountUserManager?.tearDown() _currentAccountUserManager = nil userFlowViewController = nil } // swiftlint:disable vertical_parameter_alignment /// Uses a modal UI operation to transition to a view controller. /// /// - Parameters: /// - viewController: The view controller. /// - animated: Whether to animate. /// - minimumDisplaySeconds: The minimum number of seconds to display the view controller for. /// - completion: Called when finished transitioning to the view controller. private func transitionToViewControllerModally(_ viewController: UIViewController, animated: Bool = true, withMinimumDisplaySeconds minimumDisplaySeconds: Double? = nil, completion: (() -> Void)? = nil) { let showViewControllerOp = GSJBlockOperation(mainQueueBlock: { [unowned self] finish in self.transitionToViewController(viewController, animated: animated) { completion?() if let minimumDisplaySeconds = minimumDisplaySeconds { DispatchQueue.main.asyncAfter(deadline: .now() + minimumDisplaySeconds) { finish() } } else { finish() } } }) showViewControllerOp.addCondition(MutuallyExclusive.modalUI) queue.addOperation(showViewControllerOp) } // swiftlint:enable vertical_parameter_alignment } // MARK: - AccountsManagerDelegate extension AppFlowViewController: AccountsManagerDelegate { func deleteAllUserDataForIdentity(withID identityID: String) { // Remove the persistent store before deleting the DB files to avoid a log error. Use // `_currentAccountUserManager`, because `currentAccountUserManager` will return nil because // `accountsManager.currentAccount` is now nil. Also, remove the current account user manager so // the sensor data manager is recreated if this same user logs back in immediately. _currentAccountUserManager?.sensorDataManager.removeStore() tearDownCurrentUser() do { try AccountDeleter(fileSystemLayout: fileSystemLayout, accountID: identityID).deleteData() } catch { print("Failed to delete user data: \(error.localizedDescription)") } } func accountsManagerWillBeginSignIn(signInType: SignInType) { switch signInType { case .newSignIn: transitionToViewControllerModally(LoadingViewController(), withMinimumDisplaySeconds: 0.5) case .restoreCachedAccount: break } } func accountsManagerSignInComplete(signInResult: SignInResult, signInType: SignInType) { switch signInResult { case .accountChanged: switch signInType { case .newSignIn: // Wait for the permissions check to finish before showing UI. break case .restoreCachedAccount: showCurrentUserOrSignIn() } case .forceSignIn: tearDownCurrentUser() showCurrentUserOrSignIn() case .noAccountChange: break } } func accountsManagerPermissionCheckComplete(permissionState: PermissionState, signInType: SignInType) { switch signInType { case .newSignIn: switch permissionState { case .granted: tearDownCurrentUser() performMigrationIfNeededAndContinueSignIn() case .denied: handlePermissionDenial() } case .restoreCachedAccount: switch permissionState { case .granted: // UI was shown when sign in completed. break case .denied: handlePermissionDenial() } } } } // MARK: - ExistingDataOptionsDelegate extension AppFlowViewController: ExistingDataOptionsDelegate { func existingDataOptionsViewControllerDidSelectSaveAllExperiments() { guard let existingDataOptionsVC = existingDataOptionsVC else { return } devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true let spinnerViewController = SpinnerViewController() spinnerViewController.present(fromViewController: existingDataOptionsVC) { self.existingDataMigrationManager?.migrateAllExperiments(completion: { (errors) in spinnerViewController.dismissSpinner { self.showCurrentUserOrSignIn() if errors.containsDiskSpaceError { showSnackbar(withMessage: String.claimExperimentsDiskSpaceErrorMessage) } else if !errors.isEmpty { showSnackbar(withMessage: String.claimExperimentsErrorMessage) } } }) } } func existingDataOptionsViewControllerDidSelectDeleteAllExperiments() { devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true existingDataMigrationManager?.removeAllExperimentsFromRootUser() showCurrentUserOrSignIn() } func existingDataOptionsViewControllerDidSelectSelectExperimentsToSave() { devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true // If the user wants to manually select experiments to claim, nothing needs to be done now. They // will see the option to claim experiments in the experiments list. showCurrentUserOrSignIn() } } // MARK: - SignInFlowViewControllerDelegate extension AppFlowViewController: SignInFlowViewControllerDelegate { func signInFlowDidCompleteWithoutAccount() { showNonAccountUser(animated: true) } } // MARK: - UserFlowViewControllerDelegate extension AppFlowViewController: UserFlowViewControllerDelegate { func presentAccountSelector() { accountsManager.presentSignIn(fromViewController: self) } } #if SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD // MARK: - Debug additions for creating data and testing claim and migration flows in-app. extension AppFlowViewController { @objc private func debug_createRootUserData() { guard let settingsVC = userFlowViewController?.settingsVC else { return } let spinnerVC = SpinnerViewController() spinnerVC.present(fromViewController: settingsVC) { self.rootUserManager.documentManager.debug_createRootUserData { DispatchQueue.main.async { self.userFlowViewController?.experimentsListVC?.refreshUnclaimedExperiments() spinnerVC.dismissSpinner() } } } } @objc private func debug_forceAuth() { devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = false devicePreferenceManager.hasAUserCompletedPermissionsGuide = false NotificationCenter.default.post(name: .DEBUG_destroyCurrentUser, object: nil, userInfo: nil) showSignIn() } } #endif // SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD
apache-2.0
bc8f18811c9ad6695d8ab733f93661b1
40.987365
100
0.699153
5.544934
false
false
false
false
rcasanovan/Social-Feed
Social Feed/Pods/HanekeSwift/Haneke/Fetch.swift
16
2172
// // Fetch.swift // Haneke // // Created by Hermes Pique on 9/28/14. // Copyright (c) 2014 Haneke. All rights reserved. // import Foundation enum FetchState<T> { case pending // Using Wrapper as a workaround for error 'unimplemented IR generation feature non-fixed multi-payload enum layout' // See: http://swiftradar.tumblr.com/post/88314603360/swift-fails-to-compile-enum-with-two-data-cases // See: http://owensd.io/2014/08/06/fixed-enum-layout.html case success(Wrapper<T>) case failure(Error?) } open class Fetch<T> { public typealias Succeeder = (T) -> () public typealias Failer = (Error?) -> () fileprivate var onSuccess : Succeeder? fileprivate var onFailure : Failer? fileprivate var state : FetchState<T> = FetchState.pending public init() {} @discardableResult open func onSuccess(_ onSuccess: @escaping Succeeder) -> Self { self.onSuccess = onSuccess switch self.state { case FetchState.success(let wrapper): onSuccess(wrapper.value) default: break } return self } @discardableResult open func onFailure(_ onFailure: @escaping Failer) -> Self { self.onFailure = onFailure switch self.state { case FetchState.failure(let error): onFailure(error) default: break } return self } func succeed(_ value: T) { self.state = FetchState.success(Wrapper(value)) self.onSuccess?(value) } func fail(_ error: Error? = nil) { self.state = FetchState.failure(error) self.onFailure?(error) } var hasFailed : Bool { switch self.state { case FetchState.failure(_): return true default: return false } } var hasSucceeded : Bool { switch self.state { case FetchState.success(_): return true default: return false } } } open class Wrapper<T> { open let value: T public init(_ value: T) { self.value = value } }
apache-2.0
9df7768464fead6b233fd218a7b6cf5d
23.404494
120
0.581031
4.370221
false
false
false
false
mathiasquintero/Sweeft
Sources/Sweeft/Promises/Subclasses/BulkPromise.swift
1
1796
// // BulkPromise.swift // Pods // // Created by Mathias Quintero on 12/29/16. // // import Foundation /// A promise that represent a collection of other promises and waits for them all to be finished public final class BulkPromise<T, O: Error>: SelfSettingPromise<[T], O> { private let queue = DispatchQueue(label: "io.quintero.Sweeft.BulkPromise") private var cancellers: [Promise<T, O>.Canceller] private var results: [Int : T] = .empty { didSet { if results.count == count { let sorted = results.sorted(ascending: firstArgument) => lastArgument setter?.success(with: sorted) } } } private var count: Int { return cancellers.count } public init(promises: [Promise<T,O>], completionQueue: DispatchQueue = .global()) { let cancellers = promises => { $0.canceller } self.cancellers = cancellers super.init(completionQueue: completionQueue) promises.withIndex => { promise, index in promise.onError(in: queue, call: self.setter.error) promise.onSuccess(in: queue) { result in self.results[index] = result } } setter.onCancel { cancellers => { $0.cancel() } } if promises.isEmpty { setter.success(with: []) } } } extension BulkPromise where T: Collection { public var flattened: Promise<[T.Element], O> { return map { result in return result.flatMap(id) } } } extension BulkPromise: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: Promise<T, O>...) { self.init(promises: elements) } }
mit
636185262fe8fdd9251b15649a371af0
25.411765
97
0.577394
4.348668
false
false
false
false
mitchtreece/Bulletin
Example/Pods/Espresso/Espresso/Classes/Core/Protocols/Convertibles/BoolConvertible.swift
1
2105
// // BoolConvertible.swift // Espresso // // Created by Mitch Treece on 12/15/17. // import Foundation /** Protocol describing the conversion to various `Bool` representations. */ public protocol BoolConvertible { /** A boolean representation. */ var bool: Bool? { get } /** A boolean integer representation; _0 or 1_. */ var boolInt: Int? { get } /** A boolean string representation _"true" or "false"_. */ var boolString: String? { get } } extension Bool: BoolConvertible { public static let trueString = "true" public static let falseString = "false" public var bool: Bool? { return self } public var boolInt: Int? { return self ? 1 : 0 } public var boolString: String? { return self ? Bool.trueString : Bool.falseString } } extension Int: BoolConvertible { public var bool: Bool? { return (self <= 0) ? false : true } public var boolInt: Int? { return (self <= 0) ? 0 : 1 } public var boolString: String? { return (self <= 0) ? Bool.falseString : Bool.trueString } } extension String: BoolConvertible { public var bool: Bool? { guard let value = self.boolInt else { return nil } switch value { case 0: return false case 1: return true default: return nil } } public var boolInt: Int? { guard let value = self.boolString else { return nil } switch value { case Bool.trueString: return 1 case Bool.falseString: return 0 default: return nil } } public var boolString: String? { let value = self.lowercased() if value == Bool.trueString || value == "1" { return Bool.trueString } else if value == Bool.falseString || value == "0" { return Bool.falseString } return nil } }
mit
1225fb632ff286c6c960bebf3e3e4136
18.490741
70
0.528266
4.36722
false
false
false
false
leios/algorithm-archive
contents/verlet_integration/code/swift/verlet.swift
1
1714
func verlet(pos: Double, acc: Double, dt: Double) -> Double { var pos = pos var temp_pos, time: Double var prev_pos = pos time = 0.0 while (pos > 0) { time += dt temp_pos = pos pos = pos*2 - prev_pos + acc * dt * dt prev_pos = temp_pos } return time } func stormerVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) { var pos = pos var temp_pos, time, vel: Double var prev_pos = pos vel = 0 time = 0 while (pos > 0) { time += dt temp_pos = pos pos = pos*2 - prev_pos + acc * dt * dt prev_pos = temp_pos vel += acc*dt } return (time:time, vel:vel) } func velocityVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) { var pos = pos var time, vel : Double vel = 0 time = 0 while (pos > 0) { time += dt pos += vel*dt + 0.5*acc * dt * dt vel += acc*dt } return (time:time, vel:vel) } func main() { let verletTime = verlet(pos: 5.0, acc: -10.0, dt: 0.01) print("[#]\nTime for Verlet integration is:") print("\(verletTime)") let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01); print("[#]\nTime for Stormer Verlet integration is:") print("\(stormer.time)") print("[#]\nVelocity for Stormer Verlet integration is:") print("\(stormer.vel)") let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01) print("[#]\nTime for velocity Verlet integration is:") print("\(velVerlet.time)") print("[#]\nVelocity for velocity Verlet integration is:") print("\(velVerlet.vel)") } main()
mit
8f0310060ee80a388b82e9b5a7ac58a6
23.84058
90
0.54084
3.321705
false
false
false
false
BBRick/wp
wp/Scenes/Home/SideVC.swift
1
2295
// // SideVC.swift // wp // // Created by 木柳 on 2016/12/22. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SideMenuController class SideVC: SideMenuController, SideMenuControllerDelegate { required init?(coder aDecoder: NSCoder) { SideMenuController.preferences.drawing.menuButtonImage = UIImage.init(named:"1") SideMenuController.preferences.drawing.sidePanelPosition = .overCenterPanelLeft SideMenuController.preferences.drawing.sidePanelWidth = UIScreen.main.bounds.size.width * 0.80 SideMenuController.preferences.drawing.centerPanelShadow = true SideMenuController.preferences.animating.statusBarBehaviour = .slideAnimation super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() performSegue(withIdentifier: "centerSegue", sender: nil) performSegue(withIdentifier: "sideSegue", sender: nil) delegate = self } func sideMenuControllerDidHide(_ sideMenuController: SideMenuController) { tabBarController?.tabBar.isHidden = false } func sideMenuControllerDidReveal(_ sideMenuController: SideMenuController) { tabBarController?.tabBar.isHidden = true } } extension SideVC{ public override static func initialize() { //tabbar的隐藏 let originalSelector = #selector(SideMenuController.toggle) let swizzledSelector = #selector(SideVC.wpToggle) let originalMethod = class_getInstanceMethod(self, originalSelector) let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) let didsMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) if didsMethod { class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) } else { method_exchangeImplementations(originalMethod, swizzledMethod); } } func wpToggle() { // if checkLogin() { self.wpToggle() super.toggle() tabBarController?.tabBar.isHidden = true // } } }
apache-2.0
8b448857e9aab47f6a33388adcbfd91b
33.059701
146
0.683173
5.282407
false
false
false
false
crazypoo/Tuan
Tuan/Deal/HMDealsViewController.swift
8
19312
// // HMDealsViewController.swift // Tuan // // Created by nero on 15/5/13. // Copyright (c) 2015年 nero. All rights reserved. // import UIKit class HMDealsViewController: HMDealListViewController { //MARK: - 顶部菜单 /** 分类菜单 */ var categoryMenu:HMDealsTopMenu! /** 区域菜单 */ var regionMenu:HMDealsTopMenu! /** 排序菜单 */ var sortMenu:HMDealsTopMenu! /** 选中的状态 */ var selectedCity:HMCity! /** 当前选中的区域 */ var selectedRegion:HMRegion! /** 当前选中的排序 */ var selectedSort:HMSort! /** 当前选中的分类 */ var selectedCategory:HMCategory! /** 当前选中的子分类名称 */ var selectedSubCategoryName:String! /** 当前选中的子区域名称 */ var selectedSubRegionName:String! //MARK: - 点击顶部菜单后弹出的Popover /** 分类Popover */ lazy var categoryPopover:UIPopoverController = { let cv = HMCategoriesViewController() return UIPopoverController(contentViewController: cv) }() /** 区域Popover */ lazy var regionPopover:UIPopoverController = { let rv = HMRegionsViewController() rv.view = NSBundle.mainBundle().loadNibNamed("HMRegionsViewController", owner: rv, options: nil).last as! UIView var region = UIPopoverController(contentViewController: rv) rv.changeCityClosuer = { region.dismissPopoverAnimated(false) } return region }() /** 排序Popover */ lazy var sortPopover:UIPopoverController = { let sv = HMSortsViewController() return UIPopoverController(contentViewController: HMSortsViewController(nibName: "HMSortsViewController", bundle: NSBundle.mainBundle())) }() /** 请求参数 */ var lastParam:HMFindDealsParam? var header:MJRefreshHeaderView! var footer:MJRefreshFooterView! /// 团购数据 /** 存储请求结果的总数*/ var totalNumber:Int = 0 override func viewDidLoad() { super.viewDidLoad() selectedSort = HMMetaDataTool.sharedMetaDataTool().selectedSort() selectedCity = HMMetaDataTool.sharedMetaDataTool().selectedCity() var rs = regionPopover.contentViewController as! HMRegionsViewController if selectedCity != nil { rs.regions = (selectedCity.regions as? [HMRegion] ) ?? nil ; } setupMenu() setupNavLeft() setupNavRight() setupRefresh() // 监听通知 HMNotificationCenter.addObserver(self, selector: Selector("citySelecte:"), name: HMCityNotification.HMCityDidSelectNotification, object: nil) HMNotificationCenter.addObserver(self, selector: Selector("sortSelect:"), name: HMSortNotification.HMSortDidSelectNotification, object: nil) HMNotificationCenter.addObserver(self, selector: Selector("categoryDidSelect:"), name: HMCategoryNotification.HMCategoryDidSelectNotification, object: nil) HMNotificationCenter.addObserver(self, selector: Selector("regionDidSelect:"), name: HMRegionNotification.HMRegionDidSelectNotification, object: nil) } func setupRefresh(){ // MJRefreshHeaderView *header = [MJRefreshHeaderView header]; self.header = MJRefreshHeaderView.header() self.footer = MJRefreshFooterView.footer() self.header.scrollView = self.collectionView self.footer.scrollView = self.collectionView self.header.delegate = self self.footer.delegate = self header.beginRefreshing() } func citySelecte(noti:NSNotification){ var dict = noti.userInfo as! [String:HMCity] selectedCity = dict[HMCityNotification.HMSelectedCity] selectedRegion = selectedCity.regions.first as! HMRegion regionMenu.titleLabel.text = selectedCity?.name.stringByAppendingString(" - 全部") regionMenu.subtitleLabel.text = "" // var regionVc = regionPopover.contentViewController as! HMRegionsViewController regionVc.regions = selectedCity?.regions as! [HMRegion] header.beginRefreshing() // 存储用户的选择到沙盒 HMMetaDataTool.sharedMetaDataTool().saveSelectedCityName(selectedCity.name) } func sortSelect(noti:NSNotification){ var dict = noti.userInfo as! [String:HMSort] selectedSort = dict[HMSortNotification.HMSelectedSort] sortMenu.subtitleLabel.text = selectedSort?.label sortPopover.dismissPopoverAnimated(true) header.beginRefreshing() // 存储用户的选择到沙盒 HMMetaDataTool.sharedMetaDataTool().saveSelectedSort(selectedSort) } func regionDidSelect(noti:NSNotification) { // 取出通知中的数据 selectedRegion = noti.userInfo?[HMRegionNotification.HMSelectedRegion] as? HMRegion selectedSubRegionName = noti.userInfo?[HMRegionNotification.HMSelectedSubRegionName] as? String regionMenu.titleLabel.text = "\(selectedCity.name) - \(selectedRegion.name)" regionMenu.subtitleLabel.text = selectedSubRegionName // 设置菜单数据 // 关闭popover regionPopover.dismissPopoverAnimated(true) header.beginRefreshing() } func categoryDidSelect(noti:NSNotification){ // 取出通知中的数据 selectedCategory = noti.userInfo?[HMCategoryNotification.HMSelectedCategory] as? HMCategory selectedSubCategoryName = noti.userInfo?[HMCategoryNotification.HMSelectedSubCategoryName] as? String // 设置菜单数据 categoryMenu.imageButton.image = selectedCategory.icon categoryMenu.imageButton.highlightedImage = selectedCategory.highlighted_icon categoryMenu.titleLabel.text = selectedCategory.name categoryMenu.subtitleLabel.text = selectedSubCategoryName // 关闭popover categoryPopover.dismissPopoverAnimated(true) header.beginRefreshing() } deinit{ HMNotificationCenter.removeObserver(self) self.footer = nil self.header = nil } /** * 设置导航栏左边的内容 */ private func setupNavLeft() { // 1.LOGO var logoItem = UIBarButtonItem(imageName: "icon_meituan_logo", highImageName: "icon_meituan_logo", target: nil, action: nil) logoItem.customView?.userInteractionEnabled = false // 2.分类 categoryMenu = HMDealsTopMenu() var categoryItem = UIBarButtonItem(customView: categoryMenu) categoryMenu.addTarget(self, action: Selector("categoryMenuClick")) // 3.区域 regionMenu = HMDealsTopMenu() regionMenu.imageButton.image = "icon_district"; regionMenu.imageButton.highlightedImage = "icon_district_highlighted"; var selectName = selectedCity?.name ?? " " regionMenu.titleLabel.text = "\(selectName) - 全部" var regionItem = UIBarButtonItem(customView: regionMenu) regionMenu.addTarget(self, action: Selector("regionMenuClick")) // 4.排序 sortMenu = HMDealsTopMenu() var sortItem = UIBarButtonItem(customView: sortMenu) sortMenu.addTarget(self, action: Selector("sortMenuClick")) sortMenu.imageButton.image = "icon_sort"; sortMenu.imageButton.highlightedImage = "icon_sort_highlighted" sortMenu.titleLabel.text = "排序" sortMenu.subtitleLabel.text = self.selectedSort?.label; self.navigationItem.leftBarButtonItems = [logoItem, categoryItem, regionItem, sortItem]; } // MARK: -leftItem Event /** 分类菜单 */ func categoryMenuClick(){ var cs = categoryPopover.contentViewController as! HMCategoriesViewController cs.selectedCategory = selectedCategory cs.selectedSubCategoryName = selectedSubCategoryName; categoryPopover.presentPopoverFromRect(categoryMenu.bounds, inView: categoryMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } /** 区域菜单 */ func regionMenuClick(){ var rs = regionPopover.contentViewController as! HMRegionsViewController rs.selectedRegion = selectedRegion; rs.selectedSubRegionName = selectedSubRegionName; regionPopover.presentPopoverFromRect(regionMenu.bounds, inView: regionMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } /** 排序菜单 */ func sortMenuClick(){ var os = sortPopover.contentViewController as! HMSortsViewController os.selectedSort = self.selectedSort; sortPopover.presentPopoverFromRect(sortMenu.bounds, inView: sortMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } /** *MARK:- 设置导航栏右边的内容 */ private func setupNavRight() { // // 1.地图 var mapItem = UIBarButtonItem(imageName: "icon_map", highImageName: "icon_map_highlighted", target: self , action: Selector("mapClick")) mapItem.customView?.width = 50 mapItem.customView?.height = 27 // // 2.搜索 var searchItem = UIBarButtonItem(imageName: "icon_search", highImageName: "icon_search_highlighted", target: self, action: Selector("searchClick")) searchItem.customView?.width = mapItem.customView!.width searchItem.customView?.width = mapItem.customView!.height self.navigationItem.rightBarButtonItems = [mapItem,searchItem] } /** * 搜索 */ func searchClick() { var searchVc = HMSearchViewController(collectionViewLayout: UICollectionViewLayout()) searchVc.selectedCity = self.selectedCity; var nav = HMNavigationController(rootViewController: searchVc) presentViewController(nav, animated: true, completion: nil) } /** * 地图 */ func mapClick(){ var nav = HMNavigationController(rootViewController: HMMapViewController()) presentViewController(nav , animated: true, completion: nil) } /** 封装请求参数 :returns: param */ func buildParam() -> HMFindDealsParam { var param = HMFindDealsParam() // 城市名称 param.city = selectedCity?.name if selectedSort != nil { param.sort = NSNumber(int: selectedSort.value) } // 除开“全部分类”和“全部”以外的所有词语都可以发 if selectedCategory != nil && !(selectedCategory?.name == "全部分类") { if selectedSubCategoryName != nil && !(self.selectedSubCategoryName == "全部"){ param.category = selectedSubCategoryName }else{ param.category = selectedCategory?.name } } if selectedRegion != nil && !(selectedRegion?.name == "全部" ){ if selectedSubRegionName != nil && !(selectedSubRegionName == "全部"){ param.region = selectedSubRegionName }else{ param.region = selectedRegion?.name } } param.page = NSNumber(int: 1) return param } func loadNewDeals(){ // // 1.创建请求参数 var param = buildParam() // // 2.加载数据 HMDealTool.findDeals(param, success: { (result) -> Void in if param != self.lastParam {return } // 记录总数 self.totalNumber = Int(result.total_count) // // 清空之前的所有数据 self.deals.removeAll(keepCapacity: false) for deal in result.deals { self.deals.append(deal as! HMDeal) } self.collectionView?.reloadData() self.header.endRefreshing() }) { (error) -> Void in if param != self.lastParam {return } MBProgressHUD.showError("加载团购失败,请稍后再试") self.header.endRefreshing() } // // 3.保存请求参数 self.lastParam = param; } /** 加载新数据 */ #if false func loadXXXNewDeals(){ HMDealTool.loadNewDeals(selectedCity, selectSort: selectedSort, selectedCategory: selectedCategory, selectedRegion: selectedRegion, selectedSubCategoryName: selectedSubCategoryName, selectedSubRegionName: selectedSubRegionName) { (result) -> Void in // 清空之前的所有数据 self.deals = [HMDeal]() // 添加新的数据 for deal in result { self.deals.append(deal as! HMDeal) } // 刷新表格 self.collectionView?.reloadData() } } #endif /** 加载更多 */ func loadMoreDeals(){ // // 1.创建请求参数 var param = buildParam() // // 页码 if let lastParam = self.lastParam { var currentPage = lastParam.page.intValue + 1 param.page = NSNumber(int: currentPage) } HMDealTool.findDeals(param, success: { (result) -> Void in if param != self.lastParam {return } for deal in result.deals { self.deals.append(deal as! HMDeal) } self.collectionView?.reloadData() self.footer.endRefreshing() }) { (error) -> Void in if param != self.lastParam {return } MBProgressHUD.showError("加载团购失败,请稍后再试") // // 结束刷新 self.footer.endRefreshing() // // 回滚页码 if let lastParam = self.lastParam { var currentPage = lastParam.page.intValue - 1 param.page = NSNumber(int: currentPage) } } self.lastParam = param } // MARK: - 初始化菜单 private func setupMenu(){ // // 1.周边的item var mineItem = itemWithContent("icon_pathMenu_mine_normal", highlightedContent: "icon_pathMenu_mine_highlighted") var collectItem = itemWithContent("icon_pathMenu_collect_normal" , highlightedContent: "icon_pathMenu_collect_highlighted") var scanItem = itemWithContent("icon_pathMenu_scan_normal", highlightedContent: "icon_pathMenu_more_normal") var moreItem = itemWithContent("icon_pathMenu_more_normal", highlightedContent: "icon_pathMenu_more_highlighted") var items = [mineItem,collectItem,scanItem,moreItem] // // 2.中间的开始tiem var startItem = AwesomeMenuItem(image: UIImage(named: "icon_pathMenu_background_normal"), highlightedImage: UIImage(named:"icon_pathMenu_background_highlighted"), contentImage: UIImage(named:"icon_pathMenu_mainMine_normal"), highlightedContentImage: UIImage(named:"icon_pathMenu_mainMine_highlighted")) var menu = AwesomeMenu(frame: CGRectZero, startItem: startItem, optionMenus: items) view.addSubview(menu) // // 真个菜单的活动范围 menu.menuWholeAngle = CGFloat( M_PI_2); // // 约束 var menuH:CGFloat = 200 menu.autoSetDimensionsToSize(CGSize(width: 200, height: menuH)) menu.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0) menu.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 0) // // 3.添加一个背景 let menubg = UIImageView() menubg.image = UIImage(named: "icon_pathMenu_background") menu.insertSubview(menubg, atIndex: 0) // 约束 menubg.autoSetDimensionsToSize(menubg.image!.size) menubg.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0) menubg.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 0) // // 起点 menu.startPoint = CGPoint(x: menubg.image!.size.width * 0.5, y: menuH - menubg.image!.size.height * 0.5) // // 禁止中间按钮旋转 menu.rotateAddButton = false // // // 设置代理 menu.delegate = self; // menu.alpha = CGFloat(0.2) } private func itemWithContent(content:String , highlightedContent:String) ->AwesomeMenuItem { let bg = UIImage(named: "bg_pathMenu_black_normal"); return AwesomeMenuItem(image: bg, highlightedImage: nil, contentImage: UIImage(named: content), highlightedContentImage: UIImage(named: highlightedContent)) } } extension HMDealsViewController:AwesomeMenuDelegate { func awesomeMenuWillAnimateClose(menu: AwesomeMenu!) { // 恢复图片 menu.contentImage = UIImage(named: "icon_pathMenu_mainMine_normal") menu.highlightedContentImage = UIImage(named: "icon_pathMenu_mainMine_highlighted") UIView.animateWithDuration(0.25, animations: { () -> Void in menu.alpha = CGFloat(0.2) }) } func awesomeMenuWillAnimateOpen(menu: AwesomeMenu!) { // 显示xx图片 menu.contentImage = UIImage(named: "icon_pathMenu_cross_normal"); menu.highlightedContentImage = UIImage(named: "icon_pathMenu_cross_highlighted") UIView.animateWithDuration(0.25, animations: { () -> Void in menu.alpha = CGFloat(1) }) } func awesomeMenu(menu: AwesomeMenu!, didSelectIndex idx: Int) { awesomeMenuWillAnimateClose(menu) if (idx == 1) { // 收藏 let collec = HMCollectViewController(collectionViewLayout: UICollectionViewFlowLayout()) var nav = HMNavigationController(rootViewController: collec) presentViewController(nav, animated: true, completion: nil) } else if (idx == 2) { // 浏览记录 let history = HMHistoryViewController(collectionViewLayout: UICollectionViewFlowLayout()) var nav = HMNavigationController(rootViewController: history) presentViewController(nav, animated: true, completion: nil) } } } // MARK: - cell And Layout extension HMDealsViewController { // #warning 如果要在数据个数发生的改变时做出响应,那么响应操作可以考虑在数据源方法中实现 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 尾部控件的可见性 self.footer.hidden = (self.deals.count == self.totalNumber); return super.collectionView(collectionView, numberOfItemsInSection: section) } } extension HMDealsViewController: MJRefreshBaseViewDelegate { func refreshViewBeginRefreshing(refreshView: MJRefreshBaseView!) { if refreshView === self.header { self.loadNewDeals() }else if refreshView === self.footer { self.loadMoreDeals() } } } //MARK: - emptyView ICON extension HMDealsViewController { override func emptyIcon() -> String { return "icon_deals_empty" } }
mit
1416ed45fb35116a1b28b8367212a88a
38.170213
313
0.634764
4.6025
false
false
false
false
emrecaliskan/ECDropDownList
ECDropDownList/ECListItemView.swift
1
2655
// // ECListItemView.swift // ECDropDownList // // Created by Emre Caliskan on 2015-03-23. // Copyright (c) 2015 pictago. All rights reserved. // import UIKit func ==(lhs: ECListItemView, rhs: ECListItemView) -> Bool { return lhs.listItem == rhs.listItem } protocol ECListItemDelegate { func didTapItem(listItemView:ECListItemView) } class ECListItemView: UIView { var listItem:ECListItem var titleLabel:UILabel = UILabel() var listItemFrameHeight = CGFloat(40.0) var listItemTextAlignment = NSTextAlignment.Center var overlayButton = UIButton() var delegate:ECListItemDelegate? override init(frame: CGRect) { self.listItem = ECListItem() super.init(frame: frame) } init(listItem:ECListItem) { self.listItem = listItem super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, listItemFrameHeight)) self.backgroundColor = UIColor.lightGrayColor() //Add titleLabel for Item titleLabel.frame = self.frame titleLabel.text = self.listItem.text titleLabel.textColor = UIColor.blackColor() titleLabel.textAlignment = listItemTextAlignment self.addSubview(titleLabel) //Configure Overlay Button that handles tap actions overlayButton.frame = self.frame overlayButton.backgroundColor = UIColor.clearColor() overlayButton.addTarget(self, action: "didPressButton", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(overlayButton) } required init(coder aDecoder: NSCoder) { self.listItem = ECListItem() super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() } /// Executes listItem action, if the listItemView is not the topView in the menu.THEN, executes delegate didTap delegate. Order is important. func didPressButton(){ if !listItem.isSelected{ listItem.action?() } delegate?.didTapItem(self) } override func copy() -> AnyObject { let copy = ECListItemView(listItem: self.listItem) copy.titleLabel = self.titleLabel copy.listItemFrameHeight = self.listItemFrameHeight copy.listItemTextAlignment = self.listItemTextAlignment copy.overlayButton = self.overlayButton return copy } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
855de3c5339f9ec0e07f2893ad86d2b1
28.831461
145
0.667797
4.724199
false
false
false
false
nfls/nflsers
app/v2/Controller/Practice/ProblemSearchController.swift
1
6265
// // ProblemSearchController.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/9/23. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import Eureka class ProblemSearchController: FormViewController { let courseProvider = CourseProvider() let paperProvider = PaperProvider() let problemProvider = ProblemProvider() enum Mode: String { case question = "题目" case paper = "往卷" case wrong = "错题" } let isNotPaper = Condition.function(["type"], { (form) -> Bool in return (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value != Mode.paper.rawValue }) let isNotQuestion = Condition.function(["type"], { (form) -> Bool in return (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value != Mode.question.rawValue }) override func viewDidLoad() { super.viewDidLoad() courseProvider.load { self.list() } self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(search)) } @objc func search() { switch (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value { case Mode.paper.rawValue: let section = form.sectionBy(tag: "paper") as! SelectableSection<ListCheckRow<UUID>> if let paper = section.selectedRow()?.selectableValue { self.problemProvider.list(withPaper: paper) { dump(self.problemProvider.list) } } break case Mode.question.rawValue: break case Mode.wrong.rawValue: break default: break } } func addCourse(withType type: Course.CourseType, name: String) { let section = SelectableSection<ListCheckRow<UUID>>(name, selectionType: .singleSelection(enableDeselection: false)) { $0.tag = String(describing: type) $0.hidden = Condition.function([], { (form) -> Bool in let section = form.sectionBy(tag: "course") as? SelectableSection<ListCheckRow<Int>> return section?.selectedRow()?.selectableValue != type.rawValue }) $0.onSelectSelectableRow = { (cell, cellRow) in self.paperProvider.load(withCourse: cellRow.selectableValue!, completion: { self.addPaperSelect() }) } } let list = self.courseProvider.list.filter { (course) -> Bool in return course.type == type } for course in list { section <<< ListCheckRow<UUID>() { listRow in listRow.title = course.name + " (" + course.remark + ")" listRow.selectableValue = course.id listRow.value = nil } } self.form +++ section } func removePaperSelect() { if let section = form.sectionBy(tag: "paper"), let index = section.index { form.remove(at: index) } } func addPaperSelect() { self.removePaperSelect() let section = SelectableSection<ListCheckRow<UUID>>("试卷", selectionType: .singleSelection(enableDeselection: false)) { $0.tag = "paper" //$0.hidden = self.isQuestion } for paper in paperProvider.list { section <<< ListCheckRow<UUID>(paper.name) { $0.title = paper.name $0.selectableValue = paper.id $0.value = nil } } form +++ section } func addTypeSelect() { let options = ["IGCSE", "A-Level", "IBDP"] let section = SelectableSection<ListCheckRow<Int>>("课程", selectionType: .singleSelection(enableDeselection: false)) { $0.tag = "course" } section <<< ListCheckRow<Int>("所有") { $0.title = "所有" $0.selectableValue = 0 $0.value = nil $0.hidden = self.isNotPaper } for (key, option) in options.enumerated() { section <<< ListCheckRow<Int>(option) { listRow in listRow.title = option listRow.selectableValue = key + 1 listRow.value = nil } } section.onSelectSelectableRow = { [weak self] _, _ in self?.form.sectionBy(tag: String(describing: Course.CourseType.alevel))?.evaluateHidden() self?.form.sectionBy(tag: String(describing: Course.CourseType.igcse))?.evaluateHidden() self?.form.sectionBy(tag: String(describing: Course.CourseType.ibdp))?.evaluateHidden() } form +++ section } func list() { self.form +++ Section("类型") <<< SegmentedRow<String>() { $0.tag = "type" $0.options = ["题目", "往卷", "错题"] $0.value = "题目" $0.onChange({ (_) in self.removePaperSelect() }) } self.addTypeSelect() self.addCourse(withType: Course.CourseType.igcse, name: "IGCSE") self.addCourse(withType: Course.CourseType.alevel, name: "A-Level") self.addCourse(withType: Course.CourseType.ibdp, name: "IBDP") self.form +++ Section("题型") {$0.hidden = self.isNotQuestion} <<< SwitchRow() { (switchRow) in switchRow.title = "选择题" switchRow.value = true } <<< SwitchRow() { (switchRow) in switchRow.title = "填空题" switchRow.value = true } +++ Section("附加") {$0.hidden = self.isNotQuestion} <<< SwitchRow() { (switchRow) in switchRow.title = "精确搜索" } +++ Section("搜索") {$0.hidden = self.isNotQuestion} <<< TextAreaRow() { (textAreaRow) in textAreaRow.placeholder = "题面,几个词即可" } <<< ButtonRow() {(buttonRow) in buttonRow.title = "拍照" } } }
apache-2.0
6d82419f341bde9385961f3d31c66cbf
34.595376
135
0.53394
4.459088
false
false
false
false
kaojohnny/CoreStore
Sources/Internal/NSManagedObjectContext+Setup.swift
1
6500
// // NSManagedObjectContext+Setup.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - NSManagedObjectContext internal extension NSManagedObjectContext { // MARK: Internal @nonobjc internal weak var parentStack: DataStack? { get { if let parentContext = self.parentContext { return parentContext.parentStack } return cs_getAssociatedObjectForKey(&PropertyKeys.parentStack, inObject: self) } set { guard self.parentContext == nil else { return } cs_setAssociatedWeakObject( newValue, forKey: &PropertyKeys.parentStack, inObject: self ) } } @nonobjc internal static func rootSavingContextForCoordinator(coordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context.persistentStoreCoordinator = coordinator context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy context.undoManager = nil context.setupForCoreStoreWithContextName("com.corestore.rootcontext") #if os(iOS) || os(OSX) context.observerForDidImportUbiquitousContentChangesNotification = NotificationObserver( notificationName: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: coordinator, closure: { [weak context] (note) -> Void in context?.performBlock { () -> Void in let updatedObjectIDs = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObjectID>) ?? [] for objectID in updatedObjectIDs { context?.objectWithID(objectID).willAccessValueForKey(nil) } context?.mergeChangesFromContextDidSaveNotification(note) } } ) #endif return context } @nonobjc internal static func mainContextForRootContext(rootContext: NSManagedObjectContext) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) context.parentContext = rootContext context.mergePolicy = NSRollbackMergePolicy context.undoManager = nil context.setupForCoreStoreWithContextName("com.corestore.maincontext") context.observerForDidSaveNotification = NotificationObserver( notificationName: NSManagedObjectContextDidSaveNotification, object: rootContext, closure: { [weak context] (note) -> Void in guard let rootContext = note.object as? NSManagedObjectContext, let context = context else { return } let mergeChanges = { () -> Void in let updatedObjects = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [] for object in updatedObjects { context.objectWithID(object.objectID).willAccessValueForKey(nil) } context.mergeChangesFromContextDidSaveNotification(note) } if rootContext.isSavingSynchronously == true { context.performBlockAndWait(mergeChanges) } else { context.performBlock(mergeChanges) } } ) return context } // MARK: Private private struct PropertyKeys { static var parentStack: Void? static var observerForDidSaveNotification: Void? static var observerForDidImportUbiquitousContentChangesNotification: Void? } @nonobjc private var observerForDidSaveNotification: NotificationObserver? { get { return cs_getAssociatedObjectForKey( &PropertyKeys.observerForDidSaveNotification, inObject: self ) } set { cs_setAssociatedRetainedObject( newValue, forKey: &PropertyKeys.observerForDidSaveNotification, inObject: self ) } } @nonobjc private var observerForDidImportUbiquitousContentChangesNotification: NotificationObserver? { get { return cs_getAssociatedObjectForKey( &PropertyKeys.observerForDidImportUbiquitousContentChangesNotification, inObject: self ) } set { cs_setAssociatedRetainedObject( newValue, forKey: &PropertyKeys.observerForDidImportUbiquitousContentChangesNotification, inObject: self ) } } }
mit
9789cf9e60a0b6fe57e1dc2a55f25826
33.94086
127
0.587167
6.512024
false
false
false
false
panjinqiang11/Swift-WeiBo
WeiBo/WeiBo/Class/View/OAuth/CommonTool.swift
1
757
// // CommonTool.swift // WeiBo // // Created by 潘金强 on 16/7/12. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit // 切换根视图控制器通知名 let SwitchRootVCNotification = "SwitchRootVCNotification" let ScreenWidth = UIScreen.mainScreen().bounds.size.width let SreenHeight = UIScreen.mainScreen().bounds.size.height //随机生成颜色 func RGB(red: CGFloat,green: CGFloat, blue :CGFloat) -> UIColor{ return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } func RandomColor() -> UIColor{ let red = random() % 256 let green = random() % 256 let blue = random() % 256 return RGB(CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255) }
mit
1dc1c953af093dcd4c290c205aeb1b08
21.870968
90
0.661017
3.277778
false
false
false
false
brentdax/swift
test/decl/func/operator_suggestions.swift
16
1520
// RUN: %target-typecheck-verify-swift _ = 1..<1 // OK _ = 1…1 // expected-error {{use of unresolved operator '…'; did you mean '...'?}} {{6-9=...}} _ = 1….1 // expected-error {{use of unresolved operator '…'; did you mean '...'?}} {{6-9=...}} _ = 1.…1 // expected-error {{use of unresolved operator '.…'; did you mean '...'?}} {{6-10=...}} _ = 1…<1 // expected-error {{use of unresolved operator '…<'; did you mean '..<'?}} {{6-10=..<}} _ = 1..1 // expected-error {{use of unresolved operator '..'; did you mean '...'?}} {{6-8=...}} _ = 1....1 // expected-error {{use of unresolved operator '....'; did you mean '...'?}} {{6-10=...}} _ = 1...<1 // expected-error {{use of unresolved operator '...<'; did you mean '..<'?}} {{6-10=..<}} _ = 1....<1 // expected-error {{use of unresolved operator '....<'; did you mean '..<'?}} {{6-11=..<}} var i = 1 i++ // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} ++i // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} i-- // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}} --i // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}} var d = 1.0 d++ // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} ++d // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} d-- // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}} --d // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}}
apache-2.0
3cf94fec0760015d943fa7faa3331b4e
64.391304
102
0.553856
3.24838
false
false
false
false
ja-mes/experiments
iOS/RetroCalculator/RetroCalculator/ViewController.swift
1
3562
// // ViewController.swift // RetroCalculator // // Created by James Brown on 8/13/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var outputLbl: UILabel! var buttonSound: AVAudioPlayer! enum Operation: String { case Divide = "/" case Multiply = "*" case Subtract = "-" case Add = "+" case Empty = "Empty" } var currentOperation = Operation.Empty var runningNumber = "" var leftValStr = "" var rightValStr = "" var result = "" override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "btn", ofType: "wav") let soundURL = URL(fileURLWithPath: path!) do { try buttonSound = AVAudioPlayer(contentsOf: soundURL) buttonSound.prepareToPlay() } catch let err as NSError { print(err.debugDescription) } outputLbl.text = "0" } @IBAction func numberPressed(sender: UIButton) { playSound() runningNumber += "\(sender.tag)" outputLbl.text = runningNumber } @IBAction func onDividePress(sender: AnyObject) { processOperation(operation: .Divide) } @IBAction func onMultiplyPress(sender: AnyObject) { processOperation(operation: .Multiply) } @IBAction func onSubtractPress(sender: AnyObject) { processOperation(operation: .Subtract) } @IBAction func onAddPress(sender: AnyObject) { processOperation(operation: .Add) } @IBAction func onEqualPressed(sender: AnyObject) { processOperation(operation: currentOperation) } @IBAction func clearButtonPressed(_ sender: AnyObject) { playSound() currentOperation = Operation.Empty runningNumber = "" result = "" leftValStr = "" rightValStr = "" outputLbl.text = "0" } func playSound() { if buttonSound.isPlaying { buttonSound.stop() } buttonSound.play() } func processOperation(operation: Operation) { playSound() if currentOperation != Operation.Empty { // A user selected a operator, but then selected another operator without first entering a number if runningNumber != "" { rightValStr = runningNumber runningNumber = "" if currentOperation == Operation.Multiply { result = "\(Double(leftValStr)! * Double(rightValStr)!)" } else if currentOperation == Operation.Divide { result = "\(Double(leftValStr)! / Double(rightValStr)!)" } else if currentOperation == Operation.Subtract { result = "\(Double(leftValStr)! - Double(rightValStr)!)" } else if currentOperation == Operation.Add { result = "\(Double(leftValStr)! + Double(rightValStr)!)" } leftValStr = result outputLbl.text = result } currentOperation = operation } else { // This is the first time a operator has been pressed leftValStr = runningNumber runningNumber = "" currentOperation = operation } } }
mit
641f80ddb5acd338a1b493b551437a8a
26.820313
109
0.553215
5.101719
false
false
false
false
jverkoey/FigmaKit
Sources/FigmaKit/Strokes.swift
1
804
/// A Figma stroke cap. /// /// "Describes the end caps of vector paths." public enum StrokeCap: String, Codable { case none = "NONE" case round = "ROUND" case square = "SQUARE" case lineArrow = "LINE_ARROW" case triangleArrow = "TRIANGLE_ARROW" } /// A Figma stroke join. /// /// "Describes how corners in vector paths are rendered." public enum StrokeJoin: String, Codable { case miter = "MITER" case bevel = "BEVEL" case round = "ROUND" } /// A Figma stroke align. /// /// "Position of stroke relative to vector outline." public enum StrokeAlign: String, Codable { /// Stroke drawn inside the shape boundary. case inside = "INSIDE" /// Stroke drawn outside the shape boundary. case outside = "OUTSIDE" /// Stroke drawn along the shape boundary. case center = "CENTER" }
apache-2.0
6b89aceb1187b8412adf62b5dfb75422
24.125
57
0.679104
3.621622
false
false
false
false
digices-llc/paqure-ios-framework
Paqure/App.swift
1
4360
// // App.swift // Paqure // // Created by Linguri Technology on 7/19/16. // Copyright © 2016 Digices. All rights reserved. // import UIKit class App: NSObject, NSCoding { // object properties var id : Int var name: NSString var major : Int var minor : Int var fix : Int var copyright : Int var company: NSString var update : Int // initialize in default state override init() { self.id = 2 self.name = NSLocalizedString("app_name", comment: "Title representing the public name of the app") self.major = 0 self.minor = 0 self.fix = 1 self.copyright = 2016 self.company = "Digices, LLC" self.update = 0 } // initialize in default state required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeIntegerForKey("id") self.name = aDecoder.decodeObjectForKey("name") as! NSString self.major = aDecoder.decodeIntegerForKey("major") self.minor = aDecoder.decodeIntegerForKey("minor") self.fix = aDecoder.decodeIntegerForKey("fix") self.copyright = aDecoder.decodeIntegerForKey("copyright") self.company = aDecoder.decodeObjectForKey("company") as! NSString self.update = aDecoder.decodeIntegerForKey("update") } // initialize with a [String:String] dictionary init(dict: NSDictionary) { if let id = dict["id"] as? String { if let idInt = Int(id) { self.id = idInt } else { self.id = 0 } } else { self.id = 0 } if let name = dict["name"] as? String { self.name = name } else { self.name = "" } if let major = dict["major"] as? String { if let majorInt = Int(major) { self.major = majorInt } else { self.major = 0 } } else { self.major = 0 } if let minor = dict["minor"] as? String { if let minorInt = Int(minor) { self.minor = minorInt } else { self.minor = 0 } } else { self.minor = 0 } if let fix = dict["fix"] as? String { if let fixInt = Int(fix) { self.fix = fixInt } else { self.fix = 0 } } else { self.fix = 0 } if let copyright = dict["copyright"] as? String { if let copyrightInt = Int(copyright) { self.copyright = copyrightInt } else { self.copyright = 0 } } else { self.copyright = 0 } if let company = dict["company"] as? String { self.company = company } else { self.company = "" } if let update = dict["update"] as? String { if let updateInt = Int(update) { self.update = updateInt } else { self.update = 0 } } else { self.update = 0 } } // NSCoding compliance when saving objects func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(self.id, forKey: "id") aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeInteger(self.major, forKey: "major") aCoder.encodeInteger(self.minor, forKey: "minor") aCoder.encodeInteger(self.fix, forKey: "fix") aCoder.encodeInteger(self.copyright, forKey: "copyright") aCoder.encodeObject(self.company, forKey: "company") aCoder.encodeInteger(self.update, forKey: "update") } // a tap to enable appending an HTTP GET string to a URL func getSuffix() -> String { return "id=\(self.id)&name=\(self.name)&major=\(self.major)&minor=\(self.minor)&fix=\(self.fix)&copyright=\(self.copyright)&company=\(self.company)&update=\(self.update)" } // return NSURLSession compliant HTTP Body header for object func encodedPostBody() -> NSData { let body = self.getSuffix() return body.dataUsingEncoding(NSUTF8StringEncoding)! as NSData } }
bsd-3-clause
ee0ea5b11d860b402bdda58367f7a1a4
28.653061
178
0.52145
4.540625
false
false
false
false
finder39/Swimgur
Swimgur/Controllers/GalleryItemView/Cells/ImgurTextCell.swift
1
2078
// // ImgurTextCell.swift // Swimgur // // Created by Joseph Neuman on 11/2/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation import UIKit class ImgurTextCell: UITableViewCell { @IBOutlet var imgurText:UITextView! override func awakeFromNib() { super.awakeFromNib() setup() } func setup() { imgurText.textColor = UIColorEXT.TextColor() imgurText.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.RGBColor(red: 51, green: 102, blue: 187)] } override func prepareForReuse() { super.prepareForReuse() imgurText.text = nil // bug fix for text maintaining old links var newImgurTextView = UITextView() newImgurTextView.font = imgurText.font newImgurTextView.backgroundColor = imgurText.backgroundColor newImgurTextView.dataDetectorTypes = imgurText.dataDetectorTypes newImgurTextView.selectable = imgurText.selectable newImgurTextView.editable = imgurText.editable newImgurTextView.scrollEnabled = imgurText.scrollEnabled newImgurTextView.textColor = imgurText.textColor newImgurTextView.linkTextAttributes = imgurText.linkTextAttributes newImgurTextView.setTranslatesAutoresizingMaskIntoConstraints(false) imgurText.removeFromSuperview() self.addSubview(newImgurTextView) imgurText = newImgurTextView let top = NSLayoutConstraint(item: newImgurTextView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0) let bottom = NSLayoutConstraint(item: newImgurTextView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0) let leading = NSLayoutConstraint(item: newImgurTextView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0) let trailing = NSLayoutConstraint(item: newImgurTextView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 0) self.addConstraints([top, bottom, leading, trailing]) } }
mit
6fb80459c3a273f2b53c778321e361ee
39.764706
168
0.750722
4.959427
false
false
false
false
hooman/swift
test/Generics/concrete_same_type_versus_anyobject.swift
4
1614
// RUN: %target-typecheck-verify-swift // RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s struct S {} class C {} struct G1<T : AnyObject> {} // CHECK-LABEL: Generic signature: <T where T == S> extension G1 where T == S {} // expected-error@-1 {{'T' requires that 'S' be a class type}} // expected-note@-2 {{same-type constraint 'T' == 'S' implied here}} // CHECK-LABEL: Generic signature: <T where T == C> extension G1 where T == C {} struct G2<U> {} // CHECK-LABEL: Generic signature: <U where U == S> extension G2 where U == S, U : AnyObject {} // expected-error@-1 {{'U' requires that 'S' be a class type}} // expected-note@-2 {{same-type constraint 'U' == 'S' implied here}} // expected-note@-3 {{constraint 'U' : 'AnyObject' implied here}} // CHECK-LABEL: Generic signature: <U where U == C> extension G2 where U == C, U : AnyObject {} // expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}} // expected-note@-2 {{constraint 'U' : 'AnyObject' implied here}} // CHECK-LABEL: Generic signature: <U where U : C> extension G2 where U : C, U : AnyObject {} // expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}} // expected-note@-2 {{constraint 'U' : 'AnyObject' implied here}} // Explicit AnyObject conformance vs derived same-type protocol P { associatedtype A where A == C } // CHECK-LABEL: Generic signature: <T where T : P> func explicitAnyObjectIsRedundant<T : P>(_: T) where T.A : AnyObject {} // expected-warning@-1 {{redundant constraint 'T.A' : 'AnyObject'}} // expected-note@-2 {{constraint 'T.A' : 'AnyObject' implied here}}
apache-2.0
9b94dad9cbd919a08714b6b50bd786a2
37.428571
95
0.662949
3.314168
false
false
false
false
col/iReSign
iReSignKit/Logger.swift
1
1072
// // Logger.swift // iReSign // // Created by Colin Harris on 15/10/15. // Copyright © 2015 Colin Harris. All rights reserved. // import Foundation public enum LogLevel: Int { case Debug = 1 case Info = 2 case Warn = 3 case Error = 4 } public class Logger { static let sharedInstance = Logger() var logLevel: LogLevel = .Info public class func setLogLevel(level: LogLevel) { sharedInstance.logLevel = level } public class func debug(message: String) { sharedInstance.log(.Debug, message: message) } public class func info(message: String) { sharedInstance.log(.Info, message: message) } public class func warn(message: String) { sharedInstance.log(.Warn, message: message) } public class func error(message: String) { sharedInstance.log(.Error, message: message) } public func log(level: LogLevel, message: String) { if level.rawValue >= logLevel.rawValue { print(message) } } }
mit
d36f620e82a67427879ee87bfa34aa33
20.44
55
0.607843
4.233202
false
false
false
false
timd/ProiOSTableCollectionViews
Ch08/MVVM/MVVM/ViewController.swift
1
1748
// // ViewController.swift // MVVM // // Created by Tim on 28/10/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var tableView: UITableView! var tableData: [Contact] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController { func setupData() { for index in 1...10 { let contact = Contact(name: "Name \(index)", number: "\(index)", notes: "The notes for contact \(index)") tableData.append(contact) } } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell let contact = tableData[indexPath.row] cell.contact = contact return cell } }
mit
834ea2b0a60393b0df1a0b8ec547e109
22.608108
118
0.613051
5.493711
false
false
false
false
joshoconnor89/BoardView_DragNDrop
KDDragAndDropCollectionViews/ViewController.swift
1
4944
// // ViewController.swift // KDDragAndDropCollectionViews // // Created by Michael Michailidis on 10/04/2015. // Copyright (c) 2015 Karmadust. All rights reserved. // import UIKit class DataItem : Equatable { var indexes : String = "" var colour : UIColor = UIColor.clear init(indexes : String, colour : UIColor) { self.indexes = indexes self.colour = colour } } func ==(lhs: DataItem, rhs: DataItem) -> Bool { return lhs.indexes == rhs.indexes && lhs.colour == rhs.colour } class ViewController: UIViewController, KDDragAndDropCollectionViewDataSource { @IBOutlet weak var firstCollectionView: UICollectionView! @IBOutlet weak var secondCollectionView: UICollectionView! @IBOutlet weak var thirdCollectionView: UICollectionView! var data : [[DataItem]] = [[DataItem]]() var dragAndDropManager : KDDragAndDropManager? override func viewDidLoad() { super.viewDidLoad() let colours : [UIColor] = [ UIColor(red: 53.0/255.0, green: 102.0/255.0, blue: 149.0/255.0, alpha: 1.0), UIColor(red: 177.0/255.0, green: 88.0/255.0, blue: 39.0/255.0, alpha: 1.0), UIColor(red: 138.0/255.0, green: 149.0/255.0, blue: 86.0/255.0, alpha: 1.0) ] for i in 0...2 { var items = [DataItem]() for j in 0...20 { let dataItem = DataItem(indexes: String(i) + ":" + String(j), colour: colours[i]) items.append(dataItem) } data.append(items) } self.dragAndDropManager = KDDragAndDropManager(canvas: self.view, collectionViews: [firstCollectionView, secondCollectionView, thirdCollectionView]) } // MARK : UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data[collectionView.tag].count } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ColorCell let dataItem = data[collectionView.tag][indexPath.item] cell.label.text = String(indexPath.item) + "\n\n" + dataItem.indexes cell.backgroundColor = dataItem.colour cell.isHidden = false if let kdCollectionView = collectionView as? KDDragAndDropCollectionView { if let draggingPathOfCellBeingDragged = kdCollectionView.draggingPathOfCellBeingDragged { if draggingPathOfCellBeingDragged.item == indexPath.item { cell.isHidden = true } } } return cell } // MARK : KDDragAndDropCollectionViewDataSource func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject { return data[collectionView.tag][indexPath.item] } func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void { if let di = dataItem as? DataItem { data[collectionView.tag].insert(di, at: indexPath.item) } } func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath : IndexPath) -> Void { data[collectionView.tag].remove(at: indexPath.item) } func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void { let fromDataItem: DataItem = data[collectionView.tag][from.item] data[collectionView.tag].remove(at: from.item) data[collectionView.tag].insert(fromDataItem, at: to.item) } func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? { if let candidate : DataItem = dataItem as? DataItem { for item : DataItem in data[collectionView.tag] { if candidate == item { let position = data[collectionView.tag].index(of: item)! // ! if we are inside the condition we are guaranteed a position let indexPath = IndexPath(item: position, section: 0) return indexPath } } } return nil } }
mit
04fb6b1b4cb905847692cdcbf23c424d
32.405405
156
0.597694
5.209694
false
false
false
false
moriturus/Concurrent
Concurrent/Channel.swift
1
2104
// // Channel.swift // Concurrent // // Created by moriturus on 8/12/14. // Copyright (c) 2014-2015 moriturus. All rights reserved. // public protocol ChannelType : Sendable, Receivable { typealias S : Sendable typealias R : Receivable var sender : S { get } var receiver : R { get } } public class ProtoChannel<T, D : Data, S : Sendable, R : Receivable where D.T == T, S.T == T, S.D == D, R.T == T, R.D == D> : ChannelType { /// sender object public private(set) var sender : S /// receiver object public private(set) var receiver : R public init(_ sender : S, _ receiver : R) { self.sender = sender self.receiver = receiver } public convenience required init(_ storage: D) { let s = S(storage) let r = R(storage) self.init(s,r) } public func send(value: T) { sender.send(value) } public func receive() -> T { return receiver.receive() } } public class DataTypeReplaceableChannel<T, D: Data where D.T == T> : ProtoChannel<T, D, Sender<D>, Receiver<D>> { public typealias S = Sender<D> public typealias R = Receiver<D> public required init(_ storage: D) { let s = S(storage) let r = R(s) super.init(s, r) } } /** Channel class */ public class Channel<T> : DataTypeReplaceableChannel<T, SafeQueue<T>> { public typealias D = SafeQueue<T> public required init(_ storage: D) { super.init(storage) } public convenience init() { let d = D() self.init(d) } } public class StackChannel<T> : DataTypeReplaceableChannel<T, SafeStack<T>> { public typealias D = SafeStack<T> public required init(_ storage: D) { super.init(storage) } public convenience init() { let d = D() self.init(d) } }
mit
b6e84955ec72e4b4c60e49cb5540aa54
17.954955
139
0.51616
3.969811
false
false
false
false
gregomni/swift
test/SILGen/check_executor.swift
9
3186
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -disable-availability-checking -enable-actor-data-race-checks | %FileCheck --enable-var-scope %s --check-prefix=CHECK-RAW // RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -disable-availability-checking -enable-actor-data-race-checks > %t.sil // RUN: %target-sil-opt -enable-sil-verify-all %t.sil -lower-hop-to-actor | %FileCheck --enable-var-scope %s --check-prefix=CHECK-CANONICAL // REQUIRES: concurrency import Swift import _Concurrency // CHECK-RAW-LABEL: sil [ossa] @$s4test11onMainActoryyF // CHECK-RAW: extract_executor [[MAIN_ACTOR:%.*]] : $MainActor // CHECK-CANONICAL-LABEL: sil [ossa] @$s4test11onMainActoryyF // CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF @MainActor public func onMainActor() { } // CHECK-CANONICAL-LABEL: sil [ossa] @$s4test17onMainActorUnsafeyyF // CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF @preconcurrency @MainActor public func onMainActorUnsafe() { } func takeClosure(_ fn: @escaping () -> Int) { } @preconcurrency func takeUnsafeMainActorClosure(_ fn: @MainActor @escaping () -> Int) { } public actor MyActor { var counter = 0 // CHECK-RAW-LABEL: sil private [ossa] @$s4test7MyActorC10getUpdaterSiycyFSiycfU_ // CHECK-RAW: extract_executor [[ACTOR:%.*]] : $MyActor // CHECK-CANONICAL-LABEL: sil private [ossa] @$s4test7MyActorC10getUpdaterSiycyFSiycfU_ // CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF public func getUpdater() -> (() -> Int) { return { self.counter = self.counter + 1 return self.counter } } // CHECK-RAW-LABEL: sil private [ossa] @$s4test7MyActorC0A10UnsafeMainyyFSiyScMYccfU_ // CHECK-RAW: _checkExpectedExecutor // CHECK-RAW: onMainActor // CHECK-RAW: return public func testUnsafeMain() { takeUnsafeMainActorClosure { onMainActor() return 5 } } // CHECK-CANONICAL-LABEL: sil private [ossa] @$s4test7MyActorC0A13LocalFunctionyyF5localL_SiyF : $@convention(thin) (@guaranteed MyActor) -> Int // CHECK-CANONICAL: [[CAPTURE:%.*]] = copy_value %0 : $MyActor // CHECK-CANONICAL-NEXT: [[BORROWED_CAPTURE:%.*]] = begin_borrow [[CAPTURE]] : $MyActor // CHECK-CANONICAL-NEXT: [[EXECUTOR:%.*]] = builtin "buildDefaultActorExecutorRef"<MyActor>([[BORROWED_CAPTURE]] : $MyActor) : $Builtin.Executor // CHECK-CANONICAL-NEXT: [[EXECUTOR_DEP:%.*]] = mark_dependence [[EXECUTOR]] : $Builtin.Executor on [[BORROWED_CAPTURE]] : $MyActor // CHECK-CANONICAL: [[CHECK_FN:%.*]] = function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Executor) -> () // CHECK-CANONICAL-NEXT: apply [[CHECK_FN]]({{.*}}, [[EXECUTOR_DEP]]) public func testLocalFunction() { func local() -> Int { return counter } print(local()) } }
apache-2.0
3fde2b2b77e1bd5efc47191da8cc779a
48.78125
261
0.721281
3.444324
false
true
false
false
robertofrontado/RxSocialConnect-iOS
Sources/Core/Apis/TwitterApi.swift
1
798
// // TwitterApi.swift // RxSocialConnect // // Created by Roberto Frontado on 5/19/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import OAuthSwift open class TwitterApi: ProviderOAuth1 { open var consumerKey: String open var consumerSecret: String open var callbackUrl: URL open var requestTokenUrl: String = "https://api.twitter.com/oauth/request_token" open var authorizeUrl: String = "https://api.twitter.com/oauth/authorize" open var accessTokenUrl: String = "https://api.twitter.com/oauth/access_token" required public init(consumerKey: String, consumerSecret: String, callbackUrl: URL) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.callbackUrl = callbackUrl } }
apache-2.0
2450eeb75daff9e79cf6d82c1eecdaa1
27.464286
89
0.70389
4.308108
false
false
false
false
parkera/swift-corelibs-foundation
Foundation/URLSession/NativeProtocol.swift
1
26009
// Foundation/URLSession/NativeProtocol.swift - NSURLSession & libcurl // // 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 the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// This file has the common implementation of Native protocols like HTTP,FTP,Data /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: NSURLSession.swift /// // ----------------------------------------------------------------------------- import CoreFoundation import Dispatch internal let enableLibcurlDebugOutput: Bool = { return ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil }() internal let enableDebugOutput: Bool = { return ProcessInfo.processInfo.environment["URLSessionDebug"] != nil }() internal class _NativeProtocol: URLProtocol, _EasyHandleDelegate { internal var easyHandle: _EasyHandle! internal lazy var tempFileURL: URL = { let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp" _ = FileManager.default.createFile(atPath: fileName, contents: nil) return URL(fileURLWithPath: fileName) }() public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { self.internalState = .initial super.init(request: task.originalRequest!, cachedResponse: cachedResponse, client: client) self.task = task self.easyHandle = _EasyHandle(delegate: self) } public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { self.internalState = .initial super.init(request: request, cachedResponse: cachedResponse, client: client) self.easyHandle = _EasyHandle(delegate: self) } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override func startLoading() { resume() } override func stopLoading() { if task?.state == .suspended { suspend() } else { self.internalState = .transferFailed guard let error = self.task?.error else { fatalError() } completeTask(withError: error) } } var internalState: _InternalState { // We manage adding / removing the easy handle and pausing / unpausing // here at a centralized place to make sure the internal state always // matches up with the state of the easy handle being added and paused. willSet { if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused { fatalError("Need to solve pausing receive.") } if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle { task?.session.remove(handle: easyHandle) } } didSet { if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle { task?.session.add(handle: easyHandle) } if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused { fatalError("Need to solve pausing receive.") } } } func didReceive(data: Data) -> _EasyHandle._Action { guard case .transferInProgress(var ts) = internalState else { fatalError("Received body data, but no transfer in progress.") } if let response = validateHeaderComplete(transferState:ts) { ts.response = response } notifyDelegate(aboutReceivedData: data) internalState = .transferInProgress(ts.byAppending(bodyData: data)) return .proceed } func validateHeaderComplete(transferState: _TransferState) -> URLResponse? { guard transferState.isHeaderComplete else { fatalError("Received body data, but the header is not complete, yet.") } return nil } fileprivate func notifyDelegate(aboutReceivedData data: Data) { guard let t = self.task else { fatalError("Cannot notify") } if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!), let dataDelegate = delegate as? URLSessionDataDelegate, let task = self.task as? URLSessionDataTask { // Forward to the delegate: guard let s = self.task?.session as? URLSession else { fatalError() } s.delegateQueue.addOperation { dataDelegate.urlSession(s, dataTask: task, didReceive: data) } } else if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!), let downloadDelegate = delegate as? URLSessionDownloadDelegate, let task = self.task as? URLSessionDownloadTask { guard let s = self.task?.session as? URLSession else { fatalError() } let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL) _ = fileHandle.seekToEndOfFile() fileHandle.write(data) task.countOfBytesReceived += Int64(data.count) s.delegateQueue.addOperation { downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: task.countOfBytesReceived, totalBytesExpectedToWrite: task.countOfBytesExpectedToReceive) } } } fileprivate func notifyDelegate(aboutUploadedData count: Int64) { guard let task = self.task as? URLSessionUploadTask, let session = self.task?.session as? URLSession, case .taskDelegate(let delegate) = session.behaviour(for: task) else { return } task.countOfBytesSent += count session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didSendBodyData: count, totalBytesSent: task.countOfBytesSent, totalBytesExpectedToSend: task.countOfBytesExpectedToSend) } } func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action { NSRequiresConcreteImplementation() } func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult { guard case .transferInProgress(let ts) = internalState else { fatalError("Requested to fill write buffer, but transfer isn't in progress.") } guard let source = ts.requestBodySource else { fatalError("Requested to fill write buffer, but transfer state has no body source.") } switch source.getNextChunk(withLength: buffer.count) { case .data(let data): copyDispatchData(data, infoBuffer: buffer) let count = data.count assert(count > 0) notifyDelegate(aboutUploadedData: Int64(count)) return .bytes(count) case .done: return .bytes(0) case .retryLater: // At this point we'll try to pause the easy handle. The body source // is responsible for un-pausing the handle once data becomes // available. return .pause case .error: return .abort } } func transferCompleted(withError error: NSError?) { // At this point the transfer is complete and we can decide what to do. // If everything went well, we will simply forward the resulting data // to the delegate. But in case of redirects etc. we might send another // request. guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer completed, but it wasn't in progress.") } guard let request = task?.currentRequest else { fatalError("Transfer completed, but there's no current request.") } guard error == nil else { internalState = .transferFailed failWith(error: error!, request: request) return } if let response = task?.response { var transferState = ts transferState.response = response } guard let response = ts.response else { fatalError("Transfer completed, but there's no response.") } internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain) let action = completionAction(forCompletedRequest: request, response: response) switch action { case .completeTask: completeTask() case .failWithError(let errorCode): internalState = .transferFailed let error = NSError(domain: NSURLErrorDomain, code: errorCode, userInfo: [NSLocalizedDescriptionKey: "Completion failure"]) failWith(error: error, request: request) case .redirectWithRequest(let newRequest): redirectFor(request: newRequest) } } func redirectFor(request: URLRequest) { NSRequiresConcreteImplementation() } func completeTask() { guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else { fatalError("Trying to complete the task, but its transfer isn't complete.") } task?.response = response // We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled. easyHandle.timeoutTimer = nil // because we deregister the task with the session on internalState being set to taskCompleted // we need to do the latter after the delegate/handler was notified/invoked if case .inMemory(let bodyData) = bodyDataDrain { var data = Data() if let body = bodyData { data = Data(bytes: body.bytes, count: body.length) } self.client?.urlProtocol(self, didLoad: data) self.internalState = .taskCompleted } else if case .toFile(let url, let fileHandle?) = bodyDataDrain { self.properties[.temporaryFileURL] = url fileHandle.closeFile() } else if task is URLSessionDownloadTask { let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL) fileHandle.closeFile() self.properties[.temporaryFileURL] = self.tempFileURL } self.client?.urlProtocolDidFinishLoading(self) self.internalState = .taskCompleted } func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction { return .completeTask } func seekInputStream(to position: UInt64) throws { // We will reset the body source and seek forward. guard let session = task?.session as? URLSession else { fatalError() } var currentInputStream: InputStream? if let delegate = session.delegate as? URLSessionTaskDelegate { let dispatchGroup = DispatchGroup() dispatchGroup.enter() delegate.urlSession(session, task: task!, needNewBodyStream: { inputStream in currentInputStream = inputStream dispatchGroup.leave() }) _ = dispatchGroup.wait(timeout: .now() + 7) } if let url = self.request.url, let inputStream = currentInputStream { switch self.internalState { case .transferInProgress(let currentTransferState): switch currentTransferState.requestBodySource { case is _BodyStreamSource: try inputStream.seek(to: position) let drain = self.createTransferBodyDataDrain() let source = _BodyStreamSource(inputStream: inputStream) let transferState = _TransferState(url: url, bodyDataDrain: drain, bodySource: source) self.internalState = .transferInProgress(transferState) default: NSUnimplemented() } default: //TODO: it's possible? break } } } func updateProgressMeter(with propgress: _EasyHandle._Progress) { //TODO: Update progress. Note that a single URLSessionTask might // perform multiple transfers. The values in `progress` are only for // the current transfer. } /// The data drain. /// /// This depends on what the delegate / completion handler need. fileprivate func createTransferBodyDataDrain() -> _DataDrain { guard let task = task else { fatalError() } let s = task.session as! URLSession switch s.behaviour(for: task) { case .noDelegate: return .ignore case .taskDelegate: // Data will be forwarded to the delegate as we receive it, we don't // need to do anything about it. return .ignore case .dataCompletionHandler: // Data needs to be concatenated in-memory such that we can pass it // to the completion handler upon completion. return .inMemory(nil) case .downloadCompletionHandler: // Data needs to be written to a file (i.e. a download task). let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL) return .toFile(self.tempFileURL, fileHandle) } } func createTransferState(url: URL, workQueue: DispatchQueue) -> _TransferState { let drain = createTransferBodyDataDrain() guard let t = task else { fatalError("Cannot create transfer state") } switch t.body { case .none: return _TransferState(url: url, bodyDataDrain: drain) case .data(let data): let source = _BodyDataSource(data: data) return _TransferState(url: url, bodyDataDrain: drain,bodySource: source) case .file(let fileURL): let source = _BodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in // Unpause the easy handle self?.easyHandle.unpauseSend() }) return _TransferState(url: url, bodyDataDrain: drain,bodySource: source) case .stream(let inputStream): let source = _BodyStreamSource(inputStream: inputStream) return _TransferState(url: url, bodyDataDrain: drain, bodySource: source) } } /// Start a new transfer func startNewTransfer(with request: URLRequest) { guard let t = task else { fatalError() } t.currentRequest = request guard let url = request.url else { fatalError("No URL in request.") } self.internalState = .transferReady(createTransferState(url: url, workQueue: t.workQueue)) if let authRequest = task?.authRequest { configureEasyHandle(for: authRequest) } else { configureEasyHandle(for: request) } if (t.suspendCount) < 1 { resume() } } func resume() { if case .initial = self.internalState { guard let r = task?.originalRequest else { fatalError("Task has no original request.") } startNewTransfer(with: r) } if case .transferReady(let transferState) = self.internalState { self.internalState = .transferInProgress(transferState) } } func suspend() { if case .transferInProgress(let transferState) = self.internalState { self.internalState = .transferReady(transferState) } } func configureEasyHandle(for: URLRequest) { NSRequiresConcreteImplementation() } } extension _NativeProtocol { /// Action to be taken after a transfer completes enum _CompletionAction { case completeTask case failWithError(Int) case redirectWithRequest(URLRequest) } func completeTask(withError error: Error) { task?.error = error guard case .transferFailed = self.internalState else { fatalError("Trying to complete the task, but its transfer isn't complete / failed.") } //We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled. easyHandle.timeoutTimer = nil self.internalState = .taskCompleted } func failWith(error: NSError, request: URLRequest) { //TODO: Error handling let userInfo: [String : Any]? = request.url.map { [ NSUnderlyingErrorKey: error, NSURLErrorFailingURLErrorKey: $0, NSURLErrorFailingURLStringErrorKey: $0.absoluteString, NSLocalizedDescriptionKey: NSLocalizedString(error.localizedDescription, comment: "N/A") ] } let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: error.code, userInfo: userInfo)) completeTask(withError: urlError) self.client?.urlProtocol(self, didFailWithError: urlError) } /// Give the delegate a chance to tell us how to proceed once we have a /// response / complete header. /// /// This will pause the transfer. func askDelegateHowToProceedAfterCompleteResponse(_ response: URLResponse, delegate: URLSessionDataDelegate) { // Ask the delegate how to proceed. // This will pause the easy handle. We need to wait for the // delegate before processing any more data. guard case .transferInProgress(let ts) = self.internalState else { fatalError("Transfer not in progress.") } self.internalState = .waitingForResponseCompletionHandler(ts) let dt = task as! URLSessionDataTask // We need this ugly cast in order to be able to support `URLSessionTask.init()` guard let s = task?.session as? URLSession else { fatalError() } s.delegateQueue.addOperation { delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in guard let task = self else { return } self?.task?.workQueue.async { task.didCompleteResponseCallback(disposition: disposition) } }) } } /// This gets called (indirectly) when the data task delegates lets us know /// how we should proceed after receiving a response (i.e. complete header). func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) { guard case .waitingForResponseCompletionHandler(let ts) = self.internalState else { fatalError("Received response disposition, but we're not waiting for it.") } switch disposition { case .cancel: let error = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled)) self.completeTask(withError: error) self.client?.urlProtocol(self, didFailWithError: error) case .allow: // Continue the transfer. This will unpause the easy handle. self.internalState = .transferInProgress(ts) case .becomeDownload: /* Turn this request into a download */ NSUnimplemented() case .becomeStream: /* Turn this task into a stream task */ NSUnimplemented() } } } extension _NativeProtocol { enum _InternalState { /// Task has been created, but nothing has been done, yet case initial /// The easy handle has been fully configured. But it is not added to /// the multi handle. case transferReady(_TransferState) /// The easy handle is currently added to the multi handle case transferInProgress(_TransferState) /// The transfer completed. /// /// The easy handle has been removed from the multi handle. This does /// not necessarily mean the task completed. A task that gets /// redirected will do multiple transfers. case transferCompleted(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain) /// The transfer failed. /// /// Same as `.transferCompleted`, but without response / body data case transferFailed /// Waiting for the completion handler of the HTTP redirect callback. /// /// When we tell the delegate that we're about to perform an HTTP /// redirect, we need to wait for the delegate to let us know what /// action to take. case waitingForRedirectCompletionHandler(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain) /// Waiting for the completion handler of the 'did receive response' callback. /// /// When we tell the delegate that we received a response (i.e. when /// we received a complete header), we need to wait for the delegate to /// let us know what action to take. In this state the easy handle is /// paused in order to suspend delegate callbacks. case waitingForResponseCompletionHandler(_TransferState) /// The task is completed /// /// Contrast this with `.transferCompleted`. case taskCompleted } } extension _NativeProtocol._InternalState { var isEasyHandleAddedToMultiHandle: Bool { switch self { case .initial: return false case .transferReady: return false case .transferInProgress: return true case .transferCompleted: return false case .transferFailed: return false case .waitingForRedirectCompletionHandler: return false case .waitingForResponseCompletionHandler: return true case .taskCompleted: return false } } var isEasyHandlePaused: Bool { switch self { case .initial: return false case .transferReady: return false case .transferInProgress: return false case .transferCompleted: return false case .transferFailed: return false case .waitingForRedirectCompletionHandler: return false case .waitingForResponseCompletionHandler: return true case .taskCompleted: return false } } } extension _NativeProtocol { enum _Error: Error { case parseSingleLineError case parseCompleteHeaderError } func errorCode(fileSystemError error: Error) -> Int { func fromCocoaErrorCode(_ code: Int) -> Int { switch code { case CocoaError.fileReadNoSuchFile.rawValue: return NSURLErrorFileDoesNotExist case CocoaError.fileReadNoPermission.rawValue: return NSURLErrorNoPermissionsToReadFile default: return NSURLErrorUnknown } } switch error { case let e as NSError where e.domain == NSCocoaErrorDomain: return fromCocoaErrorCode(e.code) default: return NSURLErrorUnknown } } } extension _NativeProtocol._ResponseHeaderLines { func createURLResponse(for URL: URL, contentLength: Int64) -> URLResponse? { return URLResponse(url: URL, mimeType: nil, expectedContentLength: Int(contentLength), textEncodingName: nil) } } internal extension _NativeProtocol { enum _Body { case none case data(DispatchData) /// Body data is read from the given file URL case file(URL) case stream(InputStream) } } fileprivate extension _NativeProtocol._Body { enum _Error : Error { case fileForBodyDataNotFound } /// - Returns: The body length, or `nil` for no body (e.g. `GET` request). func getBodyLength() throws -> UInt64? { switch self { case .none: return 0 case .data(let d): return UInt64(d.count) /// Body data is read from the given file URL case .file(let fileURL): guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else { throw _Error.fileForBodyDataNotFound } return s.uint64Value case .stream: return nil } } } extension _NativeProtocol { /// Set request body length. /// /// An unknown length func set(requestBodyLength length: _HTTPURLProtocol._RequestBodyLength) { switch length { case .noBody: easyHandle.set(upload: false) easyHandle.set(requestBodyLength: 0) case .length(let length): easyHandle.set(upload: true) easyHandle.set(requestBodyLength: Int64(length)) case .unknown: easyHandle.set(upload: true) easyHandle.set(requestBodyLength: -1) } } enum _RequestBodyLength { case noBody /// case length(UInt64) /// Will result in a chunked upload case unknown } } extension URLSession { static func printDebug(_ text: @autoclosure () -> String) { guard enableDebugOutput else { return } debugPrint(text()) } }
apache-2.0
bd2f84957a241d7c2294429bb1b97fd5
38.952381
145
0.615633
5.394939
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/Cells/AAHeaderCell.swift
4
1284
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAHeaderCell: AATableViewCell { open var titleView = UILabel() open var iconView = UIImageView() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = appStyle.vcBackyardColor selectionStyle = UITableViewCellSelectionStyle.none titleView.textColor = appStyle.cellHeaderColor titleView.font = UIFont.systemFont(ofSize: 14) contentView.addSubview(titleView) iconView.contentMode = UIViewContentMode.scaleAspectFill contentView.addSubview(iconView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() let height = self.contentView.bounds.height let width = self.contentView.bounds.width titleView.frame = CGRect(x: 15, y: height - 28, width: width - 48, height: 24) iconView.frame = CGRect(x: width - 18 - 15, y: height - 18 - 4, width: 18, height: 18) } }
agpl-3.0
a0af6fc7a4e7a0c1eedadcb41ced04d2
31.923077
94
0.653427
4.863636
false
false
false
false
cgossain/AppController
AppController/Classes/AppController.swift
1
12569
// // AppController.swift // // Copyright (c) 2021 Christian Gossain // // 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 public class AppController { public struct Configuration { /// The animation duration when transitionning between logged in/out states. A duration of zero /// indicates no animation should occur. public var transitionDuration: TimeInterval = 0.6 /// The animation delay when transitioning between logged in/out states. The default value of 0.0 generally /// works well, however they may be times when an additional delay is required. This is provided /// as an additional transition configuration point. public var transitionDelay: TimeInterval = 0.0 /// Indicates if the any presented view controllers should first be dismissed before performing /// the interface transition. The default value of `true` should work well for most cases. This /// is provided as an additional transition configuration point. public var dismissesPresentedViewControllerOnTransition = true /// Initializes the configuration with the given options. public init(transitionDuration: TimeInterval = 0.6, dismissesPresentedViewControllerOnTransition: Bool = true) { self.transitionDuration = transitionDuration self.dismissesPresentedViewControllerOnTransition = dismissesPresentedViewControllerOnTransition } } /// The object that acts as the interface provider for the controller. public let interfaceProvider: AppControllerInterfaceProviding /// A closure that is called just before the transition to the _logged in_ interface begins. The view /// controller that is about to be presented is passed to the block as the targetViewController. /// /// - Note: This handler is called just before the transition begins, this means that if configured accordingly /// a presented view controller would first be dismissed before this handler is called. public var willLoginHandler: ((_ targetViewController: UIViewController) -> Void)? /// A closure that is called after the transition to the _logged in_ interface completes. public var didLoginHandler: (() -> Void)? /// A closure that is called just before the transition to the _logged out_ interface begins. The view /// controller that is about to be presented is passed to the block as the targetViewController. /// /// - Note: This handler is called just before the transition begins, this means that if configured accordingly /// a presented view controller would first be dismissed before this handler is called. public var willLogoutHandler: ((_ targetViewController: UIViewController) -> Void)? /// A closure that is called after the transition to the _logged out_ interface completes. public var didLogoutHandler: (() -> Void)? /// The view controller that should be installed as your window's rootViewController. public lazy var rootViewController: AppViewController = { if let storyboard = self.storyboard { // get the rootViewController from the storyboard return storyboard.instantiateInitialViewController() as! AppViewController } // if there is no storyboard, just create an instance of the app view controller (using the custom class if provided) return self.appViewControllerClass.init() }() /// Returns the storyboard instance being used if the controller was initialized using the convenience storyboad initializer, otherwise retuns `nil`. public var storyboard: UIStoryboard? { return (interfaceProvider as? StoryboardInterfaceProvider)?.storyboard } // MARK: - Lifecycle /// Initializes the controller using the specified storyboard name, and uses the given `loggedOutInterfaceID`, and `loggedInInterfaceID` values to instantiate /// the appropriate view controller from the storyboad. /// /// - Parameters: /// - storyboardName: The name of the storyboard that contains the view controllers. /// - loggedOutInterfaceID: The storyboard identifier of the view controller to use as the _logged out_ view controller. /// - loggedInInterfaceID: The storyboard identifier of the view controller to use as the _logged in_ view controller. /// - Note: The controller automatically installs the _initial view controller_ from the storyboard as the root view /// controller. Therfore, the _initial view controller_ in the specified storyboard MUST be an instance /// of `AppViewController`, otherwise a crash will occur. public convenience init(storyboardName: String, loggedOutInterfaceID: String, loggedInInterfaceID: String, configuration: AppController.Configuration = Configuration()) { let storyboard = UIStoryboard(name: storyboardName, bundle: nil) let provider = StoryboardInterfaceProvider(storyboard: storyboard, loggedOutInterfaceID: loggedOutInterfaceID, loggedInInterfaceID: loggedInInterfaceID, configuration: configuration) self.init(interfaceProvider: provider) } /// Initializes the controller with closures that return the view controllers to install for the _logged out_ and _logged in_ states. /// /// - Parameters: /// - interfaceProvider: The object that will act as the interface provider for the controller. /// - appViewControllerClass: Specify a custom `AppViewController` subclass to use as the rootViewController, or `nil` to use the standard `AppViewController`. public init(interfaceProvider: AppControllerInterfaceProviding, appViewControllerClass: AppViewController.Type? = nil) { self.interfaceProvider = interfaceProvider // replace the default AppViewController class with the custom class, if provided if let customAppViewControllerClass = appViewControllerClass { self.appViewControllerClass = customAppViewControllerClass } // observe login notifications loginNotificationObserver = NotificationCenter.default.addObserver( forName: AppController.shouldLoginNotification, object: nil, queue: .main, using: { [weak self] notification in guard let strongSelf = self else { return } strongSelf.transitionToLoggedInInterface() }) // observe logout notifications logoutNotificationObserver = NotificationCenter.default.addObserver( forName: AppController.shouldLogoutNotification, object: nil, queue: .main, using: { [weak self] notification in guard let strongSelf = self else { return } strongSelf.transitionToLoggedOutInterface() }) } deinit { NotificationCenter.default.removeObserver(loginNotificationObserver!) NotificationCenter.default.removeObserver(logoutNotificationObserver!) } // MARK: - Internal private var appViewControllerClass = AppViewController.self private var loginNotificationObserver: AnyObject? private var logoutNotificationObserver: AnyObject? } extension AppController { /// Internal notification that is posted on `AppController.login()`. private static let shouldLoginNotification = Notification.Name(rawValue: "AppControllerShouldLoginNotification") /// Internal notification that is posted on `AppController.logout()`. private static let shouldLogoutNotification = Notification.Name(rawValue: "AppControllerShouldLogoutNotification") /// Installs the receivers' instance of `AppViewController` as the windows' `rootViewController`, then calls `makeKeyAndVisible()` on /// the window, and finally transtitions to the initial interface. public func installRootViewController(in window: UIWindow) { // setting the root view controller before transitioning allows the target interface to have access to a fully defined trait collection if needed window.rootViewController = rootViewController window.makeKeyAndVisible() // transtion to the initial interface; since handlers should already be aware of their desired initial interface, they shouldn't be notified here if interfaceProvider.isInitiallyLoggedIn(for: self) { transitionToLoggedInInterface(notify: false) } else { transitionToLoggedOutInterface(notify: false) } } /// Posts a notification that notifies any active AppController instance to switch to its _logged in_ interface. /// Note that any given app should only have a single active AppController instance. Therefore that single instance /// will be the one that receives and handles the notification. public static func login() { NotificationCenter.default.post(name: AppController.shouldLoginNotification, object: nil, userInfo: nil) } /// Posts a notification that notifies any active AppController instance to switch to its _logged out_ interface. /// Note that any given app should only have a single active AppController instance. Therefore that single instance /// will be the one that receives and handles the notification. public static func logout() { NotificationCenter.default.post(name: AppController.shouldLogoutNotification, object: nil, userInfo: nil) } } extension AppController { private func transitionToLoggedInInterface(notify: Bool = true) { let target = interfaceProvider.loggedInInterfaceViewController(for: self) let configuration = interfaceProvider.configuration(for: self, traitCollection: rootViewController.traitCollection) rootViewController.transition(to: target, configuration: configuration, willBeginTransition: { [weak self] in guard let strongSelf = self else { return } if notify { strongSelf.willLoginHandler?(target) } }, completionHandler: { [weak self] in guard let strongSelf = self else { return } if notify { strongSelf.didLoginHandler?() } }) } private func transitionToLoggedOutInterface(notify: Bool = true) { let target = interfaceProvider.loggedOutInterfaceViewController(for: self) let configuration = interfaceProvider.configuration(for: self, traitCollection: rootViewController.traitCollection) rootViewController.transition(to: target, configuration: configuration, willBeginTransition: { [weak self] in guard let strongSelf = self else { return } if notify { strongSelf.willLogoutHandler?(target) } }, completionHandler: { [weak self] in guard let strongSelf = self else { return } if notify { strongSelf.didLogoutHandler?() } }) } }
mit
6fc618d43a91fc307bd324beeaaa0b27
50.093496
190
0.686769
5.67962
false
true
false
false
kstaring/swift
stdlib/public/core/Print.swift
4
11798
//===--- Print.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Writes the textual representations of the given items into the standard /// output. /// /// You can pass zero or more items to the `print(_:separator:terminator:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a string, /// a closed range of integers, and a group of floating-point values to /// standard output: /// /// print("One two three four five") /// // Prints "One two three four five" /// /// print(1...5) /// // Prints "1...5" /// /// print(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `print(_:separator:terminator:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// for n in 1...5 { /// print(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// /// - SeeAlso: `debugPrint(_:separator:terminator:)`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func print( _ items: Any..., separator: String = " ", terminator: String = "\n" ) { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _print( items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _print( items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items most suitable for /// debugging into the standard output. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:)` function. The textual representation /// for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints the debugging /// representation of a string, a closed range of integers, and a group of /// floating-point values to standard output: /// /// debugPrint("One two three four five") /// // Prints "One two three four five" /// /// debugPrint(1...5) /// // Prints "CountableClosedRange(1...5)" /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `debugPrint(_:separator:terminator:)` includes /// a newline by default. To print the items without a trailing newline, pass /// an empty string as `terminator`. /// /// for n in 1...5 { /// debugPrint(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// /// - SeeAlso: `print(_:separator:terminator:)`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func debugPrint( _ items: Any..., separator: String = " ", terminator: String = "\n") { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _debugPrint( items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _debugPrint( items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items into the given output /// stream. /// /// You can pass zero or more items to the `print(_:separator:terminator:to:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a closed /// range of integers to a string: /// /// var range = "My range: " /// print(1...5, to: &range) /// // range == "My range: 1...5\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `print(_:separator:terminator:to:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// print(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. /// /// - SeeAlso: `print(_:separator:terminator:)`, /// `debugPrint(_:separator:terminator:to:)`, /// `TextOutputStream`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(__always) public func print<Target : TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _print(items, separator: separator, terminator: terminator, to: &output) } /// Writes the textual representations of the given items most suitable for /// debugging into the given output stream. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:to:)` function. The textual /// representation for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints a closed range of /// integers to a string: /// /// var range = "My range: " /// debugPrint(1...5, to: &range) /// // range == "My range: CountableClosedRange(1...5)\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `debugPrint(_:separator:terminator:to:)` /// includes a newline by default. To print the items without a trailing /// newline, pass an empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// debugPrint(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. /// /// - SeeAlso: `debugPrint(_:separator:terminator:)`, /// `print(_:separator:terminator:to:)`, /// `TextOutputStream`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(__always) public func debugPrint<Target : TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _debugPrint( items, separator: separator, terminator: terminator, to: &output) } @_versioned @inline(never) @_semantics("stdlib_binary_only") internal func _print<Target : TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _print_unlocked(item, &output) prefix = separator } output.write(terminator) } @_versioned @inline(never) @_semantics("stdlib_binary_only") internal func _debugPrint<Target : TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _debugPrint_unlocked(item, &output) prefix = separator } output.write(terminator) } //===----------------------------------------------------------------------===// //===--- Migration Aids ---------------------------------------------------===// @available(*, unavailable, renamed: "print(_:separator:terminator:to:)") public func print<Target : TextOutputStream>( _ items: Any..., separator: String = "", terminator: String = "", toStream output: inout Target ) {} @available(*, unavailable, renamed: "debugPrint(_:separator:terminator:to:)") public func debugPrint<Target : TextOutputStream>( _ items: Any..., separator: String = "", terminator: String = "", toStream output: inout Target ) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'") public func print<T>(_: T, appendNewline: Bool = true) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'") public func debugPrint<T>(_: T, appendNewline: Bool = true) {} //===--- FIXME: Not working due to <rdar://22101775> ----------------------===// @available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'") public func print<T>(_: T, _: inout TextOutputStream) {} @available(*, unavailable, message: "Please use the 'to' label for the target stream: 'debugPrint((...), to: &...))'") public func debugPrint<T>(_: T, _: inout TextOutputStream) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'print((...), terminator: \"\", to: &...)'") public func print<T>(_: T, _: inout TextOutputStream, appendNewline: Bool = true) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'debugPrint((...), terminator: \"\", to: &...)'") public func debugPrint<T>( _: T, _: inout TextOutputStream, appendNewline: Bool = true ) {} //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
apache-2.0
d07feabeac6cc6dba192db997b6bdc34
35.753894
196
0.608832
3.920904
false
false
false
false
Dormmate/DORMLibrary
DORM/Classes/UITextField+Extension.swift
1
3687
// // UITextField+Extension.swift // DORM // // Created by Dormmate on 2017. 5. 4.. // Copyright © 2017 Dormmate. All rights reserved. // import UIKit private var targetView: UIView! private var emojiFlag: Int = 0 extension UITextField: UITextFieldDelegate{ public func setTextField(fontName: String = ".SFUIText", size: CGFloat, placeholderText: String = "NO_PLACEHOLDER", _ targetView: UIView){ if placeholderText != "NO_PLACEHOLDER"{ self.placeholder = placeholderText } self.font = UIFont(name: fontName, size: size*widthRatio) self.autocorrectionType = UITextAutocorrectionType.no self.keyboardType = UIKeyboardType.default self.returnKeyType = UIReturnKeyType.done self.delegate = self targetView.addSubview(self) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /* 키보드 올라갈 때 화면 올림 사용법 : textField.setKeyboardNotification(target: self.view) override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { textField.endEditing(true) textField.setEmojiFlag() } */ public func setKeyboardNotification(target: UIView!){ targetView = target NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } public func setEmojiFlag(){ emojiFlag = 0 } public func keyboardWillShow(notification:NSNotification,target: UIView) { adjustingHeight(show: false, notification: notification) } public func keyboardWillHide(notification:NSNotification) { targetView.y = 0 } public func adjustingHeight(show:Bool, notification:NSNotification) { var userInfo = notification.userInfo! let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval let changeInHeight = -(keyboardFrame.height) let changeInEmoji : CGFloat = -(42 * heightRatio) let initialLanguage = self.textInputMode?.primaryLanguage UIView.animate(withDuration: animationDuration, animations: { () -> Void in if self.textInputMode?.primaryLanguage == nil{ targetView.frame.origin.y += changeInEmoji emojiFlag = 1 } else if self.textInputMode?.primaryLanguage == initialLanguage && emojiFlag == 0 { targetView.frame.origin.y += changeInHeight } else if self.textInputMode?.primaryLanguage == initialLanguage && emojiFlag == 1 { targetView.frame.origin.y += (42 * heightRatio) emojiFlag = 0 } else{ targetView.frame.origin.y += changeInHeight emojiFlag = 0 } }) //범위 밖 충돌 현상 또는 3rd party keyboard 버그 발생시 if targetView.frame.origin.y < -258.0 || keyboardFrame.height == 0.0{ targetView.frame.origin.y = -216.0 } } }
mit
57686c01e9343cd560c7f21bf6cf395d
30.565217
150
0.606612
5.200573
false
false
false
false
tapwork/WikiLocation
WikiManager/WikiManager.swift
1
2655
// // WikiManager.swift // WikiLocation // // Created by Christian Menschel on 29.06.14. // Copyright (c) 2014 enterprise. All rights reserved. // import Foundation let kWikilocationBaseURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&list=geosearch&gsradius=10000&gscoord=" let kBackgrounddownloadID = "net.tapwork.wikilocation.backgrounddownload.config" public class WikiManager : NSObject { //MARK: - Properties public class var sharedInstance: WikiManager { struct SharedInstance { static let instance = WikiManager() } return SharedInstance.instance } //MARK: - Download func downloadURL(#url:NSURL,completion:((NSData!, NSError!) -> Void)) { let request: NSURLRequest = NSURLRequest(URL:url) var config = NSURLSessionConfiguration.defaultSessionConfiguration() if UIApplication.sharedApplication().applicationState == .Background { config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(kBackgrounddownloadID) } let session = NSURLSession(configuration: config) let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in dispatch_async(dispatch_get_main_queue(), { completion(data, error) }) }); task.resume() } // NOTE: #major forces first parameter to be named in function call public func downloadWikis(#latitude:Double,longitude:Double,completion:(([WikiArticle]) -> Void)) { let path = "\(latitude)%7C\(longitude)" let fullURLString = kWikilocationBaseURL + path let url = NSURL(string: fullURLString) self.downloadURL(url: url!) { (data, error) -> Void in var articles = NSMutableOrderedSet() if (data.length > 0) { var error:NSError? var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error:&error) as NSDictionary if let result = jsonResult["query"] as? NSDictionary { if let jsonarticles = result["geosearch"]! as? NSArray { for item : AnyObject in jsonarticles { var article = WikiArticle(json: item as Dictionary<String, AnyObject>) articles.addObject(article) } } } } completion(articles.array as [WikiArticle]) } } }
mit
b2877df557df435d6f23d14477b3cc10
35.888889
156
0.608286
5.047529
false
true
false
false
tfmalt/garage-door-opener-ble
iOS/GarageOpener/GOOpenerController.swift
1
20039
// // OpenerViewController.swift // GarageOpener // // Created by Thomas Malt on 10/01/15. // Copyright (c) 2015 Thomas Malt. All rights reserved. // import UIKit import CoreBluetooth import AVFoundation // Constructing global singleton of this var captureCtrl : GOCaptureController = GOCaptureController() // Struct containing the colors I use. struct Colors { static let wait = UIColor.colorWithHex("#D00000")! static let waitHighlight = UIColor.colorWithHex("#D00000")! static let open = UIColor.colorWithHex("#33BB33")! static let openHighlight = UIColor.colorWithHex("#208840")! static let scanning = UIColor.colorWithHex("#D00000")! static let scanningHighlight = UIColor.colorWithHex("#D00000")! static let start = UIColor.colorWithHex("#1080C0")! // FFAA00 static let startHighlight = UIColor.colorWithHex("#0C4778")! // 0C4778 FFDD00 } class GOOpenerController: UIViewController { @IBOutlet weak var openButton: UIButton! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var rssiLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var lumValueLabel: UILabel! @IBOutlet weak var lumLabel: UILabel! let AnimationDuration = 0.5 // An enum to keep track of the application states defined. enum States { case Connected case Initializing case Scanning case Waiting case DeviceNotFound case DeviceFound case BluetoothOff case Disconnected } var currentState = States.Disconnected var discovery : BTDiscoveryManager? var captureCtrl : GOCaptureController = GOCaptureController() var needToShowCameraNotAuthorizedAlert : Bool = false var hasShownCameraNotAuthorized : Bool = false var config = NSUserDefaults.standardUserDefaults() let nc = NSNotificationCenter.defaultCenter() let DEMO : Bool = false let STATE : States = States.Scanning override func viewDidLoad() { super.viewDidLoad() self.initLabels() self.makeButtonCircular() if DEMO == true { self.setTheme() switch (STATE) { case States.Connected: self.updateOpenButtonNormal() self.setupWithoutAutoTheme() self.setSignalLevel(3) self.activityIndicator.stopAnimating() self.setStatusLabel("Connected to Home") break case States.Scanning: self.updateOpenButtonScanning() self.setupWithoutAutoTheme() self.setStatusLabel("Scanning") break default: self.updateOpenButtonWait() break } } else { self.updateOpenButtonWait() self.registerObservers() self.setTheme() self.checkAndConfigureAutoTheme() self.discovery = BTDiscoveryManager() } } func checkAndConfigureAutoTheme() { if self.config.boolForKey("useAutoTheme") == true { self.initAutoThemeLabels() self.captureCtrl.initializeCaptureSession() } else { self.setupWithoutAutoTheme() } } func initLabels() { self.lumValueLabel.text = "" self.setStatusLabel("Initializing") self.setSignalLevel(0) } /// updates the rssiLabel with the signal meter number func setSignalLevel(strength: Int) { assert( (strength >= 0 && strength <= 5), "argument strength need to be an Integer between 0 and 5." ) if let label = self.rssiLabel { label.text = self.getConnectionBar(strength) } } /// updates the status label with new text. func setStatusLabel(text: String) { if let label = self.statusLabel { label.text = text } } override func viewDidAppear(animated: Bool) { if self.needToShowCameraNotAuthorizedAlert == true { self.showCameraNotAuthorizedAlert() } self.hasShownCameraNotAuthorized = true } func showCameraNotAuthorizedAlert() { let alert = self.captureCtrl.getCameraNotAuthorizedAlert() self.presentViewController(alert, animated: true, completion: { () -> Void in self.needToShowCameraNotAuthorizedAlert = false }) } func handleCaptureDeviceNotAuthorized(notification: NSNotification) { config.setBool(false, forKey: "useAutoTheme") self.setupWithoutAutoTheme() if self.hasShownCameraNotAuthorized == false { if (self.isViewLoaded() && (self.view.window != nil)) { self.showCameraNotAuthorizedAlert() } else { self.needToShowCameraNotAuthorizedAlert = true } } } func handleCaptureDeviceAuthorizationNotDetermined(notification: NSNotification) { setupWithoutAutoTheme() config.setBool(false, forKey: "useAutoTheme") } func initAutoThemeLabels() { lumLabel.text = "Lum:" } func setupWithoutAutoTheme() { lumLabel.text = "" lumValueLabel.text = "" } /////////////////////////////////////////////////////////////////////// // // Functions relating to theming and adjusting the visual style // depending on settings // func setTheme() { if (config.boolForKey("useDarkTheme")) { self.setDarkTheme() } else { self.setLightTheme() } self.setNeedsStatusBarAppearanceUpdate() } /// Updates the automatic theme settings based on the luminance value func updateAutoTheme(luminance: Float) { if self.config.boolForKey("useAutoTheme") == false { return } if (luminance >= 0.50) { self.setLightThemeAnimated() } else if (luminance <= 0.40) { self.setDarkThemeAnimated() } delay(0.5) { self.setNeedsStatusBarAppearanceUpdate() } } func setDarkThemeAnimated() { UIView.animateWithDuration(AnimationDuration, animations: { self.view.backgroundColor = UIColor.blackColor() }) statusLabel.textColor = UIColor.colorWithHex("#CCCCCC") activityIndicator.color = UIColor.colorWithHex("#CCCCCC") } func setLightThemeAnimated() { UIView.animateWithDuration(AnimationDuration, animations: { self.view.backgroundColor = UIColor.whiteColor() }) statusLabel.textColor = UIColor.colorWithHex("#888888") activityIndicator.color = UIColor.colorWithHex("#888888") } func setDarkTheme() { self.view.backgroundColor = UIColor.blackColor() statusLabel.textColor = UIColor.colorWithHex("#CCCCCC") activityIndicator.color = UIColor.colorWithHex("#CCCCCC") } func setLightTheme() { self.view.backgroundColor = UIColor.whiteColor() statusLabel.textColor = UIColor.colorWithHex("#888888") activityIndicator.color = UIColor.colorWithHex("#888888") } override func preferredStatusBarStyle() -> UIStatusBarStyle { if self.view.backgroundColor == UIColor.blackColor() { return UIStatusBarStyle.LightContent } else { return UIStatusBarStyle.Default } } /////////////////////////////////////////////////////////////////////// // // Observers and their handlers // /// The full list of events the app is listening to. func registerObservers() { nc.addObserver( self, selector: Selector("appWillEnterForeground:"), name: UIApplicationWillEnterForegroundNotification, object: nil ) nc.addObserver( self, selector: Selector("appDidEnterBackground:"), name: UIApplicationDidEnterBackgroundNotification, object: nil ) nc.addObserver( self, selector: Selector("btStateChanged:"), name: "btStateChangedNotification", object: nil ) nc.addObserver( self, selector: "handleBTScanningTimedOut:", name: "BTDiscoveryScanningTimedOutNotification", object: nil ) nc.addObserver( self, selector: Selector("btConnectionChanged:"), name: "btConnectionChangedNotification", object: nil ) nc.addObserver( self, selector: Selector("btFoundDevice:"), name: "btFoundDeviceNotification", object: nil ) nc.addObserver( self, selector: Selector("btUpdateRSSI:"), name: "btRSSIUpdateNotification", object: nil ) nc.addObserver( self, selector: "handleSettingsUpdated", name: "SettingsUpdatedNotification", object: nil ) nc.addObserver( self, selector: "handleLightLevelUpdate:", name: "GOCaptureCalculatedLightLevelNotification", object: nil ) nc.addObserver( self, selector: "handleCaptureDeviceNotAuthorized:", name: "GOCaptureDeviceNotAuthorizedNotification", object: nil ) nc.addObserver( self, selector: "handleCaptureDeviceAuthorizationNotDetermined:", name: "GOCaptureDeviceAuthorizationNotDetermined", object: nil ) } /////////////////////////////////////////////////////////////////////// // // App activity notifications // func appWillEnterForeground(notification: NSNotification) { self.updateOpenButtonWait() self.checkAndConfigureAutoTheme() } func appDidEnterBackground(notification: NSNotification) { self.updateOpenButtonWait() self.captureCtrl.removeImageCaptureTimer() self.captureCtrl.endCaptureSession() } /////////////////////////////////////////////////////////////////////// // // Settings view notification handlers // func handleSettingsUpdated() { self.setTheme() if self.config.boolForKey("useAutoTheme") == true { self.initAutoThemeLabels() } else { self.setupWithoutAutoTheme() } } /////////////////////////////////////////////////////////////////////// func handleLightLevelUpdate(notification: NSNotification) { var info = notification.userInfo as [String : AnyObject] var luminance = info["luminance"] as Float dispatch_async(dispatch_get_main_queue(), { self.updateAutoTheme(luminance) self.lumValueLabel.text = String(format: "%.2f", luminance) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getConnectionBar(strength: Int) -> String { let s : String = "\u{25A1}" let b : String = "\u{25A0}" var result : String = "" for (var i = 0; i < 5; i++) { if i < strength { result = result + b; } else { result = result + s; } } return result } @IBAction func openButtonPressed(sender: UIButton) { if self.currentState == States.Connected { self.sendOpenCommand() return } if self.currentState == States.DeviceNotFound { if let discovery = self.discovery { discovery.startScanning() } return } } func sendOpenCommand() { if let rx = self.getRXCharacteristic() { if let peripheral = self.getActivePeripheral() { if let pass = config.valueForKey("password") as? String { var str = "0" + pass; var data : NSData = str.dataUsingEncoding(NSUTF8StringEncoding)! peripheral.writeValue( data, forCharacteristic: rx, type: CBCharacteristicWriteType.WithoutResponse ) } } } } func getActivePeripheral() -> CBPeripheral? { if self.discovery == nil { return nil } if let peripheral = self.discovery!.activePeripheral { if peripheral.state != CBPeripheralState.Connected { return nil } return peripheral } return nil } func getRXCharacteristic() -> CBCharacteristic? { if let peripheral = self.getActivePeripheral() { if let service = self.discovery?.activeService { if let rx = service.rxCharacteristic { return rx } } } return nil } func updateOpenButtonWait() { UIView.animateWithDuration(AnimationDuration, animations: { self.openButton.backgroundColor = Colors.wait }) openButton.setBackgroundImage( UIImage.imageWithColor(Colors.wait), forState: UIControlState.Highlighted ) openButton.setTitle("Wait", forState: UIControlState.Normal) } func updateOpenButtonNormal() { UIView.animateWithDuration(AnimationDuration, animations: { self.openButton.backgroundColor = Colors.open }) openButton.setBackgroundImage( UIImage.imageWithColor(Colors.openHighlight), forState: UIControlState.Highlighted ) self.openButton.setTitle("Open", forState: UIControlState.Normal) } func updateOpenButtonScanning() { UIView.animateWithDuration(AnimationDuration, animations: { self.openButton.backgroundColor = Colors.scanning }) self.openButton.setBackgroundImage( UIImage.imageWithColor(Colors.scanning), forState: UIControlState.Highlighted ) self.openButton.setTitle("Wait", forState: UIControlState.Normal) } func updateOpenButtonStartScan() { UIView.animateWithDuration(AnimationDuration, animations: { self.openButton.backgroundColor = Colors.start }) self.openButton.setBackgroundImage( UIImage.imageWithColor(Colors.startHighlight), forState: UIControlState.Highlighted ) openButton.setTitle("Connect", forState: UIControlState.Normal) } /// Updates the button to make size and layout is correct. func makeButtonCircular() { openButton.frame = CGRectMake(0, 0, 180, 180); openButton.clipsToBounds = true; openButton.layer.cornerRadius = 90 } /// Listens to notifications about CoreBluetooth state changes /// /// :param: notification The NSNotification object /// :returns: nil func btStateChanged(notification: NSNotification) { var msg = notification.object as String dispatch_async(dispatch_get_main_queue(), { if (msg.hasPrefix("Low Signal")) { self.currentState = States.Scanning return } self.setStatusLabel(msg) if (msg != "Scanning") { self.activityIndicator.stopAnimating() } if (msg == "Disconnected") { self.currentState = States.Disconnected self.updateOpenButtonWait() } else if (msg == "Bluetooth Off") { self.currentState = States.BluetoothOff self.updateOpenButtonWait() self.setSignalLevel(0) } else if (msg == "Scanning") { self.currentState = States.Scanning self.updateOpenButtonScanning() self.setSignalLevel(0) self.activityIndicator.startAnimating() } }) } func handleBTScanningTimedOut(notification: NSNotification) { self.currentState = States.DeviceNotFound dispatch_async(dispatch_get_main_queue(), { self.updateOpenButtonWait() self.setSignalLevel(0) self.activityIndicator.stopAnimating() self.setStatusLabel("Device Not Found") self.delay(2.0) { self.updateOpenButtonStartScan() self.setStatusLabel("Scan Finished") } }) } /// Handler for the connection. func btConnectionChanged(notification: NSNotification) { let info = notification.userInfo as [String: AnyObject] var name = info["name"] as NSString if name.length < 1 { name = "" } else { name = " to " + name } if let isConnected = info["isConnected"] as? Bool { self.currentState = States.Connected dispatch_async(dispatch_get_main_queue(), { self.updateOpenButtonNormal() self.setStatusLabel("Connected\(name)") self.activityIndicator.stopAnimating() }) } } func btFoundDevice(notification: NSNotification) { let info = notification.userInfo as [String: AnyObject] var peripheral = info["peripheral"] as CBPeripheral var rssi = info["RSSI"] as NSNumber var name = String(peripheral.name) self.currentState = States.DeviceFound dispatch_async(dispatch_get_main_queue(), { self.openButton.backgroundColor = UIColor.orangeColor() self.setStatusLabel("Found Device...") }) } func getQualityFromRSSI(RSSI: NSNumber!) -> Int { var quality = 2 * (RSSI.integerValue + 100); if quality < 0 { quality = 0 } if quality > 100 { quality = 100 } return quality } func btUpdateRSSI(notification: NSNotification) { let info = notification.userInfo as [String: NSNumber] let peripheral = notification.object as CBPeripheral var rssi : NSNumber! = info["rssi"] if peripheral.state != CBPeripheralState.Connected { return } var quality : Int = self.getQualityFromRSSI(rssi) var strength : Int = Int(ceil(Double(quality) / 20)) dispatch_async(dispatch_get_main_queue(), { self.setSignalLevel(strength) }) } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure ) } }
mit
82a36500ee8553bd709c1f9c3f4de652
28.731454
86
0.54883
5.564843
false
false
false
false
SunshineYG888/YG_NetEaseOpenCourse
YG_NetEaseOpenCourse/YG_NetEaseOpenCourse/Classes/View/Category/YGSearchView.swift
1
7268
// // YGSearchView.swift // YG_NetEaseOpenCourse // // Created by male on 16/4/13. // Copyright © 2016年 yg. All rights reserved. // import UIKit import SnapKit enum SearchViewType { case Home case Category } let SearchViewMargin = 12 class YGSearchView: UIView, UITextFieldDelegate { /* 属性 */ var textFieldTailCons: Constraint? var textFieldLeadCons: Constraint? var type: SearchViewType = SearchViewType.Home lazy var searchKeyWordsTableVC: YGSearchKeyWordsTableViewController = YGSearchKeyWordsTableViewController() /* 构造函数 */ convenience init(searViewType: SearchViewType, frame: CGRect) { self.init(frame: frame) type = searViewType setupUI() } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* 点击"取消按钮" */ func cancelBtnDidClick(sender: UIButton) { textField.resignFirstResponder() textFieldLeadCons?.uninstall() textFieldTailCons?.uninstall() textField.snp_makeConstraints(closure: { (make) -> Void in textFieldLeadCons = make.left.equalTo(logoImageView.snp_right).offset(SearchViewMargin).constraint if type == SearchViewType.Home { textFieldTailCons = make.right.equalTo(historyBtn.snp_left).offset(-SearchViewMargin).constraint } else { textFieldTailCons = make.right.equalTo(self.snp_right).offset(-SearchViewMargin).constraint } }) textField.text = "" UIView.animateWithDuration(0.5) { () -> Void in self.logoImageView.alpha = 1 self.cancelBtn.hidden = true if self.type == SearchViewType.Home { self.historyBtn.alpha = 1 self.downloadBtn.alpha = 1 } } searchKeyWordsTableVC.dismiss() } /* 懒加载子控件 */ // logo private lazy var logoImageView: UIImageView = UIImageView(image: UIImage(named: "home_logo")) // textField private lazy var textField: UITextField = { let textField = UITextField() textField.backgroundColor = UIColor.colorWithRGB(39, green: 95, blue: 62) textField.placeholder = "Ted" textField.textColor = UIColor.whiteColor() textField.layer.cornerRadius = 5 textField.layer.masksToBounds = true return textField }() // textField 中的放大镜 private lazy var searchImageView: UIImageView = UIImageView(image: UIImage(named: "home_search")) // 播放记录 private lazy var historyBtn: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "home_history"), forState: .Normal) return btn }() // 已下载 private lazy var downloadBtn: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "home_download"), forState: .Normal) return btn }() // "取消"按钮 private lazy var cancelBtn: UIButton = { let btn = UIButton() btn.setTitle("取消", forState: .Normal) btn.setTitleColor(UIColor.whiteColor(), forState: .Normal) btn.titleLabel?.font = UIFont.systemFontOfSize(14) btn.hidden = true btn.sizeToFit() return btn }() } /* 设置界面 */ extension YGSearchView { private func setupUI() { addSubview(logoImageView) addSubview(textField) addSubview(cancelBtn) textField.delegate = self cancelBtn.addTarget(self, action: "cancelBtnDidClick:", forControlEvents: .TouchUpInside) logoImageView.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(self.snp_centerY) make.left.equalTo(self.snp_left) make.width.height.equalTo(35) } cancelBtn.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(self.snp_centerY) make.right.equalTo(self.snp_right) } textField.snp_makeConstraints { (make) -> Void in textFieldLeadCons = make.left.equalTo(logoImageView.snp_right).offset(SearchViewMargin).constraint make.centerY.equalTo(self.snp_centerY) make.height.equalTo(28) textFieldTailCons = make.right.equalTo(self.snp_right).offset(-SearchViewMargin).constraint } setupLeftView() if type == SearchViewType.Home { addSubview(downloadBtn) addSubview(historyBtn) downloadBtn.snp_makeConstraints(closure: { (make) -> Void in make.centerY.equalTo(self.snp_centerY) make.right.equalTo(self.snp_right) make.width.height.equalTo(20) }) historyBtn.snp_makeConstraints(closure: { (make) -> Void in make.centerY.equalTo(self.snp_centerY) make.width.height.equalTo(20) make.right.equalTo(downloadBtn.snp_left).offset(-SearchViewMargin) }) textFieldTailCons?.uninstall() textField.snp_makeConstraints(closure: { (make) -> Void in textFieldTailCons = make.right.equalTo(historyBtn.snp_left).offset(-SearchViewMargin).constraint }) } } /* 设置 textField 的左图 */ private func setupLeftView() { textField.leftView = searchImageView textField.leftView?.contentMode = .Center textField.leftViewMode = .Always searchImageView.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(textField.leftView!.snp_centerY) make.left.equalTo(textField.leftView!.snp_left) make.width.height.equalTo(30) } } } /* UITextFieldDelegate */ extension YGSearchView { /* textField 开始编辑时调用的代理方法 */ func textFieldDidBeginEditing(textField: UITextField) { adjustNavigationBar() searchKeyWordsTableVC.show() } private func adjustNavigationBar() { if type == SearchViewType.Home { historyBtn.alpha = 0 downloadBtn.alpha = 0 } logoImageView.alpha = 0 cancelBtn.hidden = false textFieldLeadCons?.uninstall() textFieldTailCons?.uninstall() textField.snp_makeConstraints(closure: { (make) -> Void in textFieldLeadCons = make.left.equalTo(self.snp_left).offset(SearchViewMargin).constraint textFieldTailCons = make.right.equalTo(cancelBtn.snp_left).offset(-SearchViewMargin).constraint }) } func textFieldShouldReturn(textField: UITextField) -> Bool { let searchWord = textField.text! if searchWord != "" { print("search " + searchWord) YGSearchHistoryManager.sharedSearchHistoryManager.addSearchedKeyWords(searchWord) } else { print("search \"TED\"") } return true } }
mit
0ba709c0b259defa2d7c1a38dc07fb53
31.216216
112
0.60509
4.74834
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Model/Sources/V3Model/Website.swift
1
2774
// // Created by Jeffrey Bergier on 2022/06/17. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public struct Website: Identifiable, Hashable, Equatable { public typealias Selection = Set<Website.Identifier> public struct Identifier: Hashable, Equatable, Codable, RawRepresentable, Identifiable { public var id: String { self.rawValue } public var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } } public var id: Identifier public var isArchived: Bool public var originalURL: URL? public var resolvedURL: URL? public var title: String? public var thumbnail: Data? public var dateCreated: Date? public var dateModified: Date? public init(id: Identifier, isArchived: Bool = false, originalURL: URL? = nil, resolvedURL: URL? = nil, title: String? = nil, thumbnail: Data? = nil, dateCreated: Date? = nil, dateModified: Date? = nil) { self.id = id self.isArchived = isArchived self.originalURL = originalURL self.resolvedURL = resolvedURL self.title = title self.thumbnail = thumbnail self.dateCreated = dateCreated self.dateModified = dateModified } } extension Website { public var preferredURL: URL? { self.resolvedURL ?? self.originalURL } } extension Website.Identifier: Comparable { public static func < (lhs: Website.Identifier, rhs: Website.Identifier) -> Bool { return lhs.rawValue < rhs.rawValue } }
mit
2337497838162367bed16ae859452755
34.564103
92
0.672675
4.5625
false
false
false
false
DrabWeb/Booru-chan
Booru-chan/Booru-chan/ViewerController.swift
1
1202
// // ViewerController.swift // Booru-chan // // Created by Ushio on 2017-12-05. // import Cocoa import Alamofire class ViewerController: NSViewController { private var thumbnailDownloader: ImageDownloader? private var imageDownloader: ImageDownloader? @IBOutlet private weak var imageView: NSImageView! //todo: fix bug where a blank thumbnail is displayed when switching posts while the image is loading func display(post: BooruPost?, progressHandler: ((Double) -> Void)? = nil) { thumbnailDownloader?.cancel(); imageDownloader?.cancel(); if post == nil { imageView.image = nil; return; } thumbnailDownloader = ImageDownloader(url: URL(string: post!.thumbnailUrl)!); thumbnailDownloader?.download(complete: { thumbnail in self.imageView.image = thumbnail; }); imageDownloader = ImageDownloader(url: URL(string: post!.imageUrl)!); imageDownloader?.download(progress: { progress in progressHandler?(progress); }, complete: { image in self.thumbnailDownloader?.cancel(); self.imageView.image = image; }); } }
gpl-3.0
f7ecbd6255fc99cca69c16b2bb2673db
28.317073
104
0.643927
4.966942
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/Custom/SeparatorView.swift
1
1274
// // SeparatorView.swift // Inbbbox // // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit final class SeparatorView: UIView { private let axis: Axis private let thickness: Double private let color: UIColor @available(*, unavailable, message: "Use init(axis: thickness: color:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(axis: Axis, thickness: Double, color: UIColor) { self.axis = axis self.thickness = thickness self.color = color super.init(frame: .zero) setupProperties() } private func setupProperties() { backgroundColor = color setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: axis == .vertical ? .vertical : .horizontal) } override var intrinsicContentSize: CGSize { switch axis { case .vertical: return CGSize(width: UIViewNoIntrinsicMetric, height: CGFloat(thickness)) case .horizontal: return CGSize(width: CGFloat(thickness), height: UIViewNoIntrinsicMetric) } } } extension SeparatorView { enum Axis { case vertical case horizontal } }
gpl-3.0
0b995c01596ac920dd99518420d89548
24.46
112
0.633936
4.663004
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Models/VIMUpload.swift
1
5160
// // VIMUpload.swift // Pods // // Created by Lehrer, Nicole on 4/18/18. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Encapsulates the upload-related information on a video object. public class VIMUpload: VIMModelObject { /// The approach for uploading the video, expressed as a Swift-only enum /// /// - streaming: Two-step upload without using tus; this will be deprecated /// - post: Upload with an HTML form or POST /// - pull: Upload from a video file that already exists on the internet /// - tus: Upload using the open-source tus protocol public struct UploadApproach: RawRepresentable, Equatable { public typealias RawValue = String public init?(rawValue: String) { self.rawValue = rawValue } public var rawValue: String public static let Streaming = UploadApproach(rawValue: "streaming")! public static let Post = UploadApproach(rawValue: "post")! public static let Pull = UploadApproach(rawValue: "pull")! public static let Tus = UploadApproach(rawValue: "tus")! } /// The status code for the availability of the uploaded video, expressed as a Swift-only enum /// /// - complete: The upload is complete /// - error: The upload ended with an error /// - underway: The upload is in progress public enum UploadStatus: String { case complete case error case inProgress = "in_progress" } /// The approach for uploading the video @objc dynamic public private(set) var approach: String? /// The file size in bytes of the uploaded video @objc dynamic public private(set) var size: NSNumber? /// The status code for the availability of the uploaded video @objc dynamic public private(set) var status: String? /// The HTML form for uploading a video through the post approach @objc dynamic public private(set) var form: String? /// The link of the video to capture through the pull approach @objc dynamic public private(set) var link: String? /// The URI for completing the upload @objc dynamic public private(set) var completeURI: String? /// The redirect URL for the upload app @objc dynamic public private(set) var redirectURL: String? /// The link for sending video file data @objc dynamic public private(set) var uploadLink: String? /// The approach for uploading the video, mapped to a Swift-only enum public private(set) var uploadApproach: UploadApproach? /// The status code for the availability of the uploaded video, mapped to a Swift-only enum public private(set) var uploadStatus: UploadStatus? public private(set) var gcs: [GCS]? @objc internal private(set) var gcsStorage: NSArray? // MARK: - VIMMappable Protocol Conformance /// Called when automatic object mapping completes public override func didFinishMapping() { if let approachString = self.approach { self.uploadApproach = UploadApproach(rawValue: approachString) } if let statusString = self.status { self.uploadStatus = UploadStatus(rawValue: statusString) } self.gcs = [GCS]() self.gcsStorage?.forEach({ (object) in guard let dictionary = object as? [String: Any], let gcsObject = try? VIMObjectMapper.mapObject(responseDictionary: dictionary) as GCS else { return } self.gcs?.append(gcsObject) }) } /// Maps the property name that mirrors the literal JSON response to another property name. /// Typically used to rename a property to one that follows this project's naming conventions. /// /// - Returns: A dictionary where the keys are the JSON response names and the values are the new property names. public override func getObjectMapping() -> Any { return ["complete_uri": "completeURI", "redirect_url": "redirectURL", "gcs": "gcsStorage"] } }
mit
1457775fecb5fb9131b7e0c11521ceb2
39.952381
153
0.67655
4.67815
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Model/Favorite.swift
1
1993
// // Favorite.swift // JenkinsiOS // // Created by Robert on 01.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation class Favorite: NSObject, NSCoding { /// An enum describing the type of a favorite /// /// - job: The favorite is a job /// - build: The favorite is a build enum FavoriteType: String { case job = "Job" case build = "Build" case folder = "Folder" } /// The type of the Favorite var type: FavoriteType /// The url that the favorite is associated with var url: URL /// The account that the account is associated with var account: Account? /// Initialize a Favorite /// /// - parameter url: The url that the favorite should be associated with /// - parameter type: The favorite's type /// - parameter account: The account associated with the favorite /// /// - returns: An initialized Favorite object init(url: URL, type: FavoriteType, account: Account?) { self.type = type self.url = url self.account = account } required init?(coder aDecoder: NSCoder) { guard let url = aDecoder.decodeObject(forKey: "url") as? URL, let type = aDecoder.decodeObject(forKey: "type") as? String, let accountUrl = aDecoder.decodeObject(forKey: "accountUrl") as? URL else { return nil } self.url = url self.type = FavoriteType(rawValue: type)! AccountManager.manager.update() account = AccountManager.manager.accounts.first(where: { $0.baseUrl == accountUrl }) } func encode(with aCoder: NSCoder) { aCoder.encode(url, forKey: "url") aCoder.encode(type.rawValue, forKey: "type") aCoder.encode(account?.baseUrl, forKey: "accountUrl") } override func isEqual(_ object: Any?) -> Bool { guard let fav = object as? Favorite else { return false } return (fav.url == url) && (fav.type == type) } }
mit
87441f190fd5619ac867fc7f6232905c
31.129032
199
0.620482
4.193684
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01170-getselftypeforcontainer.swift
11
985
// 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 // RUN: not %target-swift-frontend %s -parse class k<g>: d { var f: g init(f: g) { l. d { typealias j = je: Int -> Int = { } let d: Int = { c, b in }(f, e) } class d { func l<j where j: h, j: d>(l: j) { } func i(k: b) -> <j>(() -> j) -> b { } class j { func y((Any, j))(v: (Any, AnyObject)) { } } func w(j: () -> ()) { } class v { l _ = w() { } } func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { } y q<x> { } o n { } class r { func s() -> p { } } class w: r, n { } func b<c { enum b { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d { func d
apache-2.0
42c0d37a754d6250ca2f281839ee4d21
15.147541
78
0.551269
2.390777
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+FAB.swift
1
1513
extension BlogDetailsViewController { /// Make a create button coordinator with /// - Returns: CreateButtonCoordinator with new post, page, and story actions. @objc func makeCreateButtonCoordinator() -> CreateButtonCoordinator { let newPage = { [weak self] in let controller = self?.tabBarController as? WPTabBarController let blog = controller?.currentOrLastBlog() controller?.showPageEditor(forBlog: blog) } let newPost = { [weak self] in let controller = self?.tabBarController as? WPTabBarController controller?.showPostTab(completion: { self?.startAlertTimer() }) } let newStory = { [weak self] in let controller = self?.tabBarController as? WPTabBarController let blog = controller?.currentOrLastBlog() controller?.showStoryEditor(forBlog: blog) } let source = "my_site" var actions: [ActionSheetItem] = [] if shouldShowNewStory { actions.append(StoryAction(handler: newStory, source: source)) } actions.append(PostAction(handler: newPost, source: source)) actions.append(PageAction(handler: newPage, source: source)) let coordinator = CreateButtonCoordinator(self, actions: actions, source: source) return coordinator } private var shouldShowNewStory: Bool { return blog.supports(.stories) && !UIDevice.isPad() } }
gpl-2.0
7ea7ca09eb585c9feeb74204728f7c7a
32.622222
89
0.631857
5.009934
false
false
false
false
megavolt605/CNLUIKitTools
CNLUIKitTools/CNLCodeScanner.swift
1
9122
// // CNLCodeScanner.swift // CNLUIKitTools // // Created by Igor Smirnov on 12/11/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import UIKit import AVFoundation import ImageIO import CNLFoundationTools public protocol CNLCodeScannerDelegate: class { func codeScanner(_ codeScanner: CNLCodeScanner, didScanObject object: AVMetadataObject, screenshot: UIImage?) func codeScanner(_ codeScanner: CNLCodeScanner, didTakePhoto image: UIImage?) func codeScannerError(_ codeScanner: CNLCodeScanner) } public enum CNLCodeScannerMode { case scanCode case takePhoto } open class CNLCodeScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate { open weak var delegate: CNLCodeScannerDelegate? var captureSession: AVCaptureSession! var captureDevice: AVCaptureDevice! var captureMetadataOutput: AVCaptureMetadataOutput! var captureImageOutput: AVCaptureStillImageOutput! var videoPreviewView: UIView! var videoPreviewLayer: AVCaptureVideoPreviewLayer! open private(set) var isReading = false open var userData: Any? open var mode: CNLCodeScannerMode = .scanCode open var metadataTypes: [AVMetadataObject.ObjectType] = [ AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.upce, AVMetadataObject.ObjectType.code39, AVMetadataObject.ObjectType.code39Mod43, AVMetadataObject.ObjectType.ean13, AVMetadataObject.ObjectType.ean8, AVMetadataObject.ObjectType.code93, AVMetadataObject.ObjectType.code128, AVMetadataObject.ObjectType.pdf417, AVMetadataObject.ObjectType.aztec ] @discardableResult open func startReading(_ inView: UIView, isFront: Bool) -> Bool { let devices = AVCaptureDevice.devices(for: AVMediaType.video) // most cases: we run in simulator guard devices.count != 0 else { delegate?.codeScannerError(self) return false } captureDevice = nil for device in devices { if isFront { if device.position == .front { captureDevice = device break } } else { if device.position == .back { captureDevice = device break } } } if captureDevice == nil { // most cases: we run in simulator delegate?.codeScannerError(self) return false } do { try captureDevice.lockForConfiguration() } catch _ as NSError { } captureDevice.videoZoomFactor = 1.0 // capability check if captureDevice.isFocusModeSupported(.continuousAutoFocus) { captureDevice.focusMode = .continuousAutoFocus } else { if captureDevice.isFocusModeSupported(.autoFocus) { captureDevice.focusMode = .autoFocus } else { if captureDevice.isFocusModeSupported(.locked) { captureDevice.focusMode = .locked } } } // capability check if captureDevice.isExposureModeSupported(.continuousAutoExposure) { captureDevice.exposureMode = .continuousAutoExposure } else { if captureDevice.isExposureModeSupported(.autoExpose) { captureDevice.exposureMode = .autoExpose } else { if captureDevice.isExposureModeSupported(.locked) { captureDevice.exposureMode = .locked } } } captureDevice?.unlockForConfiguration() do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession.sessionPreset = AVCaptureSession.Preset.high captureSession.addInput(input) captureImageOutput = AVCaptureStillImageOutput() captureSession?.addOutput(captureImageOutput) switch mode { case .scanCode: let dispatchQueue = DispatchQueue(label: "barCodeQueue", attributes: []) captureMetadataOutput = AVCaptureMetadataOutput() captureSession.addOutput(captureMetadataOutput) captureMetadataOutput.metadataObjectTypes = metadataTypes.filter { captureMetadataOutput.availableMetadataObjectTypes.contains($0) } captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatchQueue) case .takePhoto: break } captureImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill videoPreviewLayer.frame = inView.layer.bounds inView.layer.addSublayer(videoPreviewLayer) videoPreviewView = inView updateOrientation() captureSession.startRunning() return true } catch _ as NSError { return false } } open func stopReading() { captureSession?.stopRunning() captureSession = nil videoPreviewLayer?.removeFromSuperlayer() videoPreviewLayer = nil captureMetadataOutput = nil captureImageOutput = nil videoPreviewView = nil isReading = false } // AVCaptureMetadataOutputObjectsDelegate delegate public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if !isReading { isReading = true guard let metadataObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject else { return } asyncMain { let objectFrame = UIView() objectFrame.backgroundColor = UIColor.clear //self.highlightView.frame = self.videoPreviewLayer.transformedMetadataObjectForMetadataObject(metadataObj).bounds //self.highlightView.hidden = false self.captureImage { image in self.delegate?.codeScanner(self, didScanObject: metadataObj, screenshot: image) self.stopReading() } } } } open func setFocusPoint(_ point: CGPoint) { do { try captureDevice.lockForConfiguration() } catch _ as NSError { } if captureDevice.isFocusPointOfInterestSupported { captureDevice.focusPointOfInterest = point } if captureDevice.isExposurePointOfInterestSupported { captureDevice.exposurePointOfInterest = point } captureDevice.unlockForConfiguration() } func updateOrientation() { guard videoPreviewLayer != nil, let connection = videoPreviewLayer.connection else { return } videoPreviewLayer.frame = videoPreviewView.bounds switch UIApplication.shared.statusBarOrientation { case .portrait: connection.videoOrientation = .portrait case .landscapeLeft: connection.videoOrientation = .landscapeLeft case .landscapeRight: connection.videoOrientation = .landscapeRight case .portraitUpsideDown: connection.videoOrientation = .portraitUpsideDown default: break //videoPreviewLayer.connection.videoOrientation = lastOrientation } } open func captureImage(_ completion: @escaping (_ image: UIImage?) -> Void) { guard let captureImageOutput = captureImageOutput else { completion(nil) return } var videoConnection: AVCaptureConnection? = nil for connection in captureImageOutput.connections { if (connection.inputPorts.contains { $0.mediaType == AVMediaType.video }) { videoConnection = connection break } if videoConnection != nil { break } } captureImageOutput.captureStillImageAsynchronously(from: videoConnection!) { (imageSampleBuffer: CMSampleBuffer?, _: Error?) -> Void in //let exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, nil) guard let sampleBuffer = imageSampleBuffer, let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer), let image = UIImage(data: imageData) else { completion(nil) return } completion(image.adoptToDevice(CGSize(width: image.size.width / 2.0, height: image.size.height / 2.0), scale: 1.0)) } } }
mit
2c3359516cee055499b2b02091efdbc6
36.846473
152
0.618682
6.342837
false
false
false
false
sjtu-meow/iOS
Pods/PKHUD/PKHUD/PKHUDAnimation.swift
1
1172
// // PKHUDAnimation.swift // PKHUD // // Created by Piergiuseppe Longo on 06/01/16. // Copyright © 2016 Piergiuseppe Longo, NSExceptional. All rights reserved. // Licensed under the MIT license. // import Foundation import QuartzCore public final class PKHUDAnimation { public static let discreteRotation: CAAnimation = { let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z") animation.values = [NSNumber]() animation.keyTimes = [NSNumber]() for i in 0..<12 { animation.values!.append(NSNumber(value: Double(i) * .pi / 6.0)) animation.keyTimes!.append(NSNumber(value: Double(i) / 12.0)) } animation.duration = 1.2 animation.calculationMode = "discrete" animation.repeatCount = Float(INT_MAX) return animation }() static let continuousRotation: CAAnimation = { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = 2.0 * .pi animation.duration = 1.2 animation.repeatCount = Float(INT_MAX) return animation }() }
apache-2.0
eb41226fe0546b4935685da1f67723d3
29.025641
76
0.635354
4.35316
false
false
false
false
jianghuihon/DYZB
DYZB/Classes/Home/View/RecommendGameView.swift
1
1743
// // RecommendGameView.swift // DYZB // // Created by Enjoy on 2017/3/27. // Copyright © 2017年 SZCE. All rights reserved. // import UIKit private let collectionGameViewCellID = "CollectionGameViewCell" private let GameMagin : CGFloat = 10 class RecommendGameView: UIView { @IBOutlet weak var collectionGameView: UICollectionView! var anthorGroups : [GameBaseModel]? { didSet{ collectionGameView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing() collectionGameView.register(UINib.init(nibName: collectionGameViewCellID, bundle: nil), forCellWithReuseIdentifier: collectionGameViewCellID) collectionGameView.contentInset = UIEdgeInsets(top: GameMagin, left: 10, bottom: 0, right: GameMagin); } } ///加载游戏选择 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)!.first as! RecommendGameView } } ///MARK - UICollectionViewDataSource extension RecommendGameView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return anthorGroups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionGameViewCellID, for: indexPath) as! CollectionGameViewCell cell.baseModel = anthorGroups?[indexPath.item] return cell } }
mit
f3fb6090ceb5b7eba7eeaa9ab1b8fc5a
18.636364
149
0.703704
5.236364
false
false
false
false
zorac/PastePad
PastePad/NSFont+Name.swift
1
1229
import AppKit /** * NSFont extension for converting to/from names. * * - Author: Mark Rigby-Jones * - Copyright: © 2019 Mark Rigby-Jones. All rights reserved. */ extension NSFont { /// The maximum point size to allow. static let maxPoints = 288.0 /// The name of this font. var name: String { return "\(self.pointSize)pt \(self.displayName!)" } /** * Create a font for a given name. * * - Parameter name: A font name. * - Parameter textMode: A text mode. * - Returns: The named font, or the default font for the given text mode */ static func fromName(_ name: String, textMode: TextMode) -> NSFont { let scanner = Scanner(string:name) var points: Double = 0.0 var face: NSString? scanner.scanDouble(&points) scanner.scanString("pt", into: nil); scanner.scanUpToCharacters(from: .newlines, into: &face) if points > maxPoints { points = maxPoints } if let font = NSFont(name: face! as String, size: CGFloat(points)) { return font } else { return textMode.userFontOfSize(CGFloat(points)) } } }
mit
aaa3b6ca9c294e7783210770101f3f73
26.909091
77
0.576547
4.249135
false
false
false
false
Baglan/MCLocalization2
Classes/MCLocalizationProviders.swift
1
7160
// // MCLocalizationProviders.swift // MCLocalization2 // // Created by Baglan on 12/12/15. // Copyright © 2015 Mobile Creators. All rights reserved. // import Foundation extension MCLocalization { /// Placeholder provider designed to be put as the last one in queue /// to "catch" unlocalized strings and display a placeholder for them /// that would look something like this: /// /// [en: some_unlocalized_key] class PlaceholderProvider: MCLocalizationProvider { var languages: [String] { get { return [] } } func string(for key: String, language: String) -> String? { return "[\(language): \(key)]" } } /// Provider for the default main bundle localization. /// /// *Does not support switching languages* class MainBundleProvider: MCLocalizationProvider { fileprivate var table: String? required init(table: String?) { self.table = table } let uniqueString = UUID().uuidString var languages: [String] { get { return Bundle.main.localizations } } func string(for key: String, language: String) -> String? { // The 'defaultValue' "trickery" is here because 'localizedStringForKey' // will always return a string even if there is no localization available // and we want to capture this condition let defaultValue = "\(uniqueString)-\(key)" let localizedString = Bundle.main.localizedString(forKey: key, value: defaultValue, table: table) if localizedString == defaultValue { return nil } return localizedString } } /// Provider for single- and multiple-language JSON sources class JSONProvider: MCLocalizationProvider { fileprivate var strings = [String:[String:String]]() fileprivate let synchronousURL: URL? fileprivate let asynchronousURL: URL? fileprivate let language: String? /// Main init /// /// - parameter synchronousURL URL to be fetched synchronously (perhaps a local file) /// - parameter asynchronousURL URL to be fetched asynchronously (perhaps a remote resource) /// - parameter language for single language JSON resources required init(synchronousURL: URL?, asynchronousURL: URL?, language: String?) { self.synchronousURL = synchronousURL self.asynchronousURL = asynchronousURL self.language = language guard synchronousURL != nil || asynchronousURL != nil else { return } if let synchronousURL = synchronousURL, let data = try? Data(contentsOf: synchronousURL), let JSONObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) { adoptJSONObject(JSONObject as AnyObject) } } /// Convenience init for a file in the main bundle /// /// - parameter language for a single language JSON resource /// - parameter fileName file name for a file in the main bundle convenience init(language: String?, fileName: String) { self.init(synchronousURL: Bundle.main.url(forResource: fileName, withExtension: nil), asynchronousURL: nil, language: language) } /// Convenience init for a multiple language file in the main bundle /// /// - parameter fileName file name for a file in the main bundle convenience init(fileName: String) { self.init(language: nil, fileName: fileName) } /// Convenience init for a remote URL resource with an optional local cache /// /// - parameter language for a single language JSON resource /// - parameter remoteURL URL for a remote resource /// - parameter localName file name for the local cache (will be stored in the 'Application Support' directory) convenience init(language: String?, remoteURL: URL, localName: String?) { let directoryURL = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let localURL: URL? if let directoryURL = directoryURL, let localName = localName { localURL = directoryURL.appendingPathComponent(localName) } else { localURL = nil } self.init(synchronousURL: localURL, asynchronousURL: remoteURL, language: language) } /// Convenience init for a multiple language remote URL resource with an optional local cache /// /// - parameter remoteURL URL for a remote resource /// - parameter localName file name for the local cache (will be stored in the 'Application Support' directory) convenience init(remoteURL: URL, localName: String?) { self.init(language: nil, remoteURL: remoteURL, localName: localName) } @discardableResult func adoptJSONObject(_ JSONObject: AnyObject) -> Bool { if let multipleLanguages = JSONObject as? [String:[String:String]] { self.strings = multipleLanguages return true } else if let singleLanguage = JSONObject as? [String:String], let language = self.language { self.strings[language] = singleLanguage return true } return false } /// Request asynchronousURL and, optionally, store it in a local cache func fetchAsynchronously() { if let asynchronousURL = asynchronousURL { OperationQueue().addOperation({ () -> Void in if let data = try? Data(contentsOf: asynchronousURL), let JSONObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) { if self.adoptJSONObject(JSONObject as AnyObject) { OperationQueue.main.addOperation({ () -> Void in MCLocalization.sharedInstance.providerUpdated(self) }) // If synchronous URL (e.g. cache) is configured, attempt to save data to it if let synchronousURL = self.synchronousURL { try? data.write(to: synchronousURL, options: [.atomic]) } } } }) } } var languages: [String] { get { return strings.map { (key: String, _) -> String in return key } } } func string(for key: String, language: String) -> String? { if let strings = strings[language] { return strings[key] } return nil } } }
mit
a373a4bb4b04b549a9f29b713392f5aa
42.920245
225
0.586255
5.562549
false
false
false
false
silt-lang/silt
Sources/Seismography/PrimOp.swift
1
18356
/// PrimOp.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import Moho /// A primitive operation that has no CPS definition, yet affects the semantics /// of a continuation. /// These are scheduled after GraphIR generation and include operations like /// application of functions, copying and destroying values, conditional /// branching, and pattern matching primitives. public class PrimOp: Value { /// An enum representing the kind of primitive operation this PrimOp exposes. public enum Code: String { /// A no-op operation. case noop /// Stack allocation. case alloca /// Stack deallocation. case dealloca /// An application of a function-type value. case apply /// An explicit copy operation of a value. case copyValue = "copy_value" /// A explicit destroy operation of a value. case destroyValue = "destroy_value" /// When the type of the source value is loadable, loads the source /// value and stores a copy of it to memory at the given address. /// /// When the type of the source value is address-only, copies the address /// from the source value to the address at the destination value. /// /// Returns the destination's memory. case copyAddress = "copy_address" /// Destroys the value pointed to by the given address but does not /// deallocate the memory at that address. The appropriate memory /// deallocation instruction should be scheduled instead. case destroyAddress = "destroy_address" /// An operation that selects a matching pattern and dispatches to another /// continuation. case switchConstr = "switch_constr" /// An operation that represents a reference to a continuation. case functionRef = "function_ref" /// A data constructor call with all parameters provided at +1. case dataInit = "data_init" /// Extracts the payload data from a data constructor. case dataExtract = "data_extract" /// Heap-allocate a box large enough to hold a given type. case allocBox = "alloc_box" /// Deallocate a heap-allocated box. case deallocBox = "dealloc_box" /// Retrieve the address of the value inside a box. case projectBox = "project_box" /// Load the value stored at an address. case load = "load" /// Store a given value to memory allocated by a given box and returns the /// newly-updated box value. case store = "store" /// Creates a tuple value from zero or more multiple field values. case tuple /// Projects the address of a tuple element. case tupleElementAddress = "tuple_element_address" /// Converts a "thin" function value pointer to a "thick" function by /// appending a closure context. case thicken /// Express a data dependency of a value on multiple other the evaluation of /// other values. case forceEffects = "force_effects" /// An instruction that is considered 'unreachable' that will trap at /// runtime. case unreachable } /// All the operands of this operation. public private(set) var operands: [Operand] = [] /// Which specific operation this PrimOp represents. public let opcode: Code /// The 'result' of this operation, or 'nil', if this operation is only for /// side effects. public var result: Value? { return nil } /// Initializes a PrimOp with the provided OpCode and no operands. /// /// - Parameter opcode: The opcode this PrimOp represents. init(opcode: Code, type: GIRType, category: Value.Category) { self.opcode = opcode super.init(type: type, category: category) } /// Adds the provided operands to this PrimOp's operand list. /// /// - Parameter ops: The operands to append to the end of the current list of /// operands. fileprivate func addOperands(_ ops: [Operand]) { self.operands.append(contentsOf: ops) } } public class TerminalOp: PrimOp { public var parent: Continuation public var successors: [Successor] { return [] } init(opcode: Code, parent: Continuation) { self.parent = parent super.init(opcode: opcode, type: BottomType.shared, category: .object) // Tie the knot self.parent.terminalOp = self } func overrideParent(_ parent: Continuation) { self.parent = parent } } /// A primitive operation that contains no operands and has no effect. public final class NoOp: PrimOp { public init() { super.init(opcode: .noop, type: BottomType.shared, category: .object) } } /// A primitive operation that transfers control out of the current continuation /// to the provided Graph IR value. The value _must_ represent a function. public final class ApplyOp: TerminalOp { /// Creates a new ApplyOp to apply the given arguments to the given value. /// - parameter fnVal: The value to which arguments are being applied. This /// must be a value of function type. /// - parameter args: The values to apply to the callee. These must match the /// arity of the provided function value. public init(_ parent: Continuation, _ fnVal: Value, _ args: [Value]) { super.init(opcode: .apply, parent: parent) if let succ = fnVal as? FunctionRefOp { self.successors_.append(Successor(parent, self, succ.function)) } self.addOperands(([fnVal] + args).map { arg in return Operand(owner: self, value: arg) }) } private var successors_: [Successor] = [] public override var successors: [Successor] { return successors_ } /// The value being applied to. public var callee: Value { return self.operands[0].value } /// The arguments being applied to the callee. public var arguments: ArraySlice<Operand> { return self.operands.dropFirst() } } public final class AllocaOp: PrimOp { public init(_ type: GIRType) { super.init(opcode: .alloca, type: type, category: .address) self.addOperands([Operand(owner: self, value: type)]) } public override var result: Value? { return self } public var addressType: GIRType { return self.operands[0].value } } public final class DeallocaOp: PrimOp { public init(_ value: GIRType) { super.init(opcode: .dealloca, type: BottomType.shared, category: .object) self.addOperands([Operand(owner: self, value: value)]) } public var addressValue: Value { return self.operands[0].value } } public final class CopyValueOp: PrimOp { public init(_ value: Value) { super.init(opcode: .copyValue, type: value.type, category: value.type.category) self.addOperands([Operand(owner: self, value: value)]) } public override var result: Value? { return self } public var value: Operand { return self.operands[0] } } public final class DestroyValueOp: PrimOp { public init(_ value: Value) { super.init(opcode: .destroyValue, type: BottomType.shared, category: .object) self.addOperands([Operand(owner: self, value: value)]) } public var value: Operand { return self.operands[0] } } public final class CopyAddressOp: PrimOp { public init(_ value: Value, to address: Value) { super.init(opcode: .copyAddress, type: address.type, category: value.type.category) self.addOperands([Operand(owner: self, value: value)]) self.addOperands([Operand(owner: self, value: address)]) } public override var result: Value? { return self } public var value: Value { return self.operands[0].value } public var address: Value { return self.operands[1].value } } public final class DestroyAddressOp: PrimOp { public init(_ value: Value) { super.init(opcode: .destroyAddress, type: BottomType.shared, category: .object) self.addOperands([Operand(owner: self, value: value)]) } public var value: Value { return self.operands[0].value } } public final class FunctionRefOp: PrimOp { public let function: Continuation public init(continuation: Continuation) { self.function = continuation super.init(opcode: .functionRef, type: continuation.type, category: .object) self.addOperands([Operand(owner: self, value: continuation)]) } public override var result: Value? { return self } public override var type: Value { return self.function.type } } public final class SwitchConstrOp: TerminalOp { /// Initializes a SwitchConstrOp matching the constructor of the provided /// value with the set of pattern/apply pairs. This will dispatch to a given /// ApplyOp with the provided value if and only if the value was constructed /// with the associated constructor. /// /// - Parameters: /// - value: The value you're pattern matching. /// - patterns: A list of pattern/apply pairs. public init( _ parent: Continuation, matching value: Value, patterns: [(pattern: String, destination: FunctionRefOp)], default: FunctionRefOp? ) { self.patterns = patterns self.`default` = `default` super.init(opcode: .switchConstr, parent: parent) self.addOperands([Operand(owner: self, value: value)]) var ops = [Operand]() for (_, dest) in patterns { ops.append(Operand(owner: self, value: dest)) successors_.append(Successor(parent, self, dest.function)) } if let defaultDest = `default` { ops.append(Operand(owner: self, value: defaultDest)) successors_.append(Successor(parent, self, defaultDest.function)) } self.addOperands(ops) } private var successors_: [Successor] = [] public override var successors: [Successor] { return successors_ } public var matchedValue: Value { return operands[0].value } public let patterns: [(pattern: String, destination: FunctionRefOp)] public let `default`: FunctionRefOp? } public final class DataInitOp: PrimOp { public let constructor: String public let dataType: Value public init(constructor: String, type: Value, argument: Value?) { self.constructor = constructor self.dataType = type super.init(opcode: .dataInit, type: type, category: .object) if let argVal = argument { self.addOperands([Operand(owner: self, value: argVal)]) } } public var argumentTuple: Value? { guard !self.operands.isEmpty else { return nil } return operands[0].value } public override var result: Value? { return self } } public final class DataExtractOp: PrimOp { public let constructor: String public let dataValue: Value public init(constructor: String, value: Value, payloadType: Value) { self.constructor = constructor self.dataValue = value super.init(opcode: .dataExtract, type: payloadType, category: payloadType.category) self.addOperands([ Operand(owner: self, value: value), ]) } public override var result: Value? { return self } } public final class TupleOp: PrimOp { init(arguments: [Value]) { let ty = TupleType(elements: arguments.map({$0.type}), category: .object) super.init(opcode: .tuple, type: ty, category: .object) self.addOperands(arguments.map { Operand(owner: self, value: $0) }) } public override var result: Value? { return self } } public final class TupleElementAddressOp: PrimOp { public let index: Int init(tuple: Value, index: Int) { guard let tupleTy = tuple.type as? TupleType else { fatalError() } self.index = index super.init(opcode: .tupleElementAddress, type: tupleTy.elements[index], category: .address) self.addOperands([ Operand(owner: self, value: tuple) ]) } public var tuple: Value { return self.operands[0].value } public override var result: Value? { return self } } public final class AllocBoxOp: PrimOp { public init(_ type: GIRType) { super.init(opcode: .allocBox, type: BoxType(type), category: .object) self.addOperands([Operand(owner: self, value: type)]) } public override var result: Value? { return self } public var boxedType: GIRType { return self.operands[0].value } } public final class ProjectBoxOp: PrimOp { public init(_ box: Value, type: GIRType) { super.init(opcode: .projectBox, type: type, category: .address) self.addOperands([ Operand(owner: self, value: box) ]) } public override var result: Value? { return self } public var boxValue: Value { return operands[0].value } } public final class LoadOp: PrimOp { public enum Ownership { case take case copy } public let ownership: Ownership public init(_ value: Value, _ ownership: Ownership) { self.ownership = ownership super.init(opcode: .load, type: value.type, category: .object) self.addOperands([ Operand(owner: self, value: value) ]) } public override var result: Value? { return self } public var addressee: Value { return operands[0].value } } public final class StoreOp: PrimOp { public init(_ value: Value, to address: Value) { super.init(opcode: .store, type: value.type, category: .address) self.addOperands([ Operand(owner: self, value: value), Operand(owner: self, value: address), ]) } public override var result: Value? { return self } public var value: Value { return operands[0].value } public var address: Value { return operands[1].value } } public final class DeallocBoxOp: PrimOp { public init(_ box: Value) { super.init(opcode: .deallocBox, type: BottomType.shared, category: .object) self.addOperands([ Operand(owner: self, value: box) ]) } public var box: Value { return operands[0].value } } public final class ThickenOp: PrimOp { public init(_ funcRef: FunctionRefOp) { super.init(opcode: .thicken, type: funcRef.type, category: .object) self.addOperands([ Operand(owner: self, value: funcRef) ]) } public override var result: Value? { return self } public var function: Value { return operands[0].value } } public final class ForceEffectsOp: PrimOp { public init(_ retVal: Value, _ effects: [Value]) { super.init(opcode: .forceEffects, type: retVal.type, category: retVal.category) self.addOperands([ Operand(owner: self, value: retVal) ]) self.addOperands(effects.map { Operand(owner: self, value: $0) }) } public var subject: Value { return operands[0].value } public override var result: Value? { return self } } public final class UnreachableOp: TerminalOp { public init(parent: Continuation) { super.init(opcode: .unreachable, parent: parent) } } public protocol PrimOpVisitor { associatedtype Ret func visitAllocaOp(_ op: AllocaOp) -> Ret func visitApplyOp(_ op: ApplyOp) -> Ret func visitDeallocaOp(_ op: DeallocaOp) -> Ret func visitCopyValueOp(_ op: CopyValueOp) -> Ret func visitDestroyValueOp(_ op: DestroyValueOp) -> Ret func visitCopyAddressOp(_ op: CopyAddressOp) -> Ret func visitDestroyAddressOp(_ op: DestroyAddressOp) -> Ret func visitFunctionRefOp(_ op: FunctionRefOp) -> Ret func visitSwitchConstrOp(_ op: SwitchConstrOp) -> Ret func visitDataInitOp(_ op: DataInitOp) -> Ret func visitDataExtractOp(_ op: DataExtractOp) -> Ret func visitTupleOp(_ op: TupleOp) -> Ret func visitTupleElementAddress(_ op: TupleElementAddressOp) -> Ret func visitLoadOp(_ op: LoadOp) -> Ret func visitStoreOp(_ op: StoreOp) -> Ret func visitAllocBoxOp(_ op: AllocBoxOp) -> Ret func visitProjectBoxOp(_ op: ProjectBoxOp) -> Ret func visitDeallocBoxOp(_ op: DeallocBoxOp) -> Ret func visitThickenOp(_ op: ThickenOp) -> Ret func visitUnreachableOp(_ op: UnreachableOp) -> Ret func visitForceEffectsOp(_ op: ForceEffectsOp) -> Ret } extension PrimOpVisitor { public func visitPrimOp(_ code: PrimOp) -> Ret { switch code.opcode { case .noop: fatalError() // swiftlint:disable force_cast case .alloca: return self.visitAllocaOp(code as! AllocaOp) // swiftlint:disable force_cast case .apply: return self.visitApplyOp(code as! ApplyOp) // swiftlint:disable force_cast case .dealloca: return self.visitDeallocaOp(code as! DeallocaOp) // swiftlint:disable force_cast case .copyValue: return self.visitCopyValueOp(code as! CopyValueOp) // swiftlint:disable force_cast case .destroyValue: return self.visitDestroyValueOp(code as! DestroyValueOp) // swiftlint:disable force_cast case .copyAddress: return self.visitCopyAddressOp(code as! CopyAddressOp) // swiftlint:disable force_cast case .destroyAddress: return self.visitDestroyAddressOp(code as! DestroyAddressOp) // swiftlint:disable force_cast case .functionRef: return self.visitFunctionRefOp(code as! FunctionRefOp) // swiftlint:disable force_cast case .switchConstr: return self.visitSwitchConstrOp(code as! SwitchConstrOp) // swiftlint:disable force_cast case .dataInit: return self.visitDataInitOp(code as! DataInitOp) // swiftlint:disable force_cast case .dataExtract: return self.visitDataExtractOp(code as! DataExtractOp) // swiftlint:disable force_cast case .tuple: return self.visitTupleOp(code as! TupleOp) // swiftlint:disable force_cast line_length case .tupleElementAddress: return self.visitTupleElementAddress(code as! TupleElementAddressOp) // swiftlint:disable force_cast case .unreachable: return self.visitUnreachableOp(code as! UnreachableOp) // swiftlint:disable force_cast case .load: return self.visitLoadOp(code as! LoadOp) // swiftlint:disable force_cast case .store: return self.visitStoreOp(code as! StoreOp) // swiftlint:disable force_cast case .allocBox: return self.visitAllocBoxOp(code as! AllocBoxOp) // swiftlint:disable force_cast case .projectBox: return self.visitProjectBoxOp(code as! ProjectBoxOp) // swiftlint:disable force_cast case .deallocBox: return self.visitDeallocBoxOp(code as! DeallocBoxOp) // swiftlint:disable force_cast case .thicken: return self.visitThickenOp(code as! ThickenOp) // swiftlint:disable force_cast case .forceEffects: return self.visitForceEffectsOp(code as! ForceEffectsOp) } } }
mit
eaafadd2fce8f7a0610eceb3180a8d10
28.895765
99
0.687132
3.930621
false
false
false
false
LeeMZC/MZCWB
MZCWB/MZCWB/Classes/Other/Tool/Base/MZCBasePopManager.swift
1
5110
// // MZCBasePresentationController.swift // MZCWB // // Created by 马纵驰 on 16/8/10. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs //MARK:- 数据源代理 protocol MZCBasePresentationControllerDataSource : NSObjectProtocol { } //MARK:- 转场控制器 class MZCBasePresentationController: UIPresentationController,UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning{ var isPresent = false weak var dataSource : MZCBasePresentationControllerDataSource? /* 1.如果不自定义转场modal出来的控制器会移除原有的控制器 2.如果自定义转场modal出来的控制器不会移除原有的控制器 3.如果不自定义转场modal出来的控制器的尺寸和屏幕一样 4.如果自定义转场modal出来的控制器的尺寸我们可以自己在containerViewWillLayoutSubviews方法中控制 5.containerView 非常重要, 容器视图, 所有modal出来的视图都是添加到containerView上的 6.presentedView() 非常重要, 通过该方法能够拿到弹出的视图 // 用于布局转场动画弹出的控件 即将弹出时调用一次 // override func containerViewWillLayoutSubviews() // { // super.containerViewWillLayoutSubviews() // } required override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { (presentedViewController: presentedViewController, presentingViewController: presentingViewController) } required override init() { super.init() } */ } //MARK:- UIViewControllerTransitioningDelegate extension MZCBasePresentationController { //MARK:转场代理 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?{ let pc = MZCBasePresentationController(presentedViewController: presented, presentingViewController: presenting) pc.dataSource = dataSource return pc } //显示时调用 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{ return self } //消失时调用 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{ return self } } //MARK:- UIViewControllerAnimatedTransitioning extension MZCBasePresentationController { //override 显示 和 消失 的动画时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval{ return 0.0 } func animateTransition(transitionContext: UIViewControllerContextTransitioning){ isPresent ? willDismissedController(transitionContext) : willPresentedController(transitionContext) isPresent = !isPresent } /// 执行展现动画 override func willPresentedController(transitionContext: UIViewControllerContextTransitioning) { /** 1.获取需要弹出视图 通过ToViewKey取出的就是toVC对应的view guard let toView = transitionContext.viewForKey(UITransitionContextToViewKey) else { return } 2.将需要弹出的视图添加到containerView上 transitionContext.containerView()?.addSubview(toView) 3.执行动画 toView.transform = CGAffineTransformMakeScale(1.0, 0.0) 设置锚点 toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in toView.transform = CGAffineTransformIdentity }) { (_) -> Void in 注意: 自定转场动画, 在执行完动画之后一定要告诉系统动画执行完毕了 transitionContext.completeTransition(true) } */ } /// 执行消失动画 override func willDismissedController(transitionContext: UIViewControllerContextTransitioning) { /** 1.拿到需要消失的视图 guard let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) else { return } 2.执行动画让视图消失 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in // 突然消失的原因: CGFloat不准确, 导致无法执行动画, 遇到这样的问题只需要将CGFloat的值设置为一个很小的值即可 fromView.transform = CGAffineTransformMakeScale(1.0, 0.00001) }, completion: { (_) -> Void in // 注意: 自定转场动画, 在执行完动画之后一定要告诉系统动画执行完毕了 transitionContext.completeTransition(true) }) */ } }
artistic-2.0
31603931a93dd743a82569a93a0f80fe
32.630769
218
0.709906
5.311057
false
false
false
false
devios1/Gravity
Plugins/Layout.swift
1
28202
// // Layout.swift // Gravity // // Created by Logan Murray on 2016-02-15. // Copyright © 2016 Logan Murray. All rights reserved. // import Foundation @available(iOS 9.0, *) extension Gravity { @objc public class Layout: GravityPlugin { public var constraints = [String : NSLayoutConstraint]() // store constraints here based on their attribute name (width, minHeight, etc.) -- we should move this to a plugin, but only if we can put all or most of the constraint registering in there as well private static let keywords = ["fill", "auto"] private var widthIdentifiers = [String: Set<GravityNode>]() // instead of storing a dictionary of arrays, can we store a dictionary that just points to the first-registered view, and then all subsequent views just add constraints back to that view? // we should reintroduce this as an *optional* array to represent attributes handled in means *other* than handleAttribute public override var handledAttributes: [String]? { get { return [ "gravity", "height", "minHeight", "maxHeight", "margin", "leftMargin", "topMargin", "rightMargin", "bottomMargin", "padding", "leftPadding", "topPadding", "rightPadding", "bottomPadding", "shrinks", "width", "minWidth", "maxWidth", "zIndex" ] } } static var swizzleToken: dispatch_once_t = 0 public override class func initialize() { Gravity.swizzle(UIView.self, original: #selector(UIView.alignmentRectInsets), override: #selector(UIView.grav_alignmentRectInsets)) // verify align as func // Gravity.swizzle(UIView.self, original: #selector(UIView.didMoveToSuperview), override: #selector(UIView.grav_didMoveToSuperview)) // dispatch_once(&swizzleToken) { // // method swizzling: // let alignmentRectInsets_orig = class_getInstanceMethod(UIView.self, #selector(UIView.alignmentRectInsets)) // let alignmentRectInsets_swiz = class_getInstanceMethod(UIView.self, Selector("grav_alignmentRectInsets")) // // if class_addMethod(UIView.self, #selector(UIView.alignmentRectInsets), method_getImplementation(alignmentRectInsets_swiz), method_getTypeEncoding(alignmentRectInsets_swiz)) { // class_replaceMethod(UIView.self, Selector("grav_alignmentRectInsets"), method_getImplementation(alignmentRectInsets_orig), method_getTypeEncoding(alignmentRectInsets_orig)); // } else { // method_exchangeImplementations(alignmentRectInsets_orig, alignmentRectInsets_swiz); // } // } } public override func instantiateView(node: GravityNode) -> UIView? { // should this be handled in a stackview plugin? switch node.nodeName { case "H": let stackView = UIStackView() stackView.axis = .Horizontal return stackView case "V": let stackView = UIStackView() stackView.axis = .Vertical return stackView default: return nil } } public override func processValue(value: GravityNode) { guard let node = value.parentNode else { return } guard let stringValue = value.stringValue else { return } // this has to be done here because widthIdentifiers should be referenced relative to the document the value is defined in, not the node they are applied to if value.attributeName == "width" { if !Layout.keywords.contains(stringValue) { let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet if stringValue.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters if widthIdentifiers[stringValue] == nil { widthIdentifiers[stringValue] = Set<GravityNode>() } widthIdentifiers[stringValue]?.unionInPlace([node]) } } return } return } /// Removes *all* constraints with a given identifier (verify that there can in fact be multiple). private func removeConstraint(identifier: String, fromNode node: GravityNode) { for constraint in node.view.constraints.filter({ $0.identifier == identifier }) { // node.view.removeConstraint(constraint) constraint.active = false // does this also mean we have to set it to true instead of re-adding?? } } public override func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult { // if let width = node["width"]?.stringValue { // if !Layout.keywords.contains(width) { // let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet // if width.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters //// if widthIdentifiers[width] == nil { //// widthIdentifiers[width] = [GravityNode]() //// } //// widthIdentifiers[width]?.append(node) // } else { // if let width = node.width { // NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // node.constraints["width"] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat(width)) // } // } // } // } // } // public override func preprocessAttribute(node: GravityNode, attribute: String, inout value: GravityNode) -> GravityResult { // NSLog(attribute) // // TODO: can we do anything with node values here? // guard let stringValue = value.stringValue else { // return .NotHandled // } // switch attribute { // TODO: may want to set these with higher priority than default to avoid view/container bindings conflicting // we should also capture these priorities as constants and put them all in one place for easier tweaking and balancing // case "width": // if !Layout.keywords.contains(stringValue) { // let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet // if stringValue.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters //// if widthIdentifiers[stringValue] == nil { //// widthIdentifiers[stringValue] = [GravityNode]() //// } //// widthIdentifiers[stringValue]?.append(node) // } else { // NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // node.constraints[attribute] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat((stringValue as NSString).floatValue)) // } // } // } // return .Handled if attribute == "width" || attribute == nil { if value != nil && node.width != nil { // will this properly handle widths of "fill"? right now it'll remove the width constraint but i think that's ok NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { node.constraints[attribute!] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat(node.width!)).autoIdentify("width") } return .Handled } else { removeConstraint("width", fromNode: node) } } if attribute == "minWidth" || attribute == nil { if let minWidth = node.minWidth { // TODO: we should consider doing this with raw auto layout by looking up a constraint or creating one and modifying its properties // let constraint = node.constraints["minWidth"] ?? NSLayoutConstraint() // NSLayoutConstraint(item: node.view, attribute: .Width, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 0.0, constant: CGFloat(minWidth) NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { node.constraints[attribute!] = node.view.autoSetDimension(.Width, toSize: CGFloat(minWidth), relation: .GreaterThanOrEqual).autoIdentify(attribute!) } NSLayoutConstraint.autoSetPriority(50) {//test node.view.autoSetDimension(.Width, toSize: CGFloat(minWidth)) } return .Handled } else { removeConstraint("minWidth", fromNode: node) } } if attribute == "maxWidth" || attribute == nil { if let maxWidth = node.maxWidth { if node.isOtherwiseFilledAlongAxis(.Horizontal) { // a maxWidth that is filled is equal to an explicit width NSLayoutConstraint.autoSetPriority(700) { // FIXME: *HOWEVER* it should have lesser priority than the fill binding because it may still be smaller if the fill size is < maxWidth! NSLog("filled maxWidth found") node.constraints["maxWidth"] = node.view.autoSetDimension(.Width, toSize: CGFloat(maxWidth)) } // NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // // experimental (we need to keep a maxWidth inside a filled view contained to that filled view, at a higher priority than typical view containment) // // FIXME: we might want to move this to postprocess so it can bind to the parent view properly // node.view.autoPinEdgeToSuperviewEdge(.Left, withInset: CGFloat(node.leftInset)) // node.view.autoPinEdgeToSuperviewEdge(.Right, withInset: CGFloat(node.rightInset)) // } } else { NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // these have to be higher priority than the normal and fill binding to parent edges node.constraints["maxWidth"] = node.view.autoSetDimension(.Width, toSize: CGFloat(maxWidth), relation: .LessThanOrEqual) } } return .Handled } else { removeConstraint("maxWidth", fromNode: node) } } if attribute == "height" || attribute == nil { if let height = node.height { // if !Layout.keywords.contains(stringValue) { // TODO: add support for height identifiers NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { node.constraints["height"] = node.view.autoSetDimension(.Height, toSize: CGFloat(height)).autoIdentify("height") } // } return .Handled } else { removeConstraint("height", fromNode: node) } } if attribute == "minHeight" || attribute == nil { if let minHeight = node.minHeight { NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { node.constraints["minHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(minHeight), relation: .GreaterThanOrEqual).autoIdentify("minHeight") } NSLayoutConstraint.autoSetPriority(50) {//test node.view.autoSetDimension(.Height, toSize: CGFloat(minHeight)).autoIdentify("minHeight") // FIXME: verify that it's safe to use the same identifier for two constraints!! we need to be able to delete them all } return .Handled } else { removeConstraint("minHeight", fromNode: node) } } if attribute == "maxHeight" || attribute == nil { if let maxHeight = node.maxHeight { NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // these have to be higher priority than the normal and fill binding to parent edges if node.isOtherwiseFilledAlongAxis(.Vertical) { // a maxWidth that is filled is equal to an explicit width NSLog("filled maxHeight found") node.constraints["maxHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(maxHeight)) } else { node.constraints["maxHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(maxHeight), relation: .LessThanOrEqual) } } return .Handled } else { removeConstraint("maxHeight", fromNode: node) } } return .NotHandled } public override func processContents(node: GravityNode) -> GravityResult { // public override func addChild(node: GravityNode, child: GravityNode) -> GravityResult { if !node.viewIsInstantiated { return .NotHandled // no default child handling if we don't have a valid view } // TODO: we may be better off actually setting a z-index on the views; this needs to be computed // we have to do a manual fucking insertion sort here, jesus gawd what the fuck swift?!! no stable sort in version 2.0 of a language??? how is that even remotely acceptable?? // because, you know, i enjoy wasting my time writing sort algorithms! var sortedChildren = [GravityNode]() for childNode in node.childNodes { var handled = false for i in 0 ..< sortedChildren.count { if sortedChildren[i].zIndex > childNode.zIndex { sortedChildren.insert(childNode, atIndex: i) handled = true break } } if !handled { sortedChildren.append(childNode) } } // i'm actually thinking this might make the most sense all in one place in postprocess for childNode in sortedChildren { assert(!childNode.unprocessed) node.view.addSubview(childNode.view) // recurse? assert(childNode.view.superview != nil) // let leftInset = CGFloat(node.leftMargin + node.leftPadding) // let rightInset = CGFloat(node.rightMargin + node.rightPadding) NSLayoutConstraint.autoSetPriority(GravityPriority.Gravity) { switch childNode.gravity.horizontal { case .Left: childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(childNode.leftInset)) break case .Center: let constraint = childNode.view.autoAlignAxisToSuperviewAxis(ALAxis.Vertical) constraint.constant = CGFloat(childNode.rightInset - childNode.leftInset); // test (not working) break case .Right: childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(childNode.rightInset)) break default: break } switch childNode.gravity.vertical { case .Top: childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(childNode.topInset)) break case .Middle: childNode.view.autoAlignAxisToSuperviewAxis(ALAxis.Horizontal) break case .Bottom: childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(childNode.bottomInset)) break default: break } } } return .Handled } public override func postprocessNode(node: GravityNode) { // FIXME: put widthIdentifiers back in here somewhere if let superview = node.view.superview { if (superview as? UIStackView)?.axis != .Horizontal { // we are not inside a stack view (of the same axis) // TODO: what priority should these be? // we need to make a special exception for UIScrollView and potentially others. should we move this back into a default handler/handleChildNodes? // FIXME: fix // NSLayoutConstraint.autoSetPriority(200 - Float(node.recursiveDepth)) { // node.view.autoMatchDimension(.Width, toDimension: .Width, ofView: superview, withOffset: 0, relation: .Equal) // } var priority = GravityPriority.ViewContainment + Float(node.recursiveDepth) if node.isDivergentAlongAxis(.Horizontal) { priority = 200 + Float(node.recursiveDepth) } NSLayoutConstraint.autoSetPriority(priority) { node.constraints["view-left"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(node.leftInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-left") node.constraints["view-right"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(node.rightInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-right") } } if (superview as? UIStackView)?.axis != .Vertical { // we are not inside a stack view (of the same axis) // FIXME: reenable this when we get horizontal working: // node.view.autoMatchDimension(.Height, toDimension: .Height, ofView: node.parentNode!.view, withOffset: 0, relation: .LessThanOrEqual) var priority = GravityPriority.ViewContainment + Float(node.recursiveDepth) if node.isDivergentAlongAxis(.Vertical) { priority = 200 + Float(node.recursiveDepth) } NSLayoutConstraint.autoSetPriority(priority) { node.constraints["view-top"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(node.topInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-top") node.constraints["view-bottom"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(node.bottomInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-bottom") } } // minWidth, etc. should probably be higher priority than these so they can override fill size if node.isFilledAlongAxis(.Horizontal) { node.view.setContentHuggingPriority(GravityPriority.FillSizeHugging, forAxis: .Horizontal) if (superview as? UIStackView)?.axis != .Horizontal { NSLayoutConstraint.autoSetPriority(GravityPriority.FillSize + Float(node.recursiveDepth)) { // i recently changed this from - to +; i didn't think it through but it solved an ambiguous layout problem with InventoryCell // node.view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: superview) node.constraints["fill-left"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(node.leftInset)).autoIdentify("gravity-fill-left") // leading? node.constraints["fill-right"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(node.rightInset)).autoIdentify("gravity-fill-right") // trailing? } } } if node.isFilledAlongAxis(.Vertical) { // should this be otherwise? one of these is wrong node.view.setContentHuggingPriority(GravityPriority.FillSizeHugging, forAxis: .Vertical) if (superview as? UIStackView)?.axis != .Vertical { NSLayoutConstraint.autoSetPriority(GravityPriority.FillSize + Float(node.recursiveDepth)) { // node.view.autoMatchDimension(ALDimension.Height, toDimension: ALDimension.Height, ofView: superview) node.constraints["fill-top"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(node.topInset)).autoIdentify("gravity-fill-top") node.constraints["fill-bottom"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(node.topInset)).autoIdentify("gravity-fill-bottom") } } } } else { NSLog("superview nil") } // do we need/want to set content hugging if superview is nil? } // public override func postprocessDocument(document: GravityDocument) { // NSLog("postprocessDocument: \(document.node.nodeName)") // // var widthIdentifiers = [String: GravityNode]() // for node in document.node { // if let width = node["width"]?.stringValue { // let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet // if width.rangeOfCharacterFromSet(charset) != nil { // if let archetype = widthIdentifiers[width] { // NSLog("Matching dimension of \(unsafeAddressOf(node)) to \(unsafeAddressOf(archetype)).") // // TODO: add a gravity priority // node.view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: archetype.view) // } else { // widthIdentifiers[width] = node // } // } // } // } // for (identifier, nodes) in widthIdentifiers { // let first = nodes[0] // for var i = 1; i < nodes.count; i++ { // // priority?? also we need to add a constraint (but what should its identifier be?) // NSLog("Matching dimension of \(unsafeAddressOf(nodes[i])) to \(unsafeAddressOf(first)).") // nodes[i].view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: first.view) // } // } // } } } public struct GravityDirection { var horizontal = Horizontal.Inherit var vertical = Vertical.Inherit public enum Horizontal: Int { case Inherit = 0 case Left case Right case Center } public enum Vertical: Int { case Inherit = 0 case Top case Bottom case Middle } // these let you shortcut the Horizontal and Vertical enums and say e.g. GravityDirection.Center public static let Left = Horizontal.Left public static let Right = Horizontal.Right public static let Center = Horizontal.Center public static let Top = Vertical.Top public static let Bottom = Vertical.Bottom public static let Middle = Vertical.Middle init() { self.horizontal = .Inherit self.vertical = .Inherit } init(horizontal: Horizontal, vertical: Vertical) { self.horizontal = horizontal self.vertical = vertical } init?(_ stringValue: String?) { guard let stringValue = stringValue else { return nil } let valueParts = stringValue.lowercaseString.componentsSeparatedByString(" ") if valueParts.contains("left") { horizontal = .Left } else if valueParts.contains("center") { horizontal = .Center } else if valueParts.contains("right") { horizontal = .Right } if valueParts.contains("top") { vertical = .Top } else if valueParts.contains("middle") { vertical = .Middle } else if valueParts.contains("bottom") { vertical = .Bottom } } } @available(iOS 9.0, *) extension UIView { public func grav_alignmentRectInsets() -> UIEdgeInsets { // get { var insets = self.grav_alignmentRectInsets() if let node = self.gravityNode { insets = UIEdgeInsetsMake(insets.top - CGFloat(node.topMargin), insets.left - CGFloat(node.leftMargin), insets.bottom - CGFloat(node.bottomMargin), insets.right - CGFloat(node.rightMargin)) } return insets // } } public func grav_didMoveToSuperview() { grav_didMoveToSuperview() if let gravityNode = gravityNode { if gravityNode.parentNode != nil { self.translatesAutoresizingMaskIntoConstraints = false // exp. } gravityNode.postprocess() } } } @available(iOS 9.0, *) extension GravityNode { // MARK: Debugging internal var leftInset: Float { get { return (parentNode?.leftMargin ?? 0) + (parentNode?.leftPadding ?? 0) } } internal var topInset: Float { get { return (parentNode?.topMargin ?? 0) + (parentNode?.topPadding ?? 0) } } internal var rightInset: Float { get { return (parentNode?.rightMargin ?? 0) + (parentNode?.rightPadding ?? 0) } } internal var bottomInset: Float { get { return (parentNode?.bottomMargin ?? 0) + (parentNode?.bottomPadding ?? 0) } } // MARK: Public public var gravity: GravityDirection { get { var gravity = GravityDirection(self["gravity"]?.stringValue) ?? GravityDirection() if gravity.horizontal == .Inherit { gravity.horizontal = parentNode?.gravity.horizontal ?? .Center } if gravity.vertical == .Inherit { gravity.vertical = parentNode?.gravity.vertical ?? .Middle } return gravity } } public var width: Float? { get { return self["width"]?.floatValue // verify this is nil for a string, also test "123test" etc. } } public var height: Float? { get { return self["height"]?.floatValue } } public var minWidth: Float? { get { return self["minWidth"]?.floatValue } } public var maxWidth: Float? { get { return self["maxWidth"]?.floatValue } } public var minHeight: Float? { get { return self["minHeight"]?.floatValue } } public var maxHeight: Float? { get { return self["maxHeight"]?.floatValue } } public var margin: Float { get { return self["margin"]?.floatValue ?? 0 } } public var leftMargin: Float { get { return self["leftMargin"]?.floatValue ?? self.margin } } public var topMargin: Float { get { return self["topMargin"]?.floatValue ?? self.margin } } public var rightMargin: Float { get { return self["rightMargin"]?.floatValue ?? self.margin } } public var bottomMargin: Float { get { return self["bottomMargin"]?.floatValue ?? self.margin } } public var padding: Float { get { return self["padding"]?.floatValue ?? 0 } } public var leftPadding: Float { get { return self["leftPadding"]?.floatValue ?? self.padding } } public var topPadding: Float { get { return self["topPadding"]?.floatValue ?? self.padding } } public var rightPadding: Float { get { return self["rightPadding"]?.floatValue ?? self.padding } } public var bottomPadding: Float { get { return self["bottomPadding"]?.floatValue ?? self.padding } } public var zIndex: Int { get { return Int(self["zIndex"]?.stringValue ?? "0")! } } internal func isExplicitlySizedAlongAxis(axis: UILayoutConstraintAxis) -> Bool { switch axis { case .Horizontal: if let width = self["width"]?.stringValue { let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet if width.rangeOfCharacterFromSet(charset) == nil { return true } } return false case .Vertical: if let height = self["height"]?.stringValue { let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet if height.rangeOfCharacterFromSet(charset) == nil { return true } } return false } } /// A node is divergent from its parent on an axis if it has the potential that at least one edge of that axis is not bound to its corresponding parent edge. For example, an auto-sized node inside a fixed size node has the potential to be smaller than its container, and is therefore considered divergent. internal func isDivergentAlongAxis(axis: UILayoutConstraintAxis) -> Bool { // make sure there aren't problems caling this when a view is added to its superview but doesn't have its parent node set if view.superview != nil { // assert(parentNode != nil) if parentNode == nil { NSLog("Warning: checking isDivergent superview exists but no parentNode") } } // wtf is this?? // if parentNode != nil && parentNode!.parentNode != nil && document.parentNode != nil { // return true // } guard let parentNode = parentNode else { return false } if self.recursiveDepth == 1 { // the root node return true // leaving in for now } if parentNode.isFilledAlongAxis(axis) { return true } else if self.isFilledAlongAxis(axis) { return false } else if parentNode.isExplicitlySizedAlongAxis(axis) { return true } // should we allow plugins to override this definition? depending on UIStackView here doesn't feel right switch axis { case .Horizontal: if (parentNode.view as? UIStackView)?.axis == .Vertical { return true } if parentNode["minWidth"] != nil { return true } case .Vertical: if (parentNode.view as? UIStackView)?.axis == .Horizontal { return true } if parentNode["minHeight"] != nil { return true } } return false } internal func isFilledAlongAxis(axis: UILayoutConstraintAxis) -> Bool { if !isOtherwiseFilledAlongAxis(axis) { return false } switch axis { case .Horizontal: return self["maxWidth"] == nil case .Vertical: return self["maxHeight"] == nil } } internal func isOtherwiseFilledAlongAxis(axis: UILayoutConstraintAxis) -> Bool { switch axis { case .Horizontal: // if self["maxWidth"] != nil { // we could verify that it is numeric, but i can't think of a concise way to do that // // even if we have width="fill", if there's a maxWidth, that still just equals width // return false // } if let width = self["width"]?.stringValue { if width == "fill" { // are there any other negation cases? return true } let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet if width.rangeOfCharacterFromSet(charset) == nil { return false } } break case .Vertical: // if self["maxHeight"] != nil { // we could verify that it is numeric, but i can't think of a concise way to do that // // even if we have width="fill", if there's a maxWidth, that still just equals width // return false // } if let height = self["height"]?.stringValue { if height == "fill" { // are there any other negation cases? return true } let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet if height.rangeOfCharacterFromSet(charset) == nil { return false } } break } for childNode in childNodes { if childNode.isFilledAlongAxis(axis) { return true } } return false } }
mit
63ceaf07666ffc4dcf6b8f57c5ac8a79
34.340852
306
0.686571
3.990519
false
false
false
false
keyeMyria/edx-app-ios
Source/CourseOutlineHeaderCell.swift
4
1891
// // CourseOutlineHeaderCell.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit class CourseOutlineHeaderCell : UITableViewHeaderFooterView { static let identifier = "CourseOutlineHeaderCellIdentifier" let headerFontStyle = OEXTextStyle(weight: .SemiBold, size: .XSmall, color : OEXStyles.sharedStyles().neutralBase()) let headerLabel = UILabel() let horizontalTopLine = UIView() var block : CourseBlock? { didSet { headerLabel.attributedText = headerFontStyle.attributedStringWithText(block?.name) } } override init(frame: CGRect) { super.init(frame: frame) } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) addSubviews() setStyles() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Helper Methods private func addSubviews(){ addSubview(headerLabel) addSubview(horizontalTopLine) } private func setStyles(){ //Using CGRectZero size because the backgroundView automatically resizes. backgroundView = UIView(frame: CGRectZero) backgroundView?.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT() horizontalTopLine.backgroundColor = OEXStyles.sharedStyles().neutralBase() } // Skip autolayout for performance reasons override func layoutSubviews() { super.layoutSubviews() let margin = OEXStyles.sharedStyles().standardHorizontalMargin() - 5 self.headerLabel.frame = UIEdgeInsetsInsetRect(self.bounds, UIEdgeInsetsMake(0, margin, 0, margin)) horizontalTopLine.frame = CGRectMake(0, 0, self.bounds.size.width, OEXStyles.dividerSize()) } }
apache-2.0
8c7826e80b637b88dbd0fcacfbd0fa88
30.533333
120
0.682179
5.138587
false
false
false
false
johnno1962d/swift
test/expr/cast/as_coerce.swift
3
3849
// RUN: %target-parse-verify-swift // Test the use of 'as' for type coercion (which requires no checking). @objc protocol P1 { func foo() } class A : P1 { @objc func foo() { } } @objc class B : A { func bar() { } } func doFoo() {} func test_coercion(_ a: A, b: B) { // Coercion to a protocol type let x = a as P1 x.foo() // Coercion to a superclass type let y = b as A y.foo() } class C : B { } class D : C { } func prefer_coercion(_ c: inout C) { let d = c as! D c = d } // Coerce literals var i32 = 1 as Int32 var i8 = -1 as Int8 // Coerce to a superclass with generic parameter inference class C1<T> { func f(_ x: T) { } } class C2<T> : C1<Int> { } var c2 = C2<()>() var c1 = c2 as C1 c1.f(5) @objc protocol P {} class CC : P {} let cc: Any = CC() if cc is P { doFoo() } if let p = cc as? P { doFoo() } // Test that 'as?' coercion fails. let strImplicitOpt: String! = nil strImplicitOpt as? String // expected-warning{{conditional cast from 'String!' to 'String' always succeeds}} class C3 {} class C4 : C3 {} class C5 {} var c: AnyObject = C3() if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}} // Only suggest replacing 'as' with 'as!' if it would fix the error. C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}} C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}} // Diagnostic shouldn't include @lvalue in type of c3. var c3 = C3() c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}} // <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions 1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}} 1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} ["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}} ([1, 2, 1.0], 1) as ([String], Int) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} [[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} (1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}} (1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} (1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} [1] as! [String] // expected-error{{'[Int]' is not convertible to '[String]'}} [(1, (1, 1))] as! [(Int, (String, Int))] // expected-error{{'[(Int, (Int, Int))]' is not convertible to '[(Int, (String, Int))]'}} // <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{9-20=}} // <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its func f(_ x : String) {} f("what" as Any as String) // expected-error{{'Any' (aka 'protocol<>') is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}} f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} // <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests let s : AnyObject = C3() s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
apache-2.0
9ef2ba8e20e52ae455db885bd73f61de
36.009615
163
0.656274
3.152334
false
false
false
false
fmscode/DrawView
Example-Swift/Example-Swift/ViewController.swift
1
3171
// // ViewController.swift // Example-Swift // // Created by Frank Michael on 12/24/14. // Copyright (c) 2014 Frank Michael Sanchez. All rights reserved. // import UIKit import AssetsLibrary class ViewController: UIViewController { @IBOutlet weak var mainDrawView: DrawView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.mainDrawView.drawingMode = .Signature // Need to do a refresh since the view has adapted to the current device size. self.mainDrawView.refreshCanvas() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) self.mainDrawView.refreshCanvas() } // MARK: Class Actions @IBAction func undo(sender: AnyObject) { self.mainDrawView.undoLastPath() } @IBAction func signatureMode(sender: AnyObject) { if self.mainDrawView.drawingMode == .Signature { self.mainDrawView.drawingMode = .Default }else{ self.mainDrawView.drawingMode = .Signature } } @IBAction func saveCanvas(sender: AnyObject) { let saveAction = UIAlertController(title: "Draw View Saving", message: "", preferredStyle: .ActionSheet) saveAction.addAction(UIAlertAction(title: "Save to Camera Roll", style: .Default, handler: { (action: UIAlertAction!) -> Void in let canvasImage = self.mainDrawView.imageRepresentation() let cameraRoll = ALAssetsLibrary() cameraRoll.writeImageToSavedPhotosAlbum(canvasImage.CGImage, orientation: .Up, completionBlock: { (assetURL: NSURL!, error: NSError!) -> Void in NSLog("\(assetURL)") NSLog("\(error)") }) })) saveAction.addAction(UIAlertAction(title: "Save as UIImage", style: .Default, handler: { (action: UIAlertAction!) -> Void in let canvasImage = self.mainDrawView.imageRepresentation() NSLog("\(canvasImage)") })) saveAction.addAction(UIAlertAction(title: "Save as UIBezierPath", style: .Default, handler: { (action: UIAlertAction!) -> Void in let canvasPath = self.mainDrawView.bezierPathRepresentation() NSLog("\(canvasPath)") })) saveAction.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(saveAction, animated: true, completion: nil) } @IBAction func animate(sender: AnyObject) { self.mainDrawView.animateCanvas() } // For iOS 7 support override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { self.mainDrawView.refreshCanvas() } // For iOS 8 support override func viewDidLayoutSubviews() { self.mainDrawView.refreshCanvas() } }
mit
62e38a8f07b2f4ab7814aa2c867c0655
39.139241
156
0.671397
5.041335
false
false
false
false
neoneye/SwiftyFORM
Source/Util/DebugViewController.swift
1
2858
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import WebKit public enum WhatToShow { case json(json: Data) case text(text: String) case url(url: URL) } /// Present various types of data: json, plain text, webpage /// /// The data is shown in a webview. /// /// This is only supposed to be used during development, /// as a quick way to inspect data. /// /// Usage: /// /// DebugViewController.showURL(self, url: URL(string: "http://www.google.com")!) /// DebugViewController.showText(self, text: "hello world") /// public class DebugViewController: UIViewController { public let dismissBlock: () -> Void public let whatToShow: WhatToShow public init(dismissBlock: @escaping () -> Void, whatToShow: WhatToShow) { self.dismissBlock = dismissBlock self.whatToShow = whatToShow super.init(nibName: nil, bundle: nil) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public class func showJSON(_ parentViewController: UIViewController, jsonData: Data) { showModally(parentViewController, whatToShow: WhatToShow.json(json: jsonData)) } public class func showText(_ parentViewController: UIViewController, text: String) { showModally(parentViewController, whatToShow: WhatToShow.text(text: text)) } public class func showURL(_ parentViewController: UIViewController, url: URL) { showModally(parentViewController, whatToShow: WhatToShow.url(url: url)) } public class func showModally(_ parentViewController: UIViewController, whatToShow: WhatToShow) { let dismissBlock: () -> Void = { [weak parentViewController] in parentViewController?.dismiss(animated: true, completion: nil) } let vc = DebugViewController(dismissBlock: dismissBlock, whatToShow: whatToShow) let nc = UINavigationController(rootViewController: vc) parentViewController.present(nc, animated: true, completion: nil) } public override func loadView() { let webview = WKWebView() self.view = webview let item = UIBarButtonItem(title: "Dismiss", style: .plain, target: self, action: #selector(DebugViewController.dismissAction(_:))) self.navigationItem.leftBarButtonItem = item switch whatToShow { case let .json(json): let url = URL(string: "http://localhost")! webview.load(json, mimeType: "application/json", characterEncodingName: "utf-8", baseURL: url) self.title = "JSON" case let .text(text): let url = URL(string: "http://localhost")! let data = (text as NSString).data(using: String.Encoding.utf8.rawValue)! webview.load(data, mimeType: "text/plain", characterEncodingName: "utf-8", baseURL: url) self.title = "Text" case let .url(url): let request = URLRequest(url: url) webview.load(request) self.title = "URL" } } @objc func dismissAction(_ sender: AnyObject?) { dismissBlock() } }
mit
c840c02cc1fc823461308bd0167d88fd
31.477273
133
0.727432
3.78543
false
false
false
false
manumax/TinyRobotWars
TinyRobotWars/Core/AST.swift
1
4311
// // AST.swift // TinyRobotWars // // Created by Manuele Mion on 21/02/2017. // Copyright © 2017 manumax. All rights reserved. // import Foundation /** Grammar: <statement> ::= <to> <to> ::= <expr> ('TO' <register>)+ <expr> ::= <term> ((<plus> | <minus>) <expr>)* <term> ::= <factor> ((<mul> | <div>) <factor>)* <factor> ::= (<plus> | <minus>) <factor> | <register> | <number> <number> ::= ([0-9])+ <plus> ::= '+' <minus> ::= '-' <mult> ::= '*' <div> ::= '/' <register> ::= [A..Z] | 'AIM' | 'SHOOT' | 'RADAR' | 'DAMAGE' | 'SPEEDX' | 'SPEEDY' | 'RANDOM' | 'INDEX' */ enum Node { case number(Int) case register(String) indirect case unaryOp(Operator, Node) indirect case binaryOp(Operator, Node, Node) indirect case to(Node, [Node]) } extension Node: Equatable { static func ==(lhs: Node, rhs: Node) -> Bool { switch (lhs, rhs) { case let (.number(l), .number(r)): return l == r case let (.register(l), .register(r)): return l == r case let (.unaryOp(lop, lnode), .unaryOp(rop, rnode)): return lop == rop && lnode == rnode case let (.binaryOp(lop, llnode, lrnode), .binaryOp(rop, rlnode, rrnode)): return lop == rop && llnode == rlnode && lrnode == rrnode case let (.to(lnode, lnodes), .to(rnode, rnodes)): return lnode == rnode && lnodes == rnodes default: return false } } } protocol Visitor { func visit(_ node: Node) } // MARK: - Parser enum ParserError: Error { case invalidSyntaxError case unexpectedTokenError } class Parser { private let lexer: Lexer private var currentToken: Token? init(withLexer lexer: Lexer) { self.lexer = lexer self.currentToken = lexer.next() } func eat() { self.currentToken = self.lexer.next() } func factor() throws -> Node { // <factor> ::= (<plus> | <minus>) <factor> | <number> guard let token = self.currentToken else { throw ParserError.unexpectedTokenError } switch token { case .op(.plus): fallthrough case .op(.minus): if case .op(let op) = token { self.eat() return .unaryOp(op, try self.factor()) } throw ParserError.invalidSyntaxError case .number(let value): self.eat() return .number(value) case .register(let name): self.eat() return .register(name) default: throw ParserError.unexpectedTokenError } } func term() throws -> Node { // <term> ::= <factor> ((<mul> | <div>) <factor>)* let node = try self.factor() guard let token = self.currentToken, case let Token.op(op) = token else { return node } switch op { case .times: fallthrough case .divide: self.eat() return .binaryOp(op, node, try self.factor()) default: return node } } func expr() throws -> Node { // <expr> ::= <term> ((<plus> | <minus>) <term>)* let node = try self.term() guard let token = self.currentToken, case let Token.op(op) = token else { return node } switch op { case .plus: fallthrough case .minus: self.eat() return .binaryOp(op, node, try self.expr()) default: return node } } func statement() throws -> Node { return try to() } func to() throws -> Node { let expr = try self.expr() var registers = [Node]() while let token = self.currentToken, case .to = token { self.eat() if let token = self.currentToken, case let .register(name) = token { self.eat() registers.append(Node.register(name)) } else { throw ParserError.unexpectedTokenError } } if registers.count == 0 { return expr } return .to(expr, registers) } func parse() throws -> Node { return try self.statement() } }
mit
7971f8d5cc4614b4cb70ea4da27fd214
24.963855
104
0.507889
3.911071
false
false
false
false
saeta/penguin
Sources/PenguinParallel/Parallel/Array+ParallelSequence.swift
1
3434
// Copyright 2020 Penguin Authors // // 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. fileprivate func buffer_psum<T: Numeric>( _ pool: ComputeThreadPool, _ buff: UnsafeBufferPointer<T>, _ level: Int ) -> T { if level == 0 || buff.count < 1000 { // TODO: tune this constant return buff.reduce(0, +) } let middle = buff.count / 2 let lhs = buff[0..<middle] let rhs = buff[middle..<buff.count] var lhsSum = T.zero var rhsSum = T.zero pool.join( { lhsSum = buffer_psum(pool, UnsafeBufferPointer(rebasing: lhs), level - 1) }, { rhsSum = buffer_psum(pool, UnsafeBufferPointer(rebasing: rhs), level - 1) }) return lhsSum + rhsSum } extension Array where Element: Numeric { /// Computes the sum of all the elements in parallel. public func pSum() -> Element { withUnsafeBufferPointer { buff in let pool = ComputeThreadPools.global return buffer_psum( pool, // TODO: Take defaulted-arg & thread local to allow for composition! buff, computeRecursiveDepth(procCount: pool.maxParallelism) + 2) // Sub-divide into quarters-per-processor in case of uneven scheduling. } } } fileprivate func buffer_pmap<T, U>( pool: ComputeThreadPool, source: UnsafeBufferPointer<T>, dest: UnsafeMutableBufferPointer<U>, mapFunc: (T) -> U ) { assert(source.count == dest.count) var threshold = 1000 // TODO: tune this constant assert( { threshold = 10 return true }(), "Hacky workaround for no #if OPT.") if source.count < threshold { for i in 0..<source.count { dest[i] = mapFunc(source[i]) } return } let middle = source.count / 2 let srcLower = source[0..<middle] let dstLower = dest[0..<middle] let srcUpper = source[middle..<source.count] let dstUpper = dest[middle..<source.count] pool.join( { buffer_pmap( pool: pool, source: UnsafeBufferPointer(rebasing: srcLower), dest: UnsafeMutableBufferPointer(rebasing: dstLower), mapFunc: mapFunc) }, { buffer_pmap( pool: pool, source: UnsafeBufferPointer(rebasing: srcUpper), dest: UnsafeMutableBufferPointer(rebasing: dstUpper), mapFunc: mapFunc) }) } extension Array { /// Makes a new array, where every element in the new array is `f(self[i])` for all `i` in `0..<count`. /// /// Note: this function applies `f` in parallel across all available threads on the local machine. public func pMap<T>(_ f: (Element) -> T) -> [T] { // TODO: support throwing. withUnsafeBufferPointer { selfBuffer in [T](unsafeUninitializedCapacity: count) { destBuffer, cnt in cnt = count buffer_pmap( pool: ComputeThreadPools.global, // TODO: Take a defaulted-arg / pull from threadlocal for better composition! source: selfBuffer, dest: destBuffer, mapFunc: f ) } } } }
apache-2.0
8c305fb0aaecc617e3e42bba95748f1e
30.504587
139
0.655504
3.929062
false
false
false
false
dduan/swift
test/SourceKit/CodeComplete/complete_sort_order.swift
1
4364
func foo(a a: String) {} func foo(a a: Int) {} func foo(b b: Int) {} func test() { let x = 1 } // RUN: %sourcekitd-test -req=complete -req-opts=hidelowpriority=0 -pos=7:1 %s -- %s > %t.orig // RUN: FileCheck -check-prefix=NAME %s < %t.orig // Make sure the order is as below, foo(Int) should come before foo(String). // NAME: key.description: "#column" // NAME: key.description: "AbsoluteValuable" // NAME: key.description: "foo(a: Int)" // NAME-NOT: key.description // NAME: key.description: "foo(a: String)" // NAME-NOT: key.description // NAME: key.description: "foo(b: Int)" // NAME: key.description: "test()" // NAME: key.description: "x" // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=hidelowpriority=0,hideunderscores=0 %s -- %s > %t.default // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=0,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.on // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=1,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.off // RUN: FileCheck -check-prefix=CONTEXT %s < %t.default // RUN: FileCheck -check-prefix=NAME %s < %t.off // FIXME: rdar://problem/20109989 non-deterministic sort order // RUN-disabled: diff %t.on %t.default // RUN: FileCheck -check-prefix=CONTEXT %s < %t.on // CONTEXT: key.kind: source.lang.swift.decl // CONTEXT-NEXT: key.name: "x" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(b:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "test()" // CONTEXT: key.name: "#column" // CONTEXT: key.name: "AbsoluteValuable" // RUN: %complete-test -tok=STMT_0 %s | FileCheck %s -check-prefix=STMT func test1() { #^STMT_0^# } // STMT: let // STMT: var // STMT: if // STMT: for // STMT: while // STMT: func // STMT: foo(a: Int) // RUN: %complete-test -tok=STMT_1 %s | FileCheck %s -check-prefix=STMT_1 func test5() { var retLocal: Int #^STMT_1,r,ret,retur,return^# } // STMT_1-LABEL: Results for filterText: r [ // STMT_1-NEXT: retLocal // STMT_1-NEXT: repeat // STMT_1-NEXT: return // STMT_1-NEXT: required // STMT_1: ] // STMT_1-LABEL: Results for filterText: ret [ // STMT_1-NEXT: retLocal // STMT_1-NEXT: return // STMT_1-NEXT: repeat // STMT_1: ] // STMT_1-LABEL: Results for filterText: retur [ // STMT_1-NEXT: return // STMT_1: ] // STMT_1-LABEL: Results for filterText: return [ // STMT_1-NEXT: return // STMT_1: ] // RUN: %complete-test -top=0 -tok=EXPR_0 %s | FileCheck %s -check-prefix=EXPR func test2() { (#^EXPR_0^#) } // EXPR: 0 // EXPR: "abc" // EXPR: true // EXPR: false // EXPR: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#] // EXPR: [#Image(imageLiteral: String)#] // EXPR: [values] // EXPR: [key: value] // EXPR: (values) // EXPR: nil // EXPR: foo(a: Int) // Top 1 // RUN: %complete-test -top=1 -tok=EXPR_1 %s | FileCheck %s -check-prefix=EXPR_TOP_1 func test3(x: Int) { let y = x let z = x let zzz = x (#^EXPR_1^#) } // EXPR_TOP_1: x // EXPR_TOP_1: 0 // EXPR_TOP_1: "abc" // EXPR_TOP_1: true // EXPR_TOP_1: false // EXPR_TOP_1: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#] // EXPR_TOP_1: [#Image(imageLiteral: String)#] // EXPR_TOP_1: [values] // EXPR_TOP_1: [key: value] // EXPR_TOP_1: (values) // EXPR_TOP_1: nil // EXPR_TOP_1: y // EXPR_TOP_1: z // EXPR_TOP_1: zzz // Top 3 // RUN: %complete-test -top=3 -tok=EXPR_2 %s | FileCheck %s -check-prefix=EXPR_TOP_3 func test4(x: Int) { let y = x let z = x let zzz = x (#^EXPR_2^#) } // EXPR_TOP_3: x // EXPR_TOP_3: y // EXPR_TOP_3: z // EXPR_TOP_3: 0 // EXPR_TOP_3: "abc" // EXPR_TOP_3: true // EXPR_TOP_3: false // EXPR_TOP_3: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#] // EXPR_TOP_3: [#Image(imageLiteral: String)#] // EXPR_TOP_3: [values] // EXPR_TOP_3: [key: value] // EXPR_TOP_3: (values) // EXPR_TOP_3: nil // EXPR_TOP_3: zzz // Top 3 with type matching // RUN: %complete-test -top=3 -tok=EXPR_3 %s | FileCheck %s -check-prefix=EXPR_TOP_3_TYPE_MATCH func test4(x: Int) { let y: String = "" let z: String = y let zzz = x let bar: Int = #^EXPR_3^# } // EXPR_TOP_3_TYPE_MATCH: x // EXPR_TOP_3_TYPE_MATCH: zzz // EXPR_TOP_3_TYPE_MATCH: 0 // EXPR_TOP_3_TYPE_MATCH: y // EXPR_TOP_3_TYPE_MATCH: z
apache-2.0
1f7e0792e8a752fa45ad5860cb6d52af
27.154839
130
0.628093
2.462754
false
true
false
false
nProdanov/FuelCalculator
Fuel economy smart calc./Fuel economy smart calc./FireBaseGasStationData.swift
1
2049
// // FireBaseGasStationData.swift // Fuel economy smart calc. // // Created by Nikolay Prodanow on 3/27/17. // Copyright © 2017 Nikolay Prodanow. All rights reserved. // import Foundation import Firebase import FirebaseDatabase class FireBaseGasStationData: BaseRemoteGasStationData { private var delegate: RemoteGasStationDataDelegate? private var dbReference: FIRDatabaseReference! init(){ if FIRApp.defaultApp() == nil { FIRApp.configure() } dbReference = FIRDatabase.database().reference() } func getAll() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.dbReference .child(Constants.GasStationDbChild) .observeSingleEvent(of: .value, with: {(snapshop) in let gasStationsDict = snapshop.value as! [NSDictionary] let gasStations = gasStationsDict.map { GasStation.fromDict($0) } DispatchQueue.main.async { self?.delegate?.didReceiveRemoteGasStations(gasStations) } }) {error in self?.delegate?.didReceiveRemoteError(error: error) } } } func getAllCount() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.dbReference .child(Constants.GasStationDbChild) .observeSingleEvent(of: .value, with: {(snapshop) in DispatchQueue.main.async { self?.delegate?.didReceiveRemoteGasStationsCount((snapshop.value as! [Any]).count) } }) {error in self?.delegate?.didReceiveRemoteError(error: error) } } } func setDelegate(_ delegate: RemoteGasStationDataDelegate) { self.delegate = delegate } private struct Constants { static let GasStationDbChild = "gasStations" } }
mit
3099b0e8266c41e6de960fdb4ed67a3f
30.030303
106
0.573242
5.031941
false
false
false
false
jtbandes/swift
test/Parse/ConditionalCompilation/can_import.swift
19
2262
// RUN: %target-typecheck-verify-swift -parse-as-library // RUN: %target-typecheck-verify-swift -D WITH_PERFORM -primary-file %s %S/Inputs/can_import_nonprimary_file.swift // REQUIRES: can_import public struct LibraryDependentBool : ExpressibleByBooleanLiteral { #if canImport(Swift) var _description: String #endif public let magicConstant: Int = { #if canImport(Swift) return 42 #else return "" // Type error #endif }() #if canImport(AppKit) || (canImport(UIKit) && (arch(i386) || arch(arm))) // On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char". var _value: Int8 init(_ value: Int8) { self._value = value #if canImport(Swift) self._description = "\(value)" #endif } public init(_ value: Bool) { #if canImport(Swift) self._description = value ? "YES" : "NO" #endif self._value = value ? 1 : 0 } #else // Everywhere else it is C/C++'s "Bool" var _value: Bool public init(_ value: Bool) { #if canImport(Swift) self._description = value ? "YES" : "NO" #endif self._value = value } #endif /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { #if canImport(AppKit) || (canImport(UIKit) && (arch(i386) || arch(arm))) return _value != 0 #else return _value #endif } /// Create an instance initialized to `value`. public init(booleanLiteral value: Bool) { self.init(value) } func withBoolValue(_ f : (Bool) -> ()) { return f(self.boolValue) } } #if canImport(Swift) func topLevelFunction() { LibraryDependentBool(true).withBoolValue { b in let value: String #if canImport(Swiftz) #if canImport(ReactiveCocoa) #if canImport(Darwin) value = NSObject() // Type error #endif #endif #else value = "" #endif print(value) } } #else enum LibraryDependentBool {} // This should not happen #endif #if WITH_PERFORM func performPerOS() -> Int { let value: Int #if canImport(Argo) value = "" // Type error #else value = 42 #endif return performFoo(withX: value, andY: value) } #endif let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(OSX) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }()
apache-2.0
01fbb66aced42c607a080193a249ad0d
18.842105
114
0.656057
3.245337
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Protocols/PedometerDataProvider.swift
1
2255
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import Foundation enum PedometerDataProviderError: Error { case quantityType case resultsNotPresent case sharingDenied case sharingNotAuthorized case unknown } struct PedometerData { let date: Date let count: Double } extension Array where Element == PedometerData { var indexOfToday: Int? { firstIndex { $0.date.endOfDay == Date().endOfDay } } } typealias PedometerDataCompletion = (Result<[PedometerData], PedometerDataProviderError>) -> Void protocol PedometerDataProvider { typealias Error = PedometerDataProviderError func retrieveStepCount(forInterval interval: DateInterval, _ completion: @escaping PedometerDataCompletion) func retrieveDistance(forInterval interval: DateInterval, _ completion: @escaping PedometerDataCompletion) }
bsd-3-clause
e33ebc34526dce5d4242421b2e75b5e2
37.862069
109
0.771517
4.715481
false
false
false
false
Josscii/iOS-Demos
TableViewIssueDemo/TableViewDemo/update/ViewController2.swift
1
3325
// // ViewController2.swift // TableViewDemo // // Created by josscii on 2018/2/7. // Copyright © 2018年 josscii. All rights reserved. // import UIKit /* 测试 beginUpdates / endUpdates 和 tableView reload/delete/insert 的关系 */ class ViewController2: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self tableView.dataSource = self // tableView.rowHeight = 100 tableView.estimatedRowHeight = 44 } var text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题" var more = false var num = 2 @IBAction func change(_ sender: Any) { more = !more if more { text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题,但也有一批人因为这个功能,系统出现了这样那样的问题,甚至影响到了正常的使用。当一个功能到了影响效率的时候,就有必要想解决办法了" } else { text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题" } // tableView.beginUpdates() // tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic) // tableView.endUpdates() // UIView.performWithoutAnimation { // tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic) // } // UIView.setAnimationsEnabled(false) // tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic) // UIView.setAnimationsEnabled(true) // tableView.reloadData() /** 对数据进行重新赋值的时候必须 dispatch 到主线程去做,因为这时候可能有其他操作 */ DispatchQueue.main.async { self.num = 1 self.tableView.reloadData() } // tableView.reloadData() tableView.beginUpdates() // tableView.insertRows(at: [IndexPath.init(row: 1, section: 0)], with: .automatic) // tableView.deleteRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic) tableView.endUpdates() /* beginUpdates 和 endUpdates 和 tableView 的动画无关,只是用于将对 tableView 的批量修改 patch */ } } extension ViewController2: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return num } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell cell.titleLabel.text = text return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } }
mit
757df2c9a7ce64d54b1921be648732b6
30.010526
130
0.620163
4.103064
false
false
false
false
WzhGoSky/ZHPlayer
ZHPlayer/ZHPlayer/ZHPlayer/ZHPlayerOperationView.swift
1
8684
// // ZHPlayerOperationView.swift // ZHPlayer // // Created by Hayder on 2017/1/3. // Copyright © 2017年 Hayder. All rights reserved. // 视屏播放时操作的View import UIKit typealias sliderProgressChangedCallBack = (_ sliderProgress: TimeInterval)->() enum screenType{ case fullScreen case smallScreen } class ZHPlayerOperationView: UIView { //滑块是否在拖动 var isSlider: Bool = false //是否隐藏topBar bottomBar 默认暂时不隐藏 var ishiddenOperationBar: Bool = true //是否在滑动 var sliderChanged: sliderProgressChangedCallBack? //目前屏幕状态 是small 还是fullScreen var screenType: screenType = .smallScreen //定时器 fileprivate var timer: Timer? //上面的bar @IBOutlet weak var topBar: UIView! //底部的bar @IBOutlet weak var bottomBar: UIView! //用来点击的View @IBOutlet weak var tapView: UIView! //播放 @IBOutlet weak var play: UIButton! //缩放(旋转) @IBOutlet weak var rotation: UIButton! //当前时间 @IBOutlet weak var currentTime: UILabel! //总时间 @IBOutlet weak var totalTime: UILabel! //缓冲进度 @IBOutlet weak var loadedProgress: UIProgressView! //播放进度 @IBOutlet weak var playProgress: UISlider! //父控件 fileprivate var superView: ZHPlayerView?{ guard let view = self.superview else { return nil } return view as? ZHPlayerView } //MARK:- 创建操作视图 class func operationView() -> ZHPlayerOperationView{ return Bundle.main.loadNibNamed("ZHPlayerOperationView", owner: self, options: nil)?.first as! ZHPlayerOperationView } //1.正在拖动 @IBAction func dragging(_ sender: UISlider) { isSlider = true if sliderChanged != nil { sliderChanged!(TimeInterval(sender.value)) } } //2.手指按下 @IBAction func touchDown(_ sender: UISlider) { superView?.Pause() } //3.手指抬起 @IBAction func touchUp(_ sender: UISlider) { superView?.Play() isSlider = false } //暂停或开始 @IBAction func playorPause(_ sender: UIButton) { play.isSelected = !play.isSelected if play.isSelected == true { superView?.Play() }else { superView?.Pause() } } //旋转屏幕 @IBAction func rotateScreen(_ sender: UIButton) { guard let superView = superView else { return } if screenType == .smallScreen { let height = UIScreen.main.bounds.width let width = UIScreen.main.bounds.height let frame = CGRect(x: (height - width)/2, y: (width - height)/2, width: width, height: height) //全屏状态 screenType = .fullScreen UIView.animate(withDuration: 0.3, animations: { superView.frame = frame superView.transform = CGAffineTransform(rotationAngle: (CGFloat)(M_PI_2)) }) rotation.isSelected = true UIApplication.shared.keyWindow?.addSubview(superView) }else { let orientation = UIDevice.current.orientation if orientation == .portrait { //全屏状态 UIView.animate(withDuration: 0.3, animations: { superView.transform = CGAffineTransform.identity superView.frame = superView.originalFrame }) screenType = .smallScreen superView.originalSuperView?.addSubview(superView) } rotation.isSelected = false } } deinit { removeTimer() NotificationCenter.default.removeObserver(self) } } //MARK:- operationBar的操作 extension ZHPlayerOperationView{ override func awakeFromNib() { super.awakeFromNib() //1.重新设置下slider的thumb图片 self.playProgress.setThumbImage(UIImage(named:"icmpv_thumb_light"), for: .normal) self.playProgress.setThumbImage(UIImage(named:"icmpv_thumb_light"), for: .highlighted) //2.给tapview添加一个手势 //添加手势 let tap = UITapGestureRecognizer(target: self, action: #selector(tap(tap:))) tapView.addGestureRecognizer(tap) //3.添加通知 NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged(noti:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } @objc fileprivate func tap(tap: UITapGestureRecognizer) { //保险起见,添加定时器的之前先移除定时器 removeTimer() //添加定时器 addTimer() handleBar() } //操作handleBar fileprivate func handleBar(){ if ishiddenOperationBar == true { UIView.animate(withDuration: 0.25, animations: { self.topBar.transform = CGAffineTransform(translationX: 0, y: -40) self.bottomBar.transform = CGAffineTransform(translationX: 0, y: 40) }) }else { UIView.animate(withDuration: 0.25, animations: { self.topBar.transform = CGAffineTransform.identity self.bottomBar.transform = CGAffineTransform.identity }) } //操作以后改变标志位的状态 ishiddenOperationBar = !ishiddenOperationBar } } //MARK:- 对定时器的操作方法 extension ZHPlayerOperationView{ ///创建定时器的方法 func addTimer(){ timer = Timer(timeInterval: 6.0, target: self, selector: #selector(hiddenOperationBar), userInfo: nil, repeats: false) RunLoop.main.add(timer!, forMode: .commonModes) } func removeTimer(){ timer?.invalidate() //从运行循环中移除 timer = nil } //隐藏操作的bar @objc private func hiddenOperationBar(){ handleBar() //操作完以后移除定时器 removeTimer() } } //MARK:- 屏幕旋转 extension ZHPlayerOperationView{ @objc fileprivate func orientationChanged(noti: NSNotification){ //1.获取屏幕现在的方向 let orientation = UIDevice.current.orientation switch orientation { case .portrait: guard let superView = superView else { return } if screenType == .fullScreen { screenType = .smallScreen rotation.isSelected = false superView.transform = CGAffineTransform.identity superView.frame = superView.originalFrame } case .landscapeLeft: if screenType == .smallScreen { screenType = .fullScreen rotation.isSelected = true } fullScreenWithOrientation(orientation: orientation) case .landscapeRight: if screenType == .smallScreen { screenType = .fullScreen rotation.isSelected = true } fullScreenWithOrientation(orientation: orientation) default: break } } private func fullScreenWithOrientation(orientation: UIDeviceOrientation) { guard let superView = superView else { return } superView.removeFromSuperview() superView.transform = CGAffineTransform.identity let height = UIScreen.main.bounds.height let width = UIScreen.main.bounds.width superView.frame = CGRect(x: 0, y: 0, width: width, height: height) UIApplication.shared.keyWindow?.addSubview(superView) } }
mit
7e45f84eebf3055b8b010fe9b5f08e01
24.140673
169
0.536309
5.366188
false
false
false
false
ministrycentered/onepassword-app-extension
Demos/App Demo for iOS Swift/App Demo for iOS Swift/RegisterViewController.swift
2
3727
// // RegisterViewController.swift // App Demo for iOS Swift // // Created by Rad Azzouz on 2015-05-14. // Copyright (c) 2015 Agilebits. All rights reserved. // import Foundation class RegisterViewController: UIViewController { @IBOutlet weak var onepasswordButton: UIButton! @IBOutlet weak var firstnameTextField: UITextField! @IBOutlet weak var lastnameTextField: UITextField! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() if let patternImage = UIImage(named: "register-background.png") { self.view.backgroundColor = UIColor(patternImage: patternImage) } onepasswordButton.isHidden = (false == OnePasswordExtension.shared().isAppExtensionAvailable()) } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.default } @IBAction func saveLoginTo1Password(_ sender:AnyObject) { let newLoginDetails:[String: Any] = [ AppExtensionTitleKey: "ACME", AppExtensionUsernameKey: usernameTextField.text ?? "", AppExtensionPasswordKey: passwordTextField.text ?? "", AppExtensionNotesKey: "Saved with the ACME app", AppExtensionSectionTitleKey: "ACME Browser", AppExtensionFieldsKey: [ "firstname" : firstnameTextField.text ?? "", "lastname" : lastnameTextField.text ?? "" // Add as many string fields as you please. ] ] // The password generation options are optional, but are very handy in case you have strict rules about password lengths, symbols and digits. let passwordGenerationOptions:[String: AnyObject] = [ // The minimum password length can be 4 or more. AppExtensionGeneratedPasswordMinLengthKey: (8 as NSNumber), // The maximum password length can be 50 or less. AppExtensionGeneratedPasswordMaxLengthKey: (30 as NSNumber), // If YES, the 1Password will guarantee that the generated password will contain at least one digit (number between 0 and 9). Passing NO will not exclude digits from the generated password. AppExtensionGeneratedPasswordRequireDigitsKey: (true as NSNumber), // If YES, the 1Password will guarantee that the generated password will contain at least one symbol (See the list below). Passing NO will not exclude symbols from the generated password. AppExtensionGeneratedPasswordRequireSymbolsKey: (true as NSNumber), // Here are all the symbols available in the the 1Password Password Generator: // !@#$%^&*()_-+=|[]{}'\";.,>?/~` // The string for AppExtensionGeneratedPasswordForbiddenCharactersKey should contain the symbols and characters that you wish 1Password to exclude from the generated password. AppExtensionGeneratedPasswordForbiddenCharactersKey: "!@#$%/0lIO" as NSString ] OnePasswordExtension.shared().storeLogin(forURLString: "https://www.acme.com", loginDetails: newLoginDetails, passwordGenerationOptions: passwordGenerationOptions, for: self, sender: sender) { (loginDictionary, error) in guard let loginDictionary = loginDictionary else { if let error = error as NSError?, error.code != AppExtensionErrorCode.cancelledByUser.rawValue { print("Error invoking 1Password App Extension for find login: \(String(describing: error))") } return } self.usernameTextField.text = loginDictionary[AppExtensionUsernameKey] as? String self.passwordTextField.text = loginDictionary[AppExtensionPasswordKey] as? String if let returnedLoginDictionary = loginDictionary[AppExtensionReturnedFieldsKey] as? [String: Any] { self.firstnameTextField.text = returnedLoginDictionary["firstname"] as? String self.lastnameTextField.text = returnedLoginDictionary["lastname"] as? String } } } }
mit
f296cbd6b2fcde829031274fbc4f672d
44.45122
222
0.759324
4.400236
false
false
false
false
Ning-Wang/Come-On
v2exProject/v2exProject/Controller/HotViewController.swift
1
3158
// // HotViewController.swift // v2exProject // // Created by 郑建文 on 16/8/4. // Copyright © 2016年 Zheng. All rights reserved. // import UIKit // 协议名要放在父类名的后面,用 , 隔开 class HotViewController: UIViewController,UITableViewDataSource { //加标签 // MARK: TEST //通过闭包创建UI控件 let tableView:UITableView = { let table:UITableView = UITableView(frame: CGRectMake(0, 0, 200, 600), style: UITableViewStyle.Plain) // swift 中通过 类型名.self 来返回类型名 table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") table.registerNib(UINib(nibName: "HotCell", bundle: nil), forCellReuseIdentifier:"hotcell") return table }() //计算属性 var frame:CGRect{ get{ return self.view.bounds } } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.frame = frame //设置tableview 的行高是自动计算的 // 使用这个方法的话就不需要再 tableview的返回高度的回调方法了 tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension //注册可视化的cell view.addSubview(tableView) //发起网络请求 //网络请求管理实例 let manager = NetworkManager.sharedManager //利用网络请求实例来发起网络请求 //下面方法分两步1.先执行fetch方法 2。解析成功执行success 下面是success的实现(回调) manager.fetchTopics(success: { //网络请求成功后就执行这行代码 self.tableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return NetworkManager.sharedManager.topics.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //查找复用的cell let cell = tableView.dequeueReusableCellWithIdentifier("hotcell", forIndexPath: indexPath) as? HotCell //为了防止写错关键字所以用? // as? 强转返回的是一个可选类型 let topic = NetworkManager.sharedManager.topics[indexPath.row] cell!.topic = topic return cell! //这个代理方法需要的返回值是UITableViewCell所以需要强转 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
1c2ba0333af0faaa7517c1d263ee4e94
27.552083
126
0.63517
4.65365
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/BillingAddressRemoteManagerImpl.swift
1
2397
//Domain B2B/BillingAddress/ import SwiftyJSON import Alamofire import ObjectMapper class BillingAddressRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/billingAddressManager/" } func loadBillingAddressDetail(billingAddressId:String, billingAddressSuccessAction: (BillingAddress)->String, billingAddressErrorAction: (String)->String){ let methodName = "loadBillingAddressDetail" let parameters = [billingAddressId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let billingAddress = self.extractBillingAddressFromJSON(json){ billingAddressSuccessAction(billingAddress) } } case .Failure(let error): print(error) billingAddressErrorAction("\(error)") } } } func extractBillingAddressFromJSON(json:JSON) -> BillingAddress?{ let jsonTool = SwiftyJSONTool() let billingAddress = jsonTool.extractBillingAddress(json) return billingAddress } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "BillingAddressRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
mit
ccb6d15bf3f0f38422869122e4ae8317
27.231707
100
0.707968
4.097436
false
false
false
false
SakuragiTen/DYTV
DYTV/DYTV/Classes/Main/Models/AnchorModel.swift
1
891
// // AnchorModel.swift // testCocopods // // Created by gongsheng on 2017/1/9. // Copyright © 2017年 com.gongsheng. All rights reserved. // import UIKit class AnchorModel: NSObject { //房间ID var room_id : Int = 0 //房间图片对应的URLString var vertical_src : String = "" //判断是手机直播还是电脑直播 //0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间) var isVertical : Int = 0 ///房间名称 var room_name : String = "" ///主播昵称 var nickname : String = "" ///观看人数 var online : Int = 0 //所在城市 var anchor_city : String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
mit
a391640ca9e3d9d39584db59abcfbb3a
12.448276
72
0.529487
3.75
false
false
false
false
benlangmuir/swift
test/Generics/sr12531.swift
4
1276
// RUN: %target-typecheck-verify-swift // https://github.com/apple/swift/issues/54974 protocol AnyPropertyProtocol { associatedtype Root = Any associatedtype Value = Any associatedtype KP: AnyKeyPath var key: KP { get } var value: Value { get } } // CHECK-LABEL: .PartialPropertyProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : AnyPropertyProtocol, Self.[AnyPropertyProtocol]KP : PartialKeyPath<Self.[AnyPropertyProtocol]Root> protocol PartialPropertyProtocol: AnyPropertyProtocol where KP: PartialKeyPath<Root> { } // CHECK-LABEL: .PropertyProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : PartialPropertyProtocol, Self.[AnyPropertyProtocol]KP : WritableKeyPath<Self.[AnyPropertyProtocol]Root, Self.[AnyPropertyProtocol]Value> protocol PropertyProtocol: PartialPropertyProtocol where KP: WritableKeyPath<Root, Value> { } extension Dictionary where Value: AnyPropertyProtocol { // CHECK-LABEL: .subscript@ // CHECK-NEXT: Generic signature: <R, V, P where P : PropertyProtocol, P.[AnyPropertyProtocol]Root == R, P.[AnyPropertyProtocol]Value == V> subscript<R, V, P>(key: Key, path: WritableKeyPath<R, V>) -> P? where P: PropertyProtocol, P.Root == R, P.Value == V { return self[key] as? P } }
apache-2.0
3c7bdba9b55c1493526dc60d5b74161b
40.16129
193
0.740596
4.116129
false
false
false
false
firebase/firebase-ios-sdk
FirebaseFunctions/Sources/Internal/FunctionsSerializer.swift
1
6856
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation private enum Constants { static let longType = "type.googleapis.com/google.protobuf.Int64Value" static let unsignedLongType = "type.googleapis.com/google.protobuf.UInt64Value" static let dateType = "type.googleapis.com/google.protobuf.Timestamp" } enum SerializerError: Error { // TODO: Add parameters class name and value case unsupportedType // (className: String, value: AnyObject) case unknownNumberType(charValue: String, number: NSNumber) case invalidValueForType(value: String, requestedType: String) } class FUNSerializer: NSObject { private let dateFormatter: DateFormatter override init() { dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormatter.timeZone = TimeZone(identifier: "UTC") } // MARK: - Internal APIs internal func encode(_ object: Any) throws -> AnyObject { if object is NSNull { return object as AnyObject } else if object is NSNumber { return try encodeNumber(object as! NSNumber) } else if object is NSString { return object as AnyObject } else if object is NSDictionary { let dict = object as! NSDictionary let encoded: NSMutableDictionary = .init() dict.enumerateKeysAndObjects { key, obj, _ in // TODO(wilsonryan): Not exact translation let anyObj = obj as AnyObject let stringKey = key as! String let value = try! encode(anyObj) encoded[stringKey] = value } return encoded } else if object is NSArray { let array = object as! NSArray let encoded = NSMutableArray() for item in array { let anyItem = item as AnyObject let encodedItem = try encode(anyItem) encoded.add(encodedItem) } return encoded } else { throw SerializerError.unsupportedType } } internal func decode(_ object: Any) throws -> AnyObject? { // Return these types as is. PORTING NOTE: Moved from the bottom of the func for readability. if let dict = object as? NSDictionary { if let requestedType = dict["@type"] as? String { guard let value = dict["value"] as? String else { // Seems like we should throw here - but this maintains compatiblity. return dict } let result = try decodeWrappedType(requestedType, value) if result != nil { return result } // Treat unknown types as dictionaries, so we don't crash old clients when we add types. } let decoded = NSMutableDictionary() var decodeError: Error? dict.enumerateKeysAndObjects { key, obj, stopPointer in do { let decodedItem = try self.decode(obj) decoded[key] = decodedItem } catch { decodeError = error stopPointer.pointee = true return } } // Throw the internal error that popped up, if it did. if let decodeError = decodeError { throw decodeError } return decoded } else if let array = object as? NSArray { let result = NSMutableArray(capacity: array.count) for obj in array { // TODO: Is this data loss? The API is a bit weird. if let decoded = try decode(obj) { result.add(decoded) } } return result } else if object is NSNumber || object is NSString || object is NSNull { return object as AnyObject } throw SerializerError.unsupportedType } // MARK: - Private Helpers private func encodeNumber(_ number: NSNumber) throws -> AnyObject { // Recover the underlying type of the number, using the method described here: // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber let cType = number.objCType // Type Encoding values taken from // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/ // Articles/ocrtTypeEncodings.html switch cType[0] { case CChar("q".utf8.first!): // "long long" might be larger than JS supports, so make it a string. return ["@type": Constants.longType, "value": "\(number)"] as AnyObject case CChar("Q".utf8.first!): // "unsigned long long" might be larger than JS supports, so make it a string. return ["@type": Constants.unsignedLongType, "value": "\(number)"] as AnyObject case CChar("i".utf8.first!), CChar("s".utf8.first!), CChar("l".utf8.first!), CChar("I".utf8.first!), CChar("S".utf8.first!): // If it"s an integer that isn"t too long, so just use the number. return number case CChar("f".utf8.first!), CChar("d".utf8.first!): // It"s a float/double that"s not too large. return number case CChar("B".utf8.first!), CChar("c".utf8.first!), CChar("C".utf8.first!): // Boolean values are weird. // // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL) // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that // legitimate usage of signed chars is impossible, but this should be rare. // // Just return Boolean values as-is. return number default: // All documented codes should be handled above, so this shouldn"t happen. throw SerializerError.unknownNumberType(charValue: String(cType[0]), number: number) } } private func decodeWrappedType(_ type: String, _ value: String) throws -> AnyObject? { switch type { case Constants.longType: let formatter = NumberFormatter() guard let n = formatter.number(from: value) else { throw SerializerError.invalidValueForType(value: value, requestedType: type) } return n case Constants.unsignedLongType: // NSNumber formatter doesn't handle unsigned long long, so we have to parse it. let str = (value as NSString).utf8String var endPtr: UnsafeMutablePointer<CChar>? let returnValue = UInt64(strtoul(str, &endPtr, 10)) guard String(returnValue) == value else { throw SerializerError.invalidValueForType(value: value, requestedType: type) } return NSNumber(value: returnValue) default: return nil } } }
apache-2.0
0e3ca945034e9a9502f4373bceacec46
34.895288
97
0.658839
4.328283
false
false
false
false
xmartlabs/Opera
Example/Example/Helpers/Helpers.swift
1
1750
// Helpers.swift // Example-iOS ( https://github.com/xmartlabs/Example-iOS ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation func DEBUGLog(_ message: String, file: String = #file, line: Int = #line, function: String = #function) { #if DEBUG let fileURL = NSURL(fileURLWithPath: file) let fileName = fileURL.URLByDeletingPathExtension?.lastPathComponent ?? "" print("\(NSDate().dblog()) \(fileName)::\(function)[L:\(line)] \(message)") #endif } func DEBUGJson(_ value: AnyObject) { #if DEBUG if Constants.Debug.jsonResponse { print(JSONStringify(value)) } #endif }
mit
2590a41209f22ef6c35726846c1d2cbf
41.682927
105
0.715429
4.36409
false
false
false
false
groovelab/SwiftBBS
SwiftBBS/SwiftBBS Server/DatabaseManager.swift
1
870
// // DatabaseManager.swift // SwiftBBS // // Created by Takeo Namba on 2016/03/05. // Copyright GrooveLab // import MySQL enum DatabaseError : ErrorType { case Connect(String) case Query(String) case StoreResults } class DatabaseManager { let db: MySQL init() throws { db = MySQL() if db.connect(Config.mysqlHost, user: Config.mysqlUser, password: Config.mysqlPassword, db: Config.mysqlDb) == false { throw DatabaseError.Connect(db.errorMessage()) } } func query(sql: String) throws { if db.query(sql) == false { throw DatabaseError.Query(db.errorMessage()) } } func storeResults() throws -> MySQL.Results { guard let results = db.storeResults() else { throw DatabaseError.StoreResults } return results } }
mit
46ed252810a95c33b2464dce29246ae5
21.307692
126
0.604598
4.103774
false
true
false
false
breadwallet/breadwallet
BreadWallet/BRBitID.swift
4
6892
// // BRBitID.swift // BreadWallet // // Created by Samuel Sutch on 6/17/16. // Copyright © 2016 breadwallet LLC. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security @objc open class BRBitID : NSObject { static let SCHEME = "bitid" static let PARAM_NONCE = "x" static let PARAM_UNSECURE = "u" static let USER_DEFAULTS_NONCE_KEY = "brbitid_nonces" static let DEFAULT_INDEX: UInt32 = 42 class open func isBitIDURL(_ url: URL!) -> Bool { return url.scheme == SCHEME } open static let BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n".data(using: String.Encoding.utf8)! open class func formatMessageForBitcoinSigning(_ message: String) -> Data { let data = NSMutableData() data.append(UInt8(BITCOIN_SIGNED_MESSAGE_HEADER.count)) data.append(BITCOIN_SIGNED_MESSAGE_HEADER) let msgBytes = message.data(using: String.Encoding.utf8)! data.appendVarInt(UInt64(msgBytes.count)) data.append(msgBytes) return data as Data } // sign a message with a key and return a base64 representation open class func signMessage(_ message: String, usingKey key: BRKey) -> String { let signingData = formatMessageForBitcoinSigning(message) let signature = key.compactSign((signingData as NSData).sha256_2())! return String(bytes: signature.base64EncodedData(options: []), encoding: String.Encoding.utf8) ?? "" } open let url: URL open var siteName: String { return "\(url.host!)\(url.path)" } public init(url: URL!) { self.url = url } open func newNonce() -> String { let defs = UserDefaults.standard let nonceKey = "\(url.host!)/\(url.path)" var allNonces = [String: [String]]() var specificNonces = [String]() // load previous nonces. we save all nonces generated for each service // so they are not used twice from the same device if let existingNonces = defs.object(forKey: BRBitID.USER_DEFAULTS_NONCE_KEY) { allNonces = existingNonces as! [String: [String]] } if let existingSpecificNonces = allNonces[nonceKey] { specificNonces = existingSpecificNonces } // generate a completely new nonce var nonce: String repeat { nonce = "\(Int(Date().timeIntervalSince1970))" } while (specificNonces.contains(nonce)) // save out the nonce list specificNonces.append(nonce) allNonces[nonceKey] = specificNonces defs.set(allNonces, forKey: BRBitID.USER_DEFAULTS_NONCE_KEY) return nonce } open func runCallback(_ completionHandler: @escaping (Data?, URLResponse?, NSError?) -> Void) { guard let manager = BRWalletManager.sharedInstance() else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("No wallet", comment: "")])) } return } autoreleasepool { guard let seed = manager.seed(withPrompt: "", forAmount: 0) else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Could not unlock", comment: "")])) } return } let seq = BRBIP32Sequence() var scheme = "https" var nonce: String guard let query = url.query?.parseQueryString() else { DispatchQueue.main.async { completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Malformed URI", comment: "")])) } return } if let u = query[BRBitID.PARAM_UNSECURE] , u.count == 1 && u[0] == "1" { scheme = "http" } if let x = query[BRBitID.PARAM_NONCE] , x.count == 1 { nonce = x[0] // service is providing a nonce } else { nonce = newNonce() // we are generating our own nonce } let uri = "\(scheme)://\(url.host!)\(url.path)" // build a payload consisting of the signature, address and signed uri let priv = BRKey(privateKey: seq.bitIdPrivateKey(BRBitID.DEFAULT_INDEX, forURI: uri, fromSeed: seed)!)! let uriWithNonce = "bitid://\(url.host!)\(url.path)?x=\(nonce)" let signature = BRBitID.signMessage(uriWithNonce, usingKey: priv) let payload: [String: String] = [ "address": priv.address!, "signature": signature, "uri": uriWithNonce ] let json = try! JSONSerialization.data(withJSONObject: payload, options: []) // send off said payload var req = URLRequest(url: URL(string: "\(uri)?x=\(nonce)")!) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "POST" req.httpBody = json let session = URLSession.shared session.dataTask(with: req, completionHandler: { (dat: Data?, resp: URLResponse?, err: Error?) in var rerr: NSError? if err != nil { rerr = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: String(describing: err)]) } completionHandler(dat, resp, rerr) }).resume() } } }
mit
4d28e352fe44f88bb271d84f01871979
42.06875
119
0.601654
4.55754
false
false
false
false
mnin/on_ruby_ios
onruby/EventsViewController.swift
1
3682
// // SettingViewController.swift // onruby // // Created by Martin Wilhelmi on 24.09.14. // class EventsViewController: UITableViewController { let notificationCenter = NSNotificationCenter.defaultCenter() var eventArray = [Event]() var observer: AnyObject! override func viewDidLoad() { super.viewDidLoad() self.setRefreshControl() self.loadUserGroup() startObserver() } deinit { notificationCenter.removeObserver(self.observer) } func setRefreshControl() { self.refreshControl = UIRefreshControl() self.refreshControlTitle() self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) } func refresh(sender: AnyObject) { self.refreshControl?.attributedTitle = NSAttributedString(string: "Refreshing...") UserGroup.current().reloadJSONFile() } func refreshControlTitle() { var dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle let lastModificationDate = UserGroup.current().getModificationDate() self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh (last updated at \(dateFormatter.stringFromDate(lastModificationDate)))") } override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.eventArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "eventCellIdentifier" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell! if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } let event = self.eventArray[indexPath.row] let eventName = cell.viewWithTag(100) as UILabel let eventDate = cell.viewWithTag(101) as UILabel eventName.text = event.name eventDate.text = event.dateString() cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var eventViewController = storyboard?.instantiateViewControllerWithIdentifier("event") as EventViewController eventViewController.event = self.eventArray[indexPath.row] navigationController?.pushViewController(eventViewController, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: false) } func startObserver() { self.observer = notificationCenter.addObserverForName("reloadUserGroup", object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {(notification: NSNotification!) -> Void in let updatedUserGroupKey = notification.object as String? if updatedUserGroupKey != nil && updatedUserGroupKey == UserGroup.current().key { self.loadUserGroup() self.navigationController?.popToRootViewControllerAnimated(false) self.tableView.reloadData() self.refreshControlTitle() } self.refreshControl?.endRefreshing() }) } func loadUserGroup() { self.navigationItem.title = UserGroup.current().name self.eventArray = UserGroup.current().allEvents() } }
gpl-3.0
1e131e93be348374c266e678356c5c31
36.191919
186
0.695546
5.74415
false
false
false
false