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
GunoH/intellij-community
plugins/kotlin/project-wizard/core/resources/org/jetbrains/kotlin/tools/projectWizard/templates/ios/singleplatformProject/appName/SceneDelegate.swift
13
2616
import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
apache-2.0
67ec8a3cc4420a3c4d170e43a657f797
45.714286
147
0.70604
5.530655
false
false
false
false
lvillani/ConcreteKit
Sources/ConcreteKit/Store.swift
1
6812
// MIT License // // Copyright (c) 2019 Lorenzo Villani // // 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 os /// Custom logger used by the loggingReducer. private let storeLogger = OSLog(subsystem: "me.villani.lorenzo.ConcreteKit", category: "Store") // MARK: Basic types /// Marker protocol for states. public protocol State {} /// Marker protocol for actions. public protocol Action {} /// Type of reducer functions used for state transformations. /// /// - Parameter state: The input state. /// - Parameter action: The input action. /// /// - Returns: The new state. public typealias Reducer<S: State, A: Action> = (_ state: S, _ action: A) -> S // MARK: Reducer Helpers /// A reducer that wraps another one and logs actions that are being dispatched. /// /// - Parameter reducer: The reducer to wrap. /// /// - Returns: A reducer that logs dispatched actions and then calls the wrapped reducer. public func loggingReducer<S: State, A: Action>(reducer: @escaping Reducer<S, A>) -> Reducer<S, A> { func wrapper(state: S, action: A) -> S { let repr = "\(action)".prefix(50) os_log("%@", log: storeLogger, type: .debug, "Dispatching: \(repr)") return reducer(state, action) } return wrapper } /// Helper function to provide syntactic sugar for copying the state, changing it and returning it /// inside a reducer. /// /// For example it turns this: /// /// ``` /// func appReducer(state: AppState, action: AppAction) -> AppState { /// switch action { /// case .foo: /// var nextState = state // Copy the state /// nextState.prop = "foobar" /// return nextState /// } /// } /// ``` /// /// Into something like this: /// /// ``` /// func appReducer(state: AppState, action: AppAction) -> AppState { /// switch action { /// case .foo: /// return newState(given: state) { $0.prop = "foobar" } /// } /// } /// ``` /// /// The gains in terms of lines of code are very little but I find it improves readability. /// /// - Parameter state: The starting state that will be copied. /// - Parameter closure: The closure where the state should be updated. /// - Parameter state: The state that can be changed in-place inside the closure. /// /// - Returns: The updated state. public func newState<S: State>(given state: S, closure: (_ state: inout S) -> Void) -> S { var nextState = state closure(&nextState) return nextState } // MARK: Store Delegate // NOTE: AnyStoreDelegate, StoreDelegate and its extension all form an hack that allows users of // this library to implement the type-safe StoreDelegate protocol without generics and associated // types madness. The original implementation of this idea can be found in ReSwift: // https://github.com/ReSwift/ReSwift /// Type-unsafe store delegate protocol. Please conform to the type-safe `StoreDelegate` protocol. public protocol AnyStoreDelegate: AnyObject { func stateChanged_<S: State>(state: S) } /// Type-safe protocol that all classes wishing to subscribe to state changes must implement. public protocol StoreDelegate: AnyStoreDelegate { associatedtype StateType: State func stateChanged(state: StateType) } public extension StoreDelegate { func stateChanged_<S: State>(state: S) { guard let state = state as? StateType else { fatalError("Please implement StoreDelegate with a valid State type") } stateChanged(state: state) } } // MARK: Store /// Holds state, dispatches actions and manages subscriptions to state change updates. /// /// This store enforces all operations to happen on the main thread and does not support recursive dispatch. public class Store<S: State, A: Action> { public var state: S { guard Thread.isMainThread else { fatalError("Must access state from the main thread") } return _state } private let reducer: Reducer<S, A> private var delegates: [AnyStoreDelegate] = [] private var isDispatching: Bool = false private var _state: S /// Initializes a new store with the given root reducer and initial state. public init(reducer: @escaping Reducer<S, A>, initialState: S) { self.reducer = reducer self._state = initialState } /// Synchronously dispatches the given action. public func dispatch(action: A) { guard Thread.isMainThread else { fatalError("Must dispatch from the main thread") } guard !isDispatching else { fatalError("Cannot dispatch while another dispatch is in progress") } isDispatching = true defer { isDispatching = false } _state = reducer(_state, action) for delegate in delegates { delegate.stateChanged_(state: _state) } } /// Subscribes the given delegate to state updates. public func subscribe(_ delegate: AnyStoreDelegate) { guard Thread.isMainThread else { fatalError("Must subscribe from the main thread") } guard !isDispatching else { fatalError("Cannot subscribe while a dispatch is in progress") } if !delegates.contains(where: { $0 === delegate }) { delegates.append(delegate) delegate.stateChanged_(state: _state) } } /// Unsubscribes the given delegate from subscription list. public func unsubscribe(_ delegate: AnyStoreDelegate) { guard Thread.isMainThread else { fatalError("Must unsubscribe from the main thread") } guard !isDispatching else { fatalError("Cannot unsubscribe while a dispatch is in progress") } delegates.removeAll(where: { $0 === delegate }) } }
mit
a6261218235f0e3dd1784c21e7eb03eb
31.593301
108
0.672343
4.487484
false
false
false
false
cristov26/moviesApp
MoviesApp/Core/Services/Adapters/MoviesRepository.swift
1
2440
// // MoviesRepository.swift // MoviesApp // // Created by Cristian Tovar on 11/16/17. // Copyright © 2017 Cristian Tovar. All rights reserved. // import Foundation typealias MoviesClosure = ([MovieData]?) -> Void enum SaveStatus { case success case failure } struct MoviesCategories { static let popularity = "r_popularity" static let topRated = "r_voteAverage" static let upcoming = "r_releaseDateString" } class MoviesRepository: Repository{ let moviesWebService = MovieDBWebService() internal var lastSyncDate: Date? { get { return nil } } func findMovie(MovieId: String) -> MovieData? { let (movies, _) = CacheImpl.objects(orderBy: "r_movieId", predicateFormat: "r_movieId = '%@'", MovieId) let movie = movies as? MovieData return movie } func listMovies(Page:Int, category: MovieStoreCategory, completion: @escaping MoviesClosure) { var movies: [Any]? var hasToUpdate: Bool var order: String = "" switch category { case .Popular: order = MoviesCategories.popularity case .TopRated: order = MoviesCategories.topRated case .Upcoming: order = MoviesCategories.upcoming } (movies, hasToUpdate) = CacheImpl.objects(orderBy: order, predicateFormat: "") if hasToUpdate || (movies?.count)!<Page*20 { MovieDBWebService.currentPage = Page moviesWebService.retrieveMovies(Category: category, completion: { [unowned self] (response) in self.handleWebServiceResponse(response: response, completion: completion) }) } else { completion(movies as? [MovieData]) } } } private extension MoviesRepository{ func handleWebServiceResponse(response: ServiceResponse, completion: @escaping MoviesClosure) { var result = [MovieData]() switch response { case .success(let Movies): for Movie in Movies { CacheImpl.add(object: Movie as! MovieData) result.append(Movie as! MovieData) } completion(result) case .notConnectedToInternet: print("notConnectedToInternet") completion(result) case .failure: print("failure") completion(result) } } }
mit
2e6863ee7a3c935985ab37985b305d5d
28.385542
111
0.604756
4.810651
false
false
false
false
sun409377708/swiftDemo
SinaSwiftPractice/SinaSwiftPractice/Classes/Tools/Extension/NSAttributeString+Extension.swift
1
1244
// // NSAttributeString+Extension.swift // AliyPaySwift // // Created by maoge on 16/8/16. // Copyright © 2016年 maoge. All rights reserved. // import UIKit extension NSAttributedString { class func imageTextWithImage(image: UIImage, imageWH: CGFloat, title: String, fontSize: CGFloat, titleColor: UIColor, space: CGFloat) -> NSAttributedString { //图片富文本 let attachment = NSTextAttachment() attachment.image = image attachment.bounds = CGRect(x: 0, y: 0, width: imageWH, height: imageWH) let attImage = NSAttributedString(attachment: attachment) //文字富文本 let attText = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : titleColor, NSFontAttributeName : UIFont.systemFont(ofSize: fontSize)]) //空格富文本 let attSpace = NSAttributedString(string: "\n\n", attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: space)]) //添加至可变数组 let attM = NSMutableAttributedString() attM.append(attImage) attM.append(attSpace) attM.append(attText) return attM } }
mit
2811321168719ecb5da56cbf33c97374
29.692308
173
0.635756
4.826613
false
false
false
false
apple/swift-tools-support-core
Sources/TSCBasic/JSONMapper.swift
1
5604
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// A type which can be mapped from JSON. public protocol JSONMappable { /// Create an object from given JSON. init(json: JSON) throws } extension JSON { /// Describes an error occurred during JSON mapping. public enum MapError: Error { /// The key is missing in JSON. case missingKey(String) /// Got a different type than expected. case typeMismatch(key: String, expected: Any.Type, json: JSON) /// A custom error. Clients can use this in their mapping method. case custom(key: String?, message: String) } /// Returns a JSON mappable object from a given key. public func get<T: JSONMappable>(_ key: String) throws -> T { let object: JSON = try get(key) return try T(json: object) } public func get<T: JSONMappable>(_ type: T.Type, forKey key: String) throws -> T { let object: JSON = try get(key) return try T(json: object) } /// Returns an optional JSON mappable object from a given key. public func get<T: JSONMappable>(_ key: String) -> T? { if let object: JSON = try? get(key) { return try? T.init(json: object) } return nil } /// Returns a JSON mappable array from a given key. public func get<T: JSONMappable>(_ key: String) throws -> [T] { let array: [JSON] = try get(key) return try array.map(T.init(json:)) } public func get<T: JSONMappable>(_ type: [T].Type, forKey key: String) throws -> [T] { let array: [JSON] = try get(key) return try array.map(T.init(json:)) } /// Returns a JSON mappable dictionary from a given key. public func get<T: JSONMappable>(_ key: String) throws -> [String: T] { let object: JSON = try get(key) guard case .dictionary(let value) = object else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: object) } return try value.mapValues({ try T.init(json: $0) }) } /// Returns a JSON mappable dictionary from a given key. public func get(_ key: String) throws -> [String: JSON] { let object: JSON = try get(key) guard case .dictionary(let value) = object else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: object) } return value } /// Returns JSON entry in the dictionary from a given key. public func get(_ key: String) throws -> JSON { guard case .dictionary(let dict) = self else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: self) } guard let object = dict[key] else { throw MapError.missingKey(key) } return object } public func getJSON(_ key: String) throws -> JSON { return try get(key) } /// Returns JSON array entry in the dictionary from a given key. public func get(_ key: String) throws -> [JSON] { let object: JSON = try get(key) guard case .array(let array) = object else { throw MapError.typeMismatch(key: key, expected: Array<JSON>.self, json: object) } return array } public func getArray(_ key: String) throws -> [JSON] { return try get(key) } public func getArray() throws -> [JSON] { guard case .array(let array) = self else { throw MapError.typeMismatch(key: "<self>", expected: Array<JSON>.self, json: self) } return array } } // MARK: - Conformance for basic JSON types. extension Int: JSONMappable { public init(json: JSON) throws { guard case .int(let int) = json else { throw JSON.MapError.custom(key: nil, message: "expected int, got \(json)") } self = int } } extension String: JSONMappable { public init(json: JSON) throws { guard case .string(let str) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self = str } } extension Bool: JSONMappable { public init(json: JSON) throws { guard case .bool(let bool) = json else { throw JSON.MapError.custom(key: nil, message: "expected bool, got \(json)") } self = bool } } extension Double: JSONMappable { public init(json: JSON) throws { guard case .double(let double) = json else { throw JSON.MapError.custom(key: nil, message: "expected double, got \(json)") } self = double } } extension Array where Element: JSONMappable { public init(json: JSON) throws { guard case .array(let array) = json else { throw JSON.MapError.custom(key: nil, message: "expected array, got \(json)") } self = try array.map({ try Element(json: $0) }) } } extension Dictionary where Key == String, Value: JSONMappable { public init(json: JSON) throws { guard case .dictionary(let dictionary) = json else { throw JSON.MapError.custom(key: nil, message: "expected dictionary, got \(json)") } self = try dictionary.mapValues({ try Value(json: $0) }) } }
apache-2.0
945809609bef05801151e715295e6077
31.581395
94
0.604211
4.111519
false
false
false
false
mparrish91/gifRecipes
framework/Model/Paginator.swift
1
1533
// // Paginator.swift // reddift // // Created by sonson on 2015/04/14. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Paginator object for paiging listing object. */ public struct Paginator { let after: String let before: String let modhash: String public init() { self.after = "" self.before = "" self.modhash = "" } public init(after: String, before: String, modhash: String) { self.after = after self.before = before self.modhash = modhash } public var isVacant: Bool { if (!after.isEmpty) || (!before.isEmpty) { return false } return true } /** Generate dictionary to add query parameters to URL. If paginator is vacant, returns vacant dictionary as [String:String]. - returns: Dictionary object for paging. */ public var parameterDictionary: [String:String] { get { var dict: [String:String] = [:] if after.characters.count > 0 { dict["after"] = after } if before.characters.count > 0 { dict["before"] = before } return dict } } public func dictionaryByAdding(parameters dict: [String:String]) -> [String:String] { var newDict = dict if after.characters.count > 0 { newDict["after"] = after } if before.characters.count > 0 { newDict["before"] = before } return newDict } }
mit
b9098999be09778fee6faab82096ca3d
21.850746
89
0.563684
4.126685
false
false
false
false
elpassion/el-space-ios
ELSpaceTests/TestDoubles/Stubs/ViewControllerTransitionContextStub.swift
1
1564
import UIKit class ViewControllerTransitionContextStub: NSObject, UIViewControllerContextTransitioning { var stubbedToView: UIView? var stubbedFromView: UIView? // MARK: - UIViewControllerContextTransitioning let containerView = UIView() let isAnimated = false let isInteractive = false let transitionWasCancelled = false let presentationStyle: UIModalPresentationStyle = .none private(set) var invokedCompleteTransition: (count: Int, didComplete: Bool)? func updateInteractiveTransition(_ percentComplete: CGFloat) {} func finishInteractiveTransition() {} func cancelInteractiveTransition() {} func pauseInteractiveTransition() {} func completeTransition(_ didComplete: Bool) { var count = invokedCompleteTransition?.count ?? 0 count += 1 invokedCompleteTransition = (count: count, didComplete: didComplete) } func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? { return nil } func view(forKey key: UITransitionContextViewKey) -> UIView? { switch key { case UITransitionContextViewKey.from: return stubbedFromView case UITransitionContextViewKey.to: return stubbedToView default: return nil } } var targetTransform: CGAffineTransform = .identity func initialFrame(for vc: UIViewController) -> CGRect { return .zero } func finalFrame(for vc: UIViewController) -> CGRect { return .zero } }
gpl-3.0
d0855069da9904de2499d9387479aa91
26.438596
96
0.690537
6.062016
false
false
false
false
slavapestov/swift
test/SILGen/dynamic_self.swift
1
8447
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s protocol P { func f() -> Self } protocol CP : class { func f() -> Self } class X : P, CP { required init(int i: Int) { } // CHECK-LABEL: sil hidden @_TFC12dynamic_self1X1f{{.*}} : $@convention(method) (@guaranteed X) -> @owned func f() -> Self { return self } // CHECK-LABEL: sil hidden @_TZFC12dynamic_self1X7factory{{.*}} : $@convention(thin) (Int, @thick X.Type) -> @owned X // CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type): // CHECK: [[CTOR:%[0-9]+]] = class_method [[SELF]] : $@thick X.Type, #X.init!allocator.1 : X.Type -> (int: Int) -> X , $@convention(thin) (Int, @thick X.Type) -> @owned X // CHECK: apply [[CTOR]]([[I]], [[SELF]]) : $@convention(thin) (Int, @thick X.Type) -> @owned X class func factory(i: Int) -> Self { return self.init(int: i) } } class Y : X { required init(int i: Int) { } } class GX<T> { func f() -> Self { return self } } class GY<T> : GX<[T]> { } // CHECK-LABEL: sil hidden @_TF12dynamic_self23testDynamicSelfDispatch{{.*}} : $@convention(thin) (@owned Y) -> () func testDynamicSelfDispatch(y: Y) { // CHECK: bb0([[Y:%[0-9]+]] : $Y): // CHECK: strong_retain [[Y]] // CHECK: [[Y_AS_X:%[0-9]+]] = upcast [[Y]] : $Y to $X // CHECK: [[X_F:%[0-9]+]] = class_method [[Y_AS_X]] : $X, #X.f!1 : X -> () -> Self , $@convention(method) (@guaranteed X) -> @owned X // CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[Y_AS_X]]) : $@convention(method) (@guaranteed X) -> @owned X // CHECK: strong_release [[Y_AS_X]] // CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y // CHECK: strong_release [[Y_RESULT]] : $Y // CHECK: strong_release [[Y]] : $Y y.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self30testDynamicSelfDispatchGeneric{{.*}} : $@convention(thin) (@owned GY<Int>) -> () func testDynamicSelfDispatchGeneric(gy: GY<Int>) { // CHECK: bb0([[GY:%[0-9]+]] : $GY<Int>): // CHECK: strong_retain [[GY]] // CHECK: [[GY_AS_GX:%[0-9]+]] = upcast [[GY]] : $GY<Int> to $GX<Array<Int>> // CHECK: [[GX_F:%[0-9]+]] = class_method [[GY_AS_GX]] : $GX<Array<Int>>, #GX.f!1 : <T> GX<T> -> () -> Self , $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[GY_AS_GX]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: strong_release [[GY_AS_GX]] // CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int> // CHECK: strong_release [[GY_RESULT]] : $GY<Int> // CHECK: strong_release [[GY]] gy.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self21testArchetypeDispatch{{.*}} : $@convention(thin) <T where T : P> (@in T) -> () func testArchetypeDispatch<T: P>(t: T) { // CHECK: bb0([[T:%[0-9]+]] : $*T): // CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@out τ_0_0, @in_guaranteed τ_0_0) -> () // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@out τ_0_0, @in_guaranteed τ_0_0) -> () t.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self23testExistentialDispatch{{.*}} func testExistentialDispatch(p: P) { // CHECK: bb0([[P:%[0-9]+]] : $*P): // CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr [[P]] : $*P to $*@opened([[N:".*"]]) P // CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P // CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P // CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@out τ_0_0, @in_guaranteed τ_0_0) -> () // CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@out τ_0_0, @in_guaranteed τ_0_0) -> () // CHECK: destroy_addr [[P_RESULT]] : $*P // CHECK: dealloc_stack [[P_RESULT]] : $*P // CHECK: destroy_addr [[P]] : $*P p.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self28testExistentialDispatchClass{{.*}} : $@convention(thin) (@owned CP) -> () func testExistentialDispatchClass(cp: CP) { // CHECK: bb0([[CP:%[0-9]+]] : $CP): // CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[CP]] : $CP to $@opened([[N:".*"]]) CP // CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1, [[CP_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP // CHECK: strong_release [[CP_F_RESULT]] : $@opened([[N]]) CP cp.f() } @objc class ObjC { @objc func method() -> Self { return self } } // CHECK-LABEL: sil hidden @_TF12dynamic_self21testAnyObjectDispatch{{.*}} : $@convention(thin) (@owned AnyObject) -> () func testAnyObjectDispatch(o: AnyObject) { // CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject): // CHECK: [[VAR_9:%[0-9]+]] = partial_apply [[METHOD]]([[O_OBJ]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject var x = o.method } // <rdar://problem/16270889> Dispatch through ObjC metatypes. class ObjCInit { dynamic required init() { } } // CHECK: sil hidden @_TF12dynamic_self12testObjCInit{{.*}} : $@convention(thin) (@thick ObjCInit.Type) -> () func testObjCInit(meta: ObjCInit.Type) { // CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type): // CHECK: [[O:%[0-9]+]] = alloc_box $ObjCInit // CHECK: [[PB:%.*]] = project_box [[O]] // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type // CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit // CHECK: [[INIT:%[0-9]+]] = class_method [volatile] [[OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : ObjCInit.Type -> () -> ObjCInit , $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: store [[RESULT_OBJ]] to [[PB]] : $*ObjCInit // CHECK: strong_release [[O]] : $@box ObjCInit // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() var o = meta.init() } class OptionalResult { func foo() -> Self? { return self } } // CHECK-LABEL: sil hidden @_TFC12dynamic_self14OptionalResult3foo // CHECK: bb0( // CHECK-NEXT: debug_value %0 : $OptionalResult // CHECK-NEXT: strong_retain [[VALUE:%[0-9]+]] // CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.Some!enumelt.1, %0 : $OptionalResult // CHECK-NEXT: return [[T0]] : $Optional<OptionalResult> class OptionalResultInheritor : OptionalResult { func bar() {} } func testOptionalResult(v : OptionalResultInheritor) { v.foo()?.bar() } // CHECK-LABEL: sil hidden @_TF12dynamic_self18testOptionalResult{{.*}} : $@convention(thin) (@owned OptionalResultInheritor) -> () // CHECK: [[T0:%.*]] = class_method [[V:%.*]] : $OptionalResult, #OptionalResult.foo!1 : OptionalResult -> () -> Self? , $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> // CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[V]]) // CHECK: select_enum [[RES]] // CHECK: [[T1:%.*]] = unchecked_enum_data [[RES]] // CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[T1]] : $OptionalResult to $OptionalResultInheritor // CHECK-NEXT: enum $Optional<OptionalResultInheritor>, #Optional.Some!enumelt.1, [[T4]] // CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self { // CHECK: method #P.f!1: @_TTWC12dynamic_self1XS_1PS_FS1_1f // CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self { // CHECK: method #CP.f!1: @_TTWC12dynamic_self1XS_2CPS_FS1_1f
apache-2.0
f12c8f0c76ee2a875cf2b771f790bb7d
51.937107
211
0.58964
2.950228
false
true
false
false
Sephiroth87/C-swifty4
Tests/BaseTest.swift
1
2273
// // BaseTest.swift // C-swifty4 // // Created by Fabio on 10/11/2016. // Copyright © 2016 orange in a day. All rights reserved. // import Cocoa import XCTest @testable import C64 class BaseTest: XCTestCase, C64Delegate { internal var c64: C64! internal var expectation: XCTestExpectation! fileprivate var fileName: String! internal var subdirectory: String { return "" } internal var timeout: TimeInterval { return 100 } func setupTest(_ filename: String) { self.fileName = filename self.expectation = self.expectation(description: name) c64.run() waitForExpectations(timeout: timeout, handler: nil) } override func setUp() { super.setUp() let romConfig = C64ROMConfiguration( kernalData: try! Data(contentsOf: Bundle(for: self.classForCoder).url(forResource: "kernal", withExtension: nil, subdirectory:"ROM")!), basicData: try! Data(contentsOf: Bundle(for: self.classForCoder).url(forResource: "basic", withExtension: nil, subdirectory:"ROM")!), characterData: try! Data(contentsOf: Bundle(for: self.classForCoder).url(forResource: "chargen", withExtension: nil, subdirectory:"ROM")!)) let config = C64Configuration(rom: romConfig, vic: VICConfiguration.pal, c1541: C1541Configuration(rom: C1541ROMConfiguration(c1541Data: try! Data(contentsOf: Bundle(for: self.classForCoder).url(forResource: "1541", withExtension: nil, subdirectory:"ROM")!)))) c64 = C64(configuration: config) c64.delegate = self c64.setBreakpoint(at: 0xE5CD) { self.c64.setBreakpoint(at: 0xE5CD, handler: nil) self.c64.loadPRGFile(try! Data(contentsOf: Bundle(for: self.classForCoder).url(forResource: self.fileName, withExtension: "prg", subdirectory: self.subdirectory)!)) self.c64.run() self.c64.loadString("RUN\n") } } func C64DidBreak(_ c64: C64) {} func C64DidCrash(_ c64: C64) { XCTAssert(false, "Crash") expectation.fulfill() } func C64VideoFrameReady(_ c64: C64) {} func C64DidRun(_ c64: C64) {} }
mit
0c7b4285cec992a14f1f57399e736c03
35.063492
225
0.628961
4.086331
false
true
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Live/View/GiftAnimation/GiftChannelView.swift
1
4051
// // GiftChannelView.swift // GiftAnimation // // Created by zcm_iOS on 2017/6/3. // Copyright © 2017年 com.zcmlc.zcmlc. All rights reserved. // import UIKit enum GiftChannelState { case idle //闲置状态 case animating //正在执行 case willEnd //即将结束 case endAnimating //结束动画 } class GiftChannelView: UIView, NibLoadable { // MARK: 控件属性 @IBOutlet weak var bgView: UIView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var senderLabel: UILabel! @IBOutlet weak var giftDescLabel: UILabel! @IBOutlet weak var giftImageView: UIImageView! @IBOutlet weak var digitLabel: GiftDigitLabel! fileprivate var cacheNumber : Int = 0 fileprivate var currentNumber : Int = 0 var giftState : GiftChannelState = .idle var complectionCallback : ((GiftChannelView) -> Void)? var giftModel : GiftAnimationModel? { didSet{ //1.对模型进行校验 guard let model = giftModel else { return } //2.给控件设置信息 iconImageView.image = UIImage(named: model.senderUrl) senderLabel.text = model.senderName giftDescLabel.text = "送出礼物:【\(model.giftName)】" giftImageView.setImage(model.giftUrl, "prop_b") digitLabel.textAlignment = .center //3.弹出视图 giftState = .animating performAnimation() } } } //MARK: 界面处理 extension GiftChannelView{ override func layoutSubviews() { super.layoutSubviews() bgView.layer.masksToBounds = true bgView.layer.cornerRadius = frame.height * 0.5 iconImageView.layer.masksToBounds = true iconImageView.layer.cornerRadius = frame.height * 0.5 iconImageView.layer.borderWidth = 1 iconImageView.layer.borderColor = UIColor.green.cgColor } } //MARK: 对外提供函数 extension GiftChannelView{ //增加到缓存里面(缓存个数) func addOnceToCache() { if giftState == .willEnd { performDigitAnimation() /**取消本类perform的操作 * 使3.0秒,重新归0计算 * self.perform(#selector(self.performEndAnimation), with: nil, afterDelay: 3.0) */ NSObject.cancelPreviousPerformRequests(withTarget: self) }else{ cacheNumber += 1 } } } // MARK:- 执行动画代码 extension GiftChannelView { fileprivate func performAnimation() { digitLabel.alpha = 1.0 digitLabel.text = " X1 " UIView.animate(withDuration: 0.25, animations: { self.alpha = 1 self.frame.origin.x = 0 }) { (isFinished) in self.performDigitAnimation() } } //label执行动画 fileprivate func performDigitAnimation(){ currentNumber += 1 digitLabel.text = " X\(currentNumber) " digitLabel.showDigitAnimation { if self.cacheNumber > 0{ self.cacheNumber -= 1 self.performDigitAnimation() }else{ self.giftState = .willEnd self.perform(#selector(self.performEndAnimation), with: nil, afterDelay: 3.0) } } } //执行结束动画 @objc fileprivate func performEndAnimation(){ giftState = .endAnimating UIView.animate(withDuration: 0.25, animations: { self.frame.origin.x = UIScreen.main.bounds.width self.alpha = 0 }) { (isFinished) in self.currentNumber = 0 self.cacheNumber = 0 self.giftModel = nil self.frame.origin.x = -self.frame.width self.giftState = .idle self.digitLabel.alpha = 0 if let complectionCallback = self.complectionCallback{ complectionCallback(self) } } } }
mit
d59bfe7720b44fb4ce8a9275a8ae811a
27.776119
93
0.58195
4.520516
false
false
false
false
HJliu1123/LearningNotes-LHJ
April/DataWithFMDB/DataWithFMDB/ViewController.swift
1
4909
// // ViewController.swift // DataWithFMDB // // Created by liuhj on 16/5/5. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit class ViewController: UIViewController { var _db : FMDatabase? var filePath : String? override func viewDidLoad() { super.viewDidLoad() self.createTable() } //创建表 func createTable() { let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first filePath = docPath?.stringByAppendingString("/test.sqlite") print(filePath) _db = FMDatabase(path: filePath) //"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);" if _db!.open() { do { try _db!.executeUpdate("CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);", values: nil) } catch let error as NSError { print(error.userInfo) } } } //插入 func insertData(stu : Student) { _db?.open() let array : [AnyObject] = [stu.id!, stu.name!, stu.sex!, stu.age!] let result = _db?.executeUpdate("INSERT INTO t_student (id, name, sex, age) VALUE (?, ?, ?, ?);", withArgumentsInArray: array) if (result != nil) { print("success: \(stu.id)") } else { print("error: \(_db?.lastErrorMessage())") } _db?.close() } //删除 func deleteData(stu : Student) { _db?.open() let result = _db?.executeUpdate("DELETE FROM t_student WHERE id = (?)", withArgumentsInArray: [stu.id!]) if (result != nil) { print("success: \(stu.id)") } else { print("failed: \(_db?.lastErrorMessage())") } _db?.close() } //改 func updateData(stu : Student) { _db?.open() let array : [AnyObject] = [stu.name!, stu.sex!, stu.age!, stu.id!] let result = _db?.executeUpdate("PUDATE t_student SET name = (?), sex = (?), age = (?) WHERE id = (?)", withArgumentsInArray: array) if (result != nil) { print("success: \(stu.id)") } else { print("failed: \(_db?.lastErrorMessage())") } _db?.close() } //查询 func selectData() -> Array<Student> { _db?.open() var stus = [Student]() //返回结果是set let result = _db?.executeQuery("SELELCT id, name, sex, age FROM t_student", withArgumentsInArray: nil) if (result != nil) { while ((result?.next()) != nil) { let id = Int((result?.intForColumn("id"))!) let name = (result?.stringForColumn("name"))! as String let sex = (result?.stringForColumn("sex"))! as String let age = Int((result?.intForColumn("age"))!) let stu = Student(id: id, name: name, sex: sex, age: age) stus.append(stu) } } else { print("failed: \(_db?.lastErrorMessage())") } _db?.close() return stus } //线程安全的 /* FMDatabaseQueue虽然看似一个队列,实际上它本身并不是,它通过内部创建一个Serial的dispatch_queue_t来处理通过inDatabase和inTransaction传入的Blocks,所以当我们在主线程(或者后台)调用inDatabase或者inTransaction时,代码实际上是同步的。FMDatabaseQueue这么设计的目的是让我们避免发生并发访问数据库的问题,因为对数据库的访问可能是随机的(在任何时候)、不同线程间(不同的网络回调等)的请求。内置一个Serial队列后,FMDatabaseQueue就变成线程安全了,所有的数据库访问都是同步执行,而且这比使用@synchronized或NSLock要高效得多。 但是这么一来就有了一个问题:如果后台在执行大量的更新,而主线程也需要访问数据库,虽然要访问的数据量很少,但是在后台执行完之前,还是会阻塞主线程。 */ func safeAddData(stu : Student) { let queue : FMDatabaseQueue = FMDatabaseQueue(path: filePath) queue.inDatabase { (_db : FMDatabase!) in _db.open() let array : [AnyObject] = [stu.id!, stu.name!, stu.sex!, stu.age!] let result = _db?.executeUpdate("INSERT INTO t_student (id, name, sex, age) VALUE (?, ?, ?, ?);", withArgumentsInArray: array) if (result != nil) { print("success: \(stu.id)") } else { print("error: \(_db?.lastErrorMessage())") } _db?.close() } } }
apache-2.0
05068542eb20811e02cbffb4b4a962d5
33.03125
332
0.544077
4.059646
false
false
false
false
tatey/LIFXHTTPKit
Source/Client.swift
1
4084
// // Created by Tate Johnson on 29/05/2015. // Copyright (c) 2015 Tate Johnson. All rights reserved. // import Foundation public class Client { public let session: HTTPSession public private(set) var lights: [Light] public private(set) var scenes: [Scene] private var observers: [ClientObserver] public convenience init(accessToken: String, lights: [Light]? = nil, scenes: [Scene]? = nil) { self.init(session: HTTPSession(accessToken: accessToken), lights: lights, scenes: scenes) } public init(session: HTTPSession, lights: [Light]? = nil, scenes: [Scene]? = nil) { self.session = session self.lights = lights ?? [] self.scenes = scenes ?? [] observers = [] } public func fetch(completionHandler: ((_ errors: [Error]) -> Void)? = nil) { let group = DispatchGroup() var errors: [Error] = [] group.enter() fetchLights { (error) in if let error = error { errors.append(error) } group.leave() } group.enter() fetchScenes { (error) in if let error = error { errors.append(error) } group.leave() } group.notify(queue: session.delegateQueue) { completionHandler?(errors) } } public func fetchLights(completionHandler: ((_ error: Error?) -> Void)? = nil) { session.lights("all") { [weak self] (request, response, lights, error) in if error != nil { completionHandler?(error) return } if let strongSelf = self { let oldLights = strongSelf.lights let newLights = lights if oldLights != newLights { strongSelf.lights = newLights for observer in strongSelf.observers { observer.lightsDidUpdateHandler(lights) } } } completionHandler?(nil) } } public func fetchScenes(completionHandler: ((_ error: Error?) -> Void)? = nil) { session.scenes { [weak self] (request, response, scenes, error) in if error != nil { completionHandler?(error) return } self?.scenes = scenes completionHandler?(nil) } } public func allLightTarget() -> LightTarget { return lightTargetWithSelector(LightTargetSelector(type: .All)) } public func lightTargetWithSelector(_ selector: LightTargetSelector) -> LightTarget { return LightTarget(client: self, selector: selector, filter: selectorToFilter(selector)) } func addObserver(lightsDidUpdateHandler: @escaping ClientObserver.LightsDidUpdate) -> ClientObserver { let observer = ClientObserver(lightsDidUpdateHandler: lightsDidUpdateHandler) observers.append(observer) return observer } func removeObserver(observer: ClientObserver) { for (index, other) in observers.enumerated() { if other === observer { observers.remove(at: index) break } } } func updateLights(_ lights: [Light]) { let oldLights = self.lights var newLights: [Light] = [] for light in lights { if !newLights.contains(where: { $0.id == light.id }) { newLights.append(light) } } for light in oldLights { if !newLights.contains(where: { $0.id == light.id }) { newLights.append(light) } } if oldLights != newLights { for observer in observers { observer.lightsDidUpdateHandler(newLights) } self.lights = newLights } } private func selectorToFilter(_ selector: LightTargetSelector) -> LightTargetFilter { switch selector.type { case .All: return { (light) in return true } case .ID: return { (light) in return light.id == selector.value } case .GroupID: return { (light) in return light.group?.id == selector.value } case .LocationID: return { (light) in return light.location?.id == selector.value } case .SceneID: return { [weak self] (light) in if let strongSelf = self, let index = strongSelf.scenes.index(where: { $0.toSelector() == selector }) { let scene = strongSelf.scenes[index] return scene.states.contains { (state) in let filter = strongSelf.selectorToFilter(state.selector) return filter(light) } } else { return false } } case .Label: return { (light) in return light.label == selector.value } } } }
mit
08c5aff9a76d60e253254a938bdce2f0
24.848101
107
0.664055
3.538995
false
false
false
false
thiagolioy/colors
Colors/ViewController.swift
1
2253
// // ViewController.swift // Colors // // Created by Thiago Lioy on 07/06/17. // Copyright © 2017 Thiago Lioy. All rights reserved. // import UIKit struct Color { let name: String let color: UIColor } class ViewController: UIViewController { @IBOutlet weak var colorContainer: UIView! @IBOutlet weak var colorLabel: UILabel! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var previousButton: UIButton! @IBOutlet weak var pageControl: UIPageControl! let colors: [Color] = [ Color(name: "Red", color: UIColor.red), Color(name: "Blue", color: UIColor.blue) ] var currentPage: Int = 0 { didSet{ pageControl.currentPage = currentPage setColor(forPage: currentPage) } } override func viewDidLoad() { super.viewDidLoad() setupInitialUIState() } func setupInitialUIState() { guard let firstColor = colors.first else { fatalError("should have an initial color") } pageControl.numberOfPages = colors.count pageControl.currentPage = 0 setupUI(with: firstColor) } func setupUI(with color: Color) { colorContainer.backgroundColor = color.color colorLabel.text = color.name } func setColor(forPage page: Int) { if page < 0 || page >= colors.count { return } let color = colors[page] setupUI(with: color) } func updatePage(page: Int) { if page < 0 || page >= colors.count { return } currentPage = page } @IBAction func previous() { updatePage(page: currentPage - 1) } @IBAction func next() { updatePage(page: currentPage + 1) } @IBAction func proceedToColorsList() { navigationController? .pushViewController(ListViewController.fromStoryboard(), animated: true) } } extension ViewController { static func fromStoryboard() -> ViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil) return storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController } }
mit
730b39096cc57dceb5017b4986620561
23.747253
104
0.604352
4.843011
false
false
false
false
huangboju/Moots
UICollectionViewLayout/CollectionKit-master/Examples/GridExample/GridViewController.swift
1
1587
// // GridViewController.swift // CollectionKitExample // // Created by Luke Zhao on 2016-06-05. // Copyright © 2016 lkzhao. All rights reserved. // import UIKit import CollectionKit let kGridCellSize = CGSize(width: 50, height: 50) let kGridSize = (width: 20, height: 20) let kGridCellPadding:CGFloat = 10 class GridViewController: CollectionViewController { override func viewDidLoad() { super.viewDidLoad() let dataProvider = ArrayDataProvider(data: Array(1...kGridSize.width * kGridSize.height), identifierMapper: { (_, data) in return "\(data)" }) let layout = Closurelayout( frameProvider: { (i: Int, data: Int, _) in CGRect(x: CGFloat(i % kGridSize.width) * (kGridCellSize.width + kGridCellPadding), y: CGFloat(i / kGridSize.width) * (kGridCellSize.height + kGridCellPadding), width: kGridCellSize.width, height: kGridCellSize.height) } ) collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let provider = CollectionProvider( dataProvider: dataProvider, viewUpdater: { (view: UILabel, data: Int, index: Int) in view.backgroundColor = UIColor(hue: CGFloat(index) / CGFloat(kGridSize.width * kGridSize.height), saturation: 0.68, brightness: 0.98, alpha: 1) view.textColor = .white view.textAlignment = .center view.text = "\(data)" } ) provider.layout = layout provider.presenter = WobblePresenter() self.provider = provider } }
mit
73c4c0de84b36936914a9a8be0511513
32.041667
126
0.645649
4.173684
false
false
false
false
rrunfa/StreamRun
StreamRun/Extensions/String+Additions.swift
1
614
// // String+Additions.swift // StreamRun // // Created by Nikita Nagaynik on 12/02/15. // Copyright (c) 2015 rrunfa. All rights reserved. // import Foundation extension String { func stringByAddQueryParams(params: Dictionary<String, String>) -> String { if params.count == 0 { return self } var result = self + "?" for (index, elem) in enumerate(params) { result = result.stringByAppendingFormat("\(elem.0)=\(elem.1)") if (index + 1 != params.count) { result += "&" } } return result } }
mit
aea1a30f70cffb98e88b1147c82ef99e
23.6
79
0.547231
4.066225
false
false
false
false
ecwineland/Presente
Presente/CustomSignUpViewController.swift
1
7435
// // CustomSignUpViewController.swift // Presente // // Created by Evan Wineland on 10/13/15. // Copyright © 2015 Evan Wineland. All rights reserved. // import UIKit import Parse import ParseUI class CustomSignUpViewController: UIViewController { @IBOutlet var iAmLabel: UILabel! @IBOutlet var userRoleSegControl: UISegmentedControl! @IBOutlet var firstNameField: UITextField! @IBOutlet var lastNameField: UITextField! @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! @IBOutlet var confirmPasswordField: UITextField! @IBOutlet var signUpButton: UIButton! var actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView override func viewDidLoad() { // Initially set userRoleSegControl to 0 = "student" self.userRoleSegControl.selectedSegmentIndex = 0 super.viewDidLoad() // Customization for the view let cornerRadiusVal: CGFloat = 5.0 self.view.backgroundColor = UIColor(red: (52/255.0), green:(57/255.0), blue:(56/255.0), alpha: 1) iAmLabel.textColor = UIColor(red: (235/255.0), green:(231/255.0), blue:(221/255.0), alpha: 1) signUpButton.backgroundColor = UIColor(red: (30/255.0), green:(170/255.0), blue:(226/255.0), alpha: 1) signUpButton.layer.cornerRadius = cornerRadiusVal userRoleSegControl.layer.borderColor = UIColor(red: (235/255.0), green:(231/255.0), blue:(221/255.0), alpha: 1).CGColor userRoleSegControl.tintColor = UIColor(red: (30/255.0), green:(170/255.0), blue:(226/255.0), alpha: 1) passwordField.secureTextEntry = true confirmPasswordField.secureTextEntry = true self.actInd.center = self.view.center self.actInd.hidesWhenStopped = true self.actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray view.addSubview(self.actInd) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: Actions @IBAction func signUpAction(sender: AnyObject) { var target:String = "" let firstname = self.firstNameField.text! let lastname = self.lastNameField.text! let username = self.emailField.text! let password = self.passwordField.text! let confirmPassword = self.confirmPasswordField.text! var role:String = "" // Set role variable by checking segmented control index if (userRoleSegControl.selectedSegmentIndex == 0) { role = "Student" } if (userRoleSegControl.selectedSegmentIndex == 1) { role = "Professor" } var errors:[String] = [] // Validate that first name is not empty if (firstname == "") { errors += ["First name cannot be empty!"] } // Validate that last name is not empty if (lastname == "") { errors += ["Last name cannot be empty!"] } // Validate email using regex let emailvalidator = EmailValidation() var (result, errorType) = emailvalidator.validate(username) if (result == false) { errors += ["Email is not valid!"] } // Validate length and format of password // Validate that confirmPassword and password are equal if (confirmPassword == password) { let passwordvalidator = PasswordValidation() var (result, errorType) = passwordvalidator.validate(password) if (result == false) { errors += ["Password must be 8 characters and contain one uppercase!"] } } else { errors += ["Passwords do not match!"] } if (!errors.isEmpty) { var m = "" if errors.count >= 2 { for index in 0...(errors.count-2) { m += errors[index] + "\n" } } m += errors[errors.count-1] let alertController: UIAlertController = UIAlertController(title: m, message: "", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) } // If validations are all OK, new User will be created else { self.actInd.startAnimating() let newUser = PFUser() newUser.username = username newUser.password = password newUser.setValue(lastname, forKey: "lastName") newUser.setValue(firstname, forKey: "firstName") newUser.setValue(role, forKey: "role") newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in self.actInd.stopAnimating() if (target == "Student") { let newStudent = PFObject(className: "Student") newStudent.setValue(lastname, forKey: "lastName") newStudent.setValue(firstname, forKey: "firstName") newStudent.setObject(newUser, forKey: "userID") newStudent.saveInBackgroundWithBlock({ (succeeded, error) -> Void in if error == nil { self.performSegueWithIdentifier("toClasses", sender: sender) return; } else { // Failed to create new Student! } }) return } if (target == "Professor") { let newProfessor = PFObject(className: "Professor") newProfessor.setValue(lastname, forKey: "lastName") newProfessor.setValue(firstname, forKey: "firstName") newProfessor.setObject(newUser, forKey: "userID") newProfessor.saveInBackgroundWithBlock({ (succeeded, error) -> Void in if error == nil { self.performSegueWithIdentifier("toClasses", sender: sender) return; } else { // Failed to create new Professor! } }) return } }) } } }
mit
944284b349d3859f78a74d504baca98d
35.62069
128
0.542507
5.564371
false
false
false
false
AlexandreCassagne/RuffLife-iOS
RuffLife/LostViewController.swift
1
6416
// // LostViewController.swift // RuffLife // // Created by Alexandre Cassagne on 21/10/2017. // Copyright © 2017 Cassagne. All rights reserved. // import UIKit import MapKit import AWSDynamoDB import CoreLocation class LostViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { var dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default () var mapView: MKMapView! // let annotation = MKPointAnnotation() var locationManager = CLLocationManager() @objc func call(sender: Any) { if let url = NSURL(string: "tel://\(5555555555)"), UIApplication.shared.canOpenURL(url as URL) { UIApplication.shared.openURL(url as URL) } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { //return nil so map view draws "blue dot" for standard user location return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.animatesDrop = true pinView!.pinColor = .purple let btn = UIButton(type: .detailDisclosure) btn.addTarget(self, action: #selector(call), for: .touchDown) pinView?.rightCalloutAccessoryView = btn } else { pinView!.annotation = annotation } return pinView } override func loadView() { // Create a map view mapView = MKMapView() // Set it as *the* view of this view controller view = mapView let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"]) segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5) segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_:)), for: .valueChanged) segmentedControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(segmentedControl) let topConstraint = segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8) let margins = view.layoutMarginsGuide let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor) let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor) topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true } @objc func mapTypeChanged(_ segControl: UISegmentedControl) { switch segControl.selectedSegmentIndex { case 0: mapView.mapType = .standard case 1: mapView.mapType = .hybrid case 2: mapView.mapType = .satellite default: break } } // func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { // let location = locations.last as! CLLocation // // let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) // let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) // // mapView.setRegion(region, animated: true) // } override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.showsUserLocation = true locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self //Check for Location Services if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuthorization() } locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() } //Zoom to user location var noLocation = CLLocationCoordinate2D() noLocation.latitude = 42.380999 noLocation.longitude = -71.124998 var viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200) mapView.setRegion(viewRegion, animated: true) DispatchQueue.main.async { self.locationManager.startUpdatingLocation() } // Querying dynambodb let scanExpression = AWSDynamoDBScanExpression() scanExpression.limit = 20 dynamoDBObjectMapper.scan(RuffLife.self, expression: scanExpression).continueWith(block: { (task:AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in if let error = task.error as? NSError { print("The request failed. Error: \(error)") } else if let resultModel = task.result{ // Do something with task.result. for result in resultModel.items { let convertResult = result as! RuffLife let newAnnotation = MKPointAnnotation() newAnnotation.title = convertResult.Breed newAnnotation.subtitle = "Call \(convertResult.PhoneNumber!)" newAnnotation.coordinate = CLLocationCoordinate2D(latitude: convertResult.lat! as! Double, longitude: convertResult.lon! as! Double) self.mapView.addAnnotation(newAnnotation) } } return nil }) } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let location = locations.last as! CLLocation let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) var region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)) region.center = mapView.userLocation.coordinate mapView.setRegion(region, animated: true) } }
mit
d68239b8e7067a9c2d08b5d7b7e7b7b1
38.355828
153
0.665316
5.492295
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Core/HTTPMethod.swift
1
870
// // HTTPMethod.swift // VimeoNetworking // // Created by Rogerio de Paula Assis on 8/31/19. // Copyright © 2019 Vimeo. All rights reserved. // import Foundation /// A typesafe representation of all available HTTP methods public enum HTTPMethod: String { /// The CONNECT method case connect = "CONNECT" /// The DELETE method case delete = "DELETE" /// The GET method case get = "GET" /// The HEAD method case head = "HEAD" /// The OPTIONS method case options = "OPTIONS" /// The PATCH method case patch = "PATCH" /// The POST method case post = "POST" /// The PUT method case put = "PUT" /// The TRACE method case trace = "TRACE" } extension HTTPMethod: Equatable {}
mit
49917333103626cfefa29a974f84d20e
20.195122
59
0.537399
4.45641
false
false
false
false
GreenCom-Networks/ios-charts
Charts/Classes/Data/Implementations/Standard/CombinedChartData.swift
1
5492
// // CombinedChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class CombinedChartData: BarLineScatterCandleBubbleChartData { private var _lineData: LineChartData! private var _lineFilledData: LineChartData! private var _barData: BarChartData! private var _scatterData: ScatterChartData! private var _candleData: CandleChartData! private var _bubbleData: BubbleChartData! public override init() { super.init() } public override init(xVals: [String?]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public var lineData: LineChartData! { get { return _lineData } set { _lineData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } public var lineFilledData: LineChartData! { get { return _lineFilledData } set { _lineFilledData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } public var barData: BarChartData! { get { return _barData } set { _barData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } public var scatterData: ScatterChartData! { get { return _scatterData } set { _scatterData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } public var candleData: CandleChartData! { get { return _candleData } set { _candleData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } public var bubbleData: BubbleChartData! { get { return _bubbleData } set { _bubbleData = newValue for dataSet in newValue.dataSets { _dataSets.append(dataSet) } checkIsLegal(newValue.dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } } /// - returns: all data objects in row: line-bar-scatter-candle-bubble if not null. public var allData: [ChartData] { var data = [ChartData]() if lineData !== nil { data.append(lineData) } if lineFilledData !== nil { data.append(lineFilledData) } if barData !== nil { data.append(barData) } if scatterData !== nil { data.append(scatterData) } if candleData !== nil { data.append(candleData) } if bubbleData !== nil { data.append(bubbleData) } return data; } public override func notifyDataChanged() { if (_lineData !== nil) { _lineData.notifyDataChanged() } if (_lineFilledData !== nil) { _lineFilledData.notifyDataChanged() } if (_barData !== nil) { _barData.notifyDataChanged() } if (_scatterData !== nil) { _scatterData.notifyDataChanged() } if (_candleData !== nil) { _candleData.notifyDataChanged() } if (_bubbleData !== nil) { _bubbleData.notifyDataChanged() } super.notifyDataChanged() // recalculate everything } }
apache-2.0
6c1c6c074b54b518617c2a17cbdf11bf
21.883333
87
0.48161
5.768908
false
false
false
false
SkinnyRat/Benchmark-MNIST
App/ViewController.swift
1
1475
// // ViewController.swift // CV // // Created by ThisUser on 8/6/19. // Copyright © 2019 ThisUser. All rights reserved. // import UIKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet weak var MainText: UILabel! var camera: Camera! var btnPressed: Int32! var theTitle: Float32! // Initialize Camera when the view loads override func viewDidLoad() { super.viewDidLoad() theTitle = 10.0 btnPressed = 1 camera = Camera(controller: self as? UIViewController & CameraDelegate, andImageView: imageView, titleText: &theTitle, bPressed: &btnPressed) } // Start it when it appears override func viewDidAppear(_ animated: Bool) { camera.start() } // Stop it when it disappears override func viewWillDisappear(_ animated: Bool) { camera.stop() } // Dispose of any resources that can be recreated. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // Update main label text at top. func updateMaintext() { let S = NSString(format: "Distance: %.1fm", theTitle) self.MainText.text = S as String } var imagePicker: UIImagePickerController! @IBAction func takePhoto(_ sender: Any) { updateMaintext() btnPressed += 1 } }
apache-2.0
9164c7d7b0c9306f9ee56f933892678c
23.983051
153
0.642469
4.649842
false
false
false
false
zachmokahn/SUV
Sources/SUV/Handle/TCPHandle.swift
1
726
public class TCPHandle: HandleType { public typealias Pointer = UnsafeMutablePointer<UVTCPType> public let loop: Loop public let pointer: Pointer public let status: Status public init(_ loop: Loop, uv_tcp_init: TCPInit = UVTCPInit) { self.loop = loop self.pointer = Pointer.alloc(sizeof(UVTCPType)) self.status = Status(uv_tcp_init(self.loop.pointer, self.pointer)) } public func bind(addr: Addr, inet: INet = .AF, uv_tcp_bind: TCPBind = UVTCPBind) -> SUV.Status { return Status(uv_tcp_bind(self.pointer, addr.pointer, inet.family)) } public func close(uv_close uv_close: Close = UVClose, _ callback: (Handle) -> Void) { Handle(self).close(uv_close: uv_close) { callback($0) } } }
mit
1916f2214aac7eaf896dfb202ae3e867
32
98
0.69146
3.315068
false
false
false
false
KarlWarfel/nutshell-ios
Nutshell/GraphView/Tidepool Graph/BoluslGraphData.swift
1
23197
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class BolusGraphDataType: GraphDataType { var extendedValue: CGFloat? var duration: NSTimeInterval? var expectedNormal: CGFloat? var expectedExtended: CGFloat? var expectedDuration: NSTimeInterval? var id: String init(event: Bolus, timeOffset: NSTimeInterval) { self.id = event.id! as String if event.extended != nil { self.extendedValue = CGFloat(event.extended!) } if event.duration != nil { let durationInMS = Int(event.duration!) self.duration = NSTimeInterval(durationInMS / 1000) } if event.expectedNormal != nil { self.expectedNormal = CGFloat(event.expectedNormal!) } if event.expectedExtended != nil { self.expectedExtended = CGFloat(event.expectedExtended!) } if event.expectedDuration != nil { let expectedDurationInMS = Int(event.expectedDuration!) self.expectedDuration = NSTimeInterval(expectedDurationInMS / 1000) } let value = CGFloat(event.value!) super.init(value: value, timeOffset: timeOffset) } func maxValue() -> CGFloat { var maxValue: CGFloat = value if let expectedNormal = expectedNormal { if expectedNormal > maxValue { maxValue = expectedNormal } } return maxValue } init(curDatapoint: BolusGraphDataType, deltaTime: NSTimeInterval) { self.id = curDatapoint.id self.extendedValue = curDatapoint.extendedValue self.duration = curDatapoint.duration self.expectedNormal = curDatapoint.expectedNormal self.expectedExtended = curDatapoint.expectedExtended self.expectedDuration = curDatapoint.expectedDuration super.init(value: curDatapoint.value, timeOffset: deltaTime) } //(timeOffset: NSTimeInterval, value: NSNumber, suppressed: NSNumber?) override func typeString() -> String { return "bolus" } } /// BolusGraphDataType and WizardGraphDataType layers are coupled. Wizard datapoints are drawn after bolus datapoints, and directly above their corresponding bolus datapoint. Also, the bolus drawing needs to refer to the corresponding wizard data to determine whether an override has taken place. class BolusGraphDataLayer: TidepoolGraphDataLayer { // when drawing the bolus layer, it is necessary to check for corresponding wizard values to determine if a bolus is an override of a wizard recommendation. var wizardLayer: WizardGraphDataLayer? // config... private let kBolusTextBlue = Styles.mediumBlueColor private let kBolusBlueRectColor = Styles.blueColor private let kBolusOverrideIconColor = UIColor(hex: 0x0C6999) private let kBolusInterruptBarColor = Styles.peachColor private let kBolusRectWidth: CGFloat = 14.0 private let kBolusLabelToRectGap: CGFloat = 0.0 private let kBolusLabelRectHeight: CGFloat = 12.0 private let kBolusMinScaleValue: CGFloat = 1.0 private let kExtensionLineHeight: CGFloat = 2.0 private let kExtensionEndshapeWidth: CGFloat = 7.0 private let kExtensionEndshapeHeight: CGFloat = 11.0 private let kExtensionInterruptBarWidth: CGFloat = 6.0 private let kBolusMaxExtension: NSTimeInterval = 6*60*60 // Assume maximum bolus extension of 6 hours! // locals... private var context: CGContext? private var startValue: CGFloat = 0.0 private var startTimeOffset: NSTimeInterval = 0.0 private var startValueSuppressed: CGFloat? // // MARK: - Loading data // override func nominalPixelWidth() -> CGFloat { return kBolusRectWidth } // NOTE: the first BolusGraphDataLayer slice that has loadDataItems called loads the bolus data for the entire graph time interval override func loadStartTime() -> NSDate { return layout.graphStartTime.dateByAddingTimeInterval(-kBolusMaxExtension) } override func loadEndTime() -> NSDate { let timeExtensionForDataFetch = NSTimeInterval(nominalPixelWidth()/viewPixelsPerSec) return layout.graphStartTime.dateByAddingTimeInterval(layout.graphTimeInterval + timeExtensionForDataFetch) } override func typeString() -> String { return "bolus" } override func loadEvent(event: CommonData, timeOffset: NSTimeInterval) { if let event = event as? Bolus { //NSLog("Adding Bolus event: \(event)") if event.value != nil { let eventTime = event.time! let graphTimeOffset = eventTime.timeIntervalSinceDate(layout.graphStartTime) let bolus = BolusGraphDataType(event: event, timeOffset: graphTimeOffset) dataArray.append(bolus) let maxValue = bolus.maxValue() if maxValue > layout.maxBolus { layout.maxBolus = maxValue } } else { NSLog("ignoring Bolus event with nil value") } } } override func loadDataItems() { // Note: since each graph tile needs to know the max bolus value for the graph, the first tile to load loads data for the whole graph range... if layout.allBolusData == nil { dataArray = [] super.loadDataItems() layout.allBolusData = dataArray if layout.maxBolus < kBolusMinScaleValue { layout.maxBolus = kBolusMinScaleValue } //NSLog("Prefetched \(dataArray.count) bolus items for graph") } dataArray = [] let dataLayerOffset = startTime.timeIntervalSinceDate(layout.graphStartTime) let rangeStart = dataLayerOffset - kBolusMaxExtension let timeExtensionForDataFetch = NSTimeInterval(nominalPixelWidth()/viewPixelsPerSec) let rangeEnd = dataLayerOffset + timeIntervalForView + timeExtensionForDataFetch // copy over cached items in the range needed for this tile! for item in layout.allBolusData! { if let bolusItem = item as? BolusGraphDataType { if bolusItem.timeOffset >= rangeStart && bolusItem.timeOffset <= rangeEnd { let copiedItem = BolusGraphDataType(curDatapoint: bolusItem, deltaTime: bolusItem.timeOffset - dataLayerOffset) dataArray.append(copiedItem) } } } //NSLog("Copied \(dataArray.count) bolus items from graph cache for slice at offset \(dataLayerOffset/3600) hours") } // // MARK: - Drawing data points // // override for any draw setup override func configureForDrawing() { context = UIGraphicsGetCurrentContext() wizardLayer?.bolusRects = [] startValue = 0.0 startTimeOffset = 0.0 startValueSuppressed = nil } // override! override func drawDataPointAtXOffset(xOffset: CGFloat, dataPoint: GraphDataType) { if let bolus = dataPoint as? BolusGraphDataType { // Bolus rect is center-aligned to time start let centerX = xOffset var bolusValue = bolus.value if bolusValue > layout.maxBolus && bolusValue > kBolusMinScaleValue { NSLog("ERR: max bolus exceeded!") bolusValue = layout.maxBolus } // Measure out the label first so we know how much space we have for the rect below it. let bolusFloatValue = Float(bolus.value) var bolusLabelTextContent = String(format: "%.2f", bolusFloatValue) if bolusLabelTextContent.hasSuffix("0") { bolusLabelTextContent = String(format: "%.1f", bolusFloatValue) } let bolusLabelStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle bolusLabelStyle.alignment = .Center let bolusLabelFontAttributes = [NSFontAttributeName: Styles.smallSemiboldFont, NSForegroundColorAttributeName: kBolusTextBlue, NSParagraphStyleAttributeName: bolusLabelStyle] var bolusLabelTextSize = bolusLabelTextContent.boundingRectWithSize(CGSizeMake(CGFloat.infinity, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: bolusLabelFontAttributes, context: nil).size bolusLabelTextSize = CGSize(width: ceil(bolusLabelTextSize.width), height: ceil(bolusLabelTextSize.height)) let pixelsPerValue = (layout.yPixelsBolus - bolusLabelTextSize.height - kBolusLabelToRectGap) / CGFloat(layout.maxBolus) var override = false var interrupted = false var wizardHasOriginal = false var originalValue: CGFloat = 0.0 // See if there is a corresponding wizard datapoint let wizardPoint = getWizardForBolusId(bolus.id) if let wizardPoint = wizardPoint { //NSLog("found wizard with carb \(wizardPoint.value) for bolus of value \(bolusValue)") if let recommended = wizardPoint.recommendedNet { if recommended != bolusValue { override = true wizardHasOriginal = true originalValue = CGFloat(recommended) } } } // Draw the bolus rectangle let rectLeft = floor(centerX - (kBolusRectWidth/2)) let bolusRectHeight = ceil(pixelsPerValue * bolusValue) var yOriginBolusRect = layout.yBottomOfBolus - bolusRectHeight let bolusValueRect = CGRect(x: rectLeft, y: yOriginBolusRect, width: kBolusRectWidth, height: bolusRectHeight) let bolusValueRectPath = UIBezierPath(rect: bolusValueRect) kBolusBlueRectColor.setFill() bolusValueRectPath.fill() layout.backgroundColor.setStroke() bolusValueRectPath.lineWidth = 0.5 bolusValueRectPath.stroke() // Handle interrupted boluses if let expectedNormal = bolus.expectedNormal { if expectedNormal > bolusValue { interrupted = true override = true originalValue = expectedNormal wizardHasOriginal = false } else { NSLog("UNEXPECTED DATA - expectedNormal \(expectedNormal) not > bolus \(bolusValue)") } } // Handle extended, and interrupted extended bolus portion if let extendedValue = bolus.extendedValue { var extendedOriginal = extendedValue if let expectedExtended = bolus.expectedExtended { if expectedExtended > extendedValue { override = true interrupted = true extendedOriginal = expectedExtended } else { NSLog("UNEXPECTED DATA - expectedExtended \(expectedExtended) not > extended \(extendedValue)") } } if !wizardHasOriginal { originalValue += extendedOriginal } } // Draw override/interrupted rectangle and icon/bar if applicable if override { let originalYOffset = layout.yBottomOfBolus - ceil(pixelsPerValue * originalValue) var yOriginOverrideIcon = originalYOffset // if recommended value was higher than the bolus, first draw a light-colored rect with dashed outline at the recommended value if originalValue > bolusValue { yOriginOverrideIcon = yOriginBolusRect // comment the following line to place the label on top of the bolus rect, over the recommended rect bottom yOriginBolusRect = originalYOffset // bump to recommended height so label goes above this! let originalRectHeight = ceil(pixelsPerValue * (originalValue - bolusValue)) let originalRect = CGRect(x: rectLeft+0.5, y: originalYOffset+0.5, width: kBolusRectWidth-1.0, height: originalRectHeight) let originalRectPath = UIBezierPath(rect: originalRect) // fill with background color layout.backgroundColor.setFill() originalRectPath.fill() // then outline with a dashed line kBolusBlueRectColor.setStroke() originalRectPath.lineWidth = 1 originalRectPath.lineCapStyle = .Butt let pattern: [CGFloat] = [2.0, 2.0] originalRectPath.setLineDash(pattern, count: 2, phase: 0.0) originalRectPath.stroke() } if interrupted { self.drawBolusInterruptBar(rectLeft, yOffset: yOriginOverrideIcon) } else { self.drawBolusOverrideIcon(rectLeft, yOffset: yOriginOverrideIcon, pointUp: originalValue < bolusValue) } } // Finally, draw the bolus label above the rectangle let bolusLabelRect = CGRect(x:centerX-(bolusLabelTextSize.width/2), y: yOriginBolusRect - kBolusLabelToRectGap - bolusLabelTextSize.height, width: bolusLabelTextSize.width, height: bolusLabelTextSize.height) let bolusLabelPath = UIBezierPath(rect: bolusLabelRect.insetBy(dx: 0.0, dy: 2.0)) layout.backgroundColor.setFill() bolusLabelPath.fill() CGContextSaveGState(context!) CGContextClipToRect(context!, bolusLabelRect); bolusLabelTextContent.drawInRect(bolusLabelRect, withAttributes: bolusLabelFontAttributes) CGContextRestoreGState(context!) if let extendedValue = bolus.extendedValue, duration = bolus.duration { let width = floor(CGFloat(duration) * viewPixelsPerSec) var height = ceil(extendedValue * pixelsPerValue) if height < kExtensionLineHeight/2.0 { // tweak to align extension rect with bottom of bolus rect height = kExtensionLineHeight/2.0 } var originalWidth: CGFloat? if let _ = bolus.expectedExtended, expectedDuration = bolus.expectedDuration { // extension was interrupted... if expectedDuration > duration { originalWidth = floor(CGFloat(expectedDuration) * viewPixelsPerSec) } else { NSLog("UNEXPECTED DATA - expectedDuration \(expectedDuration) not > duration \(duration)") } } var yOrigin = layout.yBottomOfBolus - height if yOrigin == bolusValueRect.origin.y { // tweak to align extension rect with top of bolus rect yOrigin = yOrigin + kExtensionLineHeight/2.0 } drawBolusExtension(bolusValueRect.origin.x + bolusValueRect.width, centerY: yOrigin, width: width, originalWidth: originalWidth) //NSLog("bolus extension duration \(bolus.duration/60) minutes, extended value \(bolus.extendedValue), total value: \(bolus.value)") } let completeBolusRect = bolusLabelRect.union(bolusValueRect) wizardLayer?.bolusRects.append(completeBolusRect) wizardPoint?.bolusTopY = completeBolusRect.origin.y } } private func drawBolusOverrideIcon(xOffset: CGFloat, yOffset: CGFloat, pointUp: Bool) { // The override icon has its origin at the y position corresponding to the suggested bolus value that was overridden. let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context!) CGContextTranslateCTM(context!, xOffset, yOffset) let flip: CGFloat = pointUp ? -1.0 : 1.0 let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(0, 0)) bezierPath.addLineToPoint(CGPointMake(0, 3.5*flip)) bezierPath.addLineToPoint(CGPointMake(3.5, 3.5*flip)) bezierPath.addLineToPoint(CGPointMake(7, 7*flip)) bezierPath.addLineToPoint(CGPointMake(10.5, 3.5*flip)) bezierPath.addLineToPoint(CGPointMake(14, 3.5*flip)) bezierPath.addLineToPoint(CGPointMake(14, 0)) bezierPath.addLineToPoint(CGPointMake(0, 0)) bezierPath.closePath() kBolusOverrideIconColor.setFill() bezierPath.fill() CGContextRestoreGState(context!) } private func drawBolusInterruptBar(xOffset: CGFloat, yOffset: CGFloat) { // Bar width matches width of bolus rect, height is 3.5 points let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context!) let barWidth = kBolusRectWidth - 1.0 CGContextTranslateCTM(context!, xOffset + 0.5, yOffset) let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(0, 0)) bezierPath.addLineToPoint(CGPointMake(0, 3.5)) bezierPath.addLineToPoint(CGPointMake(barWidth, 3.5)) bezierPath.addLineToPoint(CGPointMake(barWidth, 0)) bezierPath.addLineToPoint(CGPointMake(0, 0)) bezierPath.closePath() kBolusInterruptBarColor.setFill() bezierPath.fill() CGContextRestoreGState(context!) } private func drawBolusExtensionInterruptBar(xOffset: CGFloat, centerY: CGFloat) { // Blip extension interrupt bar width is smaller than bolus interrupt bar by 10:24 ratio, x:14 here // Bar width is 5 points, and fits on the end of the delivered extension bar let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context!) let barHeight = kExtensionLineHeight CGContextTranslateCTM(context!, xOffset, centerY-(barHeight/2.0)) let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(0, 0)) bezierPath.addLineToPoint(CGPointMake(kExtensionInterruptBarWidth, 0)) bezierPath.addLineToPoint(CGPointMake(kExtensionInterruptBarWidth, barHeight)) bezierPath.addLineToPoint(CGPointMake(0, barHeight)) bezierPath.addLineToPoint(CGPointMake(0, 0)) bezierPath.closePath() kBolusInterruptBarColor.setFill() bezierPath.fill() CGContextRestoreGState(context!) } private func drawBolusExtensionShape(originX: CGFloat, centerY: CGFloat, width: CGFloat, borderOnly: Bool = false, noEndShape: Bool = false) { let centerY = round(centerY) let originY = centerY - (kExtensionEndshapeHeight/2.0) let bottomLineY = centerY + (kExtensionLineHeight / 2.0) let topLineY = centerY - (kExtensionLineHeight / 2.0) let rightSideX = originX + width //// Bezier Drawing let bezierPath = UIBezierPath() if noEndShape { bezierPath.moveToPoint(CGPointMake(rightSideX, topLineY)) bezierPath.addLineToPoint(CGPointMake(rightSideX, bottomLineY)) bezierPath.addLineToPoint(CGPointMake(originX, bottomLineY)) bezierPath.addLineToPoint(CGPointMake(originX, topLineY)) bezierPath.addLineToPoint(CGPointMake(rightSideX, topLineY)) } else { bezierPath.moveToPoint(CGPointMake(rightSideX, originY)) bezierPath.addLineToPoint(CGPointMake(rightSideX, originY + kExtensionEndshapeHeight)) bezierPath.addLineToPoint(CGPointMake(rightSideX - kExtensionEndshapeWidth, bottomLineY)) bezierPath.addLineToPoint(CGPointMake(originX, bottomLineY)) bezierPath.addLineToPoint(CGPointMake(originX, topLineY)) bezierPath.addLineToPoint(CGPointMake(rightSideX - kExtensionEndshapeWidth, topLineY)) bezierPath.addLineToPoint(CGPointMake(rightSideX, originY)) } bezierPath.closePath() if borderOnly { // use a border, with no fill kBolusBlueRectColor.setStroke() bezierPath.lineWidth = 1 bezierPath.lineCapStyle = .Butt let pattern: [CGFloat] = [2.0, 2.0] bezierPath.setLineDash(pattern, count: 2, phase: 0.0) bezierPath.stroke() } else { kBolusBlueRectColor.setFill() bezierPath.fill() } } private func drawBolusExtension( originX: CGFloat, centerY: CGFloat, width: CGFloat, originalWidth: CGFloat?) { var width = width var originX = originX if width < kExtensionEndshapeWidth { // If extension is shorter than the end trapezoid shape, only draw that shape, backing it into the bolus rect originX = originX - (kExtensionEndshapeWidth - width) width = kExtensionEndshapeWidth } // only draw original end shape if bolus was not interrupted! drawBolusExtensionShape(originX, centerY: centerY, width: width, borderOnly: false, noEndShape: (originalWidth != nil)) // handle interrupted extended bolus if let originalWidth = originalWidth { // draw original extension, but make sure it is at least as large as the end shape! var extensionWidth = originalWidth - width if extensionWidth < kExtensionEndshapeWidth { extensionWidth = kExtensionEndshapeWidth } drawBolusExtensionShape(originX + width, centerY: centerY, width: extensionWidth, borderOnly: true) // always draw an interrupt bar at the end of the delivered part of the extension drawBolusExtensionInterruptBar(originX + width, centerY: centerY) } } private func getWizardForBolusId(bolusId: String) -> WizardGraphDataType? { if let wizardLayer = wizardLayer { for wizardItem in wizardLayer.dataArray { if let wizardItem = wizardItem as? WizardGraphDataType { if let wizBolusId = wizardItem.bolusId { if wizBolusId == bolusId { return wizardItem } } } } } return nil } }
bsd-2-clause
a6875b7381e60e92a02e76e7f7ee3bab
46.828866
296
0.636203
5.655046
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Node Output Plot.xcplaygroundpage/Contents.swift
1
1004
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Node Output Plot //: ### What's interesting here is that we're plotting the waveform BEFORE the delay is processed import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var delay = AKDelay(player) delay.time = 0.1 // seconds delay.feedback = 0.9 // Normalized Value 0 - 1 delay.dryWetMix = 0.6 // Normalized Value 0 - 1 AudioKit.output = delay AudioKit.start() player.play() let plot = AKNodeOutputPlot(player) plot.plot?.plotType = .Rolling plot.plot?.shouldFill = true plot.plot?.shouldMirror = true plot.plot?.color = UIColor.blueColor() let view = plot.containerView XCPlaygroundPage.currentPage.liveView = plot.containerView XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
aba876deca5c103d57d802da8572108d
26.135135
97
0.728088
3.691176
false
false
false
false
crash-wu/SGRoutePlan
Example/SGRoutePlan/BusLineSectionView.swift
1
3455
// // BusLineSectionView.swift // imapMobile // // Created by 吴小星 on 16/5/31. // Copyright © 2016年 crash. All rights reserved. // import UIKit class BusLineSectionView: UITableViewHeaderFooterView { var contrainView :UIView! var lineNameLb :UILabel!//路线名称 var lineInfoLb :UILabel!//路线详情名称 var arrowImg :UIImageView!//箭头 var isOpen: Bool = false { didSet { rotateIndicate() } } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.contentView.backgroundColor = UIColor.whiteColor() contrainView = UIView() self.contentView.addSubview(contrainView) lineNameLb = UILabel() contrainView.addSubview(lineNameLb) lineInfoLb = UILabel() contrainView.addSubview(lineInfoLb) arrowImg = UIImageView() contrainView.addSubview(arrowImg) contrainView.snp_makeConstraints { (make) in make.top.equalTo(self.contentView.snp_top).offset(5) make.left.equalTo(self.contentView.snp_left).offset(5) make.right.equalTo(self.contentView.snp_right).offset(-5) make.bottom.equalTo(self.contentView.snp_bottom).offset(-5) } contrainView.backgroundColor = UIColor(hexString: "#f5fafb") lineNameLb.snp_makeConstraints(closure: {(make) in make.top.equalTo(contrainView.snp_top) make.left.equalTo(contrainView.snp_left).offset(5) make.right.equalTo(contrainView.snp_right).offset(-25) make.bottom.equalTo(self.lineInfoLb.snp_top) make.height.equalTo(self.lineInfoLb.snp_height) }) lineNameLb.textAlignment = .Left lineNameLb.textColor = UIColor(hexString: "#5a5a5a") lineNameLb.font = UIFont.systemFontOfSize(13) lineInfoLb.snp_makeConstraints(closure: {(make) in make.top.equalTo(self.lineNameLb.snp_bottom) make.left.equalTo(contrainView.snp_left).offset(15) make.right.equalTo(contrainView.snp_right).offset(-25) make.bottom.equalTo(contrainView.snp_bottom).offset(2) make.height.equalTo(self.lineNameLb.snp_height) }) lineInfoLb.textAlignment = .Left lineInfoLb.textColor = UIColor(hexString: "#4d757c") lineInfoLb.font = UIFont.systemFontOfSize(12) arrowImg.snp_makeConstraints(closure: {(make) in make.centerY.equalTo(contrainView.snp_centerY) make.width.equalTo(10) make.height.equalTo(5) make.right.equalTo(contrainView.snp_right).offset(-10) }) arrowImg.image = UIImage(named: "下拉") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 旋转标识图片 private func rotateIndicate() { UIView.animateWithDuration(0.3) { [weak self] in if self!.isOpen { self?.arrowImg.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)); }else{ self?.arrowImg.transform = CGAffineTransformMakeRotation (0); } } } }
mit
30c940d04d328da337dea83abcd7bb53
30.537037
88
0.59219
4.602703
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Extensions/Sources/SwiftExtensions/Result.swift
1
5584
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public protocol ResultProtocol { associatedtype Success associatedtype Failure: Error var result: Result<Success, Failure> { get } static func success(_ success: Success) -> Self static func failure(_ failure: Failure) -> Self func map<NewSuccess>( _ transform: (Success) -> NewSuccess ) -> Result<NewSuccess, Failure> func mapError<NewFailure>( _ transform: (Failure) -> NewFailure) -> Result<Success, NewFailure> where NewFailure: Error func flatMap<NewSuccess>( _ transform: (Success) -> Result<NewSuccess, Failure> ) -> Result<NewSuccess, Failure> func flatMapError<NewFailure>( _ transform: (Failure) -> Result<Success, NewFailure> ) -> Result<Success, NewFailure> where NewFailure: Error func get() throws -> Success } extension Result: ResultProtocol { public var result: Result<Success, Failure> { self } @inlinable public var success: Success? { switch result { case .success(let success): return success case .failure: return nil } } @inlinable public var failure: Failure? { switch result { case .failure(let failure): return failure case .success: return nil } } } extension ResultProtocol { @inlinable public var isSuccess: Bool { success != nil } @inlinable public var isFailure: Bool { failure != nil } @inlinable public var success: Success? { switch result { case .success(let success): return success case .failure: return nil } } @inlinable public var failure: Failure? { switch result { case .success: return nil case .failure(let failure): return failure } } } extension RandomAccessCollection where Element: ResultProtocol { public func zip() -> Result<[Element.Success], Element.Failure> { switch count { case 0: return .success([]) case 1: return self[_0] .map { [$0] } case 2: return self[_0].result .zip(self[_1].result) .map { [$0, $1] } case 3: return self[_0].result .zip(self[_1].result, self[_2].result) .map { [$0, $1, $2] } case 4: return self[_0].result .zip(self[_1].result, self[_2].result, self[_3].result) .map { [$0, $1, $2, $3] } default: return prefix(4).zip() .zip(dropFirst(4).zip()) .map { $0 + $1 } } } private var _0: Index { startIndex } private var _1: Index { index(after: startIndex) } private var _2: Index { index(after: _1) } private var _3: Index { index(after: _2) } } extension Result { public func zip<A>( _ a: Result<A, Failure> ) -> Result<(Success, A), Failure> { flatMap { success in switch a { case .success(let a): return .success((success, a)) case .failure(let error): return .failure(error) } } } public func zip<A, B>( _ a: Result<A, Failure>, _ b: Result<B, Failure> ) -> Result<(Success, A, B), Failure> { zip(a) .zip(b) .map { ($0.0, $0.1, $1) } } public func zip<A, B, C>( _ a: Result<A, Failure>, _ b: Result<B, Failure>, _ c: Result<C, Failure> // swiftlint:disable:next large_tuple ) -> Result<(Success, A, B, C), Failure> { zip(a, b) .zip(c) .map { ($0.0, $0.1, $0.2, $1) } } public func zip<A, B, C, D>( _ a: Result<A, Failure>, _ b: Result<B, Failure>, _ c: Result<C, Failure>, _ d: Result<D, Failure> // swiftlint:disable:next large_tuple ) -> Result<(Success, A, B, C, D), Failure> { zip(a, b, c) .zip(d) .map { ($0.0, $0.1, $0.2, $0.3, $1) } } } extension Result where Success: OptionalProtocol { public func onNil(error: Failure) -> Result<Success.Wrapped, Failure> { flatMap { element -> Result<Success.Wrapped, Failure> in guard let value = element.wrapped else { return .failure(error) } return .success(value) } } } extension Result where Failure == Never { public func mapError<E: Error>(to type: E.Type) -> Result<Success, E> { mapError() } public func mapError<E: Error>() -> Result<Success, E> { switch self { case .success(let value): return .success(value) } } } extension Result where Success == Never { public func map<T>(to type: T.Type) -> Result<T, Failure> { map() } public func map<T>() -> Result<T, Failure> { switch self { case .failure(let error): return .failure(error) } } } extension Result { public func replaceError<E: Error>(with error: E) -> Result<Success, E> { mapError { _ in error } } } extension Result { public func eraseError() -> Result<Success, Error> { mapError { $0 } } } extension Result { public func reduce<NewValue>(_ transform: (Result<Success, Failure>) -> NewValue) -> NewValue { transform(self) } }
lgpl-3.0
ef80e20150035e48c3839fee6b909752
24.262443
100
0.527852
4.007897
false
false
false
false
1yvT0s/Nuke
Nuke/Source/Core/ImageManagerLoader.swift
4
11052
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit internal protocol ImageManagerLoaderDelegate: class { func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64) func imageLoader(imageLoader: ImageManagerLoader, imageTask: ImageTask, didCompleteWithImage image: UIImage?, error: ErrorType?) } internal class ImageManagerLoader { internal weak var delegate: ImageManagerLoaderDelegate? private let conf: ImageManagerConfiguration private var pendingTasks = [ImageTask]() private var executingTasks = [ImageTask : ImageLoaderTask]() private var sessionTasks = [ImageRequestKey : ImageLoaderSessionTask]() private let queue = dispatch_queue_create("ImageManagerLoader-InternalSerialQueue", DISPATCH_QUEUE_SERIAL) private let decodingQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() private let processingQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 2 return queue }() internal init(configuration: ImageManagerConfiguration) { self.conf = configuration } internal func startLoadingForTask(task: ImageTask) { dispatch_async(self.queue) { self.pendingTasks.append(task) self.executePendingTasks() } } private func startSessionTaskForTask(task: ImageLoaderTask) { let key = ImageRequestKey(task.request, type: .Load, owner: self) var sessionTask: ImageLoaderSessionTask! = self.sessionTasks[key] if sessionTask == nil { sessionTask = ImageLoaderSessionTask(key: key) let dataTask = self.conf.dataLoader.imageDataTaskWithURL(task.request.URL, progressHandler: { [weak self] completedUnits, totalUnits in self?.sessionTask(sessionTask, didUpdateProgressWithCompletedUnitCount: completedUnits, totalUnitCount: totalUnits) }, completionHandler: { [weak self] data, _, error in self?.sessionTask(sessionTask, didCompleteWithData: data, error: error) }) dataTask.resume() sessionTask.dataTask = dataTask self.sessionTasks[key] = sessionTask } else { self.delegate?.imageLoader(self, imageTask: task.imageTask, didUpdateProgressWithCompletedUnitCount: sessionTask.completedUnitCount, totalUnitCount: sessionTask.completedUnitCount) } task.sessionTask = sessionTask sessionTask.tasks.append(task) } private func sessionTask(sessionTask: ImageLoaderSessionTask, didUpdateProgressWithCompletedUnitCount completedUnitCount: Int64, totalUnitCount: Int64) { dispatch_async(self.queue) { sessionTask.totalUnitCount = totalUnitCount sessionTask.completedUnitCount = completedUnitCount for loaderTask in sessionTask.tasks { self.delegate?.imageLoader(self, imageTask: loaderTask.imageTask, didUpdateProgressWithCompletedUnitCount: completedUnitCount, totalUnitCount: totalUnitCount) } } } private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithData data: NSData?, error: ErrorType?) { if let data = data { self.decodingQueue.addOperationWithBlock { [weak self] in let image = self?.conf.decoder.imageWithData(data) self?.sessionTask(sessionTask, didCompleteWithImage: image, error: error) } } else { self.sessionTask(sessionTask, didCompleteWithImage: nil, error: error) } } private func sessionTask(sessionTask: ImageLoaderSessionTask, didCompleteWithImage image: UIImage?, error: ErrorType?) { dispatch_async(self.queue) { for loaderTask in sessionTask.tasks { self.processImage(image, error: error, forLoaderTask: loaderTask) } sessionTask.tasks.removeAll() sessionTask.dataTask = nil self.removeSessionTask(sessionTask) } } private func processImage(image: UIImage?, error: ErrorType?, forLoaderTask task: ImageLoaderTask) { if let image = image, processor = self.processorForRequest(task.request) { let operation = NSBlockOperation { [weak self] in let processedImage = processor.processImage(image) self?.storeImage(processedImage, forRequest: task.request) self?.loaderTask(task, didCompleteWithImage: processedImage, error: error) } self.processingQueue.addOperation(operation) task.processingOperation = operation } else { self.storeImage(image, forRequest: task.request) self.loaderTask(task, didCompleteWithImage: image, error: error) } } private func processorForRequest(request: ImageRequest) -> ImageProcessing? { var processors = [ImageProcessing]() if request.shouldDecompressImage { processors.append(ImageDecompressor(targetSize: request.targetSize, contentMode: request.contentMode)) } if let processor = request.processor { processors.append(processor) } return processors.isEmpty ? nil : ImageProcessorComposition(processors: processors) } private func loaderTask(task: ImageLoaderTask, didCompleteWithImage image: UIImage?, error: ErrorType?) { dispatch_async(self.queue) { self.delegate?.imageLoader(self, imageTask: task.imageTask, didCompleteWithImage: image, error: error) self.executingTasks[task.imageTask] = nil self.executePendingTasks() } } internal func stopLoadingForTask(imageTask: ImageTask) { dispatch_async(self.queue) { if let loaderTask = self.executingTasks[imageTask], sessionTask = loaderTask.sessionTask { if let index = (sessionTask.tasks.indexOf { $0 === loaderTask }) { sessionTask.tasks.removeAtIndex(index) } if sessionTask.tasks.isEmpty { sessionTask.dataTask?.cancel() sessionTask.dataTask = nil self.removeSessionTask(sessionTask) } loaderTask.processingOperation?.cancel() self.executingTasks[imageTask] = nil self.executePendingTasks() } else if let index = (self.pendingTasks.indexOf { $0 === imageTask }) { self.pendingTasks.removeAtIndex(index) } } } // MARK: Queue private func executePendingTasks() { func shouldExecuteNextPendingTask() -> Bool { return self.executingTasks.count < self.conf.maxConcurrentTaskCount } func dequeueNextPendingTask() -> ImageTask? { return self.pendingTasks.isEmpty ? nil : self.pendingTasks.removeFirst() } while shouldExecuteNextPendingTask() { guard let task = dequeueNextPendingTask() else { return } let loaderTask = ImageLoaderTask(imageTask: task) self.executingTasks[task] = loaderTask self.startSessionTaskForTask(loaderTask) } } // MARK: Misc internal func cachedResponseForRequest(request: ImageRequest) -> ImageCachedResponse? { return self.conf.cache?.cachedResponseForKey(ImageRequestKey(request, type: .Cache, owner: self)) } private func storeImage(image: UIImage?, forRequest request: ImageRequest) { if let image = image { let cachedResponse = ImageCachedResponse(image: image, userInfo: nil) self.conf.cache?.storeResponse(cachedResponse, forKey: ImageRequestKey(request, type: .Cache, owner: self)) } } internal func preheatingKeyForRequest(request: ImageRequest) -> ImageRequestKey { return ImageRequestKey(request, type: .Cache, owner: self) } private func removeSessionTask(task: ImageLoaderSessionTask) { if self.sessionTasks[task.key] === task { self.sessionTasks[task.key] = nil } } } // MARK: ImageManagerLoader: ImageRequestKeyOwner extension ImageManagerLoader: ImageRequestKeyOwner { internal func isImageRequestKey(lhs: ImageRequestKey, equalToKey rhs: ImageRequestKey) -> Bool { switch lhs.type { case .Cache: guard self.conf.dataLoader.isRequestCacheEquivalent(lhs.request, toRequest: rhs.request) else { return false } switch (self.processorForRequest(lhs.request), self.processorForRequest(rhs.request)) { case (.Some(let lhs), .Some(let rhs)): return lhs.isEquivalentToProcessor(rhs) case (.None, .None): return true default: return false } case .Load: return self.conf.dataLoader.isRequestLoadEquivalent(lhs.request, toRequest: rhs.request) } } } // MARK: - ImageLoaderTask private class ImageLoaderTask { let imageTask: ImageTask var request: ImageRequest { return self.imageTask.request } var sessionTask: ImageLoaderSessionTask? var processingOperation: NSOperation? private init(imageTask: ImageTask) { self.imageTask = imageTask } } // MARK: - ImageLoaderSessionTask private class ImageLoaderSessionTask { let key: ImageRequestKey var dataTask: NSURLSessionTask? var tasks = [ImageLoaderTask]() var totalUnitCount: Int64 = 0 var completedUnitCount: Int64 = 0 init(key: ImageRequestKey) { self.key = key } } // MARK: - ImageRequestKey private protocol ImageRequestKeyOwner: class { func isImageRequestKey(key: ImageRequestKey, equalToKey: ImageRequestKey) -> Bool } private enum ImageRequestKeyType { case Load, Cache } /** Makes it possible to use ImageRequest as a key in dictionaries, sets, etc */ internal class ImageRequestKey: NSObject { private let request: ImageRequest private let type: ImageRequestKeyType private weak var owner: ImageRequestKeyOwner? private init(_ request: ImageRequest, type: ImageRequestKeyType, owner: ImageRequestKeyOwner) { self.request = request self.type = type self.owner = owner } override var hash: Int { return self.request.URL.hashValue } override func isEqual(other: AnyObject?) -> Bool { guard let other = other as? ImageRequestKey else { return false } guard let owner = self.owner where self.owner === other.owner && self.type == other.type else { return false } return owner.isImageRequestKey(self, equalToKey: other) } }
mit
0498139e76effd09d4ffa463455d99ba
38.471429
192
0.659157
5.457778
false
false
false
false
gaelfoppolo/handicarparking
HandiParking/HandiParking/Source/DTIAnimWave.swift
1
4213
// // DTIAnimWave.swift // SampleObjc // // Created by dtissera on 16/08/2014. // Copyright (c) 2014 o--O--o. All rights reserved. // import UIKit import QuartzCore class DTIAnimWave: DTIAnimProtocol { /** private properties */ private let owner: DTIActivityIndicatorView private let spinnerView = UIView() private let rectView = UIView() private let animationDuration = CFTimeInterval(1.2) private let spaceBetweenRect: CGFloat = 3.0 private let rectCount = 5 /** ctor */ init(indicatorView: DTIActivityIndicatorView) { self.owner = indicatorView for var index = 0; index < rectCount; ++index { let layer = CALayer() layer.transform = CATransform3DMakeScale(1.0, 0.4, 0.0); self.rectView.layer.addSublayer(layer) } } // ------------------------------------------------------------------------- // DTIAnimProtocol // ------------------------------------------------------------------------- func needLayoutSubviews() { self.spinnerView.frame = self.owner.bounds let contentSize = self.owner.bounds.size let rectWidth: CGFloat = (contentSize.width - spaceBetweenRect * CGFloat(rectCount-1)) / CGFloat(rectCount) self.rectView.frame = self.owner.bounds; for var index = 0; index < rectCount; ++index { let rectLayer = self.rectView.layer.sublayers[index] as! CALayer rectLayer.frame = CGRect(x: CGFloat(index)*(rectWidth+spaceBetweenRect), y: 0.0, width: rectWidth, height: contentSize.height) } } func needUpdateColor() { // Debug stuff // self.spinnerView.backgroundColor = UIColor.grayColor() for var index = 0; index < rectCount; ++index { let rectLayer = self.rectView.layer.sublayers[index] as! CALayer rectLayer.backgroundColor = self.owner.indicatorColor.CGColor } } func setUp() { self.spinnerView.addSubview(self.rectView) } func startActivity() { self.owner.addSubview(self.spinnerView) let beginTime = CACurrentMediaTime() + self.animationDuration; for var index = 0; index < rectCount; ++index { let rectLayer = self.rectView.layer.sublayers[index] as! CALayer let aniScale = CAKeyframeAnimation() aniScale.keyPath = "transform" aniScale.removedOnCompletion = false aniScale.repeatCount = HUGE aniScale.duration = self.animationDuration aniScale.beginTime = beginTime - self.animationDuration + CFTimeInterval(index) * 0.1; aniScale.keyTimes = [0.0, 0.2, 0.4, 1.0]; aniScale.timingFunctions = [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) ] aniScale.values = [ NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(1.0, 0.4, 0.0)) ] rectLayer.addAnimation(aniScale, forKey: "DTIAnimWave~scale\(index)") } } func stopActivity(animated: Bool) { func removeAnimations() { self.spinnerView.layer.removeAllAnimations() for var index = 0; index < rectCount; ++index { let rectLayer = self.rectView.layer.sublayers[index] as! CALayer rectLayer.removeAllAnimations() } self.spinnerView.removeFromSuperview() } if (animated) { self.spinnerView.layer.dismissAnimated(removeAnimations) } else { removeAnimations() } } }
gpl-3.0
be753675f8866e99fd07e9dc599fc3cf
35.327586
138
0.58367
5.051559
false
false
false
false
lorentey/swift
test/decl/enum/enumtest.swift
3
18570
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Tests for various simple enum constructs //===----------------------------------------------------------------------===// public enum unionSearchFlags { case none case backwards case anchored init() { self = .none } } func test1() -> unionSearchFlags { let _ : unionSearchFlags var b = unionSearchFlags.none b = unionSearchFlags.anchored _ = b return unionSearchFlags.backwards } func test1a() -> unionSearchFlags { var _ : unionSearchFlags var b : unionSearchFlags = .none b = .anchored _ = b // ForwardIndex use of MaybeInt. _ = MaybeInt.none return .backwards } func test1b(_ b : Bool) { _ = 123 _ = .description == 1 // expected-error {{instance member 'description' cannot be used on type 'Int'}} // expected-error@-1 {{member 'description' in 'Int' produces result of type 'String', but context expects 'Int'}} } enum MaybeInt { case none case some(Int) // expected-note {{'some' declared here}} init(_ i: Int) { self = MaybeInt.some(i) } } func test2(_ a: Int, _ b: Int, _ c: MaybeInt) { _ = MaybeInt.some(4) _ = MaybeInt.some _ = MaybeInt.some(b) test2(1, 2, .none) } enum ZeroOneTwoThree { case Zero case One(Int) case Two(Int, Int) case Three(Int,Int,Int) case Unknown(MaybeInt, MaybeInt, MaybeInt) init (_ i: Int) { self = .One(i) } init (_ i: Int, _ j: Int, _ k: Int) { self = .Three(i, j, k) } init (_ i: MaybeInt, _ j: MaybeInt, _ k: MaybeInt) { self = .Unknown(i, j, k) } } func test3(_ a: ZeroOneTwoThree) { _ = ZeroOneTwoThree.Three(1,2,3) _ = ZeroOneTwoThree.Unknown( MaybeInt.none, MaybeInt.some(4), MaybeInt.some(32)) _ = ZeroOneTwoThree(MaybeInt.none, MaybeInt(4), MaybeInt(32)) var _ : Int = ZeroOneTwoThree.Zero // expected-error {{cannot convert value of type 'ZeroOneTwoThree' to specified type 'Int'}} // expected-warning @+1 {{unused}} test3 ZeroOneTwoThree.Zero // expected-error {{expression resolves to an unused function}} expected-error{{consecutive statements}} {{8-8=;}} test3 (ZeroOneTwoThree.Zero) test3(ZeroOneTwoThree.Zero) test3 // expected-error {{expression resolves to an unused function}} // expected-warning @+1 {{unused}} (ZeroOneTwoThree.Zero) var _ : ZeroOneTwoThree = .One(4) var _ : (Int,Int) -> ZeroOneTwoThree = .Two // expected-error{{type '(Int, Int) -> ZeroOneTwoThree' has no member 'Two'}} var _ : Int = .Two // expected-error{{type 'Int' has no member 'Two'}} var _ : MaybeInt = 0 > 3 ? .none : .soma(3) // expected-error {{type 'MaybeInt' has no member 'soma'; did you mean 'some'?}} } func test3a(_ a: ZeroOneTwoThree) { var e : ZeroOneTwoThree = (.Three(1, 2, 3)) var f = ZeroOneTwoThree.Unknown(.none, .some(4), .some(32)) var g = .none // expected-error {{reference to member 'none' cannot be resolved without a contextual type}} // Overload resolution can resolve this to the right constructor. var h = ZeroOneTwoThree(1) var i = 0 > 3 ? .none : .some(3) // expected-error {{cannot infer contextual base in reference to member 'none'}} // expected-error@-1 {{cannot infer contextual base in reference to member 'some'}} test3a; // expected-error {{unused function}} .Zero // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}} test3a // expected-error {{unused function}} (.Zero) // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}} test3a(.Zero) } struct CGPoint { var x : Int, y : Int } typealias OtherPoint = (x : Int, y : Int) func test4() { var a : CGPoint // Note: we reject the following because it conflicts with the current // "init" hack. var b = CGPoint.CGPoint(1, 2) // expected-error {{type 'CGPoint' has no member 'CGPoint'}} var c = CGPoint(x: 2, y : 1) // Using injected name. var e = CGPoint.x // expected-error {{member 'x' cannot be used on type 'CGPoint'}} var f = OtherPoint.x // expected-error {{type 'OtherPoint' (aka '(x: Int, y: Int)') has no member 'x'}} } struct CGSize { var width : Int, height : Int } extension CGSize { func area() -> Int { return width*self.height } func area_wrapper() -> Int { return area() } } struct CGRect { var origin : CGPoint, size : CGSize func area() -> Int { return self.size.area() } } func area(_ r: CGRect) -> Int { return r.size.area() } extension CGRect { func search(_ x: Int) -> CGSize {} func bad_search(_: Int) -> CGSize {} } func test5(_ myorigin: CGPoint) { let x1 = CGRect(origin: myorigin, size: CGSize(width: 42, height: 123)) let x2 = x1 _ = 4+5 // Dot syntax. _ = x2.origin.x _ = x1.size.area() _ = (r : x1.size).r.area() // expected-error {{cannot create a single-element tuple with an element label}} _ = x1.size.area() _ = (r : x1.size).r.area() // expected-error {{cannot create a single-element tuple with an element label}} _ = x1.area _ = x1.search(42) _ = x1.search(42).width // TODO: something like this (name binding on the LHS): // var (CGSize(width, height)) = CGSize(1,2) // TODO: something like this, how do we get it in scope in the {} block? //if (var some(x) = somemaybeint) { ... } } struct StructTest1 { var a : Int, c, b : Int typealias ElementType = Int } enum UnionTest1 { case x case y(Int) func foo() {} init() { self = .x } } extension UnionTest1 { func food() {} func bar() {} // Type method. static func baz() {} } struct EmptyStruct { func foo() {} } func f() { let a : UnionTest1 a.bar() UnionTest1.baz() // dot syntax access to a static method. // Test that we can get the "address of a member". var _ : () -> () = UnionTest1.baz var _ : (UnionTest1) -> () -> () = UnionTest1.bar } func union_error(_ a: ZeroOneTwoThree) { var _ : ZeroOneTwoThree = .Zero(1) // expected-error {{enum case 'Zero' has no associated values}} var _ : ZeroOneTwoThree = .Zero() // expected-error {{enum case 'Zero' has no associated values}} {{34-36=}} var _ : ZeroOneTwoThree = .One // expected-error {{member 'One' expects argument of type 'Int'}} var _ : ZeroOneTwoThree = .foo // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} var _ : ZeroOneTwoThree = .foo() // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} } func local_struct() { struct s { func y() {} } } //===----------------------------------------------------------------------===// // A silly units example showing "user defined literals". //===----------------------------------------------------------------------===// struct distance { var v : Int } func - (lhs: distance, rhs: distance) -> distance {} extension Int { func km() -> enumtest.distance {} func cm() -> enumtest.distance {} } func units(_ x: Int) -> distance { return x.km() - 4.cm() - 42.km() } var %% : distance -> distance // expected-error {{expected pattern}} func badTupleElement() { typealias X = (x : Int, y : Int) var y = X.y // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'y'}} var z = X.z // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'z'}} } enum Direction { case North(distance: Int) case NorthEast(distanceNorth: Int, distanceEast: Int) } func testDirection() { var dir: Direction = .North(distance: 5) dir = .NorthEast(distanceNorth: 5, distanceEast: 7) var i: Int switch dir { case .North(let x): i = x break case .NorthEast(let x): // expected-warning {{cannot match several associated values at once, implicitly tupling the associated values and trying to match that instead}} i = x.distanceEast break } _ = i } enum NestedSingleElementTuple { case Case(x: (y: Int)) // expected-error{{cannot create a single-element tuple with an element label}} {{17-20=}} } enum SimpleEnum { case X, Y } func testSimpleEnum() { let _ : SimpleEnum = .X let _ : SimpleEnum = (.X) let _ : SimpleEnum=.X // expected-error {{'=' must have consistent whitespace on both sides}} } enum SR510: String { case Thing = "thing" case Bob = {"test"} // expected-error {{raw value for enum case must be a literal}} } // <rdar://problem/21269142> Diagnostic should say why enum has no .rawValue member enum E21269142 { // expected-note {{did you mean to specify a raw type on the enum declaration?}} case Foo } print(E21269142.Foo.rawValue) // expected-error {{value of type 'E21269142' has no member 'rawValue'}} // Check that typo correction does something sensible with synthesized members. enum SyntheticMember { // expected-note {{property 'hashValue' is implicitly declared}} case Foo } func useSynthesizedMember() { print(SyntheticMember.Foo.hasValue) // expected-error {{value of type 'SyntheticMember' has no member 'hasValue'; did you mean 'hashValue'?}} } // Non-materializable argument type enum Lens<T> { case foo(inout T) // expected-error {{'inout' may only be used on parameters}} case bar(inout T, Int) // expected-error {{'inout' may only be used on parameters}} case baz((inout T) -> ()) // ok case quux((inout T, inout T) -> ()) // ok } // In the long term, these should be legal, but we don't support them right // now and we shouldn't pretend to. // rdar://46684504 enum HasVariadic { case variadic(x: Int...) // expected-error {{variadic enum cases are not supported}} } // SR-2176 enum Foo { case bar case none } let _: Foo? = .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{15-15=Optional}} // expected-note@-2 {{use 'Foo.none' instead}} {{15-15=Foo}} let _: Foo?? = .none // expected-warning {{assuming you mean 'Optional<Optional<Foo>>.none'; did you mean 'Foo.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{16-16=Optional}} // expected-note@-2 {{use 'Foo.none' instead}} {{16-16=Foo}} let _: Foo = .none // ok let _: Foo = .bar // ok let _: Foo? = .bar // ok let _: Foo?? = .bar // ok let _: Foo = Foo.bar // ok let _: Foo = Foo.none // ok let _: Foo? = Foo.none // ok let _: Foo?? = Foo.none // ok func baz(_: Foo?) {} baz(.none) // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{5-5=Optional}} // expected-note@-2 {{use 'Foo.none' instead}} {{5-5=Foo}} let test: Foo? = .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{18-18=Optional}} // expected-note@-2 {{use 'Foo.none' instead}} {{18-18=Foo}} let answer = test == .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{22-22=Optional}} // expected-note@-2 {{use 'Foo.none' instead}} {{22-22=Foo}} enum Bar { case baz } let _: Bar? = .none // ok let _: Bar?? = .none // ok let _: Bar? = .baz // ok let _: Bar?? = .baz // ok let _: Bar = .baz // ok enum AnotherFoo { case none(Any) } let _: AnotherFoo? = .none // ok let _: AnotherFoo? = .none(0) // ok struct FooStruct { static let none = FooStruct() static let one = FooStruct() } let _: FooStruct? = .none // expected-warning {{assuming you mean 'Optional<FooStruct>.none'; did you mean 'FooStruct.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{21-21=Optional}} // expected-note@-2 {{use 'FooStruct.none' instead}} {{21-21=FooStruct}} let _: FooStruct?? = .none // expected-warning {{assuming you mean 'Optional<Optional<FooStruct>>.none'; did you mean 'FooStruct.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{22-22=Optional}} // expected-note@-2 {{use 'FooStruct.none' instead}} {{22-22=FooStruct}} let _: FooStruct = .none // ok let _: FooStruct = .one // ok let _: FooStruct? = .one // ok let _: FooStruct?? = .one // ok struct NestedBazEnum { enum Baz { case one case none } } let _: NestedBazEnum.Baz? = .none // expected-warning {{assuming you mean 'Optional<NestedBazEnum.Baz>.none'; did you mean 'NestedBazEnum.Baz.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{29-29=Optional}} // expected-note@-2 {{use 'NestedBazEnum.Baz.none' instead}} {{29-29=NestedBazEnum.Baz}} let _: NestedBazEnum.Baz?? = .none // expected-warning {{assuming you mean 'Optional<Optional<NestedBazEnum.Baz>>.none'; did you mean 'NestedBazEnum.Baz.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{30-30=Optional}} // expected-note@-2 {{use 'NestedBazEnum.Baz.none' instead}} {{30-30=NestedBazEnum.Baz}} let _: NestedBazEnum.Baz = .none // ok let _: NestedBazEnum.Baz = .one // ok let _: NestedBazEnum.Baz? = .one // ok let _: NestedBazEnum.Baz?? = .one // ok struct NestedBazEnumGeneric { enum Baz<T> { case one case none } } let _: NestedBazEnumGeneric.Baz<Int>? = .none // expected-warning {{assuming you mean 'Optional<NestedBazEnumGeneric.Baz<Int>>.none'; did you mean 'NestedBazEnumGeneric.Baz<Int>.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{41-41=Optional}} // expected-note@-2 {{use 'NestedBazEnumGeneric.Baz<Int>.none' instead}} {{41-41=NestedBazEnumGeneric.Baz<Int>}} let _: NestedBazEnumGeneric.Baz<Int>?? = .none // expected-warning {{assuming you mean 'Optional<Optional<NestedBazEnumGeneric.Baz<Int>>>.none'; did you mean 'NestedBazEnumGeneric.Baz<Int>.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{42-42=Optional}} // expected-note@-2 {{use 'NestedBazEnumGeneric.Baz<Int>.none' instead}} {{42-42=NestedBazEnumGeneric.Baz<Int>}} let _: NestedBazEnumGeneric.Baz<Int> = .none // ok let _: NestedBazEnumGeneric.Baz<Int> = .one // ok let _: NestedBazEnumGeneric.Baz<Int>? = .one // ok let _: NestedBazEnumGeneric.Baz<Int>?? = .one // ok class C {} protocol P {} enum E : C & P {} // expected-error@-1 {{inheritance from class-constrained protocol composition type 'C & P'}} // SR-11522 enum EnumWithStaticNone1 { case a static let none = 1 } enum EnumWithStaticNone2 { case a static let none = EnumWithStaticNone2.a } enum EnumWithStaticNone3 { case a static let none = EnumWithStaticNone3.a var none: EnumWithStaticNone3 { return .a } } enum EnumWithStaticNone4 { case a var none: EnumWithStaticNone4 { return .a } static let none = EnumWithStaticNone4.a } enum EnumWithStaticFuncNone1 { case a static func none() -> Int { return 1 } } enum EnumWithStaticFuncNone2 { case a static func none() -> EnumWithStaticFuncNone2 { return .a } } /// Make sure we don't diagnose 'static let none = 1', but do diagnose 'static let none = TheEnum.anotherCase' /// let _: EnumWithStaticNone1? = .none // Okay let _: EnumWithStaticNone2? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone2>.none'; did you mean 'EnumWithStaticNone2.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}} // expected-note@-2 {{use 'EnumWithStaticNone2.none' instead}}{{31-31=EnumWithStaticNone2}} /// Make sure we diagnose if we have both static and instance 'none' member regardless of source order /// let _: EnumWithStaticNone3? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone3>.none'; did you mean 'EnumWithStaticNone3.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}} // expected-note@-2 {{use 'EnumWithStaticNone3.none' instead}}{{31-31=EnumWithStaticNone3}} let _: EnumWithStaticNone4? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone4>.none'; did you mean 'EnumWithStaticNone4.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}} // expected-note@-2 {{use 'EnumWithStaticNone4.none' instead}}{{31-31=EnumWithStaticNone4}} /// Make sure we don't diagnose 'static func none -> T' /// let _: EnumWithStaticFuncNone1? = .none // Okay let _: EnumWithStaticFuncNone2? = .none // Okay /// Make sure we diagnose generic ones as well including conditional ones /// enum GenericEnumWithStaticNone<T> { case a static var none: GenericEnumWithStaticNone<Int> { .a } } let _: GenericEnumWithStaticNone<Int>? = .none // expected-warning {{assuming you mean 'Optional<GenericEnumWithStaticNone<Int>>.none'; did you mean 'GenericEnumWithStaticNone<Int>.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{42-42=Optional}} // expected-note@-2 {{use 'GenericEnumWithStaticNone<Int>.none' instead}}{{42-42=GenericEnumWithStaticNone<Int>}} let _: GenericEnumWithStaticNone<String>? = .none // Okay let _: GenericEnumWithStaticNone? = .none // FIXME(SR-11535): This should be diagnosed enum GenericEnumWithoutNone<T> { case a } extension GenericEnumWithoutNone where T == Int { static var none: GenericEnumWithoutNone<Int> { .a } } let _: GenericEnumWithoutNone<Int>? = .none // expected-warning {{assuming you mean 'Optional<GenericEnumWithoutNone<Int>>.none'; did you mean 'GenericEnumWithoutNone<Int>.none' instead?}} // expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{39-39=Optional}} // expected-note@-2 {{use 'GenericEnumWithoutNone<Int>.none' instead}}{{39-39=GenericEnumWithoutNone<Int>}} let _: GenericEnumWithoutNone<String>? = .none // Okay // A couple of edge cases that shouldn't trigger the warning // enum EnumWithStructNone { case bar struct none {} } enum EnumWithTypealiasNone { case bar typealias none = EnumWithTypealiasNone } enum EnumWithBothStructAndComputedNone { case bar struct none {} var none: EnumWithBothStructAndComputedNone { . bar } } enum EnumWithBothTypealiasAndComputedNone { case bar typealias none = EnumWithBothTypealiasAndComputedNone var none: EnumWithBothTypealiasAndComputedNone { . bar } } let _: EnumWithStructNone? = .none // Okay let _: EnumWithTypealiasNone? = .none // Okay let _: EnumWithBothStructAndComputedNone? = .none // Okay let _: EnumWithBothTypealiasAndComputedNone? = .none // Okay
apache-2.0
d8b6c9a20a6706ac87c2c9cd43559419
32.399281
205
0.664082
3.682332
false
true
false
false
BrianL3D/RWPickFlavor
RWPickFlavor/PickFlavorViewController.swift
1
2389
// // ViewController.swift // IceCreamShop // // Created by Joshua Greene on 2/8/15. // Copyright (c) 2015 Razeware, LLC. All rights reserved. // import UIKit import Alamofire import MBProgressHUD public class PickFlavorViewController: UIViewController, UICollectionViewDelegate { // MARK: Instance Variables var flavors: [Flavor] = [] { didSet { pickFlavorDataSource?.flavors = flavors } } private var pickFlavorDataSource: PickFlavorDataSource? { return collectionView?.dataSource as! PickFlavorDataSource? } private let flavorFactory = FlavorFactory() // MARK: Outlets @IBOutlet var contentView: UIView! @IBOutlet var collectionView: UICollectionView! @IBOutlet var iceCreamView: IceCreamView! @IBOutlet var label: UILabel! // MARK: View Lifecycle public override func viewDidLoad() { super.viewDidLoad() loadFlavors() } private func loadFlavors() { let urlString = "http://www.raywenderlich.com/downloads/Flavors.plist" showLoadingHUD() // 1 Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0)) .responsePropertyList {request, response, array, error in self.hideLoadingHUD() // 2 if let error = error { println("Error: \(error)") // 3 } else if let array = array as? [[String: String]] { //4 if array.isEmpty { println("No flavors were found!") // 5 } else { self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array) self.collectionView.reloadData() self.selectFirstFlavor() } } } } private func showLoadingHUD() { let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true) hud.labelText = "Loading..." } private func hideLoadingHUD() { MBProgressHUD.hideAllHUDsForView(contentView, animated: true) } private func selectFirstFlavor() { if let flavor = flavors.first { updateWithFlavor(flavor) } } // MARK: UICollectionViewDelegate public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let flavor = flavors[indexPath.row] updateWithFlavor(flavor) } // MARK: Internal private func updateWithFlavor(flavor: Flavor) { iceCreamView.updateWithFlavor(flavor) label.text = flavor.name } }
mit
04bda89b49938d95400a04629f14d183
21.327103
113
0.676852
4.367459
false
false
false
false
vector-im/vector-ios
Riot/Modules/Secrets/Setup/RecoveryKey/SecretsSetupRecoveryKeyViewController.swift
1
10068
// File created from ScreenTemplate // $ createScreen.sh SecretsSetupRecoveryKey SecretsSetupRecoveryKey /* Copyright 2020 New Vector Ltd 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 final class SecretsSetupRecoveryKeyViewController: UIViewController { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var secureKeyImageView: UIImageView! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var recoveryKeyLabel: UILabel! @IBOutlet private weak var exportButton: RoundedButton! @IBOutlet private weak var doneButton: RoundedButton! // MARK: Private private var viewModel: SecretsSetupRecoveryKeyViewModelType! private var isPassphraseOnly: Bool = true private var cancellable: Bool! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var recoveryKey: String? private var hasSavedRecoveryKey: Bool = false // MARK: - Setup class func instantiate(with viewModel: SecretsSetupRecoveryKeyViewModelType, cancellable: Bool) -> SecretsSetupRecoveryKeyViewController { let viewController = StoryboardScene.SecretsSetupRecoveryKeyViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.cancellable = cancellable viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.secureKeyImageView.tintColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor self.recoveryKeyLabel.textColor = theme.textSecondaryColor self.exportButton.update(theme: theme) self.doneButton.update(theme: theme) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { if self.cancellable { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem } self.vc_removeBackTitle() self.title = VectorL10n.secretsSetupRecoveryKeyTitle self.secureKeyImageView.image = Asset.Images.secretsSetupKey.image.withRenderingMode(.alwaysTemplate) self.informationLabel.text = VectorL10n.secretsSetupRecoveryKeyInformation self.recoveryKeyLabel.text = VectorL10n.secretsSetupRecoveryKeyLoading self.exportButton.setTitle(VectorL10n.secretsSetupRecoveryKeyExportAction, for: .normal) self.exportButton.isEnabled = false self.doneButton.setTitle(VectorL10n.continue, for: .normal) self.updateDoneButton() } private func render(viewState: SecretsSetupRecoveryKeyViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(let passphraseOnly): self.renderLoaded(passphraseOnly: passphraseOnly) case .recoveryCreated(let recoveryKey): self.renderRecoveryCreated(recoveryKey: recoveryKey) case .error(let error): self.render(error: error) } } private func renderLoaded(passphraseOnly: Bool) { self.isPassphraseOnly = passphraseOnly let title: String let secretsLogoImage: UIImage let informationText: String let recoveryKeyText: String? if passphraseOnly { title = VectorL10n.secretsSetupRecoveryPassphraseSummaryTitle secretsLogoImage = Asset.Images.secretsSetupPassphrase.image informationText = VectorL10n.secretsSetupRecoveryPassphraseSummaryInformation recoveryKeyText = nil } else { title = VectorL10n.secretsSetupRecoveryKeyTitle secretsLogoImage = Asset.Images.secretsSetupKey.image informationText = VectorL10n.secretsSetupRecoveryKeyInformation recoveryKeyText = VectorL10n.secretsSetupRecoveryKeyLoading } self.title = title self.secureKeyImageView.image = secretsLogoImage self.informationLabel.text = informationText self.exportButton.isHidden = passphraseOnly self.recoveryKeyLabel.text = recoveryKeyText } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderRecoveryCreated(recoveryKey: String) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.exportButton.isEnabled = !self.isPassphraseOnly self.doneButton.isEnabled = self.isPassphraseOnly if !self.isPassphraseOnly { self.recoveryKey = recoveryKey self.recoveryKeyLabel.text = recoveryKey } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true) { self.viewModel.process(viewAction: .errorAlertOk) } } private func updateDoneButton() { self.doneButton.isEnabled = self.hasSavedRecoveryKey } private func presentKeepSafeAlert() { let alertController = UIAlertController(title: VectorL10n.secretsSetupRecoveryKeyStorageAlertTitle, message: VectorL10n.secretsSetupRecoveryKeyStorageAlertMessage, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: VectorL10n.continue, style: .cancel, handler: { action in self.viewModel.process(viewAction: .done) })) self.present(alertController, animated: true, completion: nil) } private func shareRecoveryKey() { guard let recoveryKey = self.recoveryKey else { return } // Set up activity view controller let activityItems: [Any] = [ recoveryKey ] let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityViewController.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in // Enable made copy button only if user has selected an activity item and has setup recovery key without passphrase if completed { self.hasSavedRecoveryKey = true self.updateDoneButton() } } // Configure source view when activity view controller is presented with a popover if let popoverPresentationController = activityViewController.popoverPresentationController { popoverPresentationController.sourceView = self.exportButton popoverPresentationController.sourceRect = self.exportButton.bounds popoverPresentationController.permittedArrowDirections = [.down, .up] } self.present(activityViewController, animated: true) } // MARK: - Actions @IBAction private func exportButtonAction(_ sender: Any) { self.shareRecoveryKey() } @IBAction private func doneButtonAction(_ sender: Any) { if self.isPassphraseOnly { self.viewModel.process(viewAction: .done) } else { self.presentKeepSafeAlert() } } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - SecretsSetupRecoveryKeyViewModelViewDelegate extension SecretsSetupRecoveryKeyViewController: SecretsSetupRecoveryKeyViewModelViewDelegate { func secretsSetupRecoveryKeyViewModel(_ viewModel: SecretsSetupRecoveryKeyViewModelType, didUpdateViewState viewSate: SecretsSetupRecoveryKeyViewState) { self.render(viewState: viewSate) } }
apache-2.0
6116c891a59365091fa20f9444ed4880
36.427509
157
0.681069
5.943329
false
false
false
false
AnthonyMDev/Nimble
Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift
20
1796
import Foundation /// A Nimble matcher that succeeds when the actual value is greater than /// or equal to the expected value. public func beGreaterThanOrEqualTo<T: Comparable>(_ expectedValue: T?) -> Predicate<T> { let message = "be greater than or equal to <\(stringify(expectedValue))>" return Predicate.simple(message) { actualExpression in let actualValue = try actualExpression.evaluate() if let actual = actualValue, let expected = expectedValue { return PredicateStatus(bool: actual >= expected) } return .fail } } public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThanOrEqualTo(rhs)) } #if canImport(Darwin) || !compiler(>=5.1) /// A Nimble matcher that succeeds when the actual value is greater than /// or equal to the expected value. public func beGreaterThanOrEqualTo<T: NMBComparable>(_ expectedValue: T?) -> Predicate<T> { let message = "be greater than or equal to <\(stringify(expectedValue))>" return Predicate.simple(message) { actualExpression in let actualValue = try actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != ComparisonResult.orderedAscending return PredicateStatus(bool: matches) } } public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThanOrEqualTo(rhs)) } #endif #if canImport(Darwin) extension NMBObjCMatcher { @objc public class func beGreaterThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBMatcher { return NMBPredicate { actualExpression in let expr = actualExpression.cast { $0 as? NMBComparable } return try beGreaterThanOrEqualTo(expected).satisfies(expr).toObjectiveC() } } } #endif
apache-2.0
279570f23e2a87f2202c933023489753
38.043478
120
0.700445
4.776596
false
false
false
false
MillmanY/MMPlayerView
MMPlayerView/Classes/SwiftUI/Modifier/FrameModifier.swift
1
605
// // FrameModifier.swift // MMPlayerView // // Created by Millman on 2020/2/7. // import Foundation import SwiftUI @available(iOS 13.0.0, *) public struct FrameModifier<K: PreferenceKey>: ViewModifier where K.Value == [CGRect] { @Binding var r: CGRect public init (rect: Binding<CGRect>) { self._r = rect } public func body(content: Content) -> some View { content.onPreferenceChange(K.self) { (values) in if let f = values.first { DispatchQueue.main.async { self.r = f } } } } }
mit
974ceacd0d9e8021ec9833306c1c89f7
23.2
87
0.560331
3.878205
false
false
false
false
smittytone/FightingFantasy
FightingFantasy/FFCollectionViewItem.swift
1
1009
// FightingFantasy // Created by Tony Smith on 02/11/2017. // Software © 2017 Tony Smith. All rights reserved. // Software ONLY issued under MIT Licence // Fighting Fantasy © 2016 Steve Jackson and Ian Livingstone import Cocoa class FFCollectionViewItem: NSCollectionViewItem { var index: Int = -1 var image: NSImage? { didSet { guard isViewLoaded else { return } if let image = image { imageView?.image = image } else { imageView?.image = nil } } } override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true view.layer?.backgroundColor = NSColor.white.cgColor view.layer?.borderColor = NSColor.init(red: 0.6, green: 0.1, blue: 0.0, alpha: 1.0).cgColor view.layer?.borderWidth = 0.0 } override var isSelected: Bool { didSet { view.layer?.borderWidth = isSelected ? 2.0 : 0.0 } } }
mit
4816318c376bd20483499f1e68a907ca
22.97619
99
0.578947
4.266949
false
false
false
false
material-motion/motion-transitioning-objc
examples/MenuExample.swift
2
2606
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MotionTransitioning class MenuExampleViewController: ExampleViewController { @objc func didTap() { let modalViewController = ModalViewController() modalViewController.mdm_transitionController.transition = MenuTransition() present(modalViewController, animated: true) } override func viewDidLoad() { super.viewDidLoad() let label = UILabel(frame: view.bounds) label.autoresizingMask = [.flexibleWidth, .flexibleHeight] label.textColor = .white label.textAlignment = .center label.text = "Tap to start the transition" view.addSubview(label) let tap = UITapGestureRecognizer(target: self, action: #selector(didTap)) view.addGestureRecognizer(tap) } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Tap to present a modal transition.") } } private final class MenuTransition: NSObject, TransitionWithPresentation { func presentationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController?) -> UIPresentationController? { return nil } func defaultModalPresentationStyle() -> UIModalPresentationStyle { return .overCurrentContext } func start(with context: TransitionContext) { let foreView = context.foreViewController.view! if(context.direction == .forward) { foreView.frame.origin.x = -1 * foreView.frame.width UIView.animate( withDuration: context.duration, animations: { foreView.frame.origin.x = -1 * (foreView.frame.width / 2) }, completion: { _ in context.transitionDidEnd() } ) } else { UIView.animate( withDuration: context.duration, animations: { foreView.frame.origin.x = -1 * foreView.frame.width }, completion: { _ in context.transitionDidEnd() } ) } } }
apache-2.0
9d381516229fc51334a0a2854f9bcd6e
30.780488
159
0.702609
4.799263
false
false
false
false
nickqiao/NKBill
Carthage/Checkouts/PagingMenuController/Pod/Classes/MenuView.swift
1
14087
// // MenuView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit public protocol MenuItemType {} extension String: MenuItemType {} extension UIImage: MenuItemType {} @objc public protocol MenuViewDelegate: class { optional func willMoveToMenuItemView(menuItemView: MenuItemView, previousMenuItemView: MenuItemView) optional func didMoveToMenuItemView(menuItemView: MenuItemView, previousMenuItemView: MenuItemView) } public class MenuView: UIScrollView { weak public var viewDelegate: MenuViewDelegate? public private(set) var menuItemViews = [MenuItemView]() public private(set) var currentPage: Int = 0 public private(set) var currentMenuItemView: MenuItemView! internal var menuItemCount: Int { switch options.menuDisplayMode { case .Infinite: return options.menuItemCount * options.dummyMenuItemViewsSet default: return options.menuItemCount } } internal var previousPage: Int { return currentPage - 1 < 0 ? menuItemCount - 1 : currentPage - 1 } internal var nextPage: Int { return currentPage + 1 > menuItemCount - 1 ? 0 : currentPage + 1 } private var sortedMenuItemViews = [MenuItemView]() private var options: PagingMenuOptions! private let contentView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy private var underlineView: UIView = { let view = UIView(frame: .zero) return view }() lazy private var roundRectView: UIView = { let view = UIView(frame: .zero) view.userInteractionEnabled = true return view }() private var menuViewBounces: Bool { switch options.menuDisplayMode { case .Standard(_, _, .ScrollEnabledAndBouces), .Infinite(_, .ScrollEnabledAndBouces): return true default: return false } } private var menuViewScrollEnabled: Bool { switch options.menuDisplayMode { case .Standard(_, _, .ScrollEnabledAndBouces), .Standard(_, _, .ScrollEnabled), .Infinite(_, .ScrollEnabledAndBouces), .Infinite(_, .ScrollEnabled): return true default: return false } } private var contentOffsetX: CGFloat { switch options.menuDisplayMode { case let .Standard(_, centerItem, _) where centerItem: return centerOfScreenWidth case .SegmentedControl: return contentOffset.x case .Infinite: return centerOfScreenWidth default: return contentOffsetXForCurrentPage } } private var centerOfScreenWidth: CGFloat { return menuItemViews[currentPage].frame.midX - UIApplication.sharedApplication().keyWindow!.bounds.width / 2 } private var contentOffsetXForCurrentPage: CGFloat { guard menuItemCount > options.minumumSupportedViewCount else { return 0.0 } let ratio = CGFloat(currentPage) / CGFloat(menuItemCount - 1) return (contentSize.width - frame.width) * ratio } lazy private var rawIndex: (Int) -> Int = { [unowned self] in let count = self.menuItemCount let startIndex = self.currentPage - count / 2 return (startIndex + $0 + count) % count } // MARK: - Lifecycle internal init<Element: MenuItemType>(menuItemTypes: [Element], options: PagingMenuOptions) { super.init(frame: .zero) self.options = options self.options.menuItemCount = menuItemTypes.count commonInit({ self.constructMenuItemViews(menuItemTypes) }) } private func commonInit(constructor: () -> Void) { setupScrollView() layoutScrollView() setupContentView() layoutContentView() setupRoundRectViewIfNeeded() constructor() layoutMenuItemViews() setupUnderlineViewIfNeeded() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func layoutSubviews() { super.layoutSubviews() adjustmentContentInsetIfNeeded() } // MARK: - Internal method internal func moveToMenu(page: Int, animated: Bool = true) { let duration = animated ? options.animationDuration : 0 let previousPage = currentPage currentPage = page // hide menu view when constructing itself if !animated { alpha = 0 } let menuItemView = menuItemViews[page] let previousMenuItemView = currentMenuItemView if let previousMenuItemView = previousMenuItemView where page != previousPage { viewDelegate?.willMoveToMenuItemView?(menuItemView, previousMenuItemView: previousMenuItemView) } UIView.animateWithDuration(duration, animations: { [unowned self] () -> Void in self.focusMenuItem() if self.options.menuSelectedItemCenter { self.positionMenuItemViews() } }) { [weak self] (_) in guard let _ = self else { return } // relayout menu item views dynamically if case .Infinite = self!.options.menuDisplayMode { self!.relayoutMenuItemViews() } if self!.options.menuSelectedItemCenter { self!.positionMenuItemViews() } self!.setNeedsLayout() self!.layoutIfNeeded() // show menu view when constructing is done if !animated { self!.alpha = 1 } if let previousMenuItemView = previousMenuItemView where page != previousPage { self!.viewDelegate?.didMoveToMenuItemView?(self!.currentMenuItemView, previousMenuItemView: previousMenuItemView) } } } internal func updateMenuViewConstraints(size size: CGSize) { if case .SegmentedControl = options.menuDisplayMode { menuItemViews.forEach { $0.updateConstraints(size) } } setNeedsLayout() layoutIfNeeded() animateUnderlineViewIfNeeded() animateRoundRectViewIfNeeded() } internal func cleanup() { contentView.removeFromSuperview() switch options.menuItemMode { case .Underline(_, _, _, _): underlineView.removeFromSuperview() case .RoundRect(_, _, _, _): roundRectView.removeFromSuperview() case .None: break } if !menuItemViews.isEmpty { menuItemViews.forEach { $0.cleanup() $0.removeFromSuperview() } } } // MARK: - Private method private func setupScrollView() { backgroundColor = options.backgroundColor showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false bounces = menuViewBounces scrollEnabled = menuViewScrollEnabled decelerationRate = options.deceleratingRate scrollsToTop = false translatesAutoresizingMaskIntoConstraints = false } private func layoutScrollView() { let viewsDictionary = ["menuView": self] let metrics = ["height": options.menuHeight] NSLayoutConstraint.activateConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView(height)]", options: [], metrics: metrics, views: viewsDictionary) ) } private func setupContentView() { addSubview(contentView) } private func layoutContentView() { let viewsDictionary = ["contentView": contentView, "scrollView": self] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(==scrollView)]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } private func constructMenuItemViews<Element: MenuItemType>(menuItemTypes: [Element]) { constructMenuItemViews({ switch self.options.menuItemViewContent { case .Text: return MenuItemView(title: menuItemTypes[$0] as! String, options: self.options, addDivider: $1) case .Image: return MenuItemView(image: menuItemTypes[$0] as! UIImage, options: self.options, addDivider: $1) } }) } private func constructMenuItemViews(constructor: (Int, Bool) -> MenuItemView) { for index in 0..<menuItemCount { let addDivider = index < menuItemCount - 1 let menuItemView = constructor(index % options.menuItemCount, addDivider) menuItemView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(menuItemView) menuItemViews.append(menuItemView) } sortMenuItemViews() } private func sortMenuItemViews() { if !sortedMenuItemViews.isEmpty { sortedMenuItemViews.removeAll() } if case .Infinite = options.menuDisplayMode { for i in 0..<menuItemCount { let index = rawIndex(i) sortedMenuItemViews.append(menuItemViews[index]) } } else { sortedMenuItemViews = menuItemViews } } private func layoutMenuItemViews() { NSLayoutConstraint.deactivateConstraints(contentView.constraints) for (index, menuItemView) in sortedMenuItemViews.enumerate() { let visualFormat: String; var viewsDicrionary = ["menuItemView": menuItemView] if index == 0 { visualFormat = "H:|[menuItemView]" } else { viewsDicrionary["previousMenuItemView"] = sortedMenuItemViews[index - 1] if index == menuItemCount - 1 { visualFormat = "H:[previousMenuItemView][menuItemView]|" } else { visualFormat = "H:[previousMenuItemView][menuItemView]" } } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: [], metrics: nil, views: viewsDicrionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuItemView]|", options: [], metrics: nil, views: viewsDicrionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } setNeedsLayout() layoutIfNeeded() } private func setupUnderlineViewIfNeeded() { guard case let .Underline(height, color, horizontalPadding, verticalPadding) = options.menuItemMode else { return } let width = menuItemViews[currentPage].bounds.width - horizontalPadding * 2 underlineView.frame = CGRectMake(horizontalPadding, options.menuHeight - (height + verticalPadding), width, height) underlineView.backgroundColor = color contentView.addSubview(underlineView) } private func setupRoundRectViewIfNeeded() { guard case let .RoundRect(radius, _, verticalPadding, selectedColor) = options.menuItemMode else { return } let height = options.menuHeight - verticalPadding * 2 roundRectView.frame = CGRectMake(0, verticalPadding, 0, height) roundRectView.layer.cornerRadius = radius roundRectView.backgroundColor = selectedColor contentView.addSubview(roundRectView) } private func animateUnderlineViewIfNeeded() { guard case let .Underline(_, _, horizontalPadding, _) = options.menuItemMode else { return } let targetFrame = menuItemViews[currentPage].frame underlineView.frame.origin.x = targetFrame.minX + horizontalPadding underlineView.frame.size.width = targetFrame.width - horizontalPadding * 2 } private func animateRoundRectViewIfNeeded() { guard case let .RoundRect(_, horizontalPadding, _, _) = options.menuItemMode else { return } let targetFrame = menuItemViews[currentPage].frame roundRectView.frame.origin.x = targetFrame.minX + horizontalPadding roundRectView.frame.size.width = targetFrame.width - horizontalPadding * 2 } private func relayoutMenuItemViews() { sortMenuItemViews() layoutMenuItemViews() } private func positionMenuItemViews() { contentOffset.x = contentOffsetX animateUnderlineViewIfNeeded() animateRoundRectViewIfNeeded() } private func adjustmentContentInsetIfNeeded() { switch options.menuDisplayMode { case let .Standard(_, centerItem, _) where centerItem: break default: return } let firstMenuView = menuItemViews.first! let lastMenuView = menuItemViews.last! var inset = contentInset let halfWidth = frame.width / 2 inset.left = halfWidth - firstMenuView.frame.width / 2 inset.right = halfWidth - lastMenuView.frame.width / 2 contentInset = inset } private func focusMenuItem() { let selected: (MenuItemView) -> Bool = { self.menuItemViews.indexOf($0) == self.currentPage } // make selected item focused menuItemViews.forEach { $0.selected = selected($0) if $0.selected { self.currentMenuItemView = $0 } } // make selected item foreground sortedMenuItemViews.forEach { $0.layer.zPosition = selected($0) ? 0 : -1 } setNeedsLayout() layoutIfNeeded() } }
apache-2.0
5d79f0040aa00bb50cd809981bebd832
36.3687
166
0.632072
5.847655
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/TextInputFormatter/TextInputValidationResult+OptimizeChanges.swift
1
1909
// // TextInputValidationResult+OptimizeChanges.swift // TextInputKit // // Created by Artem Starosvetskiy on 10/12/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // public extension TextInputValidationResult { static func optimalValidationResult( forEditing originalString: String, replacing replacementString: String, at editedRange: Range<String.Index>, withSelection originalSelectedRange: Range<String.Index>, resulting resultingString: String, withSelection resultingSelectedRange: Range<String.Index>) -> TextInputValidationResult { let hasChangesAgainstOriginalInput: Bool = { return (originalSelectedRange != resultingSelectedRange) || (originalString != resultingString) }() if !hasChangesAgainstOriginalInput { return .rejected } let hasChangesAgainstProposedResult: Bool = { let proposedResultingString = originalString.replacingCharacters(in: editedRange, with: replacementString) if resultingString != proposedResultingString { return true } let proposedResultingSelectedRange: Range<String.Index> = { var index = (editedRange.lowerBound == originalString.startIndex) ? proposedResultingString.startIndex : proposedResultingString.index(after: originalString.index(before: editedRange.lowerBound)) index = proposedResultingString.index(index, offsetBy: replacementString.count) return index..<index }() return resultingSelectedRange != proposedResultingSelectedRange }() if !hasChangesAgainstProposedResult { return .accepted } return .changed(resultingString, selectedRange: resultingSelectedRange) } }
mit
69443a74b4620fd61e7184cfbc626c1d
36.411765
118
0.665618
6.115385
false
false
false
false
TENDIGI/TVBoard
Keyboard/KeyboardTransition.swift
1
2814
// // KeyboardTransition.swift // Pods // // Created by Eric Kunz on 12/1/15. // // import Foundation import UIKit struct KeyboardTransitionConstants { static let animationDuration = 0.5 } class KeyboardPresentationTransition: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let fromView = fromController.view let toController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! Keyboard let collectionView = toController.view let keyboardHeight = toController.keyboardHeight() collectionView?.frame = CGRect(x: 0, y: fromView.frame.height, width: fromView.frame.width, height: fromView.frame.height) transitionContext.containerView()?.addSubview(collectionView!) var endFrame = collectionView!.frame endFrame.origin.y = fromView.frame.height - keyboardHeight if transitionContext.isAnimated() { UIView.animateWithDuration(KeyboardTransitionConstants.animationDuration, animations: { () -> Void in collectionView?.frame = endFrame }, completion: { (completed) -> Void in transitionContext.completeTransition(completed) }) } else { collectionView?.frame = endFrame } } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return KeyboardTransitionConstants.animationDuration } } class KeyboardDismissalTransition: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let keyboardController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let keyboard = keyboardController.view var endFrame = keyboard!.frame endFrame.origin.y = keyboard.frame.height if transitionContext.isAnimated() { UIView.animateWithDuration(KeyboardTransitionConstants.animationDuration, animations: { () -> Void in keyboard?.frame = endFrame }, completion: { (completed) -> Void in keyboard?.removeFromSuperview() transitionContext.completeTransition(completed) }) } else { keyboard?.frame = endFrame } } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return KeyboardTransitionConstants.animationDuration } }
mit
3908811a1d827a3cc77e42349232d06f
36.039474
130
0.687278
6.605634
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Extrude graphics/ExtrudeGraphicsViewController.swift
1
4436
// // Copyright 2016 Esri. // // 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 ArcGIS class ExtrudeGraphicsViewController: UIViewController { @IBOutlet var sceneView:AGSSceneView! private var graphicsOverlay: AGSGraphicsOverlay! private let squareSize:Double = 0.01 private let spacing:Double = 0.01 private let maxHeight = 10000 override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ExtrudeGraphicsViewController"] //initialize scene with topographic basemap let scene = AGSScene(basemap: AGSBasemap.topographicBasemap()) //assign scene to the scene view self.sceneView.scene = scene //set the viewpoint camera let camera = AGSCamera(latitude: 28.4, longitude: 83, altitude: 20000, heading: 10, pitch: 70, roll: 300) self.sceneView.setViewpointCamera(camera) //add graphics overlay self.graphicsOverlay = AGSGraphicsOverlay() self.graphicsOverlay.sceneProperties?.surfacePlacement = .Draped self.sceneView.graphicsOverlays.addObject(self.graphicsOverlay) //simple renderer with extrusion property let renderer = AGSSimpleRenderer() let lineSymbol = AGSSimpleLineSymbol(style: .Solid, color: UIColor.whiteColor(), width: 1) renderer.symbol = AGSSimpleFillSymbol(style: .Solid, color: UIColor.primaryBlue(), outline: lineSymbol) renderer.sceneProperties?.extrusionMode = .BaseHeight renderer.sceneProperties?.extrusionExpression = "[height]" self.graphicsOverlay.renderer = renderer // add base surface for elevation data let surface = AGSSurface() let elevationSource = AGSArcGISTiledElevationSource(URL: NSURL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!) surface.elevationSources.append(elevationSource) scene.baseSurface = surface //add the graphics self.addGraphics() } private func addGraphics() { //starting point let x = self.sceneView.currentViewpointCamera().location.x - 0.01 let y = self.sceneView.currentViewpointCamera().location.y + 0.25 //creating a grid of polygon graphics for i in 0...6 { for j in 0...4 { let polygon = self.polygonForStartingPoint(AGSPoint(x: x + Double(i) * (squareSize + spacing), y: y + Double(j) * (squareSize + spacing), spatialReference: nil)) self.addGraphicForPolygon(polygon) } } } //the function returns a polygon starting at the given point //with size equal to squareSize private func polygonForStartingPoint(point:AGSPoint) -> AGSPolygon { let polygon = AGSPolygonBuilder(spatialReference: AGSSpatialReference.WGS84()) polygon.addPointWithX(point.x, y: point.y) polygon.addPointWithX(point.x, y: point.y+squareSize) polygon.addPointWithX(point.x + squareSize, y: point.y + squareSize) polygon.addPointWithX(point.x + squareSize, y: point.y) return polygon.toGeometry() } //add a graphic to the graphics overlay for the given polygon private func addGraphicForPolygon(polygon:AGSPolygon) { let rand = Int(arc4random()) % self.maxHeight let graphic = AGSGraphic(geometry: polygon, symbol: nil, attributes: nil) graphic.attributes.setValue(rand, forKey: "height") self.graphicsOverlay.graphics.addObject(graphic) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
b9090496f62277201f66bc460f5c0b36
40.074074
177
0.679441
4.679325
false
false
false
false
fabianehlert/FEQRScanViewController
FEQRScanViewController/FEQRScanViewController.swift
1
8888
/* FEQRScanViewController.swift Created by Fabian Ehlert on 19.12.15. Copyright © 2015 Fabian Ehlert. 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 UIKit import AVFoundation class FENavigationController: UINavigationController { override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .Portrait } } protocol FEQRScanViewControllerDelegate { func didScanCodeWithResult(result: String) } class FEQRScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var delegate: FEQRScanViewControllerDelegate? @IBOutlet weak var cameraView: UIView! private var closeTitle = "Close" private var captureSession: AVCaptureSession! private var previewLayer: AVCaptureVideoPreviewLayer! // MARK: Init init(closeTitle: String) { super.init(nibName: nil, bundle: nil) self.closeTitle = closeTitle } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: ViewController lifecycle override func viewDidLoad() { super.viewDidLoad() // Close-Button let doneButton = UIBarButtonItem(title: closeTitle, style: .Plain, target: self, action: "done") navigationItem.setLeftBarButtonItem(doneButton, animated: false) // Request camera access AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in if granted { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.setupScanner() }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.accessDenied() }) } }) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateUI() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Setup private func setupScanner() { // Initialize and configure the CaptureSession captureSession = AVCaptureSession() captureSession = configureSession(captureSession) let metadataOutput = AVCaptureMetadataOutput() if captureSession.canAddOutput(metadataOutput) { captureSession.addOutput(metadataOutput) if qrScanTypeAvailable(metadataOutput) { metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()!) metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] } else { scannerFailed() return } } else { scannerFailed() return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.frame = cameraView.layer.bounds cameraView.layer.masksToBounds = true cameraView.layer.addSublayer(previewLayer) updateUI() dispatch_async(dispatch_get_main_queue()) { () -> Void in self.captureSession.startRunning() } } private func configureSession(session: AVCaptureSession) -> AVCaptureSession { session.beginConfiguration() for input in session.inputs { session.removeInput(input as! AVCaptureInput) } if let input = rearCamera() { session.addInput(input) } session.commitConfiguration() return session } private func rearCamera() -> AVCaptureDeviceInput? { // Search for input devices. If one is available, return it for device in (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)) { if let captureDevice: AVCaptureDevice! = device as! AVCaptureDevice { if captureDevice.position == .Back { var input: AVCaptureDeviceInput? do { input = try AVCaptureDeviceInput(device: captureDevice) return input } catch let error { print(error) } return nil } } } return nil } private func qrScanTypeAvailable(metadataOutput: AVCaptureMetadataOutput) -> Bool { if let types: [String] = metadataOutput.availableMetadataObjectTypes as? [String] { if types.contains(AVMetadataObjectTypeQRCode) { return true } return false } return false } // MARK: Scanner lifecycle private func foundCode(result: String) { done() delegate?.didScanCodeWithResult(result) } private func updateUI() { dispatch_async(dispatch_get_main_queue()) { () -> Void in if let _ = self.previewLayer { self.previewLayer.frame = self.cameraView.layer.bounds } } } // MARK: AVCaptureMetadataOutputObjectsDelegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if let _ = captureSession { captureSession.stopRunning() } if let metadataObject = metadataObjects.first { let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) foundCode(readableObject.stringValue) } } // MARK: Error messages private func accessDenied() { let permissionAlert = UIAlertController(title: "Camera access denied!", message: nil, preferredStyle: UIAlertControllerStyle.Alert) permissionAlert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action: UIAlertAction) -> Void in self.done() })) self.presentViewController(permissionAlert, animated: true, completion: nil) } private func scannerFailed() { let alert = UIAlertController(title: "Scanning failed!", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action: UIAlertAction) -> Void in self.done() })) presentViewController(alert, animated: true, completion: nil) } // MARK: ScanController dismissal func done() { dismissViewControllerAnimated(true, completion: nil) } // MARK: Helper private func interfaceOrientationToVideoOrientation(orientation: UIInterfaceOrientation) -> AVCaptureVideoOrientation { switch orientation { case .Portrait: return AVCaptureVideoOrientation.Portrait case .PortraitUpsideDown: return AVCaptureVideoOrientation.PortraitUpsideDown case .LandscapeLeft: return AVCaptureVideoOrientation.LandscapeLeft case .LandscapeRight: return AVCaptureVideoOrientation.LandscapeRight default: return AVCaptureVideoOrientation.Portrait } } // MARK: Rotation override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .Portrait } }
mit
1f8f865513a5c52430501ace3b98b384
32.409774
162
0.638911
5.944482
false
false
false
false
WaterReporter/WaterReporter-iOS
WaterReporter/WaterReporter/NewReportTableViewController.swift
1
39643
// // NewReportTableViewController.swift // WaterReporter // // Created by Viable Industries on 7/24/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import CoreLocation import Mapbox import OpenGraph import SwiftyJSON import UIKit class NewReportTableViewController: UITableViewController, UIImagePickerControllerDelegate, UITextViewDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, MGLMapViewDelegate, NewReportLocationSelectorDelegate { // // MARK: @IBOutlets // @IBOutlet weak var navigationBarButtonSave: UIBarButtonItem! @IBOutlet var indicatorLoadingView: UIView! // // MARK: @IBActions // @IBAction func launchNewReportLocationSelector(sender: UIButton) { self.performSegueWithIdentifier("setLocationForNewReport", sender: sender) } @IBAction func attemptOpenPhotoTypeSelector(sender: AnyObject) { let thisActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .Default, handler:self.cameraActionHandler) thisActionSheet.addAction(cameraAction) let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .Default, handler:self.photoLibraryActionHandler) thisActionSheet.addAction(photoLibraryAction) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) thisActionSheet.addAction(cancelAction) presentViewController(thisActionSheet, animated: true, completion: nil) } @IBAction func buttonSaveNewReportTableViewController(sender: UIBarButtonItem) { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] self.attemptNewReportSave(headers) } @IBAction func selectGroup(sender: UISwitch) { if sender.on { let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])" self.tempGroups.append(_organization_id_number) print("addGroup::finished::tempGroups \(self.tempGroups)") } else { let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])" self.tempGroups = self.tempGroups.filter() {$0 != _organization_id_number} print("removeGroup::finished::tempGroups \(self.tempGroups)") } } // // MARK: Variables // var loadingView: UIView! var userSelectedCoorindates: CLLocationCoordinate2D! var imageReportImagePreviewIsSet:Bool = false var thisLocationManager: CLLocationManager = CLLocationManager() var tempGroups: [String] = [String]() var groups: JSON? var reportImage: UIImage! var reportDescription: String = "Write a few words about the photo or paste a link..." var hashtagAutocomplete: [String] = [String]() var hashtagSearchEnabled: Bool = false var dataSource: HashtagTableView = HashtagTableView() var hashtagSearchTimer: NSTimer = NSTimer() var og_paste: String! var og_active: Bool = false var og_title: String! var og_description: String! var og_sitename: String! var og_type: String! var og_image: String! var og_url: String! // // MARK: Overrides // override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) // // Load default list of groups into the form // self.attemptLoadUserGroups() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(true) if self.tabBarController?.selectedIndex != 2 { // // When navigating away from this tab the Commons team wants this // form to clear out. // // Reset all fields self.imageReportImagePreviewIsSet = false self.reportDescription = "Write a few words about the photo or paste a link..." self.reportImage = nil self.og_paste = "" self.og_active = false self.og_title = "" self.og_description = "" self.og_sitename = "" self.og_type = "" self.og_image = "" self.og_url = "" self.tempGroups = [String]() self.tableView.reloadData() self.userSelectedCoorindates = nil } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) } override func viewDidLoad() { super.viewDidLoad() // // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up // self.view.setNeedsLayout() self.view.layoutIfNeeded() self.navigationItem.title = "New Report" self.tableView.backgroundColor = UIColor.colorBackground(1.00) self.dataSource.parent = self // // Setup Navigation Bar // navigationBarButtonSave.target = self navigationBarButtonSave.action = #selector(buttonSaveNewReportTableViewController(_:)) } // // MARK: Advanced TextView Interactions // func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { // [text isEqualToString:[UIPasteboard generalPasteboard].string] let _pasteboard = UIPasteboard.generalPasteboard().string if (text == _pasteboard) { // // Step 1: Get the information being pasted // print("Pasting text", _pasteboard) // _pasteboard = _pasteboard!.stringByRemovingPercentEncoding!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! if let checkedUrl = NSURL(string: _pasteboard!) { // // Step 2: Check to see if the text being pasted is a link // OpenGraph.fetch(checkedUrl) { og, error in print("Open Graph \(og)") self.og_paste = "\(checkedUrl)" if og?[.title] != nil { let _og_title = og?[.title]!.stringByDecodingHTMLEntities self.og_title = "\(_og_title!)" } else { self.og_title = "" } if og?[.description] != nil { let _og_description_encoded = og?[.description]! let _og_description = _og_description_encoded?.stringByDecodingHTMLEntities self.og_description = "\(_og_description!)" self.reportDescription = "\(_og_description!)" } else { self.og_description = "" } if og?[.type] != nil { let _og_type = og?[.type]! self.og_type = "\(_og_type!)" } else { self.og_type = "" } if og?[.image] != nil { let _ogImage = og?[.image]! print("_ogImage \(_ogImage!)") if let imageURL = NSURL(string: _ogImage!) { self.og_image = "\(imageURL)" } else { let _tmpImage = "\(_ogImage!)" let _image = _tmpImage.characters.split{$0 == " "}.map(String.init) if _image.count >= 1 { var _imageUrl = _image[0] if let imageURLRange = _imageUrl.rangeOfString("?") { _imageUrl.removeRange(imageURLRange.startIndex..<_imageUrl.endIndex) self.og_image = "\(_imageUrl)" } } } } else { self.og_image = "" } if og?[.url] != nil { let _og_url = og?[.url]! self.og_url = "\(_og_url!)" } else { self.og_url = "" } if self.og_url != "" && self.og_image != "" { self.og_active = true } // We need to wait for all other tasks to finish before // executing the table reload // NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.reloadData() } } } return true } return false } func textViewDidBeginEditing(textView: UITextView) { if textView.text == "Write a few words about the photo or paste a link..." { textView.text = "" } } func textViewDidChange(textView: UITextView) { let _text: String = "\(textView.text)" // let _index = NSIndexPath.init(forRow: 0, inSection: 0) // Always make sure we are constantly copying what is entered into the // remote text field into this controller so that we can pass it along // to the report save methods. // self.reportDescription = _text // if _text != "" && _text.characters.last! == "#" { // self.hashtagSearchEnabled = true // // print("Hashtag Search: Found start of hashtag") // } // else if _text != "" && self.hashtagSearchEnabled == true && _text.characters.last! == " " { // self.hashtagSearchEnabled = false // self.dataSource.results = [String]() // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // print("Hashtag Search: Disabling search because space was entered") // print("Hashtag Search: Timer reset to zero due to search termination (space entered)") // self.hashtagSearchTimer.invalidate() // // } // else if _text != "" && self.hashtagSearchEnabled == true { // // self.dataSource.results = [String]() // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // // Identify hashtag search // // // let _hashtag_identifier = _text.rangeOfString("#", options:NSStringCompareOptions.BackwardsSearch) // if ((_hashtag_identifier) != nil) { // let _hashtag_search: String! = _text.substringFromIndex((_hashtag_identifier?.endIndex)!) // // // Add what the user is typing to the top of the list // // // print("Hashtag Search: Performing search for \(_hashtag_search)") // // dataSource.results = ["\(_hashtag_search)"] // dataSource.search = "\(_hashtag_search)" // // dataSource.numberOfRowsInSection(dataSource.results.count) // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // // Execute the serverside search BUT wait a few milliseconds between // // each character so we aren't returning inconsistent results to // // the user // // // print("Hashtag Search: Timer reset to zero") // self.hashtagSearchTimer.invalidate() // // print("Hashtag Search: Send this to search methods \(_hashtag_search) after delay expires") //// self.hashtagSearchTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.searchHashtags(_:)), userInfo: _hashtag_search, repeats: false) // // } // // } } // // MARK: Custom TextView Functionality // func focusTextView() { } // // MARK: Table Overrides // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRows: Int = 2 if section == 0 { numberOfRows = 2 // if self.dataSource.results != nil { // let numberOfHashtags: Int = (self.dataSource.results.count) // numberOfRows = numberOfHashtags // } } else if section == 1 { if self.groups != nil { let numberOfGroups: Int = (self.groups?["features"].count)! numberOfRows = (numberOfGroups) } } return numberOfRows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportContentTableViewCell", forIndexPath: indexPath) as! NewReportContentTableViewCell // Report Image // cell.buttonReportAddImage.addTarget(self, action: #selector(NewReportTableViewController.attemptOpenPhotoTypeSelector(_:)), forControlEvents: .TouchUpInside) if (self.reportImage != nil) { cell.imageReportImage.image = self.reportImage } else { cell.imageReportImage.image = UIImage(named: "icon--camera") } // Report Description // if self.reportDescription != "" { cell.textviewReportDescription.text = self.reportDescription } cell.textviewReportDescription.delegate = self cell.textviewReportDescription.targetForAction(#selector(self.textViewDidChange(_:)), withSender: self) // Report Description > Hashtag Type Ahead // cell.tableViewHashtag.delegate = self.dataSource cell.tableViewHashtag.dataSource = self.dataSource if self.hashtagSearchEnabled == true { cell.tableViewHashtag.hidden = false cell.typeAheadHeight.constant = 128.0 } else { cell.tableViewHashtag.hidden = true cell.typeAheadHeight.constant = 0.0 } // Report Description > Open Graph // if self.og_active { cell.ogView.hidden = false cell.ogViewHeightConstraint.constant = 256.0 // Open Graph > Title // cell.ogTitle.text = self.og_title // Open Graph > Description // cell.ogDescription.text = self.og_description // Open Graph > Image // if self.og_image != "" { let ogImageURL:NSURL = NSURL(string: "\(self.og_image)")! cell.ogImage.kf_indicatorType = .Activity cell.ogImage.kf_showIndicatorWhenLoading = true cell.ogImage.kf_setImageWithURL(ogImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.ogImage.image = image if (self.imageReportImagePreviewIsSet == false) { self.reportImage = image self.imageReportImagePreviewIsSet = true self.tableView.reloadData() } }) } } else { cell.ogView.hidden = true cell.ogViewHeightConstraint.constant = 0.0 } return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportLocationTableViewCell", forIndexPath: indexPath) as! NewReportLocationTableViewCell print("Location Row") // Display location selection map when Confirm Location button is // tapped/touched // cell.buttonChangeLocation.addTarget(self, action: #selector(self.launchNewReportLocationSelector(_:)), forControlEvents: .TouchUpInside) // Update the text display for the user selected coordinates when // the self.userSelectedCoorindates variable is not empty // print("self.userSelectedCoorindates \(self.userSelectedCoorindates)") if self.userSelectedCoorindates != nil { cell.labelLocation.text = String(self.userSelectedCoorindates.longitude) + " " + String(self.userSelectedCoorindates.latitude) } else { cell.labelLocation.text = "Confirm location" } return cell } } else if indexPath.section == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportGroupTableViewCell", forIndexPath: indexPath) as! NewReportGroupTableViewCell guard (self.groups != nil) else { return cell } let _index = indexPath.row let group = self.groups?["features"][_index] if group != nil { // Organization Logo // cell.imageGroupLogo.tag = _index cell.imageGroupLogo.tag = indexPath.row let organizationImageUrl:NSURL = NSURL(string: "\(group!["properties"]["organization"]["properties"]["picture"])")! cell.imageGroupLogo.kf_indicatorType = .Activity cell.imageGroupLogo.kf_showIndicatorWhenLoading = true cell.imageGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.imageGroupLogo.image = image cell.imageGroupLogo.layer.cornerRadius = cell.imageGroupLogo.frame.size.width / 2 cell.imageGroupLogo.clipsToBounds = true }) // Organization Name // cell.labelGroupName.text = "\(group!["properties"]["organization"]["properties"]["name"])" // Organization Switch/Selection // cell.switchGroupSelect.tag = _index if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] { if self.tempGroups.contains("\(_organization_id_number)") { cell.switchGroupSelect.on = true } else { cell.switchGroupSelect.on = false } } } return cell } return UITableViewCell() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var rowHeight: CGFloat = 44.0 if indexPath.section == 0 { // if (indexPath.row == 1 && self.hashtagTypeAhead.hidden == false) { if (indexPath.row == 0) { if (self.og_active == false) { if (self.hashtagSearchEnabled == true) { rowHeight = 288.0 } else if (self.hashtagSearchEnabled == false) { rowHeight = 128.0 } } else if (self.og_active == true) { if (self.hashtagSearchEnabled == true) { rowHeight = 527.0 } else if (self.hashtagSearchEnabled == false) { rowHeight = 384.0 } } else { rowHeight = 128.0 } } } else if indexPath.section == 1 { rowHeight = 72.0 } return rowHeight } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let segueId = segue.identifier else { return } switch segueId { case "setLocationForNewReport": let destinationNavigationViewController = segue.destinationViewController as! UINavigationController let destinationNewReportLocationSelectorViewController = destinationNavigationViewController.topViewController as! NewReportLocationSelector destinationNewReportLocationSelectorViewController.delegate = self destinationNewReportLocationSelectorViewController.userSelectedCoordinates = self.userSelectedCoorindates break default: break } } func onSetCoordinatesComplete(isFinished: Bool) { return } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // // MARK: Custom Statuses // func saving() { // // Create a view that covers the entire screen // self.loadingView = self.indicatorLoadingView self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) self.view.addSubview(self.loadingView) self.view.bringSubviewToFront(self.loadingView) // // Make sure that the Done/Save button is disabled // self.navigationItem.rightBarButtonItem?.enabled = false // // Make sure our view is scrolled to the top // self.tableView.setContentOffset(CGPointZero, animated: false) } func finishedSaving() { // // Create a view that covers the entire screen // self.loadingView.removeFromSuperview() // // Make sure that the Done/Save button is disabled // self.navigationItem.rightBarButtonItem?.enabled = true // // Make sure our view is scrolled to the top // self.tableView.setContentOffset(CGPointZero, animated: false) // Reset all fields self.imageReportImagePreviewIsSet = false self.reportDescription = "Write a few words about the photo or paste a link..." self.reportImage = nil self.og_paste = "" self.og_active = false self.og_title = "" self.og_description = "" self.og_sitename = "" self.og_type = "" self.og_image = "" self.og_url = "" self.tempGroups = [String]() self.tableView.reloadData() self.userSelectedCoorindates = nil } func finishedSavingWithError() { self.navigationItem.rightBarButtonItem?.enabled = true } // // MARK: Camera Functionality // func cameraActionHandler(action:UIAlertAction) -> Void { if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } func photoLibraryActionHandler(action:UIAlertAction) -> Void { if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { // Change the default camera icon to a preview of the image the user // has selected to be their report image. // self.reportImage = image self.imageReportImagePreviewIsSet = true // Refresh the table view to display the updated image data // self.dismissViewControllerAnimated(true, completion: { self.tableView.reloadData() }) } // // MARK: Location Child Delegate // func sendCoordinates(coordinates: CLLocationCoordinate2D) { print("PARENT:sendCoordinates see \(coordinates)") // Pass off coorindates to the self.userSelectedCoordinates // self.userSelectedCoorindates = coordinates // Update the display of the returned coordinates in the "Confirm // Location" table view cell label // self.tableView.reloadData() } // // MARK: Server Request/Response functionality // func displayErrorMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func buildRequestHeaders() -> [String: String] { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") return [ "Authorization": "Bearer " + (accessToken! as! String) ] } func attemptNewReportSave(headers: [String: String]) { // // Error Check for Geometry // var geometryCollection: [String: AnyObject] = [ "type": "GeometryCollection" ] if (self.userSelectedCoorindates != nil) { var geometry: [String: AnyObject] = [ "type": "Point" ] let coordinates: Array = [ self.userSelectedCoorindates.longitude, self.userSelectedCoorindates.latitude ] geometry["coordinates"] = coordinates let geometries: [AnyObject] = [geometry] geometryCollection["geometries"] = geometries } else { self.displayErrorMessage("Location Field Empty", message: "Please add a location to your report before saving") self.finishedSavingWithError() return } // // Check image value // if (!imageReportImagePreviewIsSet) { self.displayErrorMessage("Image Field Empty", message: "Please add an image to your report before saving") self.finishedSavingWithError() return } // Before starting the saving process, hide the form // and show the user the saving indicator self.saving() // // REPORT DATE // let dateFormatter = NSDateFormatter() let date = NSDate() dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle let report_date: String = dateFormatter.stringFromDate(date) print("report_date \(report_date)") // // PARAMETERS // if self.reportDescription == "Write a few words about the photo or paste a link..." { self.reportDescription = "" } var parameters: [String: AnyObject] = [ "report_description": self.reportDescription, "report_date": report_date, "is_public": "true", "geometry": geometryCollection, "state": "open" ] // // GROUPS // var _temporary_groups: [AnyObject] = [AnyObject]() for _organization_id in tempGroups { print("group id \(_organization_id)") let _group = [ "id": "\(_organization_id)", ] _temporary_groups.append(_group) } parameters["groups"] = _temporary_groups // // OPEN GRAPH // var open_graph: [AnyObject] = [AnyObject]() if self.og_active { let _social = [ "og_title": self.og_title, "og_type": self.og_type, "og_url": self.og_url, "og_image_url": self.og_image, "og_description": self.og_description ] open_graph.append(_social) } parameters["social"] = open_graph // // Make request // if (self.reportImage != nil) { Alamofire.upload(.POST, Endpoints.POST_IMAGE, headers: headers, multipartFormData: { multipartFormData in // import image to request if let imageData = UIImageJPEGRepresentation(self.reportImage!, 1) { multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "ReportImageFromiPhone.jpg", mimeType: "image/jpeg") } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in print("Image uploaded \(response)") if let value = response.result.value { let imageResponse = JSON(value) let image = [ "id": String(imageResponse["id"].rawValue) ] let images: [AnyObject] = [image] parameters["images"] = images print("parameters \(parameters)") Alamofire.request(.POST, Endpoints.POST_REPORT, parameters: parameters, headers: headers, encoding: .JSON) .responseJSON { response in print("Response \(response)") switch response.result { case .Success(let value): print("Response Sucess \(value)") // Hide the loading indicator self.finishedSaving() // Send user to the Activty Feed self.tabBarController?.selectedIndex = 0 case .Failure(let error): print("Response Failure \(error)") break } } } } case .Failure(let encodingError): print(encodingError) } }) } } func attemptLoadUserGroups() { // Set headers let _headers = self.buildRequestHeaders() if let userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber { let GET_GROUPS_ENDPOINT = Endpoints.GET_USER_PROFILE + "\(userId)" + "/groups" Alamofire.request(.GET, GET_GROUPS_ENDPOINT, headers: _headers, encoding: .JSON).responseJSON { response in print("response.result \(response.result)") switch response.result { case .Success(let value): // print("Request Success for Groups: \(value)") // Assign response to groups variable self.groups = JSON(value) // Refresh the data in the table so the newest items appear self.tableView.reloadData() break case .Failure(let error): print("Request Failure: \(error)") break } } } else { self.attemptRetrieveUserID() } } func attemptRetrieveUserID() { // Set headers let _headers = self.buildRequestHeaders() Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): let json = JSON(value) if let data: AnyObject = json.rawValue { NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID") self.attemptLoadUserGroups() } case .Failure(let error): print(error) } } } // // MARK: Hashtag // func searchHashtags(timer: NSTimer) { let queryText: String! = "\(timer.userInfo!)" print("searchHashtags fired with \(queryText)") // // Send a request to the defined endpoint with the given parameters // let parameters = [ "q": "{\"filters\": [{\"name\":\"tag\",\"op\":\"like\",\"val\":\"\(queryText)%\"}]}" ] Alamofire.request(.GET, Endpoints.GET_MANY_HASHTAGS, parameters: parameters) .responseJSON { response in switch response.result { case .Success(let value): let _results = JSON(value) // print("self.dataSource >>>> _results \(_results)") for _result in _results["features"] { print("_result \(_result.1["properties"]["tag"])") let _tag = "\(_result.1["properties"]["tag"])" self.dataSource.results.append(_tag) } self.dataSource.numberOfRowsInSection(_results["features"].count) let _index = NSIndexPath.init(forRow: 0, inSection: 0) self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) case .Failure(let error): print(error) break } } } func selectedValue(value: String, searchText: String) { let _index = NSIndexPath.init(forRow: 0, inSection: 0) let _selection = "\(value)" print("Hashtag Selected, now we need to update the textview with selected \(value) and search text \(searchText) so that it makes sense with \(self.reportDescription)") let _temporaryCopy = self.reportDescription let _updatedDescription = _temporaryCopy.stringByReplacingOccurrencesOfString(searchText, withString: _selection, options: NSStringCompareOptions.LiteralSearch, range: nil) print("Updated Text \(_updatedDescription)") // Add the hashtag to the text // self.reportDescription = "\(_updatedDescription)" // Reset the search // self.hashtagSearchEnabled = false self.dataSource.results = [String]() self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) print("Hashtag Search: Timer reset to zero due to user selection") self.hashtagSearchTimer.invalidate() } }
agpl-3.0
11d8b44a159ac2c635ad67c42fd70080
34.907609
226
0.50116
6.138433
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
PerchReadyApp/apps/Perch/iphone/native/Perch/Utilities/WLProcedureCaller.swift
1
2529
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation /** * An extension to the WLDelegate protocol that additionally declares an onPreExecute() and onPostExecute() method. */ protocol WLDataDelegate : WLDelegate { func onPreExecute() func onPostExecute() } /** * Wrapper class for making a Worklight procedure call. */ class WLProcedureCaller: NSObject { private var dataDelegate : WLDataDelegate! private var adapterName : String! private var procedureName : String! private var logWLStartTime : NSDate! private let TIMEOUT_MILLIS = 10000 /** Constructor to initialize the procedure caller with both the adapter name and procedure name. - parameter adapterName: - parameter procedureName: - returns: WLProcedureCaller */ init(adapterName : String, procedureName: String){ self.adapterName = adapterName self.procedureName = procedureName } /** This function will execute the adapter procedure and invoke the appropriate functions of the WLDataDelegate that is passed in. - parameter dataDelegate: - parameter params: Procedure parameters */ func invokeWithResponse(dataDelegate: WLDataDelegate, params: Array<String>?){ self.dataDelegate = dataDelegate self.dataDelegate.onPreExecute() let invocationData = WLProcedureInvocationData(adapterName: adapterName, procedureName: procedureName) invocationData.parameters = params //Timeout value in milliseconds let options = NSDictionary(object:TIMEOUT_MILLIS, forKey: "timeout") logWLStartTime = NSDate() WLClient.sharedInstance().invokeProcedure(invocationData, withDelegate: self, options:options as [NSObject : AnyObject]) } } extension WLProcedureCaller: WLDelegate { func onSuccess(response: WLResponse!) { _ = NSDate().timeIntervalSinceDate(logWLStartTime) dataDelegate.onSuccess(response) dataDelegate.onPostExecute() } func onFailure(response: WLFailResponse!) { var resultText : String = "Invocation Failure" if(response.responseText != nil) { resultText = "\(resultText): \(response.responseText)" print(resultText) MQALogger.log("\(resultText)", withLevel: MQALogLevelWarning) } dataDelegate.onFailure(response) dataDelegate.onPostExecute() } }
epl-1.0
93660049b9641b282749d4a2e2144779
31
128
0.685522
5.401709
false
false
false
false
ZevEisenberg/Padiddle
Padiddle/Padiddle/Utilities/Geometry.swift
1
2923
// // Geometry.swift // Padiddle // // Created by Zev Eisenberg on 10/16/15. // Copyright © 2015 Zev Eisenberg. All rights reserved. // import CoreGraphics.CGGeometry import UIKit.UIScreen extension CGPoint { static func distanceBetween(_ p1: CGPoint, _ p2: CGPoint) -> CGFloat { if p1.equalTo(p2) { return 0 } else { return hypot(p1.x - p2.x, p1.y - p2.y) } } static func lineIntersection(m1: CGFloat, b1: CGFloat, m2: CGFloat, b2: CGFloat) -> CGPoint? { if m1 == m2 { // lines are parallel return nil } let returnX = (b2 - b1) / (m1 - m2) let returnY = m1 * returnX + b1 return CGPoint(x: returnX, y: returnY) } } extension CGSize { static func max(_ size1: CGSize, _ size2: CGSize) -> CGSize { let maxWidth = Swift.max(size1.width, size2.width) let maxHeight = Swift.max(size1.height, size2.height) return CGSize(width: maxWidth, height: maxHeight) } } extension CGRect { func centerSmallerRect(_ smallerRect: CGRect) -> CGRect { assert(smallerRect.width <= self.width) assert(smallerRect.height <= self.height) assert(smallerRect.origin == .zero) assert(self.origin == .zero) let newRect = smallerRect.offsetBy( dx: (self.width - smallerRect.width) / 2, dy: (self.height - smallerRect.height) / 2 ) return newRect } } extension CGPoint { var screenPixelsIntegral: CGPoint { let screenScale = UIScreen.main.scale var newX = x var newY = y // integralize to screen pixels newX *= screenScale newY *= screenScale newX = round(newX) newY = round(newY) newX /= screenScale newY /= screenScale return CGPoint(x: newX, y: newY) } func offsetBy(dx: CGFloat, dy: CGFloat) -> CGPoint { CGPoint(x: x + dx, y: y + dy) } } extension CGAffineTransform { var angle: CGFloat { atan2(b, a) } } extension UIInterfaceOrientation { var imageRotation: (orientation: UIImage.Orientation, rotation: CGFloat) { let rotation: CGFloat let imageOrientaion: UIImage.Orientation switch self { case .landscapeLeft: rotation = -CGFloat.pi / 2.0 imageOrientaion = .right case .landscapeRight: rotation = .pi / 2.0 imageOrientaion = .left case .portraitUpsideDown: rotation = .pi imageOrientaion = .down case .portrait, .unknown: rotation = 0 imageOrientaion = .up @unknown default: assertionFailure("Unknown orientation \(rawValue)") rotation = 0 imageOrientaion = .up } return (imageOrientaion, rotation) } }
mit
9ab51bf9b9950b4cec12c7ca436dfa74
21.828125
98
0.568446
4.132956
false
false
false
false
omaralbeik/SwifterSwift
Sources/Extensions/Foundation/Deprecated/FoundationDeprecated.swift
1
1665
// // FoundationDeprecated.swift // SwifterSwift // // Created by Guy Kogus on 04/10/2018. // Copyright © 2018 SwifterSwift // #if canImport(Foundation) import Foundation extension Date { /// SwifterSwift: Random date between two dates. /// /// Date.random() /// Date.random(from: Date()) /// Date.random(upTo: Date()) /// Date.random(from: Date(), upTo: Date()) /// /// - Parameters: /// - fromDate: minimum date (default is Date.distantPast) /// - toDate: maximum date (default is Date.distantFuture) /// - Returns: random date between two dates. @available(*, deprecated: 4.7.0, message: "Use random(in:) or random(in:using:) instead") public static func random(from fromDate: Date = Date.distantPast, upTo toDate: Date = Date.distantFuture) -> Date { guard fromDate != toDate else { return fromDate } let diff = llabs(Int64(toDate.timeIntervalSinceReferenceDate - fromDate.timeIntervalSinceReferenceDate)) var randomValue: Int64 = Int64.random(in: Int64.min...Int64.max) randomValue = llabs(randomValue%diff) let startReferenceDate = toDate > fromDate ? fromDate : toDate return startReferenceDate.addingTimeInterval(TimeInterval(randomValue)) } /// SwifterSwift: Time zone used currently by system. /// /// Date().timeZone -> Europe/Istanbul (current) /// @available(*, deprecated: 4.7.0, message: "`Date` objects are timezone-agnostic. Please use Calendar.current.timeZone instead.") public var timeZone: TimeZone { return Calendar.current.timeZone } } #endif
mit
09b1c91564d0a9e8cac99ddca4af105d
32.959184
132
0.647837
4.277635
false
false
false
false
mixalich7b/SwiftTBot
Examples/EchoBotExample/EchoBotExample/AppDelegate.swift
1
6793
// // AppDelegate.swift // EchoBotExample // // Created by Тупицин Константин on 25.04.16. // Copyright © 2016 mixalich7b. All rights reserved. // import Cocoa import SwiftTBot @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, TBotDelegate { private let bot = TBot(token: "<your_token>") @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { bot.delegate = self bot.on("/start") { "Hello, \($0.from?.firstName ?? $0.chat.firstName ?? "" )"} .on("/test") { _ in "It's work"} .on("/info") {[weak self] (message, textReply) in do { try self?.bot.sendRequest(TBGetMeRequest(), completion: { (response) in if let username = response.responseEntities?.first?.username { textReply.send("\(username)\nhttps://telegram.me/\(username)") } }) } catch { } } let awesomeCommandRegex = try! NSRegularExpression( pattern: "^(\\/awesome)\\s([0-9]{1,4})\\s([0-9]{1,4})$", options: NSRegularExpression.Options(rawValue: 0) ) let argsParsingRegex = try! NSRegularExpression( pattern: "([0-9]{1,4})", options: NSRegularExpression.Options(rawValue: 0) ) bot.on(awesomeCommandRegex) { (message, matchRange, textReply) in guard let text = message.text else { return } let replyString = argsParsingRegex.matches( in: text, options: NSRegularExpression.MatchingOptions.reportProgress, range: matchRange) .reduce("Args: ") { (replyText, checkResult) -> String in return replyText + (text as NSString).substring(with: checkResult.range) + ", " } textReply.send(replyString) } bot.onInline(awesomeCommandRegex) { (inlineQuery, range, inlineQueryReply) in let article1 = TBInlineQueryResultArticle( id: "\(arc4random_uniform(1000))", title: "Test title", inputMessageContent: TBInputTextMessageContent(messageText: "Test text") ) article1.url = "google.com" inlineQueryReply.send([article1]) } bot.start { (error) in print("Bot haven't started, error: \(error?.description ?? "unknown")") } } func applicationWillTerminate(_ aNotification: Notification) { bot.stop() } // MARK: TBotDelegate func didReceiveMessages(messages: [TBMessage], fromBot bot: TBot) -> Void { // messages.forEach(self.respondToMessage) } func didReceiveInlineQueries(inlineQueries: [TBInlineQuery], fromBot bot: TBot) -> Void { // inlineQueries.forEach(self.respondToInlineQuery) } func didFailReceivingUpdates<Res: TBEntity>(fromBot bot: TBot, response: TBResponse<Res>?) { print("Receiving updates failure: \(response?.error?.description ?? "unknown error")") } private func respondToMessage(_ message: TBMessage) { let text = message.text let contact = message.contact let location = message.location let replyText = text ?? contact.map{"\($0.phoneNumber), \($0.firstName)"} ?? location?.debugDescription ?? "Hello!" let replyHTML = "<i>\(replyText)</i>\n<a href='http://www.instml.com/'>Instaml</a>"; let keyboard = TBReplyKeyboardMarkup(buttons: [ [TBKeyboardButton(text: "Contact", requestContact: true)], [TBKeyboardButton(text: "Location", requestLocation: true)] ]); keyboard.selective = true keyboard.oneTimeKeyboard = true let echoRequest = TBSendMessageRequest( chatId: message.chat.id, text: replyHTML, replyMarkup: keyboard, parseMode: .HTML ) do { try self.bot.sendRequest(echoRequest, completion: { (response) in if !response.isOk { print("API error: \(response.error?.description ?? "unknown")") } }) } catch TBError.badRequest { print("Bad request") } catch { print("") } } private func respondToInlineQuery(_ inlineQuery: TBInlineQuery) { let article1 = TBInlineQueryResultArticle( id: "\(arc4random_uniform(1000))", title: "Test title", inputMessageContent: TBInputTextMessageContent(messageText: "Test text") ) article1.url = "google.com" let article2 = TBInlineQueryResultArticle( id: "\(arc4random_uniform(1000))", title: "Awesome article", inputMessageContent: TBInputLocationMessageContent(longitude: 98.292905, latitude: 7.817627) ) article2.url = "vk.com" let btn1 = TBInlineKeyboardButton(text: "Btn1") btn1.url = "2ch.hk/b" btn1.callbackData = "btn1" let btn2 = TBInlineKeyboardButton(text: "Btn2") btn2.callbackData = "btn2" btn2.switchInlineQuery = "switch inline btn2" let btn3 = TBInlineKeyboardButton(text: "Btn3") btn3.callbackData = "btn3" let replyKeyboardMarkup = TBInlineKeyboardMarkup(buttons: [[btn1, btn2], [btn3]]) let article3 = TBInlineQueryResultArticle(id: "\(arc4random_uniform(1000))", title: "Echo result", inputMessageContent: TBInputTextMessageContent(messageText: "Echo: \(inlineQuery.text)"), replyKeyboardMarkup: replyKeyboardMarkup ) article3.url = "youtube.com" article3.description = "Echo: \(inlineQuery.text),\noffset: \(inlineQuery.offset)" let answerInlineRequest = TBAnswerInlineQueryRequest( inlineRequestId: inlineQuery.id, results: [article1, article2, article3] ) answerInlineRequest.switchPMText = "Go PM" answerInlineRequest.switchPMParameter = "info" answerInlineRequest.cacheTimeSeconds = 5 do { try self.bot.sendRequest(answerInlineRequest, completion: { (response) in if !response.isOk { print("API error: \(response.error?.description ?? "unknown")") } }) } catch TBError.badRequest { print("Bad request") } catch { print("") } } }
gpl-3.0
f4f672bccb980d01c53faa21ae14ca09
37.276836
110
0.567085
4.711405
false
false
false
false
brynbellomy/SwiftBitmask
Source/AutoBitmask.swift
1
1478
// // AutoBitmask.swift // SwiftBitmask // // Created by bryn austin bellomy on 2014 Nov 5. // Copyright (c) 2014 bryn austin bellomy. All rights reserved. // import Foundation import Funky public protocol IAutoBitmaskable: Equatable { static var autoBitmaskValues: [Self] { get } } /** The functions in AutoBitmask implement a simple technique allowing non-bitwise types to conform to `IBitmaskRepresentable` with only a few lines of code. Types must conform to `IAutoBitmaskable` (which inherits from `IBitmaskRepresentable`). Enums seem to work best. */ public struct AutoBitmask { public static func autoBitmaskValueFor <T: protocol<IAutoBitmaskable, IBitmaskRepresentable>> (autoBitmaskable:T) -> T.BitmaskRawType { if let index = T.autoBitmaskValues.indexOf(autoBitmaskable) { return T.BitmaskRawType(1 << index) } else { preconditionFailure("Attempted to call autoBitmaskValueFor(_:) with a non-bitmaskable value of T.") } } public static func autoValueFromBitmask <T: protocol<IAutoBitmaskable, IBitmaskRepresentable>> (bitmaskValue:T.BitmaskRawType) -> T { let index = findWhere(T.autoBitmaskValues) { $0.bitmaskValue == bitmaskValue } if let index = index { return T.autoBitmaskValues[index] } else { preconditionFailure("Attempted to call autoBitmaskValueFor(_:) with a non-bitmaskable value of T.") } } }
mit
275751fa18f7bc6359c9ad11224c57d3
26.37037
116
0.692828
4.128492
false
false
false
false
ignacio-chiazzo/ARKit
ARKitProject/UI Elements/FocusSquare.swift
1
15593
import Foundation import ARKit class FocusSquare: SCNNode { // Original size of the focus square in m. private let focusSquareSize: Float = 0.17 // Thickness of the focus square lines in m. private let focusSquareThickness: Float = 0.018 // Scale factor for the focus square when it is closed, w.r.t. the original size. private let scaleForClosedSquare: Float = 0.97 // Side length of the focus square segments when it is open (w.r.t. to a 1x1 square). private let sideLengthForOpenSquareSegments: CGFloat = 0.2 // Duration of the open/close animation private let animationDuration = 0.7 // Color of the focus square private let focusSquareColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // base yellow private let focusSquareColorLight = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1) // light yellow // For scale adapdation based on the camera distance, see the `scaleBasedOnDistance(camera:)` method. ///////////////////////////////////////////////// var lastPositionOnPlane: SCNVector3? var lastPosition: SCNVector3? override init() { super.init() self.opacity = 0.0 self.addChildNode(focusSquareNode()) open() lastPositionOnPlane = nil lastPosition = nil recentFocusSquarePositions = [] anchorsOfVisitedPlanes = [] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(for position: SCNVector3, planeAnchor: ARPlaneAnchor?, camera: ARCamera?) { lastPosition = position if let anchor = planeAnchor { close(flash: !anchorsOfVisitedPlanes.contains(anchor)) lastPositionOnPlane = position anchorsOfVisitedPlanes.insert(anchor) } else { open() } updateTransform(for: position, camera: camera) } func hide() { if self.opacity == 1.0 { self.runAction(SCNAction.fadeOut(duration: 0.5)) } } func unhide() { if self.opacity == 0.0 { self.runAction(SCNAction.fadeIn(duration: 0.5)) } } // MARK: - Private private var isOpen = false // use average of recent positions to avoid jitter private var recentFocusSquarePositions = [SCNVector3]() private var anchorsOfVisitedPlanes: Set<ARAnchor> = [] private func updateTransform(for position: SCNVector3, camera: ARCamera?) { recentFocusSquarePositions.append(position) // remove anything older than the last 8 recentFocusSquarePositions.keepLast(8) // move to average of recent positions to avoid jitter if let average = recentFocusSquarePositions.average { self.position = average self.setUniformScale(scaleBasedOnDistance(camera: camera)) } // Correct y rotation of camera square if let camera = camera { let tilt = abs(camera.eulerAngles.x) let threshold1: Float = Float.pi / 2 * 0.65 let threshold2: Float = Float.pi / 2 * 0.75 let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x) var angle: Float = 0 switch tilt { case 0..<threshold1: angle = camera.eulerAngles.y case threshold1..<threshold2: let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1)) let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw) angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange default: angle = yaw } self.rotation = SCNVector4Make(0, 1, 0, angle) } } private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float { // Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal var normalized = angle while abs(normalized - ref) > Float.pi / 4 { if angle > ref { normalized -= Float.pi / 2 } else { normalized += Float.pi / 2 } } return normalized } private func scaleBasedOnDistance(camera: ARCamera?) -> Float { if let camera = camera { let distanceFromCamera = (self.worldPosition - SCNVector3.positionFromTransform(camera.transform)).length() // This function reduces size changes of the focus square based on the distance by scaling it up if it far away, // and down if it is very close. // The values are adjusted such that scale will be 1 in 0.7 m distance (estimated distance when looking at a table), // and 1.2 in 1.5 m distance (estimated distance when looking at the floor). let newScale = distanceFromCamera < 0.7 ? (distanceFromCamera / 0.7) : (0.25 * distanceFromCamera + 0.825) return newScale } return 1.0 } private func pulseAction() -> SCNAction { let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5) let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5) pulseOutAction.timingMode = .easeInEaseOut pulseInAction.timingMode = .easeInEaseOut return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction])) } private func stopPulsing(for node: SCNNode?) { node?.removeAction(forKey: "pulse") node?.opacity = 1.0 } private var isAnimating: Bool = false private func open() { if isOpen || isAnimating { return } // Open animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) SCNTransaction.animationDuration = animationDuration / 4 entireSquare?.opacity = 1.0 self.segments?[0].open(direction: .left, newLength: sideLengthForOpenSquareSegments) self.segments?[1].open(direction: .right, newLength: sideLengthForOpenSquareSegments) self.segments?[2].open(direction: .up, newLength: sideLengthForOpenSquareSegments) self.segments?[3].open(direction: .up, newLength: sideLengthForOpenSquareSegments) self.segments?[4].open(direction: .down, newLength: sideLengthForOpenSquareSegments) self.segments?[5].open(direction: .down, newLength: sideLengthForOpenSquareSegments) self.segments?[6].open(direction: .left, newLength: sideLengthForOpenSquareSegments) self.segments?[7].open(direction: .right, newLength: sideLengthForOpenSquareSegments) SCNTransaction.completionBlock = { self.entireSquare?.runAction(self.pulseAction(), forKey: "pulse") } SCNTransaction.commit() // Scale/bounce animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) SCNTransaction.animationDuration = animationDuration / 4 entireSquare?.setUniformScale(focusSquareSize) SCNTransaction.commit() isOpen = true } private func close(flash: Bool = false) { if !isOpen || isAnimating { return } isAnimating = true stopPulsing(for: entireSquare) // Close animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) SCNTransaction.animationDuration = self.animationDuration / 2 entireSquare?.opacity = 0.99 SCNTransaction.completionBlock = { SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) SCNTransaction.animationDuration = self.animationDuration / 4 self.segments?[0].close(direction: .right) self.segments?[1].close(direction: .left) self.segments?[2].close(direction: .down) self.segments?[3].close(direction: .down) self.segments?[4].close(direction: .up) self.segments?[5].close(direction: .up) self.segments?[6].close(direction: .right) self.segments?[7].close(direction: .left) SCNTransaction.completionBlock = { self.isAnimating = false } SCNTransaction.commit() } SCNTransaction.commit() // Scale/bounce animation entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x") entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y") entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z") // Flash if flash { let waitAction = SCNAction.wait(duration: animationDuration * 0.75) let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: animationDuration * 0.125) let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: animationDuration * 0.125) fillPlane?.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction])) let flashSquareAction = flashAnimation(duration: animationDuration * 0.25) segments?[0].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[1].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[2].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[3].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[4].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[5].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[6].runAction(SCNAction.sequence([waitAction, flashSquareAction])) segments?[7].runAction(SCNAction.sequence([waitAction, flashSquareAction])) } isOpen = false } private func flashAnimation(duration: TimeInterval) -> SCNAction { let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in // animate color from HSB 48/100/100 to 48/30/100 and back let elapsedTimePercentage = elapsedTime / CGFloat(duration) let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3 if let material = node.geometry?.firstMaterial { material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0) } } return action } private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath) let easeOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) let easeInOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let linear = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) let fs = focusSquareSize let ts = focusSquareSize * scaleForClosedSquare let values = [fs, fs * 1.15, fs * 1.15, ts * 0.97, ts] let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00] let timingFunctions = [easeOut, linear, easeOut, easeInOut] scaleAnimation.values = values scaleAnimation.keyTimes = keyTimes scaleAnimation.timingFunctions = timingFunctions scaleAnimation.duration = animationDuration return scaleAnimation } private var segments: [FocusSquareSegment]? { guard let s1 = childNode(withName: "s1", recursively: true) as? FocusSquareSegment, let s2 = childNode(withName: "s2", recursively: true) as? FocusSquareSegment, let s3 = childNode(withName: "s3", recursively: true) as? FocusSquareSegment, let s4 = childNode(withName: "s4", recursively: true) as? FocusSquareSegment, let s5 = childNode(withName: "s5", recursively: true) as? FocusSquareSegment, let s6 = childNode(withName: "s6", recursively: true) as? FocusSquareSegment, let s7 = childNode(withName: "s7", recursively: true) as? FocusSquareSegment, let s8 = childNode(withName: "s8", recursively: true) as? FocusSquareSegment else { return nil } return [s1, s2, s3, s4, s5, s6, s7, s8] } private var fillPlane: SCNNode? { return childNode(withName: "fillPlane", recursively: true) } private var entireSquare: SCNNode? { return self.childNodes.first } private func focusSquareNode() -> SCNNode { /* The focus square consists of eight segments as follows, which can be individually animated. s1 s2 _ _ s3 | | s4 s5 | | s6 - - s7 s8 */ let sl: Float = 0.5 // segment length let st = focusSquareThickness let c: Float = focusSquareThickness / 2 // correction to align lines perfectly let s1 = FocusSquareSegment(name: "s1", width: sl, thickness: st, color: focusSquareColor) let s2 = FocusSquareSegment(name: "s2", width: sl, thickness: st, color: focusSquareColor) let s3 = FocusSquareSegment(name: "s3", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s4 = FocusSquareSegment(name: "s4", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s5 = FocusSquareSegment(name: "s5", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s6 = FocusSquareSegment(name: "s6", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s7 = FocusSquareSegment(name: "s7", width: sl, thickness: st, color: focusSquareColor) let s8 = FocusSquareSegment(name: "s8", width: sl, thickness: st, color: focusSquareColor) s1.position += SCNVector3Make(-(sl / 2 - c), -(sl - c), 0) s2.position += SCNVector3Make(sl / 2 - c, -(sl - c), 0) s3.position += SCNVector3Make(-sl, -sl / 2, 0) s4.position += SCNVector3Make(sl, -sl / 2, 0) s5.position += SCNVector3Make(-sl, sl / 2, 0) s6.position += SCNVector3Make(sl, sl / 2, 0) s7.position += SCNVector3Make(-(sl / 2 - c), sl - c, 0) s8.position += SCNVector3Make(sl / 2 - c, sl - c, 0) let fillPlane = SCNPlane(width: CGFloat(1.0 - st * 2 + c), height: CGFloat(1.0 - st * 2 + c)) let material = SCNMaterial.material(withDiffuse: focusSquareColorLight, respondsToLighting: false) fillPlane.materials = [material] let fillPlaneNode = SCNNode(geometry: fillPlane) fillPlaneNode.name = "fillPlane" fillPlaneNode.opacity = 0.0 let planeNode = SCNNode() planeNode.eulerAngles = SCNVector3Make(Float.pi / 2.0, 0, 0) // Horizontal planeNode.setUniformScale(focusSquareSize * scaleForClosedSquare) planeNode.addChildNode(s1) planeNode.addChildNode(s2) planeNode.addChildNode(s3) planeNode.addChildNode(s4) planeNode.addChildNode(s5) planeNode.addChildNode(s6) planeNode.addChildNode(s7) planeNode.addChildNode(s8) planeNode.addChildNode(fillPlaneNode) isOpen = false // Always render focus square on top planeNode.renderOnTop() return planeNode } } class FocusSquareSegment: SCNNode { enum Direction { case up case down case left case right } init(name: String, width: Float, thickness: Float, color: UIColor, vertical: Bool = false) { super.init() let material = SCNMaterial.material(withDiffuse: color, respondsToLighting: false) var plane: SCNPlane if vertical { plane = SCNPlane(width: CGFloat(thickness), height: CGFloat(width)) } else { plane = SCNPlane(width: CGFloat(width), height: CGFloat(thickness)) } plane.materials = [material] self.geometry = plane self.name = name } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func open(direction: Direction, newLength: CGFloat) { guard let p = self.geometry as? SCNPlane else { return } if direction == .left || direction == .right { p.width = newLength } else { p.height = newLength } switch direction { case .left: self.position.x -= Float(0.5 / 2 - p.width / 2) case .right: self.position.x += Float(0.5 / 2 - p.width / 2) case .up: self.position.y -= Float(0.5 / 2 - p.height / 2) case .down: self.position.y += Float(0.5 / 2 - p.height / 2) } } func close(direction: Direction) { guard let p = self.geometry as? SCNPlane else { return } var oldLength: CGFloat if direction == .left || direction == .right { oldLength = p.width p.width = 0.5 } else { oldLength = p.height p.height = 0.5 } switch direction { case .left: self.position.x -= Float(0.5 / 2 - oldLength / 2) case .right: self.position.x += Float(0.5 / 2 - oldLength / 2) case .up: self.position.y -= Float(0.5 / 2 - oldLength / 2) case .down: self.position.y += Float(0.5 / 2 - oldLength / 2) } } }
mit
94e39213bbe544d321ff6074f8e2eae7
34.519362
136
0.718335
3.708205
false
false
false
false
SwiftBond/Bond
Sources/Bond/UIKit/UICollectionView+DataSource.swift
2
12839
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 os(iOS) || os(tvOS) import UIKit import ReactiveKit extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Error == NoError { /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - createCell: A closure that creates (dequeues) cell for the given table view and configures it with the given data source at the given index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. @discardableResult public func bind(to collectionView: UICollectionView, createCell: @escaping (Element.Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell) -> Disposable { let binder = CollectionViewBinderDataSource<Element.Changeset>(createCell) return bind(to: collectionView, using: binder) } /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - binder: A `TableViewBinder` or its subclass that will manage the binding. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. @discardableResult public func bind(to collectionView: UICollectionView, using binderDataSource: CollectionViewBinderDataSource<Element.Changeset>) -> Disposable { binderDataSource.collectionView = collectionView return bind(to: collectionView) { (_, changeset) in binderDataSource.changeset = changeset.asSectionedDataSourceChangeset } } } extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Element.Changeset.Collection: QueryableSectionedDataSourceProtocol, Error == NoError { /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - cellType: A type of the cells that should display the data. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - configureCell: A closure that configures the cell with the data source item at the respective index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. /// /// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell. /// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file. @discardableResult public func bind<Cell: UICollectionViewCell>(to collectionView: UICollectionView, cellType: Cell.Type, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable { let identifier = String(describing: Cell.self) let bundle = Bundle(for: Cell.self) if let _ = bundle.path(forResource: identifier, ofType: "nib") { let nib = UINib(nibName: identifier, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: identifier) } else { collectionView.register(cellType as AnyClass, forCellWithReuseIdentifier: identifier) } return bind(to: collectionView, createCell: { (dataSource, indexPath, collectionView) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! Cell let item = dataSource.item(at: indexPath) configureCell(cell, item) return cell }) } /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - tableView: A table view that should display the data from the data source. /// - cellType: A type of the cells that should display the data. Cell type name will be used as reusable identifier and the binding will automatically dequeue cell. /// - animated: Animate partial or batched updates. Default is `true`. /// - rowAnimation: Row animation for partial or batched updates. Relevant only when `animated` is `true`. Default is `.automatic`. /// - configureCell: A closure that configures the cell with the data source item at the respective index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the table view is deallocated. /// /// Note that the cell type name will be used as a reusable identifier and the binding will automatically register and dequeue the cell. /// If there exists a nib file in the bundle with the same name as the cell type name, the framework will load the cell from the nib file. @discardableResult public func bind<Cell: UICollectionViewCell>(to collectionView: UICollectionView, cellType: Cell.Type, using binderDataSource: CollectionViewBinderDataSource<Element.Changeset>, configureCell: @escaping (Cell, Element.Changeset.Collection.Item) -> Void) -> Disposable { let identifier = String(describing: Cell.self) let bundle = Bundle(for: Cell.self) if let _ = bundle.path(forResource: identifier, ofType: "nib") { let nib = UINib(nibName: identifier, bundle: bundle) collectionView.register(nib, forCellWithReuseIdentifier: identifier) } else { collectionView.register(cellType as AnyClass, forCellWithReuseIdentifier: identifier) } binderDataSource.createCell = { (dataSource, indexPath, collectionView) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! Cell let item = dataSource.item(at: indexPath) configureCell(cell, item) return cell } return bind(to: collectionView, using: binderDataSource) } } private var CollectionViewBinderDataSourceAssociationKey = "CollectionViewBinderDataSource" open class CollectionViewBinderDataSource<Changeset: SectionedDataSourceChangeset>: NSObject, UICollectionViewDataSource { public var createCell: ((Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell)? public var changeset: Changeset? = nil { didSet { if let changeset = changeset, oldValue != nil { applyChangeset(changeset) } else { collectionView?.reloadData() ensureCollectionViewSyncsWithTheDataSource() } } } open weak var collectionView: UICollectionView? = nil { didSet { guard let collectionView = collectionView else { return } associateWithCollectionView(collectionView) } } public override init() { createCell = nil } /// - parameter createCell: A closure that creates cell for a given table view and configures it with the given data source at the given index path. public init(_ createCell: @escaping (Changeset.Collection, IndexPath, UICollectionView) -> UICollectionViewCell) { self.createCell = createCell } open func numberOfSections(in collectionView: UICollectionView) -> Int { return changeset?.collection.numberOfSections ?? 0 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return changeset?.collection.numberOfItems(inSection: section) ?? 0 } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let changeset = changeset else { fatalError() } if let createCell = createCell { return createCell(changeset.collection, indexPath, collectionView) } else { fatalError("Subclass of CollectionViewBinderDataSource should override and implement collectionView(_:cellForItemAt:) method if they do not initialize `createCell` closure.") } } open func applyChangeset(_ changeset: Changeset) { guard let collectionView = collectionView else { return } let diff = changeset.diff.asOrderedCollectionDiff.map { $0.asSectionDataIndexPath } if diff.isEmpty { collectionView.reloadData() } else if diff.count == 1 { applyChangesetDiff(diff) } else { collectionView.performBatchUpdates({ applyChangesetDiff(diff) }, completion: nil) } ensureCollectionViewSyncsWithTheDataSource() } open func applyChangesetDiff(_ diff: OrderedCollectionDiff<IndexPath>) { guard let collectionView = collectionView else { return } let insertedSections = diff.inserts.filter { $0.count == 1 }.map { $0[0] } if !insertedSections.isEmpty { collectionView.insertSections(IndexSet(insertedSections)) } let insertedItems = diff.inserts.filter { $0.count == 2 } if !insertedItems.isEmpty { collectionView.insertItems(at: insertedItems) } let deletedSections = diff.deletes.filter { $0.count == 1 }.map { $0[0] } if !deletedSections.isEmpty { collectionView.deleteSections(IndexSet(deletedSections)) } let deletedItems = diff.deletes.filter { $0.count == 2 } if !deletedItems.isEmpty { collectionView.deleteItems(at: deletedItems) } let updatedItems = diff.updates.filter { $0.count == 2 } if !updatedItems.isEmpty { collectionView.reloadItems(at: updatedItems) } let updatedSections = diff.updates.filter { $0.count == 1 }.map { $0[0] } if !updatedSections.isEmpty { collectionView.reloadSections(IndexSet(updatedSections)) } for move in diff.moves { if move.from.count == 2 && move.to.count == 2 { collectionView.moveItem(at: move.from, to: move.to) } else if move.from.count == 1 && move.to.count == 1 { collectionView.moveSection(move.from[0], toSection: move.to[0]) } } } private func ensureCollectionViewSyncsWithTheDataSource() { // Hack to immediately apply changes. Solves the crashing issue when performing updates before collection view is on screen. _ = collectionView?.numberOfSections } private func associateWithCollectionView(_ collectionView: UICollectionView) { objc_setAssociatedObject(collectionView, &CollectionViewBinderDataSourceAssociationKey, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if collectionView.reactive.hasProtocolProxy(for: UICollectionViewDataSource.self) { collectionView.reactive.dataSource.forwardTo = self } else { collectionView.dataSource = self } } } #endif
mit
97b65b6cf44ad912d44ccf11111c8cc3
52.495833
273
0.692733
5.18538
false
false
false
false
xqz001/WWDC
WWDC/AppDelegate.swift
1
3876
// // AppDelegate.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Crashlytics import Updater @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow? private var downloadListWindowController: DownloadListWindowController? private var preferencesWindowController: PreferencesWindowController? func applicationOpenUntitledFile(sender: NSApplication) -> Bool { window?.makeKeyAndOrderFront(nil) return false } func applicationDidFinishLaunching(aNotification: NSNotification) { // start checking for live event LiveEventObserver.SharedObserver().start() // check for updates checkForUpdates(nil) // Keep a reference to the main application window window = NSApplication.sharedApplication().windows.last as! NSWindow? // continue any paused downloads VideoStore.SharedStore().initialize() // initialize Crashlytics GRCrashlyticsHelper.install() // tell the user he can watch the live keynote using the app, only once if !Preferences.SharedPreferences().userKnowsLiveEventThing { tellUserAboutTheLiveEventThing() } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func checkForUpdates(sender: AnyObject?) { UDUpdater.sharedUpdater().updateAutomatically = true UDUpdater.sharedUpdater().checkForUpdatesWithCompletionHandler { newRelease in if newRelease != nil { if sender != nil { let alert = NSAlert() alert.messageText = "New version available" alert.informativeText = "Version \(newRelease.version) is now available. It will be installed automatically the next time you launch the app." alert.addButtonWithTitle("Ok") alert.runModal() } else { let notification = NSUserNotification() notification.title = "New version available" notification.informativeText = "A new version is available, relaunch the app to update" NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) } } else { if sender != nil { let alert = NSAlert() alert.messageText = "You're up to date!" alert.informativeText = "You have the newest version" alert.addButtonWithTitle("Ok") alert.runModal() } } } } @IBAction func showDownloadsWindow(sender: AnyObject?) { if downloadListWindowController == nil { downloadListWindowController = DownloadListWindowController() } downloadListWindowController?.showWindow(self) } @IBAction func showPreferencesWindow(sender: AnyObject?) { if preferencesWindowController == nil { preferencesWindowController = PreferencesWindowController() } preferencesWindowController?.showWindow(self) } private func tellUserAboutTheLiveEventThing() { let alert = NSAlert() alert.messageText = "Did you know?" alert.informativeText = "You can watch live WWDC events using this app! Just open the app while the event is live and It will start playing automatically." alert.addButtonWithTitle("Got It!") alert.runModal() Preferences.SharedPreferences().userKnowsLiveEventThing = true } }
bsd-2-clause
bc541619b7aa01ab4ba1bf16973fa63c
35.224299
163
0.627709
6.05625
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/Settings/Cells/SettingsTableViewLinkCell.swift
9
631
@objc final class SettingsTableViewLinkCell: MWMTableViewCell { @IBOutlet fileprivate weak var title: UILabel! @IBOutlet fileprivate weak var info: UILabel! @objc func config(title: String, info: String?) { backgroundColor = UIColor.white() self.title.text = title styleTitle() self.info.text = info self.info.isHidden = info == nil styleInfo() } fileprivate func styleTitle() { title.textColor = UIColor.blackPrimaryText() title.font = UIFont.regular17() } fileprivate func styleInfo() { info.textColor = UIColor.blackSecondaryText() info.font = UIFont.regular17() } }
apache-2.0
36962485101c6fb9860fe6536ee929b0
23.269231
57
0.695721
4.263514
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Foundation/Managers/SentryIntegration.swift
2
3833
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Sentry public enum SentryTag: String { case swiftData = "SwiftData" case browserDB = "BrowserDB" case notificationService = "NotificationService" case unifiedTelemetry = "UnifiedTelemetry" case general = "General" case tabManager = "TabManager" case bookmarks = "Bookmarks" } public class Sentry { public static let shared = Sentry() public static var crashedLastLaunch: Bool { return Client.shared?.crashedLastLaunch() ?? false } private let SentryDSNKey = "SentryDSN" private let SentryDeviceAppHashKey = "SentryDeviceAppHash" private let DefaultDeviceAppHash = "0000000000000000000000000000000000000000" private let DeviceAppHashLength = UInt(20) private var enabled = false private var attributes: [String: Any] = [:] public func setup(sendCrashReports: Bool) { assert(!enabled, "Sentry.setup() should only be called once") if !sendCrashReports { print("Not enabling Sentry; Not enabled by user choice") return } guard let dsn = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String, !dsn.isEmpty else { print("Not enabling Sentry; Not configured in Info.plist") return } print("Enabling Sentry crash handler") do { Client.shared = try Client(dsn: dsn) try Client.shared?.startCrashHandler() enabled = true // If we have not already for this install, generate a completely random identifier // for this device. let defaults = UserDefaults.standard if defaults.string(forKey: SentryDeviceAppHashKey) == nil { defaults.set(generateRandomBytes(DeviceAppHashLength).hexEncodedString, forKey: SentryDeviceAppHashKey) defaults.synchronize() } Client.shared?.beforeSerializeEvent = { event in event.context?.appContext?["device_app_hash"] = self.DefaultDeviceAppHash var attributes = event.extra ?? [:] attributes.merge(self.attributes, uniquingKeysWith: { (first, _) in first }) event.extra = attributes } } catch let error { print("Failed to initialize Sentry: \(error)") } } public func crash() { Client.shared?.crash() } /* This is the behaviour we want for Sentry logging .info .error .severe Debug y y y Beta y y y Relase n n y */ private func shouldNotSendEventFor(_ severity: SentrySeverity) -> Bool { return !enabled || (AppStatus.sharedInstance.isRelease() && severity != .fatal) } private func makeEvent(message: String, tag: String, severity: SentrySeverity, extra: [String: Any]?) -> Event { let event = Event(level: severity) event.message = message event.tags = ["tag": tag] if let extra = extra { event.extra = extra } return event } private func generateRandomBytes(_ len: UInt) -> Data { let len = Int(len) var data = Data(count: len) data.withUnsafeMutableBytes { (p: UnsafeMutablePointer<UInt8>) in if (SecRandomCopyBytes(kSecRandomDefault, len, p) != errSecSuccess) { fatalError("Random byte generation failed.") } } return data } }
mpl-2.0
51dd2d7c0c023e574d5c4870f32bdfba
33.223214
119
0.594573
5.063408
false
false
false
false
tbointeractive/bytes
Sources/bytes/SemanticVersion.swift
1
5352
// // SemanticVersion // bytes // // Created by Cornelius Horstmann on 11.12.16. // Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved. // import Foundation /// Represents a Version as defined at http://semver.org. /// Can parse a SemanticVersion from a string and serialize to it. /// Implements `Equatable` and `Compareable` as defined at http://semver.org. public struct SemanticVersion { public let major: Int8 public let minor: Int8 public let patch: Int8 /// All additional prerelease identifiers. public let prereleaseIdentifiers: [String] /// Initializes a new SemanticVersion with major, minor and patch versions aswell as additional prerelease idenfifiers. /// /// - Parameters: /// - major: The major version. /// - minor: The minor version. Default = 0 /// - patch: The patch version. Default = 0 /// - prereleaseIdentifiers: All aditional prereleaseIdentifiers. Default = none. public init(major: Int8, minor: Int8?, patch: Int8?, prereleaseIdentifiers: [String] = []) { self.major = major self.minor = minor ?? 0 self.patch = patch ?? 0 self.prereleaseIdentifiers = prereleaseIdentifiers } /// Initializes a new SemanticVersion with a string. Valid, parseable strings are defined at http://semver.org /// Non-defined minor and patch versions are defaulting to 0. /// /// - Parameters: /// - string: The string to parse. public init?(_ string: String) { let basic: [String] = string.trimmingCharacters(in: .whitespaces).components(separatedBy: "-") let components = basic[0].components(separatedBy: ".") guard let major = Int8(components[0]) else { return nil } let minor = components.count > 1 ? Int8(components[1]) : nil let patch = components.count > 2 ? Int8(components[2]) : nil let prereleaseIdentifiers = basic.count > 1 ? basic[1].components(separatedBy: ".") : [] self.init(major: major, minor: minor, patch: patch, prereleaseIdentifiers: prereleaseIdentifiers) } } extension SemanticVersion: CustomStringConvertible { /// Returns the version as a string. Will always contain minor and major, even if they are zero. /// Will not contain a hyphen if there are no prereleaseIdentifiers. public var description: String { get { guard prereleaseIdentifiers.count > 0 else { return "\(major).\(minor).\(patch)" } return "\(major).\(minor).\(patch)-\(prereleaseIdentifiers.joined(separator: "."))" } } } extension SemanticVersion: Equatable { public static func ==(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool { return lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch && lhs.prereleaseIdentifiers == rhs.prereleaseIdentifiers } } extension SemanticVersion: Comparable { public static func <(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool { if lhs == rhs { return false } if lhs.major > rhs.major { return false } if lhs.major == rhs.major && lhs.minor > rhs.minor { return false } if lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch > rhs.patch { return false } if lhs.prereleaseIdentifiers.count == 0 && rhs.prereleaseIdentifiers.count > 0 { return false } if rhs.prereleaseIdentifiers.count == 0 && lhs.prereleaseIdentifiers.count > 0 { return true } for (index,label) in lhs.prereleaseIdentifiers.enumerated() { guard rhs.prereleaseIdentifiers.count > index else { // A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal. return false } let otherLabel = rhs.prereleaseIdentifiers[index] if let labelInt = Int8(label) { if let otherLabelInt = Int8(otherLabel) { if labelInt < otherLabelInt { // identifiers consisting of only digits are compared numerically return true } else if labelInt > otherLabelInt { return false } } else { // Numeric identifiers always have lower precedence than non-numeric identifiers. return true } } else { if Int8(otherLabel) != nil { return false } else { if label > otherLabel { // identifiers with letters or hyphens are compared lexically in ASCII sort order. return false } else if label < otherLabel { return true } } } } return true } public static func >(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool { return rhs < lhs } public static func <=(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool { return lhs < rhs || lhs == rhs } public static func >=(lhs: SemanticVersion, rhs: SemanticVersion) -> Bool { return lhs > rhs || lhs == rhs } }
mit
46896adc9e0e30da6df7edd4003d6fce
41.133858
147
0.59615
4.940905
false
false
false
false
Hexaville/HexavilleAuth
Sources/HexavilleAuthExample/main.swift
1
3154
// // main.swift // HexavilleAuth // // Created by Yuki Takei on 2017/05/30. // // import Foundation import HexavilleAuth import HexavilleFramework let app = HexavilleFramework() let sessionMiddleware = SessionMiddleware( cookieAttribute: CookieAttribute( expiration: 3600, httpOnly: true, secure: false ), store: SessionMemoryStore() ) app.use(sessionMiddleware) var auth = HexavilleAuth() let APP_URL = ProcessInfo.processInfo.environment["APP_URL"] ?? "http://localhsot:3000" let facebookProvider = FacebookAuthorizationProvider( path: "/auth/facebook", consumerKey: ProcessInfo.processInfo.environment["FACEBOOK_APP_ID"] ?? "", consumerSecret: ProcessInfo.processInfo.environment["FACEBOOK_APP_SECRET"] ?? "", callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/facebook/callback"), scope: "public_profile,email" ) { credential, user, request, context in return Response(body: "\(user)") } let githubProvider = GithubAuthorizationProvider( path: "/auth/github", consumerKey: ProcessInfo.processInfo.environment["GITHUB_APP_ID"] ?? "", consumerSecret: ProcessInfo.processInfo.environment["GITHUB_APP_SECRET"] ?? "", callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/github/callback"), scope: "user,repo" ) { credential, user, request, context in return Response(body: "\(user)") } let googleProvider = GoogleAuthorizationProvider( path: "/auth/google", consumerKey: ProcessInfo.processInfo.environment["GOOGLE_APP_ID"] ?? "", consumerSecret: ProcessInfo.processInfo.environment["GOOGLE_APP_SECRET"] ?? "", callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/google/callback"), scope: "https://www.googleapis.com/auth/drive" ) { credential, user, request, context in return Response(body: "\(credential)") } let instagramProvider = InstagramAuthorizationProvider( path: "/auth/instagram", consumerKey: ProcessInfo.processInfo.environment["INSTAGRAM_APP_ID"] ?? "", consumerSecret: ProcessInfo.processInfo.environment["INSTAGRAM_APP_SECRET"] ?? "", callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/instagram/callback"), scope: "basic" ) { credential, user, request, context in return Response(body: "\(credential)") } let twitterProvider = TwitterAuthorizationProvider( path: "/auth/twitter", consumerKey: ProcessInfo.processInfo.environment["TWITTER_APP_ID"] ?? "", consumerSecret: ProcessInfo.processInfo.environment["TWITTER_APP_SECRET"] ?? "", callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/twitter/callback"), scope: "" ) { credential, user, request, context in return Response(body: "\(user)") } auth.add(facebookProvider) auth.add(githubProvider) auth.add(googleProvider) auth.add(instagramProvider) auth.add(twitterProvider) app.use(HexavilleAuth.AuthenticationMiddleware()) app.use(auth) var router = Router() router.use(.GET, "/") { req, context in return Response(body: "Welcome to Hexaville Auth") } app.use(router) app.catch { error in print(error) return Response(status: .badRequest, body: "\(error)") } try app.run()
mit
b238580aafceeacd698cf965553e8a2d
29.621359
87
0.71338
3.992405
false
false
false
false
manish-1988/MPAudioRecorder
AudioFunctions/MPAudioRecorder/MPAudioRecorder.swift
1
7402
// // MPAudioRecorder.swift // AudioFunctions // // Created by MANISH_iOS on 28/06/17. // Copyright © 2017 iDevelopers. All rights reserved. // //MARK:- Protocol /// This is a mandatory protocol you should implement @objc protocol MPAudioRecorderDelegate { func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) @objc optional func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) @objc optional func audioRecorderBeginInterruption(_ recorder: AVAudioRecorder) @objc optional func audioRecorderEndInterruption(_ recorder: AVAudioRecorder, withOptions flags: Int) /// This will invoke after audio session permission request response comes. /// /// - Parameter granted: Granted will be true if the permission is granted else it will be false. @objc optional func audioSessionPermission(granted: Bool) /// This function will be called if there is a failure /// /// - Parameter errorMessage: Error message func audioRecorderFailed(errorMessage: String) } import UIKit import AVFoundation //MARK:- Class MPAudioRecorder /// This class is responsible for recording. class MPAudioRecorder: NSObject { /// AVAudio session private var recordingSession : AVAudioSession! /// AVAudio recorder private var audioRecorder : AVAudioRecorder! /// Settings, audio settings for a recorded audio public var audioSettings : [String : Int]? /// File name, Name of the audio file with which user wants to save it public var audioFileName: String? /// Custom url if any user wants to save the recorded Audio file at specific location public var customPath: String? /// If user wants the recorded audio filed to be saved to the iPhone's library public var shouldSaveToLibrary: Bool = false /// If user want delegates methods to be implemented in their class public var delegateMPAR: MPAudioRecorderDelegate? override init() { super.init() initialiseRecordingSession() } //MARK:- Custom Functions /// This function will start the audio recording, If Audio File name & destination URL is not provided it will take the default values public func startAudioRecording() { if recordingSession == nil { initialiseRecordingSession() }else { unowned let unownedSelf = self // To handle unseen nil of class settingUpRecorder(completionHandler: { (setupComplete) in if setupComplete == true { do { try unownedSelf.recordingSession.setActive(true) unownedSelf.audioRecorder.record() // Main } catch { if unownedSelf.delegateMPAR != nil { unownedSelf.delegateMPAR?.audioRecorderFailed(errorMessage: "Unable to start the recording") unownedSelf.clearAudioRecorder() } } } }) } } /// This function will stop the audio recording public func stopAudioRecording() { clearAudioRecorder() } //MARK:- Private Functions private func clearAudioRecorder() { if audioRecorder != nil { if audioRecorder.isRecording == true { audioRecorder.stop() } audioRecorder = nil } } private func initialiseRecordingSession() { if recordingSession == nil { unowned let unownedSelf = self // Unowned self MPAudioSessionConfig.shared.initialiseRecordingSession(completionHandlerWithGrantPermission: { (isGranted, mSession) in if isGranted == true, mSession != nil { unownedSelf.recordingSession = mSession if unownedSelf.delegateMPAR != nil { unownedSelf.delegateMPAR?.audioSessionPermission!(granted: true) }else { unownedSelf.delegateMPAR?.audioSessionPermission!(granted: false) } } }) } } /// Put audio settings, configure AVAudioRecorder, destination file path private func settingUpRecorder(completionHandler :@escaping (_ success : Bool) -> Void) { do // Setting up the recorder { audioRecorder = try AVAudioRecorder(url: MPAudioSessionConfig.getDirectoryURLForFileName(fName: audioFileName != nil ? audioFileName! : "recordedAudioFile")!, settings: audioSettings == nil ? MPAudioSessionConfig.getDefaultAudioSettings() : audioSettings!) audioRecorder.delegate = self audioRecorder.prepareToRecord() completionHandler(true) } catch { delegateMPAR?.audioRecorderFailed(errorMessage: "Unable to initialise AVAudioRecorder") clearAudioRecorder() completionHandler(false) } } } extension MPAudioRecorder: AVAudioRecorderDelegate { /* audioRecorderDidFinishRecording:successfully: is called when a recording has been finished or stopped. This method is NOT called if the recorder is stopped due to an interruption. */ func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if delegateMPAR != nil { delegateMPAR?.audioRecorderDidFinishRecording(recorder, successfully: flag) } stopAudioRecording() // Clear recording } /* if an error occurs while encoding it will be reported to the delegate. */ func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { if delegateMPAR != nil { delegateMPAR?.audioRecorderEncodeErrorDidOccur!(recorder, error: error) delegateMPAR?.audioRecorderFailed(errorMessage: (error?.localizedDescription)!) } stopAudioRecording() // Clear recording } /* AVAudioRecorder INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */ /* audioRecorderBeginInterruption: is called when the audio session has been interrupted while the recorder was recording. The recorded file will be closed. */ func audioRecorderBeginInterruption(_ recorder: AVAudioRecorder) { if delegateMPAR != nil { delegateMPAR?.audioRecorderBeginInterruption!(recorder) } } /* audioRecorderEndInterruption:withOptions: is called when the audio session interruption has ended and this recorder had been interrupted while recording. */ /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */ func audioRecorderEndInterruption(_ recorder: AVAudioRecorder, withOptions flags: Int) { if delegateMPAR != nil { delegateMPAR?.audioRecorderEndInterruption!(recorder, withOptions: flags) } } }
mit
4da1ac4243f1c9628abd5ae2f6c23295
35.820896
189
0.622213
6.076355
false
false
false
false
wtrumler/FluentSwiftAssertions
FluentSwiftAssertions/ArrayExtension.swift
1
1518
// // ArrayExtension.swift // FluentSwiftAssertions // // Created by Wolfgang Trumler on 13.05.17. // Copyright © 2017 Wolfgang Trumler. All rights reserved. // import Foundation import XCTest extension Array where Element: Equatable { public var should : Array { return self } public func beEqualTo( _ expression2: @autoclosure () throws -> Array<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> Array<Element>, _ exp2: @autoclosure () throws -> Array<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual) { assertionFunction(self, expression2, message, file, line) } public func notBeEqualTo( _ expression2: @autoclosure () throws -> Array<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> Array<Element>, _ exp2: @autoclosure () throws -> Array<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual) { assertionFunction(self, expression2, message, file, line) } }
mit
2d457e450e7314a468a6897a5e209f74
43.617647
265
0.562953
4.846645
false
false
false
false
raphaelmor/GeoJSON
GeoJSON/Geometry/MultiPoint.swift
1
3107
// MultiPoint.swift // // The MIT License (MIT) // // Copyright (c) 2014 Raphaël Mor // // 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 final class MultiPoint : GeoJSONEncodable { /// Public points public var points: [Point] { return _points } /// Prefix used for GeoJSON Encoding public var prefix: String { return "coordinates" } /// Private points private var _points: [Point] = [] /** Designated initializer for creating a MultiPoint from a SwiftyJSON object :param: json The SwiftyJSON Object. :returns: The created MultiPoint object. */ public init?(json: JSON) { if let jsonPoints = json.array { for jsonPoint in jsonPoints { if let point = Point(json: jsonPoint) { _points.append(point) } else { return nil } } } else { return nil } } /** Designated initializer for creating a MultiPoint from [Point] :param: points The Point array. :returns: The created MultiPoint object. */ public init?(points: [Point]) { _points = points } /** Build a object that can be serialized to JSON :returns: Representation of the MultiPoint Object */ public func json() -> AnyObject { return points.map { $0.json() } } } /// Array forwarding methods public extension MultiPoint { /// number of points public var count: Int { return points.count } /// subscript to access the Nth Point public subscript(index: Int) -> Point { get { return _points[index] } set(newValue) { _points[index] = newValue } } } /// MultiPoint related methods on GeoJSON public extension GeoJSON { /// Optional MultiPoint public var multiPoint: MultiPoint? { get { switch type { case .MultiPoint: return object as? MultiPoint default: return nil } } set { _object = newValue ?? NSNull() } } /** Convenience initializer for creating a GeoJSON Object from a MultiPoint :param: multiPoint The MultiPoint object. :returns: The created GeoJSON object. */ convenience public init(multiPoint: MultiPoint) { self.init() object = multiPoint } }
mit
ba18a2de0ede096d70067242144e5d97
24.669421
81
0.706053
3.892231
false
false
false
false
nguyenantinhbk77/practice-swift
CoreMotion/Retrieving Accelerometer Data/Retrieving Accelerometer Data/ViewController.swift
2
890
// // ViewController.swift // Retrieving Accelerometer Data // // Created by Domenico on 21/05/15. // License MIT // import UIKit import CoreMotion class ViewController: UIViewController { lazy var motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() if motionManager.accelerometerAvailable{ let queue = NSOperationQueue() motionManager.startAccelerometerUpdatesToQueue(queue, withHandler: {(data: CMAccelerometerData!, error: NSError!) in println("X = \(data.acceleration.x)") println("Y = \(data.acceleration.y)") println("Z = \(data.acceleration.z)") } ) } else { println("Accelerometer is not available") } } }
mit
1d0b13ef7134ec12fcb0880613ae8f06
24.428571
78
0.549438
5.632911
false
false
false
false
Kezuino/SMPT31
NOtification/NOtification/ChatViewController.swift
1
8356
// // ChatViewController.swift // NOtification // // Created by Fhict on 18/06/15. // Copyright (c) 2015 SMPT31. All rights reserved. // import UIKit import NOKit /* Configuration for online demo server let SERVER_URL = "http://push.lightstreamer.com" let ADAPTER_SET = "DEMO" let DATA_ADAPTER = "CHAT_ROOM" */ let CHAT_SUBVIEW_TAG = 101 let TEXT_FIELD_TAG = 102 let AVERAGE_LINE_LENGTH = 40 let TOP_BORDER_HEIGHT: CGFloat = 13.0 let BOTTOM_BORDER_HEIGHT: CGFloat = 30.0 let LINE_HEIGHT: CGFloat = 20.0 let DEFAULT_CELL_HEIGHT: CGFloat = 77.0 class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate { @IBOutlet weak var chatTable: UITableView! var conversation:Conversation? var _keyboardShown = false var _snapshotEnded = false let user = User(name: "Jip") let user2 = User(name: "anonymous") var messages = [Message]() var dates = [String]() @IBOutlet var _tableView: UITableView? @IBOutlet var _textField: UITextField? ////////////////////////////////////////////////////////////////////////// // Methods of UIViewController override func viewWillAppear(animated: Bool) { // Register for keyboard notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { // Unregister for keyboard notifications while not visible NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } ////////////////////////////////////////////////////////////////////////// // Action methods ////////////////////////////////////////////////////////////////////////// // Methods of UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return conversation!.getMessages().count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let index = indexPath.row let message = conversation!.getMessages()[index] let size = count(message.body) let height = (2 + (size / 60)) * 30 return CGFloat(height) //cell!.messageTextView!.sizeThatFits(size) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("ChatCell") as? ChatCell if cell == nil { cell = ChatCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ChatCell") } let index = indexPath.row // Compose cell content let message = conversation!.getMessages()[index] if message.message != "" { cell!.messageTextView!.text = message.message tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) //let myString: NSString = message.body as NSString //let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)]) //cell!.messageTextView!.sizeThatFits(size) } if (message.timestamp != 0) { var formatter = NSDateFormatter(); formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"; let defaultTimeZoneStr = formatter.stringFromDate(message.timestamp.date); cell!.originLabel!.text = defaultTimeZoneStr } return cell! } ////////////////////////////////////////////////////////////////////////// // Methods of UITableViewDelegate func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // No selection allowed return nil } ////////////////////////////////////////////////////////////////////////// // Methods of UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { // Get the message text var message = Array(_textField!.text) var newmessage = [Character]() _textField!.text = "" if(message.count > 50) { var i = 0 while(i < message.count) { var j = 0 while(j < 50 && i < message.count) { newmessage.append(message[i]) j++ i++ } newmessage.append("\n") } } else { newmessage = message } print(String(newmessage)) let completeMessage = Message(from: user, to: user2, message: String(newmessage)) conversation?.addMessage(completeMessage) //var date = formatADate() //dates.append(date) //let amessage = Message() chatTable.reloadData() // No linefeeds allowed inside the message return false } ////////////////////////////////////////////////////////////////////////// // Keyboard hide/show notifications func keyboardWillShow(notification: NSNotification) { // Check for double invocation if _keyboardShown { return } _keyboardShown = true // Reducing size of table let baseView = self.view.viewWithTag(CHAT_SUBVIEW_TAG) let keyboardFrame = notification.userInfo![UIKeyboardFrameBeginUserInfoKey]!.CGRectValue() let keyboardDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue let visibleRows = _tableView!.indexPathsForVisibleRows() as! [NSIndexPath]? var lastIndexPath : NSIndexPath? = nil if (visibleRows != nil) && visibleRows!.count > 0 { lastIndexPath = visibleRows![visibleRows!.count-1] as NSIndexPath } UIView.animateWithDuration(keyboardDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { baseView!.frame = CGRectMake(baseView!.frame.origin.x, baseView!.frame.origin.y, baseView!.frame.size.width, baseView!.frame.size.height - keyboardFrame.size.height) }, completion: { (finished: Bool) in if lastIndexPath != nil { // Scroll down the table so that the last // visible row remains visible self._tableView!.scrollToRowAtIndexPath(lastIndexPath!, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true) } }) } func keyboardWillHide(notification: NSNotification) { // Check for double invocation if !_keyboardShown { return } _keyboardShown = false // Expanding size of table let baseView = self.view.viewWithTag(CHAT_SUBVIEW_TAG) let keyboardFrame = notification.userInfo![UIKeyboardFrameBeginUserInfoKey]!.CGRectValue() let keyboardDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue UIView.animateWithDuration(keyboardDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { baseView!.frame = CGRectMake(baseView!.frame.origin.x, baseView!.frame.origin.y, baseView!.frame.size.width, baseView!.frame.size.height + keyboardFrame.size.height) }, completion: nil) } }
mit
d7ed88988f08a44395a23942f18b8c87
32.027668
177
0.572642
5.80681
false
false
false
false
aleffert/dials-snapkit
Example/FirstViewController.swift
2
1152
// // FirstViewController.swift // Example // // Created by Akiva Leffert on 9/24/15. // Copyright © 2015 Akiva Leffert. All rights reserved. // import UIKit import SnapKit let size = 100 class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let leadingView = UIView() leadingView.backgroundColor = UIColor(red: 1.0, green: 157.0/255.0, blue: 0, alpha: 1) let trailingView = UIView() trailingView.backgroundColor = UIColor(red: 1.0, green: 157.0/255.0, blue: 0, alpha: 1) view.addSubview(leadingView) view.addSubview(trailingView) leadingView.snp_makeConstraints {make in make.width.equalTo(size) make.height.equalTo(size) make.leading.equalTo(view).offset(50) make.centerY.equalTo(view) } trailingView.snp_makeConstraints{make in make.width.equalTo(leadingView).offset(20) make.height.equalTo(leadingView) make.trailing.equalTo(view).offset(-50) make.centerY.equalTo(view) } } }
mit
0bab0cba225d530019af129e6d5fbc41
26.404762
95
0.617724
4.216117
false
false
false
false
JohnEstropia/CoreStore
Demo/Sources/Demos/Classic/ColorsDemo/Classic.ColorsDemo.DetailViewController.swift
1
11394
// // Demo // Copyright © 2020 John Rommel Estropia, Inc. All rights reserved. import CoreStore import UIKit // MARK: - Classic.ColorsDemo extension Classic.ColorsDemo { // MARK: - Classic.ColorsDemo.DetailViewController final class DetailViewController: UIViewController, ObjectObserver { /** ⭐️ Sample 1: We can normally use `ObjectPublisher` directly, which is simpler. But for this demo, we will be using `ObjectMonitor` instead because we need to keep track of which properties change to prevent our `UISlider` from stuttering. Refer to the `objectMonitor(_:didUpdateObject:changedPersistentKeys:)` implementation below. */ var palette: ObjectMonitor<Classic.ColorsDemo.Palette> { didSet { oldValue.removeObserver(self) self.startMonitoringObject() } } init(_ palette: ObjectMonitor<Classic.ColorsDemo.Palette>) { self.palette = palette super.init(nibName: nil, bundle: nil) } /** ⭐️ Sample 2: Once the views are created, we can start receiving `ObjectMonitor` updates in our `ObjectObserver` conformance methods. We typically call this at the end of `viewDidLoad`. Note that after the `addObserver` call, only succeeding updates will trigger our `ObjectObserver` methods, so to immediately display the current values, we need to initialize our views once (in this case, using `reloadPaletteInfo(_:changedKeys:)`. */ private func startMonitoringObject() { self.palette.addObserver(self) if let palette = self.palette.object { self.reloadPaletteInfo(palette, changedKeys: nil) } } /** ⭐️ Sample 3: We can end monitoring updates anytime. `removeObserver()` was called here for illustration purposes only. `ObjectMonitor`s safely remove deallocated observers automatically. */ deinit { self.palette.removeObserver(self) } /** ⭐️ Sample 4: Our `objectMonitor(_:didUpdateObject:changedPersistentKeys:)` implementation passes a `Set<KeyPathString>` to our reload method. We can then inspect which values were triggered by each `UISlider`, so we can avoid double-updates that can lag the `UISlider` dragging. */ func reloadPaletteInfo( _ palette: Classic.ColorsDemo.Palette, changedKeys: Set<KeyPathString>? ) { self.view.backgroundColor = palette.color self.hueLabel.text = "H: \(Int(palette.hue * 359))°" self.saturationLabel.text = "S: \(Int(palette.saturation * 100))%" self.brightnessLabel.text = "B: \(Int(palette.brightness * 100))%" if changedKeys == nil || changedKeys?.contains(String(keyPath: \Classic.ColorsDemo.Palette.hue)) == true { self.hueSlider.value = Float(palette.hue) } if changedKeys == nil || changedKeys?.contains(String(keyPath: \Classic.ColorsDemo.Palette.saturation)) == true { self.saturationSlider.value = palette.saturation } if changedKeys == nil || changedKeys?.contains(String(keyPath: \Classic.ColorsDemo.Palette.brightness)) == true { self.brightnessSlider.value = palette.brightness } } // MARK: ObjectObserver func objectMonitor( _ monitor: ObjectMonitor<Classic.ColorsDemo.Palette>, didUpdateObject object: Classic.ColorsDemo.Palette, changedPersistentKeys: Set<KeyPathString> ) { self.reloadPaletteInfo(object, changedKeys: changedPersistentKeys) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let view = self.view! let containerView = UIView() do { containerView.translatesAutoresizingMaskIntoConstraints = false containerView.backgroundColor = UIColor.white containerView.layer.cornerRadius = 10 containerView.layer.masksToBounds = true containerView.layer.shadowColor = UIColor(white: 0.5, alpha: 0.3).cgColor containerView.layer.shadowOffset = .init(width: 1, height: 1) containerView.layer.shadowRadius = 2 view.addSubview(containerView) } let vStackView = UIStackView() do { vStackView.translatesAutoresizingMaskIntoConstraints = false vStackView.axis = .vertical vStackView.spacing = 10 vStackView.distribution = .fill vStackView.alignment = .fill containerView.addSubview(vStackView) } let palette = self.palette.object let rows: [(label: UILabel, slider: UISlider, initialValue: Float, sliderValueChangedSelector: Selector)] = [ ( self.hueLabel, self.hueSlider, palette?.hue ?? 0, #selector(self.hueSliderValueDidChange(_:)) ), ( self.saturationLabel, self.saturationSlider, palette?.saturation ?? 0, #selector(self.saturationSliderValueDidChange(_:)) ), ( self.brightnessLabel, self.brightnessSlider, palette?.brightness ?? 0, #selector(self.brightnessSliderValueDidChange(_:)) ) ] for (label, slider, initialValue, sliderValueChangedSelector) in rows { let hStackView = UIStackView() do { hStackView.translatesAutoresizingMaskIntoConstraints = false hStackView.axis = .horizontal hStackView.spacing = 5 hStackView.distribution = .fill hStackView.alignment = .center vStackView.addArrangedSubview(hStackView) } do { label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor(white: 0, alpha: 0.8) label.textAlignment = .center hStackView.addArrangedSubview(label) } do { slider.translatesAutoresizingMaskIntoConstraints = false slider.minimumValue = 0 slider.maximumValue = 1 slider.value = initialValue slider.addTarget( self, action: sliderValueChangedSelector, for: .valueChanged ) hStackView.addArrangedSubview(slider) } } layout: do { NSLayoutConstraint.activate( [ containerView.leadingAnchor.constraint( equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10 ), containerView.bottomAnchor.constraint( equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10 ), containerView.trailingAnchor.constraint( equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10 ), vStackView.topAnchor.constraint( equalTo: containerView.topAnchor, constant: 15 ), vStackView.leadingAnchor.constraint( equalTo: containerView.leadingAnchor, constant: 15 ), vStackView.bottomAnchor.constraint( equalTo: containerView.bottomAnchor, constant: -15 ), vStackView.trailingAnchor.constraint( equalTo: containerView.trailingAnchor, constant: -15 ) ] ) NSLayoutConstraint.activate( rows.map { label, _, _, _ in label.widthAnchor.constraint(equalToConstant: 80) } ) } self.startMonitoringObject() } // MARK: Private @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } private let hueLabel: UILabel = .init() private let saturationLabel: UILabel = .init() private let brightnessLabel: UILabel = .init() private let hueSlider: UISlider = .init() private let saturationSlider: UISlider = .init() private let brightnessSlider: UISlider = .init() @objc private dynamic func hueSliderValueDidChange(_ sender: UISlider) { let value = sender.value Classic.ColorsDemo.dataStack.perform( asynchronous: { [weak self] (transaction) in let palette = transaction.edit(self?.palette.object) palette?.hue = value }, completion: { _ in } ) } @objc private dynamic func saturationSliderValueDidChange(_ sender: UISlider) { let value = sender.value Classic.ColorsDemo.dataStack.perform( asynchronous: { [weak self] (transaction) in let palette = transaction.edit(self?.palette.object) palette?.saturation = value }, completion: { _ in } ) } @objc private dynamic func brightnessSliderValueDidChange(_ sender: UISlider) { let value = sender.value Classic.ColorsDemo.dataStack.perform( asynchronous: { [weak self] (transaction) in let palette = transaction.edit(self?.palette.object) palette?.brightness = value }, completion: { _ in } ) } } }
mit
d49ae664fa6d8f1743f33cd52da51f15
38.092784
441
0.5
6.534176
false
false
false
false
jeevanRao7/Swift_Playgrounds
Swift Playgrounds/Design Patterns/Builder Pattern - Theme.playground/Contents.swift
1
688
import UIKit ///- Builder pattern : Theme builder. protocol ThemeProtocol { var backgroundColor:UIColor? { get } var textColor:UIColor? { get } } class Theme : ThemeProtocol { var backgroundColor:UIColor? var textColor:UIColor? var weight:Int? typealias buildThemeClosure = (Theme) -> Void init(build:buildThemeClosure) { build(self) } } let darkTheme = Theme(build: { $0.backgroundColor = UIColor.black $0.textColor = UIColor.white }) let lightTheme = Theme(build: { $0.backgroundColor = UIColor.white $0.textColor = UIColor.black }) ///usage in some were in your code darkTheme.textColor lightTheme.backgroundColor = .red
mit
c4d0371504d0e8c8a9ff2b2ec7d17635
19.235294
49
0.6875
3.865169
false
false
false
false
ALiOSDev/ALTableView
ALTableViewSwift/TestALTableView/TestALTableView/Orders/LoadingRetry/LoadingRetryTableViewCell.swift
1
1530
// // LoadingRetryTableViewCell.swift // BimbaYLola // // Created by lorenzo villarroel perez on 20/12/2018. // Copyright © 2018 BimbaYLola. All rights reserved. // import UIKit import ALTableView class LoadingRetryTableViewCell: UITableViewCell, ALCellProtocol { @IBOutlet weak var btShowMore: SecondaryButton! class var nib: String { return "LoadingRetryTableViewCell" } class var reuseIdentifier: String { return "LoadingRetryTableViewCellReuseIdentifier" } func cellCreated(dataObject: Any?) { btShowMore.isUserInteractionEnabled = false btShowMore.setTitle("PRODUCTS_GRID_SHOW_MORE", for: .normal) } } class SecondaryButton: UIButton { override var intrinsicContentSize: CGSize { get { let baseSize = super.intrinsicContentSize return CGSize(width: baseSize.width + titleEdgeInsets.left + titleEdgeInsets.right, height: baseSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom) } set { } } override func awakeFromNib() { super.awakeFromNib() setTitleColor(.black, for: .normal) titleLabel?.font = UIFont.systemFont(ofSize: 15.0) backgroundColor = .white layer.borderWidth = 1.0 layer.borderColor = UIColor.black.cgColor titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 16.0, bottom: 0.0, right: 16.0) } }
mit
d33b789e5480cf3a22ddd0cd3728f7da
24.915254
97
0.624591
4.704615
false
false
false
false
DanielFulton/ImageLibraryTests
ImageLibraryTests/Hayabusa.swift
1
1830
// // Hayabusa.swift // Hayabusa // // Created by Daniel Fulton on 8/8/16. // Copyright © 2016 GLS Japan. All rights reserved. // import UIKit import ImageIO import MobileCoreServices enum ImageIOError:ErrorType { case imageSourceCreationFailure case imageSourceNoImages case imageSourceIncompleteImage case imageOpCancelled case imageCreationFailure } typealias opCompletion = (image:UIImage?,error:ImageIOError?) -> Void class HayabusaOperation: NSOperation { let requestURL:NSURL let completion:opCompletion init(url:NSURL, completion:opCompletion) { self.requestURL = url self.completion = completion super.init() } override func main() { if self.cancelled { self.completion(image: nil,error: .imageOpCancelled) return } let sourceDict = [kCGImageSourceShouldCache as String:true, kCGImageSourceTypeIdentifierHint as String:kUTTypeJPEG] guard let imageSourceRef = CGImageSourceCreateWithURL(self.requestURL, sourceDict) else { self.completion(image: nil, error: .imageSourceCreationFailure) return } guard CGImageSourceGetCount(imageSourceRef) > 0 else { self.completion(image: nil, error: .imageSourceNoImages) return } let status = CGImageSourceGetStatus(imageSourceRef) guard status == CGImageSourceStatus.StatusComplete else { self.completion(image: nil, error: .imageSourceIncompleteImage) return } guard let image = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, sourceDict) else { self.completion(image: nil, error: .imageCreationFailure) return } self.completion(image: UIImage(CGImage: image), error: nil) } }
mit
7e2c4aa6ddbff4cc3fc8b38e198178e0
32.272727
123
0.676326
4.877333
false
false
false
false
nifty-swift/Nifty
Sources/Matrix.swift
2
14870
/*************************************************************************************************** * Matrix.swift * * This file defines the Matrix data structure. * * Author: Philip Erickson * Creation Date: 14 Aug 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ // FIXME: matrix initializer infers type any on mixed integer/double array... // E.g. Matrix([[1,3.5],[2,4]]) creates a Matrix<Any>. This is easily fixed by either // Matrix<Double>([[1,3.5],[2,4]]) or Matrix([[1.0,3.5],[2.0,4.0]]), but the error is kind of // cryptic since it shows up when I try to pass the matrix to something that takes Matrix<Double>... // Is there a way to get it to default to a Matrix<Double>? Maybe add overloads for Matrix<Any> to // the functions that convert all elements to Double? import Foundation /// Data structure for a 2-D, row-major order matrix. public struct Matrix<Element>: TensorProtocol { public let count: Int public var size: [Int] public var data: [Element] public var name: String? public var showName: Bool public var format: NumberFormatter /// Number of rows in the Matrix. public var rows: Int { return self.size[0] } /// Number of columns in the Matrix. public var columns: Int { return self.size[1] } //---------------------------------------------------------------------------------------------- // MARK: INITIALIZE //---------------------------------------------------------------------------------------------- public init(_ size: [Int], _ data: [Element], name: String? = nil, showName: Bool? = nil) { precondition(size.count == 2, "Matrix must be 2 dimensional") self.init(size[0], size[1], data, name: name, showName: showName) } public init(_ size: [Int], value: Element, name: String? = nil, showName: Bool? = nil) { precondition(size.count == 2, "Matrix must be 2 dimensional") self.init(size[0], size[1], value: value, name: name, showName: showName) } public init<T>(_ t: T, name: String? = nil, showName: Bool? = nil) where T : TensorProtocol, Element == T.Element { precondition(t.size.count > 0 , "Tensor must have at least 1 dimension") let size: [Int] if t.size.count == 1 { size = [1, t.size[0]] } else { size = t.size } self.init(size, t.data, name: name, showName: showName) } public init(_ rawDescription: String, name: String? = nil, showName: Bool? = nil) { // FIXME: implement fatalError("Not yet implemented") } /// Initialize a new matrix, inferring size from the provided data. /// /// - Parameters: /// - data: matrix data where each inner array represents an entire row /// - name: optional name of matrix /// - showName: determine whether to print the matrix name; defaults to true if the matrix is /// given a name, otherwise to false public init(_ data: [[Element]], name: String? = nil, showName: Bool? = nil) { let size = [data.count, data[0].count] var flatData = [Element]() for row in data { precondition(row.count == size[1], "Matrix must have same number of columns in all rows") flatData.append(contentsOf: row) } self.init(size, flatData, name: name, showName: showName) } /// Initialize a new matrix with the given dimensions and uniform value. /// /// - Parameters: /// - rows: number of rows in matrix /// - columns: number of columns in matrix /// - value: single value repeated throughout matrix /// - name: optional name of matrix /// - showName: determine whether to print the matrix name; defaults to true if the matrix is /// given a name, otherwise to false public init(_ rows: Int, _ columns: Int, value: Element, name: String? = nil, showName: Bool? = nil) { let count = rows * columns precondition(count > 0, "Matrix must have at least one element") let data = Array<Element>(repeating: value, count: count) self.init(rows, columns, data, name: name, showName: showName) } /// Initialize a new matrix with the given dimensions from a row-major ordered array. /// /// - Parameters: /// - rows: number of rows in matrix /// - columns: number of columns in a matrix /// - data: matrix data in row-major order /// - name: optional name of matrix /// - showName: determine whether to print the matrix name; defaults to true if the matrix is /// given a name, otherwise to false public init(_ rows: Int, _ columns: Int, _ data: [Element], name: String? = nil, showName: Bool? = nil) { precondition(rows >= 1 && columns >= 1, "Matrix have at least 1 row and 1 column") let count = rows * columns precondition(data.count == count, "Matrix dimensions must match data") self.size = [rows, columns] self.count = count self.data = data self.name = name if let show = showName { self.showName = show } else { self.showName = name != nil } // default display settings let fmt = NumberFormatter() fmt.numberStyle = .decimal fmt.usesSignificantDigits = true fmt.paddingCharacter = " " fmt.paddingPosition = .afterSuffix fmt.formatWidth = 8 self.format = fmt } /// Initialize a new square matrix with the given dimensions from a row-major ordered array. /// /// - Parameters: /// - side: number of elements along one side of square matrix /// - data: matrix data in row-major order /// - name: optional name of matrix /// - showName: determine whether to print the matrix name; defaults to true if the matrix is /// given a name, otherwise to false public init(_ side: Int, _ data: [Element], name: String? = nil, showName: Bool? = nil) { self.init(side, side, data, name: name, showName: showName) } /// Initialize a new square matrix with the given dimensions and uniform value. /// /// - Parameters: /// - side: number of elements along one side of square matrix /// - value: single value repeated throughout matrix /// - name: optional name of matrix /// - showName: determine whether to print the matrix name; defaults to true if the matrix is /// given a name, otherwise to false public init(_ side: Int, value: Element, name: String? = nil, showName: Bool? = nil) { self.init(side, side, value: value, name: name, showName: showName) } //---------------------------------------------------------------------------------------------- // MARK: SUBSCRIPT //---------------------------------------------------------------------------------------------- /// Access a single element of the matrix with a row-major linear index. /// /// - Parameters: /// - index: linear index into matrix /// - Returns: single value at index public subscript(_ index: Int) -> Element { get { precondition(index >= 0 && index < self.count, "Matrix subscript out of bounds") return self.data[index] } set(newVal) { precondition(index >= 0 && index < self.count, "Matrix subscript out of bounds") self.data[index] = newVal } } /// Access a single element of the matrix with a row, column subscript. /// /// - Parameters: /// - row: row subscript /// - column: column subscript /// - Returns: single value at subscript public subscript(_ row: Int, _ column: Int) -> Element { get { let index = sub2ind([row, column], size: self.size) return self.data[index] } set(newVal) { let index = sub2ind([row, column], size: self.size) self.data[index] = newVal } } /// Access a slice of the matrix with a row-major linear index range. /// /// - Parameters: /// - index: linear index range /// - Returns: new matrix composed of slice public subscript(_ index: SliceIndex) -> Matrix<Element> { get { let range = _convertToCountableClosedRange(index) // inherit name, add slice info var sliceName = self.name if sliceName != nil { sliceName = "\(_parenthesizeExpression(sliceName!))[\(index)]" } return Matrix([Array(self.data[range])], name: sliceName, showName: self.showName) } set(newVal) { let range = _convertToCountableClosedRange(index) self.data[range] = ArraySlice(newVal.data) return } } /// Access a slice of the matrix with a row, column range subscript. /// /// - Parameters: /// - rows: row range /// - columns: column range /// - Returns: new matrix composed of slice public subscript(_ rows: SliceIndex, _ columns: SliceIndex) -> Matrix<Element> { get { let ranges = _convertToCountableClosedRanges([rows, columns]) // determine size of resulting matrix slice, and start/end subscripts to read var newSize = [Int](repeating: 0, count: ranges.count) var startSub = [Int](repeating: 0, count: ranges.count) var endSub = [Int](repeating: 0, count: ranges.count) for (i, range) in ranges.enumerated() { newSize[i] = range.count startSub[i] = range.lowerBound endSub[i] = range.upperBound } // start reading from matrix, rolling over each dimension var newData = [Element]() var curSub = startSub while true { newData.append(self[curSub[0], curSub[1]]) guard let inc = _cascadeIncrementSubscript(curSub, min: startSub, max: endSub) else { break } curSub = inc } // inherit name, add slice info var sliceName = self.name if sliceName != nil { sliceName = "\(_parenthesizeExpression(sliceName!))[\(rows), \(columns)]" } return Matrix(newSize, newData, name: sliceName, showName: self.showName) } set(newVal) { let ranges = _convertToCountableClosedRanges([rows, columns]) // determine range of writes in each dimension var startSub = [Int](repeating: 0, count: ranges.count) var endSub = [Int](repeating: 0, count: ranges.count) for (i,range) in ranges.enumerated() { startSub[i] = range.lowerBound endSub[i] = range.upperBound } // ensure that new data size matches size of slice to write to let sliceSize = [endSub[0]-startSub[0]+1, endSub[1]-startSub[1]+1] precondition(sliceSize == newVal.size, "Provided data must match matrix slice size") // start writing to matrix, rolling over each dimension var newData = newVal.data var curSub = startSub for i in 0..<newData.count { self[curSub[0], curSub[1]] = newData[i] guard let inc = _cascadeIncrementSubscript(curSub, min: startSub, max: endSub) else { return } curSub = inc } } } //---------------------------------------------------------------------------------------------- // MARK: DISPLAY //---------------------------------------------------------------------------------------------- /// Return matrix contents in an easily readable grid format. /// /// - Note: The formatter associated with this matrix is used as a suggestion; elements may be /// formatted differently to improve readability. Elements that can't be displayed under the /// current formatting constraints will be displayed as '#'; non-numeric elements may be /// abbreviated by truncating and appending "...". public var description: String { // create matrix title var title = "" if self.showName { title = (self.name ?? "\(self.size[0])x\(self.size[1]) matrix") + ":\n" } // store length of widest element of each column, including additional column for row header var colWidths = Array<Int>(repeating: 0, count: self.columns+1) // create string representation of elements of each matrix row var lines = [[String]]() for r in 0..<self.rows { var curRow = [String]() // form row header let header = "R\(r):" curRow.append(header) colWidths[0] = max(colWidths[0], header.count) for c in 0..<self.columns { let el = self[r, c] let s = _formatElement(el, self.format) curRow.append(s) // advance index by 1 because element 0 is row header colWidths[c+1] = max(colWidths[c+1], s.count) } lines.append(curRow) } // pad each column in row to the max width, storing each row as single string var rowStrs = [String]() for rs in 0..<lines.count { var str = [String]() for cs in 0..<lines[0].count { let s = lines[rs][cs] assert(s.count <= colWidths[cs], "Max column width was computed incorrectly") let pad = String(repeating: " ", count: colWidths[cs]-s.count) str.append(pad+s) } rowStrs.append(str.joined(separator: " ")) } return title + rowStrs.joined(separator: "\n") } /// Return matrix representation in unformatted, comma separated list. /// /// Elements of a row are comma separated. Rows are separated by newlines. public var rawDescription: String { var s = [String]() for r in 0..<self.rows { let row = self[r, 0..<self.columns] let v = Vector(row) s.append(v.rawDescription) } return s.joined(separator: "\n") } }
apache-2.0
e0957aecfa60a8f8dd8c2166f7961d3a
34.404762
117
0.561802
4.282834
false
false
false
false
ahoppen/swift
test/SILOptimizer/definite_init_closures.swift
13
1006
// RUN: %target-swift-frontend -emit-sil %s -o /dev/null // Test boolean operators with implicit closures struct Simple { let x: Bool let y: Bool init() { x = false y = false || x } } struct NestedClosures { let x: Bool let y: Bool let z: Bool init(a: Bool) { x = false y = false z = false || (y || (x || a)) } init(b: Bool) { x = false y = false // With explicit self z = false || (self.y || (self.x || b)) } } class SimpleClass { let x: Bool let y: Bool init() { x = false y = false || x } } func forward(_ b: inout Bool) -> Bool { return b } struct InoutUse { var x: Bool var y: Bool init() { x = false y = false || forward(&x) } } protocol P { var b: Bool { get } } struct Generic<T : P> { let x: T let y: Bool init(_ t: T) { x = t y = false || x.b } } class Base { } class Derived : Base { var x: Bool var y: Bool init(_: Int) { x = false y = true || x } }
apache-2.0
5e812b8e55a8a4e12fc2d72c6a1d9877
11.120482
56
0.506958
2.890805
false
false
false
false
tehprofessor/SwiftyFORM
Source/Util/Logging.swift
1
489
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved. import Foundation // http://stackoverflow.com/questions/24114288/macros-in-swift #if DEBUG func DLog(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) { print("[\(file.lastPathComponent):\(line)] \(function) - \(message)") } #else func DLog(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) { // do nothing } #endif
mit
5e08b518622160e740ac56b4a23d2adc
31.6
109
0.660532
3.492857
false
false
false
false
ben-ng/swift
stdlib/private/StdlibUnittest/OpaqueIdentityFunctions.swift
1
2451
//===--- OpaqueIdentityFunctions.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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_silgen_name("swift_stdlib_getPointer") func _stdlib_getPointer(_ x: OpaquePointer) -> OpaquePointer public func _opaqueIdentity<T>(_ x: T) -> T { let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1) ptr.initialize(to: x) let result = UnsafeMutablePointer<T>(_stdlib_getPointer(OpaquePointer(ptr))).pointee ptr.deinitialize() ptr.deallocate(capacity: 1) return result } func _blackHolePtr<T>(_ x: UnsafePointer<T>) { _ = _stdlib_getPointer(OpaquePointer(x)) } public func _blackHole<T>(_ x: T) { var x = x _blackHolePtr(&x) } @inline(never) public func getBool(_ x: Bool) -> Bool { return _opaqueIdentity(x) } @inline(never) public func getInt8(_ x: Int8) -> Int8 { return _opaqueIdentity(x) } @inline(never) public func getInt16(_ x: Int16) -> Int16 { return _opaqueIdentity(x) } @inline(never) public func getInt32(_ x: Int32) -> Int32 { return _opaqueIdentity(x) } @inline(never) public func getInt64(_ x: Int64) -> Int64 { return _opaqueIdentity(x) } @inline(never) public func getInt(_ x: Int) -> Int { return _opaqueIdentity(x) } @inline(never) public func getUInt8(_ x: UInt8) -> UInt8 { return _opaqueIdentity(x) } @inline(never) public func getUInt16(_ x: UInt16) -> UInt16 { return _opaqueIdentity(x) } @inline(never) public func getUInt32(_ x: UInt32) -> UInt32 { return _opaqueIdentity(x) } @inline(never) public func getUInt64(_ x: UInt64) -> UInt64 { return _opaqueIdentity(x) } @inline(never) public func getUInt(_ x: UInt) -> UInt { return _opaqueIdentity(x) } @inline(never) public func getFloat32(_ x: Float32) -> Float32 { return _opaqueIdentity(x) } @inline(never) public func getFloat64(_ x: Float64) -> Float64 { return _opaqueIdentity(x) } #if arch(i386) || arch(x86_64) @inline(never) public func getFloat80(_ x: Float80) -> Float80 { return _opaqueIdentity(x) } #endif public func getPointer(_ x: OpaquePointer) -> OpaquePointer { return _opaqueIdentity(x) }
apache-2.0
2953e304d7f43fa916e86e0f35a9fe9d
28.890244
80
0.668299
3.516499
false
false
false
false
liuguya/TestKitchen_1606
TestKitchen/Pods/Kingfisher/Sources/ImageCache.swift
5
27021
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[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 os(OSX) import AppKit #else import UIKit #endif /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification" /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" private let defaultCacheName = "default" private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache." private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue." private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue." private let defaultCacheInstance = ImageCache(name: defaultCacheName) private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = dispatch_block_t /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case None, Memory, Disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher. public class ImageCache { //Memory private let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory. public var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk private let ioQueue: dispatch_queue_t private var fileManager: NSFileManager! ///The disk cache location. public let diskCachePath: String /// The longest time duration of the cache being stored in disk. Default is 1 week. public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond /// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit. public var maxDiskCacheSize: UInt = 0 private let processQueue: dispatch_queue_t /// The default cache. public class var defaultCache: ImageCache { return defaultCacheInstance } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string. - parameter path: Optional - Location of cache path on disk. If `nil` is passed (the default value), the cache folder in of your app will be used. If you want to cache some user generating images, you could pass the Documentation path here. - returns: The cache object. */ public init(name: String, path: String? = nil) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = cacheReverseDNS + name memoryCache.name = cacheName let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! diskCachePath = (dstPath as NSString).stringByAppendingPathComponent(cacheName) ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL) processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT) dispatch_sync(ioQueue, { () -> Void in self.fileManager = NSFileManager() }) #if !os(OSX) && !os(watchOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.clearMemoryCache), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.cleanExpiredDiskCache), name: UIApplicationWillTerminateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCache.backgroundCleanExpiredDiskCache), name: UIApplicationDidEnterBackgroundNotification, object: nil) #endif } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } // MARK: - Store & Remove extension ImageCache { /** Store an image to cache. It will be saved to both memory and disk. It is an async operation. - parameter image: The image to be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when store operation completes. */ public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String, toDisk: Bool = true, completionHandler: (() -> Void)? = nil) { memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if toDisk { dispatch_async(ioQueue, { let imageFormat: ImageFormat if let originalData = originalData { imageFormat = originalData.kf_imageFormat } else { imageFormat = .Unknown } let data: NSData? switch imageFormat { case .PNG: data = originalData ?? ImagePNGRepresentation(image) case .JPEG: data = originalData ?? ImageJPEGRepresentation(image, 1.0) case .GIF: data = originalData ?? ImageGIFRepresentation(image) case .Unknown: data = originalData ?? ImagePNGRepresentation(image.kf_normalizedImage()) } if let data = data { if !self.fileManager.fileExistsAtPath(self.diskCachePath) { do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil) } callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation. - parameter key: Key for the image. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ public func removeImageForKey(key: String, fromDisk: Bool = true, completionHandler: (() -> Void)? = nil) { memoryCache.removeObjectForKey(key) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if fromDisk { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.cachePathForKey(key)) } catch _ {} callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } } // MARK: - Get data from cache extension ImageCache { /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ public func retrieveImageForKey(key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? let options = options ?? KingfisherEmptyOptionsInfo if let image = self.retrieveImageInMemoryCacheForKey(key) { dispatch_async_safely_to_queue(options.callbackDispatchQueue) { () -> Void in completionHandler(image, .Memory) } } else { var sSelf: ImageCache! = self block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) { // Begin to load image from disk if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) { if options.backgroundDecode { dispatch_async(sSelf.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scaleFactor) sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil) dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in completionHandler(result, .Memory) sSelf = nil }) }) } else { sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil) dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in completionHandler(image, .Disk) sSelf = nil }) } } else { // No image found from either memory or disk dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in completionHandler(nil, .None) sSelf = nil }) } } dispatch_async(sSelf.ioQueue, block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInMemoryCacheForKey(key: String) -> Image? { return memoryCache.objectForKey(key) as? Image } /** Get an image for a key from disk. - parameter key: Key for the image. - parameter scale: The scale factor to assume when interpreting the image data. - parameter preloadAllGIFData: Whether all GIF data should be loaded. If true, you can set the loaded image to a regular UIImageView to play the GIF animation. Otherwise, you should use `AnimatedImageView` to play it. Default is `false` - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = 1.0, preloadAllGIFData: Bool = false) -> Image? { return diskImageForKey(key, scale: scale, preloadAllGIFData: preloadAllGIFData) } } // MARK: - Clear & Clean extension ImageCache { /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is could be an async or sync operation. Specify the way you want it by passing the `sync` parameter. */ public func clearDiskCache() { clearDiskCacheWithCompletionHandler(nil) } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.diskCachePath) try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let completionHander = completionHander { dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHander() }) } }) } /** Clean expired disk cache. This is an async operation. */ @objc public func cleanExpiredDiskCache() { cleanExpiredDiskCacheWithCompletionHander(nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) { // Do things in cocurrent io queue dispatch_async(ioQueue, { () -> Void in var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false) for fileURL in URLsToDelete { do { try self.fileManager.removeItemAtURL(fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue { resourceValue1, resourceValue2 -> Bool in if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate, date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate { return date1.compare(date2) == .OrderedAscending } // Not valid date information. This should not happen. Just in case. return true } for fileURL in sortedFiles { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize -= fileSize.unsignedLongValue } if diskCacheSize < targetSize { break } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map({ (url) -> String in return url.lastPathComponent! }) NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } completionHandler?() }) }) } private func travelCachedFiles(onlyForCacheSize onlyForCacheSize: Bool) -> (URLsToDelete: [NSURL], diskCacheSize: UInt, cachedFiles: [NSURL: [NSObject: AnyObject]]) { let diskCacheURL = NSURL(fileURLWithPath: diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond) var cachedFiles = [NSURL: [NSObject: AnyObject]]() var URLsToDelete = [NSURL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber { if isDirectory.boolValue { continue } } if !onlyForCacheSize { // If this file is expired, add it to URLsToDelete if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expiredDate) == expiredDate { URLsToDelete.append(fileURL) continue } } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue if !onlyForCacheSize { cachedFiles[fileURL] = resourceValues } } } catch _ { } } } return (URLsToDelete, diskCacheSize, cachedFiles) } #if !os(OSX) && !os(watchOS) /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = UIApplication.kf_sharedApplication() else { return } func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTaskWithExpirationHandler { () -> Void in endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCacheWithCompletionHander { () -> () in endBackgroundTask(&backgroundTask!) } } #endif } // MARK: - Check cache status extension ImageCache { /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Determine if a cached image exists for the given image, as keyed by the URL. It will return true if the image is found either in memory or on disk. Essentially as long as there is a cache of the image somewhere true is returned. A convenience method that decodes `isImageCachedForKey`. - parameter url: The image URL. - returns: True if the image is cached, false otherwise. */ public func cachedImageExistsforURL(url: NSURL) -> Bool { let resource = Resource(downloadURL: url) let result = isImageCachedForKey(resource.cacheKey) return result.cached } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ public func isImageCachedForKey(key: String) -> CacheCheckResult { if memoryCache.objectForKey(key) != nil { return CacheCheckResult(cached: true, cacheType: .Memory) } let filePath = cachePathForKey(key) var diskCached = false dispatch_sync(ioQueue) { () -> Void in diskCached = self.fileManager.fileExistsAtPath(filePath) } if diskCached { return CacheCheckResult(cached: true, cacheType: .Disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - returns: Corresponding hash. */ public func hashForKey(key: String) -> String { return cacheFileNameForKey(key) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())) { dispatch_async(ioQueue, { () -> Void in let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true) dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler(size: diskCacheSize) }) }) } /** Get the cache path for the key. It is useful for projects with UIWebView or anyone that needs access to the local file path. i.e. `<img src='path_for_key'>` - Note: This method does not guarantee there is an image already cached in the path. You could use `isImageCachedForKey` method to check whether the image is cached under that key. */ public func cachePathForKey(key: String) -> String { let fileName = cacheFileNameForKey(key) return (diskCachePath as NSString).stringByAppendingPathComponent(fileName) } } // MARK: - Internal Helper extension ImageCache { func diskImageForKey(key: String, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { if let data = diskImageDataForKey(key) { return Image.kf_imageWithData(data, scale: scale, preloadAllGIFData: preloadAllGIFData) } else { return nil } } func diskImageDataForKey(key: String) -> NSData? { let filePath = cachePathForKey(key) return NSData(contentsOfFile: filePath) } func cacheFileNameForKey(key: String) -> String { return key.kf_MD5 } } extension Image { var kf_imageCost: Int { return kf_images == nil ? Int(size.height * size.width * kf_scale * kf_scale) : Int(size.height * size.width * kf_scale * kf_scale) * kf_images!.count } } extension Dictionary { func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(OSX) && !os(watchOS) // MARK: - For App Extensions extension UIApplication { public static func kf_sharedApplication() -> UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard respondsToSelector(selector) else { return nil } return performSelector(selector).takeUnretainedValue() as? UIApplication } } #endif
mit
01a4652a1f9f0d8a29117b81f4aaa890
40.506912
337
0.608527
5.480933
false
false
false
false
tkremenek/swift
test/refactoring/ConvertAsync/path_classification.swift
1
8533
// RUN: %empty-directory(%t) func simpleWithError(completion: (String?, Error?) -> Void) {} func simpleWithError() async throws -> String {} func testPathClassification() async throws { // Both of these test cases should produce the same refactoring. // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION %s simpleWithError { str, err in if err == nil { print("a") } else if .random() { print("b") } else { print("c") } if err != nil { print("d") } else if .random() { print("e") } else { print("f") } } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION %s simpleWithError { str, err in if let str = str { print("a") } else if .random() { print("b") } else { print("c") } if str == nil { print("d") } else if .random() { print("e") } else { print("f") } } // ELSE-IF-CLASSIFICATION: do { // ELSE-IF-CLASSIFICATION-NEXT: let str = try await simpleWithError() // ELSE-IF-CLASSIFICATION-NEXT: print("a") // ELSE-IF-CLASSIFICATION-NEXT: if .random() { // ELSE-IF-CLASSIFICATION-NEXT: print("e") // ELSE-IF-CLASSIFICATION-NEXT: } else { // ELSE-IF-CLASSIFICATION-NEXT: print("f") // ELSE-IF-CLASSIFICATION-NEXT: } // ELSE-IF-CLASSIFICATION-NEXT: } catch let err { // ELSE-IF-CLASSIFICATION-NEXT: if .random() { // ELSE-IF-CLASSIFICATION-NEXT: print("b") // ELSE-IF-CLASSIFICATION-NEXT: } else { // ELSE-IF-CLASSIFICATION-NEXT: print("c") // ELSE-IF-CLASSIFICATION-NEXT: } // ELSE-IF-CLASSIFICATION-NEXT: print("d") // ELSE-IF-CLASSIFICATION-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION2 %s simpleWithError { str, err in if err == nil { print("a") } else if .random() { print("b") } if .random() { print("c") } if err != nil, .random() { print("d") } } // Make sure the classification of 'b' into the error block doesn't affect the // handling of 'c'. // ELSE-IF-CLASSIFICATION2: do { // ELSE-IF-CLASSIFICATION2-NEXT: let str = try await simpleWithError() // ELSE-IF-CLASSIFICATION2-NEXT: print("a") // ELSE-IF-CLASSIFICATION2-NEXT: if .random() { // ELSE-IF-CLASSIFICATION2-NEXT: print("c") // ELSE-IF-CLASSIFICATION2-NEXT: } // ELSE-IF-CLASSIFICATION2-NEXT: } catch let err { // ELSE-IF-CLASSIFICATION2-NEXT: if .random() { // ELSE-IF-CLASSIFICATION2-NEXT: print("b") // ELSE-IF-CLASSIFICATION2-NEXT: } // ELSE-IF-CLASSIFICATION2-NEXT: if <#err#> != nil, .random() { // ELSE-IF-CLASSIFICATION2-NEXT: print("d") // ELSE-IF-CLASSIFICATION2-NEXT: } // ELSE-IF-CLASSIFICATION2-NEXT: } // FIXME: This case is a little tricky: Being in the else block of 'err == nil' // should allow us to place 'if let str = str' in the failure block. However, this // is a success condition, so we still place it in the success block. Really what // we need to do here is check to see if simpleWithError has an existing async // alternative that still returns optional success values, and allow success // classification in that case. Otherwise, we'd probably be better off leaving // the condition unhandled, as it's not clear what the user is doing. // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION3 %s simpleWithError { str, err in if err == nil { print("a") } else if let str = str { print("b") } else { print("c") } } // ELSE-IF-CLASSIFICATION3: do { // ELSE-IF-CLASSIFICATION3-NEXT: let str = try await simpleWithError() // ELSE-IF-CLASSIFICATION3-NEXT: print("a") // ELSE-IF-CLASSIFICATION3-NEXT: print("b") // ELSE-IF-CLASSIFICATION3-NEXT: } catch let err { // ELSE-IF-CLASSIFICATION3-NEXT: print("c") // ELSE-IF-CLASSIFICATION3-NEXT: } // FIXME: Similar to the case above. // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION4 %s simpleWithError { str, err in if err == nil { print("a") } else if let str = str { print("b") } else if .random() { print("c") } else { print("d") } } // ELSE-IF-CLASSIFICATION4: do { // ELSE-IF-CLASSIFICATION4-NEXT: let str = try await simpleWithError() // ELSE-IF-CLASSIFICATION4-NEXT: print("a") // ELSE-IF-CLASSIFICATION4-NEXT: print("b") // ELSE-IF-CLASSIFICATION4-NEXT: } catch let err { // ELSE-IF-CLASSIFICATION4-NEXT: if .random() { // ELSE-IF-CLASSIFICATION4-NEXT: print("c") // ELSE-IF-CLASSIFICATION4-NEXT: } else { // ELSE-IF-CLASSIFICATION4-NEXT: print("d") // ELSE-IF-CLASSIFICATION4-NEXT: } // ELSE-IF-CLASSIFICATION4-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ELSE-IF-CLASSIFICATION5 %s simpleWithError { str, err in if let err = err { print("a") } else if let str = str { print("b") return } else if .random() { print("c") } else { print("d") } } // ELSE-IF-CLASSIFICATION5: do { // ELSE-IF-CLASSIFICATION5-NEXT: let str = try await simpleWithError() // ELSE-IF-CLASSIFICATION5-NEXT: print("b") // ELSE-IF-CLASSIFICATION5-NEXT: } catch let err { // ELSE-IF-CLASSIFICATION5-NEXT: print("a") // ELSE-IF-CLASSIFICATION5-NEXT: if .random() { // ELSE-IF-CLASSIFICATION5-NEXT: print("c") // ELSE-IF-CLASSIFICATION5-NEXT: } else { // ELSE-IF-CLASSIFICATION5-NEXT: print("d") // ELSE-IF-CLASSIFICATION5-NEXT: } // ELSE-IF-CLASSIFICATION5-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=IF-LET-RETURN-CLASSIFICATION %s simpleWithError { str, err in if let str = str { print("a") return } if .random(), let err = err { print("b") } else { print("c") } } // IF-LET-RETURN-CLASSIFICATION: do { // IF-LET-RETURN-CLASSIFICATION-NEXT: let str = try await simpleWithError() // IF-LET-RETURN-CLASSIFICATION-NEXT: print("a") // IF-LET-RETURN-CLASSIFICATION-NEXT: } catch let err { // IF-LET-RETURN-CLASSIFICATION-NEXT: if .random(), let err = <#err#> { // IF-LET-RETURN-CLASSIFICATION-NEXT: print("b") // IF-LET-RETURN-CLASSIFICATION-NEXT: } else { // IF-LET-RETURN-CLASSIFICATION-NEXT: print("c") // IF-LET-RETURN-CLASSIFICATION-NEXT: } // IF-LET-RETURN-CLASSIFICATION-NEXT: } // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=GUARD-CLASSIFICATION %s simpleWithError { str, err in guard let str = str else { print("a") return } guard err == nil, .random() else { print("b") return } print("c") } // GUARD-CLASSIFICATION: do { // GUARD-CLASSIFICATION-NEXT: let str = try await simpleWithError() // GUARD-CLASSIFICATION-NEXT: guard <#err#> == nil, .random() else { // GUARD-CLASSIFICATION-NEXT: print("b") // GUARD-CLASSIFICATION-NEXT: <#return#> // GUARD-CLASSIFICATION-NEXT: } // GUARD-CLASSIFICATION-NEXT: print("c") // GUARD-CLASSIFICATION-NEXT: } catch let err { // GUARD-CLASSIFICATION-NEXT: print("a") // GUARD-CLASSIFICATION-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=SILLY-CLASSIFICATION %s simpleWithError { str, err in guard let str = str else { return } guard let err = err else { return } print("urr") } // In this case we just take whichever guard is last. // SILLY-CLASSIFICATION: do { // SILLY-CLASSIFICATION-NEXT: let str = try await simpleWithError() // SILLY-CLASSIFICATION-NEXT: } catch let err { // SILLY-CLASSIFICATION-NEXT: print("urr") // SILLY-CLASSIFICATION-NEXT: } }
apache-2.0
7f94d78e1534f930ff38a1651228bec8
35.465812
171
0.625571
3.447677
false
false
false
false
Draveness/RbSwift
Sources/Dir.swift
1
9972
// // Dir.swift // RbSwift // // Created by draveness on 10/04/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation public class Dir: CustomStringConvertible { private var _dir: UnsafeMutablePointer<DIR>? /// Returns the path parameter passed to dir’s constructor. public let path: String /// Returns the file descriptor used in dir. /// This method uses `dirfd()` function defined by POSIX 2008. public var fileno: Int { return dirfd(_dir).to_i } /// Returns the current position in dir. See also `Dir#seek(pos:)`. public var pos: Int { get { return telldir(_dir) } set { seek(newValue) } } /// Returns the current position in dir. public var tell: Int { return pos } /// Returns the path parameter passed to dir’s constructor. public var to_path: String { return path } /// Return a string describing this Dir object. public var inspect: String { return path } /// Return a string describing this Dir object. public var description: String { return path } /// Returns a new directory object for the named directory. public init?(_ path: String) { self.path = path guard let dir = opendir(path) else { return nil } self._dir = dir } /// Returns a new directory object for the named directory. /// /// - Parameter path: A directory path. /// - Returns: A new `Dir` object or nil. public static func new(_ path: String) -> Dir? { return Dir(path) } /// Returns a new directory object for the named directory. /// /// - Parameter path: A directory path. /// - Returns: A new `Dir` object or nil. public static func open(_ path: String) -> Dir? { return Dir(path) } /// Returns the path to the current working directory of this process as a string. public static var getwd: String { return FileManager.default.currentDirectoryPath } /// Returns the path to the current working directory of this process as a string. /// An alias to `Dir#getwd` var. public static var pwd: String { return getwd } // public static func glob(_ pattern: String) -> [String] { // return [] // } /// Returns the home directory of the current user or the named user if given. /// /// Dir.home #=> "/Users/username" /// public static var home: String { return NSHomeDirectory() } /// Error throws when user doesn't exists. /// /// - notExists: User doesn't exists public enum HomeDirectory: Error { case notExists } /// Returns the home directory of the current user or the named user if given. /// /// Dir.home() #=> "/Users/username" /// Dir.home("user") #=> "/user" /// /// - Parameter path: The name of user. /// - Returns: Home directory. /// - Throws: HomeDirectory.notExists if user doesn't exist. public static func home(_ user: String? = nil) throws -> String { if let home = NSHomeDirectoryForUser(user) { return home } throw HomeDirectory.notExists } /// Changes the current working directory of the process to the given string. /// /// Dir.chdir("/var/spool/mail") /// Dir.pwd #=> "/var/spool/mail" /// /// - Parameter path: A new current working directory. /// - Returns: A bool indicates the result of `Dir#chdir(path:)` @discardableResult public static func chdir(_ path: String = "~") -> Bool { return FileManager.default.changeCurrentDirectoryPath(path) } /// Changes this process’s idea of the file system root. /// /// - Parameter path: A directory path. /// - Returns: A bool value indicates the result of `Darwin.chroot` /// - SeeAlso: `Darwin.chroot`. @discardableResult public static func chroot(_ path: String) -> Bool { return Darwin.chroot(path) == 0 } /// Changes the current working directory of the process to the given string. /// Block is passed the name of the new current directory, and the block /// is executed with that as the current directory. The original working directory /// is restored when the block exits. The return value of chdir is the value of the block. /// /// Dir.pwd #=> "/work" /// let value = Dir.chdir("/var") { /// Dir.pwd #=> "/var" /// return 1 /// } /// Dir.pwd #=> "/work" /// value #=> 1 /// /// - Parameters: /// - path: A new current working directory. /// - closure: A block executed in target directory. /// - Returns: The value of the closure. @discardableResult public static func chdir<T>(_ path: String = "~", closure: (() -> T)) -> T { let pwd = Dir.pwd Dir.chdir(path) let result = closure() Dir.chdir(pwd) return result } /// Makes a new directory named by string, with permissions specified by the optional parameter anInteger. /// /// try Dir.mkdir("draveness") /// try! Dir.mkdir("draveness/spool/mail", recursive: true) /// /// - Parameters: /// - path: A new directory path. /// - recursive: Whether creats intermeidate directories. /// - permissions: An integer represents the posix permission. /// - Throws: When `FileManager#createDirectory(atPath:withIntermediateDirectories:attributes:)` throws. public static func mkdir(_ path: String, recursive: Bool = false, _ permissions: Int? = nil) throws { var attributes: [String: Any] = [:] if let permissions = permissions { attributes[FileAttributeKey.posixPermissions.rawValue] = permissions } try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: recursive, attributes: attributes) } /// Error throws when called `Dir#rmdir(path:)` method. /// /// - notEmpty: Directory is not empty. /// - notExists: Directory is not exists. public enum RemoveDirectoryError: Error { case notEmpty case cocoa(String) } /// Deletes the named directory. /// /// try Dir.rmdir("/a/folder/path") /// /// - Parameter path: A directory path /// - Throws: `RemoveDirectoryError` if the directory isn’t empty. public static func rmdir(_ path: String) throws { if !Dir.isEmpty(path) { throw RemoveDirectoryError.notEmpty } do { try FileManager.default.removeItem(atPath: path) } catch { throw RemoveDirectoryError.cocoa(error.localizedDescription) } } /// Deletes the named directory. An alias to `Dir.rmdir(path:)`. /// /// try Dir.unlink("/a/folder/path") /// /// - Parameter path: A directory path /// - Throws: `RemoveDirectoryError` if the directory isn’t empty. public static func unlink(_ path: String) throws { try rmdir(path) } /// Returns true if the named file is a directory, false otherwise. /// /// Dir.isExist("/a/folder/path/not/exists") #=> false /// Dir.isExist("/a/folder/path/exists") #=> true /// /// - Parameter path: A file path. /// - Returns: A bool value indicates whether there is a directory in given path. public static func isExist(_ path: String) -> Bool { var isDirectory = false as ObjCBool let exist = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) return exist && isDirectory.boolValue } /// Returns true if the named file is an empty directory, false if it is /// not a directory or non-empty. /// /// Dir.isEmpty("/a/empty/folder") #=> true /// Dir.isEmpty("/a/folder/not/exists") #=> true /// Dir.isEmpty("/a/folder/with/files") #=> false /// /// - Parameter path: A directory path. /// - Returns: A bool value indicates the directory is not exists or is empty. public static func isEmpty(_ path: String) -> Bool { if let result = try? FileManager.default.contentsOfDirectory(atPath: path) { return result.isEmpty } return true } /// Returns an array containing all of the filenames in the given directory. Will return an empty array /// if the named directory doesn’t exist. /// /// - Parameter path: A directory path. /// - Returns: An array of all filenames in the given directory. public static func entries(_ path: String) -> [String] { do { let filenames = try FileManager.default.contentsOfDirectory(atPath: path) return [".", ".."] + filenames } catch { return [] } } /// Calls the block once for each entry in the named directory, passing the filename of each /// entry as a parameter to the block. /// /// - Parameters: /// - path: A directory path. /// - closure: A closure accepts all the entries in current directory. public static func foreach(_ path: String, closure: (String) -> ()) { entries(path).each(closure) } /// Deletes the named directory. /// /// - Parameter path: A directory path. /// - Returns: A bool value indicates the result of `Dir.delete(path:)` @discardableResult public static func delete(_ path: String) -> Bool { return Darwin.rmdir(path) == 0 } /// Seeks to a particular location in dir. /// /// - Parameter pos: A particular location. public func seek(_ pos: Int) { seekdir(_dir, pos) } /// Repositions dir to the first entry. public func rewind() { rewinddir(_dir) } }
mit
20112ffe2a0150e15de5e7adedb5c5c6
32.87415
125
0.59504
4.422291
false
false
false
false
ddaguro/clintonconcord
OIMApp/Controls/Spring/TransitionZoom.swift
1
3283
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class TransitionZoom: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var isPresenting = true var duration = 0.4 public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! if isPresenting { container!.addSubview(fromView) container!.addSubview(toView) toView.alpha = 0 toView.transform = CGAffineTransformMakeScale(2, 2) springEaseInOut(duration) { fromView.transform = CGAffineTransformMakeScale(0.5, 0.5) fromView.alpha = 0 toView.transform = CGAffineTransformIdentity toView.alpha = 1 } } else { container!.addSubview(toView) container!.addSubview(fromView) springEaseInOut(duration) { fromView.transform = CGAffineTransformMakeScale(2, 2) fromView.alpha = 0 toView.transform = CGAffineTransformMakeScale(1, 1) toView.alpha = 1 } } delay(duration, closure: { transitionContext.completeTransition(true) }) } public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
mit
b5d832572f11e41af6690490ac887ad2
41.102564
224
0.689309
5.925993
false
false
false
false
pjocprac/PTPopupWebView
Pod/Classes/PTPopupWebViewStyle.swift
1
5845
// // PTPopupWebViewStyle.swift // PTPopupWebView // // Created by Takeshi Watanabe on 2016/03/19. // Copyright © 2016 Takeshi Watanabe. All rights reserved. // import Foundation public enum PTPopupWebViewButtonDistribution { /// All buttons have equal width case equal /// Adjust the width the contents of the button case proportional } open class PTPopupWebViewStyle { // MARK: Content view's property open fileprivate(set) var outerMargin : UIEdgeInsets = UIEdgeInsets.zero open fileprivate(set) var innerMargin : UIEdgeInsets = UIEdgeInsets.zero open fileprivate(set) var backgroundColor : UIColor = .white open fileprivate(set) var cornerRadius : CGFloat = 8.0 // MARK: Content view's property setter /// Content view's corner radius (Default: 8.0) open func cornerRadius(_ value: CGFloat) -> Self { self.cornerRadius = value return self } /// Spacing between frame and content view (Default: UIEdgeInsetsZero) open func outerMargin(_ value: UIEdgeInsets) -> Self { self.outerMargin = value return self } /// Spacing between content view and web view (Default: UIEdgeInsetsZero) open func innerMargin(_ value: UIEdgeInsets) -> Self { self.innerMargin = value return self } /// Content view's background color (Default: white color) open func backgroundColor(_ value: UIColor) -> Self { self.backgroundColor = value return self } // MARK: Title area's property open fileprivate(set) var titleHeight : CGFloat = 40.0 open fileprivate(set) var titleHidden = false open fileprivate(set) var titleBackgroundColor : UIColor = .clear open fileprivate(set) var titleForegroundColor : UIColor = .darkGray open fileprivate(set) var titleFont : UIFont = .systemFont(ofSize: 16) // MARK: Title area's property setter /// Title area's height (Default: 40.0) open func titleHeight(_ value: CGFloat) -> Self { self.titleHeight = value; return self } /// Title area's invisibility (Default: false (visible)) open func titleHidden(_ value: Bool) -> Self { self.titleHidden = value return self } /// Title area's background color (Default: clear color) open func titleBackgroundColor(_ value: UIColor) -> Self { self.titleBackgroundColor = value return self } /// Title area's foreground color (Default: dark gray color) open func titleForegroundColor(_ value: UIColor) -> Self { self.titleForegroundColor = value return self } /// Title's font (Default: .systemFontOfSize(16)) open func titleFont(_ value: UIFont) -> Self { self.titleFont = value return self } // MARK: Button area's property open fileprivate(set) var buttonHeight : CGFloat = 40 open fileprivate(set) var buttonHidden = false open fileprivate(set) var buttonBackgroundColor : UIColor = .clear open fileprivate(set) var buttonForegroundColor : UIColor = UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1) open fileprivate(set) var buttonDisabledColor : UIColor = .lightGray open fileprivate(set) var buttonFont : UIFont = .systemFont(ofSize: 16) open fileprivate(set) var buttonDistribution : PTPopupWebViewButtonDistribution = .equal // MARK: Button's property setter /// Button area's height (Default: 40.0) open func buttonHeight(_ value: CGFloat) -> Self { self.buttonHeight = value return self } /// Button area's invisibility (Default: false (visible)) open func buttonHidden(_ value: Bool) -> Self { self.buttonHidden = value return self } /// Button's default background color (Default: clear color) /// This setting can be overridden by the button indivisual setting. open func buttonBackgroundColor(_ value: UIColor) -> Self { self.buttonBackgroundColor = value return self } /// Button's default foreground color (Default: green color, rgb(76,175,80)) /// This setting can be overridden by the button indivisual setting. open func buttonForegroundColor(_ value: UIColor) -> Self { self.buttonForegroundColor = value return self } /// Button's default foreground color when button is disabled (Default: light gray color) /// This setting can be overridden by the button indivisual setting. open func buttonDisabledColor(_ value: UIColor) -> Self { self.buttonDisabledColor = value return self } /// Button's font (Default: .systemFontOfSize(16)) /// This setting can be overridden by the button indivisual setting. open func buttonFont(_ value: UIFont) -> Self { self.buttonFont = value return self } /// Button's distribution (Default: .Equal, all buttons have equal width) open func buttonDistribution(_ value: PTPopupWebViewButtonDistribution) -> Self { self.buttonDistribution = value return self } // MARK: Other properties open fileprivate(set) var closeButtonHidden = true // MARK: Other properties setter /// Close button's invisibility (positioned at right top of view) (Default: true (invisible)) open func closeButtonHidden(_ value: Bool) -> Self { self.closeButtonHidden = value return self } // MARK: Initilizer public init(){ // nothing } } open class PTPopupWebViewControllerStyle : PTPopupWebViewStyle { override public init(){ super.init() let screenBounds = UIScreen.main.bounds let vMargin = screenBounds.height * 0.1 let hMargin = screenBounds.width * 0.05 outerMargin = UIEdgeInsetsMake(vMargin, hMargin, vMargin, hMargin) } }
mit
985f8d41329f80fcd9f312ee9466a062
32.394286
124
0.668207
4.801972
false
false
false
false
thehung111/visearch-widget-swift
WidgetsExample/WidgetsExample/StopWatch.swift
2
915
// // StopWatch.swift // WidgetsExample // // Created by Hung on 15/12/16. // Copyright © 2016 Visenze. All rights reserved. // import UIKit // record time public class StopWatch { public let name: String public var startTime: CFAbsoluteTime? = nil public var elapsedTime: CFAbsoluteTime = 0 public var elapsedTimeStep: CFAbsoluteTime = 0 public init(name: String) { self.name = name } public func reset() { elapsedTime = 0 elapsedTimeStep = 0 startTime = nil } public func resume() { if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } } public func pause() { if let startTime = startTime { elapsedTimeStep = CFAbsoluteTimeGetCurrent() - startTime elapsedTime += elapsedTimeStep self.startTime = nil } } }
mit
4cf8bef49cb19ef89c8223a8e71e5b74
20.255814
68
0.583151
4.861702
false
false
false
false
lhc70000/iina
iina/TouchBarSupport.swift
1
17109
// // MainWindowTouchBarSupport.swift // iina // // Created by lhc on 16/5/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa // MARK: - Touch bar @available(macOS 10.12.2, *) fileprivate extension NSTouchBar.CustomizationIdentifier { static let windowBar = NSTouchBar.CustomizationIdentifier("\(Bundle.main.bundleIdentifier!).windowTouchBar") } @available(macOS 10.12.2, *) fileprivate extension NSTouchBarItem.Identifier { static let playPause = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.playPause") static let slider = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.slider") static let volumeUp = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.voUp") static let volumeDown = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.voDn") static let rewind = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.rewind") static let fastForward = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.forward") static let time = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.time") static let remainingTime = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.remainingTime") static let ahead15Sec = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.ahead15Sec") static let back15Sec = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.back15Sec") static let ahead30Sec = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.ahead30Sec") static let back30Sec = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.back30Sec") static let next = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.next") static let prev = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.prev") static let exitFullScr = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.exitFullScr") static let togglePIP = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).TouchBarItem.togglePIP") } // Image name, tag, custom label @available(macOS 10.12.2, *) fileprivate let touchBarItemBinding: [NSTouchBarItem.Identifier: (NSImage.Name, Int, String)] = [ .ahead15Sec: (NSImage.touchBarSkipAhead15SecondsTemplateName, 15, NSLocalizedString("touchbar.ahead_15", comment: "15sec Ahead")), .ahead30Sec: (NSImage.touchBarSkipAhead30SecondsTemplateName, 30, NSLocalizedString("touchbar.ahead_30", comment: "30sec Ahead")), .back15Sec: (NSImage.touchBarSkipBack15SecondsTemplateName, -15, NSLocalizedString("touchbar.back_15", comment: "-15sec Ahead")), .back30Sec: (NSImage.touchBarSkipBack30SecondsTemplateName, -30, NSLocalizedString("touchbar.back_30", comment: "-30sec Ahead")), .next: (NSImage.touchBarSkipAheadTemplateName, 0, NSLocalizedString("touchbar.next_video", comment: "Next Video")), .prev: (NSImage.touchBarSkipBackTemplateName, 1, NSLocalizedString("touchbar.prev_video", comment: "Previous Video")), .volumeUp: (NSImage.touchBarVolumeUpTemplateName, 0, NSLocalizedString("touchbar.increase_volume", comment: "Volume +")), .volumeDown: (NSImage.touchBarVolumeDownTemplateName, 1, NSLocalizedString("touchbar.decrease_volume", comment: "Volume -")), .rewind: (NSImage.touchBarRewindTemplateName, 0, NSLocalizedString("touchbar.rewind", comment: "Rewind")), .fastForward: (NSImage.touchBarFastForwardTemplateName, 1, NSLocalizedString("touchbar.fast_forward", comment: "Fast Forward")) ] @available(macOS 10.12.2, *) class TouchBarSupport: NSObject, NSTouchBarDelegate { private var player: PlayerCore lazy var touchBar: NSTouchBar = { let touchBar = NSTouchBar() touchBar.delegate = self touchBar.customizationIdentifier = .windowBar touchBar.defaultItemIdentifiers = [.playPause, .time, .slider, .remainingTime] touchBar.customizationAllowedItemIdentifiers = [.playPause, .slider, .volumeUp, .volumeDown, .rewind, .fastForward, .time, .remainingTime, .ahead15Sec, .ahead30Sec, .back15Sec, .back30Sec, .next, .prev, .togglePIP, .fixedSpaceLarge] return touchBar }() weak var touchBarPlaySlider: TouchBarPlaySlider? weak var touchBarPlayPauseBtn: NSButton? var touchBarPosLabels: [DurationDisplayTextField] = [] var touchBarPosLabelWidthLayout: NSLayoutConstraint? /** The current/remaining time label in Touch Bar. */ lazy var sizingTouchBarTextField: NSTextField = { return NSTextField() }() init(playerCore: PlayerCore) { self.player = playerCore } func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? { switch identifier { case .playPause: let item = NSCustomTouchBarItem(identifier: identifier) item.view = NSButton(image: NSImage(named: NSImage.touchBarPauseTemplateName)!, target: self, action: #selector(self.touchBarPlayBtnAction(_:))) item.customizationLabel = NSLocalizedString("touchbar.play_pause", comment: "Play / Pause") self.touchBarPlayPauseBtn = item.view as? NSButton return item case .slider: let item = NSSliderTouchBarItem(identifier: identifier) item.slider = TouchBarPlaySlider() item.slider.cell = TouchBarPlaySliderCell() item.slider.minValue = 0 item.slider.maxValue = 100 item.slider.target = self item.slider.action = #selector(self.touchBarSliderAction(_:)) item.customizationLabel = NSLocalizedString("touchbar.seek", comment: "Seek") self.touchBarPlaySlider = item.slider as? TouchBarPlaySlider return item case .volumeUp, .volumeDown: guard let data = touchBarItemBinding[identifier] else { return nil } return buttonTouchBarItem(withIdentifier: identifier, imageName: data.0, tag: data.1, customLabel: data.2, action: #selector(self.touchBarVolumeAction(_:))) case .rewind, .fastForward: guard let data = touchBarItemBinding[identifier] else { return nil } return buttonTouchBarItem(withIdentifier: identifier, imageName: data.0, tag: data.1, customLabel: data.2, action: #selector(self.touchBarRewindAction(_:))) case .time: let item = NSCustomTouchBarItem(identifier: identifier) let label = DurationDisplayTextField(labelWithString: "00:00") label.alignment = .center label.font = .monospacedDigitSystemFont(ofSize: 0, weight: .regular) label.mode = .current self.touchBarPosLabels.append(label) item.view = label item.customizationLabel = NSLocalizedString("touchbar.time", comment: "Time Position") return item case .remainingTime: let item = NSCustomTouchBarItem(identifier: identifier) let label = DurationDisplayTextField(labelWithString: "00:00") label.alignment = .center label.font = .monospacedDigitSystemFont(ofSize: 0, weight: .regular) label.mode = .remaining self.touchBarPosLabels.append(label) item.view = label item.customizationLabel = NSLocalizedString("touchbar.remainingTime", comment: "Remaining Time Position") return item case .ahead15Sec, .back15Sec, .ahead30Sec, .back30Sec: guard let data = touchBarItemBinding[identifier] else { return nil } return buttonTouchBarItem(withIdentifier: identifier, imageName: data.0, tag: data.1, customLabel: data.2, action: #selector(self.touchBarSeekAction(_:))) case .next, .prev: guard let data = touchBarItemBinding[identifier] else { return nil } return buttonTouchBarItem(withIdentifier: identifier, imageName: data.0, tag: data.1, customLabel: data.2, action: #selector(self.touchBarSkipAction(_:))) case .exitFullScr: let item = NSCustomTouchBarItem(identifier: identifier) item.view = NSButton(image: NSImage(named: NSImage.touchBarExitFullScreenTemplateName)!, target: self, action: #selector(self.touchBarExitFullScrAction(_:))) return item case .togglePIP: let item = NSCustomTouchBarItem(identifier: identifier) // FIXME: we might need a better icon for this item.view = NSButton(image: Bundle.main.image(forResource: "pip")!, target: self, action: #selector(self.touchBarTogglePIP(_:))) item.customizationLabel = NSLocalizedString("touchbar.toggle_pip", comment: "Toggle PIP") return item default: return nil } } func updateTouchBarPlayBtn() { if player.info.isPaused { touchBarPlayPauseBtn?.image = NSImage(named: NSImage.touchBarPlayTemplateName) } else { touchBarPlayPauseBtn?.image = NSImage(named: NSImage.touchBarPauseTemplateName) } } @objc func touchBarPlayBtnAction(_ sender: NSButton) { player.togglePause(nil) } @objc func touchBarVolumeAction(_ sender: NSButton) { let currVolume = player.info.volume player.setVolume(currVolume + (sender.tag == 0 ? 5 : -5)) } @objc func touchBarRewindAction(_ sender: NSButton) { player.mainWindow.arrowButtonAction(left: sender.tag == 0) } @objc func touchBarSeekAction(_ sender: NSButton) { let sec = sender.tag player.seek(relativeSecond: Double(sec), option: .relative) } @objc func touchBarSkipAction(_ sender: NSButton) { player.navigateInPlaylist(nextMedia: sender.tag == 0) } @objc func touchBarSliderAction(_ sender: NSSlider) { let percentage = 100 * sender.doubleValue / sender.maxValue player.seek(percent: percentage, forceExact: true) } @objc func touchBarExitFullScrAction(_ sender: NSButton) { player.mainWindow.toggleWindowFullScreen() } @objc func touchBarTogglePIP(_ sender: NSButton) { player.mainWindow.menuTogglePIP(.dummy) } private func buttonTouchBarItem(withIdentifier identifier: NSTouchBarItem.Identifier, imageName: NSImage.Name, tag: Int, customLabel: String, action: Selector) -> NSCustomTouchBarItem { let item = NSCustomTouchBarItem(identifier: identifier) let button = NSButton(image: NSImage(named: imageName)!, target: self, action: action) button.tag = tag item.view = button item.customizationLabel = customLabel return item } func setupTouchBarUI() { let duration: VideoTime = player.info.videoDuration ?? .zero let pad: CGFloat = 16.0 sizingTouchBarTextField.stringValue = duration.stringRepresentation if let widthConstant = sizingTouchBarTextField.cell?.cellSize.width, !touchBarPosLabels.isEmpty { if let posConstraint = touchBarPosLabelWidthLayout { posConstraint.constant = widthConstant + pad touchBarPosLabels.forEach { $0.setNeedsDisplay() } } else { for posLabel in touchBarPosLabels { let posConstraint = NSLayoutConstraint(item: posLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: widthConstant + pad) posLabel.addConstraint(posConstraint) touchBarPosLabelWidthLayout = posConstraint } } } } func toggleTouchBarEsc(enteringFullScr: Bool) { if enteringFullScr, PlayerCore.keyBindings["ESC"]?.readableAction == "set fullscreen no" { touchBar.escapeKeyReplacementItemIdentifier = .exitFullScr } else { touchBar.escapeKeyReplacementItemIdentifier = nil } } } @available(macOS 10.12.2, *) extension MainWindowController { override func makeTouchBar() -> NSTouchBar? { return player.touchBarSupport.touchBar } } @available(macOS 10.12.2, *) extension MiniPlayerWindowController { override func makeTouchBar() -> NSTouchBar? { return player.touchBarSupport.touchBar } } // MARK: - Slider class TouchBarPlaySlider: NSSlider { var isTouching = false var playerCore: PlayerCore { return (self.window?.windowController as? MainWindowController)?.player ?? .active } override func touchesBegan(with event: NSEvent) { isTouching = true playerCore.togglePause(true) super.touchesBegan(with: event) } override func touchesEnded(with event: NSEvent) { isTouching = false playerCore.togglePause(false) super.touchesEnded(with: event) } func resetCachedThumbnails() { (cell as! TouchBarPlaySliderCell).cachedThumbnailProgress = -1 } func setDoubleValueSafely(_ value: Double) { guard !isTouching else { return } doubleValue = value } } class TouchBarPlaySliderCell: NSSliderCell { var cachedThumbnailProgress: Double = -1 private let solidColor = NSColor.labelColor.withAlphaComponent(0.4) private let knobWidthWithImage: CGFloat = 60 private var backgroundImage: NSImage? var isTouching: Bool { return (self.controlView as! TouchBarPlaySlider).isTouching } var playerCore: PlayerCore { return (self.controlView as! TouchBarPlaySlider).playerCore } override var knobThickness: CGFloat { return 4 } override func barRect(flipped: Bool) -> NSRect { self.controlView?.superview?.layer?.backgroundColor = .black let rect = super.barRect(flipped: flipped) return NSRect(x: rect.origin.x, y: 2, width: rect.width, height: self.controlView!.frame.height - 4) } override func knobRect(flipped: Bool) -> NSRect { let info = playerCore.info let superKnob = super.knobRect(flipped: flipped) if isTouching { if info.thumbnails.count > 0 { let imageKnobWidth = knobWidthWithImage let barWidth = barRect(flipped: flipped).width return NSRect(x: superKnob.origin.x * (barWidth - (imageKnobWidth - superKnob.width)) / barWidth, y: superKnob.origin.y, width: imageKnobWidth, height: superKnob.height) } else { return superKnob } } else { let remainingKnobWidth = superKnob.width - knobThickness return NSRect(x: superKnob.origin.x + remainingKnobWidth * CGFloat(doubleValue/100), y: superKnob.origin.y, width: knobThickness, height: superKnob.height) } } override func drawKnob(_ knobRect: NSRect) { let info = playerCore.info guard !info.isIdle else { return } if isTouching, let dur = info.videoDuration?.second, let tb = info.getThumbnail(forSecond: (doubleValue / 100) * dur), let image = tb.image { NSGraphicsContext.saveGraphicsState() NSBezierPath(roundedRect: knobRect, xRadius: 3, yRadius: 3).setClip() let origSize = image.size.crop(withAspect: Aspect(size: knobRect.size)) let origRect = NSRect(x: (image.size.width - origSize.width) / 2, y: (image.size.height - origSize.height) / 2, width: origSize.width, height: origSize.height) image.draw(in: knobRect, from: origRect, operation: .copy, fraction: 1, respectFlipped: true, hints: nil) NSColor.white.setStroke() let outerBorder = NSBezierPath(roundedRect: knobRect.insetBy(dx: 1, dy: 1), xRadius: 3, yRadius: 3) outerBorder.lineWidth = 1 outerBorder.stroke() NSColor.black.setStroke() let innerBorder = NSBezierPath(roundedRect: knobRect.insetBy(dx: 2, dy: 2), xRadius: 2, yRadius: 2) innerBorder.lineWidth = 1 innerBorder.stroke() NSGraphicsContext.restoreGraphicsState() } else { NSColor.labelColor.setFill() let path = NSBezierPath(roundedRect: knobRect, xRadius: 2, yRadius: 2) path.fill() } } override func drawBar(inside rect: NSRect, flipped: Bool) { let info = playerCore.info guard !info.isIdle else { return } let barRect = self.barRect(flipped: flipped) if let image = backgroundImage, info.thumbnailsProgress == cachedThumbnailProgress { // draw cached background image image.draw(in: barRect) } else { // draw the background image let imageRect = NSRect(origin: .zero, size: barRect.size) let image = NSImage(size: barRect.size) image.lockFocus() NSGraphicsContext.saveGraphicsState() NSBezierPath(roundedRect: imageRect, xRadius: 2.5, yRadius: 2.5).setClip() let step: CGFloat = 3 let end = imageRect.width var i: CGFloat = 0 solidColor.setFill() while (i < end + step) { let percent = Double(i / end) let dest = NSRect(x: i, y: 0, width: 2, height: imageRect.height) if let dur = info.videoDuration?.second, let image = info.getThumbnail(forSecond: percent * dur)?.image, info.thumbnailsProgress >= percent { let orig = NSRect(origin: .zero, size: image.size) image.draw(in: dest, from: orig, operation: .copy, fraction: 1, respectFlipped: true, hints: nil) } else { NSBezierPath(rect: dest).fill() } i += step } NSGraphicsContext.restoreGraphicsState() image.unlockFocus() backgroundImage = image cachedThumbnailProgress = info.thumbnailsProgress image.draw(in: barRect) } } }
gpl-3.0
a1ab35b3e5a09dd5dc6162d7d266287e
39.830549
236
0.708382
4.512793
false
false
false
false
QB3L/easypost-ios
EasyPostSample/Easypost/EasyPostSwift.swift
1
7713
// // EasyPostSwift.swift // EasyPostSample // // Created by Ruben Nieves on 6/4/16. // Copyright © 2016 TopBalance Software. All rights reserved. // import UIKit enum EasyPostServiceErrorCode : Int { case EasyPostServiceErrorGeneral = 1 /* Non-specific error */ case EasyPostServiceErrorMissingParameters = 2 } typealias CompletionBlock = (NSError?, Dictionary <String , String>?) -> Void //error and result class EasyPostSwift: NSObject { static var EasyPostServiceErrorDomain : String = "EasyPostServiceError" #if (TEST_VERSION) static var APIKEY = "" //Test Key #else static var APIKEY = ""; #endif func showNetworkIndicator() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true; } func hideNetworkIndicator() { UIApplication.sharedApplication().networkActivityIndicatorVisible = false; } //Generic function for getting something from API class func requestService(parameters:Dictionary <String, String>, link:String, completion:CompletionBlock) { var body : String = "" for (key, value) in parameters { body += "\(key)=\(value)&" } let method = parameters.isEmpty ? "GET" : "POST" if method == "POST" { body = String(body.characters.dropLast()) //Delete last & character } let requestData : NSData? = body.dataUsingEncoding(NSUTF8StringEncoding) let request : NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: link)!) if (requestData != nil) { //Authorization let authStr : String = "\(APIKEY):" let authData : NSData = authStr.dataUsingEncoding(NSASCIIStringEncoding)! let authValue : String = "Basic\(Base64Encoder.base64EncodeForData(authData) as String)=" request.setValue(authValue, forKey: "Authorization") //Finish request let postLength : String = "\(String(requestData?.length))" request.HTTPMethod = method request.setValue(postLength, forKey: "Content-Length") request.setValue("application/x-www-form-urlencoded", forKey: "Content-Type") let config : NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let session : NSURLSession = NSURLSession(configuration: config) let uploadTask : NSURLSessionUploadTask = session.uploadTaskWithRequest(request, fromData: requestData, completionHandler: { (data, response, error) in if error == nil { completion(error,nil) } else { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: String] completion(nil, json) } catch let error as NSError { print("Failed to parse: \(error.localizedDescription)") completion(error, nil) } } }); uploadTask .resume() } else { completion(NSError.init(domain: EasyPostServiceErrorDomain, code: 500, userInfo: ["Error":"Error creating request"]), nil) } } class func getPostageLabelForShipment(shipmentId:String, rateId:String, completion:CompletionBlock) { let link : String = "https://api.easypost.com/v2/shipments/\(shipmentId)/buy" let dict : Dictionary = ["rate[id]" : rateId] EasyPostSwift.requestService(dict, link: link, completion: completion) } class func getAddress(addressDict:Dictionary <String,String>, completion:CompletionBlock) { EasyPostSwift.requestService(addressDict, link: "https://api.easypost.com/v2/addresses", completion: completion) } class func getParcel(parcelDict:Dictionary<String, String>, completion:CompletionBlock) { EasyPostSwift.requestService(parcelDict, link: "https://api.easypost.com/v2/parcels", completion: completion) } class func getShipment(toAddressId:String, fromAddressId:String, parcelId:String, customsId:String?, completion:CompletionBlock) { var dict : Dictionary = ["shipment[to_address][id]" : toAddressId, "shipment[from_address][id]" : fromAddressId, "shipment[parcel][id]" : parcelId ] if customsId != nil { dict["shipment[customs_info][id]"] = customsId } EasyPostSwift.requestService(dict, link: "https://api.easypost.com/v2/shipments", completion: completion) } class func getShipment(toDictionary:Dictionary<String,String>, fromDictionary:Dictionary<String,String>, parcelDictionary:Dictionary<String,String>, completion:CompletionBlock) { var dict : Dictionary = [String:String]() //Empty dictionary first //Add addresses values for shipment for index in 0...1 { var addressDict : Dictionary = index == 0 ? fromDictionary : toDictionary let addressKeyString = index == 0 ? "from_address" : "to_address" if let name = addressDict["address[name]"] { dict["shipment[\(addressKeyString)][name]"] = name } if let company = addressDict["address[company]"] { dict["shipment[\(addressKeyString)][company]"] = company } if let street1 = addressDict["address[street1]"] { dict["shipment[\(addressKeyString)][street1]"] = street1 } if let street2 = addressDict["address[street2]"] { dict["shipment[\(addressKeyString)][street2]"] = street2 } if let city = addressDict["address[city]"] { dict["shipment[\(addressKeyString)][city]"] = city } if let state = addressDict["address[state]"] { dict["shipment[\(addressKeyString)][state]"] = state } if let zip = addressDict["address[zip]"] { dict["shipment[\(addressKeyString)][zip]"] = zip } if let zip = addressDict["address[country]"] { dict["shipment[\(addressKeyString)][country]"] = zip } else { dict["shipment[\(addressKeyString)][country]"] = "US" } if let phone = addressDict["address[phone]"] { dict["shipment[\(addressKeyString)][phone]"] = phone } if let email = addressDict["address[email]"] { dict["shipment[\(addressKeyString)][email]"] = email } } if let predefinedPackage = parcelDictionary["parcel[predefined_package]"] { dict["shipment[parcel][predefined_package]"] = predefinedPackage } if let weight = parcelDictionary["parcel[weight]"] { dict["shipment[parcel][weight]"] = weight } if let length = parcelDictionary["parcel[length]"] { dict["shipment[parcel][length]"] = length } if let width = parcelDictionary["parcel[width]"] { dict["shipment[parcel][width]"] = width } if let height = parcelDictionary["parcel[height]"] { dict["shipment[parcel][height]"] = height } EasyPostSwift.requestService(dict, link: "https://api.easypost.com/v2/shipments", completion: completion) } }
mit
074a4904f83fa4be26b8901eb8dc3311
41.142077
182
0.58584
5.214334
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Services/CommentService+Likes.swift
1
5569
extension CommentService { /** Fetches a list of users from remote that liked the comment with the given IDs. @param commentID The ID of the comment to fetch likes for @param siteID The ID of the site that contains the post @param count Number of records to retrieve. Optional. Defaults to the endpoint max of 90. @param before Filter results to likes before this date/time. Optional. @param excludingIDs An array of user IDs to exclude from the returned results. Optional. @param purgeExisting Indicates if existing Likes for the given post and site should be purged before new ones are created. Defaults to true. @param success A success block returning: - Array of LikeUser - Total number of likes for the given comment - Number of likes per fetch @param failure A failure block */ func getLikesFor(commentID: NSNumber, siteID: NSNumber, count: Int = 90, before: String? = nil, excludingIDs: [NSNumber]? = nil, purgeExisting: Bool = true, success: @escaping (([LikeUser], Int, Int) -> Void), failure: @escaping ((Error?) -> Void)) { guard let remote = restRemote(forSite: siteID) else { DDLogError("Unable to create a REST remote for comments.") failure(nil) return } remote.getLikesForCommentID(commentID, count: NSNumber(value: count), before: before, excludeUserIDs: excludingIDs, success: { remoteLikeUsers, totalLikes in self.createNewUsers(from: remoteLikeUsers, commentID: commentID, siteID: siteID, purgeExisting: purgeExisting) { let users = self.likeUsersFor(commentID: commentID, siteID: siteID) success(users, totalLikes.intValue, count) LikeUserHelper.purgeStaleLikes() } }, failure: { error in DDLogError(String(describing: error)) failure(error) }) } /** Fetches a list of users from Core Data that liked the comment with the given IDs. @param commentID The ID of the comment to fetch likes for. @param siteID The ID of the site that contains the post. @param after Filter results to likes after this Date. Optional. */ func likeUsersFor(commentID: NSNumber, siteID: NSNumber, after: Date? = nil) -> [LikeUser] { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = { if let after = after { // The date comparison is 'less than' because Likes are in descending order. return NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@ AND dateLiked < %@", siteID, commentID, after as CVarArg) } return NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@", siteID, commentID) }() request.sortDescriptors = [NSSortDescriptor(key: "dateLiked", ascending: false)] if let users = try? managedObjectContext.fetch(request) { return users } return [LikeUser]() } } private extension CommentService { func createNewUsers(from remoteLikeUsers: [RemoteLikeUser]?, commentID: NSNumber, siteID: NSNumber, purgeExisting: Bool, onComplete: @escaping (() -> Void)) { guard let remoteLikeUsers = remoteLikeUsers, !remoteLikeUsers.isEmpty else { DispatchQueue.main.async { onComplete() } return } ContextManager.shared.performAndSave { derivedContext in let likers = remoteLikeUsers.map { remoteUser in LikeUserHelper.createOrUpdateFrom(remoteUser: remoteUser, context: derivedContext) } if purgeExisting { self.deleteExistingUsersFor(commentID: commentID, siteID: siteID, from: derivedContext, likesToKeep: likers) } } completion: { DispatchQueue.main.async { onComplete() } } } func deleteExistingUsersFor(commentID: NSNumber, siteID: NSNumber, from context: NSManagedObjectContext, likesToKeep: [LikeUser]) { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = NSPredicate(format: "likedSiteID = %@ AND likedCommentID = %@ AND NOT (self IN %@)", siteID, commentID, likesToKeep) do { let users = try context.fetch(request) users.forEach { context.delete($0) } } catch { DDLogError("Error fetching comment Like Users: \(error)") } } }
gpl-2.0
866d3f132100142d23b3342eb4431fe1
43.198413
144
0.527204
5.95615
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/NextRideFeature/NextRideCore.swift
1
5074
import Combine import ComposableArchitecture import ComposableCoreLocation import Foundation import Logger import SharedDependencies import SharedModels // MARK: State public struct NextRideFeature: ReducerProtocol { public init() {} @Dependency(\.nextRideService) public var service @Dependency(\.userDefaultsClient) public var userDefaultsClient @Dependency(\.date) public var date @Dependency(\.mainQueue) public var mainQueue @Dependency(\.coordinateObfuscator) public var coordinateObfuscator @Dependency(\.isNetworkAvailable) public var isNetworkAvailable public struct State: Equatable { public init(nextRide: Ride? = nil) { self.nextRide = nextRide } public var nextRide: Ride? public var rideEvents: [Ride] = [] public var userLocation: Coordinate? } // MARK: Actions public enum Action: Equatable { case getNextRide(Coordinate) case nextRideResponse(TaskResult<[Ride]>) case setNextRide(Ride) } // MARK: Reducer /// Reducer handling next ride feature actions public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> { switch action { case let .getNextRide(coordinate): guard userDefaultsClient.rideEventSettings.isEnabled else { logger.debug("NextRide featue is disabled") return .none } guard isNetworkAvailable else { logger.debug("Not fetching next ride. No connectivity") return .none } let obfuscatedCoordinate = coordinateObfuscator.obfuscate( coordinate, .thirdDecimal ) let requestRidesInMonth: Int = queryMonth(for: date.callAsFunction) return .task { await .nextRideResponse( TaskResult { try await service.nextRide( obfuscatedCoordinate, userDefaultsClient.rideEventSettings.eventDistance.rawValue, requestRidesInMonth ) } ) } case let .nextRideResponse(.failure(error)): logger.error("Get next ride failed 🛑 with error: \(error)") return .none case let .nextRideResponse(.success(rides)): guard !rides.isEmpty else { logger.info("Rides array is empty") return .none } guard !rides.map(\.rideType).isEmpty else { logger.info("No upcoming events for filter selection rideType") return .none } state.rideEvents = rides.sortByDateAndFilterBeforeDate(date.callAsFunction) // Sort rides by date and pick the first one with a date greater than now let ride = rides // swiftlint:disable:this sorted_first_last .lazy .filter { guard let type = $0.rideType else { return true } return userDefaultsClient.rideEventSettings.typeSettings .lazy .filter(\.isEnabled) .map(\.type) .contains(type) } .filter(\.enabled) .sorted { lhs, rhs in let byDate = lhs.dateTime < rhs.dateTime guard let userLocation = state.userLocation, let lhsCoordinate = lhs.coordinate, let rhsCoordinate = rhs.coordinate else { return byDate } if Calendar.current.isDate(lhs.dateTime, inSameDayAs: rhs.dateTime) { return lhsCoordinate.distance(from: userLocation) < rhsCoordinate.distance(from: userLocation) } else { return byDate } } .first { ride in ride.dateTime > date() } guard let filteredRide = ride else { logger.info("No upcoming events after filter") return .none } return Effect(value: .setNextRide(filteredRide)) case let .setNextRide(ride): state.nextRide = ride return .none } } } // MARK: Helper enum EventError: Error, LocalizedError { case eventsAreNotEnabled case invalidDateError case rideIsOutOfRangeError case noUpcomingRides case rideTypeIsFiltered case rideDisabled } private func queryMonth(for date: () -> Date = Date.init, calendar: Calendar = .current) -> Int { let currentMonthOfFallback = calendar.dateComponents([.month], from: date()).month ?? 0 guard !calendar.isDateInWeekend(date()) else { // current date is on a weekend return currentMonthOfFallback } guard let startDateOfNextWeekend = calendar.nextWeekend(startingAfter: date())?.start else { return currentMonthOfFallback } guard let month = calendar.dateComponents([.month], from: startDateOfNextWeekend).month else { return currentMonthOfFallback } return max(currentMonthOfFallback, month) } public extension Array where Element == Ride { func sortByDateAndFilterBeforeDate(_ now: () -> Date) -> Self { lazy .sorted(by: \.dateTime) .filter { $0.dateTime > now() } } } extension SharedModels.Coordinate { init(_ location: ComposableCoreLocation.Location) { self = .init( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ) } }
mit
48c586717676f5a51f7d61e67334d6e3
27.649718
106
0.659436
4.734827
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Views/LoadingStatusView.swift
2
1962
import Foundation class LoadingStatusView: UIView { @objc init(title: String) { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false backgroundColor = .clear autoresizingMask = .flexibleWidth titleLabel.text = title activityIndicator.startAnimating() configureLayout() } private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = .appBarText label.font = WPFontManager.systemRegularFont(ofSize: 14.0) label.translatesAutoresizingMaskIntoConstraints = false label.sizeToFit() label.numberOfLines = 1 label.textAlignment = .natural label.lineBreakMode = .byTruncatingTail label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) addSubview(label) return label }() private lazy var activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .medium) indicator.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ indicator.widthAnchor.constraint(equalToConstant: 20.0), indicator.heightAnchor.constraint(equalToConstant: 20.0), ]) addSubview(indicator) return indicator }() private func configureLayout() { NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor), activityIndicator.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 2.0), activityIndicator.trailingAnchor.constraint(equalTo: trailingAnchor), activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
72553a3c1238e75c219697ffaa01567c
36.730769
106
0.679409
6.036923
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Generators/Physical Models/Rhodes Piano/AKRhodesPiano.swift
1
4195
// // AKRhodesPiano.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// STK RhodesPiano /// open class AKRhodesPiano: AKNode, AKToggleable, AKComponent { /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(generator: "rhod") public typealias AKAudioUnitType = AKRhodesPianoAudioUnit // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var frequencyParameter: AUParameter? fileprivate var amplitudeParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. @objc open dynamic var frequency: Double = 110 { willSet { if frequency != newValue { if let existingToken = token { frequencyParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Amplitude @objc open dynamic var amplitude: Double = 0.5 { willSet { if amplitude != newValue { if let existingToken = token { amplitudeParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize the mandolin with defaults override convenience init() { self.init(frequency: 110) } /// Initialize the STK RhodesPiano model /// /// - Parameters: /// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is /// greater than that. /// - amplitude: Amplitude /// @objc public init( frequency: Double = 440, amplitude: Double = 0.5) { self.frequency = frequency self.amplitude = amplitude _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } frequencyParameter = tree["frequency"] amplitudeParameter = tree["amplitude"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) } /// Trigger the sound with an optional set of parameters /// - Parameters: /// - frequency: Frequency in Hz /// - amplitude amplitude: Volume /// open func trigger(frequency: Double, amplitude: Double = 1) { self.frequency = frequency self.amplitude = amplitude internalAU?.start() internalAU?.triggerFrequency(Float(frequency), amplitude: Float(amplitude)) } /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
8468ef0ae5ea5d756c01d1c2505d4de9
31.015267
113
0.612065
5.229426
false
false
false
false
bamurph/FeedKit
Sources/Model/Atom/AtomFeedLink.swift
2
7818
// // AtomFeedLink.swift // // Copyright (c) 2016 Nuno Manuel Dias // // 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 /** The "atom:link" element defines a reference from an entry or feed to a Web resource. This specification assigns no meaning to the content (if any) of this element. */ open class AtomFeedLink { /** The element's attributes */ open class Attributes { /** The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose value MUST be a IRI reference [RFC3987]. */ open var href: String? /** The atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate". The value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, implementations MUST consider the link relation type equivalent to the same name registered within the IANA Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning of the link, but does not impose any behavioral requirements on Atom Processors. This document defines five initial values for the Registry of Link Relations: 1. The value "alternate" signifies that the IRI in the value of the href attribute identifies an alternate version of the resource described by the containing element. 2. The value "related" signifies that the IRI in the value of the href attribute identifies a resource related to the resource described by the containing element. For example, the feed for a site that discusses the performance of the search engine at "http://search.example.com" might contain, as a child of atom:feed: <link rel="related" href="http://search.example.com/"/> An identical link might appear as a child of any atom:entry whose content contains a discussion of that same search engine. 3. The value "self" signifies that the IRI in the value of the href attribute identifies a resource equivalent to the containing element. 4. The value "enclosure" signifies that the IRI in the value of the href attribute identifies a related resource that is potentially large in size and might require special handling. For atom:link elements with rel="enclosure", the length attribute SHOULD be provided. 5. The value "via" signifies that the IRI in the value of the href attribute identifies a resource that is the source of the information provided in the containing element. */ open var rel: String? /** On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note that the type attribute does not override the actual media type returned with the representation. Link elements MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. */ open var type: String? /** The "hreflang" attribute's content describes the language of the resource pointed to by the href attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. */ open var hreflang: String? /** The "title" attribute conveys human-readable information about the link. The content of the "title" attribute is Language-Sensitive. Entities such as "&amp;" and "&lt;" represent their corresponding characters ("&" and "<", respectively), not markup. Link elements MAY have a title attribute. */ open var title: String? /** The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about the content length of the representation returned when the IRI in the href attribute is mapped to a URI and dereferenced. Note that the length attribute does not override the actual content length of the representation as reported by the underlying protocol. Link elements MAY have a length attribute. */ open var length: Int64? } /** The element's attributes */ open var attributes: Attributes? } // MARK: - Initializers extension AtomFeedLink { /** Initializes the `AtomFeedLink` with the attributes of the "atom:link" element - parameter attributeDict: A dictionary with the attributes of the "atom:link" element - returns: An `AtomFeedLink` instance */ convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = AtomFeedLink.Attributes(attributes: attributeDict) } } extension AtomFeedLink.Attributes { /** Initializes the `Attributes` of the `AtomFeedLink` - parameter: A dictionary with the attributes of the "atom:link" element - returns: An `AtomFeedLink.Attributes` instance */ convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.href = attributeDict["href"] self.hreflang = attributeDict["hreflang"] self.type = attributeDict["type"] self.rel = attributeDict["rel"] self.title = attributeDict["title"] self.length = Int64(attributeDict["length"] ?? "") } }
mit
6afa25df26452e9d60bf17d60d5cf3ef
35.704225
91
0.633666
5.126557
false
false
false
false
stephentyrone/swift
test/AutoDiff/Sema/transpose_attr_type_checking.swift
3
16888
// RUN: %target-swift-frontend-typecheck -verify %s import _Differentiation // ~~~~~~~~~~~~~ Test top-level functions. ~~~~~~~~~~~~~ func linearFunc(_ x: Float) -> Float { return x } @transpose(of: linearFunc, wrt: 0) func linearFuncTranspose(x: Float) -> Float { return x } func twoParams(_ x: Float, _ y: Double) -> Double { return Double(x) + y } @transpose(of: twoParams, wrt: 0) func twoParamsT1(_ y: Double, _ t: Double) -> Float { return Float(t + y) } @transpose(of: twoParams, wrt: 1) func twoParamsT2(_ x: Float, _ t: Double) -> Double { return Double(x) + t } @transpose(of: twoParams, wrt: (0, 1)) func twoParamsT3(_ t: Double) -> (Float, Double) { return (Float(t), t) } func threeParams(_ x: Float, _ y: Double, _ z: Float) -> Double { return Double(x) + y } @transpose(of: threeParams, wrt: 0) func threeParamsT1(_ y: Double, _ z: Float, _ t: Double) -> Float { return Float(t + y) + z } @transpose(of: threeParams, wrt: 1) func threeParamsT2(_ x: Float, _ z: Float, _ t: Double) -> Double { return Double(x + z) + t } @transpose(of: threeParams, wrt: 2) func threeParamsT3(_ x: Float, _ y: Double, _ t: Double) -> Float { return Float(y + t) + x } @transpose(of: threeParams, wrt: (0, 1)) func threeParamsT4(_ z: Float, _ t: Double) -> (Float, Double) { return (z + Float(t), Double(z) + t) } @transpose(of: threeParams, wrt: (0, 2)) func threeParamsT5(_ y: Double, _ t: Double) -> (Float, Float) { let ret = Float(y + t) return (ret, ret) } @transpose(of: threeParams, wrt: (0, 1, 2)) func threeParamsT5(_ t: Double) -> (Float, Double, Float) { let ret = Float(t) return (ret, t, ret) } // Generics func generic<T: Differentiable>(x: T) -> T where T == T.TangentVector { return x } @transpose(of: generic, wrt: 0) func genericT<T: Differentiable>(x: T) -> T where T == T.TangentVector { return x } func genericThreeParam< T: Differentiable & BinaryFloatingPoint, U: Differentiable & BinaryFloatingPoint, V: Differentiable & BinaryFloatingPoint>( t: T, u: U, v: V ) -> T where T == T.TangentVector, U == U.TangentVector, V == V.TangentVector { return t } @transpose(of: genericThreeParam, wrt: 1) func genericThreeParamT2< T: Differentiable & BinaryFloatingPoint, U: Differentiable & BinaryFloatingPoint, V: Differentiable & BinaryFloatingPoint>( t: T, v: V, s: T ) -> U where T == T.TangentVector, U == U.TangentVector, V == V.TangentVector { return U(1) } @transpose(of: genericThreeParam, wrt: (0, 1, 2)) func genericThreeParamT2< T: Differentiable & BinaryFloatingPoint, U: Differentiable & BinaryFloatingPoint, V: Differentiable & BinaryFloatingPoint>( t: T ) -> (T, U, V) where T == T.TangentVector, U == U.TangentVector, V == V.TangentVector { return (T(1), U(1), V(1)) } func genericOneParamFloatOneParam<T: Differentiable & BinaryFloatingPoint>( t: T, f: Float ) -> T where T == T.TangentVector { return T(f) } @transpose(of: genericOneParamFloatOneParam, wrt: 0) func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( f: Float, t: T ) -> T where T == T.TangentVector { return t } @transpose(of: genericOneParamFloatOneParam, wrt: 1) func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( t1: T, t2: T ) -> Float where T == T.TangentVector { return 1 } @transpose(of: genericOneParamFloatOneParam, wrt: (0, 1)) func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( t: T ) -> (T, Float) where T == T.TangentVector { return (T(1), 1) } func withInt(x: Float, y: Int) -> Float { if y >= 0 { return x } else { return x } } @transpose(of: withInt, wrt: 0) func withIntT(x: Int, t: Float) -> Float { return t } func missingDiffSelfRequirement<T: AdditiveArithmetic>(x: T) -> T { return x } // expected-error @+1 {{cannot transpose with respect to original result 'T' that does not conform to 'Differentiable' and satisfy 'T == T.TangentVector'}} @transpose(of: missingDiffSelfRequirement, wrt: 0) func missingDiffSelfRequirementT<T: AdditiveArithmetic>(x: T) -> T { return x } func missingSelfRequirement<T: Differentiable>(x: T) -> T where T.TangentVector == T { return x } // expected-error @+1 {{cannot transpose with respect to original result 'T' that does not conform to 'Differentiable' and satisfy 'T == T.TangentVector'}} @transpose(of: missingSelfRequirement, wrt: 0) func missingSelfRequirementT<T: Differentiable>(x: T) -> T { return x } func differentGenericConstraint<T: Differentiable & BinaryFloatingPoint>(x: T) -> T where T == T.TangentVector { return x } // expected-error @+1 {{could not find function 'differentGenericConstraint' with expected type '<T where T : Differentiable, T == T.TangentVector> (T) -> T'}} @transpose(of: differentGenericConstraint, wrt: 0) func differentGenericConstraintT<T: Differentiable>(x: T) -> T where T == T.TangentVector { return x } func transposingInt(x: Float, y: Int) -> Float { if y >= 0 { return x } else { return x } } // expected-error @+1 {{cannot transpose with respect to original parameter 'Int' that does not conform to 'Differentiable' and satisfy 'Int == Int.TangentVector'}} @transpose(of: transposingInt, wrt: 1) func transposingIntT1(x: Float, t: Float) -> Int { return Int(x) } @transpose(of: transposingInt, wrt: 0) func tangentNotLast(y: Int, t: Float) -> Float { return t } // ~~~~~~~~~~~~~ Test methods. ~~~~~~~~~~~~~ // // Method no parameters. extension Float { func getDouble() -> Double { return Double(self) } @transpose(of: Float.getDouble, wrt: self) static func structTranspose(v: Double) -> Float { return Float(v) } } // Method with one parameter. extension Float { func adding(_ double: Double) -> Float { return self + Float(double) } @transpose(of: Float.adding, wrt: 0) func addingT1(t: Float) -> Double { return Double(self + t) } @transpose(of: Float.adding, wrt: self) static func addingT2(_ double: Double, t: Float) -> Float { return Float(double) + t } @transpose(of: Float.adding, wrt: (self, 0)) static func addingT3(t: Float) -> (Float, Double) { return (t, Double(t)) } } // Different self type/result type. extension Int { func myAdding(_ double: Double) -> Float { return Float(double) } @transpose(of: Int.myAdding, wrt: 0) func addingT3(t: Float) -> Double { return Double(t) } // expected-error @+1 {{cannot transpose with respect to original parameter 'Int' that does not conform to 'Differentiable' and satisfy 'Int == Int.TangentVector'}} @transpose(of: Int.myAdding, wrt: (self, 0)) static func addingT3(v: Float) -> (Int, Double) { return (Int(v), Double(v)) } } // Static methods. struct A : Differentiable & AdditiveArithmetic { typealias TangentVector = A var x: Double static prefix func -(a: A) -> A { return A(x: -a.x) } @transpose(of: -, wrt: 0) static func transposeNegate(t: A) -> A { return A(x: -t.x) } static prefix func +(a: A) -> A { return a } // TODO(TF-1065): Consider disallowing qualified operator names. @transpose(of: A.+, wrt: 0) static func transposeIdQualified(t: A) -> A { return t } } extension Float { static func myMultiply(lhs: Float, rhs: Float) -> Float { return lhs * rhs } @transpose(of: Float.myMultiply, wrt: 0) @transpose(of: Float.myMultiply, wrt: 1) static func myMultiplyT(param: Float, v: Float) -> Float { return param + v } static func threeParamsStatic(_ x: Float, _ y: Double, _ z: Float) -> Double { return Double(x + z) + y } @transpose(of: Float.threeParamsStatic, wrt: (0, 1, 2)) static func threeParamsT12(v: Double) -> (x: Float, y: Double, z: Float) { return (Float(v), v, Float(v)) } @transpose(of: Float.threeParamsStatic, wrt: (0, 2)) static func threeParamsT12(_ y: Double, v: Double) -> (x: Float, z: Float) { let ret = Float(y + v) return (ret, ret) } @transpose(of: Float.threeParamsStatic, wrt: 1) static func threeParamsT12(_ x: Float, _ z: Float, v: Double) -> Double { return v + Double(x + z) } } // Method with 3 parameters. extension Float { func threeParams(_ x: Float, _ y: Double, _ z: Float) -> Double { return Double(self + x + z) + y } @transpose(of: Float.threeParams, wrt: 0) func threeParamsT1(_ y: Double, _ z: Float, t: Double) -> Float { return self + Float(t + y) + z } @transpose(of: Float.threeParams, wrt: 1) func threeParamsT2(_ x: Float, _ z: Float, t: Double) -> Double { return t + Double(x + z + self) } @transpose(of: Float.threeParams, wrt: 2) func threeParamsT3(_ x: Float, _ y: Double, t: Double) -> Float { return x + Float(y + t) + self } @transpose(of: Float.threeParams, wrt: (0, 1)) func threeParamsT4(_ z: Float, t: Double) -> (x: Float, y: Double) { return (Float(t) + z + self, t + Double(z + self)) } @transpose(of: Float.threeParams, wrt: (0, 2)) func threeParamsT5(_ y: Double, t: Double) -> (x: Float, z: Float) { let ret = Float(y + t) + self return (ret, ret) } @transpose(of: Float.threeParams, wrt: (0, 1, 2)) func threeParamsT6(t: Double) -> (x: Float, y: Double, z: Float) { return (Float(t) + self, t + Double(self), Float(t) + self) } @transpose(of: Float.threeParams, wrt: self) static func threeParamsT6(_ x: Float, _ y: Double, _ z: Float, t: Double) -> Float { return x + z + Float(y + t) } @transpose(of: Float.threeParams, wrt: (self, 0)) static func threeParamsT7(_ y: Double, _ z: Float, t: Double) -> (self: Float, x: Float) { let ret = Float(y + t) + z return (ret, ret) } @transpose(of: Float.threeParams, wrt: (self, 1)) static func threeParamsT7(_ x: Float, _ z: Float, t: Double) -> (self: Float, y: Double) { return (x + z + Float(t), t + Double(x + z)) } @transpose(of: Float.threeParams, wrt: (self, 2)) static func threeParamsT9(_ x: Float, _ y: Double, t: Double) -> (self: Float, z: Float) { let ret = Float(y + t) + x return (ret, ret) } @transpose(of: Float.threeParams, wrt: (self, 0, 1)) static func threeParamsT10(_ z: Float, t: Double) -> (self: Float, x: Float, y: Double) { let ret = Float(t) + z return (ret, ret, Double(ret)) } @transpose(of: Float.threeParams, wrt: (self, 0, 2)) static func threeParamsT11(_ y: Double, t: Double) -> (self: Float, x: Float, z: Float) { let ret = Float(t + y) return (ret, ret, ret) } @transpose(of: Float.threeParams, wrt: (self, 0, 1, 2)) static func threeParamsT12(t: Double) -> (self: Float, x: Float, y: Double, z: Float) { return (Float(t), Float(t), t, Float(t)) } } // Nested struct struct level1 { struct level2: Differentiable & AdditiveArithmetic { static var zero: Self { Self() } static func + (_: Self, _: Self) -> Self { Self() } static func - (_: Self, _: Self) -> Self { Self() } typealias TangentVector = Self mutating func move(along: TangentVector) {} func foo(x: Float) -> Float { return x } } struct level2_nondiff { func foo(x: Float) -> Float { return x } } } extension level1.level2 { @transpose(of: foo, wrt: 0) func trans(t: Float) -> Float { return t } @transpose(of: foo, wrt: (self, 0)) static func trans(t: Float) -> (self: level1.level2, x: Float) { return (level1.level2(), t) } } extension level1.level2_nondiff { // expected-error @+1 {{cannot transpose with respect to original parameter 'level1.level2_nondiff' that does not conform to 'Differentiable' and satisfy 'level1.level2_nondiff == level1.level2_nondiff.TangentVector'}} @transpose(of: level1.level2_nondiff.foo, wrt: (self, 0)) static func trans(t: Float) -> (self: level1.level2_nondiff, x: Float) { return (level1.level2_nondiff(), t) } } // Generics extension Float { func genericOneParamFloatOneParam<T: Differentiable & BinaryFloatingPoint>( x: T, y: Float ) -> Float where T == T.TangentVector { return y + Float(x) } @transpose(of: Float.genericOneParamFloatOneParam, wrt: 0) func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( y: Float, t: Float ) -> T where T == T.TangentVector { return T(y + t) } @transpose(of: Float.genericOneParamFloatOneParam, wrt: (0, 1)) func genericOneParamFloatOneParamT2<T: Differentiable & BinaryFloatingPoint>( t: Float ) -> (x: T, y: Float) where T == T.TangentVector { return (T(t), t) } @transpose(of: Float.genericOneParamFloatOneParam, wrt: (self, 1)) static func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( x: T, t: Float ) -> (self: Float, y: Float) where T == T.TangentVector { return (Float(x) + t, Float(x) + t) } @transpose(of: Float.genericOneParamFloatOneParam, wrt: (self, 0, 1)) static func genericOneParamFloatOneParamT1<T: Differentiable & BinaryFloatingPoint>( t: Float ) -> (self: Float, x: T, y: Float) where T == T.TangentVector { return (t, T(t), t) } } // Test non-`func` original declarations. struct Struct<T> {} extension Struct: Equatable where T: Equatable {} extension Struct: Differentiable & AdditiveArithmetic where T: Differentiable & AdditiveArithmetic { static var zero: Self { Self() } static func + (_: Self, _: Self) -> Self { Self() } static func - (_: Self, _: Self) -> Self { Self() } typealias TangentVector = Self mutating func move(along: TangentVector) {} } // Test computed properties. extension Struct { var computedProperty: Struct { self } } extension Struct where T: Differentiable & AdditiveArithmetic { @transpose(of: computedProperty, wrt: self) static func transposeProperty(t: Self) -> Self { t } } // Test initializers. extension Struct { init(_ x: Float) {} init(_ x: T, y: Float) {} } extension Struct where T: Differentiable, T == T.TangentVector { @transpose(of: init, wrt: 0) static func vjpInitX(_ x: Self) -> Float { fatalError() } @transpose(of: init(_:y:), wrt: (0, 1)) static func vjpInitXY(_ x: Self) -> (T, Float) { fatalError() } // Test instance transpose for static original intializer. // TODO(TF-1015): Add improved instance/static member mismatch error. // expected-error @+1 {{could not find function 'init' with expected type '<T where T : Differentiable, T == T.TangentVector> (Struct<T>) -> (Float) -> Struct<T>'}} @transpose(of: init, wrt: 0) func vjpInitStaticMismatch(_ x: Self) -> Float { fatalError() } } // Test subscripts. extension Struct { subscript() -> Self { get { self } set {} } subscript(float float: Float) -> Self { self } subscript<U: Differentiable>(x: U) -> Self { self } } extension Struct where T: Differentiable & AdditiveArithmetic { @transpose(of: subscript, wrt: self) static func vjpSubscript(t: Struct) -> Struct { t } @transpose(of: subscript(float:), wrt: self) static func vjpSubscriptLabelled(float: Float, t: Struct) -> Struct { t } @transpose(of: subscript(_:), wrt: self) static func vjpSubscriptGeneric<U: Differentiable>(x: U, t: Struct) -> Struct { t } } // Check that `@transpose` attribute rejects stored property original declarations. struct StoredProperty: Differentiable & AdditiveArithmetic { var stored: Float typealias TangentVector = StoredProperty static var zero: StoredProperty { StoredProperty(stored: 0) } static func + (_: StoredProperty, _: StoredProperty) -> StoredProperty { StoredProperty(stored: 0) } static func - (_: StoredProperty, _: StoredProperty) -> StoredProperty { StoredProperty(stored: 0) } // Note: `@transpose` support for instance members is currently too limited // to properly register a transpose for a non-`Self`-typed member. // expected-error @+1 {{could not find function 'stored' with expected type '(StoredProperty) -> () -> StoredProperty'}} @transpose(of: stored, wrt: self) static func vjpStored(v: Self) -> Self { fatalError() } } // Check that the self type of the method and the result type are the same when // transposing WRT self. Needed to make sure they are defined within the same // context. extension Float { func convertToDouble() -> Double { Double(self) } // Ok @transpose(of: convertToDouble, wrt: self) static func t1(t: Double) -> Float { Float(t) } } extension Double { // expected-error @+2 {{the transpose of an instance method must be a 'static' method in the same type when 'self' is a linearity parameter}} // expected-note @+1 {{the transpose is declared in 'Double' but the original function is declared in 'Float'}} @transpose(of: Float.convertToDouble, wrt: self) static func t1(t: Double) -> Float { Float(t) } }
apache-2.0
ab8f1bc0aa715ab40da6166c8607849c
27.383193
220
0.648271
3.440212
false
false
false
false
openHPI/xikolo-ios
iOS/Helpers/PersistenceManager/DownloadState.swift
1
950
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation enum DownloadState: String { case notDownloaded // not downloaded at all case pending // waiting for downloaded to start case downloading // download in progress case downloaded // downloaded and saved on disk static let didChangeNotification = Notification.Name("de.xikolo.ios.download.stateChanged") } enum DownloadProgress { static let didChangeNotification = Notification.Name("de.xikolo.ios.download.progressChanged") } enum DownloadNotificationKey { static let resourceId = "ResourceIdKey" static let downloadState = "ResourceDownloadStateKey" static let downloadProgress = "ResourceDownloadProgressKey" static let downloadType = "DownloadTypeKey" } enum LastVideoProgress { static let didChangeNotification = Notification.Name("de.xikolo.ios.video.lastPositionChanged") }
gpl-3.0
1a7f3b948a88cfdc4dbab2074fb2cb0d
30.633333
99
0.758693
4.54067
false
false
false
false
HorexC/CX-Swift-Advanced
Swift-Advanced-Demo/Dictionary.swift
1
2019
// // Dictionary.swift // Swift-Advanced-Demo // // Created by horex on 2017/8/2. // Copyright © 2017年 horex. All rights reserved. // import Foundation struct Person { var name: String var zipCode: Int var brithday: Date } extension Person: Equatable { static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.zipCode == rhs.zipCode && lhs.brithday == rhs.brithday } } extension Person: Hashable { var hashValue: Int { return name.hashValue ^ zipCode.hashValue ^ brithday.hashValue } } func DictionaryDemo() { enum Setting { case text(String) case int(Int) case bool(Bool) } let defaultSettings: [String: Setting] = [ "Airplane Mode": .bool(true), "Name": .text("My iPhone"), ] let _ = defaultSettings["Name"] var localizedSettings: [String: String] = [:] localizedSettings["Name"] = "Mein iPhone" localizedSettings["Do Not Disturb"] = "true" let _ = localizedSettings.updateValue("", forKey: "") let defaultAlarms = (1..<5).map{ (key: "Alarm\($0)", value: false) } let _ = Dictionary(defaultAlarms) let _ = defaultSettings.mapValues{ setting -> String in switch setting { case .text(let text): return text case .int(let number): return String(number) case .bool(let value): return String(value) } } } extension Dictionary { mutating func merge<S>(_ other: S) where S: Sequence, S.Iterator.Element == (key: Key, value: Value) { for (k, v) in other { self[k] = v } } init<S: Sequence>(_ sequence: S) where S.Iterator.Element == (key: Key, value: Value) { self = [:] self.merge(sequence) } func mapValues<NewValue>(transform: (Value) -> NewValue) -> [Key: NewValue] { return Dictionary<Key, NewValue>(map{ (key, value) in return (key, transform(value)) }) } }
mit
d69b0dd198cceb7b0644e2b1c98f1555
23.888889
106
0.580853
3.825427
false
false
false
false
GeolocalizatedNotification/FirstFramework
Framework/LayoutPreferences.swift
1
3348
// // LayoutPreferences.swift // Framework // // Created by Miguel Pimentel on 31/05/17. // Copyright © 2017 BEPiD. All rights reserved. // import UIKit public class LayoutPreferences: NSObject { // Set background color to status bar public static func setStatusBarColor(color: UIColor) { let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) { statusBar.backgroundColor = color } } // Set status bar text color to black public static func setStatusBarTextColorToBlack() { UIApplication.shared.statusBarStyle = .default } // Set status bar text colot to white public static func setStatusBarTextColorToWhite() { UIApplication.shared.statusBarStyle = .lightContent } // Set navigation bar background color, text colot e color for icons public static func navigationControllerProperties(color: UIColor, textColor: UIColor, iconColor: UIColor) { navigationControllerColor(color: color) textColorToNavbar(color: textColor) iconColorToNavbar(color: iconColor) } // Set navigation controller background color public static func navigationControllerColor(color: UIColor) { UINavigationBar.appearance().barTintColor = color } // Set text color in navbar public static func textColorToNavbar(color: UIColor) { UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: color] } // Set navbar icon color public static func iconColorToNavbar(color: UIColor) { UINavigationBar.appearance().tintColor = UIColor.white } // Hide navbarColor public static func hideNavigationBar(navigationController: UINavigationController) { navigationController.setNavigationBarHidden(true, animated: true) } // Set view background color public static func changeViewBackgroundColor(view: UIView, color: UIColor) { view.backgroundColor = color } } // Set possibility to hide keyboard when tapped around extension UIViewController { public func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } // Set possibility to use hexadecimal colors in UIColor extension UIColor { convenience public init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience public init(rgb: Int) { self.init( red: (rgb >> 16) & 0xFF, green: (rgb >> 8) & 0xFF, blue: rgb & 0xFF ) } }
mit
a6935b2dcfe49ee5566b1de996e4af09
27.853448
131
0.640872
5.086626
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/map annotations/TKUIAnnotations+TripKit.swift
1
3633
// // TKUIAnnotations+TripKit.swift // TripKitUI-iOS // // Created by Adrian Schönig on 24.01.19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import Foundation import TripKit // MARK: - TKModeCoordinate // MARK: TKUIModeAnnotation extension TKModeCoordinate: TKUIModeAnnotation { public var modeInfo: TKModeInfo! { return stopModeInfo } } // MARK: TKUIGlyphableAnnotation extension TKModeCoordinate: TKUIGlyphableAnnotation { public var glyphColor: TKColor? { return stopModeInfo.glyphColor } public var glyphImage: TKImage? { let image = stopModeInfo.image #if os(iOS) || os(tvOS) return image?.withRenderingMode(.alwaysTemplate) #else return image #endif } public var glyphImageURL: URL? { guard stopModeInfo.remoteImageIsTemplate else { return nil } return stopModeInfo.imageURL } public var glyphImageIsTemplate: Bool { return stopModeInfo.remoteImageIsTemplate } } // MARK: - TKStopCoordinate // MARK: TKUIStopAnnotation extension TKStopCoordinate: TKUIStopAnnotation {} // MARK: - Alert // MARK: TKUIImageAnnotation extension Alert: TKUIImageAnnotation { public var image: TKImage? { // Only show an image, if we have a location guard location != nil else { return nil } return TKInfoIcon.image(for: infoIconType, usage: .map) } } // MARK: - StopLocation // MARK: TKUIModeAnnotation extension StopLocation: TKUIModeAnnotation { public var modeInfo: TKModeInfo! { return stopModeInfo } public var clusterIdentifier: String? { return stopModeInfo?.identifier ?? "StopLocation" } } // MARK: TKUIStopAnnotation extension StopLocation: TKUIStopAnnotation {} // MARK: - StopVisits // MARK: TKUIModeAnnotation extension StopVisits: TKUIModeAnnotation { public var modeInfo: TKModeInfo! { return service.findModeInfo() ?? .unknown } public var clusterIdentifier: String? { return modeInfo?.identifier ?? "StopVisits" } } // MARK: TKUISemaphoreDisplayable extension StopVisits: TKUISemaphoreDisplayable { public var selectionIdentifier: String? { return nil } public var semaphoreMode: TKUISemaphoreView.Mode? { return .none } public var isTerminal: Bool { return false } } // MARK: - TKSegment // MARK: - TKUIModeAnnotation extension TKSegment: TKUIModeAnnotation { public var clusterIdentifier: String? { return nil } } // MARK: - TKUISemaphoreDisplayable extension TKSegment: TKUISemaphoreDisplayable { public var selectionIdentifier: String? { // Should match the definition in TripKit => Shape switch order { case .start: return "start" case .regular: return String(originalSegmentIncludingContinuation().templateHashCode) case .end: return "end" } } public var semaphoreMode: TKUISemaphoreView.Mode? { if let frequency = self.frequency?.intValue { if !isTerminal { return .headWithFrequency(minutes: frequency) } else { return .headOnly } } else { return trip.hideExactTimes ? .headOnly : .headWithTime(departureTime, timeZone, isRealTime: timesAreRealTime) } } public var canFlipImage: Bool { // only those pointing left or right return isSelfNavigating || self.modeIdentifier == TKTransportMode.autoRickshaw.modeIdentifier } public var isTerminal: Bool { return order == .end } } // MARK: - TKRegion.City extension TKRegion.City: TKUIImageAnnotation { public var image: TKImage? { return TKStyleManager.image(named: "icon-map-info-city") } public var imageURL: URL? { return nil } }
apache-2.0
bc560cad8e792268c5be076f4f72a58d
20.233918
115
0.707519
4.343301
false
false
false
false
jpadilla/rabbitmqapp
RabbitMQ/AppDelegate.swift
1
7880
// // AppDelegate.swift // RabbitMQ // // Created by José Padilla on 2/20/16. // Copyright © 2016 José Padilla. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var updater: SUUpdater! var paths = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) var documentsDirectory: AnyObject var dataPath: String var logPath: String var environment: [String: String] var task: NSTask = NSTask() var pipe: NSPipe = NSPipe() var file: NSFileHandle var statusBar = NSStatusBar.systemStatusBar() var statusBarItem: NSStatusItem = NSStatusItem() var menu: NSMenu = NSMenu() var statusMenuItem: NSMenuItem = NSMenuItem() var openUIMenuItem: NSMenuItem = NSMenuItem() var openLogsMenuItem: NSMenuItem = NSMenuItem() var docsMenuItem: NSMenuItem = NSMenuItem() var aboutMenuItem: NSMenuItem = NSMenuItem() var versionMenuItem: NSMenuItem = NSMenuItem() var quitMenuItem: NSMenuItem = NSMenuItem() var updatesMenuItem: NSMenuItem = NSMenuItem() override init() { self.file = self.pipe.fileHandleForReading self.documentsDirectory = self.paths[0] self.dataPath = documentsDirectory.stringByAppendingPathComponent("RabbitMQData") self.logPath = documentsDirectory.stringByAppendingPathComponent("RabbitMQData/Logs") self.environment = [ "HOME": NSProcessInfo.processInfo().environment["HOME"]!, "RABBITMQ_MNESIA_BASE": self.dataPath, "RABBITMQ_LOG_BASE": self.logPath, "RABBITMQ_ENABLED_PLUGINS_FILE": self.dataPath + "/enabled_plugins", "RABBITMQ_NODENAME": "rabbit@localhost", "RABBITMQ_NODE_IP_ADDRESS": "127.0.0.1" ] super.init() } func startServer() { self.task = NSTask() self.pipe = NSPipe() self.file = self.pipe.fileHandleForReading if let path = NSBundle.mainBundle().pathForResource("rabbitmq-server", ofType: "", inDirectory: "Vendor/rabbitmq/sbin") { self.task.launchPath = path } self.task.environment = self.environment self.task.standardOutput = self.pipe print("Run rabbitmq-server") self.task.launch() print("Enabling rabbitmq_management plugin") self.enablePlugin("rabbitmq_management") } func enablePlugin(plugin: String) { let task = NSTask() if let path = NSBundle.mainBundle().pathForResource("rabbitmq-plugins", ofType: "", inDirectory: "Vendor/rabbitmq/sbin") { task.launchPath = path } task.arguments = ["enable", plugin] task.environment = self.environment print("Run rabbitmq-plugins enable") task.launch() } func stopServer() { let task = NSTask() if let path = NSBundle.mainBundle().pathForResource("rabbitmqctl", ofType: "", inDirectory: "Vendor/rabbitmq/sbin") { task.launchPath = path } task.arguments = ["stop"] task.environment = self.environment print("Run rabbitmqctl stop") task.launch() let data: NSData = self.file.readDataToEndOfFile() self.file.closeFile() let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String print(output) } func openUI(sender: AnyObject) { if let url: NSURL = NSURL(string: "http://localhost:15672") { NSWorkspace.sharedWorkspace().openURL(url) } } func openDocumentationPage(send: AnyObject) { if let url: NSURL = NSURL(string: "https://jpadilla.github.io/rabbitmqapp/") { NSWorkspace.sharedWorkspace().openURL(url) } } func openLogsDirectory(send: AnyObject) { NSWorkspace.sharedWorkspace().openFile(self.logPath) } func createDirectories() { if (!NSFileManager.defaultManager().fileExistsAtPath(self.dataPath)) { do { try NSFileManager.defaultManager() .createDirectoryAtPath(self.dataPath, withIntermediateDirectories: false, attributes: nil) } catch { print("Something went wrong creating dataPath") } } if (!NSFileManager.defaultManager().fileExistsAtPath(self.logPath)) { do { try NSFileManager.defaultManager() .createDirectoryAtPath(self.logPath, withIntermediateDirectories: false, attributes: nil) } catch { print("Something went wrong creating logPath") } } print("RabbitMQ data directory: \(self.dataPath)") print("RabbitMQ logs directory: \(self.logPath)") } func checkForUpdates(sender: AnyObject?) { print("Checking for updates") self.updater.checkForUpdates(sender) } func setupSystemMenuItem() { // Add statusBarItem statusBarItem = statusBar.statusItemWithLength(-1) statusBarItem.menu = menu let icon = NSImage(named: "logo") icon!.template = true icon!.size = NSSize(width: 18, height: 18) statusBarItem.image = icon // Add version to menu versionMenuItem.title = "RabbitMQ" if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String? { versionMenuItem.title = "RabbitMQ v\(version)" } menu.addItem(versionMenuItem) // Add actionMenuItem to menu statusMenuItem.title = "Running on port 5672" menu.addItem(statusMenuItem) // Add separator menu.addItem(NSMenuItem.separatorItem()) // Add open management ui to menu openUIMenuItem.title = "Open Management UI" openUIMenuItem.action = Selector("openUI:") menu.addItem(openUIMenuItem) // Add open logs to menu openLogsMenuItem.title = "Open logs directory" openLogsMenuItem.action = Selector("openLogsDirectory:") menu.addItem(openLogsMenuItem) // Add separator menu.addItem(NSMenuItem.separatorItem()) // Add docs to menu docsMenuItem.title = "Documentation" docsMenuItem.action = Selector("openDocumentationPage:") menu.addItem(docsMenuItem) // Add check for updates to menu updatesMenuItem.title = "Check for updates" updatesMenuItem.action = Selector("checkForUpdates:") menu.addItem(updatesMenuItem) // Add about to menu aboutMenuItem.title = "About" aboutMenuItem.action = Selector("orderFrontStandardAboutPanel:") menu.addItem(aboutMenuItem) // Add separator menu.addItem(NSMenuItem.separatorItem()) // Add quitMenuItem to menu quitMenuItem.title = "Quit" quitMenuItem.action = Selector("terminate:") menu.addItem(quitMenuItem) } func appExists(appName: String) -> Bool { let found = [ "/Applications/\(appName).app", "/Applications/Utilities/\(appName).app", "\(NSHomeDirectory())/Applications/\(appName).app" ].map { return NSFileManager.defaultManager().fileExistsAtPath($0) }.reduce(false) { if $0 == false && $1 == false { return false; } else { return true; } } return found } func applicationDidFinishLaunching(aNotification: NSNotification) { createDirectories() setupSystemMenuItem() startServer() } func applicationWillTerminate(notification: NSNotification) { stopServer() } }
mit
d174d7c2299abe6c9ffab49d84e36167
31.155102
130
0.624222
5.039667
false
false
false
false
slecoustre/PhotoMozaic
Classes/PhotoMozaic.swift
1
10905
// // PhotoMozaic.swift // PhotoMozaic // // Created by Stephane on 26/06/2015. // Copyright (c) 2015 fettle. All rights reserved. // import UIKit @IBDesignable public class PhotoMozaic: UIView { @IBInspectable public var textColor: UIColor = UIColor.whiteColor() { didSet { self.numberLabel.textColor = self.textColor } } @IBInspectable public var backgroundColorLabel: UIColor = UIColor.blackColor().colorWithAlphaComponent(0.70) { didSet { self.numberLabel.backgroundColor = self.backgroundColorLabel } } @IBInspectable public var margin: UInt = 0 { didSet { self.createConstraints() } } public var font: UIFont = UIFont.systemFontOfSize(40) public var photos: [PhotoMozaicItem] = [] { didSet { self.createConstraints() } } public var contentPhotoMode: UIViewContentMode = UIViewContentMode.ScaleAspectFill { didSet { self.img1.contentMode = self.contentPhotoMode self.img2.contentMode = self.contentPhotoMode self.img3.contentMode = self.contentPhotoMode self.img4.contentMode = self.contentPhotoMode } } public var delegate: PhotoMozaicDelegate? // MARK: - init override public init(frame: CGRect) { super.init(frame: frame) self.createSubviews() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.createSubviews() } // MARK: - private fields private var numberLabel: UILabel! private var img1: UIImageView! private var img2: UIImageView! private var img3: UIImageView! private var img4: UIImageView! // MARK: - Action TapGesture func img1TapHandler(gestureRecognizer: UIGestureRecognizer) { self.delegate?.photoMozaicSelected(0, sender: self.img1) } func img2TapHandler(gestureRecognizer: UIGestureRecognizer) { self.delegate?.photoMozaicSelected(1, sender: self.img2) } func img3TapHandler(gestureRecognizer: UIGestureRecognizer) { self.delegate?.photoMozaicSelected(2, sender: self.img3) } func img4TapHandler(gestureRecognizer: UIGestureRecognizer) { self.delegate?.photoMozaicSelected(3, sender: self.img4) } // MARK: - private method private func createSubviews() { self.img1 = UIImageView() self.img1.clipsToBounds = true self.img1.translatesAutoresizingMaskIntoConstraints = false self.img1.contentMode = self.contentPhotoMode self.img1.userInteractionEnabled = true self.addSubview(self.img1) self.img1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("img1TapHandler:"))) self.img2 = UIImageView() self.img2.clipsToBounds = true self.img2.translatesAutoresizingMaskIntoConstraints = false self.img2.contentMode = self.contentPhotoMode self.img2.userInteractionEnabled = true self.addSubview(self.img2) self.img2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("img2TapHandler:"))) self.img3 = UIImageView() self.img3.clipsToBounds = true self.img3.translatesAutoresizingMaskIntoConstraints = false self.img3.contentMode = self.contentPhotoMode self.img3.userInteractionEnabled = true self.addSubview(self.img3) self.img3.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("img3TapHandler:"))) self.img4 = UIImageView() self.img4.clipsToBounds = true self.img4.translatesAutoresizingMaskIntoConstraints = false self.img4.contentMode = self.contentPhotoMode self.img4.userInteractionEnabled = true self.addSubview(self.img4) self.img4.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("img4TapHandler:"))) self.numberLabel = UILabel() self.numberLabel.font = self.font self.numberLabel.textColor = self.textColor self.numberLabel.translatesAutoresizingMaskIntoConstraints = false self.numberLabel.textAlignment = NSTextAlignment.Center self.numberLabel.backgroundColor = self.backgroundColorLabel self.numberLabel.userInteractionEnabled = true self.addSubview(self.numberLabel) self.numberLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("img4TapHandler:"))) self.createConstraints() } private func createConstraints() { self.removeAllConstraints(self) let views: [String: UIView] = ["img1":img1, "img2":img2, "img3":img3, "img4":img4, "lbl": self.numberLabel] if self.photos.count > 0 { self.img1.setPhotoMozaicItem(self.photos[0]) } if self.photos.count > 1 { self.img2.setPhotoMozaicItem(self.photos[1]) } if self.photos.count > 2 { self.img3.setPhotoMozaicItem(self.photos[2]) } if self.photos.count > 3 { self.img4.setPhotoMozaicItem(self.photos[3]) } var cmargin = "" if self.margin > 0 { cmargin = "-(\(self.margin))-" } switch self.photos.count { case 1: self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[img1]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img1]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) break case 2: self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[img1]\(cmargin)[img2(==img1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img1]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img2]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) break case 3: self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[img1]\(cmargin)[img2(==img1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[img1]\(cmargin)[img3(==img1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img1]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img2]\(cmargin)[img3(==img2)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) break default: if self.photos.count > 3{ self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[img1]\(cmargin)[img2(==img1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[img1]\(cmargin)[img3]\(cmargin)[img4(==img3)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img1]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img2]\(cmargin)[img3(==img2)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[img2]\(cmargin)[img4(==img2)]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[img3]\(cmargin)[lbl]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[img2]\(cmargin)[lbl]|", options: NSLayoutFormatOptions(), metrics: nil, views: views)) } break } if self.photos.count > 4 { self.numberLabel.text = "+\(self.photos.count-4)" self.numberLabel.hidden = false } else { self.numberLabel.text = "" self.numberLabel.hidden = true } } private func removeAllConstraints(view: UIView) { for child in view.subviews { self.removeAllConstraints(child ) } view.removeConstraints(view.constraints) } private func imageWithColor(color: UIColor, size: CGSize) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } // MARK: - prepareForInterfaceBuilder override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.photos = [ PhotoMozaicItem(image: imageWithColor(UIColor.purpleColor(), size: CGSize(width: 10, height: 10))), PhotoMozaicItem(image: imageWithColor(UIColor.yellowColor(), size: CGSize(width: 10, height: 10))), PhotoMozaicItem(image: imageWithColor(UIColor.blueColor(), size: CGSize(width: 10, height: 10))), PhotoMozaicItem(image: imageWithColor(UIColor.greenColor(), size: CGSize(width: 10, height: 10))), PhotoMozaicItem(url: ""), PhotoMozaicItem(url: ""), PhotoMozaicItem(url: ""), PhotoMozaicItem(url: ""), PhotoMozaicItem(url: ""), PhotoMozaicItem(url: "") ] self.createConstraints() self.img1.contentMode = UIViewContentMode.ScaleToFill self.img2.contentMode = UIViewContentMode.ScaleToFill self.img3.contentMode = UIViewContentMode.ScaleToFill self.img4.contentMode = UIViewContentMode.ScaleToFill } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
ec5438182e3e5e3114c4c1855fffe022
41.267442
198
0.651628
5.187916
false
false
false
false
PureSwift/LittleCMS
Sources/LittleCMS/ColorTransform.swift
1
2587
// // ColorTransform.swift // LittleCMS // // Created by Alsey Coleman Miller on 6/3/17. // // import struct Foundation.Data import CLCMS public final class ColorTransform { // MARK: - Properties internal let internalPointer: cmsHTRANSFORM public let context: Context? /// Other CMS object wrappers / reference-backed value types to retain (besides the context) private let retain: [Any] // MARK: - Initialization deinit { cmsDeleteTransform(internalPointer) } /// Creates a color transform for translating bitmaps. public init?(input: (profile: Profile, format: cmsUInt32Number), output: (profile: Profile, format: cmsUInt32Number), intent: Intent, flags: cmsUInt32Number = 0, context: Context? = nil) { guard let internalPointer = cmsCreateTransformTHR(context?.internalPointer, input.profile.internalReference.reference.internalPointer, input.format, output.profile.internalReference.reference.internalPointer, output.format, intent.rawValue, flags) else { return nil } self.internalPointer = internalPointer self.context = context self.retain = [input.profile, output.profile] } // MARK: - Methods /// Translates bitmaps according of parameters setup when creating the color transform. public func transform(_ bitmap: Data) -> Data { let internalPointer = self.internalPointer var output = Data(count: bitmap.count) bitmap.withUnsafeBytes { (inputBytes: UnsafePointer<UInt8>) in let inputBytes = UnsafeRawPointer(inputBytes) output.withUnsafeMutableBytes { (outputBytes: UnsafeMutablePointer<UInt8>) in let outputBytes = UnsafeMutableRawPointer(outputBytes) cmsDoTransform(internalPointer, inputBytes, outputBytes, cmsUInt32Number(bitmap.count)) } } return output } } extension ColorTransform: ContextualHandle { static var cmsGetContextID: cmsGetContextIDFunction { return cmsGetTransformContextID } }
mit
18c5f483bc628e480ff4b8acc261eaf1
32.166667
112
0.557016
5.800448
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/MutablePersistableRecordChangesTests.swift
1
21993
import XCTest import GRDB private struct Player: FetchableRecord, MutablePersistableRecord, Codable { static let databaseTableName = "players" var id: Int64? var name: String? var score: Int? var creationDate: Date? init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) { self.id = id self.name = name self.score = score self.creationDate = creationDate } mutating func willInsert(_ db: Database) throws { if creationDate == nil { creationDate = Date() } } mutating func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID } } class MutablePersistableRecordChangesTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in t.column("id", .integer).primaryKey() t.column("name", .text) t.column("score", .integer) t.column("creationDate", .datetime) } } } func testDegenerateDatabaseEqualsWithSelf() throws { struct DegenerateRecord: MutablePersistableRecord { static let databaseTableName = "degenerated" func encode(to container: inout PersistenceContainer) { } } let record = DegenerateRecord() XCTAssertTrue(record.databaseEquals(record)) try XCTAssertTrue(record.databaseChanges(from: record).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in // table must exist try db.create(table: DegenerateRecord.databaseTableName) { t in t.autoIncrementedPrimaryKey("id") } let totalChangesCount = db.totalChangesCount try XCTAssertFalse(record.updateChanges(db, from: record)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) } } func testDatabaseEqualsWithSelf() throws { do { let player = Player(id: nil, name: nil, score: nil, creationDate: nil) XCTAssertTrue(player.databaseEquals(player)) try XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertFalse(player.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) } } do { let player = Player(id: 1, name: "foo", score: 42, creationDate: Date()) XCTAssertTrue(player.databaseEquals(player)) try XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertFalse(player.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) } } } func testRecordValueChange() throws { let dbQueue = try makeDatabaseQueue() var player = Player(id: 1, name: "Arthur", score: nil, creationDate: nil) try dbQueue.inDatabase { db in try player.insert(db) } do { // non-nil vs. non-nil var newPlayer = player newPlayer.name = "Bobby" XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Bobby\' WHERE \"id\"=1") } } do { // non-nil vs. nil var newPlayer = player newPlayer.name = nil XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=NULL WHERE \"id\"=1") } } do { // nil vs. non-nil var newPlayer = player newPlayer.score = 41 XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=41 WHERE \"id\"=1") } } do { // multiple changes var newPlayer = player newPlayer.name = "Bobby" newPlayer.score = 41 XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = try newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) XCTAssertEqual(changes["score"]!, .null) try dbQueue.inDatabase { db in let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: player)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) let fetchedPlayer = try Player.fetchOne(db, key: player.id) XCTAssertEqual(fetchedPlayer?.name, newPlayer.name) XCTAssertEqual(fetchedPlayer?.score, newPlayer.score) } } } func testDatabaseEqualsWithDifferentTypesAndDifferentWidth() throws { // Mangle column case as well, for fun ;-) struct NarrowPlayer: MutablePersistableRecord, Codable { static let databaseTableName = "players" var ID: Int64? var NAME: String? } let dbQueue = try makeDatabaseQueue() do { var oldPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") let newPlayer = Player(id: 1, name: "Arthur", score: 41, creationDate: nil) let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) try dbQueue.inTransaction { db in try oldPlayer.insert(db) let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=41 WHERE \"id\"=1") return .rollback } } do { var oldPlayer = NarrowPlayer(ID: 1, NAME: "Bobby") let newPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil) let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Bobby".databaseValue) XCTAssertEqual(changes["score"]!, .null) try dbQueue.inTransaction { db in try oldPlayer.insert(db) let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) let fetchedPlayer = try Player.fetchOne(db, key: newPlayer.id) XCTAssertEqual(fetchedPlayer?.name, newPlayer.name) XCTAssertEqual(fetchedPlayer?.score, newPlayer.score) return .rollback } } do { let oldPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertTrue(changes.isEmpty) try dbQueue.inTransaction { db in let totalChangesCount = db.totalChangesCount try XCTAssertFalse(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) return .rollback } } do { let oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur") let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertTrue(changes.isEmpty) try dbQueue.inTransaction { db in let totalChangesCount = db.totalChangesCount try XCTAssertFalse(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount) return .rollback } } do { var oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil) let newPlayer = NarrowPlayer(ID: 1, NAME: "Bobby") let changes = try newPlayer.databaseChanges(from: oldPlayer) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["NAME"]!, "Arthur".databaseValue) try dbQueue.inTransaction { db in try oldPlayer.insert(db) let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"='Bobby' WHERE \"id\"=1") return .rollback } } } func testUpdateChangesWithRecord() throws { class MyRecord: Record { var id: Int64? var firstName: String? var lastName: String? init(id: Int64?, firstName: String?, lastName: String?) { self.id = id self.firstName = firstName self.lastName = lastName super.init() } override class var databaseTableName: String { "myRecord" } enum Columns: String, ColumnExpression { case id, firstName, lastName } required init(row: Row) throws { id = row[Columns.id] firstName = row[Columns.firstName] lastName = row[Columns.lastName] try super.init(row: row) } override func encode(to container: inout PersistenceContainer) throws { container[Columns.id] = id container[Columns.firstName] = firstName container[Columns.lastName] = lastName } override func didInsert(_ inserted: InsertionSuccess) { super.didInsert(inserted) id = inserted.rowID } } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "myRecord") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) } var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { sqlQueries = [] let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = nil } XCTAssertEqual(record.firstName, nil) XCTAssertEqual(record.lastName, "Smith") XCTAssertTrue(modified) XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" } XCTAssertEqual(record.firstName, "Bob") XCTAssertEqual(record.lastName, "Johnson") XCTAssertTrue(modified) XCTAssertTrue([ "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] .contains(lastSQLQuery)) } } } func testUpdateChangesWithNonRecordClass() throws { class MyRecord: Codable, PersistableRecord { var id: Int64? var firstName: String? var lastName: String? init(id: Int64?, firstName: String?, lastName: String?) { self.id = id self.firstName = firstName self.lastName = lastName } func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID } } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "myRecord") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) } var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { sqlQueries = [] let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = nil } XCTAssertEqual(record.firstName, nil) XCTAssertEqual(record.lastName, "Smith") XCTAssertTrue(modified) XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" } XCTAssertEqual(record.firstName, "Bob") XCTAssertEqual(record.lastName, "Johnson") XCTAssertTrue(modified) XCTAssertTrue([ "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] .contains(lastSQLQuery)) } } } func testUpdateChangesWithMutableStruct() throws { struct MyRecord: Codable, MutablePersistableRecord { var id: Int64? var firstName: String? var lastName: String? mutating func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID } } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "myRecord") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) } var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { sqlQueries = [] let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = nil } XCTAssertEqual(record.firstName, nil) XCTAssertEqual(record.lastName, "Smith") XCTAssertTrue(modified) XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" } XCTAssertEqual(record.firstName, "Bob") XCTAssertEqual(record.lastName, "Johnson") XCTAssertTrue(modified) XCTAssertTrue([ "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] .contains(lastSQLQuery)) } } } func testUpdateChangesWithImmutableStruct() throws { struct MyRecord: Codable, PersistableRecord { var id: Int64 var firstName: String? var lastName: String? } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "myRecord") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) } var record = MyRecord(id: 1, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { sqlQueries = [] let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = nil } XCTAssertEqual(record.firstName, nil) XCTAssertEqual(record.lastName, "Smith") XCTAssertTrue(modified) XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") } do { sqlQueries = [] let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" } XCTAssertEqual(record.firstName, "Bob") XCTAssertEqual(record.lastName, "Johnson") XCTAssertTrue(modified) XCTAssertTrue([ "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] .contains(lastSQLQuery)) } } } }
mit
1a9b6fd961722cf55924127de6017a1d
37.994681
109
0.515437
5.661004
false
false
false
false
stripysock/SwiftGen
Pods/Commander/Commander/ArgumentDescription.swift
2
7312
public enum ArgumentType { case Argument case Option } public protocol ArgumentDescriptor { typealias ValueType /// The arguments name var name:String { get } /// The arguments description var description:String? { get } var type:ArgumentType { get } /// Parse the argument func parse(parser:ArgumentParser) throws -> ValueType } extension ArgumentConvertible { init(string: String) throws { try self.init(parser: ArgumentParser(arguments: [string])) } } public class VaradicArgument<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = [T] public let name: String public let description: String? public var type: ArgumentType { return .Argument } public init(_ name: String, description: String? = nil) { self.name = name self.description = description } public func parse(parser: ArgumentParser) throws -> ValueType { return try Array<T>(parser: parser) } } public class Argument<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = T public typealias Validator = ValueType throws -> ValueType public let name:String public let description:String? public let validator:Validator? public var type:ArgumentType { return .Argument } public init(_ name:String, description:String? = nil, validator: Validator? = nil) { self.name = name self.description = description self.validator = validator } public func parse(parser:ArgumentParser) throws -> ValueType { let value: T do { value = try T(parser: parser) } catch ArgumentError.MissingValue { throw ArgumentError.MissingValue(argument: name) } catch { throw error } if let validator = validator { return try validator(value) } return value } } public class Option<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = T public typealias Validator = ValueType throws -> ValueType public let name:String public let flag:Character? public let description:String? public let `default`:ValueType public var type:ArgumentType { return .Option } public let validator:Validator? public init(_ name:String, _ `default`:ValueType, flag:Character? = nil, description:String? = nil, validator: Validator? = nil) { self.name = name self.flag = flag self.description = description self.`default` = `default` self.validator = validator } public func parse(parser:ArgumentParser) throws -> ValueType { if let value = try parser.shiftValueForOption(name) { let value = try T(string: value) if let validator = validator { return try validator(value) } return value } if let flag = flag { if let value = try parser.shiftValueForFlag(flag) { let value = try T(string: value) if let validator = validator { return try validator(value) } return value } } return `default` } } public class Options<T : ArgumentConvertible> : ArgumentDescriptor { public typealias ValueType = [T] public let name:String public let description:String? public let count:Int public let `default`:ValueType public var type:ArgumentType { return .Option } public init(_ name:String, _ `default`:ValueType, count: Int, description:String? = nil) { self.name = name self.`default` = `default` self.count = count self.description = description } public func parse(parser:ArgumentParser) throws -> ValueType { let values = try parser.shiftValuesForOption(name, count: count) return try values?.map { try T(string: $0) } ?? `default` } } public class Flag : ArgumentDescriptor { public typealias ValueType = Bool public let name:String public let flag:Character? public let disabledName:String public let disabledFlag:Character? public let description:String? public let `default`:ValueType public var type:ArgumentType { return .Option } public init(_ name:String, flag:Character? = nil, disabledName:String? = nil, disabledFlag:Character? = nil, description:String? = nil, `default`:Bool = false) { self.name = name self.disabledName = disabledName ?? "no-\(name)" self.flag = flag self.disabledFlag = disabledFlag self.description = description self.`default` = `default` } public func parse(parser:ArgumentParser) throws -> ValueType { if parser.hasOption(disabledName) { return false } if parser.hasOption(name) { return true } if let flag = flag { if parser.hasFlag(flag) { return true } } if let disabledFlag = disabledFlag { if parser.hasFlag(disabledFlag) { return false } } return `default` } } class BoxedArgumentDescriptor { let name:String let description:String? let `default`:String? let type:ArgumentType init<T : ArgumentDescriptor>(value:T) { name = value.name description = value.description type = value.type if let value = value as? Flag { `default` = value.`default`.description } else { // TODO, default for Option and Options `default` = nil } } } class UsageError : ErrorType, CustomStringConvertible { let message: String let help: Help init(_ message: String, _ help: Help) { self.message = message self.help = help } var description: String { return [message, help.description].filter { !$0.isEmpty }.joinWithSeparator("\n\n") } } class Help : ErrorType, CustomStringConvertible { let command:String? let group:Group? let descriptors:[BoxedArgumentDescriptor] init(_ descriptors:[BoxedArgumentDescriptor], command:String? = nil, group:Group? = nil) { self.command = command self.group = group self.descriptors = descriptors } func reraise(command:String? = nil) -> Help { if let oldCommand = self.command, newCommand = command { return Help(descriptors, command: "\(newCommand) \(oldCommand)") } return Help(descriptors, command: command ?? self.command) } var description:String { var output = [String]() let arguments = descriptors.filter { $0.type == ArgumentType.Argument } let options = descriptors.filter { $0.type == ArgumentType.Option } if let command = command { let args = arguments.map { $0.name } let usage = ([command] + args).joinWithSeparator(" ") output.append("Usage:") output.append("") output.append(" \(usage)") output.append("") } if let group = group { output.append("Commands:") output.append("") for command in group.commands { if let description = command.description { output.append(" + \(command.name) - \(description)") } else { output.append(" + \(command.name)") } } output.append("") } if !options.isEmpty { output.append("Options:") for option in options { // TODO: default, [default: `\(`default`)`] if let description = option.description { output.append(" --\(option.name) - \(description)") } else { output.append(" --\(option.name)") } } } return output.joinWithSeparator("\n") } }
mit
a1c2846b22203a8a984fbb7fbf84d7d8
24.301038
163
0.656865
4.313864
false
false
false
false
mzaks/FlatBuffersSwiftPerformanceTest
FBTest/bench_decode_direct4.swift
1
2557
// // bench_decode_direct4.swift // FBTest // // Created by Maxim Zaks on 27.09.16. // Copyright © 2016 maxim.zaks. All rights reserved. // import Foundation public struct FooBarContainerDirect<T : FBReader> : Hashable { private let reader : T private let myOffset : Offset init(reader: T, myOffset: Offset){ self.reader = reader self.myOffset = myOffset } public init?(_ reader: T) { self.reader = reader guard let offest = reader.rootObjectOffset else { return nil } self.myOffset = offest } public var listCount : Int { return reader.getVectorLength(reader.getOffset(myOffset, propertyIndex: 0)) } public func getListElement(atIndex index : Int) -> FooBarDirect<T>? { let offsetList = reader.getOffset(myOffset, propertyIndex: 0) if let ofs = reader.getVectorOffsetElement(offsetList, index: index) { return FooBarDirect(reader: reader, myOffset: ofs) } return nil } public var initialized : Bool { get { return reader.get(myOffset, propertyIndex: 1, defaultValue: false) } } public var fruit : Enum? { get { return Enum(rawValue: reader.get(myOffset, propertyIndex: 2, defaultValue: Enum.Apples.rawValue)) } } public var location : UnsafeBufferPointer<UInt8>? { get { return reader.getStringBuffer(reader.getOffset(myOffset, propertyIndex:3)) } } public var hashValue: Int { return Int(myOffset) } } public func ==<T>(t1: FooBarContainerDirect<T>, t2: FooBarContainerDirect<T>) -> Bool { return t1.reader.isEqual(t2.reader) && t1.myOffset == t2.myOffset } public struct FooBarDirect<T: FBReader> : Hashable { private let reader : T private let myOffset : Offset init(reader: T, myOffset: Offset){ self.reader = reader self.myOffset = myOffset } public var sibling : Bar? { get { return reader.get(myOffset, propertyIndex: 0)} } public var name : UnsafeBufferPointer<UInt8>? { get { return reader.getStringBuffer(reader.getOffset(myOffset, propertyIndex:1)) } } public var rating : Float64 { get { return reader.get(myOffset, propertyIndex: 2, defaultValue: 0) } } public var postfix : UInt8 { get { return reader.get(myOffset, propertyIndex: 3, defaultValue: 0) } } public var hashValue: Int { return Int(myOffset) } } public func ==<T>(t1: FooBarDirect<T>, t2: FooBarDirect<T>) -> Bool { return t1.reader.isEqual(t2.reader) && t1.myOffset == t2.myOffset }
mit
a2c176ffc0981a0aa0730c8bbcc63c15
36.043478
140
0.657668
4.00627
false
false
false
false
mohitathwani/swift-corelibs-foundation
Foundation/NSScanner.swift
1
25613
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation open class Scanner: NSObject, NSCopying { internal var _scanString: String internal var _skipSet: CharacterSet? internal var _invertedSkipSet: CharacterSet? internal var _scanLocation: Int open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return Scanner(string: string) } open var string: String { return _scanString } open var scanLocation: Int { get { return _scanLocation } set { if newValue > string.length { fatalError("Index \(newValue) beyond bounds; string length \(string.length)") } _scanLocation = newValue } } /*@NSCopying*/ open var charactersToBeSkipped: CharacterSet? { get { return _skipSet } set { _skipSet = newValue _invertedSkipSet = nil } } internal var invertedSkipSet: CharacterSet? { if let inverted = _invertedSkipSet { return inverted } else { if let set = charactersToBeSkipped { _invertedSkipSet = set.inverted return _invertedSkipSet } return nil } } open var caseSensitive: Bool = false open var locale: Locale? internal static let defaultSkipSet = CharacterSet.whitespacesAndNewlines public init(string: String) { _scanString = string _skipSet = Scanner.defaultSkipSet _scanLocation = 0 } } internal struct _NSStringBuffer { var bufferLen: Int var bufferLoc: Int var string: NSString var stringLen: Int var _stringLoc: Int var buffer = Array<unichar>(repeating: 0, count: 32) var curChar: unichar? static let EndCharacter = unichar(0xffff) init(string: String, start: Int, end: Int) { self.string = string._bridgeToObjectiveC() _stringLoc = start stringLen = end if _stringLoc < stringLen { bufferLen = min(32, stringLen - _stringLoc) let range = NSMakeRange(_stringLoc, bufferLen) bufferLoc = 1 buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in self.string.getCharacters(ptr.baseAddress!, range: range) }) curChar = buffer[0] } else { bufferLen = 0 bufferLoc = 1 curChar = _NSStringBuffer.EndCharacter } } init(string: NSString, start: Int, end: Int) { self.string = string _stringLoc = start stringLen = end if _stringLoc < stringLen { bufferLen = min(32, stringLen - _stringLoc) let range = NSMakeRange(_stringLoc, bufferLen) bufferLoc = 1 buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in self.string.getCharacters(ptr.baseAddress!, range: range) }) curChar = buffer[0] } else { bufferLen = 0 bufferLoc = 1 curChar = _NSStringBuffer.EndCharacter } } var currentCharacter: unichar { return curChar! } var isAtEnd: Bool { return curChar == _NSStringBuffer.EndCharacter } mutating func fill() { bufferLen = min(32, stringLen - _stringLoc) let range = NSMakeRange(_stringLoc, bufferLen) buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in string.getCharacters(ptr.baseAddress!, range: range) }) bufferLoc = 1 curChar = buffer[0] } mutating func advance() { if bufferLoc < bufferLen { /*buffer is OK*/ curChar = buffer[bufferLoc] bufferLoc += 1 } else if (_stringLoc + bufferLen < stringLen) { /* Buffer is empty but can be filled */ _stringLoc += bufferLen fill() } else { /* Buffer is empty and we're at the end */ bufferLoc = bufferLen + 1 curChar = _NSStringBuffer.EndCharacter } } mutating func rewind() { if bufferLoc > 1 { /* Buffer is OK */ bufferLoc -= 1 curChar = buffer[bufferLoc - 1] } else if _stringLoc > 0 { /* Buffer is empty but can be filled */ bufferLoc = min(32, _stringLoc) bufferLen = bufferLoc _stringLoc -= bufferLen let range = NSMakeRange(_stringLoc, bufferLen) buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in string.getCharacters(ptr.baseAddress!, range: range) }) curChar = buffer[bufferLoc - 1] } else { bufferLoc = 0 curChar = _NSStringBuffer.EndCharacter } } mutating func skip(_ skipSet: CharacterSet?) { if let set = skipSet { while set.contains(UnicodeScalar(currentCharacter)!) && !isAtEnd { advance() } } } var location: Int { get { return _stringLoc + bufferLoc - 1 } mutating set { if newValue < _stringLoc || newValue >= _stringLoc + bufferLen { if newValue < 16 { /* Get the first NSStringBufferSize chars */ _stringLoc = 0 } else if newValue > stringLen - 16 { /* Get the last NSStringBufferSize chars */ _stringLoc = stringLen < 32 ? 0 : stringLen - 32 } else { _stringLoc = newValue - 16 /* Center around loc */ } fill() } bufferLoc = newValue - _stringLoc curChar = buffer[bufferLoc] bufferLoc += 1 } } } private func isADigit(_ ch: unichar) -> Bool { struct Local { static let set = CharacterSet.decimalDigits } return Local.set.contains(UnicodeScalar(ch)!) } // This is just here to allow just enough generic math to handle what is needed for scanning an abstract integer from a string, perhaps these should be on IntegerType? internal protocol _BitShiftable { static func >>(lhs: Self, rhs: Self) -> Self static func <<(lhs: Self, rhs: Self) -> Self } internal protocol _IntegerLike : Integer, _BitShiftable { init(_ value: Int) static var max: Self { get } static var min: Self { get } } extension Int : _IntegerLike { } extension Int32 : _IntegerLike { } extension Int64 : _IntegerLike { } extension UInt32 : _IntegerLike { } extension UInt64 : _IntegerLike { } private func numericValue(_ ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else { return __CFCharDigitValue(UniChar(ch)) } } private func numericOrHexValue(_ ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else if (ch >= unichar(unicodeScalarLiteral: "A") && ch <= unichar(unicodeScalarLiteral: "F")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "A")) } else if (ch >= unichar(unicodeScalarLiteral: "a") && ch <= unichar(unicodeScalarLiteral: "f")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "a")) } else { return -1 } } private func decimalSep(_ locale: Locale?) -> String { if let loc = locale { if let sep = loc._bridgeToObjectiveC().object(forKey: .decimalSeparator) as? NSString { return sep._swiftObject } return "." } else { return decimalSep(Locale.current) } } extension String { internal func scan<T: _IntegerLike>(_ skipSet: CharacterSet?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = 0 if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } if (localResult >= T.max / 10) && ((localResult > T.max / 10) || T(numeral - (neg ? 1 : 0)) >= T.max - localResult * 10) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? T.min : T.max neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { // normal case for scanning localResult = localResult * 10 + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) to(neg ? -1 * localResult : localResult) locationToScanFrom = buf.location return true } internal func scanHex<T: _IntegerLike>(_ skipSet: CharacterSet?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var localResult: T = 0 var curDigit: Int if buf.currentCharacter == unichar(unicodeScalarLiteral: "0") { buf.advance() let locRewindTo = buf.location curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { if buf.currentCharacter == unichar(unicodeScalarLiteral: "x") || buf.currentCharacter == unichar(unicodeScalarLiteral: "X") { buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } } if curDigit == -1 { locationToScanFrom = locRewindTo to(T(0)) return true } } else { curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { return false } } repeat { if localResult > T.max >> T(4) { localResult = T.max } else { localResult = (localResult << T(4)) + T(curDigit) } buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } while (curDigit != -1) to(localResult) locationToScanFrom = buf.location return true } internal func scan<T: BinaryFloatingPoint>(_ skipSet: CharacterSet?, locale: Locale?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool { let ds_chars = decimalSep(locale).utf16 let ds = ds_chars[ds_chars.startIndex] var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = T(0) if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } // if (localResult >= T.greatestFiniteMagnitude / T(10)) && ((localResult > T.greatestFiniteMagnitude / T(10)) || T(numericValue(buf.currentCharacter) - (neg ? 1 : 0)) >= T.greatestFiniteMagnitude - localResult * T(10)) is evidently too complex; so break it down to more "edible chunks" let limit1 = localResult >= T.greatestFiniteMagnitude / T(10) let limit2 = localResult > T.greatestFiniteMagnitude / T(10) let limit3 = T(numeral - (neg ? 1 : 0)) >= T.greatestFiniteMagnitude - localResult * T(10) if (limit1) && (limit2 || limit3) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? -T.infinity : T.infinity neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { localResult = localResult * T(10) + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) if buf.currentCharacter == ds { var factor = T(0.1) buf.advance() repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } localResult = localResult + T(numeral) * factor factor = factor * T(0.1) buf.advance() } while (isADigit(buf.currentCharacter)) } to(neg ? T(-1) * localResult : localResult) locationToScanFrom = buf.location return true } internal func scanHex<T: BinaryFloatingPoint>(_ skipSet: CharacterSet?, locale: Locale?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool { NSUnimplemented() } } extension Scanner { // On overflow, the below methods will return success and clamp public func scanInt(_ result: UnsafeMutablePointer<Int32>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int32) -> Void in result.pointee = value } } public func scanInteger(_ result: UnsafeMutablePointer<Int>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int) -> Void in result.pointee = value } } public func scanLongLong(_ result: UnsafeMutablePointer<Int64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int64) -> Void in result.pointee = value } } public func scanUnsignedLongLong(_ result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt64) -> Void in result.pointee = value } } public func scanFloat(_ result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Float) -> Void in result.pointee = value } } public func scanDouble(_ result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Double) -> Void in result.pointee = value } } public func scanHexInt(_ result: UnsafeMutablePointer<UInt32>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt32) -> Void in result.pointee = value } } public func scanHexLongLong(_ result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt64) -> Void in result.pointee = value } } public func scanHexFloat(_ result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Float) -> Void in result.pointee = value } } public func scanHexDouble(_ result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Double) -> Void in result.pointee = value } } public var atEnd: Bool { var stringLoc = scanLocation let stringLen = string.length if let invSet = invertedSkipSet { let range = string._nsObject.rangeOfCharacter(from: invSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } return stringLoc == stringLen } open class func localizedScannerWithString(_ string: String) -> AnyObject { NSUnimplemented() } } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer and better Optional usage. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future extension Scanner { public func scanInt() -> Int32? { var value: Int32 = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Int32>) -> Int32? in if scanInt(ptr) { return ptr.pointee } else { return nil } } } public func scanInteger() -> Int? { var value: Int = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Int>) -> Int? in if scanInteger(ptr) { return ptr.pointee } else { return nil } } } public func scanLongLong() -> Int64? { var value: Int64 = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Int64>) -> Int64? in if scanLongLong(ptr) { return ptr.pointee } else { return nil } } } public func scanUnsignedLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanUnsignedLongLong(ptr) { return ptr.pointee } else { return nil } } } public func scanFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanFloat(ptr) { return ptr.pointee } else { return nil } } } public func scanDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanDouble(ptr) { return ptr.pointee } else { return nil } } } public func scanHexInt() -> UInt32? { var value: UInt32 = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<UInt32>) -> UInt32? in if scanHexInt(ptr) { return ptr.pointee } else { return nil } } } public func scanHexLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanHexLongLong(ptr) { return ptr.pointee } else { return nil } } } public func scanHexFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanHexFloat(ptr) { return ptr.pointee } else { return nil } } } public func scanHexDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(to: &value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanHexDouble(ptr) { return ptr.pointee } else { return nil } } } // These methods avoid calling the private API for _invertedSkipSet and manually re-construct them so that it is only usage of public API usage // Future implementations on Darwin of these methods will likely be more optimized to take advantage of the cached values. public func scanString(string searchString: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSString.CompareOptions = [caseSensitive ? [] : NSString.CompareOptions.caseInsensitive, NSString.CompareOptions.anchored] if let invSkipSet = charactersToBeSkipped?.inverted { let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } let range = str.range(of: searchString, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length > 0 { /* ??? Is the range below simply range? 99.9% of the time, and perhaps even 100% of the time... Hmm... */ let res = str.substring(with: NSMakeRange(stringLoc, range.location + range.length - stringLoc)) scanLocation = range.location + range.length return res } return nil } public func scanCharactersFromSet(_ set: CharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSString.CompareOptions = caseSensitive ? [] : NSString.CompareOptions.caseInsensitive if let invSkipSet = charactersToBeSkipped?.inverted { let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacter(from: set.inverted, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToString(_ string: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSString.CompareOptions = caseSensitive ? [] : NSString.CompareOptions.caseInsensitive if let invSkipSet = charactersToBeSkipped?.inverted { let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.range(of: string, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToCharactersFromSet(_ set: CharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSString.CompareOptions = caseSensitive ? [] : NSString.CompareOptions.caseInsensitive if let invSkipSet = charactersToBeSkipped?.inverted { let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacter(from: set, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } }
apache-2.0
c6022cd5124767b5ea93ae6b22de6feb
36.336735
299
0.576621
5.071881
false
false
false
false
DigNeurosurgeon/TREMOR12
TREMOR12/TremorViewController.swift
1
10053
// // TremorViewController.swift // TremorDBS // // Created by Pieter Kubben on 20-05-15. // Copyright (c) 2015 DigitalNeurosurgeon.com. All rights reserved. // // import UIKit import CoreMotion import MessageUI class TremorViewController: UIViewController { @IBOutlet weak var startStopButton: UIButton! @IBOutlet weak var recordingIndicator: UIActivityIndicatorView! lazy var motionManager = CMMotionManager() lazy var tremorSamples = [TremorSample]() var timeIntervalAtLastBoot = NSTimeInterval() var samplingStarted = false var notificationForResearchOnlyPresented = false // MARK: - Base functions override func viewDidLoad() { super.viewDidLoad() // Calculate offset for CMDeviceMotion timestamps let secondsSinceReferenceDate = NSDate().timeIntervalSinceReferenceDate let secondsSinceLastBoot = NSProcessInfo().systemUptime timeIntervalAtLastBoot = secondsSinceReferenceDate - secondsSinceLastBoot // Initialize empty sample _ = TremorSample() } override func viewDidAppear(animated: Bool) { if !notificationForResearchOnlyPresented { showNotificationForResearchOnly() } } override func viewWillDisappear(animated: Bool) { stopMotionManager() } override func didReceiveMemoryWarning() { startStopSampling(self) showNotificationAfterRecording("Memory warning", messageText: "Continuing measurements may result in loss of data or crashing the app. What do you want to do?") } // MARK: - Motion manager func startMotionManager() { if motionManager.accelerometerAvailable { let queue = NSOperationQueue() motionManager.startDeviceMotionUpdatesToQueue(queue, /*motionManager.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrame.XMagneticNorthZVertical, toQueue: queue,*/ withHandler: { (motion: CMDeviceMotion?, error: NSError?) in self.collectTremorSamples(motion, error: error) // Use code below if interaction with UI is required // (UI code needs to run on main thread) /* dispatch_sync(dispatch_get_main_queue()) { self.collectTremorSamples(motion, error: error) } */ }) } else { print("Accelerometer is not available.") } } func stopMotionManager() { motionManager.stopDeviceMotionUpdates() } @IBAction func startStopSampling(sender: AnyObject) { if !samplingStarted { startMotionManager() startStopButton.setTitle("Stop", forState: .Normal) samplingStarted = true recordingIndicator.startAnimating() } else { stopMotionManager() startStopButton.setTitle("Record", forState: .Normal) samplingStarted = false recordingIndicator.stopAnimating() showNotificationAfterRecording("Question", messageText: "What do you want to do?") } } // MARK: - Tremor samples func collectTremorSamples(motion: CMDeviceMotion!, error: NSError!) { if (error != nil) { print(error) } let attitude: CMAttitude = motion.attitude let attRoll = attitude.roll let attYaw = attitude.yaw let attPitch = attitude.pitch let rotation: CMRotationRate = motion.rotationRate let rotX = rotation.x let rotY = rotation.y let rotZ = rotation.z let acceleration: CMAcceleration = motion.userAcceleration let accX = acceleration.x let accY = acceleration.y let accZ = acceleration.z let gravity: CMAcceleration = motion.gravity let gravX = CGFloat(gravity.x) let gravY = CGFloat(gravity.y) let gravZ = CGFloat(gravity.z) // let magneticField: CMCalibratedMagneticField = motion.magneticField // let magX = magneticField.field.x // let magY = magneticField.field.y // let magZ = magneticField.field.z // // let magneticFieldCalibrationAccuracy: CMMagneticFieldCalibrationAccuracy = magneticField.accuracy // let magneticFieldCalibrationAccuracyValue = magneticFieldCalibrationAccuracy.value let timeStamp = motion.timestamp let timeStampSince2001 = timeIntervalAtLastBoot + timeStamp let timeStampSince2001Milliseconds = timeStampSince2001 * 1000 let sample = TremorSample(roll: attRoll, yaw: attYaw, pitch: attPitch, rotX: rotX, rotY: rotY, rotZ: rotZ, accX: accX, accY: accY, accZ: accZ, gravX: gravX, gravY: gravY, gravZ: gravZ, datetime: timeStampSince2001Milliseconds) tremorSamples.append(sample) } @IBAction func resetSamples(sender: AnyObject) { let alertController = UIAlertController(title: "Please confirm", message: "Are you sure you want to delete the samples?", preferredStyle: UIAlertControllerStyle.ActionSheet) let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive) { (action) -> Void in self.tremorSamples = [TremorSample]() } alertController.addAction(deleteAction) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } // MARK: - Export data func csvFileWithPath() -> NSURL? { // Create date string from local timezone for filename let date = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone() dateFormatter.dateFormat = "YYYY_MM_dd_hhmm" let localDateForFileName = dateFormatter.stringFromDate(date) // Create CSV file with output var csvString = "timestamp2001_ms,roll,pitch,yaw,rotX,rotY,rotZ,accX,accY,accZ,gravX,gravY,gravZ\n" for sample in tremorSamples { csvString += sample.exportAsCommaSeparatedValues() } let dirPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let docsDir = dirPaths[0] let csvFileName = "TREMOR12_samples_\(localDateForFileName).csv" let csvFilePath = docsDir.stringByAppendingString("/" + csvFileName) // Generate output var csvURL: NSURL? do { try csvString.writeToFile(csvFilePath, atomically: true, encoding: NSUTF8StringEncoding) csvURL = NSURL(fileURLWithPath: csvFilePath) } catch { csvURL = nil } return csvURL } @IBAction func exportSamples(sender: AnyObject) { // Export content if possible, else show alert if let content = csvFileWithPath() { let activityViewController = UIActivityViewController(activityItems: [content], applicationActivities: nil) if activityViewController.respondsToSelector("popoverPresentationController") { activityViewController.popoverPresentationController?.sourceView = self.view activityViewController.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem } presentViewController(activityViewController, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "Error", message: "CSV file could not be created.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } } // MARK: - Notifications func showNotificationForResearchOnly() { let warningMessage = "This tool is only meant for research and not for direct patient treatment." let warningController = UIAlertController(title: "Warning", message: warningMessage, preferredStyle: UIAlertControllerStyle.Alert) let confirmAction = UIAlertAction(title: "I understand", style: UIAlertActionStyle.Default, handler: nil) warningController.addAction(confirmAction) presentViewController(warningController, animated: true, completion: nil) notificationForResearchOnlyPresented = true } func showNotificationAfterRecording(titleText: String, messageText: String) { let controller = UIAlertController(title: titleText, message: messageText, preferredStyle: UIAlertControllerStyle.ActionSheet) let continueAction = UIAlertAction(title: "Continue measurements", style: UIAlertActionStyle.Default) { (action) -> Void in self.startStopSampling(self) } controller.addAction(continueAction) let exportAction = UIAlertAction(title: "Export data", style: UIAlertActionStyle.Default) { (action) -> Void in self.exportSamples(self) } controller.addAction(exportAction) let deleteAction = UIAlertAction(title: "Delete data", style: UIAlertActionStyle.Destructive) { (action) -> Void in self.resetSamples(self) } controller.addAction(deleteAction) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) controller.addAction(cancelAction) presentViewController(controller, animated: true, completion: nil) } }
gpl-3.0
94733ea864de0f4ca2cdfdba5210cb7e
37.079545
234
0.64906
5.502463
false
false
false
false
PlugForMac/HypeMachineAPI
Source/MeRequests.swift
1
3825
// // MeRequests.swift // HypeMachineAPI // // Created by Alex Marchant on 5/13/15. // Copyright (c) 2015 Plug. All rights reserved. // import Foundation import Alamofire extension Requests { public struct Me { public static func favorites( params: Parameters? = nil, completionHandler: @escaping (DataResponse<[Track]>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.favorites(params: params)) .responseCollection(completionHandler: completionHandler) } public static func toggleTrackFavorite( id: String, params: Parameters? = nil, completionHandler: @escaping (DataResponse<Bool>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.toggleTrackFavorite(id: id, params: params)) .responseBool(completionHandler: completionHandler) } public static func toggleBlogFavorite( id: Int, params: Parameters? = nil, completionHandler: @escaping (DataResponse<Bool>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.toggleBlogFavorite(id: id, params: params)) .responseBool(completionHandler: completionHandler) } public static func toggleUserFavorite( id: String, params: Parameters? = nil, completionHandler: @escaping (DataResponse<Bool>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.toggleUserFavorite(id: id, params: params)) .responseBool(completionHandler: completionHandler) } public static func playlistNames( _ completionHandler: @escaping (DataResponse<[String]>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.playlistNames) .responseStringArray(completionHandler: completionHandler) } // Playlist id's are 1...3 public static func showPlaylist( id: Int, params: Parameters? = nil, completionHandler: @escaping (DataResponse<[Track]>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.showPlaylist(id: id, params: params)) .responseCollection(completionHandler: completionHandler) } public static func postHistory( id: String, position: Int, params: Parameters? = nil, completionHandler: @escaping (DataResponse<String>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.postHistory(id: id, position: position, params: params)) .responseString(completionHandler: completionHandler) } public static func friends( params: Parameters? = nil, completionHandler: @escaping (DataResponse<[User]>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.friends(params: params)) .responseCollection(completionHandler: completionHandler) } public static func feed( params: Parameters? = nil, completionHandler: @escaping (DataResponse<[Track]>)->Void ) -> DataRequest { return Requests .defaultRequest(Router.Me.feed(params: params)) .responseCollection(completionHandler: completionHandler) } } }
mit
40a0bc2700cb88769981b468fe69ce8e
33.772727
98
0.561307
5.734633
false
false
false
false
Yvent/YVImagePickerController
YVImagePickerController-Demo/YVImagePickerController-Demo/SingleSelectionVideoVC.swift
1
2735
// // SingleSelectionVideoVC.swift // Demo // // Created by 周逸文 on 2017/10/12. // Copyright © 2017年 YV. All rights reserved. // import UIKit import AVFoundation import YVImagePickerController class SingleSelectionVideoVC: UIViewController, YVImagePickerControllerDelegate { var player: AVPlayer! var playerLayer: AVPlayerLayer! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white addNavRightItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addNavRightItem() { let btn = UIButton(type: .custom) btn.frame = CGRect(x: 0, y: 0, width: 70, height: 35) btn.setTitle("添加", for: .normal) btn.setTitleColor(UIColor.black, for: .normal) btn.addTarget(self, action: #selector(navRightItemClicked), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn) } @objc func navRightItemClicked() { let pickerVC = YVImagePickerController() pickerVC.yvmediaType = . video pickerVC.yvcolumns = 4 pickerVC.yvIsMultiselect = false pickerVC.yvdelegate = self self.present(pickerVC, animated: true, completion: nil) } func yvimagePickerController(_ picker: YVImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: nil) if info["videodata"] != nil{ let url = info["videodata"] as! URL let ccnovvor = YVVideoEditorViewController() ccnovvor.inputVideoUrl = url ccnovvor.outputVideoUrl = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last! + "/YVPicker_temp.mp4") ccnovvor.finished = { [weak self] (url) in let playerItem = AVPlayerItem(url: url) self?.player = AVPlayer(playerItem: playerItem) self?.playerLayer = AVPlayerLayer(player: self?.player) self?.playerLayer.backgroundColor = UIColor.gray.cgColor self?.playerLayer.frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight-64) self?.view.layer.addSublayer((self?.playerLayer)!) self?.player.play() } self.present(ccnovvor, animated: true, completion: nil) } } func yvimagePickerControllerDidCancel(_ picker: YVImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
mit
1a1856e17b9bcf09010b953724bd16ef
35.783784
165
0.637032
4.800705
false
false
false
false
maxoly/PulsarKit
PulsarKit/PulsarKit/Sources/CollectionSource/CollectionSource+Dispatch.swift
1
5951
// // CollectionSource+Dispatch.swift // PulsarKit // // Created by Massimo Oliviero on 06/10/2018. // Copyright © 2019 Nacoon. All rights reserved. // import Foundation extension CollectionSource { func dispatch(event: Event.Selection, container: UICollectionView, indexPath: IndexPath) { guard let model = self.model(safeAt: indexPath) else { return } descriptor(for: model)?.handle.event(event, model: model, container: container, indexPath: indexPath) let context = StandardContext(model: model, container: container, indexPath: indexPath) on.dispatch(event: event, context: context) events.forEach { $0.dispatch(source: self, event: event, context: context) } } func dispatch(event: Event.Should, container: UICollectionView, indexPath: IndexPath) -> Bool { let standard = true guard indexPath.isEmpty == false else { return standard } guard let model = self.model(safeAt: indexPath) else { return standard } let context = StandardContext(model: model, container: container, indexPath: indexPath) let specific = descriptor(for: model)?.handle.event(event, model: model, container: container, indexPath: indexPath) ?? standard let general = on.dispatch(event: event, context: context) ?? standard let plugin = events.reduce(standard) { $0 && ($1.dispatch(source: self, event: event, context: context) ?? standard) } return specific && general && plugin } func dispatch(event: Event.Display, container: UICollectionView, cell: UICollectionViewCell, indexPath: IndexPath) { guard indexPath.isEmpty == false else { return } guard let model = self.model(safeAt: indexPath) else { return } descriptor(for: model)?.handle.event(event, model: model, container: container, cell: cell, indexPath: indexPath) let context = CellContext(model: model, cell: cell, container: container, indexPath: indexPath) (model as? Displayable)?.container(display: event, view: cell) on.dispatch(event: event, context: context) events.forEach { $0.dispatch(source: self, event: event, context: context) } } func dispatch(event: Event.Menu, container: UICollectionView, indexPath: IndexPath) -> Bool { let standard = false guard indexPath.isEmpty == false else { return standard } guard let model = self.model(safeAt: indexPath) else { return standard } let context = ActionContext(model: model, container: container, indexPath: indexPath, action: nil, sender: nil) let specific = descriptor(for: model)?.handle.event(event, model: model, container: container, indexPath: indexPath) ?? standard let general = on.dispatch(event: event, context: context) ?? standard let plugin = events.reduce(standard) { $0 && ($1.dispatch(source: self, event: event, context: context) ?? standard) } return specific && general && plugin } func dispatch(event: Event.Menu, container: UICollectionView, indexPath: IndexPath, action: Selector, sender: Any?) -> Bool { let standard = false guard indexPath.isEmpty == false else { return standard } guard let model = self.model(safeAt: indexPath) else { return standard } let context = ActionContext(model: model, container: container, indexPath: indexPath, action: action, sender: sender) let specific = descriptor(for: model)?.handle.event(event, model: model, container: container, indexPath: indexPath) ?? standard let general = on.dispatch(event: event, context: context) ?? standard let plugin = events.reduce(standard) { $0 && ($1.dispatch(source: self, event: event, context: context) ?? standard) } return specific && general && plugin } func dispatch(event: Event.Move, container: UICollectionView, indexPath: IndexPath) -> Bool { let standard = false guard indexPath.isEmpty == false else { return standard } guard let model = self.model(safeAt: indexPath) else { return standard } let context = StandardContext(model: model, container: container, indexPath: indexPath) let specific = descriptor(for: model)?.handle.event(event, model: model, container: container, indexPath: indexPath) ?? standard let general = on.dispatch(event: event, context: context) ?? standard let plugin = events.reduce(standard) { $0 && ($1.dispatch(source: self, event: event, context: context) ?? standard) } return specific || general || plugin } func dispatch(event: Event.TargetMove, container: UICollectionView, originalIndexPath: IndexPath, proposedIndexPath: IndexPath) -> IndexPath { let defaultValue = proposedIndexPath guard originalIndexPath.isEmpty == false else { return defaultValue } guard let originalModel = self.model(safeAt: originalIndexPath) else { return defaultValue } let context = TargetMoveContext(originalModel: originalModel, container: container, originalIndexPath: originalIndexPath, proposedIndexPath: proposedIndexPath) let specific = descriptor(for: originalModel)?.handle.event(event, originalModel: originalModel, container: container, originalIndexPath: originalIndexPath, proposedIndexPath: proposedIndexPath) let general = on.dispatch(event: event, context: context) return specific ?? general ?? defaultValue } }
mit
09a13262fdfd9df14b55dc76f3b920ef
55.666667
146
0.636303
5.042373
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookShare/Sources/Share/Content/Video/VideoShareContent.swift
13
3641
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit /** A model for video content to be shared. */ public struct VideoShareContent: ContentProtocol { public typealias Result = PostSharingResult /// Video to be shared. public var video: Video /// The photo that represents the video. public var previewPhoto: Photo? /** Create a `VideoShareContent` with a list of of photos to share. - parameter video: The video to share. - parameter previewPhoto: The photo that represents the video. */ public init(video: Video, previewPhoto: Photo? = nil) { self.video = video self.previewPhoto = previewPhoto } //-------------------------------------- // MARK - ContentProtocol //-------------------------------------- /** URL for the content being shared. This URL will be checked for all link meta tags for linking in platform specific ways. See documentation for [App Links](https://developers.facebook.com/docs/applinks/) */ public var url: URL? /// Hashtag for the content being shared. public var hashtag: Hashtag? /** List of IDs for taggable people to tag with this content. See documentation for [Taggable Friends](https://developers.facebook.com/docs/graph-api/reference/user/taggable_friends) */ public var taggedPeopleIds: [String]? /// The ID for a place to tag with this content. public var placeId: String? /// A value to be added to the referrer URL when a person follows a link from this shared content on feed. public var referer: String? } extension VideoShareContent: Equatable { /** Compare two `VideoShareContent`s for equality. - parameter lhs: The first `VideoShareContent` to compare. - parameter rhs: The second `VideoShareContent` to compare. - returns: Whether or not the content are equal. */ public static func == (lhs: VideoShareContent, rhs: VideoShareContent) -> Bool { return lhs.sdkSharingContentRepresentation.isEqual(rhs.sdkSharingContentRepresentation) } } extension VideoShareContent: SDKBridgedContent { var sdkSharingContentRepresentation: FBSDKSharingContent { let sdkVideoContent = FBSDKShareVideoContent() sdkVideoContent.video = video.sdkVideoRepresentation sdkVideoContent.previewPhoto = previewPhoto?.sdkPhotoRepresentation sdkVideoContent.contentURL = url sdkVideoContent.hashtag = hashtag?.sdkHashtagRepresentation sdkVideoContent.peopleIDs = taggedPeopleIds sdkVideoContent.placeID = placeId sdkVideoContent.ref = referer return sdkVideoContent } }
mit
bc19feb7e92553f5566f90f90ff7007f
35.41
123
0.730843
4.854667
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardVerify/FrameData.swift
1
1351
import UIKit struct FrameData { let bin: String? let last4: String? let expiry: Expiry? let numberBoundingBox: CGRect? let numberBoxesInFullImageFrame: [CGRect]? let croppedCardSize: CGSize let squareCardImage: CGImage let fullCardImage: CGImage let centeredCardState: CenteredCardState? let ocrSuccess: Bool let uxFrameConfidenceValues: UxFrameConfidenceValues? let flashForcedOn: Bool func toDictForOcrFrame() -> [String: Any] { var numberBox: [String: Any]? if let numberBoundingBox = self.numberBoundingBox { numberBox = [ "x_min": numberBoundingBox.minX / CGFloat(croppedCardSize.width), "y_min": numberBoundingBox.minY / CGFloat(croppedCardSize.height), "width": numberBoundingBox.width / CGFloat(croppedCardSize.width), "height": numberBoundingBox.height / CGFloat(croppedCardSize.height), "label": -1, "confidence": 1, ] } var result: [String: Any] = [:] result["bin"] = self.bin result["last4"] = self.last4 result["number_box"] = numberBox result["exp_month"] = (self.expiry?.month).map { String($0) } result["exp_year"] = (self.expiry?.year).map { String($0) } return result } }
mit
5e2a842f44a52d3fbdedba3d29a4b020
32.775
85
0.611399
4.330128
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/17160-no-stacktrace.swift
11
2274
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } var d = return ( ) -> { } case c, func g { protocol A { case c, { struct A<T, A : b case , } } } case struct A.m( ) .e { protocol A { case , case , deinit { class r { deinit { nil class func g { case case , func a( ) -> { class { let end = e class case c, struct A.e { typealias e class r { protocol b : A class d<r { var d ( ) .m( ) -> { { } for c : A class r { class d<T, A : A { case c, init { class A { var d = let a { } var a { case , class { case , func a( ) .e { } { } { } class { func g { func g { class class nil { { (r( ) .e { class A : A { func < { } var a { { let end = [Void{ struct A.e { var d = e } case , class } var a { func f<T, A { protocol A { for in a { var d ( ) -> { protocol b { enum A { func a( ) .e { func a( ) } return ( ) protocol b : A func a( ) { } let a { class d< { case c, enum A : a { var d = [Void{ class { protocol b { { } } var d ( ) -> { protocol A : A { struct A<T, A { case c, } class d< { { for in a { case c, let a { nil class a = [Void{ protocol b { class for c : b func < { } { class } init { protocol A { { enum A : A<r { protocol A : A class A : A { { protocol b : A.m( ) .e { func < { { } case c, class class r { typealias b : A<T, A : A { typealias b { case c, class let end = [Void{ } func g { { var d ( ) .m( ) -> { func a( ) .e { { { { protocol A { var d = [Void{ protocol A { protocol b : A } { case , { let end = e func < { } let end = [Void{ } class { { let a { let end = [Void{ init { let a { let end = [Void{ class d< { case c, nil case , case class a = [Void{ func g { case c, class struct A<T, A { var d = [Void{ } class typealias b : A return ( ) let a = [Void{ for in a { for c : A return ( ) .e { protocol A { class a { case var d = [Void{ { return ( ) struct A (r( ) class r { } class case , enum A : A protocol A { } class r { case class struct A.e { struct S { class } } } case c, struct A.e { nil var d = { protocol b : A.m( ) init { let a { case func < { } (r( ) { { { init { func a( ) -> { { for c : b { struct A.e { class { { func g { { { } } case c, typealias e { let a { class func g { { { case , let a { protocol A : A case , class
mit
fae050ef8712564b35642ef0525dd3a5
7.581132
87
0.551451
2.212062
false
false
false
false
CodeMozart/MHzSinaWeibo-Swift-
SinaWeibo(stroyboard)/SinaWeibo/Classes/Tools/UIButton+Extension.swift
1
967
// // UIButton+Extension.swift // SinaWeibo // // Created by Minghe on 11/6/15. // Copyright © 2015 Stanford swift. All rights reserved. // import UIKit extension UIButton { // // func == OC - // // class func == OC + convenience init(imageName: String?, backgroundImage: String) { self.init() setBackgroundImage(UIImage(named: backgroundImage), forState: .Normal) setBackgroundImage(UIImage(named: backgroundImage + "_highlighted"), forState: .Highlighted) sizeToFit() guard let name = imageName else { return } setImage(UIImage(named: name), forState: .Normal) setImage(UIImage(named: name + "_highlighted"), forState: .Highlighted) sizeToFit() } /// 根据背景图片创建按钮 convenience init(backgroundImage: String) { self.init(imageName:nil, backgroundImage: backgroundImage) } }
mit
95412c1ad12df5cff658ca6e4384d608
23.25641
100
0.603594
4.637255
false
false
false
false
alonecuzzo/ystrdy
ystrdy/Model/YesterdayTemp.swift
1
833
// // YesterdayTemp.swift // ystrdy // // Created by Jabari Bell on 2/6/17. // Copyright © 2017 theowl. All rights reserved. // import Foundation struct YesterdayTemp: TemperatureType { var tempF: Double } extension YesterdayTemp: ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) { guard let innerRepresentation = representation as? [String: Any], let history = innerRepresentation["history"] as? [String: Any], let summary = history["observations"] as? [Any], let summaryObj = summary.first as? [String: Any], let tempFString = summaryObj["tempi"] as? String else { return nil } let n = NumberFormatter().number(from: tempFString)! self.tempF = Double(n) } }
apache-2.0
b51a043234c62e24d4288d39914bd46e
25.83871
75
0.620192
4.310881
false
false
false
false