repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
igerard/Genesis
refs/heads/master
Genesis/Board/BoardAppDelegate.swift
mit
1
// // AppDelegate.swift // Genesis // // Created by Gerard Iglesias on 27/08/2017. // Copyright © 2017 Gerard Iglesias. All rights reserved. // import UIKit import CoreData @UIApplicationMain class BoardAppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var boardContainer: BoardContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = BoardContainer(name: "Genesis") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } board_log_debug("Persistent Store description: %@", storeDescription) }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = boardContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
930a09c17e7fe4ce47a21d228ed98db9
45.752688
281
0.734131
false
false
false
false
MartySchmidt/phonertc
refs/heads/master
src/ios/Config.swift
apache-2.0
7
import Foundation class SessionConfig { var isInitiator: Bool var turn: TurnConfig var streams: StreamsConfig init(data: AnyObject) { self.isInitiator = data.objectForKey("isInitiator") as Bool let turnObject: AnyObject = data.objectForKey("turn")! self.turn = TurnConfig( host: turnObject.objectForKey("host") as String, username: turnObject.objectForKey("username") as String, password: turnObject.objectForKey("password") as String ) let streamsObject: AnyObject = data.objectForKey("streams")! self.streams = StreamsConfig( audio: streamsObject.objectForKey("audio") as Bool, video: streamsObject.objectForKey("video") as Bool ) } } struct TurnConfig { var host: String var username: String var password: String } struct StreamsConfig { var audio: Bool var video: Bool } class VideoConfig { var container: VideoLayoutParams var local: VideoLayoutParams? init(data: AnyObject) { let containerParams: AnyObject = data.objectForKey("containerParams")! let localParams: AnyObject? = data.objectForKey("local") self.container = VideoLayoutParams(data: containerParams) if localParams != nil { self.local = VideoLayoutParams(data: localParams!) } } } class VideoLayoutParams { var x, y, width, height: Int init(x: Int, y: Int, width: Int, height: Int) { self.x = x self.y = y self.width = width self.height = height } init(data: AnyObject) { let position: [AnyObject] = data.objectForKey("position")! as [AnyObject] self.x = position[0] as Int self.y = position[1] as Int let size: [AnyObject] = data.objectForKey("size")! as [AnyObject] self.width = size[0] as Int self.height = size[1] as Int } }
a8e8e0b19d3d633197593142052b37d2
26.652778
81
0.60804
false
true
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/CircledRankView.swift
mit
1
class CircledRankView: SizeThatFitsView { fileprivate let label: UILabel = UILabel() let padding = UIEdgeInsetsMake(3, 3, 3, 3) override func setup() { super.setup() layer.borderWidth = 1 label.isOpaque = true addSubview(label) } var rank: Int = 0 { didSet { label.text = String.localizedStringWithFormat("%d", rank) setNeedsLayout() } } var labelBackgroundColor: UIColor? { didSet { label.backgroundColor = labelBackgroundColor } } override func tintColorDidChange() { label.textColor = tintColor layer.borderColor = tintColor.cgColor } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) label.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection) } override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { let insetSize = UIEdgeInsetsInsetRect(CGRect(origin: .zero, size: size), padding) let labelSize = label.sizeThatFits(insetSize.size) if (apply) { layer.cornerRadius = 0.5*size.width label.frame = CGRect(origin: CGPoint(x: 0.5*size.width - 0.5*labelSize.width, y: 0.5*size.height - 0.5*labelSize.height), size: labelSize) } let width = labelSize.width + padding.left + padding.right let height = labelSize.height + padding.top + padding.bottom let dimension = max(width, height) return CGSize(width: dimension, height: dimension) } }
b77b3f1513342af2eab872d7510949ac
34.723404
150
0.633115
false
false
false
false
Snail93/iOSDemos
refs/heads/dev
SnailSwiftDemos/SnailSwiftDemos/Tools/CustomTool/Calculator.swift
apache-2.0
2
// // Calculator.swift // SwiftDemos // // Created by codans on 16/4/15. // Copyright © 2016年 Snail. All rights reserved. // import UIKit class Calculator: NSObject { //计算两点间的距离 class func calculateTwoPointDistance(_ lng1: Double, lat1: Double, lng2: Double, lat2: Double)-> Int { let startPoint = MAMapPointForCoordinate(CLLocationCoordinate2DMake(lat1,lng1)) let endPoint = MAMapPointForCoordinate(CLLocationCoordinate2DMake(lat2,lng2)) let distance = MAMetersBetweenMapPoints(startPoint,endPoint) return Int(distance) } //计算两点间距离并加上单位 class func calculateTwoPointDistanceHasUnit(_ lng1: Double, lat1: Double, lng2: Double, lat2: Double)-> String? { let startPoint = MAMapPointForCoordinate(CLLocationCoordinate2DMake(lat1,lng1)) let endPoint = MAMapPointForCoordinate(CLLocationCoordinate2DMake(lat2,lng2)) let distance = MAMetersBetweenMapPoints(startPoint,endPoint) if distance < 1000 { return "\(Int(distance))米" } else { return String(format: "%.1f千米", arguments: [distance/1000]) } } }
f639cf978ee2b887bece3b885471e148
33.636364
117
0.68154
false
false
false
false
thomaschristensen/Pantomime
refs/heads/master
sources/StringBufferedReader.swift
mit
1
// // Created by Thomas Christensen on 26/08/16. // Copyright (c) 2016 Sebastian Kreutzberger. All rights reserved. // import Foundation /** * Uses a string as a stream and reads it line by line. */ open class StringBufferedReader: BufferedReader { var _buffer: [String] var _line: Int public init(string: String) { _line = 0 _buffer = string.components(separatedBy: CharacterSet.newlines) } open func close() { } open func readLine() -> String? { if _buffer.isEmpty || _buffer.count <= _line { return nil } let result = _buffer[_line] _line += 1 return result } }
cd5707b159a4e2e731b72b063cb58d4c
19.96875
71
0.596125
false
false
false
false
zozep/Alimentum
refs/heads/master
alimentum/alimentum/IntroPageViewController.swift
mit
1
// // AppDelegate.swift // alimentum // // Created by Joseph Park, Nitish Dayal // Copyright © 2016 Joseph Park, Nitish Dayal. All rights reserved. import UIKit import CoreLocation import OAuthSwift //MARK: - Declare protocol 'IntroPageViewControllerDelegate' protocol IntroPageViewControllerDelegate: class { /* Function that will be called to update current page count */ func introPageViewController(pageViewController: IntroPageViewController, didUpdatePageCount count: Int) func introPageViewController(pageViewController: IntroPageViewController, didUpdatePageIndex index: Int) } class IntroPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { //MARK: - Declare variables to be used throughout IntroPageViewController weak var viewDelegate : IntroPageViewControllerDelegate? lazy var orderedViewControllers: [UIViewController] = { //When orderedViewControllers is called upon, set to array of value returned from calling method(function) newViewController return [self.newViewController("page1"), self.newViewController("page2"), self.newViewController("page3")] }() //MARK: - Declare default functions override func viewDidLoad() { super.viewDidLoad() //On view load, set self to be dataSource and delegate for PageViewController dataSource = self delegate = self let launchedBefore = NSUserDefaults.standardUserDefaults().boolForKey("launchedBefore") if launchedBefore { let mainAppStoryboard = UIStoryboard(name: "Main", bundle: nil) let mainVC = mainAppStoryboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController //Present is done asynchronously in order to allow for current view controller to be added to the view hierarchy. Otherwise app breaks mainVC.checkLocationServices() dispatch_async(dispatch_get_main_queue(), { self.presentViewController(mainVC, animated: true, completion: nil) }) //If launchedBefore returns false/is not set, set value for launchedBefore to true and show introductory views } else { NSUserDefaults.standardUserDefaults().setBool(true, forKey: "launchedBefore") if let firstViewController = orderedViewControllers.first { setViewControllers([firstViewController],direction: .Forward, animated: true, completion: nil) viewDelegate?.introPageViewController(self, didUpdatePageCount: orderedViewControllers.count) } initAppearance() } } //MARK: - UIPageViewControllerDelegate/DataSource functions func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){ if let firstViewController = viewControllers?.first, let index = orderedViewControllers.indexOf(firstViewController) { viewDelegate?.introPageViewController(self, didUpdatePageIndex: index) } } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {return nil} let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else {return nil} guard orderedViewControllers.count > previousIndex else {return nil} return orderedViewControllers[previousIndex] } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {return nil} let nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = orderedViewControllers.count guard orderedViewControllersCount != nextIndex else {return nil} guard orderedViewControllersCount > nextIndex else {return nil} return orderedViewControllers[nextIndex] } //MARK: - Custom functions /* Takes a parameter "identifier" of type string */ func newViewController(identifier: String) -> UIViewController { //Returns view controller that matches identifier passed in as parameter return UIStoryboard(name: "FirstTime", bundle: nil).instantiateViewControllerWithIdentifier(identifier) } func initAppearance() -> Void { let background = CAGradientLayer().turquoiseColor() background.frame = self.view.bounds self.view.layer.insertSublayer(background, atIndex: 0) } }
35f951e10b67429f5816c096ae6ec025
38.724409
187
0.705649
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOConcurrencyHelpers/lock.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Windows) import ucrt import WinSDK #else import Glibc #endif /// A threading lock based on `libpthread` instead of `libdispatch`. /// /// This object provides a lock on top of a single `pthread_mutex_t`. This kind /// of lock is safe to use with `libpthread`-based threading models, such as the /// one used by NIO. On Windows, the lock is based on the substantially similar /// `SRWLOCK` type. @available(*, deprecated, renamed: "NIOLock") public final class Lock { #if os(Windows) fileprivate let mutex: UnsafeMutablePointer<SRWLOCK> = UnsafeMutablePointer.allocate(capacity: 1) #else fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> = UnsafeMutablePointer.allocate(capacity: 1) #endif /// Create a new lock. public init() { #if os(Windows) InitializeSRWLock(self.mutex) #else var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) debugOnly { pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) } let err = pthread_mutex_init(self.mutex, &attr) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif } deinit { #if os(Windows) // SRWLOCK does not need to be free'd #else let err = pthread_mutex_destroy(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif mutex.deallocate() } /// Acquire the lock. /// /// Whenever possible, consider using `withLock` instead of this method and /// `unlock`, to simplify lock handling. public func lock() { #if os(Windows) AcquireSRWLockExclusive(self.mutex) #else let err = pthread_mutex_lock(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif } /// Release the lock. /// /// Whenever possible, consider using `withLock` instead of this method and /// `lock`, to simplify lock handling. public func unlock() { #if os(Windows) ReleaseSRWLockExclusive(self.mutex) #else let err = pthread_mutex_unlock(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif } /// Acquire the lock for the duration of the given block. /// /// This convenience method should be preferred to `lock` and `unlock` in /// most situations, as it ensures that the lock will be released regardless /// of how `body` exits. /// /// - Parameter body: The block to execute while holding the lock. /// - Returns: The value returned by the block. @inlinable public func withLock<T>(_ body: () throws -> T) rethrows -> T { self.lock() defer { self.unlock() } return try body() } // specialise Void return (for performance) @inlinable public func withLockVoid(_ body: () throws -> Void) rethrows -> Void { try self.withLock(body) } } /// A `Lock` with a built-in state variable. /// /// This class provides a convenience addition to `Lock`: it provides the ability to wait /// until the state variable is set to a specific value to acquire the lock. public final class ConditionLock<T: Equatable> { private var _value: T private let mutex: NIOLock #if os(Windows) private let cond: UnsafeMutablePointer<CONDITION_VARIABLE> = UnsafeMutablePointer.allocate(capacity: 1) #else private let cond: UnsafeMutablePointer<pthread_cond_t> = UnsafeMutablePointer.allocate(capacity: 1) #endif /// Create the lock, and initialize the state variable to `value`. /// /// - Parameter value: The initial value to give the state variable. public init(value: T) { self._value = value self.mutex = NIOLock() #if os(Windows) InitializeConditionVariable(self.cond) #else let err = pthread_cond_init(self.cond, nil) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif } deinit { #if os(Windows) // condition variables do not need to be explicitly destroyed #else let err = pthread_cond_destroy(self.cond) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif self.cond.deallocate() } /// Acquire the lock, regardless of the value of the state variable. public func lock() { self.mutex.lock() } /// Release the lock, regardless of the value of the state variable. public func unlock() { self.mutex.unlock() } /// The value of the state variable. /// /// Obtaining the value of the state variable requires acquiring the lock. /// This means that it is not safe to access this property while holding the /// lock: it is only safe to use it when not holding it. public var value: T { self.lock() defer { self.unlock() } return self._value } /// Acquire the lock when the state variable is equal to `wantedValue`. /// /// - Parameter wantedValue: The value to wait for the state variable /// to have before acquiring the lock. public func lock(whenValue wantedValue: T) { self.lock() while true { if self._value == wantedValue { break } self.mutex.withLockPrimitive { mutex in #if os(Windows) let result = SleepConditionVariableSRW(self.cond, mutex, INFINITE, 0) precondition(result, "\(#function) failed in SleepConditionVariableSRW with error \(GetLastError())") #else let err = pthread_cond_wait(self.cond, mutex) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif } } } /// Acquire the lock when the state variable is equal to `wantedValue`, /// waiting no more than `timeoutSeconds` seconds. /// /// - Parameter wantedValue: The value to wait for the state variable /// to have before acquiring the lock. /// - Parameter timeoutSeconds: The number of seconds to wait to acquire /// the lock before giving up. /// - Returns: `true` if the lock was acquired, `false` if the wait timed out. public func lock(whenValue wantedValue: T, timeoutSeconds: Double) -> Bool { precondition(timeoutSeconds >= 0) #if os(Windows) var dwMilliseconds: DWORD = DWORD(timeoutSeconds * 1000) self.lock() while true { if self._value == wantedValue { return true } let dwWaitStart = timeGetTime() if !SleepConditionVariableSRW(self.cond, self.mutex._storage.mutex, dwMilliseconds, 0) { let dwError = GetLastError() if (dwError == ERROR_TIMEOUT) { self.unlock() return false } fatalError("SleepConditionVariableSRW: \(dwError)") } // NOTE: this may be a spurious wakeup, adjust the timeout accordingly dwMilliseconds = dwMilliseconds - (timeGetTime() - dwWaitStart) } #else let nsecPerSec: Int64 = 1000000000 self.lock() /* the timeout as a (seconds, nano seconds) pair */ let timeoutNS = Int64(timeoutSeconds * Double(nsecPerSec)) var curTime = timeval() gettimeofday(&curTime, nil) let allNSecs: Int64 = timeoutNS + Int64(curTime.tv_usec) * 1000 var timeoutAbs = timespec(tv_sec: curTime.tv_sec + Int((allNSecs / nsecPerSec)), tv_nsec: Int(allNSecs % nsecPerSec)) assert(timeoutAbs.tv_nsec >= 0 && timeoutAbs.tv_nsec < Int(nsecPerSec)) assert(timeoutAbs.tv_sec >= curTime.tv_sec) return self.mutex.withLockPrimitive { mutex -> Bool in while true { if self._value == wantedValue { return true } switch pthread_cond_timedwait(self.cond, mutex, &timeoutAbs) { case 0: continue case ETIMEDOUT: self.unlock() return false case let e: fatalError("caught error \(e) when calling pthread_cond_timedwait") } } } #endif } /// Release the lock, setting the state variable to `newValue`. /// /// - Parameter newValue: The value to give to the state variable when we /// release the lock. public func unlock(withValue newValue: T) { self._value = newValue self.unlock() #if os(Windows) WakeAllConditionVariable(self.cond) #else let err = pthread_cond_broadcast(self.cond) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif } } /// A utility function that runs the body code only in debug builds, without /// emitting compiler warnings. /// /// This is currently the only way to do this in Swift: see /// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion. @inlinable internal func debugOnly(_ body: () -> Void) { assert({ body(); return true }()) } @available(*, deprecated) extension Lock: Sendable {} extension ConditionLock: @unchecked Sendable {}
07d2011d3542562b89292d858c8a9306
32.949153
117
0.605891
false
false
false
false
tonyarnold/Bond
refs/heads/master
Sources/Bond/Observable Collections/Signal+ChangesetProtocol.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // 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 ReactiveKit public extension SignalProtocol where Element: ChangesetProtocol { /// When working with a changeset that calculates patch lazily, /// you can use this method to calculate the patch in advance. /// Observer will then have patch available in O(1). public func precalculatePatch() -> Signal<Element, Error> { return map { changeset in _ = changeset.patch return changeset } } /// When working with a changeset that calculates diff lazily, /// you can use this method to calculate the diff in advance. /// Observer will then have diff available in O(1). public func precalculateDiff() -> Signal<Element, Error> { return map { changeset in _ = changeset.diff return changeset } } } extension SignalProtocol where Element: Collection, Element.Index: Strideable { /// Generate the diff between previous and current collection using the provided diff generator function. public func diff(generateDiff: @escaping (Element, Element) -> OrderedCollectionChangeset<Element>.Diff) -> Signal<OrderedCollectionChangeset<Element>, Error> { return Signal { observer in var collection: Element? return self.observe { event in switch event { case .next(let element): let newCollection = element if let collection = collection { let diff = generateDiff(collection, newCollection) observer.next(OrderedCollectionChangeset(collection: newCollection, patch: [], diff: diff)) } else { observer.next(OrderedCollectionChangeset(collection: newCollection, patch: [])) } collection = newCollection case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } extension SignalProtocol where Element: TreeProtocol { /// Generate the diff between previous and current tree using the provided diff generator function. public func diff(generateDiff: @escaping (Element, Element) -> TreeChangeset<Element>.Diff) -> Signal<TreeChangeset<Element>, Error> { return Signal { observer in var collection: Element? return self.observe { event in switch event { case .next(let element): let newCollection = element if let collection = collection { let diff = generateDiff(collection, newCollection) observer.next(TreeChangeset(collection: newCollection, patch: [], diff: diff)) } else { observer.next(TreeChangeset(collection: newCollection, patch: [])) } collection = newCollection case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } public extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index: Hashable { /// - complexity: Each event sorts the collection O(nlogn). public func sortedCollection(by areInIncreasingOrder: @escaping (Element.Collection.Element, Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Element.Collection.Index: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let indices = event.collection.indices let elementsWithIndices = Swift.zip(event.collection, indices) let sortedElementsWithIndices = elementsWithIndices.sorted(by: { (a, b) -> Bool in return areInIncreasingOrder(a.0, b.0) }) let sortedElements = sortedElementsWithIndices.map { $0.0 } let indexMap = sortedElementsWithIndices.map { $0.1 }.enumerated().reduce([Element.Collection.Index: Int](), { (indexMap, new) -> [Element.Collection.Index: Int] in return indexMap.merging([new.element: new.offset], uniquingKeysWith: { $1 }) }) let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: sortedElements, diff: diff ) } } } public extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index: Hashable, Element.Collection.Element: Comparable { /// - complexity: Each event sorts collection O(nlogn). public func sortedCollection() -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { return sortedCollection(by: <) } } public extension SignalProtocol where Element: UnorderedCollectionChangesetProtocol, Element.Collection.Index: Hashable { /// - complexity: Each event sorts the collection O(nlogn). public func sortedCollection(by areInIncreasingOrder: @escaping (Element.Collection.Element, Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Element.Collection.Index: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let indices = event.collection.indices let elementsWithIndices = Swift.zip(event.collection, indices) let sortedElementsWithIndices = elementsWithIndices.sorted(by: { (a, b) -> Bool in return areInIncreasingOrder(a.0, b.0) }) let sortedElements = sortedElementsWithIndices.map { $0.0 } let indexMap = sortedElementsWithIndices.map { $0.1 }.enumerated().reduce([Element.Collection.Index: Int](), { (indexMap, new) -> [Element.Collection.Index: Int] in return indexMap.merging([new.element: new.offset], uniquingKeysWith: { $1 }) }) let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: sortedElements, diff: OrderedCollectionDiff(inserts: diff.inserts, deletes: diff.deletes, updates: diff.updates, moves: []) ) } } } public extension SignalProtocol where Element: UnorderedCollectionChangesetProtocol, Element.Collection.Index: Hashable, Element.Collection.Element: Comparable { /// - complexity: Each event sorts collection O(nlogn). public func sortedCollection() -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { return sortedCollection(by: <) } } public extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index == Int { /// - complexity: Each event transforms collection O(n). Use `lazyMapCollection` if you need on-demand mapping. public func mapCollection<U>(_ transform: @escaping (Element.Collection.Element) -> U) -> Signal<OrderedCollectionChangeset<[U]>, Error> { return map { (event: Element) -> OrderedCollectionChangeset<[U]> in return OrderedCollectionChangeset( collection: event.collection.map(transform), diff: event.diff ) } } /// - complexity: O(1). public func lazyMapCollection<U>(_ transform: @escaping (Element.Collection.Element) -> U) -> Signal<OrderedCollectionChangeset<LazyMapCollection<Element.Collection, U>>, Error> { return map { (event: Element) -> OrderedCollectionChangeset<LazyMapCollection<Element.Collection, U>> in return OrderedCollectionChangeset( collection: event.collection.lazy.map(transform), diff: event.diff ) } } /// - complexity: Each event transforms collection O(n). public func filterCollection(_ isIncluded: @escaping (Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Int: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let collection = event.collection var filtered: [Element.Collection.Element] = [] var indexMap: [Int: Int] = [:] filtered.reserveCapacity(collection.count) indexMap.reserveCapacity(collection.count) var iterator = 0 for (index, element) in collection.enumerated() { if isIncluded(element) { filtered.append(element) indexMap[index] = iterator iterator += 1 } } let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: filtered, diff: diff ) } } } extension OrderedCollectionDiff where Index: Hashable { public func transformingIndices<NewIndex>(fromIndexMap: [Index: NewIndex], toIndexMap: [Index: NewIndex]) -> OrderedCollectionDiff<NewIndex> { var inserts = self.inserts.compactMap { toIndexMap[$0] } var deletes = self.deletes.compactMap { fromIndexMap[$0] } let moves = self.moves.compactMap { (move: (from: Index, to: Index)) -> (from: NewIndex, to: NewIndex)? in if let mappedFrom = fromIndexMap[move.from], let mappedTo = toIndexMap[move.to] { return (from: mappedFrom, to: mappedTo) } else { return nil } } var updates: [NewIndex] = [] for index in self.updates { if let mappedIndex = toIndexMap[index] { if let _ = fromIndexMap[index] { updates.append(mappedIndex) } else { inserts.append(mappedIndex) } } else if let mappedIndex = fromIndexMap[index] { deletes.append(mappedIndex) } } return OrderedCollectionDiff<NewIndex>(inserts: inserts, deletes: deletes, updates: updates, moves: moves) } } extension UnorderedCollectionDiff where Index: Hashable { public func transformingIndices<NewIndex>(fromIndexMap: [Index: NewIndex], toIndexMap: [Index: NewIndex]) -> UnorderedCollectionDiff<NewIndex> { var inserts = self.inserts.compactMap { toIndexMap[$0] } var deletes = self.deletes.compactMap { fromIndexMap[$0] } var updates: [NewIndex] = [] for index in self.updates { if let mappedIndex = toIndexMap[index] { if let _ = fromIndexMap[index] { updates.append(mappedIndex) } else { inserts.append(mappedIndex) } } else if let mappedIndex = fromIndexMap[index] { deletes.append(mappedIndex) } } return UnorderedCollectionDiff<NewIndex>(inserts: inserts, deletes: deletes, updates: updates) } }
65bd51e21dcfd4681195e256070d981d
44.250883
210
0.634
false
false
false
false
bluesnap/bluesnap-ios
refs/heads/develop
BluesnapSDK/BluesnapSDK/BSAddress.swift
mit
1
// // BSAddress.swift // BluesnapSDK // // Created by Shevie Chen on 07/08/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import Foundation /** Shopper address details for purchase. State is mandatory only if the country has state (USA, Canada and Brazil). For not-full billing details, only name, country and zip are filled, email is optional For full billing details, everything is mandatory except email which is optional. For shipping details all field are mandatory. */ public class BSBaseAddressDetails: NSObject, BSModel { public static let FIRST_NAME: String = "firstName"; public static let LAST_NAME: String = "lastName"; public static let ADDRESS: String = "address"; public static let ADDRESS_1: String = "address1"; public static let ADDRESS_2: String = "address2"; public static let STATE: String = "state"; public static let ZIP: String = "zip"; public static let COUNTRY: String = "country"; public static let CITY: String = "city"; public static let EMAIL: String = "email"; public static let PHONE: String = "phone"; public var name: String! = "" public var address: String? public var city: String? public var zip: String? public var country: String? public var state: String? public override init() { super.init() } public func getSplitName() -> (firstName: String, lastName: String)? { return BSStringUtils.splitName(name) } public func toJson() -> ([String: Any])! { var baseAddressDetails: [String: Any] = [:] if let splitName = getSplitName() { baseAddressDetails[BSBaseAddressDetails.FIRST_NAME] = splitName.firstName baseAddressDetails[BSBaseAddressDetails.LAST_NAME] = splitName.lastName } if let country = country { baseAddressDetails[BSBaseAddressDetails.COUNTRY] = country } if let state = state { baseAddressDetails[BSBaseAddressDetails.STATE] = state } if let city = city { baseAddressDetails[BSBaseAddressDetails.CITY] = city } if let zip = zip { baseAddressDetails[BSBaseAddressDetails.ZIP] = zip } if let address = address { baseAddressDetails[BSBaseAddressDetails.ADDRESS] = address } return baseAddressDetails } } /** Shopper billing details - basically address + email */ public class BSBillingAddressDetails: BSBaseAddressDetails, NSCopying { public var email: String? public override init() { super.init() } public init(email: String?, name: String!, address: String?, city: String?, zip: String?, country: String?, state: String?) { super.init() self.email = email self.name = name self.address = address self.city = city self.zip = zip self.country = country self.state = state } public func copy(with zone: NSZone? = nil) -> Any { let copy = BSBillingAddressDetails(email: email, name: name, address: address, city: city, zip: zip, country: country, state: state) return copy } public override func toJson() -> ([String: Any])! { var billingAddressDetails: [String: Any] = super.toJson() if let email = email { billingAddressDetails[BSBaseAddressDetails.EMAIL] = email } if let address = address { billingAddressDetails[BSBaseAddressDetails.ADDRESS_1] = address } return billingAddressDetails } } /** Shopper shipping details - basically address */ public class BSShippingAddressDetails: BSBaseAddressDetails, NSCopying { public override init() { super.init() } public init(name: String!, address: String?, city: String?, zip: String?, country: String?, state: String?) { super.init() self.name = name self.address = address self.city = city self.zip = zip self.country = country self.state = state } public func copy(with zone: NSZone? = nil) -> Any { let copy = BSShippingAddressDetails(name: name, address: address, city: city, zip: zip, country: country, state: state) return copy } public override func toJson() -> ([String: Any])! { var shippingAddressDetails: [String: Any] = super.toJson() if let address = address { shippingAddressDetails[BSBaseAddressDetails.ADDRESS_1] = address } return shippingAddressDetails } }
456c9a759761d3e5514c2739c53718f5
30.75
140
0.63867
false
false
false
false
ngageoint/mage-ios
refs/heads/master
Mage/CoreData/Observation.swift
apache-2.0
1
// // Observation.m // mage-ios-sdk // // Created by William Newman on 4/13/16. // Copyright © 2016 National Geospatial-Intelligence Agency. All rights reserved. // import Foundation import CoreData import sf_ios import UIKit import MagicalRecord import geopackage_ios enum State: Int, CustomStringConvertible { case Archive, Active var description: String { switch self { case .Archive: return "archive" case .Active: return "active" } } } @objc public class Observation: NSManagedObject, Navigable { var orderedAttachments: [Attachment]? { get { var observationForms: [[String: Any]] = [] if let properties = self.properties as? [String: Any] { if (properties.keys.contains("forms")) { observationForms = properties["forms"] as! [[String: Any]]; } } return attachments?.sorted(by: { first, second in // return true if first comes before second, false otherwise if first.observationFormId == second.observationFormId { // if they are in the same form, sort on field if first.fieldName == second.fieldName { // if they are the same field return the order comparison unless they are both zero, then return the lat modified comparison let firstOrder = first.order?.intValue ?? 0 let secondOrder = second.order?.intValue ?? 0 return (firstOrder != secondOrder) ? (firstOrder < secondOrder) : (first.lastModified ?? Date()) < (second.lastModified ?? Date()) } else { // return the first field let form = observationForms.first { form in return form[FormKey.id.key] as? String == first.observationFormId } let firstFieldIndex = (form?[FormKey.fields.key] as? [[String: Any]])?.firstIndex { form in return form[FieldKey.name.key] as? String == first.fieldName } ?? 0 let secondFieldIndex = (form?[FormKey.fields.key] as? [[String: Any]])?.firstIndex { form in return form[FieldKey.name.key] as? String == second.fieldName } ?? 0 return firstFieldIndex < secondFieldIndex } } else { // different forms, sort on form order let firstFormIndex = observationForms.firstIndex { form in return form[FormKey.id.key] as? String == first.observationFormId } ?? 0 let secondFormIndex = observationForms.firstIndex { form in return form[FormKey.id.key] as? String == second.observationFormId } ?? 0 return firstFormIndex < secondFormIndex } }) } } var coordinate: CLLocationCoordinate2D { get { return location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0) } } public func viewRegion(mapView: MKMapView) -> MKCoordinateRegion { if let geometry = self.geometry { var latitudeMeters = 2500.0 var longitudeMeters = 2500.0 if geometry is SFPoint { if let properties = properties, let accuracy = properties[ObservationKey.accuracy.key] as? Double { latitudeMeters = accuracy * 2.5 longitudeMeters = accuracy * 2.5 } } else { let envelope = SFGeometryEnvelopeBuilder.buildEnvelope(with: geometry) let boundingBox = GPKGBoundingBox(envelope: envelope) if let size = boundingBox?.sizeInMeters() { latitudeMeters = size.height + (2 * (size.height * 0.1)) longitudeMeters = size.width + (2 * (size.width * 0.1)) } } if let centroid = geometry.centroid() { return MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: centroid.y.doubleValue, longitude: centroid.x.doubleValue), latitudinalMeters: latitudeMeters, longitudinalMeters: longitudeMeters) } } return MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0, longitude: 0), latitudinalMeters: 50000, longitudinalMeters: 50000) } static func fetchedResultsController(_ observation: Observation, delegate: NSFetchedResultsControllerDelegate) -> NSFetchedResultsController<Observation>? { let fetchRequest = Observation.fetchRequest() if let remoteId = observation.remoteId { fetchRequest.predicate = NSPredicate(format: "remoteId = %@", remoteId) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] } else { fetchRequest.predicate = NSPredicate(format: "self = %@", observation) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] } let observationFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: NSManagedObjectContext.mr_default(), sectionNameKeyPath: nil, cacheName: nil) observationFetchedResultsController.delegate = delegate do { try observationFetchedResultsController.performFetch() } catch { let fetchError = error as NSError print("Unable to Perform Fetch Request") print("\(fetchError), \(fetchError.localizedDescription)") } return observationFetchedResultsController } @objc public static func operationToPullInitialObservations(success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { return Observation.operationToPullObservations(initial: true, success: success, failure: failure); } @objc public static func operationToPullObservations(success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { return Observation.operationToPullObservations(initial: false, success: success, failure: failure); } static func operationToPullObservations(initial: Bool, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { guard let currentEventId = Server.currentEventId(), let baseURL = MageServer.baseURL() else { return nil; } let url = "\(baseURL.absoluteURL)/api/events/\(currentEventId)/observations"; print("Fetching observations from event \(currentEventId)"); var parameters: [AnyHashable : Any] = [ // does this work on the server? "sort" : "lastModified+DESC" ] if let lastObservationDate = Observation.fetchLastObservationDate(context: NSManagedObjectContext.mr_default()) { parameters["startDate"] = ISO8601DateFormatter.string(from: lastObservationDate, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]) } let manager = MageSessionManager.shared(); let methodStart = Date() NSLog("TIMING Fetching Observations for event \(currentEventId) @ \(methodStart)") let task = manager?.get_TASK(url, parameters: parameters, progress: nil, success: { task, responseObject in NSLog("TIMING Fetched Observations for event \(currentEventId). Elapsed: \(methodStart.timeIntervalSinceNow) seconds") guard let features = responseObject as? [[AnyHashable : Any]] else { success?(task, nil); return; } print("Fetched \(features.count) observations from the server, saving"); if features.count == 0 { success?(task, responseObject) return; } let saveStart = Date() NSLog("TIMING Saving Observations for event \(currentEventId) @ \(saveStart)") let rootSavingContext = NSManagedObjectContext.mr_rootSaving(); let localContext = NSManagedObjectContext.mr_context(withParent: rootSavingContext); localContext.perform { NSLog("TIMING There are \(features.count) features to save, chunking into groups of 250") localContext.mr_setWorkingName(#function) var chunks = features.chunked(into: 250); var newObservationCount = 0; var observationToNotifyAbout: Observation?; var eventFormDictionary: [NSNumber: [[String: AnyHashable]]] = [:] if let event = Event.getEvent(eventId: currentEventId, context: localContext), let eventForms = event.forms { for eventForm in eventForms { if let formId = eventForm.formId, let json = eventForm.json?.json { eventFormDictionary[formId] = json[FormKey.fields.key] as? [[String: AnyHashable]] } } } localContext.reset(); NSLog("TIMING we have \(chunks.count) groups to save") while (chunks.count > 0) { autoreleasepool { guard let features = chunks.last else { return; } chunks.removeLast(); let createObservationsDate = Date() NSLog("TIMING creating \(features.count) observations for chunk \(chunks.count)") for observation in features { if let newObservation = Observation.create(feature: observation, eventForms: eventFormDictionary, context: localContext) { newObservationCount = newObservationCount + 1; if (!initial) { observationToNotifyAbout = newObservation; } } } NSLog("TIMING created \(features.count) observations for chunk \(chunks.count) Elapsed: \(createObservationsDate.timeIntervalSinceNow) seconds") } // only save once per chunk let localSaveDate = Date() do { NSLog("TIMING saving \(features.count) observations on local context") try localContext.save() } catch { print("Error saving observations: \(error)") } NSLog("TIMING saved \(features.count) observations on local context. Elapsed \(localSaveDate.timeIntervalSinceNow) seconds") rootSavingContext.perform { let rootSaveDate = Date() do { NSLog("TIMING saving \(features.count) observations on root context") try rootSavingContext.save() } catch { print("Error saving observations: \(error)") } NSLog("TIMING saved \(features.count) observations on root context. Elapsed \(rootSaveDate.timeIntervalSinceNow) seconds") } localContext.reset(); NSLog("TIMING reset the local context for chunk \(chunks.count)") NSLog("Saved chunk \(chunks.count)") } NSLog("Received \(newObservationCount) new observations and send bulk is \(initial)") if ((initial && newObservationCount > 0) || newObservationCount > 1) { NotificationRequester.sendBulkNotificationCount(UInt(newObservationCount), in: Event.getCurrentEvent(context: localContext)); } else if let observationToNotifyAbout = observationToNotifyAbout { NotificationRequester.observationPulled(observationToNotifyAbout); } NSLog("TIMING Saved Observations for event \(currentEventId). Elapsed: \(saveStart.timeIntervalSinceNow) seconds") DispatchQueue.main.async { success?(task, responseObject); } } }, failure: { task, error in print("Error \(error)") failure?(task, error); }) return task; } @objc public static func operationToPushObservation(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error?) -> Void)?) -> URLSessionDataTask? { let archived = (observation.state?.intValue ?? 0) == State.Archive.rawValue if observation.remoteId != nil { if (archived) { return Observation.operationToDelete(observation: observation, success: success, failure: failure); } else { return Observation.operationToUpdate(observation: observation, success: success, failure: failure); } } else { return Observation.operationToCreate(observation: observation, success: success, failure: failure); } } @objc public static func operationToPushFavorite(favorite: ObservationFavorite, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { guard let eventId = favorite.observation?.eventId, let observationRemoteId = favorite.observation?.remoteId, let baseURL = MageServer.baseURL() else { return nil; } let url = "\(baseURL.absoluteURL)/api/events/\(eventId)/observations/\(observationRemoteId)/favorite"; NSLog("Trying to push favorite to server \(url)") let manager = MageSessionManager.shared(); if (!favorite.favorite) { return manager?.delete_TASK(url, parameters: nil, success: success, failure: failure); } else { return manager?.put_TASK(url, parameters: nil, success: success, failure: failure); } } @objc public static func operationToPushImportant(important: ObservationImportant, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { guard let eventId = important.observation?.eventId, let observationRemoteId = important.observation?.remoteId, let baseURL = MageServer.baseURL() else { return nil; } let url = "\(baseURL.absoluteURL)/api/events/\(eventId)/observations/\(observationRemoteId)/important"; NSLog("Trying to push favorite to server \(url)") let manager = MageSessionManager.shared(); if (important.important) { let parameters: [String : String?] = [ ObservationImportantKey.description.key : important.reason ] return manager?.put_TASK(url, parameters: parameters, success: success, failure: failure); } else { return manager?.delete_TASK(url, parameters: nil, success: success, failure: failure); } } static func operationToDelete(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error?) -> Void)?) -> URLSessionDataTask? { NSLog("Trying to delete observation \(observation.url ?? "no url")"); let deleteMethod = MAGERoutes.observation().deleteRoute(observation); let manager = MageSessionManager.shared(); return manager?.post_TASK(deleteMethod.route, parameters: deleteMethod.parameters, progress: nil, success: { task, responseObject in // if the delete worked, remove the observation from the database on the phone MagicalRecord.save { context in observation.mr_deleteEntity(in: context); } completion: { contextDidSave, error in // TODO: why are we calling failure here? // I think because the ObservationPushService is going to try to parse the response and update the observation which we do not want failure?(task, nil); } }, failure: { task, error in NSLog("Failure to delete") let error = error as NSError if let data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data { let errorString = String(data: data, encoding: .utf8); NSLog("Error deleting observation \(errorString ?? "unknown error")"); if let response = task?.response as? HTTPURLResponse { if (response.statusCode == 404) { // Observation does not exist on the server, delete it MagicalRecord.save { context in observation.mr_deleteEntity(in: context); } completion: { contextDidSave, error in // TODO: why are we calling failure here? // I think because the ObservationPushService is going to try to parse the response and update the observation which we do not want failure?(task, nil); } } } else { failure?(task, error); } } else { failure?(task, error); } }); } static func operationToUpdate(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { NSLog("Trying to update observation \(observation.url ?? "unknown url")") let manager = MageSessionManager.shared(); guard let context = observation.managedObjectContext, let event = Event.getCurrentEvent(context:context) else { return nil; } if (MageServer.isServerVersion5) { if let observationUrl = observation.url { return manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure); } } else { //} if MageServer.isServerVersion6_0() { if let observationUrl = observation.url { return manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure); } } // else { // // TODO: 6.1 and above // if let observationUrl = observation.url { // return manager?.patch_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure); // } // } return nil; } static func operationToCreate(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? { let create = MAGERoutes.observation().createId(observation); NSLog("Trying to create observation %@", create.route); let manager = MageSessionManager.shared(); let task = manager?.post_TASK(create.route, parameters: nil, progress: nil, success: { task, response in NSLog("Successfully created location for observation resource"); guard let response = response as? [AnyHashable : Any], let observationUrl = response[ObservationKey.url.key] as? String, let remoteId = response[ObservationKey.id.key] as? String else { return; } MagicalRecord.save { context in guard let localObservation = observation.mr_(in: context) else { return; } localObservation.remoteId = remoteId localObservation.url = observationUrl; } completion: { contextDidSave, error in if !contextDidSave { NSLog("Failed to save observation to DB after getting an ID") } guard let context = observation.managedObjectContext, let event = Event.getCurrentEvent(context: context) else { return; } let putTask = manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: { task, response in print("successfully submitted observation") success?(task, response); }, failure: { task, error in print("failure"); }); manager?.addTask(putTask); } }, failure: failure) return task; } func fieldNameToField(formId: NSNumber, name: String) -> [AnyHashable : Any]? { if let managedObjectContext = managedObjectContext, let form : Form = Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext) { return form.getFieldByName(name: name) } return nil } func createJsonToSubmit(event: Event) -> [AnyHashable : Any] { var observationJson: [AnyHashable : Any] = [:] if let remoteId = self.remoteId { observationJson[ObservationKey.id.key] = remoteId; } if let userId = self.userId { observationJson[ObservationKey.userId.key] = userId; } if let deviceId = self.deviceId { observationJson[ObservationKey.deviceId.key] = deviceId; } if let url = self.url { observationJson[ObservationKey.url.key] = url; } observationJson[ObservationKey.type.key] = "Feature"; let state = self.state?.intValue ?? State.Active.rawValue observationJson[ObservationKey.state.key] = ["name":(State(rawValue: state) ?? .Active).description] if let geometry = self.geometry { observationJson[ObservationKey.geometry.key] = GeometrySerializer.serializeGeometry(geometry); } if let timestamp = self.timestamp { observationJson[ObservationKey.timestamp.key] = ISO8601DateFormatter.string(from: timestamp, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]); } var jsonProperties : [AnyHashable : Any] = self.properties ?? [:] var attachmentsToDelete : [String: [String : [Attachment]]] = [:] if (!MageServer.isServerVersion5) { // check for attachments marked for deletion and be sure to add them to the form properties if let attachments = attachments { for case let attachment in attachments where attachment.markedForDeletion { var attachmentsPerForm: [String : [Attachment]] = [:] if let observationFormId = attachment.observationFormId, let currentAttachmentsPerForm = attachmentsToDelete[observationFormId] { attachmentsPerForm = currentAttachmentsPerForm; } var attachmentsInField: [Attachment] = []; if let fieldName = attachment.fieldName, let currentAttachmentsInField = attachmentsPerForm[fieldName] { attachmentsInField = currentAttachmentsInField; } attachmentsInField.append(attachment); if let fieldName = attachment.fieldName, let observationFormId = attachment.observationFormId { attachmentsPerForm[fieldName] = attachmentsInField; attachmentsToDelete[observationFormId] = attachmentsPerForm } } } } let forms = jsonProperties[ObservationKey.forms.key] as? [[String: Any]] var formArray: [Any] = []; if let forms = forms { for form in forms { var formProperties: [String: Any] = form; for (key, value) in form { if let formId = form[FormKey.formId.key] as? NSNumber { if let field = self.fieldNameToField(formId: formId, name:key) { if let fieldType = field[FieldKey.type.key] as? String, fieldType == FieldType.geometry.key { if let fieldGeometry = value as? SFGeometry { formProperties[key] = GeometrySerializer.serializeGeometry(fieldGeometry); } } else if let fieldType = field[FieldKey.type.key] as? String, fieldType == FieldType.attachment.key { // filter out the unsent attachemnts which are marked for deletion var newAttachments:[[AnyHashable:Any]] = [] if let currentAttachments = formProperties[key] as? [[AnyHashable:Any]] { for attachment in currentAttachments { if let markedForDeletion = attachment[AttachmentKey.markedForDeletion.key] as? Int, markedForDeletion == 1 { //skip it } else { newAttachments.append(attachment) } } formProperties[key] = newAttachments } } } } } // check for deleted attachments and add them to the proper field if let formId = form[FormKey.id.key] as? String, let attachmentsToDeleteForForm = attachmentsToDelete[formId] { for (field, attachmentsToDeleteForField) in attachmentsToDeleteForForm { var newAttachments: [[AnyHashable : Any]] = []; if let value = form[field] as? [[AnyHashable : Any]] { newAttachments = value; } for a in attachmentsToDeleteForField { if let remoteId = a.remoteId { newAttachments.append([ AttachmentKey.id.key: remoteId, AttachmentKey.action.key: "delete" ]) } } formProperties[field] = newAttachments; } } formArray.append(formProperties); } } jsonProperties[ObservationKey.forms.key] = formArray; observationJson[ObservationKey.properties.key] = jsonProperties; return observationJson; } @objc public static func fetchLastObservationDate(context: NSManagedObjectContext) -> Date? { let user = User.fetchCurrentUser(context: context); if let userRemoteId = user?.remoteId, let currentEventId = Server.currentEventId() { let observation = Observation.mr_findFirst(with: NSPredicate(format: "\(ObservationKey.eventId.key) == %@ AND user.\(UserKey.remoteId.key) != %@", currentEventId, userRemoteId), sortedBy: ObservationKey.lastModified.key, ascending: false, in:context); return observation?.lastModified; } return nil; } @discardableResult @objc public static func create(geometry: SFGeometry?, date: Date? = nil, accuracy: CLLocationAccuracy, provider: String?, delta: Double, context: NSManagedObjectContext) -> Observation { var observationDate = date ?? Date(); observationDate = Calendar.current.date(bySetting: .second, value: 0, of: observationDate)! observationDate = Calendar.current.date(bySetting: .nanosecond, value: 0, of: observationDate)! let observation = Observation.mr_createEntity(in: context)!; observation.timestamp = observationDate; var properties: [AnyHashable : Any] = [:]; properties[ObservationKey.timestamp.key] = ISO8601DateFormatter.string(from: observationDate, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]) if let geometry = geometry, let provider = provider { properties[ObservationKey.provider.key] = provider; if (provider != "manual") { properties[ObservationKey.accuracy.key] = accuracy; properties[ObservationKey.delta.key] = delta; } observation.geometry = geometry; } properties[ObservationKey.forms.key] = []; observation.properties = properties; observation.user = User.fetchCurrentUser(context: context); observation.dirty = false; observation.state = NSNumber(value: State.Active.rawValue) observation.eventId = Server.currentEventId(); return observation; } static func idFromJson(json: [AnyHashable : Any]) -> String? { return json[ObservationKey.id.key] as? String } static func stateFromJson(json: [AnyHashable : Any]) -> State { if let stateJson = json[ObservationKey.state.key] as? [AnyHashable : Any], let stateName = stateJson["name"] as? String { if stateName == State.Archive.description { return State.Archive } else { return State.Active; } } return State.Active; } @discardableResult @objc public static func create(feature: [AnyHashable : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil, context:NSManagedObjectContext) -> Observation? { var newObservation: Observation? = nil; let remoteId = Observation.idFromJson(json: feature); let state = Observation.stateFromJson(json: feature); // NSLog("TIMING create the observation \(remoteId)") if let remoteId = remoteId, let existingObservation = Observation.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: remoteId, in: context) { // if the observation is archived, delete it if state == .Archive { NSLog("Deleting archived observation with id: %@", remoteId); existingObservation.mr_deleteEntity(in: context); } else if !existingObservation.isDirty { // if the observation is not dirty, and has been updated, update it if let lastModified = feature[ObservationKey.lastModified.key] as? String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]; formatter.timeZone = TimeZone(secondsFromGMT: 0)!; let lastModifiedDate = formatter.date(from: lastModified) ?? Date(); if lastModifiedDate == existingObservation.lastModified { // If the last modified date for this observation has not changed no need to update. return newObservation } } existingObservation.populate(json: feature, eventForms: eventForms); if let userId = existingObservation.userId { if let user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context) { existingObservation.user = user if user.lastUpdated == nil { // new user, go fetch let manager = MageSessionManager.shared(); let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in NSLog("Fetched user \(userId) successfully.") } failure: { task, error in NSLog("Failed to fetch user \(userId) error \(error)") } manager?.addTask(fetchUserTask) } } else { // new user, go fetch let manager = MageSessionManager.shared(); let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in NSLog("Fetched user \(userId) successfully.") existingObservation.user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context) } failure: { task, error in NSLog("Failed to fetch user \(userId) error \(error)") } manager?.addTask(fetchUserTask) } } if let importantJson = feature[ObservationKey.important.key] as? [String : Any] { if let important = ObservationImportant.important(json: importantJson, context: context) { important.observation = existingObservation; existingObservation.observationImportant = important; } } else if let existingObservationImportant = existingObservation.observationImportant { existingObservationImportant.mr_deleteEntity(in: context); existingObservation.observationImportant = nil; } let favoritesMap = existingObservation.favoritesMap; let favoriteUserIds = (feature[ObservationKey.favoriteUserIds.key] as? [String]) ?? [] for favoriteUserId in favoriteUserIds { if favoritesMap[favoriteUserId] == nil { if let favorite = ObservationFavorite.favorite(userId: favoriteUserId, context: context) { favorite.observation = existingObservation; existingObservation.addToFavorites(favorite); } } } for (userId, favorite) in favoritesMap { if !favoriteUserIds.contains(userId) { favorite.mr_deleteEntity(in: context); existingObservation.removeFromFavorites(favorite); } } if let attachmentsJson = feature[ObservationKey.attachments.key] as? [[AnyHashable : Any]] { for (index, attachmentJson) in attachmentsJson.enumerated() { var attachmentFound = false; if let remoteId = attachmentJson[AttachmentKey.id.key] as? String, let attachments = existingObservation.attachments { for attachment in attachments { if remoteId == attachment.remoteId { attachment.contentType = attachmentJson[AttachmentKey.contentType.key] as? String attachment.name = attachmentJson[AttachmentKey.name.key] as? String attachment.size = attachmentJson[AttachmentKey.size.key] as? NSNumber attachment.url = attachmentJson[AttachmentKey.url.key] as? String attachment.remotePath = attachmentJson[AttachmentKey.remotePath.key] as? String attachment.observation = existingObservation; attachment.order = NSNumber(value: index) attachmentFound = true; break; } } } if !attachmentFound { if let attachment = Attachment.attachment(json: attachmentJson, order: index, context: context) { existingObservation.addToAttachments(attachment); } } } } } } else { if state != .Archive { // if the observation doesn't exist, insert it if let observation = Observation.mr_createEntity(in: context) { observation.populate(json: feature, eventForms: eventForms); if let userId = observation.userId { if let user = User.mr_findFirst(byAttribute: UserKey.remoteId.key, withValue: userId, in: context) { observation.user = user // this could happen if we pulled the teams and know this user belongs on a team // but did not pull the user information because the bulk user pull failed if user.lastUpdated == nil { // new user, go fetch let manager = MageSessionManager.shared(); let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in NSLog("Fetched user \(userId) successfully.") } failure: { task, error in NSLog("Failed to fetch user \(userId) error \(error)") } manager?.addTask(fetchUserTask) } } else { // new user, go fetch let manager = MageSessionManager.shared(); let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in NSLog("Fetched user \(userId) successfully.") observation.user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context) } failure: { task, error in NSLog("Failed to fetch user \(userId) error \(error)") } manager?.addTask(fetchUserTask) } } if let importantJson = feature[ObservationKey.important.key] as? [String : Any] { if let important = ObservationImportant.important(json: importantJson, context: context) { important.observation = observation; observation.observationImportant = important; } } if let favoriteUserIds = feature[ObservationKey.favoriteUserIds.key] as? [String] { for favoriteUserId in favoriteUserIds { if let favorite = ObservationFavorite.favorite(userId: favoriteUserId, context: context) { favorite.observation = observation; observation.addToFavorites(favorite); } } } if let attachmentsJson = feature[ObservationKey.attachments.key] as? [[AnyHashable : Any]] { for (index, attachmentJson) in attachmentsJson.enumerated() { if let attachment = Attachment.attachment(json: attachmentJson, order: index, context: context) { observation.addToAttachments(attachment); } } } newObservation = observation; } } } return newObservation; } @objc public static func isRectangle(points: [SFPoint]) -> Bool { let size = points.count if size == 4 || size == 5 { let point1 = points[0] let lastPoint = points[size - 1] let closed: Bool = point1.x == lastPoint.x && point1.y == lastPoint.y; if ((closed && size == 5) || (!closed && size == 4)) { let point2 = points[1] let point3 = points[2] let point4 = points[3] if ((point1.x == point2.x) && (point2.y == point3.y)) { if ((point1.y == point4.y) && (point3.x == point4.x)) { return true; } } else if ((point1.y == point2.y) && (point2.x == point3.x)) { if ((point1.x == point4.x) && (point3.y == point4.y)) { return true; } } } } return false; } @discardableResult @objc public func populate(json: [AnyHashable : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil) -> Observation { self.eventId = json[ObservationKey.eventId.key] as? NSNumber self.remoteId = Observation.idFromJson(json: json); self.userId = json[ObservationKey.userId.key] as? String self.deviceId = json[ObservationKey.deviceId.key] as? String self.dirty = false if let properties = json[ObservationKey.properties.key] as? [String : Any] { self.properties = self.generateProperties(propertyJson: properties, eventForms: eventForms); } if let lastModified = json[ObservationKey.lastModified.key] as? String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]; formatter.timeZone = TimeZone(secondsFromGMT: 0)!; self.lastModified = formatter.date(from: lastModified); } if let timestamp = self.properties?[ObservationKey.timestamp.key] as? String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]; formatter.timeZone = TimeZone(secondsFromGMT: 0)!; self.timestamp = formatter.date(from: timestamp); } self.url = json[ObservationKey.url.key] as? String let state = Observation.stateFromJson(json: json); self.state = NSNumber(value: state.rawValue) self.geometry = GeometryDeserializer.parseGeometry(json: json[ObservationKey.geometry.key] as? [AnyHashable : Any]) return self; } func generateProperties(propertyJson: [String : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil) -> [AnyHashable : Any] { var parsedProperties: [String : Any] = [:] if self.event == nil { return parsedProperties; } for (key, value) in propertyJson { if key == ObservationKey.forms.key { var forms:[[String : Any]] = [] if let formsProperties = value as? [[String : Any]] { for formProperties in formsProperties { var parsedFormProperties:[String:Any] = formProperties; if let formId = formProperties[EventKey.formId.key] as? NSNumber { var formFields: [[String: AnyHashable]]? = nil if let eventForms = eventForms { formFields = eventForms[formId] } else if let managedObjectContext = managedObjectContext, let fetchedForm : Form = Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext) { formFields = fetchedForm.json?.json?[FormKey.fields.key] as? [[String: AnyHashable]] } if let formFields = formFields { for (formKey, value) in formProperties { if let field = Form.getFieldByNameFromJSONFields(json: formFields, name: formKey) { if let type = field[FieldKey.type.key] as? String, type == FieldType.geometry.key { if let value = value as? [String: Any] { let geometry = GeometryDeserializer.parseGeometry(json: value) parsedFormProperties[formKey] = geometry; } } } } } forms.append(parsedFormProperties); } } } parsedProperties[ObservationKey.forms.key] = forms; } else { parsedProperties[key] = value; } } return parsedProperties; } @objc public func addTransientAttachment(attachment: Attachment) { self.transientAttachments.append(attachment); } @objc public var transientAttachments: [Attachment] = []; @objc public var geometry: SFGeometry? { get { if let geometryData = self.geometryData { return SFGeometryUtils.decodeGeometry(geometryData); } return nil } set { if let newValue = newValue { self.geometryData = SFGeometryUtils.encode(newValue); } else { self.geometryData = nil } } } @objc public var location: CLLocation? { get { if let geometry = geometry, let centroid = SFGeometryUtils.centroid(of: geometry) { return CLLocation(latitude: centroid.y.doubleValue, longitude: centroid.x.doubleValue); } return CLLocation(latitude: 0, longitude: 0); } } @objc public var isDirty: Bool { get { return self.dirty } } @objc public var isImportant: Bool { get { if let observationImportant = self.observationImportant, observationImportant.important { return true; } return false; } } @objc public var isDeletableByCurrentUser: Bool { get { guard let managedObjectContext = self.managedObjectContext, let currentUser = User.fetchCurrentUser(context: managedObjectContext), let event = self.event else { return false; } // if the user has update on the event if let userRemoteId = currentUser.remoteId, let acl = event.acl, let userAcl = acl[userRemoteId] as? [String : Any], let userPermissions = userAcl[PermissionsKey.permissions.key] as? [String] { if (userPermissions.contains(PermissionsKey.update.key)) { return true; } } // if the user has DELETE_OBSERVATION permission if let role = currentUser.role, let rolePermissions = role.permissions { if rolePermissions.contains(PermissionsKey.DELETE_OBSERVATION.key) { return true; } } // If the observation was created by this user if let userRemoteId = currentUser.remoteId, let user = self.user { if userRemoteId == user.remoteId { return true; } } return false; } } @objc public var currentUserCanUpdateImportant: Bool { get { guard let managedObjectContext = self.managedObjectContext, let currentUser = User.fetchCurrentUser(context: managedObjectContext), let event = self.event else { return false; } // if the user has update on the event if let userRemoteId = currentUser.remoteId, let acl = event.acl, let userAcl = acl[userRemoteId] as? [String : Any], let userPermissions = userAcl[PermissionsKey.permissions.key] as? [String] { if (userPermissions.contains(PermissionsKey.update.key)) { return true; } } // if the user has UPDATE_EVENT permission if let role = currentUser.role, let rolePermissions = role.permissions { if rolePermissions.contains(PermissionsKey.UPDATE_EVENT.key) { return true; } } return false; } } var event : Event? { get { if let eventId = self.eventId, let managedObjectContext = self.managedObjectContext { return Event.getEvent(eventId: eventId, context: managedObjectContext) } return nil; } } @objc public var hasValidationError: Bool { get { if let error = self.error { return error[ObservationPushService.ObservationErrorStatusCode] != nil } return false; } } @objc public var errorMessage: String { get { if let error = self.error { if let errorMessage = error[ObservationPushService.ObservationErrorMessage] as? String { return errorMessage } else if let errorMessage = error[ObservationPushService.ObservationErrorDescription] as? String { return errorMessage } } return ""; } } @objc public var formsToBeDeleted: NSMutableIndexSet = NSMutableIndexSet() @objc public func clearFormsToBeDeleted() { formsToBeDeleted = NSMutableIndexSet() } @objc public func addFormToBeDeleted(formIndex: Int) { self.formsToBeDeleted.add(formIndex); } @objc public func removeFormToBeDeleted(formIndex: Int) { self.formsToBeDeleted.remove(formIndex); } @objc public var primaryObservationForm: [AnyHashable : Any]? { get { if let properties = self.properties, let forms = properties[ObservationKey.forms.key] as? [[AnyHashable:Any]] { for (index, form) in forms.enumerated() { // here we can ignore forms which will be deleted if !self.formsToBeDeleted.contains(index) { return form; } } } return nil } } @objc public var primaryEventForm: Form? { get { if let primaryObservationForm = primaryObservationForm, let formId = primaryObservationForm[EventKey.formId.key] as? NSNumber { return Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext ?? NSManagedObjectContext.mr_default()) } return nil; } } @objc public var primaryField: String? { get { if let primaryEventForm = primaryEventForm { return primaryEventForm.primaryMapField?[FieldKey.name.key] as? String } return nil } } @objc public var secondaryField: String? { get { if let primaryEventForm = primaryEventForm { return primaryEventForm.secondaryMapField?[FieldKey.name.key] as? String } return nil } } @objc public var primaryFieldText: String? { get { if let primaryField = primaryEventForm?.primaryMapField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let primaryFieldName = primaryField[FieldKey.name.key] as? String, observationForms.count > 0 { let value = self.primaryObservationForm?[primaryFieldName] return Observation.fieldValueText(value: value, field: primaryField) } return nil; } } @objc public var secondaryFieldText: String? { get { if let variantField = primaryEventForm?.secondaryMapField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let variantFieldName = variantField[FieldKey.name.key] as? String, observationForms.count > 0 { let value = self.primaryObservationForm?[variantFieldName] return Observation.fieldValueText(value: value, field: variantField) } return nil; } } @objc public var primaryFeedFieldText: String? { get { if let primaryFeedField = primaryEventForm?.primaryFeedField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let primaryFeedFieldName = primaryFeedField[FieldKey.name.key] as? String, observationForms.count > 0 { let value = primaryObservationForm?[primaryFeedFieldName] return Observation.fieldValueText(value: value, field: primaryFeedField) } return nil; } } @objc public var secondaryFeedFieldText: String? { get { if let secondaryFeedField = primaryEventForm?.secondaryFeedField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let secondaryFeedFieldName = secondaryFeedField[FieldKey.name.key] as? String, observationForms.count > 0 { let value = self.primaryObservationForm?[secondaryFeedFieldName] return Observation.fieldValueText(value: value, field: secondaryFeedField) } return nil; } } @objc public static func fieldValueText(value: Any?, field: [AnyHashable : Any]) -> String { guard let value = value, let type = field[FieldKey.type.key] as? String else { return ""; } if type == FieldType.geometry.key { var geometry: SFGeometry?; if let valueDictionary = value as? [AnyHashable : Any] { geometry = GeometryDeserializer.parseGeometry(json: valueDictionary); } else { geometry = value as? SFGeometry } if let geometry = geometry, let centroid = SFGeometryUtils.centroid(of: geometry) { return "\(String(format: "%.6f", centroid.y.doubleValue)), \(String(format: "%.6f", centroid.x.doubleValue))" } } else if type == FieldType.date.key { if let value = value as? String { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]; formatter.timeZone = TimeZone(secondsFromGMT: 0)!; let date = formatter.date(from: value); return (date as NSDate?)?.formattedDisplay() ?? ""; } } else if type == FieldType.checkbox.key { if let value = value as? Bool { if value { return "YES" } else { return "NO" } } else if let value = value as? NSNumber { if value == 1 { return "YES" } else { return "NO" } } } else if type == FieldType.numberfield.key { return String(describing:value); } else if type == FieldType.multiselectdropdown.key { if let value = value as? [String] { return value.joined(separator: ", ") } } else if (type == FieldType.textfield.key || type == FieldType.textarea.key || type == FieldType.email.key || type == FieldType.password.key || type == FieldType.radio.key || type == FieldType.dropdown.key) { if let value = value as? String { return value; } } return ""; } @objc public func toggleFavorite(completion:((Bool,Error?) -> Void)?) { MagicalRecord.save({ [weak self] localContext in if let localObservation = self?.mr_(in: localContext), let user = User.fetchCurrentUser(context: localContext), let userRemoteId = user.remoteId { if let favorite = localObservation.favoritesMap[userRemoteId], favorite.favorite { // toggle off favorite.dirty = true; favorite.favorite = false } else { // toggle on if let favorite = localObservation.favoritesMap[userRemoteId] { favorite.dirty = true; favorite.favorite = true favorite.userId = userRemoteId } else { if let favorite = ObservationFavorite.mr_createEntity(in: localContext) { localObservation.addToFavorites(favorite); favorite.observation = localObservation; favorite.dirty = true; favorite.favorite = true favorite.userId = userRemoteId } } } } }, completion: completion) } @objc public var favoritesMap: [String : ObservationFavorite] { get { var favoritesMap: [String:ObservationFavorite] = [:] if let favorites = self.favorites { for favorite in favorites { if let userId = favorite.userId { favoritesMap[userId] = favorite } } } return favoritesMap } } @objc public func flagImportant(description: String, completion:((Bool,Error?) -> Void)?) { if !self.currentUserCanUpdateImportant { completion?(false, nil); return; } MagicalRecord.save({ [weak self] localContext in if let localObservation = self?.mr_(in: localContext), let user = User.fetchCurrentUser(context: localContext), let userRemoteId = user.remoteId { if let important = self?.observationImportant { important.dirty = true; important.important = true; important.userId = userRemoteId; important.reason = description // this will get overridden by the server, but let's set an initial value so the UI has something to display important.timestamp = Date(); } else { if let important = ObservationImportant.mr_createEntity(in: localContext) { important.observation = localObservation localObservation.observationImportant = important; important.dirty = true; important.important = true; important.userId = userRemoteId; important.reason = description // this will get overridden by the server, but let's set an initial value so the UI has something to display important.timestamp = Date(); } } } }, completion: completion) } @objc public func removeImportant(completion:((Bool,Error?) -> Void)?) { if !self.currentUserCanUpdateImportant { completion?(false, nil); return; } MagicalRecord.save({ [weak self] localContext in if let localObservation = self?.mr_(in: localContext), let user = User.fetchCurrentUser(context: localContext), let userRemoteId = user.remoteId { if let important = self?.observationImportant { important.dirty = true; important.important = false; important.userId = userRemoteId; important.reason = nil // this will get overridden by the server, but let's set an initial value so the UI has something to display important.timestamp = Date(); } else { if let important = ObservationImportant.mr_createEntity(in: localContext) { important.observation = localObservation localObservation.observationImportant = important; important.dirty = true; important.important = false; important.userId = userRemoteId; important.reason = nil // this will get overridden by the server, but let's set an initial value so the UI has something to display important.timestamp = Date(); } } } }, completion: completion) } @objc public func delete(completion:((Bool,Error?) -> Void)?) { if !self.isDeletableByCurrentUser { completion?(false, nil); return; } if self.remoteId != nil { self.state = NSNumber(value: State.Archive.rawValue) self.dirty = true self.managedObjectContext?.mr_saveToPersistentStore(completion: completion) } else { MagicalRecord.save({ [weak self] localContext in self?.mr_deleteEntity(in: localContext); }, completion: completion) } } }
f732586b385e191fdc0f420386368514
48.98597
280
0.545609
false
false
false
false
JGiola/swift
refs/heads/main
test/Concurrency/Runtime/async_task_locals_groups.swift
apache-2.0
9
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: rdar82092187 // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.1, *) enum TL { @TaskLocal static var number = 0 } @available(SwiftStdlib 5.1, *) @discardableResult func printTaskLocal<V>( _ key: TaskLocal<V>, _ expected: V? = nil, file: String = #file, line: UInt = #line ) -> V? { let value = key.get() print("\(key) (\(value)) at \(file):\(line)") if let expected = expected { assert("\(expected)" == "\(value)", "Expected [\(expected)] but found: \(value), at \(file):\(line)") } return expected } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.1, *) func groups() async { // no value _ = await withTaskGroup(of: Int.self) { group in printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) } // no value in parent, value in child let x1: Int = await withTaskGroup(of: Int.self) { group in group.spawn { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) // inside the child task, set a value _ = TL.$number.withValue(1) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (1) } printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) return TL.$number.get() // 0 } return await group.next()! } assert(x1 == 0) // value in parent and in groups await TL.$number.withValue(2) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) let x2: Int = await withTaskGroup(of: Int.self) { group in printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) group.spawn { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) async let childInsideGroupChild = printTaskLocal(TL.$number) _ = await childInsideGroupChild // CHECK: TaskLocal<Int>(defaultValue: 0) (2) return TL.$number.get() } printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) return await group.next()! } assert(x2 == 2) } } @available(SwiftStdlib 5.1, *) func taskInsideGroup() async { Task { print("outside") // CHECK: outside _ = await withTaskGroup(of: Int.self) { group -> Int in print("in group") // CHECK: in group printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) for _ in 0..<5 { Task { printTaskLocal(TL.$number) print("some task") } } return 0 } } // CHECK: some task // CHECK: some task // CHECK: some task // CHECK: some task await Task.sleep(5 * 1_000_000_000) // await t.value } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { await groups() await taskInsideGroup() } }
d4fa17d1f31e879d29d0c754a7851be9
25.632479
130
0.604621
false
false
false
false
Decybel07/L10n-swift
refs/heads/master
Example/Example iOS/Scenes/Plurals/PluralsViewController.swift
mit
1
// // PluralsViewController.swift // Example // // Created by Adrian Bobrowski on 17.08.2017. // // import UIKit import L10n_swift final class PluralsViewController: UIViewController { // MARK: - @IBOutlet @IBOutlet weak var tableView: UITableView! @IBOutlet weak var stepper: UIStepper! @IBOutlet weak var numberField: UITextField! // MARK: - variable fileprivate var items: [L10n] = L10n.supportedLanguages.map { L10n(language: $0) } fileprivate var value: Int = 0 // MARK: - @IBAction @IBAction private func onTapped() { self.view.endEditing(true) } @IBAction private func onFieldValueChanged(_ sender: UITextField) { let value = Int(sender.text ?? "") ?? 0 self.stepper.value = Double(value) self.onValueChanged(value) } @IBAction private func onStepperValueChanged(_ sender: UIStepper) { let value = Int(sender.value) self.numberField.text = value.description self.onValueChanged(value) } private func onValueChanged(_ value: Int) { self.value = value self.tableView.reloadData() } } // MARK: - UITableViewDataSource extension PluralsViewController: UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return self.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "plural", for: indexPath) let item = self.items[indexPath.row] cell.textLabel?.text = L10n.shared.locale?.localizedString(forLanguageCode: item.language) cell.detailTextLabel?.text = "plurals.numberOfApples".l10nPlural(instance: item, self.value) return cell } }
15803c060ba90da125c6d9440be1a579
23.837838
100
0.665941
false
false
false
false
jeroendesloovere/examples-swift
refs/heads/master
Swift-Playgrounds/SwiftStanardLibrary/Dictionary.playground/section-1.swift
mit
1
// Swift Standard Library - Types - Dictionary var emptyDictionary = Dictionary<String, Int>() var equivilentEmptyDictionary = [String: Int]() var anotherEmptyDictionary = Dictionary<String, Int>(minimumCapacity: 10) var literalDictionary = ["a":1] // Accessing and Changing Dictionary Elements var dictionary = ["one": 1, "two": 2, "three": 3] let value = dictionary["two"] if let unwrappedValue = dictionary["three"] { println("The integer value for \"three\" was: \(unwrappedValue)") unwrappedValue } dictionary["three"] = 33 dictionary // You can add to a dictionary using subscripting dictionary["four"] = 4 dictionary // you can remove a value for a key by setting it to nil dictionary["three"] = nil dictionary // You can't change, add or remove elements to a constant dictionary dictionary = ["one": 1, "two": 2, "three": 3] let previousValue = dictionary.updateValue(22, forKey: "two") dictionary if let unwrappedPreviousValue = dictionary.updateValue(33, forKey: "three") { println("Replaced the previous value: \(unwrappedPreviousValue)") } else { println("Added a new value") } dictionary = ["one": 1, "two": 2, "three": 3] let prevValue = dictionary.removeValueForKey("two") if let unwrappedPreviousValue = dictionary.removeValueForKey("three") { println("Removed the old value: \(unwrappedPreviousValue)") } else { println("Didn't find a value for the given key to delete") } dictionary.removeAll() dictionary // Querying a Dictionary dictionary = ["one": 1, "two": 2, "three": 3] let elementCount = dictionary.count for key in dictionary.keys { println("Key: \(key)") } let keysArray = Array(dictionary.keys) for value in dictionary.values { println("Value: \(value)") } let valuesArray = Array(dictionary.values) // Operators let dictionary1 = ["one": 1, "two": 2] var dictionary2 = ["one": 1] dictionary2["two"] = 2 let result = dictionary1 == dictionary2 dictionary2 = ["one": 1] let secondResult = dictionary1 != dictionary2
11cff44ef6efd66c717d4369955e7d6e
24.615385
77
0.710711
false
false
false
false
didinozka/Projekt_Bakalarka
refs/heads/master
bp_v1/BeaconBluetoothDiscovery.swift
apache-2.0
1
// // BeaconBluetoothFinder.swift // bp_v1 // // Created by Dusan Drabik on 17/03/16. // Copyright © 2016 Dusan Drabik. All rights reserved. // import Foundation import CoreBluetooth class BeaconBluetoothDiscovery: NSObject, CBCentralManagerDelegate { private var _btCentralManager: CBCentralManager! private var _btAlowed = false private var _isDiscovering = false var delegate: BTPeripheralDiscoveryDelegate? override init() { super.init() _btCentralManager = CBCentralManager() _btCentralManager.delegate = self } func startDiscoveringPeripherals() { //checkBtState() if _btAlowed { print("BeaconBluetoothDiscovery: Searching BT peripherals...") _btCentralManager.scanForPeripheralsWithServices(nil, options: nil) } } func stopDiscoveringPeripherals() { _btCentralManager.stopScan() print("BeaconBluetoothDiscovery: Scanning for BT peripherals stopped.") } func checkBtState() { debugPrint("BeaconBluetoothDiscovery: Checking state") switch _btCentralManager.state { case .PoweredOff: print("BeaconBluetoothDiscovery: BT is powered off") // todo create alert to turn on bt case .PoweredOn: print("BeaconBluetoothDiscovery: BT is powered on") _btAlowed = true case .Unauthorized: print("BeaconBluetoothDiscovery: BT usage is unauthorized") case .Unsupported: print("BeaconBluetoothDiscovery: BT is unsupported") case .Resetting : print("BeaconBluetoothDiscovery: BT module resetting") default : print("BeaconBluetoothDiscovery: Some unidentified problem with BT module") } } func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { print(peripheral) } @objc func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData:[String : AnyObject], RSSI: NSNumber){ print(peripheral) print(advertisementData) print("\(peripheral)") central.connectPeripheral(peripheral, options: nil) if delegate != nil { delegate?.peripheralDidDiscovered(didDiscoveredPeripheral: peripheral, advertisedData: advertisementData, RSSI: RSSI) }else { print("BeaconBluetoothDiscovery: Delegate not set") } } @objc func centralManagerDidUpdateState(central: CBCentralManager) { checkBtState() if _btAlowed == false { return } if _isDiscovering == false { startDiscoveringPeripherals() _isDiscovering = true }else { stopDiscoveringPeripherals() _isDiscovering = false } } }
df14beb3689e56c742b1d8b91b513f10
28.349515
161
0.619583
false
false
false
false
phakphumi/Chula-Expo-iOS-Application
refs/heads/master
Chula Expo 2017/Chula Expo 2017/Third_events/EventsTableViewController.swift
mit
1
// // EventsTableViewController.swift // Chula Expo 2017 // // Created by PANUPONG TONGTAWACH on 1/7/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import UIKit import CoreData class EventsTableViewController: CoreDataTableViewController { var facity: String? { didSet { updateData() } } var interestDesc: String? var managedObjectContext: NSManagedObjectContext? { didSet { updateData() } } var facityBanner: String? var facityName: String? var facityDesc: String? var facityTag: String? // var isFaculty = false var isInterest = false fileprivate func updateData() { if let facity = facity { if let context = managedObjectContext, (facity.characters.count) > 0 { if facity == "Reservation" { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ReservedActivity") title = "MY RESERVATION" request.sortDescriptors = [NSSortDescriptor( key: "toActivity.start", ascending: true )] fetchedResultsController = NSFetchedResultsController( fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) } else if facity == "Favorite" { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "FavoritedActivity") title = "MY FAVORITE" request.sortDescriptors = [NSSortDescriptor( key: "toActivity.start", ascending: true )] fetchedResultsController = NSFetchedResultsController( fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) } else if isInterest { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ActivityData") request.predicate = NSPredicate(format: "ANY toTags.name == %@", facity) request.sortDescriptors = [NSSortDescriptor( key: "start", ascending: true )] fetchedResultsController = NSFetchedResultsController( fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) } else { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ActivityData") request.predicate = NSPredicate(format: "faculty contains[c] %@", facity) request.sortDescriptors = [NSSortDescriptor( key: "start", ascending: true )] fetchedResultsController = NSFetchedResultsController( fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) } } } else { fetchedResultsController = nil } } override func viewDidLoad() { tableView.estimatedRowHeight = 300 // self.navigationController?.navigationBar.isTranslucent = true // self.tabBarController?.tabBar.isTranslucent = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isTranslucent = true self.tabBarController?.tabBar.isTranslucent = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBar.isTranslucent = false self.tabBarController?.tabBar.isTranslucent = false } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() if indexPath.row == 0 { if !isInterest{ cell = tableView.dequeueReusableCell(withIdentifier: "facBanner", for: indexPath) if let bannercell = cell as? FacultyBannerCell{ var bannerURL: String? managedObjectContext?.performAndWait { if let facityID = self.facity{ bannerURL = ZoneData.fetchZoneBannerFrom(id: facityID, incontext: self.managedObjectContext!) } } bannercell.bannerUrl = bannerURL } } } else if indexPath.row == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "facDesc", for: indexPath) if let descCell = cell as? FacultyDescCell{ var name: String? var desc: String? if isInterest { desc = interestDesc name = facity }else{ managedObjectContext?.performAndWait { if let facityID = self.facity{ name = ZoneData.fetchZoneNameFrom(id: facityID, incontext: self.managedObjectContext!) desc = ZoneData.fetchZoneDescFrom(id: facityID, incontext: self.managedObjectContext!) desc = ("\(ZoneData.fetchZoneWelcomeFrom(id: facityID, incontext: self.managedObjectContext!) )\n\n\(desc ?? "")") } } } descCell.facityDesc = desc descCell.facityTitle = name descCell.facTag = facityTag } } else if indexPath.row == 2 { cell = tableView.dequeueReusableCell(withIdentifier: "Header", for: indexPath) if let headCell = cell as? HeaderTableViewCell { if tableView.numberOfRows(inSection: 0) == 3 { if facity == "Reservation" { headCell.title1 = "NOT HAVE RESERVATION" headCell.title2 = "ไม่มีบันทึกการจองกิจกรรม" headCell.iconImage = "crossIcon" } else if facity == "Favorite" { headCell.title1 = "NOT HAVE FAVORITE EVENTS" headCell.title2 = "คุณยังไม่ได้เพิ่มกิจกรรมที่สนใจ" headCell.iconImage = "crossIcon" } else { headCell.title1 = "EVENT NOT FOUND!" headCell.title2 = "ไม่พบกิจกรรมที่เกี่ยวข้อง" headCell.iconImage = "crossIcon" } } else { if facity == "Reservation" { headCell.title1 = "MY RESERVATION" headCell.title2 = "กิจกรรมที่คุณได้ทำการจองไว้" headCell.iconImage = "relatedeventsIcon" } else if facity == "Favorite" { headCell.title1 = "MY FAVORITE EVENTS" headCell.title2 = "กิจกรรมที่คุณสนใจ" headCell.iconImage = "relatedeventsIcon" } else { headCell.title1 = "RELATED EVENTS" headCell.title2 = "กิจกรรมที่เกี่ยวข้อง" headCell.iconImage = "relatedeventsIcon" } } } } else { cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) var name: String? var thumbnail: String? var toRound: NSSet? var facity: String? var activityId: String? var time: String? if let fetchData = fetchedResultsController?.object(at: IndexPath(row: indexPath.row - 3, section: 0)) as? ActivityData{ fetchData.managedObjectContext?.performAndWait{ name = fetchData.name thumbnail = fetchData.thumbnailsUrl facity = fetchData.faculty toRound = fetchData.toRound activityId = fetchData.activityId if let stime = fetchData.start{ if let eTime = fetchData.end{ time = stime.toThaiText(withEnd: eTime) } } if let toRound = toRound{ if time != nil{ if toRound.count > 0 { time = ("\(time!) + \(toRound.count) รอบ") } } } } } else if let fetchData = fetchedResultsController?.object(at: IndexPath(row: indexPath.row - 3, section: 0)) as? FavoritedActivity { fetchData.managedObjectContext?.performAndWait{ name = fetchData.toActivity?.name thumbnail = fetchData.toActivity?.thumbnailsUrl facity = fetchData.toActivity?.faculty toRound = fetchData.toActivity?.toRound activityId = fetchData.toActivity?.activityId if let stime = fetchData.toActivity?.start{ if let eTime = fetchData.toActivity?.end{ time = stime.toThaiText(withEnd: eTime) } } if let toRound = toRound{ if time != nil{ if toRound.count > 0 { time = ("\(time!) + \(toRound.count) รอบ") } } } } } else if let fetchData = fetchedResultsController?.object(at: IndexPath(row: indexPath.row - 3, section: 0)) as? ReservedActivity { fetchData.managedObjectContext?.performAndWait{ name = fetchData.toActivity?.name thumbnail = fetchData.toActivity?.thumbnailsUrl facity = fetchData.toActivity?.faculty toRound = fetchData.toActivity?.toRound activityId = fetchData.toActivity?.activityId if let stime = fetchData.toActivity?.start{ if let eTime = fetchData.toActivity?.end{ time = stime.toThaiText(withEnd: eTime) } } if let toRound = toRound{ if time != nil{ if toRound.count > 0 { time = ("\(time!) + \(toRound.count) รอบ") } } } } } if let eventFeedCell = cell as? EventFeedCell{ eventFeedCell.manageObjectContext = managedObjectContext if name != nil{ eventFeedCell.name = name } if time != nil{ eventFeedCell.timeText = time } eventFeedCell.eventTumbnailImage.image = #imageLiteral(resourceName: "defaultImage") eventFeedCell.thumbnail = thumbnail eventFeedCell.facity = facity eventFeedCell.activityId = activityId eventFeedCell.toRound = toRound } } cell.selectionStyle = .none return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? { if facity == "Reservation" && editActionsForRowAt.row > 2 { let remove = UITableViewRowAction(style: .normal, title: "Cancel") { action, index in if let fetchData = self.fetchedResultsController?.object(at: IndexPath(row: index.row - 3, section: 0)) as? ReservedActivity{ if let roundId = fetchData.roundId{ APIController.removeReservedActivity(fromRoundID: roundId, inManageobjectcontext: self.managedObjectContext!, completion: nil) } } print("remove") } remove.backgroundColor = UIColor(red: 0.9922, green: 0.431, blue: 0.604, alpha: 1) return [remove] } return [] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if facity == "Reservation" && indexPath.row > 2 { return true } else { return false } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0{ if indexPath.row == 0{ if facity == "Favorite" || facity == "Reservation" { return 0 } else if !isInterest == true { return UITableViewAutomaticDimension } return 0 } else if indexPath.row == 1{ if facity == "Favorite" || facity == "Reservation" { return 0 } return UITableViewAutomaticDimension } else if indexPath.row == 2{ return 58 } return 78 } return UITableViewAutomaticDimension } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toDetail" { if let destination = segue.destination as? EventDetailTableViewController{ if let eventcell = sender as? EventFeedCell?{ if let id = eventcell?.activityId{ ActivityData.fetchActivityData(activityId: id, inManageobjectcontext: managedObjectContext!, completion: { (activityData) in if let activityData = activityData { destination.activityId = activityData.activityId destination.bannerUrl = activityData.bannerUrl destination.topic = activityData.name destination.locationDesc = "" destination.toRounds = activityData.toRound destination.desc = activityData.desc destination.room = activityData.room destination.place = activityData.place destination.zoneId = activityData.faculty destination.latitude = activityData.latitude destination.longitude = activityData.longitude destination.pdf = activityData.pdf destination.video = activityData.video destination.toImages = activityData.toImages destination.toTags = activityData.toTags destination.start = activityData.start destination.end = activityData.end destination.managedObjectContext = self.managedObjectContext print(destination.toRounds) } }) } } } } } }
35872e0a4be8c9b8b688d7ffe5207ff7
37.712121
150
0.446408
false
false
false
false
CalQL8ed-K-OS/Swift-RPG
refs/heads/master
Swift RPG/Combatant.swift
mit
1
// // Combatant.swift // Simple RPG // // Created by Xavi Matos on 10/2/14. // Copyright (c) 2014 Xavi Matos. All rights reserved. // import Foundation class Combatant { var name:String var curHP:Float = 1.0 var pow:Float var def:Float class func plistFolderURL() -> NSURL { let folders = ["GameResources", "Combatants"] var path = NSBundle.mainBundle().resourcePath! for folder in folders { path = path.stringByAppendingPathComponent(folder) } return NSURL(fileURLWithPath: path, isDirectory: true)! } init(var plistName:String) { plistName = plistName.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! if !plistName.hasSuffix(".plist") { plistName = plistName + ".plist" } let plistURL = NSURL(string: plistName, relativeToURL: Combatant.plistFolderURL())! let plist = NSDictionary(contentsOfURL: plistURL)! as Dictionary<String, AnyObject> self.name = plist["name"] as String self.pow = plist["pow"]!.floatValue as Float self.def = plist["def"]!.floatValue as Float } enum DamageResult { case Hit case Dodged case Died } func takeDmg(dmg:Float) -> DamageResult { curHP -= dmg if curHP < 0 { curHP = 0 } // TODO: implement dodging behavior switch curHP { case 0: return .Died case 0...Float.infinity: return .Hit default: raise(1) // should never happen ... i think return .Hit } } }
c1ba88e4f4ef533ac9ed992175aa9223
25.904762
94
0.569912
false
false
false
false
pvbaleeiro/movie-aholic
refs/heads/master
movieaholic/movieaholic/recursos/view/HomeItemCell.swift
mit
1
// // HomeItemCell.swift // movieaholic // // Created by Victor Baleeiro on 23/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit class HomeItemCell: BaseCollectionViewCell { //------------------------------------------------------------------------------------------------------------- // MARK: Propriedades //------------------------------------------------------------------------------------------------------------- var movie: MovieTrending? { didSet { let year : Int = (movie?.movie?.year)! lblYear.text = String(year) lblDescription.text = movie?.movie?.title let watchers : Int = (movie?.watchers)! lblWatchers.text = String(watchers) + " Watchers" } } var homeDescription: String? { didSet { lblDescription.text = homeDescription } } //------------------------------------------------------------------------------------------------------------- // MARK: Viewa //------------------------------------------------------------------------------------------------------------- var imgPoster: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFill view.clipsToBounds = true return view }() var viewLoading: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFill view.clipsToBounds = true return view }() var lblYear: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 14) view.textColor = UIColor.black return view }() var lblDescription: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.systemFont(ofSize: 14) view.textColor = UIColor.gray return view }() var lblWatchers: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.font = UIFont.boldSystemFont(ofSize: 10) view.textColor = UIColor.darkGray return view }() //------------------------------------------------------------------------------------------------------------- // MARK: Ciclo de vida //------------------------------------------------------------------------------------------------------------- override func setLayout() { addSubview(imgPoster) imgPoster.topAnchor.constraint(equalTo: topAnchor).isActive = true imgPoster.heightAnchor.constraint(equalToConstant: 180).isActive = true imgPoster.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true imgPoster.rightAnchor.constraint(equalTo: rightAnchor).isActive = true imgPoster.addSubview(viewLoading) addSubview(lblYear) lblYear.topAnchor.constraint(equalTo: imgPoster.bottomAnchor, constant: 10).isActive = true lblYear.heightAnchor.constraint(equalToConstant: 20).isActive = true lblYear.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true lblYear.widthAnchor.constraint(equalToConstant: 50).isActive = true addSubview(lblDescription) lblDescription.topAnchor.constraint(equalTo: imgPoster.bottomAnchor, constant: 10).isActive = true lblDescription.heightAnchor.constraint(equalToConstant: 20).isActive = true lblDescription.leftAnchor.constraint(equalTo: lblYear.rightAnchor).isActive = true lblDescription.rightAnchor.constraint(equalTo: rightAnchor).isActive = true addSubview(lblWatchers) lblWatchers.topAnchor.constraint(equalTo: lblYear.bottomAnchor, constant: 0).isActive = true lblWatchers.heightAnchor.constraint(equalToConstant: 20).isActive = true lblWatchers.leftAnchor.constraint(equalTo: lblYear.leftAnchor, constant: 0).isActive = true lblWatchers.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } //------------------------------------------------------------------------------------------------------------- // MARK: Carrega dados web //------------------------------------------------------------------------------------------------------------- func loadImage() { //Buscando a imagem... let tmdbId : Int = (self.movie?.movie?.ids?.tmdb)! APIMovie.getImagesMovies(tmdbId: tmdbId) { (response) in switch response { case .onSuccess(let imageDetail as MovieImageDetail): //Obtem imagem let url = URL(string: Url.endpointTheMovieDbImage.rawValue + imageDetail.filePath!) self.viewLoading.stopShimmering() APIMovie.getImage(fromUrl: url!, forImageView: self.imgPoster) break case .onError(let erro): self.viewLoading.stopShimmering() print(erro) break case .onNoConnection(): self.viewLoading.stopShimmering() print("Sem conexão") break default: break } } } }
854b3db6a8ea5a5eaffb4c9ea819a31b
38.239437
115
0.514896
false
false
false
false
Sorix/CloudCore
refs/heads/master
Source/Classes/Save/CloudSaveOperationQueue.swift
mit
1
// // CloudSaveController.swift // CloudCore // // Created by Vasily Ulianov on 06.02.17. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CloudKit import CoreData class CloudSaveOperationQueue: OperationQueue { var errorBlock: ErrorBlock? /// Modify CloudKit database, operations will be created and added to operation queue. func addOperations(recordsToSave: [RecordWithDatabase], recordIDsToDelete: [RecordIDWithDatabase]) { var datasource = [DatabaseModifyDataSource]() // Split records to save to databases for recordToSave in recordsToSave { if let modifier = datasource.find(database: recordToSave.database) { modifier.save.append(recordToSave.record) } else { let newModifier = DatabaseModifyDataSource(database: recordToSave.database) newModifier.save.append(recordToSave.record) datasource.append(newModifier) } } // Split record ids to delete to databases for idToDelete in recordIDsToDelete { if let modifier = datasource.find(database: idToDelete.database) { modifier.delete.append(idToDelete.recordID) } else { let newModifier = DatabaseModifyDataSource(database: idToDelete.database) newModifier.delete.append(idToDelete.recordID) datasource.append(newModifier) } } // Perform for databaseModifier in datasource { addOperation(recordsToSave: databaseModifier.save, recordIDsToDelete: databaseModifier.delete, database: databaseModifier.database) } } private func addOperation(recordsToSave: [CKRecord], recordIDsToDelete: [CKRecordID], database: CKDatabase) { // Modify CKRecord Operation let modifyOperation = CKModifyRecordsOperation(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete) modifyOperation.savePolicy = .changedKeys modifyOperation.perRecordCompletionBlock = { record, error in if let error = error { self.errorBlock?(error) } else { self.removeCachedAssets(for: record) } } modifyOperation.modifyRecordsCompletionBlock = { _, _, error in if let error = error { self.errorBlock?(error) } } modifyOperation.database = database self.addOperation(modifyOperation) } /// Remove locally cached assets prepared for uploading at CloudKit private func removeCachedAssets(for record: CKRecord) { for key in record.allKeys() { guard let asset = record.value(forKey: key) as? CKAsset else { continue } try? FileManager.default.removeItem(at: asset.fileURL) } } } fileprivate class DatabaseModifyDataSource { let database: CKDatabase var save = [CKRecord]() var delete = [CKRecordID]() init(database: CKDatabase) { self.database = database } } extension Sequence where Iterator.Element == DatabaseModifyDataSource { func find(database: CKDatabase) -> DatabaseModifyDataSource? { for element in self { if element.database == database { return element } } return nil } }
e9a1463f17cbe96d07d8c69d90086ca3
28.434343
134
0.745024
false
false
false
false
quickthyme/PUTcat
refs/heads/master
PUTcat/Presentation/App/AppDelegateImportPresenter.swift
apache-2.0
1
import UIKit class AppDelegateImportPresenter : AppDelegateImportDelegate { func handleLaunchURL(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) { if let url = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL { self.importURL(url: url) } } func handleOpenURL(url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return self.importURL(url: url, options: options) } @discardableResult func importURL(url:URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { switch (url.pathExtension) { case AppDocument.Project.Extension: return self.importProject(url: url, options: options) case AppDocument.Environment.Extension: return self.importEnvironment(url: url, options: options) default: return false } } func importProject(url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { UseCaseImportProjectFromURL.action(url: url).execute { _ in NotificationCenter.default.post(name: MainNotification.Present.Projects, object: nil) } return true } func importEnvironment(url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { UseCaseImportEnvironmentFromURL.action(url: url).execute { _ in NotificationCenter.default.post(name: MainNotification.Present.Environments, object: nil) } return true } }
1e0465defa45c8d2e16076af50bef96b
38.657895
111
0.662243
false
false
false
false
dotmat/StatusPageIOSampleApp
refs/heads/master
StatusPageIOStatus/StatusPageIO/UIDeviceDeterminer.swift
gpl-3.0
1
// // UIDeviceDeterminer.swift // TwilioStatus // // Created by Mathew Jenkinson on 11/02/2016. // Copyright © 2016 Chicken and Bee. All rights reserved. // import Foundation import UIKit public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 where value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,7", "iPad6,8": return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } }
a7445007172204f82fc44addeddcf2bb
48.196078
96
0.475678
false
false
false
false
jrmgx/swift
refs/heads/master
jrmgx/Classes/Helper/JrmgxAsync.swift
mit
1
import UIKit open class JrmgxAsync { /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias UIImageResultBlock = (_ image: UIImage?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias NSURLResultBlock = (_ url: URL?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias AnyObjectsResultBlock = (_ objects: [AnyObject]?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias StringResultBlock = (_ string: String?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias NumberResultBlock = (_ number: NSNumber?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias IntResultBlock = (_ number: Int?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias BoolResultBlock = (_ success: Bool, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ open static let NOOPBoolResultBlock: BoolResultBlock = { success, error in } // fileprivate static var namedQueues = ["main": DispatchQueue.main] /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func GetNamedQueue(_ name: String = "main") -> DispatchQueue { if namedQueues[name] == nil { namedQueues[name] = DispatchQueue(label: name, attributes: []) } return namedQueues[name]! } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(_ block: @escaping () -> Void) { Execute(onNamedQueue: "main", block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onNamedQueue name: String, block: @escaping () -> Void) { let queue = GetNamedQueue(name) Execute(onQueue: queue, block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onNamedQueue name: String, afterSeconds delay: Double, block: @escaping () -> Void) { let queue = GetNamedQueue(name) Execute(onQueue: queue, afterSeconds: delay, block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onQueue queue: DispatchQueue, block: @escaping () -> Void) { queue.async(execute: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onQueue queue: DispatchQueue, afterSeconds delay: Double, block: @escaping () -> Void) { let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: block) } }
3feb708e80a3b55a0544a43f511af9fe
21.797386
117
0.530677
false
false
false
false
coach-plus/ios
refs/heads/master
Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/TextFieldEffects.swift
mit
4
// // TextFieldEffects.swift // TextFieldEffects // // Created by Raúl Riera on 24/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit extension String { /** true if self contains characters. */ var isNotEmpty: Bool { return !isEmpty } } /** A TextFieldEffects object is a control that displays editable text and contains the boilerplates to setup unique animations for text entry and display. You typically use this class the same way you use UITextField. */ open class TextFieldEffects : UITextField { /** The type of animation a TextFieldEffect can perform. - TextEntry: animation that takes effect when the textfield has focus. - TextDisplay: animation that takes effect when the textfield loses focus. */ public enum AnimationType: Int { case textEntry case textDisplay } /** Closure executed when an animation has been completed. */ public typealias AnimationCompletionHandler = (_ type: AnimationType)->() /** UILabel that holds all the placeholder information */ public let placeholderLabel = UILabel() /** Creates all the animations that are used to leave the textfield in the "entering text" state. */ open func animateViewsForTextEntry() { fatalError("\(#function) must be overridden") } /** Creates all the animations that are used to leave the textfield in the "display input text" state. */ open func animateViewsForTextDisplay() { fatalError("\(#function) must be overridden") } /** The animation completion handler is the best place to be notified when the text field animation has ended. */ open var animationCompletionHandler: AnimationCompletionHandler? /** Draws the receiver’s image within the passed-in rectangle. - parameter rect: The portion of the view’s bounds that needs to be updated. */ open func drawViewsForRect(_ rect: CGRect) { fatalError("\(#function) must be overridden") } open func updateViewsForBoundsChange(_ bounds: CGRect) { fatalError("\(#function) must be overridden") } // MARK: - Overrides override open func draw(_ rect: CGRect) { // FIXME: Short-circuit if the view is currently selected. iOS 11 introduced // a setNeedsDisplay when you focus on a textfield, calling this method again // and messing up some of the effects due to the logic contained inside these // methods. // This is just a "quick fix", something better needs to come along. guard isFirstResponder == false else { return } drawViewsForRect(rect) } override open func drawPlaceholder(in rect: CGRect) { // Don't draw any placeholders } override open var text: String? { didSet { if let text = text, text.isNotEmpty || isFirstResponder { animateViewsForTextEntry() } else { animateViewsForTextDisplay() } } } // MARK: - UITextField Observing override open func willMove(toSuperview newSuperview: UIView!) { if newSuperview != nil { NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidEndEditing), name: UITextField.textDidEndEditingNotification, object: self) NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidBeginEditing), name: UITextField.textDidBeginEditingNotification, object: self) } else { NotificationCenter.default.removeObserver(self) } } /** The textfield has started an editing session. */ @objc open func textFieldDidBeginEditing() { animateViewsForTextEntry() } /** The textfield has ended an editing session. */ @objc open func textFieldDidEndEditing() { animateViewsForTextDisplay() } // MARK: - Interface Builder override open func prepareForInterfaceBuilder() { drawViewsForRect(frame) } }
5c2b291d7f0109e8f4ab92df7a5d58bb
29.820896
214
0.655932
false
false
false
false
kvvzr/Twinkrun
refs/heads/master
Twinkrun/Controllers/HistoryViewController.swift
mit
2
// // HistoryViewController.swift // Twinkrun // // Created by Kawazure on 2014/10/23. // Copyright (c) 2014年 Twinkrun. All rights reserved. // import UIKit import CoreBluetooth class HistoryViewController: UITableViewController { var resultData: [TWRResult]? var toolbar: UIToolbar? var selectedRows: [Int] = [] override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let documentsPath = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String)! let path = documentsPath.URLByAppendingPathComponent("TWRResultData2").path! resultData = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [TWRResult] dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } override func viewDidLoad() { super.viewDidLoad() let font = UIFont(name: "HelveticaNeue-Light", size: 22) if let font = font { navigationController!.navigationBar.barTintColor = UIColor.twinkrunGreen() navigationController!.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: font ] navigationController!.navigationBar.tintColor = UIColor.whiteColor() } navigationItem.rightBarButtonItem = editButtonItem() tableView.delegate = self tableView.dataSource = self tableView.backgroundView = UIView() tableView.backgroundView!.backgroundColor = UIColor.twinkrunBlack() tableView.allowsSelection = false tableView.allowsMultipleSelection = false tableView.allowsSelectionDuringEditing = true tableView.allowsMultipleSelectionDuringEditing = true toolbar = UIToolbar(frame: tabBarController!.tabBar.frame) toolbar!.backgroundColor = UIColor.twinkrunBlack() toolbar!.items = [ UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector("onAction:")), UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: Selector("onDelete:")) ] toolbar!.hidden = true tabBarController!.tabBar.superview!.addSubview(toolbar!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let resultData = resultData { return resultData.count } return 0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 240 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("resultCell")! as UITableViewCell cell.backgroundColor = UIColor.clearColor() cell.selectedBackgroundView = UIView() cell.selectedBackgroundView!.backgroundColor = UIColor.clearColor() let view = cell.viewWithTag(1)! as! ResultView view.result = self.resultData![indexPath.row] dispatch_async(dispatch_get_main_queue(), { view.reload(animated: false) }) return cell } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { selectedRows.removeObject(indexPath.row) if let toolbar = toolbar { (toolbar.items!.first! as UIBarButtonItem).enabled = (selectedRows.count == 1) } if selectedRows.count == 0 { tabBarController!.tabBar.hidden = false if let toolbar = toolbar { toolbar.hidden = true } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedRows.append(indexPath.row) if selectedRows.count > 0 { tabBarController!.tabBar.hidden = true if let toolbar = toolbar { toolbar.hidden = false (toolbar.items!.first! as UIBarButtonItem).enabled = (selectedRows.count == 1) } } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if !editing { tabBarController!.tabBar.hidden = false if let toolbar = toolbar { toolbar.hidden = true } } selectedRows = [] } func onDelete(sender: UIBarButtonItem) { var indexPaths: [NSIndexPath] = [] selectedRows.sortInPlace {$0 > $1} for row in selectedRows { indexPaths.append(NSIndexPath(forRow: row, inSection: 0)) resultData!.removeAtIndex(row) } tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None) let documentsPath = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])! let path = documentsPath.URLByAppendingPathComponent("TWRResultData2").path! NSKeyedArchiver.archiveRootObject(resultData!, toFile: path) self.setEditing(false, animated: true) } func onAction(sender: UIBarButtonItem) { for row in selectedRows { let result = resultData![row] let view = UIView(frame: CGRectMake(0, 0, 320, 224)) view.backgroundColor = UIColor.twinkrunBlack() let resultView = UINib(nibName: "ShareBoard", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! ResultView resultView.frame = CGRectMake(0, 0, 320, 244) resultView.result = result resultView.reload(animated: false) resultView.back(nil) view.addSubview(resultView) let image = viewToImage(view) let contents = ["I got \(result.score) points in this game! #twinkrun", image] let controller = UIActivityViewController(activityItems: contents, applicationActivities: nil) controller.excludedActivityTypes = [UIActivityTypeAddToReadingList, UIActivityTypeAirDrop, UIActivityTypePostToFlickr, UIActivityTypeSaveToCameraRoll, UIActivityTypePrint] presentViewController(controller, animated: true, completion: {}) } self.setEditing(false, animated: true) } func viewToImage(view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() view.layer.renderInContext(context!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
461a75346880f80021f1eabbf08f5283
37.859375
183
0.642493
false
false
false
false
soracom/soracom-sdk-ios
refs/heads/master
Pod/Classes/AuthAPI.swift
mit
1
import Foundation import Alamofire extension Soracom { public class func auth(email: String, password: String, timeout: Int = 86400, onSuccess: (() -> ())? = nil, onError: ((NSError) -> ())? = nil) { Alamofire.request(Router.Auth(["email" : email, "password": password, "tokenTimeoutSeconds" : timeout])).responseJSON { response in if let error = response.result.error { onError?(error) } else { if let value = response.result.value as? [String: String], let apiKey = value["apiKey"], let token = value["token"], let operatorId = value["operatorId"] { Router.token = token Router.apiKey = apiKey Router.operatorId = operatorId onSuccess?() } else { print(response.result.value) } } } } public static var isLoggedIn: Bool { return Router.apiKey != nil } public static var operatorId: String? { return Router.operatorId } }
9f88e3d072b9a59c920e734ee3447994
33.081081
143
0.46709
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuideTests/LSRangeTests.swift
mit
3
// // LSRangeTests.swift // DereGuideTests // // Created by zzk on 06/01/2018. // Copyright © 2018 zzk. All rights reserved. // import XCTest @testable import DereGuide class LSRangeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { let r1 = LSRange(begin: 1, end: 10) let r2 = LSRange(begin: 2, end: 8) assert(r1.subtract(r2) == [LSRange(begin: 1, end: 2), LSRange(begin: 8, end: 10)]) let r3 = LSRange(begin: 10, end: 20) assert(r1.subtract(r3) == [r1]) assert(r1.intersects(r3) == false) // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
df79823c8f73e9f18f1dfe839ab3a527
28.159091
111
0.600935
false
true
false
false
Edig/EDChat
refs/heads/master
EdChat/EDChatMessageView.swift
mit
1
// // EDChatMessageView.swift // Eduardo Iglesias // // Created by Eduardo Iglesias on 5/12/16. // Copyright © 2016 Eduardo Iglesias. All rights reserved. // import UIKit class EDChatMessageView: UIView { private var message: EDChatMessage! //Configuration var font: UIFont! var sendingMessageBackrgound = UIColor.blueColor() var incomingMessageBackrgound = UIColor.grayColor() var sendingMessageTextColor = UIColor.whiteColor() var incomingMessageTextColor = UIColor.whiteColor() init(message: EDChatMessage, withFont font: UIFont) { super.init(frame: CGRectZero) self.message = message self.font = font if self.message.isOutgoingMessage { self.backgroundColor = self.sendingMessageBackrgound }else{ self.backgroundColor = self.incomingMessageBackrgound } let tap = UILongPressGestureRecognizer(target: self, action: #selector(self.didTapOnBubble(_:))) self.addGestureRecognizer(tap) self.initBubble() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initBubble() { self.layer.cornerRadius = 5 let label = UILabel() label.text = self.message.message label.font = self.font label.numberOfLines = 0 if self.message.isOutgoingMessage { label.textColor = self.sendingMessageTextColor }else{ label.textColor = self.incomingMessageTextColor } label.translatesAutoresizingMaskIntoConstraints = false self.addSubview(label) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: [], metrics: nil, views: ["label": label])) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-|", options: [], metrics: nil, views: ["label": label])) } func didTapOnBubble(recognizer: UIGestureRecognizer) { if recognizer.state == .Began { print("Tap") //Todo: copy } } }
d24559fb809316dde68b30f77473fdb3
29.013514
144
0.623143
false
false
false
false
NijiDigital/NetworkStack
refs/heads/master
Example/MoyaComparison/MoyaComparison/Models/Parser/JSONCodable/Video+JSONCodable.swift
apache-2.0
1
// // Copyright 2017 niji // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import JSONCodable import class JSONCodable.JSONEncoder extension Video: JSONCodable { convenience init(object: JSONObject) throws { self.init() let decoder = JSONDecoder(object: object) // Attributes self.identifier = try decoder.decode(Attributes.identifier) self.title = try decoder.decode(Attributes.title) self.creationDate = try decoder.decode(Attributes.creationDate, transformer: JSONTransformers.StringToDate) self.likeCounts = try decoder.decode(Attributes.likeCounts) self.hasSponsors.value = try decoder.decode(Attributes.hasSponsors) self.statusCode.value = try decoder.decode(Attributes.statusCode) // RelationShips let relatedVideosSandbox: [Video] = try decoder.decode(Relationships.relatedVideos) self.relatedVideos.append(objectsIn: relatedVideosSandbox) } func toJSON() throws -> JSONObject { return try JSONEncoder.create({ (encoder: JSONEncoder) in try encoder.encode(self.identifier, key: Attributes.identifier) try encoder.encode(self.title, key: Attributes.title) try encoder.encode(self.creationDate, key: Attributes.creationDate, transformer: JSONTransformers.StringToDate) try encoder.encode(self.likeCounts, key: Attributes.likeCounts) try encoder.encode(self.hasSponsors.value, key: Attributes.hasSponsors) try encoder.encode(self.statusCode.value, key: Attributes.statusCode) let relatedVideosSandbox: [Video] = Array(self.relatedVideos) try encoder.encode(relatedVideosSandbox, key: Relationships.relatedVideos) }) } } public struct JSONTransformers { public static let StringToDate = JSONTransformer<String, Date?>( decoding: {DateFormatter.iso8601Formatter.date(from: $0)}, encoding: {DateFormatter.iso8601Formatter.string(from: $0 ?? Date())}) }
e7c2a3c7d89020421d42df6cb95b590c
42.836364
117
0.754873
false
false
false
false
AlexanderMazaletskiy/SAHistoryNavigationViewController
refs/heads/master
SAHistoryNavigationViewControllerSample/SAHistoryNavigationViewControllerSample/TimelineView/TimelineViewController.swift
mit
2
// // TimelineViewController.swift // SAHistoryNavigationViewControllerSample // // Created by 鈴木大貴 on 2015/04/01. // Copyright (c) 2015年 &#37428;&#26408;&#22823;&#36020;. All rights reserved. // import UIKit class TimelineViewController: UIViewController { @IBOutlet weak var tableView: UITableView! private let kCellIdentifier = "Cell" private var contents: [TimelineContent] = [ TimelineContent(username: "Alex", text: "This is SAHistoryNavigationViewController."), TimelineContent(username: "Brian", text: "It has history jump function."), TimelineContent(username: "Cassy", text: "If you want to launch history viewer,"), TimelineContent(username: "Dave", text: "please tap longer \"<Back\" of Navigation Bar."), TimelineContent(username: "Elithabeth", text: "You can see ViewController history"), TimelineContent(username: "Alex", text: "as horizonal scroll view."), TimelineContent(username: "Brian", text: "If you select one of history,"), TimelineContent(username: "Cassy", text: "go back to that ViewController."), TimelineContent(username: "Dave", text: "Thanks for trying this sample."), TimelineContent(username: "Elithabeth", text: "by skz-atmosphere") ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Timeline" let nib = UINib(nibName: "TimelineViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: kCellIdentifier) tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } struct TimelineContent { var username: String var text: String } } extension TimelineViewController: UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)! if let cell = cell as? TimelineViewCell { let num = indexPath.row % 5 + 1 if let image = UIImage(named: "icon_\(num)") { cell.setIconImage(image) } let content = contents[indexPath.row] cell.setUsername(content.username) cell.setMainText(content.text) } cell.layoutMargins = UIEdgeInsetsZero return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contents.count } } extension TimelineViewController: UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let storyboard = UIStoryboard(name: "Main", bundle: nil) if let viewController = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? TimelineViewCell { viewController.iconImage = cell.iconImageView?.image } let content = contents[indexPath.row] viewController.username = content.username viewController.text = content.text navigationController?.pushViewController(viewController, animated: true) } } }
ef607d3be657d68ed96c178af0dd58c2
37.73
133
0.663223
false
false
false
false
jvk75/NFCNDEFParse
refs/heads/master
NFCNDEFParse/NDEFMessageWithWellKnownTypeUri.swift
mit
1
// // NDEFMessageWithWellKnownTypeUri.swift // NFCNDEFParse // // Created by Jari Kalinainen on 09.10.17. // import Foundation import CoreNFC /// NFCForum-TS-RTD_URI_1.0 2006-07-24 /// - **url** : URL /// - not nil if payload can be created as URL type /// - **string** : String ( /// - string representation of the payload @objc public class NFCForumWellKnownTypeUri: NSObject, NFCForumWellKnownTypeUriProtocol { @objc public var type: NFCForumWellKnownTypeEnum = .uri @objc public var url: URL? @objc public var string: String? @objc public var recordDescription: String { return "- \(self.type.description): \n\tstring: \(string ?? "nil") \n\turl: \(url?.absoluteString ?? "nil")" } public init?(payload: Data) { super.init() let bytes = [UInt8](payload) guard bytes.count > 2 else { return } let uriIdentifierByte = bytes[0] let textBytes = bytes[1...] if let textString = String(bytes: textBytes, encoding: .utf8) { self.string = self.abbreviation(uriIdentifierByte) + textString if let string = self.string { self.url = URL(string: string) } } } private func abbreviation(_ value: UInt8) -> String { switch value { case 0x01: return "http://www." case 0x02: return "https://www." case 0x03: return "http://" case 0x04: return "https://" case 0x05: return "tel:" case 0x06: return "mailto:" case 0x07: return "ftp://anonymous:anonymous@" case 0x08: return "ftp://ftp." case 0x09: return "ftps://" case 0x0A: return "sftp://" case 0x0B: return "smb://" case 0x0C: return "nfs://" case 0x0D: return "ftp://" case 0x0E: return "dav://" case 0x0F: return "news://" case 0x10: return "telnet://" case 0x11: return "imap://" case 0x12: return "rtsp://" case 0x13: return "urn:" case 0x14: return "pop:" case 0x15: return "sip:" case 0x16: return "sips:" case 0x17: return "tftp:" case 0x18: return "btspp://" case 0x19: return "btl2cap://" case 0x1A: return "btgoep://" case 0x1B: return "tcpobex://" case 0x1C: return "irdaobex://" case 0x1D: return "file://" case 0x1E: return "urn:epc:id:" case 0x1F: return "urn:epc:tag:" case 0x20: return "urn:epc:pat:" case 0x21: return "urn:epc:raw:" case 0x22: return "urn:epc:" case 0x23: return "urn:nfc:" default: return "" } } }
8bcb98cfc371609d822126f44417d983
25.117647
116
0.484556
false
false
false
false
rsyncOSX/RsyncOSX
refs/heads/master
RsyncOSX/ViewControllerEstimatingTasks.swift
mit
1
// // ViewControllerEstimatingTasks.swift // RsyncOSX // // Created by Thomas Evensen on 21.04.2018. // Copyright © 2018 Thomas Evensen. All rights reserved. // import Cocoa import Foundation // Protocol for progress indicator protocol CountRemoteEstimatingNumberoftasks: AnyObject { func maxCount() -> Int func inprogressCount() -> Int } class ViewControllerEstimatingTasks: NSViewController, Abort, SetConfigurations, SetDismisser { weak var countDelegate: CountRemoteEstimatingNumberoftasks? private var remoteinfotask: RemoteinfoEstimation? var diddissappear: Bool = false @IBOutlet var abort: NSButton! @IBOutlet var progress: NSProgressIndicator! @IBAction func abort(_: NSButton) { remoteinfotask?.abort() abort() remoteinfotask = nil closeview() } override func viewDidLoad() { super.viewDidLoad() SharedReference.shared.setvcref(viewcontroller: .vcestimatingtasks, nsviewcontroller: self) } override func viewDidAppear() { super.viewDidAppear() guard diddissappear == false else { return } abort.isEnabled = true remoteinfotask = RemoteinfoEstimation(viewcontroller: self, processtermination: processtermination) initiateProgressbar() } override func viewWillDisappear() { super.viewWillDisappear() diddissappear = true // Release the estimating object remoteinfotask?.abort() remoteinfotask = nil } // Progress bars private func initiateProgressbar() { progress.maxValue = Double(remoteinfotask?.maxCount() ?? 0) progress.minValue = 0 progress.doubleValue = 0 progress.startAnimation(self) } private func updateProgressbar(_ value: Double) { progress.doubleValue = value } private func closeview() { if (presentingViewController as? ViewControllerMain) != nil { dismissview(viewcontroller: self, vcontroller: .vctabmain) } else if (presentingViewController as? ViewControllerNewConfigurations) != nil { dismissview(viewcontroller: self, vcontroller: .vcnewconfigurations) } else if (presentingViewController as? ViewControllerRestore) != nil { dismissview(viewcontroller: self, vcontroller: .vcrestore) } else if (presentingViewController as? ViewControllerSnapshots) != nil { dismissview(viewcontroller: self, vcontroller: .vcsnapshot) } else if (presentingViewController as? ViewControllerSsh) != nil { dismissview(viewcontroller: self, vcontroller: .vcssh) } else if (presentingViewController as? ViewControllerLoggData) != nil { dismissview(viewcontroller: self, vcontroller: .vcloggdata) } } } extension ViewControllerEstimatingTasks { func processtermination() { let progress = Double(remoteinfotask?.maxCount() ?? 0) - Double(remoteinfotask?.inprogressCount() ?? 0) updateProgressbar(progress) } } extension ViewControllerEstimatingTasks: StartStopProgressIndicator { func start() { // } func stop() { weak var openDelegate: OpenQuickBackup? if (presentingViewController as? ViewControllerMain) != nil { openDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } else if (presentingViewController as? ViewControllerRestore) != nil { openDelegate = SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore } else if (presentingViewController as? ViewControllerLoggData) != nil { openDelegate = SharedReference.shared.getvcref(viewcontroller: .vcloggdata) as? ViewControllerLoggData } else if (presentingViewController as? ViewControllerSnapshots) != nil { openDelegate = SharedReference.shared.getvcref(viewcontroller: .vcsnapshot) as? ViewControllerSnapshots } closeview() openDelegate?.openquickbackup() } }
003888c56bd297df9f1c8a4171071c9b
36.229358
115
0.692213
false
false
false
false
nifty-swift/Nifty
refs/heads/master
Sources/transpose.swift
apache-2.0
2
/*************************************************************************************************** * transpose.swift * * This file provides functionality for transposing matrices. * * Author: Philip Erickson * Creation Date: 16 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 **************************************************************************************************/ #if NIFTY_XCODE_BUILD import Accelerate #else import CBlas #endif // TODO: transpose only operates on double matrices... extend to int, float, string, etc. // It's specific to doubles because of the use of BLAS function. Can use BLAS on ints/floats, but // for strings or Any we'll have to do something custom (which will be slower). // TODO: there must be a faster way to transpose... // LAPACKE states that it transposes row-major matrices on input (since fortran is column-major), // and that seems to barely be noticeable in inverting large (5000x5000) matrices (both row and // column take around 6 seconds). But just transposing the way it's done below takes around 4 // seconds (still better than the 8 seconds a naive double for loop takes). // TODO: decide on operator, add it to documentation. Maybe A^ to transpose? A* should be conjugate. // A~ maybe. A` is invalid I believe. Maybe unicode symbols? Aᵀ postfix operator ^ public postfix func ^ (A: Matrix<Double>) -> Matrix<Double> { return transpose(A) } /// Return the nonconjugate transpose of the given matrix. /// /// Alternatively, `transpose(B)` can be executed with `B^`. /// /// - Parameters: /// - B: the matrix to transpose /// - Returns: transposed matrix public func transpose(_ B: Matrix<Double>) -> Matrix<Double> { let A = eye(B.columns, B.columns) let transA = CblasNoTrans let m = A.rows let k = A.columns let a = A.data let lda = m let alpha = 1.0 let transB = CblasTrans assert(k == B.columns) // k is rows in transpose(B) and columns in A let n = B.rows // n is columns in transpose(B) and columns in C let b = B.data let ldb = k // ldb is rows in transpose(B) var c = Array<Double>(repeating: 0, count: k*n) let ldc = n // for row-major, leading dimension is the number of elements in row let beta = 0.0 cblas_dgemm(CblasRowMajor, transA, transB, Int32(m), Int32(n), Int32(k), alpha, a, Int32(lda), b, Int32(ldb), beta, &c, Int32(ldc)) // inherit name var newName = A.name if newName != nil { newName = "transpose(\(newName!))"} return Matrix(k, n, c, name: newName, showName: A.showName) }
a427db82896c4a225b17aa63a8f5c110
38.308642
101
0.636935
false
false
false
false
yichizhang/UIColor-Hex-Swift
refs/heads/master
UIColorExtension.swift
mit
1
// // UIColorExtension.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = advance(rgba.startIndex, 1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { if countElements(hex) == 3 { red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 } else if countElements(hex) == 4 { red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 } else if countElements(hex) == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if countElements(hex) == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { println("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
b1a4777bb176ca56d79a590ef49cd055
41.433962
109
0.477546
false
false
false
false
mumuda/Swift_Weibo
refs/heads/master
weibo/weibo/Classes/Home/Popover/PopoverAnimal.swift
mit
1
// // PopoverAnimal.swift // weibo // // Created by ldj on 16/6/3. // Copyright © 2016年 ldj. All rights reserved. // import UIKit // 定义常量,保存通知的名称 let ZDPopoverAnimalWillShow = "ZDPopoverAnimalWillShow" let ZDPopoverAnimalWillDismiss = "ZDPopoverAnimalWillDismiss" class PopoverAnimal: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning { // 记录当前是否展开 var isPresent:Bool = false // 定义属性,保存菜单大小 var presentedFrame = CGRectZero // 实现代理方法,告诉系统谁来负责专场动画 // UIPresentationController iOS8推出专门用来负责转场动画 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let pc = PopPresentationController(presentedViewController: presented, presentingViewController: presenting) pc.presentedFrame = presentedFrame return pc } // MARK: - 只要实现了一下方法,系统默认的动画就没有了,"所有"东西都需要程序员自己实现 /** 告诉系统谁来负责modal 的展现动画 - parameter presented: 被展现实体 - parameter presenting: 发起视图 - returns: 谁来负责 */ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{ isPresent = true // 发送通知,通知控制器即将展开 NSNotificationCenter.defaultCenter().postNotificationName(ZDPopoverAnimalWillShow, object: self) return self } /** 告诉系统谁来负责modal的消失动画 - parameter dismissed: 被关闭的视图 - returns: 谁来负责 */ func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false // 发送通知,通知控制器即将消失 NSNotificationCenter.defaultCenter().postNotificationName(ZDPopoverAnimalWillDismiss, object: self) return self } // MARK: - UIViewControllerAnimatedTransitioning /** 返回动画时长 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 - returns: 动画时长 */ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /** 告诉系统如何动画,无论是动画展示或者消失,都会调用这个动画 - parameter transitionContext: 上下文,里面保存了动画需要的所有参数 */ func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 1.拿到展示视图 // let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) // let frameVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) // print(toVC , frameVC) // 通过打印发现要修改的就是toVC上面的view if isPresent { let toView = transitionContext.viewForKey(UITransitionContextToViewKey) toView?.transform = CGAffineTransformMakeScale(1.0, 0.0) transitionContext.containerView()?.addSubview(toView!) // 设置锚点 toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0) // 2..执行动画 // 注意: 一定要将视图添加到容器上 [UIView .animateWithDuration(transitionDuration(transitionContext), animations: { toView?.transform = CGAffineTransformIdentity }, completion: { (_) in // 2.1执行完动画一定要告诉系统 // 如果不写,可能导致一些未知错误 transitionContext.completeTransition(true) })] }else { let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { // 注意: 犹豫cgfloat是不准确的,所以如果写0.0是没有动画的, fromView?.transform = CGAffineTransformMakeScale(1.0, 0.00001) }, completion: { (_) in transitionContext.completeTransition(true) }) } } }
207ea05438874249fbeb61c655be3d15
32.572581
219
0.650012
false
false
false
false
stockx/BubbleRankingIndicator
refs/heads/master
Source/BubbleRankingIndicatorView.swift
mit
1
// // BubbleRankingIndicatorView.swift // BubbleRankingIndicator // // Created by Sklar, Josh on 10/5/16. // Copyright © 2016 Sklar. All rights reserved. // import UIKit // Libs import SnapKit public struct Rank { public let level: Int public let name: String public let backgroundImageName: String? public init(level: Int, name: String, backgroundImageName: String?) { self.level = level self.name = name self.backgroundImageName = backgroundImageName } } public class BubbleRankingIndicatorView: UIView { public struct State { public var ranks: [Rank] public var activeRankLevel: Int public var unachievedRankBackgroundColor: UIColor public var rankNameFont: UIFont public var rankNameColor: UIColor /// Whether or not the rank level number is hidden on the active bubble rank. /// Defaults to true. public var rankNameOnActiveRankIsHidden: Bool init() { ranks = [] activeRankLevel = 0 unachievedRankBackgroundColor = .lightGray rankNameFont = .systemFont(ofSize: 16) rankNameColor = .white rankNameOnActiveRankIsHidden = true } } public var state: State { didSet { update(oldValue) } } /** Represents how much larger the active BubbleRankView will be than the inactive ones. */ public let activeRankSizeMultiplier: CGFloat = 1.3 fileprivate var rankViews = [BubbleRankView]() // MARK: Init public init(state: State) { self.state = state super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { fatalError("init(frame:) has not been implemented. Use init(state:).") } required public init?(coder aDecoder: NSCoder) { let defaultState = State() self.state = defaultState super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { self.rankViews.forEach { self.addSubview($0) } // Use a default state for the oldValue let defaultState = State() update(defaultState) } // MARK: State func update(_ oldState: State) { // If the number of ranks has changed, need to remove the old ones and // add the new ones. if oldState.ranks.count != self.state.ranks.count { self.rankViews.forEach { $0.removeFromSuperview() } self.rankViews = self.state.ranks.map { _ in return BubbleRankView(frame: CGRect.zero) } self.rankViews.forEach { self.addSubview($0) } } // Update all the rankViews state's. for (index, rankView) in self.rankViews.enumerated() { let rankIsActive = self.state.ranks[index].level == self.state.activeRankLevel var state = BubbleRankView.State(rank: self.state.ranks[index], isActive: rankIsActive, hasAchievedRank: self.state.ranks[index].level <= self.state.activeRankLevel, outerRingColor: .white, backgroundColor: self.state.unachievedRankBackgroundColor, rankNameFont: self.state.rankNameFont, rankNameColor: self.state.rankNameColor, rankLevelLabelIsHidden: false) state.rankLevelLabelIsHidden = rankIsActive && self.state.rankNameOnActiveRankIsHidden rankView.state = state } self.setNeedsUpdateConstraints() } // MARK: View override public func updateConstraints() { guard self.state.ranks.count > 0 else { super.updateConstraints() return } let width = bounds.width let height = bounds.height // If the view height is too small to accomodate for the bubbles to all // be right next to eachother, don't do anything and // print a warning message to the console. // Currently (v1.0), this does not support when the height is too small // thus requiring the ranks to be spaced out. let targetedDiameter = width / CGFloat(self.state.ranks.count) guard (targetedDiameter * self.activeRankSizeMultiplier) <= height else { print("BubbleRankingIndicator: BubbleRankingIndicatorView is too short to support bubbles given the number of ranks.\nNot drawing any ranks.") self.rankViews.forEach { $0.snp.removeConstraints() } super.updateConstraints() return } var inactiveRankViews = [BubbleRankView]() var activeRankView: BubbleRankView? = nil var hasShownActiveRankView = false for (index, rankView) in self.rankViews.enumerated() { // If it's the first one, anchor it to the left side. if index == 0 { rankView.snp.remakeConstraints { make in make.centerY.equalToSuperview() make.left.equalToSuperview() make.height.equalTo(rankView.snp.width) } } // If it's somewhere in the middle or the end, anchor the left to to the previous one, // and set the height and width equal if index > 0 && index <= (self.rankViews.count - 1) { rankView.snp.remakeConstraints { make in make.centerY.equalToSuperview() make.left.equalTo(self.rankViews[index - 1].snp.right).offset(-20) make.height.equalTo(rankView.snp.width) } } // If it's the last one, add (snp.make, not snp.remake since we don't // want to blow away the ones we just created) an anchor to the right side if index == self.rankViews.count - 1 { rankView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.right.equalToSuperview() } } if rankView.state?.isActive == true { bringSubview(toFront: rankView) hasShownActiveRankView = true activeRankView = rankView } else { if !hasShownActiveRankView { bringSubview(toFront: rankView) } else { sendSubview(toBack: rankView) } inactiveRankViews.append(rankView) } } // Make all width's of the inactive rankViews equal. for (index, rankView) in inactiveRankViews.enumerated() { if index > 0 { rankView.snp.makeConstraints { make in make.width.equalTo(inactiveRankViews[index - 1].snp.width) } } } // Make the width of the active rankView larger than the inactive ones. if let activeRankView = activeRankView, let firstInactiveRankView = inactiveRankViews.first { activeRankView.snp.makeConstraints { make in make.width.equalTo(firstInactiveRankView.snp.width).multipliedBy(self.activeRankSizeMultiplier) } } super.updateConstraints() } }
db208278bb6325d3e55c784b88ae28aa
33.519651
154
0.548008
false
false
false
false
juliobertolacini/ReduxPaperSwift
refs/heads/master
ReduxPaperScissors/ReduxPaperScissors/Reducers.swift
mit
1
// // Created by Julio Bertolacini on 02/08/17. // Copyright © 2017 Julio Bertolacini Organization. All rights reserved. // import ReSwift // MARK:- REDUCERS func appReducer(action: Action, state: AppState?) -> AppState { // creates a new state if one does not already exist var state = state ?? AppState() switch action { case let chooseWeaponAction as ChooseWeaponAction: let turn = state.turn switch turn.player { case .one: // create a play let play = Play(chosen: true, weapon: chooseWeaponAction.weapon) state.player1Play = play // pass the turn to the next player state.turn = Turn(player: .two) // change the message state.message = .player2choose case .two: // create a play let play = Play(chosen: true, weapon: chooseWeaponAction.weapon) state.player2Play = play // calculate who won let player1weapon = state.player1Play.weapon ?? .rock let player2weapon = state.player2Play.weapon ?? .rock switch player1weapon { case .rock: switch player2weapon { case .rock: state.result = .draw state.message = .draw case .paper: state.result = .player2wins state.message = .player2wins case .scissors: state.result = .player1wins state.message = .player1wins } case .paper: switch player2weapon { case .rock: state.result = .player1wins state.message = .player1wins case .paper: state.result = .draw state.message = .draw case .scissors: state.result = .player2wins state.message = .player2wins } case .scissors: switch player2weapon { case .rock: state.result = .player2wins state.message = .player2wins case .paper: state.result = .player1wins state.message = .player1wins case .scissors: state.result = .draw state.message = .draw } } } default: break } // return the new state return state }
3a518fcb9f5a3d8561144e6c285e5cf2
29.920455
76
0.46821
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestUserProgressDA.swift
mit
1
// // QuestUserProgressDA.swift // AwesomeCore // // Created by Antonio on 1/4/18. // //import Foundation // //class QuestUserProgressDA { // // // MARK: - Parser // // func parseToCoreData(_ questUserProgress: QuestUserProgress, quest: Quest, result: @escaping (CDUserProgress) -> Void) { // AwesomeCoreDataAccess.shared.backgroundContext.perform { // let cdUserProgress = self.parseToCoreData(questUserProgress, quest: quest) // result(cdUserProgress) // } // } // // func parseToCoreData(_ questUserProgress: QuestUserProgress, quest: Quest) -> CDUserProgress { // // guard let questId = quest.id else { // fatalError("CDUserProgress object can't be created without id.") // } // let p = predicate(questId, questUserProgress.questId ?? "") // let cdUserProgress = CDUserProgress.getObjectAC(predicate: p, createIfNil: true) as! CDUserProgress // // cdUserProgress.currentDayId = questUserProgress.currentDayId // cdUserProgress.daysCompleted = questUserProgress.daysCompleted.map(String.init).joined(separator: ", ") // cdUserProgress.introsCompleted = questUserProgress.introsCompleted.map(String.init).joined(separator: ", ") // cdUserProgress.started = questUserProgress.started // cdUserProgress.startedAt = questUserProgress.startedAt // cdUserProgress.ended = questUserProgress.ended // cdUserProgress.endedAt = questUserProgress.endedAt // cdUserProgress.completed = questUserProgress.completed // cdUserProgress.completedAt = questUserProgress.completedAt // cdUserProgress.totalDays = Int16(questUserProgress.totalDays) // cdUserProgress.totalDaysCompleted = Int16(questUserProgress.totalDaysCompleted) // cdUserProgress.totalIntros = Int16(questUserProgress.totalIntros) // cdUserProgress.totalIntrosCompleted = Int16(questUserProgress.totalIntrosCompleted) // // // as we have a one to one relationship we can use a Quest id as a QuestUserProgress id // cdUserProgress.id = questId // // return cdUserProgress // } // // func parseFromCoreData(_ cdUserProgress: CDUserProgress) -> QuestUserProgress { // // var daysCompleted: [Int] { // guard let days = cdUserProgress.daysCompleted else { return [] } // return days.components(separatedBy: ", ").map({(value) in // if let intValue = Int(value) { // return intValue // } // return 0 // }) // } // var introsCompleted: [Int] { // guard let intros = cdUserProgress.introsCompleted else { return [] } // return intros.components(separatedBy: ", ").map({(value) in // if let intValue = Int(value) { // return intValue // } // return 0 // }) // } // // /** // * we agreed on not storing the CurrentDay object instead we're storing // * only its id. (currentDayId) // */ // return QuestUserProgress( // id: cdUserProgress.id, // currentDay: nil, // currentDayId: cdUserProgress.currentDayId, // daysCompleted: daysCompleted, // ended: false, // endedAt: nil, // completed: false, // completedAt: nil, // enrolledAt: nil, // enrollmentStartedAt: nil, // introsCompleted: introsCompleted, // started: cdUserProgress.started, // startedAt: nil, // totalDays: Int(cdUserProgress.totalDays), // totalDaysCompleted: Int(cdUserProgress.totalDaysCompleted), // totalIntros: Int(cdUserProgress.totalIntros), // totalIntrosCompleted: Int(cdUserProgress.totalIntrosCompleted), // questId: cdUserProgress.quest?.id // ) // } // // // MARK: - Fetch // // func loadBy(userProgressId: String, questId: String, result: @escaping (CDUserProgress?) -> Void) { // func perform() { // let p = predicate(userProgressId, questId) // guard let cdUserProgress = CDUserProgress.listAC(predicate: p).first as? CDUserProgress else { // result(nil) // return // } // result(cdUserProgress) // } // AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in // perform() // }) // } // // // MARK: - Helpers // // private func predicate(_ userProgressId: String, _ questId: String) -> NSPredicate { // return NSPredicate(format: "id == %@ AND quest.id == %@", userProgressId, questId) // } // //}
212868910a221673d4204cedcd8ab371
39.739496
126
0.59571
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/CallSettingsModalController.swift
gpl-2.0
1
// // CallSettingsModalController.swift // Telegram // // Created by Mikhail Filimonov on 21/02/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TelegramCore import SwiftSignalKit import Postbox import TGUIKit func CallSettingsModalController(_ sharedContext: SharedAccountContext) -> InputDataModalController { var close: (()->Void)? = nil let controller = CallSettingsController(sharedContext: sharedContext) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { close?() }) let modalController = InputDataModalController(controller) close = { [weak modalController] in modalController?.close() } return modalController }
6e2c45b60cafd12e90f1ad36fe4a72f6
20.444444
101
0.709845
false
false
false
false
geosor/SymondsStudentApp
refs/heads/master
Sources/SSACore/Timetable/Day.swift
mit
1
// // Day.swift // SSACore // // Created by Søren Mortensen on 16/12/2017. // Copyright © 2017 Søren Mortensen, George Taylor. All rights reserved. // import Foundation /// A day of the week. /// /// This enum is fully equipped for specialised use in tracking the days of the week on which particular /// `TimetableItem`s take place. This includes the raw values of the cases, which represent days of the week, /// `Day.today`, which returns the day of the week at the current moment, and the methods `dateThisWeek(from:)` and /// `dayThisWeek(for:)`, which are used for converting between `Day`s and `Date`s. /// /// - SeeAlso: `TimetableItem` public enum Day: Int, CustomStringConvertible { case monday = 0, tuesday, wednesday, thursday, friday, saturday, sunday // MARK: - Static Properties /// The day of the week for today. public static var today: Day { var weekday = calendar.component(.weekday, from: calendar.today()) - 2 // Change Sunday to 6 instead of -1, so that the numbers (and therefore the days' raw values) reflect how many // days they are after the start of the week (Monday). if weekday == -1 { weekday += 7 } let day = Day(rawValue: weekday)! return day } /// The days of the week in an array, going from Monday to Sunday. public static var week: [Day] = [.monday, .tuesday, .wednesday, .thursday, .friday, .saturday, .sunday] internal static var calendar: CalendarProtocol = Calendar.current // MARK: - Static Functions /// Calculates this week's date for a particular day of the week, going backwards if necessary. /// /// - Parameter day: The day of the week for which to calculate the date. /// - Returns: The date of that day of the week. Note that this is the *start of the day* on that date. public static func dateThisWeek(from day: Day) -> Date { let difference = day.rawValue - Day.today.rawValue return calendar.startOfDay(for: calendar.today()).addingTimeInterval(60 * 60 * 24 * TimeInterval(difference)) } /// Returns the weekday of a date within this week. If the provided date is not within this week, returns `nil`. /// /// - Parameter date: The date to convert. /// - Returns: The day of the week if the provided date is within this week; otherwise, `nil`. public static func dayThisWeek(for date: Date) -> Day? { let dateToday = dateThisWeek(from: .today) let otherDate = calendar.startOfDay(for: date) let differenceSeconds = otherDate.timeIntervalSince(dateToday) let differenceDays = Int(differenceSeconds / 60 / 60 / 24) guard differenceDays >= -today.rawValue && differenceDays <= 7 - today.rawValue else { return nil } return Day(rawValue: today.rawValue + differenceDays) } // MARK: - CustomStringConvertible /// :nodoc: public var description: String { switch self { case .monday: return "Monday" case .tuesday: return "Tuesday" case .wednesday: return "Wednesday" case .thursday: return "Thursday" case .friday: return "Friday" case .saturday: return "Saturday" case .sunday: return "Sunday" } } } // MARK: - Comparable extension Day: Comparable { /// :nodoc: public static func < (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday < rhsWeekday } /// :nodoc: public static func <= (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday <= rhsWeekday } /// :nodoc: public static func >= (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday >= rhsWeekday } /// :nodoc: public static func > (lhs: Day, rhs: Day) -> Bool { let lhsWeekday = lhs == .sunday ? lhs.rawValue + 7 : lhs.rawValue let rhsWeekday = rhs == .sunday ? lhs.rawValue + 7 : rhs.rawValue return lhsWeekday > rhsWeekday } }
a39855aecf780706d7e8878671eab8bf
36.739496
118
0.623914
false
false
false
false
dsay/POPDataSource
refs/heads/master
DataSources/DataSource/TableViewItemConfigurators.swift
mit
1
import UIKit public enum HeaderFooterView <Section: UIView>{ case title(String) case view((Section, Int) -> ()) case none } public struct DataSource { public enum Action { case select case edit case delete case highlight case unhighlight case willDisplay case willDisplayHeader case custom(String) } } extension DataSource.Action: Hashable, Equatable { public var hashValue: Int { switch self { case .select: return 1 case .edit: return 2 case .delete: return 3 case .highlight: return 4 case .unhighlight: return 5 case .willDisplay: return 6 case .willDisplayHeader: return 7 case .custom(let x): return 8 + x.hashValue } } public static func ==(lhs: DataSource.Action, rhs: DataSource.Action) -> Bool { return lhs.hashValue == rhs.hashValue } } /** * Cell */ public protocol CellContainable { associatedtype Configurator: CellConfigurator var cellConfigurator: Configurator? { get } } /** * Cell configurator */ public protocol CellConfigurator { associatedtype Item associatedtype Cell: UITableViewCell func reuseIdentifier() -> String func configurateCell(_ cell: Cell, item: Item, at indexPath: IndexPath) } /** * Selectable Cell */ public protocol CellSelectable: CellConfigurator { typealias Handler = (Cell, IndexPath, Item) -> () var selectors: [DataSource.Action: Handler] { get set } } public extension CellSelectable { func invoke(_ action: DataSource.Action) -> Handler? { return self.selectors[action] } mutating func on(_ action: DataSource.Action, handler: @escaping Handler) { self.selectors[action] = handler } } /** * Section */ public protocol HeaderContainable { associatedtype Header: SectionConfigurator var header: Header? { get } } public protocol FooterContainable { associatedtype Footer: SectionConfigurator var footer: Footer? { get } } /** * Section configurator */ public protocol SectionConfigurator { associatedtype SectionView: UIView func section() -> HeaderFooterView<SectionView> } /** * Selectable Section */ public protocol SectionSelectable: SectionConfigurator { typealias Handler = (SectionView, Int) -> () var selectors: [DataSource.Action: Handler] { get set } } public extension SectionSelectable { func invoke(_ action: DataSource.Action) -> Handler? { return self.selectors[action] } mutating func on(_ action: DataSource.Action, handler: @escaping Handler) { self.selectors[action] = handler } }
2c21969f5211931ba177c4b7c0efd5ba
20.84127
83
0.649346
false
true
false
false
material-motion/motion-transitions-objc
refs/heads/develop
tests/unit/TransitionTargetTests.swift
apache-2.0
1
/* 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 XCTest import MotionTransitions class TransitionTargetTests: XCTestCase { func testCustomTargetResolution() { let targetView = UIView() let target = TransitionTarget(view: targetView) let resolvedView = target.resolve(with: MockTransitionContext()) XCTAssertEqual(targetView, resolvedView) } func testForeResolution() { let target = TransitionTarget.withForeView() let context = MockTransitionContext() let resolvedView = target.resolve(with: context) XCTAssertEqual(context.foreViewController.view, resolvedView) } func testBackResolution() { let target = TransitionTarget.withBackView() let context = MockTransitionContext() let resolvedView = target.resolve(with: context) XCTAssertEqual(context.backViewController.view, resolvedView) } }
47ab19e4a1b7e22aa53de11bf70b1661
30.065217
73
0.764871
false
true
false
false
eselkin/DirectionFieldiOS
refs/heads/master
Pods/GRDB.swift/GRDB/Core/Database.swift
gpl-3.0
1
import Foundation /// A raw SQLite connection, suitable for the SQLite C API. public typealias SQLiteConnection = COpaquePointer /// A Database connection. /// /// You don't create a database directly. Instead, you use a DatabaseQueue: /// /// let dbQueue = DatabaseQueue(...) /// /// // The Database is the `db` in the closure: /// dbQueue.inDatabase { db in /// db.execute(...) /// } public final class Database { // ========================================================================= // MARK: - Select Statements /// Returns a prepared statement that can be reused. /// /// let statement = try db.selectStatement("SELECT * FROM persons WHERE age > ?") /// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])! /// /// - parameter sql: An SQL query. /// - returns: A SelectStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func selectStatement(sql: String) throws -> SelectStatement { return try SelectStatement(database: self, sql: sql) } // ========================================================================= // MARK: - Update Statements /// Returns an prepared statement that can be reused. /// /// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// /// This method may throw a DatabaseError. /// /// - parameter sql: An SQL query. /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. public func updateStatement(sql: String) throws -> UpdateStatement { return try UpdateStatement(database: self, sql: sql) } /// Executes an update statement. /// /// db.excute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"]) /// /// This method may throw a DatabaseError. /// /// - parameter sql: An SQL query. /// - parameter arguments: Statement arguments. /// - returns: A DatabaseChanges. /// - throws: A DatabaseError whenever a SQLite error occurs. public func execute(sql: String, arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges { let statement = try updateStatement(sql) return try statement.execute(arguments: arguments) } /// Executes multiple SQL statements, separated by semi-colons. /// /// try db.executeMultiStatement( /// "INSERT INTO persons (name) VALUES ('Harry');" + /// "INSERT INTO persons (name) VALUES ('Ron');" + /// "INSERT INTO persons (name) VALUES ('Hermione');") /// /// This method may throw a DatabaseError. /// /// - parameter sql: SQL containing multiple statements separated by /// semi-colons. /// - returns: A DatabaseChanges. Note that insertedRowID will always be nil. /// - throws: A DatabaseError whenever a SQLite error occurs. public func executeMultiStatement(sql: String) throws -> DatabaseChanges { preconditionValidQueue() let changedRowsBefore = sqlite3_total_changes(sqliteConnection) let code = sqlite3_exec(sqliteConnection, sql, nil, nil, nil) guard code == SQLITE_OK else { throw DatabaseError(code: code, message: lastErrorMessage, sql: sql, arguments: nil) } let changedRowsAfter = sqlite3_total_changes(sqliteConnection) return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: nil) } // ========================================================================= // MARK: - Transactions /// Executes a block inside a database transaction. /// /// try dbQueue.inDatabase do { /// try db.inTransaction { /// try db.execute("INSERT ...") /// return .Commit /// } /// } /// /// If the block throws an error, the transaction is rollbacked and the /// error is rethrown. /// /// This method is not reentrant: you can't nest transactions. /// /// - parameter kind: The transaction type (default nil). If nil, the /// transaction type is configuration.defaultTransactionKind, which itself /// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html /// for more information. /// - parameter block: A block that executes SQL statements and return /// either .Commit or .Rollback. /// - throws: The error thrown by the block. public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws { preconditionValidQueue() var completion: TransactionCompletion = .Rollback var blockError: ErrorType? = nil try beginTransaction(kind) do { completion = try block() } catch { completion = .Rollback blockError = error } switch completion { case .Commit: try commit() case .Rollback: // https://www.sqlite.org/lang_transaction.html#immediate // // > Response To Errors Within A Transaction // > // > If certain kinds of errors occur within a transaction, the // > transaction may or may not be rolled back automatically. The // > errors that can cause an automatic rollback include: // > // > - SQLITE_FULL: database or disk full // > - SQLITE_IOERR: disk I/O error // > - SQLITE_BUSY: database in use by another process // > - SQLITE_NOMEM: out or memory // > // > [...] It is recommended that applications respond to the errors // > listed above by explicitly issuing a ROLLBACK command. If the // > transaction has already been rolled back automatically by the // > error response, then the ROLLBACK command will fail with an // > error, but no harm is caused by this. if let blockError = blockError as? DatabaseError { switch Int32(blockError.code) { case SQLITE_FULL, SQLITE_IOERR, SQLITE_BUSY, SQLITE_NOMEM: do { try rollback() } catch { } default: try rollback() } } else { try rollback() } } if let blockError = blockError { throw blockError } } private func beginTransaction(kind: TransactionKind? = nil) throws { switch kind ?? configuration.defaultTransactionKind { case .Deferred: try execute("BEGIN DEFERRED TRANSACTION") case .Immediate: try execute("BEGIN IMMEDIATE TRANSACTION") case .Exclusive: try execute("BEGIN EXCLUSIVE TRANSACTION") } } private func rollback() throws { try execute("ROLLBACK TRANSACTION") } private func commit() throws { try execute("COMMIT TRANSACTION") } // ========================================================================= // MARK: - Transaction Observation private enum StatementCompletion { // Statement has ended with a commit (implicit or explicit). case TransactionCommit // Statement has ended with a rollback. case TransactionRollback // Statement has been rollbacked by transactionObserver. case TransactionErrorRollback(ErrorType) // All other cases (CREATE TABLE, etc.) case Regular } /// Updated in SQLite callbacks (see setupTransactionHooks()) /// Consumed in updateStatementDidFail() and updateStatementDidExecute(). private var statementCompletion: StatementCompletion = .Regular func updateStatementDidFail() throws { let statementCompletion = self.statementCompletion self.statementCompletion = .Regular switch statementCompletion { case .TransactionErrorRollback(let error): // The transaction has been rollbacked from // TransactionObserverType.transactionWillCommit(). configuration.transactionObserver!.databaseDidRollback(self) throw error default: break } } func updateStatementDidExecute() { let statementCompletion = self.statementCompletion self.statementCompletion = .Regular switch statementCompletion { case .TransactionCommit: configuration.transactionObserver!.databaseDidCommit(self) case .TransactionRollback: configuration.transactionObserver!.databaseDidRollback(self) default: break } } private func setupTransactionHooks() { // No need to setup any hook when there is no transactionObserver: guard configuration.transactionObserver != nil else { return } let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in let db = unsafeBitCast(dbPointer, Database.self) // Notify change event let event = DatabaseEvent( kind: DatabaseEvent.Kind(rawValue: updateKind)!, databaseName: String.fromCString(databaseName)!, tableName: String.fromCString(tableName)!, rowID: rowID) db.configuration.transactionObserver!.databaseDidChangeWithEvent(event) }, dbPointer) sqlite3_commit_hook(sqliteConnection, { dbPointer in let db = unsafeBitCast(dbPointer, Database.self) do { try db.configuration.transactionObserver!.databaseWillCommit() // Next step: updateStatementDidExecute() db.statementCompletion = .TransactionCommit return 0 } catch { // Next step: sqlite3_rollback_hook callback db.statementCompletion = .TransactionErrorRollback(error) return 1 } }, dbPointer) sqlite3_rollback_hook(sqliteConnection, { dbPointer in let db = unsafeBitCast(dbPointer, Database.self) switch db.statementCompletion { case .TransactionErrorRollback: // The transactionObserver has rollbacked the transaction. // Don't lose this information. // Next step: updateStatementDidFail() break default: // Next step: updateStatementDidExecute() db.statementCompletion = .TransactionRollback } }, dbPointer) } // ========================================================================= // MARK: - Concurrency /// The busy handler callback, if any. See Configuration.busyMode. private var busyCallback: BusyCallback? func setupBusyMode() { switch configuration.busyMode { case .ImmediateError: break case .Timeout(let duration): let milliseconds = Int32(duration * 1000) sqlite3_busy_timeout(sqliteConnection, milliseconds) case .Callback(let callback): let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) busyCallback = callback sqlite3_busy_handler( sqliteConnection, { (dbPointer: UnsafeMutablePointer<Void>, numberOfTries: Int32) in let database = unsafeBitCast(dbPointer, Database.self) let callback = database.busyCallback! return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0 }, dbPointer) } } // ========================================================================= // MARK: - Functions private var functions = Set<DatabaseFunction>() /// Add or redefine an SQL function. /// /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in /// let dbv = databaseValues.first! /// guard let int = dbv.value() as Int? else { /// return nil /// } /// return int + 1 /// } /// db.addFunction(fn) /// Int.fetchOne(db, "SELECT succ(1)")! // 2 /// /// - parameter function: A function. public func addFunction(function: DatabaseFunction) { functions.remove(function) functions.insert(function) let functionPointer = unsafeBitCast(function, UnsafeMutablePointer<Void>.self) let code = sqlite3_create_function_v2( sqliteConnection, function.name, function.argumentCount, SQLITE_UTF8 | function.eTextRep, functionPointer, { (context, argc, argv) in let function = unsafeBitCast(sqlite3_user_data(context), DatabaseFunction.self) do { let result = try function.function(context, argc, argv) switch result.storage { case .Null: sqlite3_result_null(context) case .Int64(let int64): sqlite3_result_int64(context, int64) case .Double(let double): sqlite3_result_double(context, double) case .String(let string): sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT) case .Blob(let data): sqlite3_result_blob(context, data.bytes, Int32(data.length), SQLITE_TRANSIENT) } } catch let error as DatabaseError { if let message = error.message { sqlite3_result_error(context, message, -1) } sqlite3_result_error_code(context, Int32(error.code)) } catch { sqlite3_result_error(context, "\(error)", -1) } }, nil, nil, nil) guard code == SQLITE_OK else { fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description) } } /// Remove an SQL function. /// /// - parameter function: A function. public func removeFunction(function: DatabaseFunction) { functions.remove(function) let code = sqlite3_create_function_v2( sqliteConnection, function.name, function.argumentCount, SQLITE_UTF8 | function.eTextRep, nil, nil, nil, nil, nil) guard code == SQLITE_OK else { fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description) } } // ========================================================================= // MARK: - Collations private var collations = Set<DatabaseCollation>() /// Add or redefine a collation. /// /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.addCollation(collation) /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// /// - parameter collation: A collation. public func addCollation(collation: DatabaseCollation) { collations.remove(collation) collations.insert(collation) let collationPointer = unsafeBitCast(collation, UnsafeMutablePointer<Void>.self) let code = sqlite3_create_collation_v2( sqliteConnection, collation.name, SQLITE_UTF8, collationPointer, { (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in let collation = unsafeBitCast(collationPointer, DatabaseCollation.self) // Buffers are not C strings: they do not end with \0. let string1 = String(bytesNoCopy: UnsafeMutablePointer<Void>(buffer1), length: Int(length1), encoding: NSUTF8StringEncoding, freeWhenDone: false)! let string2 = String(bytesNoCopy: UnsafeMutablePointer<Void>(buffer2), length: Int(length2), encoding: NSUTF8StringEncoding, freeWhenDone: false)! return Int32(collation.function(string1, string2).rawValue) }, nil) guard code == SQLITE_OK else { fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description) } } /// Remove a collation. /// /// - parameter collation: A collation. public func removeCollation(collation: DatabaseCollation) { collations.remove(collation) sqlite3_create_collation_v2( sqliteConnection, collation.name, SQLITE_UTF8, nil, nil, nil) } // ========================================================================= // MARK: - Database Informations /// Clears the database schema cache. /// /// You may need to clear the cache if you modify the database schema /// outside of a migration (see DatabaseMigrator). public func clearSchemaCache() { preconditionValidQueue() columnInfosCache = [:] } /// The last error message var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) } /// Returns whether a table exists. /// /// - parameter tableName: A table name. /// - returns: True if the table exists. public func tableExists(tableName: String) -> Bool { // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) return Row.fetchOne(self, "SELECT sql FROM sqlite_master WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercaseString]) != nil } /// Return the primary key for table named `tableName`, or nil if table does /// not exist. /// /// This method is not thread-safe. func primaryKey(tableName: String) -> PrimaryKey? { // https://www.sqlite.org/pragma.html // // > PRAGMA database.table_info(table-name); // > // > This pragma returns one row for each column in the named table. // > Columns in the result set include the column name, data type, // > whether or not the column can be NULL, and the default value for // > the column. The "pk" column in the result set is zero for columns // > that are not part of the primary key, and is the index of the // > column in the primary key for columns that are part of the primary // > key. // // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // firstName TEXT, // lastName TEXT) // // PRAGMA table_info("persons") // // cid | name | type | notnull | dflt_value | pk | // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | let columnInfos = self.columnInfos(tableName) guard columnInfos.count > 0 else { // Table does not exist return nil } let pkColumnInfos = columnInfos .filter { $0.primaryKeyIndex > 0 } .sort { $0.primaryKeyIndex < $1.primaryKeyIndex } switch pkColumnInfos.count { case 0: // No primary key column return PrimaryKey.None case 1: // Single column let pkColumnInfo = pkColumnInfos.first! // https://www.sqlite.org/lang_createtable.html: // // > With one exception noted below, if a rowid table has a primary // > key that consists of a single column and the declared type of // > that column is "INTEGER" in any mixture of upper and lower // > case, then the column becomes an alias for the rowid. Such a // > column is usually referred to as an "integer primary key". // > A PRIMARY KEY column only becomes an integer primary key if the // > declared type name is exactly "INTEGER". Other integer type // > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED // > INTEGER" causes the primary key column to behave as an ordinary // > table column with integer affinity and a unique index, not as // > an alias for the rowid. // > // > The exception mentioned above is that if the declaration of a // > column with declared type "INTEGER" includes an "PRIMARY KEY // > DESC" clause, it does not become an alias for the rowid [...] // // We ignore the exception, and consider all INTEGER primary keys as // aliases for the rowid: if pkColumnInfo.type.uppercaseString == "INTEGER" { return .Managed(pkColumnInfo.name) } else { return .Unmanaged([pkColumnInfo.name]) } default: // Multi-columns primary key return .Unmanaged(pkColumnInfos.map { $0.name }) } } // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // firstName TEXT, // lastName TEXT) // // PRAGMA table_info("persons") // // cid | name | type | notnull | dflt_value | pk | // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | private struct ColumnInfo : RowConvertible { let name: String let type: String let notNull: Bool let defaultDatabaseValue: DatabaseValue let primaryKeyIndex: Int static func fromRow(row: Row) -> ColumnInfo { return ColumnInfo( name:row.value(named: "name"), type:row.value(named: "type"), notNull:row.value(named: "notnull"), defaultDatabaseValue:row["dflt_value"]!, primaryKeyIndex:row.value(named: "pk")) } } // Cache for columnInfos() private var columnInfosCache: [String: [ColumnInfo]] = [:] private func columnInfos(tableName: String) -> [ColumnInfo] { if let columnInfos = columnInfosCache[tableName] { return columnInfos } else { // This pragma is case-insensitive: PRAGMA table_info("PERSONS") and // PRAGMA table_info("persons") yield the same results. let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") columnInfosCache[tableName] = columnInfos return columnInfos } } // ========================================================================= // MARK: - Raw SQLite connetion /// The raw SQLite connection, suitable for the SQLite C API. public let sqliteConnection: SQLiteConnection // ========================================================================= // MARK: - Configuration /// The database configuration public let configuration: Configuration // ========================================================================= // MARK: - Initialization /// The queue from which the database can be used. See preconditionValidQueue(). /// Design note: this is not very clean. A delegation pattern may be a /// better fit. var databaseQueueID: DatabaseQueueID = nil init(path: String, configuration: Configuration) throws { self.configuration = configuration // See https://www.sqlite.org/c3ref/open.html var sqliteConnection = SQLiteConnection() let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) self.sqliteConnection = sqliteConnection if code != SQLITE_OK { throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) } setupTrace() // First, so that all queries, including initialization queries, are traced. try setupForeignKeys() setupBusyMode() setupTransactionHooks() } // Initializes an in-memory database convenience init(configuration: Configuration) { try! self.init(path: ":memory:", configuration: configuration) } deinit { sqlite3_close(sqliteConnection) } // ========================================================================= // MARK: - Misc func preconditionValidQueue() { precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, use fetchAll() instead: it returns an Array that can be iterated on any thread.") } func setupForeignKeys() throws { if configuration.foreignKeysEnabled { try execute("PRAGMA foreign_keys = ON") } } func setupTrace() { guard configuration.trace != nil else { return } let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) sqlite3_trace(sqliteConnection, { (dbPointer, sql) in let database = unsafeBitCast(dbPointer, Database.self) database.configuration.trace!(String.fromCString(sql)!) }, dbPointer) } } // ============================================================================= // MARK: - PrimaryKey /// A primary key enum PrimaryKey { /// No primary key case None /// A primary key managed by SQLite. Associated string is a column name. case Managed(String) /// A primary key not managed by SQLite. It can span accross several /// columns. Associated strings are column names. case Unmanaged([String]) /// The columns in the primary key. May be empty. var columns: [String] { switch self { case .None: return [] case .Managed(let column): return [column] case .Unmanaged(let columns): return columns } } } // ============================================================================= // MARK: - TransactionKind /// A SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html public enum TransactionKind { case Deferred case Immediate case Exclusive } // ============================================================================= // MARK: - TransactionCompletion /// The end of a transaction: Commit, or Rollback public enum TransactionCompletion { case Commit case Rollback } // ============================================================================= // MARK: - TransactionObserverType /// A transaction observer is notified of all changes and transactions committed /// or rollbacked on a database. /// /// Adopting types must be a class. public protocol TransactionObserverType : class { /// Notifies a database change (insert, update, or delete). /// /// The change is pending until the end of the current transaction, notified /// to databaseWillCommit, databaseDidCommit and databaseDidRollback. /// /// This method is called on the database queue. /// /// **WARNING**: this method must not change the database. /// /// - parameter event: A database event. func databaseDidChangeWithEvent(event: DatabaseEvent) /// When a transaction is about to be committed, the transaction observer /// has an opportunity to rollback pending changes by throwing an error. /// /// This method is called on the database queue. /// /// **WARNING**: this method must not change the database. /// /// - throws: An eventual error that rollbacks pending changes. func databaseWillCommit() throws /// Database changes have been committed. /// /// This method is called on the database queue. It can change the database. /// /// - parameter db: A Database. func databaseDidCommit(db: Database) /// Database changes have been rollbacked. /// /// This method is called on the database queue. It can change the database. /// /// - parameter db: A Database. func databaseDidRollback(db: Database) } // ============================================================================= // MARK: - DatabaseEvent /// A database event, notified to TransactionObserverType. /// /// See https://www.sqlite.org/c3ref/update_hook.html for more information. public struct DatabaseEvent { /// An event kind public enum Kind: Int32 { case Insert = 18 // SQLITE_INSERT case Delete = 9 // SQLITE_DELETE case Update = 23 // SQLITE_UPDATE } /// The event kind public let kind: Kind /// The database name public let databaseName: String /// The table name public let tableName: String /// The rowID of the changed row. public let rowID: Int64 } // ============================================================================= // MARK: - ThreadingMode /// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html. enum ThreadingMode { case Default case MultiThread case Serialized var sqliteOpenFlags: Int32 { switch self { case .Default: return 0 case .MultiThread: return SQLITE_OPEN_NOMUTEX case .Serialized: return SQLITE_OPEN_FULLMUTEX } } } // ============================================================================= // MARK: - BusyMode /// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html public typealias BusyCallback = (numberOfTries: Int) -> Bool /// When there are several connections to a database, a connection may try to /// access the database while it is locked by another connection. /// /// The BusyMode enum describes the behavior of GRDB when such a situation /// occurs: /// /// - .ImmediateError: The SQLITE_BUSY error is immediately returned to the /// connection that tries to access the locked database. /// /// - .Timeout: The SQLITE_BUSY error will be returned only if the database /// remains locked for more than the specified duration. /// /// - .Callback: Perform your custom lock handling. /// /// To set the busy mode of a database, use Configuration: /// /// let configuration = Configuration(busyMode: .Timeout(1)) /// let dbQueue = DatabaseQueue(path: "...", configuration: configuration) /// /// Relevant SQLite documentation: /// /// - https://www.sqlite.org/c3ref/busy_timeout.html /// - https://www.sqlite.org/c3ref/busy_handler.html /// - https://www.sqlite.org/lang_transaction.html /// - https://www.sqlite.org/wal.html public enum BusyMode { /// The SQLITE_BUSY error is immediately returned to the connection that /// tries to access the locked database. case ImmediateError /// The SQLITE_BUSY error will be returned only if the database remains /// locked for more than the specified duration. case Timeout(NSTimeInterval) /// A custom callback that is called when a database is locked. /// See https://www.sqlite.org/c3ref/busy_handler.html case Callback(BusyCallback) } // ========================================================================= // MARK: - Functions /// An SQL function. public class DatabaseFunction : Hashable { let name: String let argumentCount: Int32 let pure: Bool let function: (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) throws -> DatabaseValue var eTextRep: Int32 { return pure ? SQLITE_DETERMINISTIC : 0 } /// The hash value. public var hashValue: Int { return name.hashValue ^ argumentCount.hashValue } /// Returns an SQL function. /// /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in /// let dbv = databaseValues.first! /// guard let int = dbv.value() as Int? else { /// return nil /// } /// return int + 1 /// } /// db.addFunction(fn) /// Int.fetchOne(db, "SELECT succ(1)")! // 2 /// /// - parameter name: The function name. /// - parameter argumentCount: The number of arguments of the function. If /// omitted, or nil, the function accepts any number of arguments. /// - parameter pure: Whether the function is "pure", which means that its /// results only depends on its inputs. When a function is pure, SQLite /// has the opportunity to perform additional optimizations. Default value /// is false. /// - parameter function: A function that takes an array of DatabaseValue /// arguments, and returns an optional DatabaseValueConvertible such as /// Int, String, NSDate, etc. The array is guaranteed to have exactly /// *argumentCount* elements, provided *argumentCount* is not nil. public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: [DatabaseValue] throws -> DatabaseValueConvertible?) { self.name = name self.argumentCount = argumentCount ?? -1 self.pure = pure self.function = { (context, argc, argv) in let arguments = (0..<Int(argc)).map { index in DatabaseValue(sqliteValue: argv[index]) } return try function(arguments)?.databaseValue ?? .Null } } } /// Two functions are equal if they share the same name and argumentCount. public func ==(lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { return lhs.name == rhs.name && lhs.argumentCount == rhs.argumentCount } // ========================================================================= // MARK: - Collations /// A Collation. public class DatabaseCollation : Hashable { let name: String let function: (String, String) -> NSComparisonResult /// The hash value. public var hashValue: Int { // We can't compute a hash since the equality is based on the opaque // sqlite3_strnicmp SQLite function. return 0 } /// Returns a collation. /// /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.addCollation(collation) /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// /// - parameter name: The function name. /// - parameter function: A function that compares two strings. public init(_ name: String, function: (String, String) -> NSComparisonResult) { self.name = name self.function = function } } /// Two collations are equal if they share the same name (case insensitive) public func ==(lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { // See https://www.sqlite.org/c3ref/create_collation.html return sqlite3_stricmp(lhs.name, lhs.name) == 0 }
ba20bdd147166da76492b4635b0d4b49
37.001041
412
0.572524
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Filters/Equalizer Filter/AKEqualizerFilter.swift
mit
1
// // AKEqualizerFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A 2nd order tunable equalization filter that provides a peak/notch filter /// for building parametric/graphic equalizers. With gain above 1, there will be /// a peak at the center frequency with a width dependent on bandwidth. If gain /// is less than 1, a notch is formed around the center frequency. /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center frequency. (in Hertz) /// - parameter bandwidth: The peak/notch bandwidth in Hertz /// - parameter gain: The peak/notch gain /// public class AKEqualizerFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKEqualizerFilterAudioUnit? internal var token: AUParameterObserverToken? private var centerFrequencyParameter: AUParameter? private var bandwidthParameter: AUParameter? private var gainParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Center frequency. (in Hertz) public var centerFrequency: Double = 1000 { willSet { if centerFrequency != newValue { if internalAU!.isSetUp() { centerFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.centerFrequency = Float(newValue) } } } } /// The peak/notch bandwidth in Hertz public var bandwidth: Double = 100 { willSet { if bandwidth != newValue { if internalAU!.isSetUp() { bandwidthParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.bandwidth = Float(newValue) } } } } /// The peak/notch gain public var gain: Double = 10 { willSet { if gain != newValue { if internalAU!.isSetUp() { gainParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.gain = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center frequency. (in Hertz) /// - parameter bandwidth: The peak/notch bandwidth in Hertz /// - parameter gain: The peak/notch gain /// public init( _ input: AKNode, centerFrequency: Double = 1000, bandwidth: Double = 100, gain: Double = 10) { self.centerFrequency = centerFrequency self.bandwidth = bandwidth self.gain = gain var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x6571666c /*'eqfl'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKEqualizerFilterAudioUnit.self, asComponentDescription: description, name: "Local AKEqualizerFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKEqualizerFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } centerFrequencyParameter = tree.valueForKey("centerFrequency") as? AUParameter bandwidthParameter = tree.valueForKey("bandwidth") as? AUParameter gainParameter = tree.valueForKey("gain") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.centerFrequencyParameter!.address { self.centerFrequency = Double(value) } else if address == self.bandwidthParameter!.address { self.bandwidth = Double(value) } else if address == self.gainParameter!.address { self.gain = Double(value) } } } internalAU?.centerFrequency = Float(centerFrequency) internalAU?.bandwidth = Float(bandwidth) internalAU?.gain = Float(gain) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
75c667c938a25143500b86037a8cab8a
33.420732
91
0.604074
false
false
false
false
jnwagstaff/PutItOnMyTabBar
refs/heads/master
Example/PutItOnMyTabBar/MainViewController.swift
mit
1
// // MainViewController.swift // PutItOnMyTabBar // // Created by Jacob Wagstaff on 8/18/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class MainViewController: UIViewController { // MARK: - Properties // MARK: - View let baseView = MainView() // MARK: - Life Cycle override func loadView() { super.loadView() view = baseView setupViewOnLoad() } /// Setup View upon loading ViewController (e.g. add targets to buttons, update labels with data, etc.) func setupViewOnLoad() { baseView.table.delegate = self baseView.table.dataSource = self title = "Example TabBars 🍻" } override func viewDidLoad() { super.viewDidLoad() } } extension MainViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() switch indexPath.row{ case 0: cell.textLabel?.text = "Normal Tab Bar" case 1: cell.textLabel?.text = "Slider Tab Bar" case 2: cell.textLabel?.text = "Background Tab Bar" case 3: cell.textLabel?.text = "Small Slider Tab Bar" default: break } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var vc : UITabBarController! switch indexPath.row { case 0: vc = NormalTabBarController() case 1: vc = SliderTabBarController() case 2: vc = BackgroundTabBarController() case 3: vc = SmallSliderTabBarController() default: break } self.navigationController?.pushViewController(vc, animated: true) } }
efaf69e15b752db9705944e46ddb73e7
23.494382
107
0.575229
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
refs/heads/master
Source/Utils/Log.swift
bsd-3-clause
1
// // Copyright (C) 2015-2020 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Class used for logging public enum Log { /// Log with DEBUG level /// /// - Parameters: /// - closure: fake closure to caprute loging details /// - functionName: functionName /// - file: file /// - line: line public static func debug(_ closure: @autoclosure () -> String, functionName: String = #function, file: String = #file, line: UInt = #line) { #if DEBUG self.log("<DEBUG>: \(closure())", functionName: functionName, file: file, line: line) #endif } /// Log with ERROR level /// /// - Parameters: /// - closure: fake closure to caprute loging details /// - functionName: functionName /// - file: file /// - line: line public static func error(_ closure: @autoclosure () -> String, functionName: String = #function, file: String = #file, line: UInt = #line) { self.log("<ERROR>: \(closure())", functionName: functionName, file: file, line: line) } private static func log(_ closure: @autoclosure () -> String, functionName: String = #function, file: String = #file, line: UInt = #line) { let str = "VIRGILSDK_LOG: \(functionName) : \(closure())" Log.writeInLog(str) } private static func writeInLog(_ message: String) { NSLogv("%@", getVaList([message])) } }
9e9fe303a9c7be3e76c8e218a12e43ff
39.644737
100
0.655876
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
refs/heads/develop
ShareExtension/ShareViewController.swift
apache-2.0
1
// // ShareViewController.swift // ShareExtension // // Created by Mia Alexiou on 01/02/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import WebKit import Social import Core class ShareViewController: UIViewController { private let urlIdentifier = "public.url" private let textIdentifier = "public.plain-text" @IBOutlet weak var backButton: UIButton! @IBOutlet weak var forwardButton: UIButton! private var webController: WebViewController? private lazy var groupData = GroupDataStore() override func viewDidLoad() { super.viewDidLoad() refreshNavigationButtons() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let urlProvider = getItemProvider(identifier: urlIdentifier) { loadUrl(urlProvider: urlProvider) return } if let textProvider = getItemProvider(identifier: textIdentifier) { loadText(textProvider: textProvider) return } } private func getItemProvider(identifier: String) -> NSItemProvider? { guard let item = extensionContext?.inputItems.first as? NSExtensionItem else { return nil } guard let itemProvider = item.attachments?.first as? NSItemProvider else { return nil } if itemProvider.hasItemConformingToTypeIdentifier(identifier) { return itemProvider } return nil } private func loadUrl(urlProvider: NSItemProvider) { urlProvider.loadItem(forTypeIdentifier: urlIdentifier, options: nil, completionHandler: { [weak self] (item, error) in if let url = item as? URL { self?.webController?.load(url: url) } }) } private func loadText(textProvider: NSItemProvider) { textProvider.loadItem(forTypeIdentifier: textIdentifier, options: nil, completionHandler: { [weak self] (item, error) in let dataStore = GroupDataStore() guard let text = item as? String else { return } guard let queryUrl = AppUrls.url(forQuery: text, filters: dataStore) else { return } self?.webController?.load(url: queryUrl) }) } fileprivate func refreshNavigationButtons() { backButton.isEnabled = webController?.canGoBack ?? false forwardButton.isEnabled = webController?.canGoForward ?? false } @IBAction func onRefreshPressed(_ sender: UIButton) { webController?.reload() } @IBAction func onBackPressed(_ sender: UIButton) { webController?.goBack() } @IBAction func onForwardPressed(_ sender: UIButton) { webController?.goForward() } @IBAction func onSaveBookmark(_ sender: UIButton) { if let link = webController?.link { groupData.addBookmark(link) webController?.view.makeToast(UserText.webSaveLinkDone) } } @IBAction func onClose(_ sender: UIButton) { webController?.tearDown() extensionContext?.completeRequest(returningItems: [], completionHandler: nil) } @IBAction func onDeleteEverything(_ sender: UIButton) { webController?.reset() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? WebViewController { controller.webEventsDelegate = self webController = controller } } } extension ShareViewController: WebEventsDelegate { func attached(webView: WKWebView) { webView.loadScripts() } func webView(_ webView: WKWebView, didReceiveLongPressForUrl url: URL) { webView.load(URLRequest(url: url)) } func webView(_ webView: WKWebView, didRequestNewTabForRequest urlRequest: URLRequest) { webView.load(urlRequest) } func webpageDidStartLoading() { } func webpageDidFinishLoading() { refreshNavigationButtons() } }
c186f93fd0058b6fac66849c938b132e
29.931818
128
0.64046
false
false
false
false
JamieScanlon/AugmentKit
refs/heads/master
AugmentKit/AKCore/Anchors/AugmentedAnchor.swift
mit
1
// // AugmentedAnchor.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // 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 ARKit import Foundation import ModelIO /** A generic implementation of `AKAugmentedAnchor`. An AR anchor that can be placed in the AR world. These can be created and given to the AR engine to render in the AR world. */ open class AugmentedAnchor: AKAugmentedAnchor { /** Returns "AugmentedAnchor" */ public static var type: String { return "AugmentedAnchor" } /** The location of the anchor */ public var worldLocation: AKWorldLocation /** The locaiton of the anchor */ public var heading: AKHeading = NorthHeading() /** The `MDLAsset` associated with the entity. */ public var asset: MDLAsset /** A unique, per-instance identifier */ public var identifier: UUID? /** An array of `AKEffect` objects that are applied by the renderer */ public var effects: [AnyEffect<Any>]? /** Specified a perfered renderer to use when rendering this enitity. Most will use the standard PBR renderer but some entities may prefer a simpiler renderer when they are not trying to achieve the look of real-world objects. Defaults to the PBR renderer. */ public var shaderPreference: ShaderPreference = .pbr /** Indicates whether this geometry participates in the generation of augmented shadows. Since this is an augmented geometry, it does generate shadows. */ public var generatesShadows: Bool = true /** If `true`, the current base color texture of the entity has changed since the last time it was rendered and the pixel data needs to be updated. This flag can be used to achieve dynamically updated textures for rendered objects. */ public var needsColorTextureUpdate: Bool = false /// If `true` the underlying mesh for this geometry has changed and the renderer needs to update. This can be used to achieve dynamically generated geometries that change over time. public var needsMeshUpdate: Bool = false /** An `ARAnchor` that will be tracked in the AR world by `ARKit` */ public var arAnchor: ARAnchor? /** Initialize a new object with an `MDLAsset` and an `AKWorldLocation` - Parameters: - withModelAsset: The `MDLAsset` associated with the entity. - at: The location of the anchor */ public init(withModelAsset asset: MDLAsset, at location: AKWorldLocation) { self.asset = asset self.worldLocation = location } /** Sets a new `arAnchor` - Parameters: - _: An `ARAnchor` */ public func setARAnchor(_ arAnchor: ARAnchor) { self.arAnchor = arAnchor if identifier == nil { identifier = arAnchor.identifier } worldLocation.transform = arAnchor.transform } } /// :nodoc: extension AugmentedAnchor: CustomDebugStringConvertible, CustomStringConvertible { /// :nodoc: public var description: String { return debugDescription } /// :nodoc: public var debugDescription: String { let myDescription = "<AugmentedAnchor: \(Unmanaged.passUnretained(self).toOpaque())> worldLocation: \(worldLocation), identifier:\(identifier?.debugDescription ?? "None"), effects: \(effects?.debugDescription ?? "None"), arAnchor: \(arAnchor?.debugDescription ?? "None"), asset: \(asset)" return myDescription } }
fcfd72c7c5752bdf0ee0535f061434e7
37.241667
296
0.691654
false
false
false
false
justinmakaila/GraphQLMapping
refs/heads/master
GraphQLMapping/NSEntityDescription+GraphQL.swift
mit
1
import CoreData import GraphQL import RemoteMapping /// Mapping for GraphQL Relationships protocol GraphQLRelationshipMapping { var graphQLRelayConnection: Bool { get } } public protocol GraphQLEntity { /// The field name representing the entity var fieldName: String { get } /// The collection name representing a collection of entities var collectionName: String { get } } private enum MappingKey: String { case relayConnection = "GraphQL.RelayConnection" case fieldName = "GraphQL.FieldName" case collectionName = "GraphQL.CollectionName" case customSelectionSet = "GraphQL.CustomSelectionSet" } extension NSPropertyDescription { public var graphQLPropertyName: String { return userInfo?[MappingKey.fieldName.rawValue] as? String ?? remotePropertyName } fileprivate var graphQLCustomSelectionSet: GraphQL.SelectionSet { guard let selectionSetString = userInfo?[MappingKey.customSelectionSet.rawValue] as? String else { return [] } let components = selectionSetString.components(separatedBy: " ") let selectionSetComponents = Array(components.dropLast().dropFirst()) return selectionSetComponents.map { GraphQL.Field(name: $0) } } } extension NSRelationshipDescription: GraphQLRelationshipMapping { public var graphQLRelayConnection: Bool { return userInfo?[MappingKey.relayConnection.rawValue] != nil } } extension NSEntityDescription: GraphQLEntity { public var fieldName: String { return (userInfo?[MappingKey.fieldName.rawValue] as? String ?? name ?? managedObjectClassName) } public var collectionName: String { return userInfo?[MappingKey.collectionName.rawValue] as? String ?? "\(fieldName)s" } } public extension NSEntityDescription { /// Returns a selection set representing the entity. public func selectionSet(_ parent: NSEntityDescription? = nil, includeRelationships: Bool = true, excludeKeys: Set<String> = [], customFields: [String: GraphQL.Field] = [:]) -> GraphQL.SelectionSet { return remoteProperties .filter { propertyDescription in return !excludeKeys.contains(propertyDescription.graphQLPropertyName) } .flatMap { propertyDescription -> GraphQL.Field? in let remoteKey = propertyDescription.graphQLPropertyName if let customField = customFields[remoteKey] { return customField } if let attributeDescription = propertyDescription as? NSAttributeDescription { return fieldForAttribute(attributeDescription) } else if let relationshipDescription = propertyDescription as? NSRelationshipDescription , (includeRelationships == true) { guard let destinationEntity = relationshipDescription.destinationEntity else { return nil } let isValidRelationship = !(parent != nil && (parent == destinationEntity) && !relationshipDescription.isToMany) if isValidRelationship { return relationshipDescription.isToMany ? fieldForToManyRelationship(destinationEntity, relationshipName: remoteKey, includeRelationships: includeRelationships, parent: self, relayConnection: relationshipDescription.graphQLRelayConnection) : fieldForToOneRelationship(destinationEntity, relationshipName: remoteKey, includeRelationships: includeRelationships, parent: self) } } return nil } } fileprivate func fieldForAttribute(_ attribute: NSAttributeDescription) -> GraphQL.Field { return GraphQL.Field(name: attribute.graphQLPropertyName, selectionSet: attribute.graphQLCustomSelectionSet) } /// Returns a field representing a to-one relationship fileprivate func fieldForToOneRelationship(_ entity: NSEntityDescription, relationshipName: String, includeRelationships: Bool = true, parent: NSEntityDescription?) -> GraphQL.Field { return GraphQL.Field(name: relationshipName, selectionSet: entity.selectionSet(parent, includeRelationships: includeRelationships)) } /// Returns a field representing a to-many relationship fileprivate func fieldForToManyRelationship(_ entity: NSEntityDescription, relationshipName: String, includeRelationships: Bool = true, parent: NSEntityDescription?, relayConnection: Bool = false) -> GraphQL.Field? { if relayConnection { return GraphQL.Field(name: relationshipName, selectionSet: [ GraphQL.Field(name: "edges", selectionSet: [ GraphQL.Field(name: "node", selectionSet: entity.selectionSet(parent, includeRelationships: includeRelationships)) ]) ] ) } else { return GraphQL.Field(name: relationshipName, selectionSet: entity.selectionSet(parent, includeRelationships: includeRelationships)) } } } extension NSManagedObject: GraphQLEntity { public var fieldName: String { return entity.fieldName } public var collectionName: String { return entity.collectionName } }
081d79ec05fbd613e4cd530475585cf7
42.52381
227
0.667761
false
false
false
false
blighli/iPhone2015
refs/heads/master
21551047黄鑫/FinalAssignment/The Ending/MasterDetailViewController.swift
mit
1
// // MasterDetailViewController.swift // The Ending // // Created by Xin on 23/12/2015. // Copyright © 2015 Huang Xin. All rights reserved. // import UIKit class MasterDetailViewController: UIViewController { private var isAnimating: Bool = false private struct Constants { static let GapWidth: CGFloat = 72 static let AnimationTime = 0.3 } ///This method must be overriden to make this controller work func detailControllerIdentifierName()->String { preconditionFailure("This method must be overridden") } lazy var child: UIViewController? = { return self.storyboard?.instantiateViewControllerWithIdentifier(self.detailControllerIdentifierName()) }() override func viewDidLoad() { super.viewDidLoad() addChildViewController(child!) self.view.addSubview(child!.view) var cFrame = child!.view.frame cFrame.size.width -= Constants.GapWidth child!.view.frame = cFrame child!.view.center = CGPointMake(-child!.view.bounds.size.width / 2, child!.view.center.y) } func slide(isUp: Bool) { if isAnimating { return } self.isAnimating = true if (isUp) { let overlayBlurView = UIVisualEffectView() overlayBlurView.frame = view.frame overlayBlurView.tag = 101 view.insertSubview(overlayBlurView, belowSubview: child!.view) UIView.animateWithDuration(Constants.AnimationTime, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.child!.view.center = CGPointMake(self.view.bounds.size.width / 2 - Constants.GapWidth / 2, self.view.bounds.size.height / 2) overlayBlurView.effect = UIBlurEffect(style: .Dark) }, completion: { finished in self.isAnimating = false }) let gestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:") gestureRecognizer.numberOfTapsRequired = 1 overlayBlurView.addGestureRecognizer(gestureRecognizer) } else { var overlayBlurView: UIVisualEffectView? = nil for subView in view.subviews { if subView.tag == 101 { overlayBlurView = subView as? UIVisualEffectView } } if let blurView = overlayBlurView { UIView.animateWithDuration(Constants.AnimationTime, animations: { self.child!.view.center = CGPointMake(-self.child!.view.bounds.size.width / 2, self.child!.view.center.y) blurView.effect = nil }, completion: { finished in blurView.removeFromSuperview() self.isAnimating = false }) } } } func handleTapGesture(gesture: UIPanGestureRecognizer) { if gesture.numberOfTouches() == 1 { slide(false) } } }
f89599edf72f754bb8ba6fb58f60e683
35.857143
145
0.59916
false
false
false
false
chiehwen/Swift3-Exercises
refs/heads/master
MemoryBasic.playground/Contents.swift
mit
1
class Person { var firstname:String var lastname:String var fullname:String init() { firstname = "Chuck" lastname = "Yang" fullname = firstname + lastname print("a person is being initialized") } deinit { print("a person is being deinitialized") } } var person1:Person? = Person() person1?.firstname person1 = nil
06646995a1ddd6176aba69f1c6b6aeff
19.210526
48
0.610966
false
false
false
false
iException/garage
refs/heads/master
Garage/Sources/LockSplashViewController.swift
mit
1
// // LockSplashViewController.swift // Garage // // Created by Yiming Tang on 10/28/17. // Copyright © 2017 Baixing. All rights reserved. // import UIKit import VENTouchLock class LockSplashViewController: VENTouchLockSplashViewController { // MARK: - Properties lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.image = #imageLiteral(resourceName: "i-love-study") return imageView }() // MARK: - Initialzation override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setIsSnapshot(true) didFinishWithSuccess = { [weak self] (success: Bool, unlockType: VENTouchLockSplashViewControllerUnlockType) -> () in if success { self?.touchLock.backgroundLockVisible = false switch unlockType { case .touchID: print("Unlocked with touch id") case .passcode: print("Unlocked with passcode") case .none: print("None passcode") } } else { let alert = UIAlertController(title: "Limit Exceeded", message: "You have exceeded the maximum number of passcode attempts", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self?.present(alert, animated: true, completion: nil) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) view.addSubview(imageView) NSLayoutConstraint.activate([ imageView.leadingAnchor .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), imageView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), imageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), ]) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(authenticate(_:))) tapGestureRecognizer.numberOfTapsRequired = 4 view.addGestureRecognizer(tapGestureRecognizer) } // MARK: - Actions @objc func authenticate(_ sender: UITapGestureRecognizer?) { if VENTouchLock.canUseTouchID() { showTouchID() } else { showPasscode(animated: true) } } }
42e48b39c70aa9742e8064b0855d76bd
33.428571
164
0.636929
false
false
false
false
MrPudin/Skeem
refs/heads/master
IOS/Prevoir/VoidDurationListVC.swift
mit
1
// // VoidDurationListVC.swift // Skeem // // Created by Zhu Zhan Yan on 2/11/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit class VoidDurationListVC: UITableViewController { //Links weak var DBC:SKMDataController! weak var SCH:SKMScheduler! weak var CFG:SKMConfig! //Data var arr_voidd:[SKMVoidDuration]! var utcell_id_voidd:String! var utcell_id_voidd_null:String! //UI Elements @IBOutlet weak var barbtn_edit: UIBarButtonItem! @IBOutlet weak var barbtn_add: UIBarButtonItem! //Data Functions /* * public func updateData() * - Updates data to reflect database */ public func updateData() { //Update Data self.DBC.updateVoidDuration() self.arr_voidd = self.DBC.sortedVoidDuration(sattr: SKMVoidDurationSort.begin) } /* * public func updateUI() * - Triggers a update to current data and UI update with that data */ public func updateUI() { //Update UI self.tableView.reloadData() } //Event Functions override func viewDidLoad() { //Init Links let appDelegate = (UIApplication.shared.delegate as! AppDelegate) self.DBC = appDelegate.DBC self.SCH = appDelegate.SCH self.CFG = appDelegate.CFG //Init Data self.utcell_id_voidd = "uitcell.list.voidd" self.utcell_id_voidd_null = "uitcell.list.voidd.null" self.arr_voidd = self.DBC.sortedVoidDuration(sattr: SKMVoidDurationSort.begin) super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { //Update Data & UI self.updateData() self.updateUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //UITableView Delegate/Data Source Functions override func numberOfSections(in tableView: UITableView) -> Int { let sections = 1 //Only one section return sections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //Prepare Data self.updateData() switch section { case 0: //First Section return self.arr_voidd.count default: abort() //Unhandled Section } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.arr_voidd.count > 0 { //Create/Update Table View Cell let cell = ((tableView.dequeueReusableCell(withIdentifier: self.utcell_id_voidd, for: indexPath)) as! VoidDurationListTBC) let voidd = self.arr_voidd[indexPath.row] //NOTE: Duration adjustment due to void duration preadjustment cell.updateUI(name: voidd.name, begin: voidd.begin, duration: voidd.duration + 1) return cell } else { //Empty Void Duration Cell let cell = tableView.dequeueReusableCell(withIdentifier: self.utcell_id_voidd_null, for: indexPath) return cell } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if self.arr_voidd.count <= 0 { return false //Cannot Edit Null Cell } else { return true } } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { switch indexPath.section { case 0: let voidd = self.DBC.sortedVoidDuration(sattr: SKMVoidDurationSort.begin)[indexPath.row] let rst = self.DBC.deleteVoidDuration(name: voidd.name) assert(rst) //Terminates Executable if delete fails default: abort() //Unhandled Section } //Update Data self.updateData() tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } else if editingStyle == UITableViewCellEditingStyle.insert { //Data Should be in databasel tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } //UI Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let sge_idf = segue.identifier { switch sge_idf { case "uisge.voidblock.add": let voiddeditvc = (segue.destination as! VoidDurationEditVC) let _ = voiddeditvc.view //Force View Load voiddeditvc.loadAddVoidDuration() case "uisge.voidblock.edit": let voiddeditvc = (segue.destination as! VoidDurationEditVC) let _ = voiddeditvc.view //Force View Load let voidd = self.arr_voidd[(self.tableView.indexPathForSelectedRow?.row)!] voiddeditvc.loadEditVoidDuration(voidd: voidd) default: abort() } } else { abort() } } @IBAction func unwind_voidDurationList(sge:UIStoryboardSegue) { self.updateUI() } }
7595fc9099bfe377f0ba3af716368eb2
29.531073
136
0.605477
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/OSX/AudioKit/Playgrounds/AudioKit for OSX.playground/Pages/Mixing Nodes.xcplaygroundpage/Contents.swift
mit
1
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Mixing Nodes //: ### So, what about connecting two nodes to output instead of having all operations sequential? To do that, you'll need a mixer. import XCPlayground import AudioKit //: This section prepares the players let bundle = NSBundle.mainBundle() let file1 = bundle.pathForResource("drumloop", ofType: "wav") let file2 = bundle.pathForResource("guitarloop", ofType: "wav") var player1 = AKAudioPlayer(file1!) player1.looping = true let player1Window = AKAudioPlayerWindow(player1, title: "Drums") var player2 = AKAudioPlayer(file2!) player2.looping = true let player2Window = AKAudioPlayerWindow(player2, title: "Guitar", xOffset: 640) //: Any number of inputs can be equally summed into one output let mixer = AKMixer(player1, player2) AudioKit.output = mixer AudioKit.start() let plotView = AKOutputWaveformPlot.createView() XCPlaygroundPage.currentPage.liveView = plotView XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
62bb7fe0487c86ca63aacbce14c9f24d
33.96875
131
0.748883
false
false
false
false
peferron/algo
refs/heads/master
EPI/Searching/Compute the real square root/swift/main.swift
mit
1
public func squareRoot(_ value: Float, tolerance: Float) -> Float { let toleranceSquared = tolerance * tolerance var (low, high) = value < 1 ? (value, 1) : (1, value) while true { let mid = low + (high - low) / 2 let midSquared = mid * mid if abs(midSquared - value) < toleranceSquared { return mid } if midSquared < value { low = mid } else { high = mid } } }
f089687717c6863ca051f86f2785af31
23.842105
67
0.504237
false
false
false
false
937447974/YJCocoa
refs/heads/master
YJCocoa/Classes/DeveloperTools/Timeline/YJTimeline.swift
mit
1
// // YJTimeline.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/6/18. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit /// 时间轴记录 @objcMembers public class YJTimeline: NSObject { static var log: String? static var time: CFAbsoluteTime = 0 /// 添加时间轴步骤 public static func add(step: String) { if self.log == nil { self.log = step } else { let time = String(format: " %.3f", CFAbsoluteTimeGetCurrent() - self.time) self.log = self.log! + time + "\n\t" + step } self.time = CFAbsoluteTimeGetCurrent() } /// 结束并打印日志 public static func end() { guard let log = self.log else { return } let time = String(format: " %.3f", CFAbsoluteTimeGetCurrent() - self.time) YJLogDebug(log + time) self.log = nil } }
d95afc1e5696dde5d946a0d985d93be2
21.97619
86
0.562694
false
false
false
false
zhangxigithub/ZXTools_Swift
refs/heads/master
Tools/UILabel+ZXTools.swift
apache-2.0
1
// // UILabel+MultipleColor.swift // xin // // Created by zhangxi on 15/7/25. // Copyright (c) 2015年 zhangxi. All rights reserved. // import UIKit public extension UILabel { public func setMultipleColorText(_ texts:Array<(color:UIColor,text:String)>) { var string = "" for text in texts { string = string + (text.text) } let aString = NSMutableAttributedString(string: string) var location = 0 for text in texts { let length = (text.text as NSString).length //aString.addAttribute(NSAttributedStringKey.foregroundColor , value: text.color, range: NSMakeRange(location,length)) location += length } self.attributedText = aString } }
50fef2d964d95f389f563dba08e47db4
22.970588
130
0.579141
false
false
false
false
kingiol/KDCycleBannerView-Swift
refs/heads/master
KDCycleBannerView/KDCycleBannerView.swift
mit
1
// // KDCycleBannerView.swift // KDCycleBannerView-Swift // // Created by Kingiol on 14-6-14. // Copyright (c) 2014年 Kingiol. All rights reserved. // import UIKit @objc protocol KDCycleBannerViewDatasource: NSObjectProtocol { func numberOfKDCycleBannerView(bannerView: KDCycleBannerView) -> Array<AnyObject>; func contentModeForImageIndex(index: Int) -> UIViewContentMode @optional func placeHolderImageOfZeroBanerView() -> UIImage @optional func placeHolderImageOfBannerView(bannerView: KDCycleBannerView, atIndex: Int) -> UIImage } @objc protocol KDCycleBannerViewDelegate: NSObjectProtocol { @optional func cycleBannerView(bannerView: KDCycleBannerView, didScrollToIndex index: Int) @optional func cycleBannerView(bannerView: KDCycleBannerView, didSelectedAtIndex index: Int) } class KDCycleBannerView: UIView, UIScrollViewDelegate, UIGestureRecognizerDelegate { @IBOutlet var datasource: KDCycleBannerViewDatasource! @IBOutlet var delegate: KDCycleBannerViewDelegate? var continuous: Bool = false // if YES, then bannerview will show like a carousel, default is NO var autoPlayTimeInterval: Int = 0 // if autoPlayTimeInterval more than 0, the bannerView will autoplay with autoPlayTimeInterval value space, default is 0 var scrollView: UIScrollView = UIScrollView() var scrollViewBounces: Bool = true var pageControl: UIPageControl = UIPageControl() var datasourceImages: Array<AnyObject> = Array() var currentSelectedPage: Int = 0 var completeBlock: (() -> ())? var autoPlayDelay: dispatch_time_t { let delay = Double(autoPlayTimeInterval) * Double(NSEC_PER_SEC) return dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) } init(frame: CGRect) { super.init(frame: frame) // Initialization code } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } func reloadDataWithCompleteBlock(block: () -> ()) { completeBlock = block setNeedsLayout() } func setCurrentPage(currentPage: Int, animated: Bool) { let page = min(datasourceImages.count - 1, max(0, currentPage)) setSwitchPage(page, animated: animated, withUserInterface: true) } override func layoutSubviews() { super.layoutSubviews() loadData() // progress autoPlayTimeInterval struct DISPATCH_ONE_STRUCT { static var token: dispatch_once_t = 0 } dispatch_once(&DISPATCH_ONE_STRUCT.token) { if self.autoPlayTimeInterval > 0 && self.continuous && self.datasourceImages.count > 3 { println("OKKKK"); dispatch_after(self.autoPlayDelay, dispatch_get_main_queue(), self.autoSwitchBanner) } } } override func didMoveToSuperview() { initialize() completeBlock?() } func initialize() { clipsToBounds = true initializeScrollView() initializePageControl() } func initializeScrollView() { scrollView = UIScrollView(frame: CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))); scrollView.delegate = self scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.autoresizingMask = autoresizingMask self.addSubview(scrollView) } func initializePageControl() { var pageControlFrame: CGRect = CGRect(x: 0, y: 0, width: CGRectGetWidth(scrollView.frame), height: 30) pageControl = UIPageControl(frame: pageControlFrame) pageControl.center = CGPoint(x: CGRectGetWidth(scrollView.frame) * 0.5, y: CGRectGetHeight(scrollView.frame) - 12) pageControl.userInteractionEnabled = false self.addSubview(pageControl) } func loadData() { datasourceImages = datasource.numberOfKDCycleBannerView(self) if datasourceImages.count == 0 { //显示默认页,无数据页面 if let image = datasource.placeHolderImageOfZeroBanerView?() { let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(scrollView.frame), height: CGRectGetHeight(scrollView.frame))) imageView.clipsToBounds = true imageView.contentMode = .ScaleAspectFill imageView.backgroundColor = UIColor.clearColor() imageView.image = image scrollView.addSubview(imageView) } return } pageControl.numberOfPages = datasourceImages.count pageControl.currentPage = 0 if continuous && datasourceImages.count > 1 { datasourceImages.insert(datasourceImages[datasourceImages.count - 1], atIndex: 0) datasourceImages.append(datasourceImages[1]) } let contentWidth = CGRectGetWidth(scrollView.frame) let contentHeight = CGRectGetHeight(scrollView.frame) scrollView.contentSize = CGSize(width: contentWidth * CGFloat(datasourceImages.count), height: contentHeight) for (index, obj: AnyObject) in enumerate(datasourceImages) { let imgRect = CGRectMake(contentWidth * CGFloat(index), 0, contentWidth, contentHeight) let imageView = UIImageView(frame: imgRect) imageView.backgroundColor = UIColor.clearColor() imageView.clipsToBounds = true imageView.contentMode = datasource.contentModeForImageIndex(index) if obj is UIImage { imageView.image = obj as UIImage }else if obj is String || obj is NSURL { let activityIndicatorView = UIActivityIndicatorView() activityIndicatorView.center = CGPointMake(CGRectGetWidth(scrollView.frame) * 0.5, CGRectGetHeight(scrollView.frame) * 0.5) activityIndicatorView.tag = 100 activityIndicatorView.activityIndicatorViewStyle = .WhiteLarge activityIndicatorView.startAnimating() imageView.addSubview(activityIndicatorView) imageView.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil) if let placeHolderImage = datasource.placeHolderImageOfBannerView?(self, atIndex: index) { imageView.setImageWithURL(obj is String ? NSURL(string: obj as String) : obj as NSURL, placeholderImage: placeHolderImage) }else { imageView.setImageWithURL(obj is String ? NSURL(string: obj as String) : obj as NSURL) } } scrollView.addSubview(imageView) } if continuous && datasourceImages.count > 1 { scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.frame), 0) } // single tap gesture recognizer let tapGestureRecognize = UITapGestureRecognizer(target: self, action: Selector("singleTapGestureRecognizer:")) // designated initializer) tapGestureRecognize.delegate = self tapGestureRecognize.numberOfTapsRequired = 1 scrollView.addGestureRecognizer(tapGestureRecognize) } func moveToTargetPosition(targetX: CGFloat, withAnimated animated: Bool) { scrollView.setContentOffset(CGPointMake(targetX, 0), animated: animated) } func setSwitchPage(switchPage: Int, animated: Bool, withUserInterface userInterface: Bool) { var page = -1 if userInterface { page = switchPage }else { currentSelectedPage++ page = currentSelectedPage % (continuous ? datasourceImages.count - 1 : datasourceImages.count) } if continuous { if datasourceImages.count > 1 { if page >= datasourceImages.count - 2 { page = datasourceImages.count - 3 currentSelectedPage = 0 moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page + 2), withAnimated: animated) }else { moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page + 1), withAnimated: animated) } }else { moveToTargetPosition(0, withAnimated: animated) } }else { moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page), withAnimated: animated) } scrollViewDidScroll(scrollView) } func autoSwitchBanner() { NSObject.cancelPreviousPerformRequestsWithTarget(self) setSwitchPage(-1, animated: true, withUserInterface: false) dispatch_after(autoPlayDelay, dispatch_get_main_queue(), autoSwitchBanner) } //pragma mark - KVO override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer) { if keyPath == "image" { let imageView = object as UIImageView let activityIndicatorView: UIActivityIndicatorView = imageView.viewWithTag(100) as UIActivityIndicatorView activityIndicatorView.removeFromSuperview() imageView.removeObserver(self, forKeyPath: "image") } } //pragma mark - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView!) { var targetX: CGFloat = scrollView.contentOffset.x var item_width = CGRectGetWidth(scrollView.frame) if continuous && datasourceImages.count >= 3 { if targetX >= item_width * CGFloat(datasourceImages.count - 1) { targetX = item_width scrollView.contentOffset = CGPointMake(targetX, 0) }else if targetX <= 0 { targetX = item_width * CGFloat(datasourceImages.count - 2) scrollView.contentOffset = CGPointMake(targetX, 0) } } var page: Int = Int(scrollView.contentOffset.x + item_width * 0.5) / Int(item_width) if continuous && datasourceImages.count > 1 { page-- if page >= pageControl.numberOfPages { page = 0 }else if (page < 0) { page = pageControl.numberOfPages - 1 } } currentSelectedPage = page if page != pageControl.currentPage { delegate?.cycleBannerView?(self, didScrollToIndex: page) } pageControl.currentPage = page } func singleTapGestureRecognizer(tapGesture: UITapGestureRecognizer) { let page = Int(scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame)) delegate?.cycleBannerView?(self, didSelectedAtIndex: page) } }
248fdf63a46a2d5d94ddaa805b8bdf6f
39.450549
158
0.638323
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-01
refs/heads/master
ReadingListModel/ReadingList.swift
mit
3
// // Copyright (C) 2014 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation let BooksKey = "books" protocol PropertyKeys { var all: [String] { get } } open class ReadingList: ModelObject { open var title = "" open var books = [Book]() open override var description: String { var s = "Title: \(title)\nCount: \(books.count)\nBooks:\n------\n" for (index, book) in books.enumerated() { s += "\(index + 1). \(book)\n" } return s } override class func keys() -> [String] { return [TitleKey, BooksKey] } open override func setValue(_ value: Any?, forKey key: String) { var mappedValue: Any? if key == BooksKey, let dicts = value as? [[String: Any]] { mappedValue = dicts.map { Book(dictionary: $0) } } super.setValue(mappedValue ?? value, forKey: key) } open override func dictionaryRepresentation() -> [String: Any] { var dict = super.dictionaryRepresentation() if let books = dict[BooksKey] as? [ModelObject] { dict[BooksKey] = books.map { $0.dictionaryRepresentation() } } return dict } }
67fdbba648712c2452d79e68b3add3ed
24.019231
74
0.56495
false
false
false
false
trungp/MulticastDelegate
refs/heads/master
MulticastDelegate/MulticastDelegate.swift
mit
1
// // MulticastCallback.swift // MulticastDelegate // // Created by TrungP1 on 4/7/16. // Copyright © 2016 TrungP1. All rights reserved. // /** * It provides a way for multiple delegates to be called, each on its own delegate queue. * There are some versions for Objective-C on github. And this is the version for Swift. */ import Foundation // Operator to compare two weakNodes func ==(lhs: WeakNode, rhs: WeakNode) -> Bool { return lhs.callback === rhs.callback } infix operator ~> {} // Operator to perform closure on delegate func ~> <T> (inout left: MulticastDelegate<T>?, right: ((T) -> Void)?) { if let left = left, right = right { left.performClosure(right) } } infix operator += {} // Operator to add delegate to multicast object func += <T> (inout left: MulticastDelegate<T>?, right: T?) { if let left = left, right = right { left.addCallback(right) } } func += <T> (inout left: MulticastDelegate<T>?, right: (T?, dispatch_queue_t?)?) { if let left = left, right = right { left.addCallback(right.0, queue: right.1) } } // Operator to remove delegate from multicast object func -= <T> (inout left: MulticastDelegate<T>?, right: T?) { if let left = left, right = right { left.removeCallback(right) } } // This class provide the way to perform selector or notify to multiple object. // Basically, it works like observer pattern, send message to all observer which registered with the multicast object. // The multicast object hold the observer inside as weak storage so make sure you are not lose the object without any reason. public class MulticastDelegate<T>: NSObject { private var nodes: [WeakNode]? public override init() { super.init() nodes = [WeakNode]() } /** Ask to know number of nodes or delegates are in multicast object whhich are ready to perform selector. - Returns Int: Number of delegates in multicast object. */ public func numberOfNodes() -> Int { return nodes?.count ?? 0 } /** Add callback to perform selector on later. - Parameter callback: The callback to perform selector in the future. - Parameter queue: The queue to perform the callback on. Default is main queue */ public func addCallback(callback: T?, queue: dispatch_queue_t? = nil) { // Default is main queue let queue: dispatch_queue_t = { guard let q = queue else { return dispatch_get_main_queue() } return q }() if var nodes = nodes, let callback = callback { let node = WeakNode(callback as? AnyObject, queue: queue) nodes.append(node) self.nodes = nodes } } public func removeCallback(callback: T?) { if let nodes = nodes, let cb1 = callback as? AnyObject { self.nodes = nodes.filter { node in if let cb = node.callback where cb === cb1 { return false } return true } } } func performClosure(closure: ((T) -> Void)?) { if let nodes = nodes, closure = closure { nodes.forEach { node in if let cb = node.callback as? T { let queue: dispatch_queue_t = { guard let q = node.queue else { return dispatch_get_main_queue() } return q }() dispatch_async(queue, { closure(cb) }) } } } } }
c11222fdc562306d980064ba40d37916
29.831933
125
0.578904
false
false
false
false
V3ronique/TailBook
refs/heads/master
TailBook/TailBook/UpdateDataSource.swift
mit
1
// // UpdateDataSource.swift // TailBook // // Created by Roni Beberoni on 2/5/16. // Copyright © 2016 Veronica. All rights reserved. // import Foundation class UpdateDataSource { var updates = [Update]() init() { updates = [] let u1 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Me", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u1) let u2 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Johny", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u2) let u3 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Meena", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u3) let u4 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Meera", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u4) let u5 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "You", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u5) let u6 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Lovely", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u6) let u7 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Me", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u7) let u8 = Update(imageId : "https://i.ytimg.com/vi/KY4IzMcjX3Y/maxresdefault.jpg", username: "Me", actionStr: "added", objectStr: "something", likes: 3, comments: ["Nice", "Sure", "Blah", "Duh"]) updates.append(u8) } func getupdates()->[Update] { return updates } }
1ab58484b77947503008db19ca5058e6
59.416667
206
0.634943
false
false
false
false
summertian4/Lotusoot
refs/heads/master
Lotusoot/LotusootCoordinator.swift
mit
1
// // LotusootCoordinator.swift // LPDBusiness // // Created by 周凌宇 on 2017/4/21. // Copyright © 2017年 LPD. All rights reserved. // import UIKit @objc public class LotusootCoordinator: NSObject { @objc public static let sharedInstance = LotusootCoordinator() // lotus(协议) 和 lotusoot(实现) 表 @objc var lotusootMap: Dictionary = Dictionary<String, Any>() @objc private override init() { } /// 注册 Lotus 和 Lotusoot /// /// - Parameters: /// - lotusoot: lotusoot 对象。自动注册的 lotusoot 都必须是集成 NSObject,手动注册不做限制 /// - lotusName: lotus 协议名 @objc public static func register(lotusoot: Any, lotusName: String) { sharedInstance.lotusootMap.updateValue(lotusoot, forKey: lotusName) } /// 通过 lotus 名称 获取 lotusoot 实例 /// /// - Parameter lotus: lotus 协议名 /// - Returns: lotusoot 对象 @objc public static func lotusoot(lotus: String) -> Any? { return sharedInstance.lotusootMap[lotus] } /// 注册所有的 lotusoot /// /// - Parameter serviceMap: 自定义传入的字典 @objc public static func registerAll(serviceMap: Dictionary<String, String>) { for (lotus, lotusootName) in serviceMap { let classStringName = lotusootName let classType = NSClassFromString(classStringName) as? NSObject.Type if let type = classType { let lotusoot = type.init() register(lotusoot: lotusoot, lotusName: lotus) } } } /// 注册所有的 lotusoot /// 使用默认生成的 Lotusoot.plist @objc public static func registerAll() { let lotusPlistPath = Bundle.main.path(forResource: "Lotusoot", ofType: "plist") if let lotusPlistPath = lotusPlistPath { let map = NSDictionary(contentsOfFile: lotusPlistPath) registerAll(serviceMap: map as! Dictionary<String, String>) } } }
fa72d35a86aa558e7e8caaf0140500f5
29.935484
87
0.615746
false
false
false
false
D8Ge/Jchat
refs/heads/master
Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/ProtobufExtensions.swift
mit
1
// ProtobufRuntime/Sources/Protobuf/ProtobufExtensions.swift - Extension support // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// A 'Message Extension' is an immutable class object that describes /// a particular extension field, including string and number /// identifiers, serialization details, and the identity of the /// message that is being extended. /// // ----------------------------------------------------------------------------- import Swift /// Note that the base ProtobufMessageExtension class has no generic /// pieces, which allows us to construct dictionaries of /// ProtobufMessageExtension-typed objects. public class ProtobufMessageExtension { public let protoFieldNumber: Int public let protoFieldName: String public let jsonFieldName: String public let swiftFieldName: String public let messageType: ProtobufMessage.Type init(protoFieldNumber: Int, protoFieldName: String, jsonFieldName: String, swiftFieldName: String, messageType: ProtobufMessage.Type) { self.protoFieldNumber = protoFieldNumber self.protoFieldName = protoFieldName self.jsonFieldName = jsonFieldName self.swiftFieldName = swiftFieldName self.messageType = messageType } public func newField() -> ProtobufExtensionField { fatalError("newField() -> ProtobufExtensionField must always be overridden.") } } public func ==(lhs: ProtobufMessageExtension, rhs: ProtobufMessageExtension) -> Bool { return lhs.protoFieldNumber == rhs.protoFieldNumber } /// A "Generic Message Extension" augments the base Extension type /// with generic information about the type of the message being /// extended. These generic constrints enable compile-time checks on /// compatibility. public class ProtobufGenericMessageExtension<FieldType: ProtobufTypedExtensionField, MessageType: ProtobufMessage>: ProtobufMessageExtension { public init(protoFieldNumber: Int, protoFieldName: String, jsonFieldName: String, swiftFieldName: String, defaultValue: FieldType.ValueType) { self.defaultValue = defaultValue super.init(protoFieldNumber: protoFieldNumber, protoFieldName: protoFieldName, jsonFieldName: jsonFieldName, swiftFieldName: swiftFieldName, messageType: MessageType.self) } public let defaultValue: FieldType.ValueType public func set(value: FieldType.ValueType) -> ProtobufExtensionField { var f = FieldType(protobufExtension: self) f.value = value return f } override public func newField() -> ProtobufExtensionField { return FieldType(protobufExtension: self) } } // Messages that support extensions implement this protocol public protocol ProtobufExtensibleMessage: ProtobufMessage { mutating func setExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, Self>, value: F.ValueType) mutating func getExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, Self>) -> F.ValueType } // Backwards compatibility shim: Remove in August 2016 public typealias ProtobufExtensibleMessageType = ProtobufExtensibleMessage // Common support for storage classes to handle extension fields public protocol ProtobufExtensibleMessageStorage: class { associatedtype ProtobufExtendedMessage: ProtobufMessage var extensionFieldValues: ProtobufExtensionFieldValueSet {get set} func setExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, ProtobufExtendedMessage>, value: F.ValueType) func getExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, ProtobufExtendedMessage>) -> F.ValueType } // Backwards compatibility shim: Remove in August 2016 public typealias ProtobufExtensibleMessageStorageType = ProtobufExtensibleMessageStorage public extension ProtobufExtensibleMessageStorage { public func setExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, ProtobufExtendedMessage>, value: F.ValueType) { extensionFieldValues[ext.protoFieldNumber] = ext.set(value: value) } public func getExtensionValue<F: ProtobufExtensionField>(ext: ProtobufGenericMessageExtension<F, ProtobufExtendedMessage>) -> F.ValueType { if let fieldValue = extensionFieldValues[ext.protoFieldNumber] as? F { return fieldValue.value } return ext.defaultValue } } /// /// A set of extensions that can be passed into deserializers /// to provide details of the particular extensions that should /// be recognized. /// // TODO: Make this more Set-like // Note: The generated code only relies on ExpressibleByArrayLiteral public struct ProtobufExtensionSet: CustomDebugStringConvertible, ExpressibleByArrayLiteral { public typealias Element = ProtobufMessageExtension // Since type objects aren't Hashable, we can't do much better than this... private var fields = [Int: Array<(ProtobufMessage.Type, ProtobufMessageExtension)>]() public init() {} public init(arrayLiteral: Element...) { insert(contentsOf: arrayLiteral) } public subscript(messageType: ProtobufMessage.Type, protoFieldNumber: Int) -> ProtobufMessageExtension? { get { if let l = fields[protoFieldNumber] { for (t, e) in l { if t == messageType { return e } } } return nil } set(newValue) { if let l = fields[protoFieldNumber] { var newL = l.flatMap { pair -> (ProtobufMessage.Type, ProtobufMessageExtension)? in if pair.0 == messageType { return nil } else { return pair } } if let newValue = newValue { newL.append((messageType, newValue)) fields[protoFieldNumber] = newL } fields[protoFieldNumber] = newL } else if let newValue = newValue { fields[protoFieldNumber] = [(messageType, newValue)] } } } public func fieldNumberForJson(messageType: ProtobufJSONMessageBase.Type, jsonFieldName: String) -> Int? { // TODO: Make this faster... for (_, list) in fields { for (_, e) in list { if e.jsonFieldName == jsonFieldName { return e.protoFieldNumber } } } return nil } public mutating func insert(_ e: Element) { self[e.messageType, e.protoFieldNumber] = e } public mutating func insert(contentsOf: [Element]) { for e in contentsOf { insert(e) } } public var debugDescription: String { var names = [String]() for (_, list) in fields { for (_, e) in list { names.append("\(e.protoFieldName)(\(e.protoFieldNumber))") } } let d = names.joined(separator: ",") return "ProtobufExtensionSet(\(d))" } public mutating func union(_ other: ProtobufExtensionSet) -> ProtobufExtensionSet { var out = self for (_, list) in other.fields { for (_, e) in list { out.insert(e) } } return out } } /// A collection of extension field values on a particular object. /// This is only used within messages to manage the values of extension fields; /// it does not need to be very sophisticated. public struct ProtobufExtensionFieldValueSet: Equatable, Sequence { public typealias Iterator = Dictionary<Int, ProtobufExtensionField>.Iterator fileprivate var values = [Int : ProtobufExtensionField]() public init() {} public func makeIterator() -> Iterator { return values.makeIterator() } public var hashValue: Int { var hash: Int = 0 for i in values.keys.sorted() { hash = (hash &* 16777619) ^ values[i]!.hashValue } return hash } public func traverse(visitor: inout ProtobufVisitor, start: Int, end: Int) throws { let validIndexes = values.keys.filter {$0 >= start && $0 < end} for i in validIndexes.sorted() { let value = values[i]! try value.traverse(visitor: &visitor) } } public subscript(index: Int) -> ProtobufExtensionField? { get {return values[index]} set(newValue) {values[index] = newValue} } } public func ==(lhs: ProtobufExtensionFieldValueSet, rhs: ProtobufExtensionFieldValueSet) -> Bool { for (index, l) in lhs.values { if let r = rhs.values[index] { if type(of: l) != type(of: r) { return false } if !l.isEqual(other: r) { return false } } else { return false } } for (index, _) in rhs.values { if lhs.values[index] == nil { return false } } return true }
a3453627aa37675891257b15973fde0f
37.434959
179
0.653834
false
false
false
false
EaglesoftZJ/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthWelcomeController.swift
agpl-3.0
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit open class AAWelcomeController: AAViewController { let bgImage: UIImageView = UIImageView() let logoView: UIImageView = UIImageView() let appNameLabel: UILabel = UILabel() let someInfoLabel: UILabel = UILabel() let signupButton: UIButton = UIButton() let signinButton: UIButton = UIButton() var size: CGSize = CGSize() var logoViewVerticalGap: CGFloat = CGFloat() public override init() { super.init(nibName: nil, bundle: nil) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func loadView() { super.loadView() self.view.backgroundColor = ActorSDK.sharedActor().style.welcomeBgColor self.bgImage.image = ActorSDK.sharedActor().style.welcomeBgImage self.bgImage.isHidden = ActorSDK.sharedActor().style.welcomeBgImage == nil self.bgImage.contentMode = .scaleAspectFill self.logoView.image = ActorSDK.sharedActor().style.welcomeLogo self.size = ActorSDK.sharedActor().style.welcomeLogoSize self.logoViewVerticalGap = ActorSDK.sharedActor().style.logoViewVerticalGap appNameLabel.text = AALocalized("WelcomeTitle").replace("{app_name}", dest: ActorSDK.sharedActor().appName) appNameLabel.textAlignment = .center appNameLabel.backgroundColor = UIColor.clear appNameLabel.font = UIFont.mediumSystemFontOfSize(24) appNameLabel.textColor = ActorSDK.sharedActor().style.welcomeTitleColor someInfoLabel.text = AALocalized("WelcomeTagline") someInfoLabel.textAlignment = .center someInfoLabel.backgroundColor = UIColor.clear someInfoLabel.font = UIFont.systemFont(ofSize: 16) someInfoLabel.numberOfLines = 2 someInfoLabel.textColor = ActorSDK.sharedActor().style.welcomeTaglineColor signupButton.setTitle(AALocalized("WelcomeSignUp"), for: UIControlState()) signupButton.titleLabel?.font = UIFont.mediumSystemFontOfSize(17) signupButton.setTitleColor(ActorSDK.sharedActor().style.welcomeSignupTextColor, for: UIControlState()) signupButton.setBackgroundImage(Imaging.roundedImage(ActorSDK.sharedActor().style.welcomeSignupBgColor, radius: 22), for: UIControlState()) signupButton.setBackgroundImage(Imaging.roundedImage(ActorSDK.sharedActor().style.welcomeSignupBgColor.alpha(0.7), radius: 22), for: .highlighted) signupButton.addTarget(self, action: #selector(AAWelcomeController.signupAction), for: UIControlEvents.touchUpInside) signinButton.setTitle(AALocalized("WelcomeLogIn"), for: UIControlState()) signinButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) signinButton.setTitleColor(ActorSDK.sharedActor().style.welcomeLoginTextColor, for: UIControlState()) signinButton.setTitleColor(ActorSDK.sharedActor().style.welcomeLoginTextColor.alpha(0.7), for: .highlighted) signinButton.addTarget(self, action: #selector(AAWelcomeController.signInAction), for: UIControlEvents.touchUpInside) self.view.addSubview(self.bgImage) self.view.addSubview(self.logoView) self.view.addSubview(self.appNameLabel) self.view.addSubview(self.someInfoLabel) //self.view.addSubview(self.signupButton) self.view.addSubview(self.signinButton) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if AADevice.isiPhone4 { logoView.frame = CGRect(x: (view.width - size.width) / 2, y: 90, width: size.width, height: size.height) appNameLabel.frame = CGRect(x: (view.width - 300) / 2, y: logoView.bottom + 30, width: 300, height: 29) someInfoLabel.frame = CGRect(x: (view.width - 300) / 2, y: appNameLabel.bottom + 8, width: 300, height: 56) signupButton.frame = CGRect(x: (view.width - 136) / 2, y: view.height - 44 - 80, width: 136, height: 44) signinButton.frame = CGRect(x: (view.width - 136) / 2, y: view.height - 44 - 25, width: 136, height: 44) } else { logoView.frame = CGRect(x: (view.width - size.width) / 2, y: logoViewVerticalGap, width: size.width, height: size.height) appNameLabel.frame = CGRect(x: (view.width - 300) / 2, y: logoView.bottom + 35, width: 300, height: 29) someInfoLabel.frame = CGRect(x: (view.width - 300) / 2, y: appNameLabel.bottom + 8, width: 300, height: 56) signupButton.frame = CGRect(x: (view.width - 136) / 2, y: view.height - 44 - 90, width: 136, height: 44) signinButton.frame = CGRect(x: (view.width - 136) / 2, y: view.height - 44 - 35, width: 136, height: 44) } self.bgImage.frame = view.bounds } open func signupAction() { // TODO: Remove BG after auth? UIApplication.shared.keyWindow?.backgroundColor = ActorSDK.sharedActor().style.welcomeBgColor self.presentElegantViewController(AAAuthNavigationController(rootViewController: AAAuthNameViewController())) } open func signInAction() {//登录 // TODO: Remove BG after auth? UIApplication.shared.keyWindow?.backgroundColor = ActorSDK.sharedActor().style.welcomeBgColor self.presentElegantViewController(AAAuthNavigationController(rootViewController: LoginViewController())) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // TODO: Fix after cancel? UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) } }
b69e9798fd967c133a10bb64b520ce12
50.45614
154
0.670303
false
false
false
false
Quaggie/Quaggify
refs/heads/master
Quaggify/TrackViewController.swift
mit
1
// // TrackViewController.swift // Quaggify // // Created by Jonathan Bijos on 05/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class TrackViewController: ViewController { var track: Track? { didSet { guard let track = track else { return } if let name = track.name { titleLabel.text = name } if let artists = track.artists { let names = artists.map { $0.name ?? "Uknown Artist" }.joined(separator: ", ") subTitleLabel.text = names navigationItem.title = names } if let smallerImage = track.album?.images?[safe: 1], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) { imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))]) } else if let smallerImage = track.album?.images?[safe: 0], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) { imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))]) } else { imageView.image = #imageLiteral(resourceName: "placeholder") } } } // MARK: Views var titleLabel: UILabel = { let label = UILabel() label.font = Font.montSerratBold(size: 20) label.textColor = ColorPalette.white label.textAlignment = .center return label }() var subTitleLabel: UILabel = { let label = UILabel() label.font = Font.montSerratRegular(size: 18) label.textColor = ColorPalette.lightGray label.textAlignment = .center return label }() lazy var addToPlaylistButton: UIButton = { let btn = UIButton(type: .system) let img = #imageLiteral(resourceName: "icon_add_playlist").withRenderingMode(.alwaysTemplate) btn.tintColor = ColorPalette.white btn.titleLabel?.font = Font.montSerratRegular(size: 30) btn.setTitle("Add to Playlist", for: .normal) btn.addTarget(self, action: #selector(addToPlaylist), for: .touchUpInside) return btn }() var imageView: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFit iv.clipsToBounds = true return iv }() let stackView: UIStackView = { let sv = UIStackView() sv.alignment = .fill sv.axis = .vertical sv.distribution = .fillEqually sv.backgroundColor = .clear sv.spacing = 8 return sv }() let containerView: UIView = { let v = UIView() v.backgroundColor = .clear return v }() override func viewDidLoad() { super.viewDidLoad() setupViews() fetchTrack() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() switch UIApplication.shared.statusBarOrientation { case .portrait: fallthrough case .portraitUpsideDown: fallthrough case .unknown: setPortraitLayout() break case .landscapeLeft: fallthrough case .landscapeRight: setLandscapeLayout() break } view.layoutIfNeeded() } // MARK: Layout override func setupViews() { super.setupViews() view.addSubview(stackView) view.addSubview(imageView) view.addSubview(containerView) view.addSubview(titleLabel) view.addSubview(subTitleLabel) view.addSubview(addToPlaylistButton) view.backgroundColor = ColorPalette.black stackView.addArrangedSubview(imageView) stackView.addArrangedSubview(containerView) stackView.anchor(topLayoutGuide.bottomAnchor, left: view.leftAnchor, bottom: bottomLayoutGuide.topAnchor, right: view.rightAnchor, topConstant: 8, leftConstant: 8, bottomConstant: 8, rightConstant: 8, widthConstant: 0, heightConstant: 0) titleLabel.anchor(containerView.topAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 24) subTitleLabel.anchor(titleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 24) addToPlaylistButton.anchor(subTitleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: containerView.bottomAnchor, right: containerView.rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) } } // MARK: Layout extension TrackViewController { func setPortraitLayout () { stackView.axis = .vertical } func setLandscapeLayout () { stackView.axis = .horizontal } } // MARK: Actions extension TrackViewController { @objc func addToPlaylist () { let trackOptionsVC = TrackOptionsViewController() trackOptionsVC.track = track let trackOptionsNav = NavigationController(rootViewController: trackOptionsVC) trackOptionsNav.modalPresentationStyle = .overCurrentContext tabBarController?.present(trackOptionsNav, animated: true, completion: nil) } func fetchTrack () { API.fetchTrack(track: track) { [weak self] (trackResponse, error) in guard let strongSelf = self else { return } if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let trackResponse = trackResponse { strongSelf.track = trackResponse } } } }
7c47e2998ac7224af0f010a9cb08f7c9
28.752688
267
0.687568
false
false
false
false
LordBonny/project-iOSRTCApp
refs/heads/master
plugins/cordova-plugin-iosrtc/src/PluginMediaStreamTrack.swift
agpl-3.0
8
import Foundation class PluginMediaStreamTrack : NSObject, RTCMediaStreamTrackDelegate { var rtcMediaStreamTrack: RTCMediaStreamTrack var id: String var kind: String var eventListener: ((data: NSDictionary) -> Void)? var eventListenerForEnded: (() -> Void)? var lostStates = Array<String>() init(rtcMediaStreamTrack: RTCMediaStreamTrack) { NSLog("PluginMediaStreamTrack#init()") self.rtcMediaStreamTrack = rtcMediaStreamTrack self.id = rtcMediaStreamTrack.label // NOTE: No "id" property provided. self.kind = rtcMediaStreamTrack.kind } func run() { NSLog("PluginMediaStreamTrack#run()") self.rtcMediaStreamTrack.delegate = self } func getJSON() -> NSDictionary { return [ "id": self.id, "kind": self.kind, "label": self.rtcMediaStreamTrack.label, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false, "readyState": PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().value] as String! ] } func setListener( eventListener: (data: NSDictionary) -> Void, eventListenerForEnded: () -> Void ) { NSLog("PluginMediaStreamTrack#setListener()") self.eventListener = eventListener self.eventListenerForEnded = eventListenerForEnded for readyState in self.lostStates { self.eventListener!(data: [ "type": "statechange", "readyState": readyState, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false ]) if readyState == "ended" { self.eventListenerForEnded!() } } self.lostStates.removeAll() } func setEnabled(value: Bool) { NSLog("PluginMediaStreamTrack#setEnabled() [value:\(value)]") self.rtcMediaStreamTrack.setEnabled(value) } func stop() { NSLog("PluginMediaStreamTrack#stop()") self.rtcMediaStreamTrack.setState(RTCTrackStateEnded) } /** * Methods inherited from RTCMediaStreamTrackDelegate. */ func mediaStreamTrackDidChange(rtcMediaStreamTrack: RTCMediaStreamTrack!) { let state_str = PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().value] as String! NSLog("PluginMediaStreamTrack | state changed [state:\(state_str), enabled:\(self.rtcMediaStreamTrack.isEnabled() ? true : false)]") if self.eventListener != nil { self.eventListener!(data: [ "type": "statechange", "readyState": state_str, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false ]) if self.rtcMediaStreamTrack.state().value == RTCTrackStateEnded.value { self.eventListenerForEnded!() } } else { // It may happen that the eventListener is not yet set, so store the lost states. self.lostStates.append(state_str) } } }
798a6ad3713741bed03ece0fbf1bce4f
24.572816
134
0.722855
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/NUX/SignupEpilogueTableViewController.swift
gpl-2.0
1
import UIKit import WordPressAuthenticator protocol SignupEpilogueTableViewControllerDelegate { func displayNameUpdated(newDisplayName: String) func displayNameAutoGenerated(newDisplayName: String) func passwordUpdated(newPassword: String) func usernameTapped(userInfo: LoginEpilogueUserInfo?) } /// Data source to get the temporary user info, not yet saved in the user account. /// protocol SignupEpilogueTableViewControllerDataSource { var customDisplayName: String? { get } var password: String? { get } var username: String? { get } } class SignupEpilogueTableViewController: UITableViewController, EpilogueUserInfoCellViewControllerProvider { // MARK: - Properties open var dataSource: SignupEpilogueTableViewControllerDataSource? open var delegate: SignupEpilogueTableViewControllerDelegate? open var credentials: AuthenticatorCredentials? open var socialService: SocialService? private var epilogueUserInfo: LoginEpilogueUserInfo? private var userInfoCell: EpilogueUserInfoCell? private var showPassword: Bool = true private var reloaded: Bool = false // MARK: - View override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .basicBackground } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) getUserInfo() configureTable() if reloaded { tableView.reloadData() } reloaded = true } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return Constants.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard section != TableSections.userInfo else { return Constants.userInfoRows } return showPassword ? Constants.allAccountRows : Constants.noPasswordRows } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // Don't show section header for User Info guard section != TableSections.userInfo, let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: CellIdentifiers.sectionHeaderFooter) as? EpilogueSectionHeaderFooter else { return nil } cell.titleLabel?.text = NSLocalizedString("Account Details", comment: "Header for account details, shown after signing up.").localizedUppercase cell.titleLabel?.accessibilityIdentifier = "New Account Header" cell.accessibilityLabel = cell.titleLabel?.text return cell } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard section != TableSections.userInfo, showPassword, let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: CellIdentifiers.sectionHeaderFooter) as? EpilogueSectionHeaderFooter else { return nil } cell.titleLabel?.numberOfLines = 0 cell.topConstraint.constant = Constants.footerTopMargin cell.titleLabel?.text = NSLocalizedString("You can always log in with a link like the one you just used, but you can also set up a password if you prefer.", comment: "Information shown below the optional password field after new account creation.") cell.accessibilityLabel = cell.titleLabel?.text return cell } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // User Info Row if indexPath.section == TableSections.userInfo { guard let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.epilogueUserInfoCell) as? EpilogueUserInfoCell else { return UITableViewCell() } if let epilogueUserInfo = epilogueUserInfo { cell.configure(userInfo: epilogueUserInfo, showEmail: true, allowGravatarUploads: true) } cell.viewControllerProvider = self userInfoCell = cell return cell } // Account Details Rows guard let cellType = EpilogueCellType(rawValue: indexPath.row) else { return UITableViewCell() } return getEpilogueCellFor(cellType: cellType) } override func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return Constants.headerFooterHeight } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == TableSections.userInfo ? 0 : UITableView.automaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { return Constants.headerFooterHeight } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard section != TableSections.userInfo, showPassword else { return 0 } return UITableView.automaticDimension } } // MARK: - Private Extension private extension SignupEpilogueTableViewController { func configureTable() { let headerFooterNib = UINib(nibName: CellNibNames.sectionHeaderFooter, bundle: nil) tableView.register(headerFooterNib, forHeaderFooterViewReuseIdentifier: CellIdentifiers.sectionHeaderFooter) let cellNib = UINib(nibName: CellNibNames.signupEpilogueCell, bundle: nil) tableView.register(cellNib, forCellReuseIdentifier: CellIdentifiers.signupEpilogueCell) let userInfoNib = UINib(nibName: CellNibNames.epilogueUserInfoCell, bundle: nil) tableView.register(userInfoNib, forCellReuseIdentifier: CellIdentifiers.epilogueUserInfoCell) WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.backgroundColor = .basicBackground // remove empty cells tableView.tableFooterView = UIView() } func getUserInfo() { let service = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext) guard let account = service.defaultWordPressComAccount() else { return } var userInfo = LoginEpilogueUserInfo(account: account) if let socialservice = socialService { showPassword = false userInfo.update(with: socialservice) } else { if let customDisplayName = dataSource?.customDisplayName { userInfo.fullName = customDisplayName } else { let autoDisplayName = generateDisplayName(from: userInfo.email) userInfo.fullName = autoDisplayName delegate?.displayNameAutoGenerated(newDisplayName: autoDisplayName) } } epilogueUserInfo = userInfo } func generateDisplayName(from rawEmail: String) -> String { // step 1: lower case let email = rawEmail.lowercased() // step 2: remove the @ and everything after let localPart = email.split(separator: "@")[0] // step 3: remove all non-alpha characters let localCleaned = localPart.replacingOccurrences(of: "[^A-Za-z/.]", with: "", options: .regularExpression) // step 4: turn periods into spaces let nameLowercased = localCleaned.replacingOccurrences(of: ".", with: " ") // step 5: capitalize let autoDisplayName = nameLowercased.capitalized return autoDisplayName } func getEpilogueCellFor(cellType: EpilogueCellType) -> SignupEpilogueCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.signupEpilogueCell) as? SignupEpilogueCell else { return SignupEpilogueCell() } switch cellType { case .displayName: cell.configureCell(forType: .displayName, labelText: NSLocalizedString("Display Name", comment: "Display Name label text."), fieldValue: dataSource?.customDisplayName ?? epilogueUserInfo?.fullName) case .username: cell.configureCell(forType: .username, labelText: NSLocalizedString("Username", comment: "Username label text."), fieldValue: dataSource?.username ?? epilogueUserInfo?.username) case .password: cell.configureCell(forType: .password, fieldValue: dataSource?.password, fieldPlaceholder: NSLocalizedString("Password (optional)", comment: "Password field placeholder text")) } cell.delegate = self return cell } struct Constants { static let numberOfSections = 2 static let userInfoRows = 1 static let noPasswordRows = 2 static let allAccountRows = 3 static let headerFooterHeight: CGFloat = 50 static let footerTrailingMargin: CGFloat = 16 static let footerTopMargin: CGFloat = 8 } struct TableSections { static let userInfo = 0 } struct CellIdentifiers { static let sectionHeaderFooter = "SectionHeaderFooter" static let signupEpilogueCell = "SignupEpilogueCell" static let epilogueUserInfoCell = "userInfo" } struct CellNibNames { static let sectionHeaderFooter = "EpilogueSectionHeaderFooter" static let signupEpilogueCell = "SignupEpilogueCell" static let epilogueUserInfoCell = "EpilogueUserInfoCell" } } // MARK: - SignupEpilogueCellDelegate extension SignupEpilogueTableViewController: SignupEpilogueCellDelegate { func updated(value: String, forType: EpilogueCellType) { switch forType { case .displayName: delegate?.displayNameUpdated(newDisplayName: value) case .password: delegate?.passwordUpdated(newPassword: value) default: break } } func changed(value: String, forType: EpilogueCellType) { if forType == .displayName { userInfoCell?.fullNameLabel?.text = value delegate?.displayNameUpdated(newDisplayName: value) } else if forType == .password { delegate?.passwordUpdated(newPassword: value) } } func usernameSelected() { delegate?.usernameTapped(userInfo: epilogueUserInfo) } }
38d009f3d811982c9f4e104c4bf1a28e
36.351064
256
0.6773
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/Interpreter/SDK/objc_swift_getObjectType.swift
apache-2.0
16
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation protocol P: class { } class AbstractP: P { } class DelegatedP<D: P>: AbstractP { init(_ d: D) { } } class AnyP: DelegatedP<AbstractP> { init<D: P>(_ d: D) { super.init(DelegatedP<D>(d)) } } extension P { var anyP: AnyP { return AnyP(self) } } // SR-4363 // Test several paths through swift_getObjectType() // instance of a Swift class that conforms to P class O: NSObject, P { } var o = O() let obase: NSObject = o print(String(cString: object_getClassName(o))) _ = (o as P).anyP _ = (obase as! P).anyP // CHECK: main.O // ... and KVO's artificial subclass thereof o.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil) print(String(cString: object_getClassName(o))) _ = (o as P).anyP _ = (obase as! P).anyP // CHECK-NEXT: NSKVONotifying_main.O // instance of an ObjC class that conforms to P extension NSLock: P { } var l = NSLock() let lbase: NSObject = l print(String(cString: object_getClassName(l))) _ = (l as P).anyP _ = (lbase as! P).anyP // CHECK-NEXT: NSLock // ... and KVO's artificial subclass thereof l.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil) print(String(cString: object_getClassName(l))) _ = (l as P).anyP _ = (lbase as! P).anyP // CHECK-NEXT: NSKVONotifying_NSLock
cdb449a738a3ecf151187c5e8c6f4b1e
22.15
75
0.663787
false
false
false
false
githubError/KaraNotes
refs/heads/master
KaraNotes/KaraNotes/WriteArticle/View/CPFEditView.swift
apache-2.0
1
// // CPFEditView.swift // KaraNotes // // Created by 崔鹏飞 on 2017/4/9. // Copyright © 2017年 崔鹏飞. All rights reserved. // import UIKit import Alamofire protocol CPFEditViewDelegate { func editView(editView:CPFEditView, didChangeText text:String) -> Void } class CPFEditView: UITextView { var titleTextField:UITextField! var editViewDelegate:CPFEditViewDelegate? var firstImageLinkString:String = "" fileprivate var keyboardAccessoryView:CPFKeyboardAccessoryView! fileprivate var textViewPlaceholderLabel:UILabel! fileprivate var separateImageView:UIImageView! override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) configure() setupSubviews() addKeyboardObserver() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() setupSubviews() addKeyboardObserver() } deinit { NotificationCenter.default.removeObserver(self) } fileprivate func addKeyboardObserver() -> Void { NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHidden), name: NSNotification.Name.UIKeyboardDidHide, object: nil) } @objc fileprivate func keyboardDidShow(notification: NSNotification) -> Void { if let userInfo = notification.userInfo { if let keyboardSize: CGSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect)?.size { let contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 10, 0.0) self.contentInset = contentInset } } } @objc fileprivate func keyboardDidHidden() -> Void { contentInset = UIEdgeInsets.zero } } // MARK: - setup subviews extension CPFEditView { fileprivate func configure() -> Void { keyboardAccessoryView = CPFKeyboardAccessoryView() keyboardAccessoryView.accessoryViewDelegate = self inputAccessoryView = keyboardAccessoryView textContainerInset = UIEdgeInsets(top: 55, left: 10, bottom: 0, right: 10) contentSize = CGSize(width: CPFScreenW, height: 0.0) layoutManager.allowsNonContiguousLayout = false font = CPFPingFangSC(weight: .regular, size: 14) delegate = self } fileprivate func setupSubviews() -> Void { titleTextField = UITextField() addSubview(titleTextField) titleTextField.placeholder = CPFLocalizableTitle("writeArticle_titlePlaceholder") titleTextField.font = CPFPingFangSC(weight: .medium, size: 18) titleTextField.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(10) make.top.equalToSuperview() make.right.equalToSuperview().offset(-10) make.height.equalTo(45) } separateImageView = UIImageView() addSubview(separateImageView) separateImageView.image = UIImage.init(named: "separateLine") separateImageView.snp.makeConstraints { (make) in make.left.right.equalToSuperview() make.top.equalTo(titleTextField.snp.bottom) make.height.equalTo(2) } configureTextViewPlaceholderLabel() } fileprivate func configureTextViewPlaceholderLabel() -> Void { textViewPlaceholderLabel = UILabel() textViewPlaceholderLabel.text = CPFLocalizableTitle("writeArticle_articlePlaceholder") textViewPlaceholderLabel.font = CPFPingFangSC(weight: .regular, size: 14) textViewPlaceholderLabel.textColor = CPFRGB(r: 185, g: 185, b: 185) addSubview(textViewPlaceholderLabel) textViewPlaceholderLabel.snp.makeConstraints { (make) in make.left.right.equalTo(titleTextField).offset(3.5) make.top.equalTo(separateImageView.snp.bottom).offset(3) make.height.equalTo(30) } } } // MARK: - UITextViewDelegate extension CPFEditView: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { textViewPlaceholderLabel.isHidden = hasText editViewDelegate?.editView(editView: self, didChangeText: self.text) highLightText() } func highLightText() -> Void { if (markedTextRange != nil) { return } let models = CPFMarkdownSyntaxManager.sharedManeger().syntaxModelsFromText(text: text) let attributedString = NSMutableAttributedString.init(string: text) let initAttributesDic = [NSFontAttributeName : CPFPingFangSC(weight: .regular, size: 16), NSForegroundColorAttributeName : UIColor.black] attributedString.addAttributes(initAttributesDic, range: NSRange(location: 0, length: attributedString.length)) for item in models { var highLightModel = CPFHighLightModel() let attributesDic = highLightModel.attributesFromMarkdownSyntaxType(markdownSyntaxType: item.markdownSyntaxType) attributedString.addAttributes(attributesDic, range: item.range) } self.isScrollEnabled = false; let selectedRange = self.selectedRange; self.attributedText = attributedString; self.selectedRange = selectedRange; self.isScrollEnabled = true; } } // MARK: - CPFKeyboardAccessoryViewDelegate extension CPFEditView: CPFKeyboardAccessoryViewDelegate { func accessoryView(accessoryView: CPFKeyboardAccessoryView, didClickAccessoryItem item: UIButton) { switch item.tag { case 1: selectImageFromPhotoLibrary() case 2: insertLink(completionHandler: { (linkString) in let insertString = "[KaraNotes](\(linkString))" self.titleTextField.isFirstResponder ? self.titleTextField.insertText(insertString) : self.insertText(insertString) let range = NSRange(location: self.selectedRange.location - insertString.characters.count + 1, length: 9) self.selectedRange = range }) case 15: resignFirstResponder() default: resignFirstResponder() } } func accessoryView(accessoryView: CPFKeyboardAccessoryView, shouldSendString string: String) { titleTextField.isFirstResponder ? titleTextField.insertText(string) : insertText(string) } } // MARK: - custom methods extension CPFEditView { func insertLink(completionHandler: @escaping (_ linkString:String) -> Void ) -> Void { let alertCtr = UIAlertController(title: CPFLocalizableTitle("writeArticle_insertLinkAlertTitle"), message: nil, preferredStyle: .alert) alertCtr.addTextField { (textFiled) in textFiled.placeholder = CPFLocalizableTitle("writeArticle_inputLinkPlaceholder") textFiled.keyboardType = .URL } let cancelAction = UIAlertAction(title: CPFLocalizableTitle("writeArticle_insertLinkAlertCancel"), style: .cancel) { (alertAction) in alertCtr.dismiss(animated: true, completion: nil) } let insertAction = UIAlertAction(title: CPFLocalizableTitle("writeArticle_insertLinkAlertInsert"), style: .default) { (alertAction) in let textField = alertCtr.textFields?.first completionHandler((textField?.text)!) } alertCtr.addAction(cancelAction) alertCtr.addAction(insertAction) let vc = self.viewController(aClass: UIViewController.classForCoder()) vc?.present(alertCtr, animated: true, completion: nil) } func insertImageLink(linkString:String) -> Void { let insertString = "![KaraNotes](\(linkString))" titleTextField.isFirstResponder ? titleTextField.insertText(insertString) :insertText(insertString) let range = NSRange(location: self.selectedRange.location - insertString.characters.count + 2, length: 9) selectedRange = range if firstImageLinkString.characters.count == 0 { let index = insertString.index(insertString.startIndex, offsetBy: 13) firstImageLinkString = insertString.substring(from: index) let startIndex = firstImageLinkString.startIndex let endIndex = firstImageLinkString.index(firstImageLinkString.endIndex, offsetBy: -1) let range = startIndex..<endIndex firstImageLinkString = firstImageLinkString.substring(with: range) } } func selectImageFromPhotoLibrary() -> Void { let imagePickerCtr = UIImagePickerController() imagePickerCtr.sourceType = .photoLibrary imagePickerCtr.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate self.viewController(aClass: UIViewController.classForCoder())?.present(imagePickerCtr, animated: true, completion: nil) } func uploadData(data:Data, completionHandler: @escaping (_ LinkString:String) -> Void) -> Void { Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(data, withName: "img", fileName: "testName", mimeType: "image/*") }, to: CPFNetworkRoute.getAPIFromRouteType(route: .uploadImage), encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.uploadProgress(closure: { (progress) in if progress.isCancelled { return } CPFProgressView.sharedInstance().showProgressView(progress: CGFloat(progress.fractionCompleted), promptMessage: "正在上传 \n \(Int(progress.fractionCompleted * 100))%") if progress.fractionCompleted == 1.0 { CPFProgressView.sharedInstance().dismissProgressView(completionHandeler: { progress.cancel() }) } }) upload.response { response in let string = String(bytes: response.data!, encoding: .utf8)! completionHandler(string) } case .failure(let encodingError): print("-------\(encodingError)") } }) } } // MARK: - UIImagePickerController extension CPFEditView: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let imageData: Data if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imageData = image.scaleImageToSize(newSize: CGSize(width: image.size.width / 5, height: image.size.height / 5)) picker.dismiss(animated: true) { self.uploadData(data: imageData, completionHandler: { (linkString) in print(linkString) self.insertImageLink(linkString: linkString) }) } } } }
5b51049350c930f6c72b44dd3cb12f74
39.667845
188
0.646972
false
false
false
false
Masteryyz/CSYMicroBlockSina
refs/heads/master
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Tools/EmoticonKeyboard/CSYTextSettingView.swift
mit
1
// // CSYTextSettingView.swift // CSYEmoticonKeyboard__Test // // Created by 姚彦兆 on 15/11/22. // Copyright © 2015年 姚彦兆. All rights reserved. // import UIKit class CSYTextSettingView: UITextView { func emoticonToString() -> String{ let attribute = attributedText var targetString : String = String() attribute.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: []) { (dict, range, isEnd) -> Void in // print(dict) // print(range) if let attachment : CSYTextAttachment = dict["NSAttachment"] as? CSYTextAttachment{ targetString += (attachment.chs ?? "") }else{ targetString += (attribute.string as NSString).substringWithRange(range) } } return targetString } func insertTextAttachment( emoticonModel : CSYEmoticonModel ){ if emoticonModel.isEmpty{ return } if emoticonModel.isRemove{ deleteBackward() return } if emoticonModel.defaultEmoticon != nil { replaceRange(selectedTextRange!, withText: emoticonModel.defaultEmoticon ?? "") return } //下面就是点击了图片表情的操作 //处理图文混排 //设置文本附件 // let attachement : NSTextAttachment = NSTextAttachment() // //给文本附件添加图片 // attachement.image = UIImage(contentsOfFile: emoticonModel.pngPath!) // // //设置控件Frame // let emoticon_H : CGFloat = font!.lineHeight // // let bounds : CGRect = CGRectMake(0, -4, emoticon_H, emoticon_H) // // attachement.bounds = bounds // // //将该附件设置为属性字符串 // let attribute : NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachement)) // // attribute.addAttribute(NSFontAttributeName, value:font!, range: NSRange(location: 0,length: 1)) let attachement : CSYTextAttachment = CSYTextAttachment() let attribute : NSAttributedString = attachement.getEmoticonAttachmentText(emoticonModel, font: font!) //获取输入框的属性文本 let targetStr : NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText) let location : NSInteger = selectedRange.location targetStr.replaceCharactersInRange(selectedRange, withAttributedString: attribute) // targetStr.replaceCharactersInRange(textInputView.selectedRange, withAttributedString: NSAttributedString(string: emoticonModel.chs!)) attributedText = targetStr // textInputView.selectedRange = NSRange(location: location + ((emoticonModel.chs)! as NSString).length, length: 0) selectedRange = NSRange(location: location + 1, length: 0) } }
bcfd27a7e10e59dce5d132ffbb29f446
28.824074
151
0.567836
false
false
false
false
seansu4you87/kupo
refs/heads/master
sandbox/apple/OpenDash/OpenDash/Restaurant/Service.swift
mit
1
// // Created by Zexiao Yu on 2/3/16. // Copyright (c) 2016 kupo. All rights reserved. // import Foundation import Alamofire extension Restaurant { class Service {} } class Network { class Task { let transport: Alamofire.Request init(transport: Alamofire.Request) { self.transport = transport } func cancel() { transport.cancel() } } } extension Restaurant.Service { func getRestaurantsAt(geocode: Geocode, success: ([Restaurant]) -> (), failure: (ErrorType) -> ()) -> Network.Task { let hardcoded = Geocode(latitude: 37.7771110, longitude: -122.4151530) let params = ["lat": hardcoded.latitude, "lng": hardcoded.longitude] let request = Alamofire .request(.GET, "https://api.doordash.com/v2/restaurant/", parameters: params) .responseJSON { response in print(response.request) // original URL request switch response.result { case .Success(let array): do { let restaurants = try (array as! [JSON]).map { restaurantJSON in Restaurant.serialize(restaurantJSON)! } success(restaurants) } catch { failure(error) } case .Failure(let error): failure(error) } } return Network.Task(transport: request) } }
5a367800e98fb3cdf980182796b7f743
28.527273
92
0.498768
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/master
Carthage/Checkouts/Swifter/Sources/SwifterFavorites.swift
mit
2
// // SwifterFavorites.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 extension Swifter { /** GET favorites/list Returns the 20 most recent Tweets favorited by the authenticating or specified user. If you do not provide either a user_id or screen_name to this method, it will assume you are requesting on behalf of the authenticating user. Specify one or the other for best results. */ public func getRecentlyFavoritedTweets(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, tweetMode: TweetMode = .default, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/list.json" var parameters = [String: Any]() parameters["count"] ??= count parameters["since_id"] ??= sinceID parameters["max_id"] ??= maxID parameters["tweet_mode"] ??= tweetMode.stringValue self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } public func getRecentlyFavoritedTweets(for userTag: UserTag, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, tweetMode: TweetMode = .default, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/list.json" var parameters = [String: Any]() parameters[userTag.key] = userTag.value parameters["count"] ??= count parameters["since_id"] ??= sinceID parameters["max_id"] ??= maxID parameters["tweet_mode"] ??= tweetMode.stringValue self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST favorites/destroy Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func unfavoriteTweet(forID id: String, includeEntities: Bool? = nil, tweetMode: TweetMode = .default, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/destroy.json" var parameters = [String: Any]() parameters["id"] = id parameters["include_entities"] ??= includeEntities parameters["tweet_mode"] ??= tweetMode.stringValue self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST favorites/create Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not. */ public func favoriteTweet(forID id: String, includeEntities: Bool? = nil, tweetMode: TweetMode = .default, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "favorites/create.json" var parameters = [String: Any]() parameters["id"] = id parameters["include_entities"] ??= includeEntities parameters["tweet_mode"] ??= tweetMode.stringValue self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } }
0bf6efc9bf29e8771f62c1783f73909a
38.578125
250
0.666798
false
false
false
false
FindGF/_BiliBili
refs/heads/master
WTBilibili/Mine-我的/Mine-我的/View/WTUserCenterButton.swift
apache-2.0
1
// // WTUserCenterButton.swift // WTBilibili // // Created by 无头骑士 GJ on 16/7/4. // Copyright © 2016年 无头骑士 GJ. All rights reserved. // import UIKit let UserCenterButtonH: CGFloat = 90 let column = 4 let UserCenterButtonW = WTScreenWidth / CGFloat(column) class WTUserCenterButton: UIButton { // MARK: - 系统回调函数 override init(frame: CGRect) { super.init(frame: frame) // 设置基本属性 backgroundColor = UIColor.whiteColor() setTitleColor(UIColor.blackColor(), forState: .Normal) titleLabel?.font = UIFont.systemFontOfSize(14) let layer = CAShapeLayer() layer.frame = self.bounds let linePath = UIBezierPath() linePath.moveToPoint(CGPoint(x: 0, y: 0)) linePath.addLineToPoint(CGPoint(x: UserCenterButtonW, y: 0)) linePath.addLineToPoint(CGPoint(x: UserCenterButtonW, y: UserCenterButtonH)) layer.path = linePath.CGPath layer.fillColor = UIColor.clearColor().CGColor layer.strokeColor = UIColor(hexString: "#666666", alpha: 0.1)?.CGColor self.layer.addSublayer(layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // 重新调整图片和标题的位置 let imageViewWH: CGFloat = 25 let imageViewX = (self.frame.width - imageViewWH) * 0.5 imageView?.frame = CGRect(x: imageViewX, y: 25, width: 25, height: 25) titleLabel?.sizeToFit() let titleLabelX = (self.frame.width - titleLabel!.frame.width) * 0.5 titleLabel?.frame = CGRect(x: titleLabelX, y: 60, width: titleLabel!.frame.width, height: titleLabel!.frame.height) } }
d6bd0468e2de9a011caae0ff2c950cb9
28.360656
123
0.632607
false
false
false
false
webelectric/AspirinKit
refs/heads/master
AspirinKit/Sources/SceneKit/SCNTransaction.swift
mit
1
// // SCNTransaction.swift // AspirinKit // // Copyright © 2015-2017 The Web Electric Corp. All rights reserved. // // import Foundation import SceneKit import CoreGraphics public extension SCNTransaction { public class func runBlockInTransaction(duration aDuration:TimeInterval? = nil, delay aDelay:TimeInterval = 0, timingFunctionName:String? = nil, completion completionBlock: NoParamBlock? = nil, scnBlock: @escaping NoParamBlock) { Thread.dispatchAsyncOnMainQueue(afterDelay: aDelay) { SCNTransaction.begin() if let duration = aDuration { SCNTransaction.animationDuration = duration } if let completion = completionBlock { SCNTransaction.completionBlock = completion } //watchOS does not include QuartzCore which includes CAMediaTimingFunction #if !os(watchOS) if let tfName = timingFunctionName { SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: tfName) } #endif scnBlock() SCNTransaction.commit() } } }
ac17cfd0ea02233f121b7e93d9355eba
28.731707
233
0.611977
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Picker/View/Cell/PhotoPickerLimitCell.swift
mit
1
// // PhotoPickerLimitCell.swift // HXPHPicker // // Created by Slience on 2021/10/22. // import UIKit class PhotoPickerLimitCell: UICollectionViewCell { lazy var lineLayer: CAShapeLayer = { let lineLayer = CAShapeLayer() lineLayer.contentsScale = UIScreen.main.scale lineLayer.fillColor = UIColor.clear.cgColor lineLayer.lineCap = .round return lineLayer }() lazy var titleLb: UILabel = { let label = UILabel() label.textAlignment = .center label.adjustsFontSizeToFitWidth = true return label }() var config: PhotoListConfiguration.LimitCell? { didSet { setConfig() } } override init(frame: CGRect) { super.init(frame: frame) contentView.layer.addSublayer(lineLayer) contentView.addSubview(titleLb) } override func layoutSubviews() { super.layoutSubviews() lineLayer.frame = bounds titleLb.x = 0 titleLb.y = (height - 20) * 0.5 + 22 titleLb.width = width titleLb.height = titleLb.textHeight setLineLayerPath() } func setConfig() { guard let config = config else { return } titleLb.text = config.title?.localized let isDark = PhotoManager.isDark backgroundColor = isDark ? config.backgroundDarkColor : config.backgroundColor lineLayer.strokeColor = isDark ? config.lineDarkColor.cgColor : config.lineColor.cgColor lineLayer.lineWidth = config.lineWidth titleLb.textColor = isDark ? config.titleDarkColor : config.titleColor titleLb.font = config.titleFont } func setLineLayerPath() { let path = UIBezierPath() let centerX = width * 0.5 let margin: CGFloat = config?.title == nil ? 0 : 20 let centerY = (height - margin) * 0.5 let linelength = (config?.lineLength ?? 30) * 0.5 path.move(to: CGPoint(x: centerX - linelength, y: centerY)) path.addLine(to: CGPoint(x: centerX + linelength, y: centerY)) path.move(to: .init(x: centerX, y: centerY - linelength)) path.addLine(to: .init(x: centerX, y: centerY + linelength)) lineLayer.path = path.cgPath } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { setConfig() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
9c7c6dda9d2e19bf517d55967f5c84e3
29.844444
97
0.612032
false
true
false
false
youandthegang/APILayer
refs/heads/master
APILayer/AlamofireExtension.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 you & the gang UG(haftungsbeschränkt) // // 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. // // This code is based on the README of Alamofire (https://github.com/Alamofire/Alamofire). // Thanks to Mattt Thompson for all the great stuff! import Foundation import Alamofire // Errors for this API public enum APIResponseStatus: Error { case success case failedRequest(statusCode: Int) case unknownProblem case invalidTopLevelJSONType case missingKey(description: String) case invalidValue(description: String) case invalidMockResponse(path: String) case encodingError(description: String) case requestFailedWithResponse(statusCode: Int, response: URLResponse) } // Protocol for objects that can be constructed from parsed JSON. public protocol MappableObject { init(map: Map) } extension Alamofire.DataRequest { // MARK: Parsing method fileprivate func callCompletionAfterJSONParsing(_ value: Any, router: RouterProtocol, response: DataResponse<Any>,completionHandler: (_ request: URLRequest?, _ response: HTTPURLResponse?, _ result: MappableObject?, _ status: APIResponseStatus) -> Void) { switch value { case let dict as [String: AnyObject]: // Top level type is dictionary let map = Map(representation: dict as AnyObject) let object = router.result(forMap: map) if let object = object , map.error == nil { // Call completion handler wiht result completionHandler(response.request, response.response, object, .success) } else { if let error = map.error { // Call completion handler with error result completionHandler(response.request, response.response, nil, error) } else { // Call completion handler with error result completionHandler(response.request, response.response, nil, APIResponseStatus.unknownProblem) } } case let array as [AnyObject]: // Top level type is array var resultArray = [Any]() for itemDict in array { let itemMap = Map(representation: itemDict) let object = router.result(forMap: itemMap) if let object = object , itemMap.error == nil { resultArray.append(object) } } if resultArray.count == array.count { // Construct collection entity to wrap the array let collection = CollectionEntity(map: Map(representation: [String: AnyObject]() as AnyObject)) collection.items.append(contentsOf: resultArray) // Call completion handler wiht result completionHandler(response.request, response.response, collection, .success) } else { // Call completion handler with error result completionHandler(response.request, response.response, nil, APIResponseStatus.unknownProblem) } default: // Call completion handler with error result completionHandler(response.request, response.response, nil, APIResponseStatus.invalidTopLevelJSONType) } } public func handleJSONCompletion(_ router: RouterProtocol, response: DataResponse<Any>, completionHandler: (_ request: URLRequest?, _ response: HTTPURLResponse?, _ result: MappableObject?, _ status: APIResponseStatus) -> Void) { switch response.result { case .success(let value): // Valid JSON! Does not mean that the JSON contains valid content. // Check status for success if let urlResponse = response.response , urlResponse.statusCode < 200 || urlResponse.statusCode >= 300 { // Request failed (we do not care about redirects, just do not do that on your API. Return error but also the JSON object, might be useful for debugging. let error = APIResponseStatus.requestFailedWithResponse(statusCode: urlResponse.statusCode, response: urlResponse) // If the response is a dictionary we try to parse it if let dict = value as? [String: AnyObject] { let map = Map(representation: dict as AnyObject) let object = router.failureResult(forMap: map) // If we could parse something, pass that error object if let object = object , map.error == nil { completionHandler(response.request, urlResponse, object, APIResponseStatus.failedRequest(statusCode: urlResponse.statusCode)) return } } completionHandler(response.request, urlResponse, nil, APIResponseStatus.failedRequest(statusCode: urlResponse.statusCode)) return } // Try to construct object from JSON structure callCompletionAfterJSONParsing(value, router: router, response: response, completionHandler: completionHandler) case .failure(let error): // No valid JSON. // But maybe the status code is valid, and we got no JSON Body. if let urlResponse = response.response , urlResponse.statusCode >= 200 || urlResponse.statusCode < 300 { // Status code is valid, so try to create response object from empty dict // because the client might expect that. let emptyDictionary = [String:String]() callCompletionAfterJSONParsing(emptyDictionary, router: router, response: response, completionHandler: completionHandler) } else { // Let router know that a request failed (in case ui wants to visualize that) router.requestFailed() let apiError = APIResponseStatus.invalidValue(description: error.localizedDescription) completionHandler(response.request, response.response, nil, apiError) } } } public func responseObject(_ router: RouterProtocol, completionHandler: @escaping (_ request: URLRequest?, _ response: HTTPURLResponse?, _ result: MappableObject?, _ status: APIResponseStatus) -> Void) -> Self { // return responseString { response in // print("Success: \(response.result.isSuccess)") // print("Response String: \(response.result.value)") // } // // return responseString(completionHandler: { response in // self.handleJSONCompletion(router, response: response, completionHandler: completionHandler) // }) return responseJSON(completionHandler: { response in self.handleJSONCompletion(router, response: response, completionHandler: completionHandler) }) } public func mockObject(forPath path: String, withRouter router: RouterProtocol, completionHandler: (MappableObject?, APIResponseStatus) -> Void) -> Self { if let mockData = NSData(contentsOfFile: path) { // Load JSON from mock response file do { let jsonObject: Any = try JSONSerialization.jsonObject(with: mockData as Data, options: JSONSerialization.ReadingOptions.allowFragments) // Try to construct the object from the JSON structure switch jsonObject { case let dict as [String: AnyObject]: // Top level type is dictionary let map = Map(representation: dict as AnyObject) let object = router.result(forMap: map) if let object = object , map.error == nil { // Call completion handler wiht result completionHandler(object, .success) } else { if let error = map.error { // Call completion handler with error result completionHandler(nil, error) } else { // Call completion handler with error result completionHandler(nil, APIResponseStatus.unknownProblem) } } case let array as [AnyObject]: // Top level type is array var resultArray = [Any]() for itemDict in array { let itemMap = Map(representation: itemDict) let object = router.result(forMap: itemMap) if let object = object , itemMap.error == nil { resultArray.append(object) } } if resultArray.count == array.count { // Construct collection entity to wrap the array let collection = CollectionEntity(map: Map(representation: [String: AnyObject]() as AnyObject)) collection.items.append(contentsOf: resultArray) // Call completion handler wiht result completionHandler(collection, .success) } else { // Call completion handler with error result completionHandler(nil, APIResponseStatus.unknownProblem) } default: // Call completion handler with error result completionHandler(nil, APIResponseStatus.invalidTopLevelJSONType) } // let map = Map(representation: jsonObject) // let object = router.result(forMap: map) // // if let error = map.error { // // completionHandler(nil, error) // // } else { // // completionHandler(object, .Success) // } } catch { let apiError = APIResponseStatus.invalidMockResponse(path: path) completionHandler(nil, apiError) } } return self } }
6b41c0aa23e06493c0b615f9afd3ea97
44
258
0.561317
false
false
false
false
adoosii/edx-app-ios
refs/heads/master
Source/PSTAlertController+Selection.swift
apache-2.0
6
// // PSTAlertController+Selection.swift // edX // // Created by Akiva Leffert on 7/21/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation extension PSTAlertController { static func actionSheetWithItems<A : Equatable>(items : [(title : String, value : A)], currentSelection : A? = nil, action : A -> Void) -> PSTAlertController { let controller = PSTAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) for (var title, value) in items { if let selection = currentSelection where value == selection { // Note that checkmark and space have a neutral text flow direction so this is correct for RTL title = "✔︎ " + title } controller.addAction( PSTAlertAction(title : title) {_ in action(value) } ) } return controller } }
15ba35fd645cf339a026bb3d20eb835e
35
163
0.592513
false
false
false
false
KrishMunot/swift
refs/heads/master
test/IRGen/globals.swift
apache-2.0
6
// RUN: %target-swift-frontend -primary-file %s -emit-ir | FileCheck %s // REQUIRES: CPU=x86_64 var g0 : Int = 1 var g1 : (Void, Int, Void) var g2 : (Void, Int, Int) var g3 : Bool // FIXME: enum IRgen // enum TY4 { case some(Int, Int); case none } // var g4 : TY4 // FIXME: enum IRgen // enum TY5 { case a(Int8, Int8, Int8, Int8) // case b(Int16) } // var g5 : TY5 var g6 : Double var g7 : Float // FIXME: enum IRgen // enum TY8 { case a } // var g8 : TY8 struct TY9 { } var g9 : TY9 // rdar://16520242 struct A {} extension A { static var foo : Int = 5 } // CHECK: [[INT:%.*]] = type <{ i64 }> // CHECK: [[BOOL:%.*]] = type <{ i1 }> // CHECK: [[DOUBLE:%.*]] = type <{ double }> // CHECK: [[FLOAT:%.*]] = type <{ float }> // CHECK-NOT: TY8 // CHECK-NOT: TY9 // CHECK: @_Tv7globals2g0Si = hidden global [[INT]] zeroinitializer, align 8 // CHECK: @_Tv7globals2g1TT_SiT__ = hidden global <{ [[INT]] }> zeroinitializer, align 8 // CHECK: @_Tv7globals2g2TT_SiSi_ = hidden global <{ [[INT]], [[INT]] }> zeroinitializer, align 8 // CHECK: @_Tv7globals2g3Sb = hidden global [[BOOL]] zeroinitializer, align 1 // CHECK: @_Tv7globals2g6Sd = hidden global [[DOUBLE]] zeroinitializer, align 8 // CHECK: @_Tv7globals2g7Sf = hidden global [[FLOAT]] zeroinitializer, align 4 // CHECK: @_TZvV7globals1A3fooSi = hidden global [[INT]] zeroinitializer, align 8 // CHECK-NOT: g8 // CHECK-NOT: g9 // CHECK: define{{( protected)?}} i32 @main(i32, i8**) {{.*}} { // CHECK: store i64 {{.*}}, i64* getelementptr inbounds ([[INT]], [[INT]]* @_Tv7globals2g0Si, i32 0, i32 0), align 8 // FIXME: give these initializers a real mangled name // CHECK: define internal void @globalinit_{{.*}}func0() {{.*}} { // CHECK: store i64 5, i64* getelementptr inbounds (%Si, %Si* @_TZvV7globals1A3fooSi, i32 0, i32 0), align 8
62172d28c3a218e786c1cd98311292a2
29.915254
122
0.618421
false
false
false
false
bvic23/VinceRP
refs/heads/master
VinceRPTests/Common/Util/WeakSetSpec.swift
mit
1
// // Created by Viktor Belenyesi on 20/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // @testable import VinceRP import Quick import Nimble class WeakSetSpec: QuickSpec { override func spec() { context("insert") { it("inserts new weakreference to empty set") { // given let foo = Foo() let ws = WeakSet<Foo>() // when ws.insert(foo) // then expect(ws.set) == toSet(foo) } it("won't insert a new object with a different set") { // given let foo1 = Foo() let foo2 = Foo() let ws = WeakSet([foo1]) // when ws.insert(foo2) // then expect(ws.set) == toSet(foo1) } it("inserts a new value with a different hash") { // given let foo1 = Foo() let foo2 = Foo(hashValue: 2) let ws = WeakSet([foo1]) // when ws.insert(foo2) // then expect(ws.set) == Set([foo1, foo2]) } } } }
a7ec4b664089a3f115df580ffded7fbb
23.551724
66
0.370084
false
false
false
false
remirobert/Naruto-shippuden-iOS
refs/heads/master
naruto-download/AppDelegate.swift
mit
1
// // AppDelegate.swift // naruto-download // // Created by Remi Robert on 01/12/14. // Copyright (c) 2014 remirobert. All rights reserved. // import UIKit import Realm @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) let tabBarController = TabBarViewController() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()] UITabBar.appearance().barTintColor = UIColor(red: 30 / 255.0, green: 30 / 255.0, blue: 30 / 255.0, alpha: 1) UIApplication.sharedApplication().networkActivityIndicatorVisible = true tabBarController.viewControllers = [tabBarController.downloadController, tabBarController.episodesController] //self.window?.rootViewController = tabBarController self.window?.rootViewController = DownloadViewController() self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
1f482e83e64abd6b00084b1cd844b0aa
47.693548
285
0.735674
false
false
false
false
GoMino/Shopmium
refs/heads/master
Shopmium/Models/User.swift
mit
1
// // User.swift // Shopmium // // Created by Amine Bezzarga on 7/13/15. // Copyright (c) 2015 Amine Bezzarga. All rights reserved. // import Foundation import JSONJoy //The object that will represent our response. More Info in the JSON Parsing section below. struct User : JSONJoy { var id: Int? var email: String? var lastName: String? var firstName: String? var referralCode: String? var account: Int? var token: String? init() { } init(_ decoder: JSONDecoder) { id = decoder["id"].integer email = decoder["email"].string account = decoder["account"].integer lastName = decoder["last_name"].string firstName = decoder["first_name"].string referralCode = decoder["referral_code"].string token = decoder["token"].string } }
c4059e456b40dfd2206d537ad7bdb3dd
24.454545
91
0.630513
false
false
false
false
karavakis/simply_counted
refs/heads/master
simply_counted/Client.swift
apache-2.0
1
// // Client.swift // simply_counted // // Created by Jennifer Karavakis on 8/19/16. // Copyright © 2017 Jennifer Karavakis. All rights reserved. // import UIKit import CloudKit open class Client: CloudKitRecord { var name: String var passes: Int var notes : String var activities = [Activity]() var lastCheckIn : Date? = nil //calculated variables var totalCheckIns = 0 var totalPasses = 0 var totalPrice : NSDecimalNumber = 0 /****************/ /* Initializers */ /****************/ init(name: String) { self.name = name self.passes = 0 self.notes = "" super.init() self.record = CKRecord(recordType: "Client") } init(clientRecord: CKRecord!) { self.name = clientRecord.object(forKey: "name") as! String self.passes = clientRecord.object(forKey: "passes") as! Int self.notes = clientRecord.object(forKey: "notes") as! String self.lastCheckIn = clientRecord.object(forKey: "lastCheckIn") as? Date super.init() self.record = clientRecord } /****************/ /* DB Functions */ /****************/ open func save(_ successHandler:(()->Void)?) { record!.setObject(self.name as CKRecordValue?, forKey: "name") record!.setObject(self.passes as CKRecordValue?, forKey: "passes") record!.setObject(self.notes as CKRecordValue?, forKey: "notes") if let lastCheckIn = self.lastCheckIn { record!.setObject(lastCheckIn as CKRecordValue?, forKey: "lastCheckIn") } self.saveRecord(successHandler, errorHandler: nil) } /*************/ /* Check-Ins */ /*************/ open func checkIn(_ date: Date) { let checkIn = CheckIn(clientId: self.record!.recordID, date: date) checkIn.save() self.passes -= 1 //TODO: Do we want to let them go into negative passes if they dont have any left? self.totalCheckIns += 1 var insertAt = activities.count for (index, activity) in activities.enumerated() { if( activity.date.compare(date) == ComparisonResult.orderedAscending) { insertAt = index break } } self.activities.insert(checkIn, at: insertAt) self.updateLastCheckIn() self.save(nil) } func updateLastCheckIn() { self.lastCheckIn = nil for activity in self.activities { if let checkIn = activity as? CheckIn { self.lastCheckIn = checkIn.date break; } } } /**********/ /* Passes */ /**********/ open func addPasses(_ passTypeAdded: PassType) { self.passes += passTypeAdded.passCount self.totalPasses += passTypeAdded.passCount self.totalPrice = self.totalPrice.adding(NSDecimalNumber(string: passTypeAdded.price)) self.save(nil) let passActivity = PassActivity(clientId: self.record!.recordID, date: Date(), passType: passTypeAdded) passActivity.save() self.activities.insert(passActivity, at: 0) } /***************/ /* Update Note */ /***************/ open func updateNotes(_ notes: String) { self.notes = notes self.save(nil) } /**********************/ /* Update Passes Left */ /**********************/ open func updatePassesLeft(_ passesLeft: Int, successHandler:(()->Void)?) { self.passes = passesLeft self.save(successHandler) } /*******************/ /* Remove Activity */ /*******************/ func removeActivity(activityIndex: Int) { if let passActivity = self.activities[activityIndex] as? PassActivity { self.passes -= passActivity.passesAdded self.totalPasses -= passActivity.passesAdded self.totalPrice = self.totalPrice.subtracting(NSDecimalNumber(string: passActivity.price)) } else { self.passes += 1 self.totalCheckIns -= 1 } self.activities.remove(at: activityIndex) updateLastCheckIn() self.save(nil) } /**************/ /* Activities */ /**************/ open func loadActivities(_ successHandler:@escaping (()->Void)) { //clear activities activities = [Activity]() //get check-ins let clientReference = CKRecord.Reference(recordID: record!.recordID, action: .deleteSelf) let predicate = NSPredicate(format: "client == %@", clientReference) let sort = NSSortDescriptor(key: "date", ascending: false) let getCheckInsQuery = CKQuery(recordType: "CheckIn", predicate: predicate) getCheckInsQuery.sortDescriptors = [sort] func checkInErrorHandler(_ error: NSError) { if(error.domain == CKErrorDomain && error.code == 11) { checkInsLoadSuccess([]) } else { print("Error: \(error) \(error.userInfo)") } } func checkInsLoadSuccess(_ records: [CKRecord]) { var checkInRecords = records totalCheckIns = checkInRecords.count func passActivitiesLoadSuccess(_ records: [CKRecord]) { var passActivityRecords = records totalPasses = 0 totalPrice = 0 //Process Activities and Check-ins func getNextPassActivity() -> PassActivity? { if let nextPassActivityObject = passActivityRecords.popLast() { let passActivity = PassActivity(activityRecord: nextPassActivityObject) totalPasses += passActivity.passesAdded totalPrice = NSDecimalNumber(string: passActivity.price).adding(totalPrice) return passActivity } return nil } var nextPassActivity = getNextPassActivity() for checkInRecord in checkInRecords { let newCheckIn = CheckIn(activityRecord : checkInRecord) //Append any Pass Activity that occurs before this checkIn while(nextPassActivity != nil && nextPassActivity!.date.compare(newCheckIn.date) == ComparisonResult.orderedDescending) { self.activities.append(nextPassActivity!) nextPassActivity = getNextPassActivity() } self.activities.append(newCheckIn) } while(nextPassActivity != nil) { self.activities.append(nextPassActivity!) nextPassActivity = getNextPassActivity() } if let lastCheckInRecord = checkInRecords.first { self.lastCheckIn = lastCheckInRecord.object(forKey: "date") as? Date } successHandler() } func passActivityErrorHandler(_ error: NSError) { if(error.domain == CKErrorDomain && error.code == 11) { passActivitiesLoadSuccess([]) } else { print("Error: \(error) \(error.userInfo)") } } let getPassActivitiesQuery = CKQuery(recordType: "PassActivity", predicate: predicate) let sort = NSSortDescriptor(key: "date", ascending: true) getPassActivitiesQuery.sortDescriptors = [sort] self.performQuery(getPassActivitiesQuery, successHandler: passActivitiesLoadSuccess, errorHandler: passActivityErrorHandler) } self.performQuery(getCheckInsQuery, successHandler: checkInsLoadSuccess, errorHandler: checkInErrorHandler) } }
80a206365e7b3a5a6ab7650da65d5be8
33.872247
141
0.557605
false
false
false
false
BuildGamesWithUs/TurnKitFramework
refs/heads/master
TurnKit/Turn Kit iOS SampleApp/GameScene.swift
mit
1
// // GameScene.swift // Turn Kit iOS SampleApp // // Created by Kyle Kilgour on 7/23/15. // Copyright (c) 2015 TeamAwesomeMcPants. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Hello, World!"; myLabel.fontSize = 65; myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(myLabel) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(self) let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.position = location let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
22efc306086ac9d2400bfda186404be1
27.977273
93
0.592941
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/WordPressNotificationContentExtension/Sources/NotificationViewController.swift
gpl-2.0
1
import UIKit import UserNotifications import UserNotificationsUI import WordPressKit // MARK: - NotificationViewController /// Responsible for enhancing the visual appearance of designated push notifications. class NotificationViewController: UIViewController { // MARK: Properties /// Long Look content is inset from iOS container bounds private struct Metrics { static let verticalInset = CGFloat(20) } /// Manages analytics calls via Tracks private let tracks = Tracks(appGroupName: WPAppGroupName) /// The service used to retrieve remote notifications private var notificationService: NotificationSyncServiceRemote? /// This view model contains the attributes necessary to render a rich notification private var viewModel: RichNotificationViewModel? { didSet { setupContentView() } } /// The subview responsible for rendering a notification's Long Look private var contentView: NotificationContentView? // MARK: UIViewController override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) notificationService?.wordPressComRestApi.invalidateAndCancelTasks() notificationService = nil view.subviews.forEach { $0.removeFromSuperview() } viewModel = nil contentView = nil } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) DispatchQueue.main.async { self.contentView?.reloadContent() } } // MARK: Private behavior /// Responsible for instantiation, installation & configuration of the content view private func setupContentView() { guard let viewModel = viewModel else { return } view.translatesAutoresizingMaskIntoConstraints = false let contentView = NotificationContentView(viewModel: viewModel) self.contentView = contentView view.addSubview(contentView) let readableGuide = view.readableContentGuide let constraints = [ contentView.topAnchor.constraint(equalTo: readableGuide.topAnchor, constant: Metrics.verticalInset), contentView.bottomAnchor.constraint(equalTo: readableGuide.bottomAnchor), contentView.leadingAnchor.constraint(equalTo: readableGuide.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: readableGuide.trailingAnchor) ] NSLayoutConstraint.activate(constraints) } } // MARK: - UNNotificationContentExtension extension NotificationViewController: UNNotificationContentExtension { func didReceive(_ notification: UNNotification) { let notificationContent = notification.request.content guard let data = notificationContent.userInfo[CodingUserInfoKey.richNotificationViewModel.rawValue] as? Data else { return } viewModel = RichNotificationViewModel(data: data) let username = readExtensionUsername() tracks.wpcomUsername = username let token = readExtensionToken() tracks.trackExtensionLaunched(token != nil) markNotificationAsReadIfNeeded() } } // MARK: - Private behavior private extension NotificationViewController { /// Attempts to mark the notification as read via the remote service. This promotes UX consistency between the /// Notification received and how it is rendered on the Notifications tab within the app. /// func markNotificationAsReadIfNeeded() { guard let token = readExtensionToken(), let viewModel = viewModel, let notificationIdentifier = viewModel.notificationIdentifier, let notificationHasBeenRead = viewModel.notificationReadStatus, notificationHasBeenRead == false else { return } let api = WordPressComRestApi(oAuthToken: token) notificationService = NotificationSyncServiceRemote(wordPressComRestApi: api) notificationService?.updateReadStatus(notificationIdentifier, read: true) { [tracks] error in guard let error = error else { return } tracks.trackFailedToMarkNotificationAsRead(notificationIdentifier: notificationIdentifier, errorDescription: error.localizedDescription) debugPrint("Error marking note as read: \(error)") } } /// Retrieves the WPCOM OAuth Token, meant for Extension usage. /// /// - Returns: the token if found; `nil` otherwise /// func readExtensionToken() -> String? { guard let oauthToken = try? KeychainUtils.shared.getPasswordForUsername(WPNotificationContentExtensionKeychainTokenKey, serviceName: WPNotificationContentExtensionKeychainServiceName, accessGroup: WPAppKeychainAccessGroup) else { debugPrint("Unable to retrieve Notification Content Extension OAuth token") return nil } return oauthToken } /// Retrieves the WPCOM username, meant for Extension usage. /// /// - Returns: the username if found; `nil` otherwise /// func readExtensionUsername() -> String? { guard let username = try? KeychainUtils.shared.getPasswordForUsername(WPNotificationContentExtensinoKeychainUsernameKey, serviceName: WPNotificationContentExtensionKeychainServiceName, accessGroup: WPAppKeychainAccessGroup) else { debugPrint("Unable to retrieve Notification Content Extension username") return nil } return username } }
1cdbd0692efa3eb5d29d02e6cbfbf29f
36.607595
148
0.670481
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/2-Element/LeftTop.Individual.swift
apache-2.0
1
// // LeftTop.Individual.swift // NotAutoLayout // // Created by 史 翔新 on 2017/06/15. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct LeftTop { let left: LayoutElement.Horizontal let top: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.LeftTop { private func makeFrame(left: Float, top: Float, size: Size) -> Rect { let origin = Point(x: left, y: top) let size = size let frame = Rect(origin: origin, size: size) return frame } } // MARK: - Set A Size - // MARK: Size extension IndividualProperty.LeftTop: LayoutPropertyCanStoreSizeToEvaluateFrameType { public func evaluateFrame(size: LayoutElement.Size, parameters: IndividualFrameCalculationParameters) -> Rect { let left = self.left.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let size = size.evaluated(from: parameters) return self.makeFrame(left: left, top: top, size: size) } } // MARK: - Set A Line - // MARK: Middle extension IndividualProperty.LeftTop: LayoutPropertyCanStoreMiddleType { public func storeMiddle(_ middle: LayoutElement.Vertical) -> IndividualProperty.LeftTopMiddle { let leftTopMiddle = IndividualProperty.LeftTopMiddle(left: self.left, top: self.top, middle: middle) return leftTopMiddle } } // MARK: Bottom extension IndividualProperty.LeftTop: LayoutPropertyCanStoreBottomType { public func storeBottom(_ bottom: LayoutElement.Vertical) -> IndividualProperty.LeftTopBottom { let leftTopBottom = IndividualProperty.LeftTopBottom(left: self.left, top: self.top, bottom: bottom) return leftTopBottom } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.LeftTop: LayoutPropertyCanStoreWidthType { public func storeWidth(_ width: LayoutElement.Length) -> IndividualProperty.LeftTopWidth { let leftTopWidth = IndividualProperty.LeftTopWidth(left: self.left, top: self.top, width: width) return leftTopWidth } } // MARK: Height extension IndividualProperty.LeftTop: LayoutPropertyCanStoreHeightType { public func storeHeight(_ height: LayoutElement.Length) -> IndividualProperty.LeftTopHeight { let leftTopHeight = IndividualProperty.LeftTopHeight(left: self.left, top: self.top, height: height) return leftTopHeight } }
331af2722656e3de0100b5f7ae4fa63b
21.131579
112
0.696393
false
false
false
false
JaSpa/swift
refs/heads/master
test/IDE/complete_pattern.swift
apache-2.0
30
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_1 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_2 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_3 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_4 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_5 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_6 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_7 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_8 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_9 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_10 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_11 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_ATOM_12 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IF_CASE_1 | %FileCheck %s -check-prefix=GLOBAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IF_CASE_2 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_1 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_2 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_3 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_4 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_5 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_6 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_7 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_8 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_9 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_10 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_11 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_ATOM_12 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_IF_CASE_1 | %FileCheck %s -check-prefix=GLOBAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_INFUNC_IF_CASE_2 | %FileCheck %s -check-prefix=NO_COMPLETIONS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_1 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_1 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_2 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_3 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_GENERIC_1 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %FileCheck %s -check-prefix=PATTERN_IS_GENERIC_1 < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_GENERIC_2 > %t.types.txt // RUN: %FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt // RUN: %FileCheck %s -check-prefix=PATTERN_IS_GENERIC_2 < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AFTER_PATTERN_IS | %FileCheck %s -check-prefix=AFTER_PATTERN_IS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_1 | %FileCheck %s -check-prefix=MULTI_PATTERN_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_2 | %FileCheck %s -check-prefix=MULTI_PATTERN_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_3 | %FileCheck %s -check-prefix=MULTI_PATTERN_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_4 | %FileCheck %s -check-prefix=MULTI_PATTERN_4 //===--- Helper types that are used in this test struct FooStruct { } var fooObject : FooStruct func fooFunc() -> FooStruct { return fooObject } enum FooEnum { } class FooClass { } protocol FooProtocol { var fooInstanceVar : Int typealias FooTypeAlias1 func fooInstanceFunc0() -> Double func fooInstanceFunc1(a: Int) -> Double subscript(i: Int) -> Double } protocol BarProtocol { var barInstanceVar : Int typealias BarTypeAlias1 func barInstanceFunc0() -> Double func barInstanceFunc1(a: Int) -> Double } typealias FooTypealias = Int // GLOBAL: Begin completions // GLOBAL-DAG: fooObject // GLOBAL-DAG: fooFunc // GLOBAL-DAG: FooTypealias // GLOBAL-DAG: FooProtocol // GLOBAL-DAG: FooClass // GLOBAL: End completions // GLOBAL_NEGATIVE-NOT: fooObject // GLOBAL_NEGATIVE-NOT: fooFunc //===--- //===--- Test that we don't try to suggest anything where pattern-atom is expected. //===--- // NO_COMPLETIONS-NOT: Begin completions // Use do { } to reset the parser after broken syntax. do { var #^PATTERN_ATOM_1^# } do { var (#^PATTERN_ATOM_2^# } do {var (a, #^PATTERN_ATOM_3^# } do {var (a #^PATTERN_ATOM_4^# } do {var ((#^PATTERN_ATOM_5^# } do {var ((a, b), #^PATTERN_ATOM_6^# } do {guard var #^PATTERN_ATOM_7^# } do {guard var #^PATTERN_ATOM_8^# else { fatalError() } } do {guard let #^PATTERN_ATOM_9^# else { fatalError() } } do {guard let a = Optional(1), let #^PATTERN_ATOM_10^# else { fatalError() } } do {if let #^PATTERN_ATOM_11^# {} } do {if let a = Optional(1), let #^PATTERN_ATOM_12^# {} } do {if case #^PATTERN_IF_CASE_1^# {} } do {if case let #^PATTERN_IF_CASE_2^# {} } func inFunc() { do { var #^PATTERN_INFUNC_ATOM_1^# } do { var (#^PATTERN_INFUNC_ATOM_2^# } do {var (a, #^PATTERN_INFUNC_ATOM_3^# } do {var (a #^PATTERN_INFUNC_ATOM_4^# } do {var ((#^PATTERN_INFUNC_ATOM_5^# } do {var ((a, b), #^PATTERN_INFUNC_ATOM_6^# } do {guard var #^PATTERN_INFUNC_ATOM_7^# } do {guard var #^PATTERN_INFUNC_ATOM_8^# else { fatalError() } } do {guard let #^PATTERN_INFUNC_ATOM_9^# else { fatalError() } } do {guard let a = Optional(1), let #^PATTERN_INFUNC_ATOM_10^# else { fatalError() } } do {if let #^PATTERN_INFUNC_ATOM_11^# {} } do {if let a = Optional(1), let #^PATTERN_INFUNC_ATOM_12^# {} } do {if case #^PATTERN_INFUNC_IF_CASE_1^# {} } do {if case let #^PATTERN_INFUNC_IF_CASE_2^# {} } } //===--- //===--- Test that we complete the type in 'is' pattern. //===--- func patternIs1(x: FooClass) { switch x { case is #^PATTERN_IS_1^# } } func patternIs2() { switch unknown_var { case is #^PATTERN_IS_2^# } } func patternIs3() { switch { case is #^PATTERN_IS_3^# } } //===--- Test that we include types from generic parameter lists. func patternIsGeneric1< GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(x: FooClass) { switch x { case is #^PATTERN_IS_GENERIC_1^# } } // PATTERN_IS_GENERIC_1: Begin completions // Generic parameters of the function. // PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // PATTERN_IS_GENERIC_1: End completions struct PatternIsGeneric2< StructGenericFoo : FooProtocol, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { func patternIsGeneric2< GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(x: FooClass) { switch x { case is #^PATTERN_IS_GENERIC_2^# } } } // PATTERN_IS_GENERIC_2: Begin completions // Generic parameters of the struct. // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // Generic parameters of the function. // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // PATTERN_IS_GENERIC_2: End completions // rdar://21174713 // AFTER_PATTERN_IS: Begin completions func test<T>(x: T) { switch T.self { case is Int.Type: #^AFTER_PATTERN_IS^# } } func test_multiple_patterns1(x: Int) { switch (x, x) { case (0, let a), #^MULTI_PATTERN_1^# } } // MULTI_PATTERN_1: Begin completions // MULTI_PATTERN_1-NOT: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // MULTI_PATTERN_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // MULTI_PATTERN_1: End completions func test_multiple_patterns2(x: Int) { switch (x, x) { case (0, let a), (let a, 0): #^MULTI_PATTERN_2^# } } // MULTI_PATTERN_2: Begin completions // MULTI_PATTERN_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // MULTI_PATTERN_2-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // MULTI_PATTERN_2: End completions func test_multiple_patterns3(x: Int) { switch (x, x) { case (0, let a), (let b, 0): #^MULTI_PATTERN_3^# } } // MULTI_PATTERN_3: Begin completions // MULTI_PATTERN_3-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // MULTI_PATTERN_3: End completions func test_multiple_patterns4(x: Int) { switch (x, x) { case (0, let a) where #^MULTI_PATTERN_4^# } } // MULTI_PATTERN_4: Begin completions // MULTI_PATTERN_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // MULTI_PATTERN_4-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // MULTI_PATTERN_4: End completions
ca7e9d074aa6ead778442df854198145
45.642586
160
0.703269
false
true
false
false
nasser0099/Express
refs/heads/master
Express/Streams+Headers.swift
gpl-3.0
1
//===--- Streams+Headers.swift --------------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express is free software: you can redistribute it and/or modify //it under the terms of the GNU Lesser General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation import BrightFutures protocol ResponseHeadDataConsumerType : DataConsumerType { func consume(head:HttpResponseHeadType) -> Future<Void, AnyError> }
77df7d3503b723253692545f72155409
39.555556
80
0.669104
false
false
false
false
calebd/swift
refs/heads/master
test/Interpreter/SDK/libc.swift
apache-2.0
4
/* magic */ // Do not edit the line above. // RUN: %empty-directory(%t) // RUN: %target-run-simple-swift %s %t | %FileCheck %s // REQUIRES: executable_test #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif let sourcePath = CommandLine.arguments[1] let tempPath = CommandLine.arguments[2] + "/libc.txt" // CHECK: Hello world fputs("Hello world", stdout) // CHECK: 4294967295 print("\(UINT32_MAX)") // CHECK: the magic word is ///* magic */// let sourceFile = open(sourcePath, O_RDONLY) assert(sourceFile >= 0) var bytes = UnsafeMutablePointer<CChar>.allocate(capacity: 12) var readed = read(sourceFile, bytes, 11) close(sourceFile) assert(readed == 11) bytes[11] = CChar(0) print("the magic word is //\(String(cString: bytes))//") // CHECK: O_CREAT|O_EXCL returned errno *17* let errFile = open(sourcePath, O_RDONLY | O_CREAT | O_EXCL) if errFile != -1 { print("O_CREAT|O_EXCL failed to return an error") } else { let e = errno print("O_CREAT|O_EXCL returned errno *\(e)*") } // CHECK-NOT: error // CHECK: created mode *33216* *33216* let tempFile = open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR) if tempFile == -1 { let e = errno print("error: open(tempPath \(tempPath)) returned -1, errno \(e)") abort() } let written = write(tempFile, bytes, 11) if (written != 11) { print("error: write(tempFile) returned \(written), errno \(errno)") abort() } var err: Int32 var statbuf1 = stat() err = fstat(tempFile, &statbuf1) if err != 0 { let e = errno print("error: fstat returned \(err), errno \(e)") abort() } close(tempFile) var statbuf2 = stat() err = stat(tempPath, &statbuf2) if err != 0 { let e = errno print("error: stat returned \(err), errno \(e)") abort() } print("created mode *\(statbuf1.st_mode)* *\(statbuf2.st_mode)*") assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR) assert(statbuf1.st_mode == statbuf2.st_mode)
c3f78835e99ca6730a03ad2cb42a7f4c
23.536585
72
0.653082
false
false
false
false
NijiDigital/NetworkStack
refs/heads/develop
Carthage/Checkouts/RxSwift/RxCocoa/Traits/ControlProperty.swift
apache-2.0
15
// // ControlProperty.swift // RxCocoa // // Created by Krunoslav Zaher on 8/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif /// Protocol that enables extension of `ControlProperty`. public protocol ControlPropertyType : ObservableType, ObserverType { /// - returns: `ControlProperty` interface func asControlProperty() -> ControlProperty<E> } /** Trait for `Observable`/`ObservableType` that represents property of UI element. Sequence of values only represents initial control value and user initiated value changes. Programatic value changes won't be reported. It's properties are: - it never fails - `shareReplay(1)` behavior - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced - it will `Complete` sequence on control being deallocated - it never errors out - it delivers events on `MainScheduler.instance` **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler (`subscribeOn(ConcurrentMainScheduler.instance)` behavior).** **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated properties, please don't use this trait.** */ public struct ControlProperty<PropertyType> : ControlPropertyType { public typealias E = PropertyType let _values: Observable<PropertyType> let _valueSink: AnyObserver<PropertyType> /// Initializes control property with a observable sequence that represents property values and observer that enables /// binding values to property. /// /// - parameter values: Observable sequence that represents property values. /// - parameter valueSink: Observer that enables binding values to control property. /// - returns: Control property created with a observable sequence of values and an observer that enables binding values /// to property. public init<V: ObservableType, S: ObserverType>(values: V, valueSink: S) where E == V.E, E == S.E { _values = values.subscribeOn(ConcurrentMainScheduler.instance) _valueSink = valueSink.asObserver() } /// Subscribes an observer to control property values. /// /// - parameter observer: Observer to subscribe to property values. /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _values.subscribe(observer) } /// `ControlEvent` of user initiated value changes. Every time user updates control value change event /// will be emitted from `changed` event. /// /// Programatic changes to control value won't be reported. /// /// It contains all control property values except for first one. /// /// The name only implies that sequence element will be generated once user changes a value and not that /// adjacent sequence values need to be different (e.g. because of interaction between programatic and user updates, /// or for any other reason). public var changed: ControlEvent<PropertyType> { get { return ControlEvent(events: _values.skip(1)) } } /// - returns: `Observable` interface. public func asObservable() -> Observable<E> { return _values } /// - returns: `ControlProperty` interface. public func asControlProperty() -> ControlProperty<E> { return self } /// Binds event to user interface. /// /// - In case next element is received, it is being set to control value. /// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output. /// - In case sequence completes, nothing happens. public func on(_ event: Event<E>) { switch event { case .error(let error): bindingError(error) case .next: _valueSink.on(event) case .completed: _valueSink.on(event) } } } extension ControlPropertyType where E == String? { /// Transforms control property of type `String?` into control property of type `String`. public var orEmpty: ControlProperty<String> { let original: ControlProperty<String?> = self.asControlProperty() let values: Observable<String> = original._values.map { $0 ?? "" } let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 } return ControlProperty<String>(values: values, valueSink: valueSink) } }
5e8505e0040e1a1dd3f5d7cf12e83409
39.073171
124
0.693447
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
2-Dynamic/2-Dynamic/Bag.swift
mit
1
// // Bag.swift // 2-Dynamic // // Created by keso on 2017/2/19. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Bag { var values:[Int] = [] var weights:[Int] = [] var maxWeight:Int = 0 var calculate:[[Int]] = [] var calculate2:[Int] = [] var calculate3:[Int] = [] init(maxW:Int,value:[Int],weight:[Int]) { maxWeight = maxW values = value weights = weight let temp:[Int] = [Int].init(repeating: 0, count: maxWeight + 1) calculate = [[Int]].init(repeating: temp, count: values.count) } func solveMaxValue()->Int { for i in 1..<values.count { // 注意起始位置 for j in 1...maxWeight { if weights[i] <= j { calculate[i][j] = maxCompare(a: values[i] + calculate[i - 1][j - weights[i]], b: calculate[i-1][j]) } else { calculate[i][j] = calculate[i - 1][j] } } } return calculate[values.count - 1][maxWeight] } func solveMaxValue2()->Int { calculate2 = [Int].init(repeating: 0, count: maxWeight + 1) for i in 1..<values.count { for j in (1...maxWeight).reversed() { if weights[i] <= j { calculate2[j] = maxCompare(a: calculate2[j], b: (calculate2[j-weights[i]]+values[i])) } } } return calculate2[maxWeight] } func solveMaxValue3()->Int { calculate3 = [Int].init(repeating: 0, count: maxWeight + 1) for i in 1..<values.count { for j in 1...maxWeight { if weights[i] <= j { calculate3[j] = maxCompare(a: calculate3[j], b: (calculate3[j-weights[i]]+values[i])) } } } return calculate3[maxWeight] } func printResult() { for i in 1..<values.count { for j in 1...maxWeight { print("\(i)--\(j)的结果---\(calculate[i][j])") } } } func printResult2() { for j in 1...maxWeight { print("\(j)的结果---\(calculate2[j])") } } func maxCompare(a:Int,b:Int) -> Int { return a > b ? a : b } }
4484da0c395a26a9a55e62bb6bdcbb9a
26.127907
119
0.467638
false
false
false
false
JsonBin/WBAlamofire
refs/heads/master
Source/WBAlConfig.swift
mit
1
// // WBAlConfig.swift // WBAlamofire // // Created by zwb on 17/3/24. // Copyright © 2017年 HengSu Technology. All rights reserved. // import Foundation import Alamofire #if os(iOS) import UIKit #endif /// WBAlURLFilterProtocol can be used to append common parameters to requests before sending them. public protocol WBAlURLFilterProtocol { /// Preprocess request URL before actually sending them. /// /// - Parameters: /// - originURL: request's origin URL, which is returned by `requestUrl` /// - request: request itself /// - Returns: A new url which will be used as a new `requestUrl` func filterURL(_ originURL: String, baseRequest request: WBAlBaseRequest) -> String } /// WBAlCacheDirPathFilterProtocol can be used to append common path components when caching response results public protocol WBAlCacheDirPathFilterProtocol { /// Preprocess cache path before actually saving them. /// /// - Parameters: /// - originPath: original base cache path, which is generated in `WBAlBaseRequest` class. /// - request: request itself /// - Returns: A new path which will be used as base path when caching. func filterCacheDirPath(_ originPath: String, baseRequest request: WBAlBaseRequest) -> String } /// WBAlConfig stored global network-related configurations, which will be used in `WBAlamofire` /// to form and filter requests, as well as caching response. public final class WBAlConfig { /// Return a shared config object. public static let shared = WBAlConfig() // MARK: - Public Properties ///============================================================================= /// @name Public Properties ///============================================================================= /// 配置项目的baseURL /// Request base URL, such as "http://www.baidu.com". Default is empty string. public var baseURL: String /// 配置项目的cdnURL /// Request CDN URL. Default is empty string. public var cdnURL: String /// 网络请求超时时间, Default 30s /// Request time out interval. Default is 30s. public var requestTimeoutInterval: TimeInterval /// 设置响应状态码的范围, 默认为(200-300) /// Request vaildator code. Default is 200~300. public var statusCode: [Int] /// 设置返回接受类型 /// Set to return to accept type public var acceptType: [String] /// 是否能通过蜂窝网络访问数据, Default true /// Whether allow cellular. Default is true. public var allowsCellularAccess: Bool /// 是否开启日志打印,默认false /// Whether to log debug info. Default is NO. public var debugLogEnable: Bool /// 是否开启监听网络,默认true /// Whether public network monitoring. Default is true. public var listenNetWork: Bool /// url protocol协议组 /// URL filters. See also `WBAlURLFilterProtocol`. public var urlFilters: [WBAlURLFilterProtocol] /// cache dirpath protocol 协议组 /// Cache path filters. See also `WBAlCacheDirPathFilterProtocol`. public var cacheDirPathFilters: [WBAlCacheDirPathFilterProtocol] /// serverPolicy will be used to Alamofire. Default nil. /// Security policy will be used by Alamofire. See also `ServerTrustPolicyManager`. public var serverPolicy: ServerTrustPolicyManager? /// SessionConfiguration will be used to Alamofire. public var sessionConfiguration: URLSessionConfiguration /// 缓存请求文件的文件夹名, 位于`/Library/Caches/{cacheFileName}` /// Save to disk file name. public var cacheFileName = "wbalamofire.request.cache.default" /// 下载文件时保存的文件名, 位于`/Library/Caches/{downFileName}`下 /// Download file name public var downFileName = "wbalamofire.download.default" // MARK: - Only iOS LoadView ///============================================================================= /// @name Only iOS LoadView ///============================================================================= #if os(iOS) /// 加载框的动画类型,默认为native /// The load view animationType. Default is native. public var loadViewAnimationType = AnimationType.native /// 加载框的文字位置,默认为bottom /// The load view text position. Default is bottom. public var loadViewTextPosition = TextLabelPosition.bottom /// 加载框的文字颜色,默认为白色 /// The load view textColor. Default is white. public var loadViewTextColor = UIColor.white /// 加载框的文字大小,默认为15. /// The load view text font. Default is 15. public var loadViewTextFont = UIFont.systemFont(ofSize: 15) /// 加载框显示的文字,默认为Loading /// The load view text. Default is 'Loading'. public var loadViewText = "Loading" #endif // MARK: - Cycle Life ///============================================================================= /// @name Cycle Life ///============================================================================= public init() { self.baseURL = "" self.cdnURL = "" self.requestTimeoutInterval = 30 self.statusCode = Array(200..<300) self.acceptType = ["application/json", "text/json", "text/javascript", "text/html", "text/plain", "image/jpeg"] self.allowsCellularAccess = true self.debugLogEnable = false self.listenNetWork = true self.serverPolicy = nil self.urlFilters = [WBAlURLFilterProtocol]() self.cacheDirPathFilters = [WBAlCacheDirPathFilterProtocol]() self.sessionConfiguration = .default } public init(baseURL: String, cdnURL: String, requestTimeoutInterval: TimeInterval, statusCode: [Int], acceptType: [String], allowsCellularAccess: Bool, debugLogEnable: Bool, listenNetWork: Bool, serverPolicy: ServerTrustPolicyManager?, urlFilters: [WBAlURLFilterProtocol], cacheDirPathFilters: [WBAlCacheDirPathFilterProtocol], sessionConfiguration: URLSessionConfiguration) { self.baseURL = baseURL self.cdnURL = cdnURL self.requestTimeoutInterval = requestTimeoutInterval self.statusCode = statusCode self.acceptType = acceptType self.allowsCellularAccess = allowsCellularAccess self.debugLogEnable = debugLogEnable self.listenNetWork = listenNetWork self.serverPolicy = serverPolicy self.urlFilters = urlFilters self.cacheDirPathFilters = cacheDirPathFilters self.sessionConfiguration = sessionConfiguration } // MARK: - Public ///============================================================================= /// @name Public ///============================================================================= /// Add a new URL filter. public func add(_ urlFilter: WBAlURLFilterProtocol) { urlFilters.append(urlFilter) } /// Add a new cache path filter public func add(_ cacheFilter: WBAlCacheDirPathFilterProtocol) { cacheDirPathFilters.append(cacheFilter) } /// Remove all URL filters. public func cleanURLFilters() -> Void { urlFilters.removeAll() } /// Clear all cache path filters. public func cleanCacheFilters() -> Void { cacheDirPathFilters.removeAll() } } // MARK: - Description ///============================================================================= /// @name Description ///============================================================================= extension WBAlConfig : CustomStringConvertible { public var description: String { return String(format: "<%@: %p>{ bseURL: %@ } { cdnURL: %@ }", #file, #function, baseURL, cdnURL) } } // MARK: - Debug Description ///============================================================================= /// @name Debug Description ///============================================================================= extension WBAlConfig : CustomDebugStringConvertible { public var debugDescription: String { return String(format: "<%@: %p>{ bseURL: %@ } { cdnURL: %@ }", #file, #function, baseURL, cdnURL) } } // MARK: - GCD ///============================================================================= /// @name GCD ///============================================================================= extension DispatchQueue { public static var wbCurrent: DispatchQueue { let name = String(format: "com.wbalamofire.request.%08x%08x", arc4random(),arc4random()) return DispatchQueue(label: name, attributes: .concurrent) } } // MARK: - Print Logs ///============================================================================= /// @name Print Logs ///============================================================================= public func WBAlog<T>(_ message: T, file File: NSString = #file, method Method: String = #function, line Line: Int = #line) -> Void { if WBAlConfig.shared.debugLogEnable { #if DEBUG print("<\(File.lastPathComponent)>{Line:\(Line)}-[\(Method)]:\(message)") #endif } }
47ce2f6e5b8279c7c1c9e2fe5c82f08c
35.567347
380
0.575734
false
true
false
false
tjw/swift
refs/heads/master
test/SILGen/collection_subtype_upcast.swift
apache-2.0
1
// RUN: %target-swift-frontend -module-name collection_subtype_upcast -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @$S25collection_subtype_upcast06array_C00D0SayypGSayAA1SVG_tF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<S>): // CHECK: debug_value [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: // function_ref // CHECK: [[FN:%.*]] = function_ref @$Ss15_arrayForceCastySayq_GSayxGr0_lF // CHECK: [[BORROWED_ARG_COPY:%.*]] = begin_borrow [[ARG_COPY]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Any>([[BORROWED_ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> // CHECK: end_borrow [[BORROWED_ARG_COPY]] from [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: return [[RESULT]] func array_upcast(array: [S]) -> [Any] { return array } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @$S25collection_subtype_upcast05dict_C00D0s10DictionaryVyAA1SVypGAEyAGSiG_tF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Dictionary<S, Int>): // CHECK: debug_value [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: // function_ref // CHECK: [[FN:%.*]] = function_ref @$Ss17_dictionaryUpCastys10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF // CHECK: [[BORROWED_ARG_COPY:%.*]] = begin_borrow [[ARG_COPY]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Int, S, Any>([[BORROWED_ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: destroy_value [[ARG_COPY]] // CHECK: return [[RESULT]] func dict_upcast(dict: [S: Int]) -> [S: Any] { return dict } // It's not actually possible to test this for Sets independent of // the bridging rules.
58c5b87ba9bde9ea0adfe2dc6d425994
42.608696
243
0.638086
false
false
false
false
alex-alex/S2Geometry
refs/heads/master
Sources/S2Loop.swift
mit
1
// // S2Loop.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif /** An S2Loop represents a simple spherical polygon. It consists of a single chain of vertices where the first vertex is implicitly connected to the last. All loops are defined to have a CCW orientation, i.e. the interior of the polygon is on the left side of the edges. This implies that a clockwise loop enclosing a small area is interpreted to be a CCW loop enclosing a very large area. Loops are not allowed to have any duplicate vertices (whether adjacent or not), and non-adjacent edges are not allowed to intersect. Loops must have at least 3 vertices. Although these restrictions are not enforced in optimized code, you may get unexpected results if they are violated. Point containment is defined such that if the sphere is subdivided into faces (loops), every point is contained by exactly one face. This implies that loops do not necessarily contain all (or any) of their vertices An S2LatLngRect represents a latitude-longitude rectangle. It is capable of representing the empty and full rectangles as well as single points. */ public struct S2Loop: S2Region, Comparable { private class S2LoopEdgeIndex: S2EdgeIndex { let loop: S2Loop init(loop: S2Loop) { self.loop = loop super.init() } private override var numEdges: Int { return loop.numVertices } private override func edgeFrom(index: Int) -> S2Point { return loop.vertex(index) } private override func edgeTo(index: Int) -> S2Point { return loop.vertex(index + 1) } } /// Max angle that intersections can be off by and yet still be considered colinear. public static let maxIntersectionError = 1e-15 public /*private(set)*/ var vertices: [S2Point] /** Edge index used for performance-critical operations. For example, contains() can determine whether a point is inside a loop in nearly constant time, whereas without an edge index it is forced to compare the query point against every edge in the loop. */ private var index: S2LoopEdgeIndex! /// Maps each S2Point to its order in the loop, from 1 to numVertices. private var vertexToIndex: [S2Point: Int] = [:] /// The index (into "vertices") of the vertex that comes first in the total ordering of all vertices in this loop. fileprivate var firstLogicalVertex: Int = 0 private var bound: S2LatLngRect = .full private var originInside: Bool = false /** The depth of a loop is defined as its nesting level within its containing polygon. "Outer shell" loops have depth 0, holes within those loops have depth 1, shells within those holes have depth 2, etc. This field is only used by the S2Polygon implementation. */ public var depth: Int = 0 /** Initialize a loop connecting the given vertices. The last vertex is implicitly connected to the first. All points should be unit length. Loops must have at least 3 vertices. */ public init(vertices: [S2Point]) { self.vertices = vertices self.index = S2LoopEdgeIndex(loop: self) // if (debugMode) { // assert (isValid(vertices, DEFAULT_MAX_ADJACENT)); // } // initOrigin() must be called before InitBound() because the latter // function expects Contains() to work properly. initOrigin() initBound() initFirstLogicalVertex() initVertexToIndex() } /// Initialize a loop corresponding to the given cell. public init(cell: S2Cell) { self.init(cell: cell, bound: cell.rectBound) } /// Like the constructor above, but assumes that the cell's bounding rectangle has been precomputed. public init(cell: S2Cell, bound: S2LatLngRect) { self.bound = bound self.vertices = [cell.getVertex(0), cell.getVertex(1), cell.getVertex(2), cell.getVertex(3)] self.index = S2LoopEdgeIndex(loop: self) initOrigin() initFirstLogicalVertex() initVertexToIndex() } /// Return true if this loop represents a hole in its containing polygon. public var isHole: Bool { return (depth & 1) != 0 } /// The sign of a loop is -1 if the loop represents a hole in its containing polygon, and +1 otherwise. public var sign: Int { return isHole ? -1 : 1 } public var numVertices: Int { return vertices.count } /** For convenience, we make two entire copies of the vertex list available: vertex(n..2*n-1) is mapped to vertex(0..n-1), where n == numVertices(). */ public func vertex(_ i: Int) -> S2Point { return vertices[i >= vertices.count ? i - vertices.count : i] } /** Calculates firstLogicalVertex, the vertex in this loop that comes first in a total ordering of all vertices (by way of S2Point's compareTo function). */ private mutating func initFirstLogicalVertex() { var first = 0; for i in 1 ..< numVertices { if vertex(i) < vertex(first) { first = i } } firstLogicalVertex = first } private mutating func initVertexToIndex() { for i in 1 ..< numVertices { vertexToIndex[vertex(i)] = i } } /// Return true if the loop area is at most 2*Pi. public var isNormalized: Bool { // We allow a bit of error so that exact hemispheres are considered normalized. return area <= 2 * M_PI + 1e-14 } /// Invert the loop if necessary so that the area enclosed by the loop is at most 2*Pi. public mutating func normalize() { if !isNormalized { invert() } } /// Reverse the order of the loop vertices, effectively complementing the region represented by the loop. public mutating func invert() { let last = numVertices - 1 for i in (0 ... (last - 1) / 2).reversed() { // for (int i = (last - 1) / 2; i >= 0; --i) { let t = vertices[i] vertices[i] = vertices[last - i] vertices[last - i] = t } vertexToIndex = [:] index = S2LoopEdgeIndex(loop: self) originInside = !originInside if bound.lat.lo > -M_PI_2 && bound.lat.hi < M_PI_2 { // The complement of this loop contains both poles. bound = .full } else { initBound() } initFirstLogicalVertex() initVertexToIndex() } public var inverted: S2Loop { var tmp = self tmp.invert() return tmp } /// Helper method to get area and optionally centroid. private func getAreaCentroid(doCentroid: Bool = true) -> S2AreaCentroid { var centroid = S2Point() // Don't crash even if loop is not well-defined. if numVertices < 3 { return S2AreaCentroid(area: 0, centroid: centroid) } // The triangle area calculation becomes numerically unstable as the length // of any edge approaches 180 degrees. However, a loop may contain vertices // that are 180 degrees apart and still be valid, e.g. a loop that defines // the northern hemisphere using four points. We handle this case by using // triangles centered around an origin that is slightly displaced from the // first vertex. The amount of displacement is enough to get plenty of // accuracy for antipodal points, but small enough so that we still get // accurate areas for very tiny triangles. // // Of course, if the loop contains a point that is exactly antipodal from // our slightly displaced vertex, the area will still be unstable, but we // expect this case to be very unlikely (i.e. a polygon with two vertices on // opposite sides of the Earth with one of them displaced by about 2mm in // exactly the right direction). Note that the approximate point resolution // using the E7 or S2CellId representation is only about 1cm. var origin = vertex(0) let axis = (origin.largestAbsComponent + 1) % 3 let slightlyDisplaced = origin.get(axis: axis) + M_E * 1e-10 origin = S2Point(x: (axis == 0) ? slightlyDisplaced : origin.x, y: (axis == 1) ? slightlyDisplaced : origin.y, z: (axis == 2) ? slightlyDisplaced : origin.z) origin = S2Point.normalize(point: origin) var areaSum: Double = 0 var centroidSum = S2Point() for i in 1 ... numVertices { areaSum += S2.signedArea(a: origin, b: vertex(i - 1), c: vertex(i)); if doCentroid { // The true centroid is already premultiplied by the triangle area. let trueCentroid = S2.trueCentroid(a: origin, b: vertex(i - 1), c: vertex(i)) centroidSum = centroidSum + trueCentroid } } // The calculated area at this point should be between -4*Pi and 4*Pi, // although it may be slightly larger or smaller than this due to // numerical errors. // assert (Math.abs(areaSum) <= 4 * S2.M_PI + 1e-12); if (areaSum < 0) { // If the area is negative, we have computed the area to the right of the // loop. The area to the left is 4*Pi - (-area). Amazingly, the centroid // does not need to be changed, since it is the negative of the integral // of position over the region to the right of the loop. This is the same // as the integral of position over the region to the left of the loop, // since the integral of position over the entire sphere is (0, 0, 0). areaSum += 4 * M_PI } // The loop's sign() does not affect the return result and should be taken // into account by the caller. if doCentroid { centroid = centroidSum } return S2AreaCentroid(area: areaSum, centroid: centroid) } /** Return the area of the loop interior, i.e. the region on the left side of the loop. The return value is between 0 and 4*Pi and the true centroid of the loop multiplied by the area of the loop (see S2.java for details on centroids). Note that the centroid may not be contained by the loop. */ public var areaAndCentroid: S2AreaCentroid { return getAreaCentroid() } /** Return the area of the polygon interior, i.e. the region on the left side of an odd number of loops. The return value is between 0 and 4*Pi. */ public var area: Double { return getAreaCentroid(doCentroid: false).area } /** Return the true centroid of the polygon multiplied by the area of the polygon (see {@link S2} for details on centroids). Note that the centroid may not be contained by the polygon. */ public var centroid: S2Point { return getAreaCentroid().centroid } // The following are the possible relationships between two loops A and B: // // (1) A and B do not intersect. // (2) A contains B. // (3) B contains A. // (4) The boundaries of A and B cross (i.e. the boundary of A // intersects the interior and exterior of B and vice versa). // (5) (A union B) is the entire sphere (i.e. A contains the // complement of B and vice versa). // // More than one of these may be true at the same time, for example if // A == B or A == Complement(B). /// Return true if the region contained by this loop is a superset of the region contained by the given other loop. public func contains(other b: S2Loop) -> Bool { // For this loop A to contains the given loop B, all of the following must // be true: // // (1) There are no edge crossings between A and B except at vertices. // // (2) At every vertex that is shared between A and B, the local edge // ordering implies that A contains B. // // (3) If there are no shared vertices, then A must contain a vertex of B // and B must not contain a vertex of A. (An arbitrary vertex may be // chosen in each case.) // // The second part of (3) is necessary to detect the case of two loops whose // union is the entire sphere, i.e. two loops that contains each other's // boundaries but not each other's interiors. if (!bound.contains(other: b.rectBound)) { return false } // Unless there are shared vertices, we need to check whether A contains a // vertex of B. Since shared vertices are rare, it is more efficient to do // this test up front as a quick rejection test. if (!contains(point: b.vertex(0)) && findVertex(point: b.vertex(0)) < 0) { return false } // Now check whether there are any edge crossings, and also check the loop // relationship at any shared vertices. if (checkEdgeCrossings(b: b, relation: WedgeContains.self) <= 0) { return false } // At this point we know that the boundaries of A and B do not intersect, // and that A contains a vertex of B. However we still need to check for // the case mentioned above, where (A union B) is the entire sphere. // Normally this check is very cheap due to the bounding box precondition. if bound.union(with: b.rectBound).isFull { if b.contains(point: vertex(0)) && b.findVertex(point: vertex(0)) < 0 { return false } } return true } /// Return true if the region contained by this loop intersects the region contained by the given other loop. public func intersects(with b: S2Loop) -> Bool { // a->Intersects(b) if and only if !a->Complement()->Contains(b). // This code is similar to Contains(), but is optimized for the case // where both loops enclose less than half of the sphere. if !bound.intersects(with: b.rectBound) { return false } // Normalize the arguments so that B has a smaller longitude span than A. // This makes intersection tests much more efficient in the case where // longitude pruning is used (see CheckEdgeCrossings). if b.rectBound.lng.length > bound.lng.length { return b.intersects(with: self) } // Unless there are shared vertices, we need to check whether A contains a // vertex of B. Since shared vertices are rare, it is more efficient to do // this test up front as a quick acceptance test. if (contains(point: b.vertex(0)) && findVertex(point: b.vertex(0)) < 0) { return true } // Now check whether there are any edge crossings, and also check the loop // relationship at any shared vertices. if (checkEdgeCrossings(b: b, relation: WedgeIntersects.self) < 0) { return true } // We know that A does not contain a vertex of B, and that there are no edge // crossings. Therefore the only way that A can intersect B is if B // entirely contains A. We can check this by testing whether B contains an // arbitrary non-shared vertex of A. Note that this check is cheap because // of the bounding box precondition and the fact that we normalized the // arguments so that A's longitude span is at least as long as B's. if b.rectBound.contains(other: bound) { if b.contains(point: vertex(0)) && b.findVertex(point: vertex(0)) < 0 { return true } } return false } /** Given two loops of a polygon, return true if A contains B. This version of contains() is much cheaper since it does not need to check whether the boundaries of the two loops cross. */ public func containsNested(other b: S2Loop) -> Bool { if !bound.contains(other: b.rectBound) { return false } // We are given that A and B do not share any edges, and that either one // loop contains the other or they do not intersect. let m = findVertex(point: b.vertex(1)) if m < 0 { // Since b->vertex(1) is not shared, we can check whether A contains it. return contains(point: b.vertex(1)) } // Check whether the edge order around b->vertex(1) is compatible with // A containin B. return WedgeContains.test(a0: vertex(m - 1), ab1: vertex(m), a2: vertex(m + 1), b0: b.vertex(0), b2: b.vertex(2)) > 0 } /** Return +1 if A contains B (i.e. the interior of B is a subset of the interior of A), -1 if the boundaries of A and B cross, and 0 otherwise. Requires that A does not properly contain the complement of B, i.e. A and B do not contain each other's boundaries. This method is used for testing whether multi-loop polygons contain each other. */ public func containsOrCrosses(other b: S2Loop) -> Int { // There can be containment or crossing only if the bounds intersect. if !bound.intersects(with: b.rectBound) { return 0 } // Now check whether there are any edge crossings, and also check the loop // relationship at any shared vertices. Note that unlike Contains() or // Intersects(), we can't do a point containment test as a shortcut because // we need to detect whether there are any edge crossings. let result = checkEdgeCrossings(b: b, relation: WedgeContainsOrCrosses.self) // If there was an edge crossing or a shared vertex, we know the result // already. (This is true even if the result is 1, but since we don't // bother keeping track of whether a shared vertex was seen, we handle this // case below.) if result <= 0 { return result } // At this point we know that the boundaries do not intersect, and we are // given that (A union B) is a proper subset of the sphere. Furthermore // either A contains B, or there are no shared vertices (due to the check // above). So now we just need to distinguish the case where A contains B // from the case where B contains A or the two loops are disjoint. if !bound.contains(other: b.rectBound) { return 0 } if !contains(point: b.vertex(0)) && findVertex(point: b.vertex(0)) < 0 { return 0 } return 1 } /** Returns true if two loops have the same boundary except for vertex perturbations. More precisely, the vertices in the two loops must be in the same cyclic order, and corresponding vertex pairs must be separated by no more than maxError. Note: This method mostly useful only for testing purposes. */ internal func boundaryApproxEquals(boundary b: S2Loop, maxError: Double) -> Bool { if numVertices != b.numVertices { return false } let maxVertices = numVertices var iThis = firstLogicalVertex var iOther = b.firstLogicalVertex for _ in 0 ..< maxVertices { if !S2.approxEquals(vertex(iThis), b.vertex(iOther), maxError: maxError) { return false } iThis += 1 iOther += 1 } return true } /// The point 'p' does not need to be normalized. public func contains(point p: S2Point) -> Bool { if !bound.contains(point: p) { return false } var inside = originInside let origin = S2.origin var crosser = EdgeCrosser(a: origin, b: p, c: vertices[numVertices - 1]) // The s2edgeindex library is not optimized yet for long edges, // so the tradeoff to using it comes with larger loops. if numVertices < 2000 { for i in 0 ..< numVertices { inside = inside != crosser.edgeOrVertexCrossing(point: vertices[i]) } } else { var previousIndex = -2 var it = getEdgeIterator(expectedQueries: numVertices) it.getCandidates(a: origin, b: p) for ai in it { if previousIndex != ai - 1 { crosser.restartAt(point: vertices[ai]) } previousIndex = ai inside = inside != crosser.edgeOrVertexCrossing(point: vertex(ai + 1)) } } return inside } /** Returns the shortest distance from a point P to this loop, given as the angle formed between P, the origin and the nearest point on the loop to P. This angle in radians is equivalent to the arclength along the unit sphere. */ public func getDistance(to p: S2Point) -> S1Angle { let normalized = S2Point.normalize(point: p) // The furthest point from p on the sphere is its antipode, which is an // angle of PI radians. This is an upper bound on the angle. var minDistance = S1Angle(radians: M_PI) for i in 0 ..< numVertices { minDistance = min(minDistance, S2EdgeUtil.getDistance(x: normalized, a: vertex(i), b: vertex(i + 1))) } return minDistance } /** Creates an edge index over the vertices, which by itself takes no time. Then the expected number of queries is used to determine whether brute force lookups are likely to be slower than really creating an index, and if so, we do so. Finally an iterator is returned that can be used to perform edge lookups. */ private func getEdgeIterator(expectedQueries: Int) -> S2EdgeIndex.DataEdgeIterator { index.predictAdditionalCalls(n: expectedQueries) return S2EdgeIndex.DataEdgeIterator(edgeIndex: index) } /// Return true if this loop is valid. public var isValid: Bool { if numVertices < 3 { // log.info("Degenerate loop"); return false } // All vertices must be unit length. for i in 0 ..< numVertices { if !S2.isUnitLength(point: vertex(i)) { // log.info("Vertex " + i + " is not unit length"); return false } } // Loops are not allowed to have any duplicate vertices. var vmap: Set<S2Point> = [] for i in 0 ..< numVertices { if !vmap.insert(vertex(i)).inserted { // log.info("Duplicate vertices: " + previousVertexIndex + " and " + i); return false } } // Non-adjacent edges are not allowed to intersect. var crosses = false var it = getEdgeIterator(expectedQueries: numVertices) for a1 in 0 ..< numVertices { let a2 = (a1 + 1) % numVertices var crosser = EdgeCrosser(a: vertex(a1), b: vertex(a2), c: vertex(0)) var previousIndex = -2 it.getCandidates(a: vertex(a1), b: vertex(a2)) for b1 in it { let b2 = (b1 + 1) % numVertices // If either 'a' index equals either 'b' index, then these two edges // share a vertex. If a1==b1 then it must be the case that a2==b2, e.g. // the two edges are the same. In that case, we skip the test, since we // don't want to test an edge against itself. If a1==b2 or b1==a2 then // we have one edge ending at the start of the other, or in other words, // the edges share a vertex -- and in S2 space, where edges are always // great circle segments on a sphere, edges can only intersect at most // once, so we don't need to do further checks in that case either. if (a1 != b2 && a2 != b1 && a1 != b1) { // WORKAROUND(shakusa, ericv): S2.robustCCW() currently // requires arbitrary-precision arithmetic to be truly robust. That // means it can give the wrong answers in cases where we are trying // to determine edge intersections. The workaround is to ignore // intersections between edge pairs where all four points are // nearly colinear. let abc = S2.angle(a: vertex(a1), b: vertex(a2), c: vertex(b1)) let abcNearlyLinear = S2.approxEquals(abc, 0, maxError: S2Loop.maxIntersectionError) || S2.approxEquals(abc, M_PI, maxError: S2Loop.maxIntersectionError) let abd = S2.angle(a: vertex(a1), b: vertex(a2), c: vertex(b2)); let abdNearlyLinear = S2.approxEquals(abd, 0, maxError: S2Loop.maxIntersectionError) || S2.approxEquals(abd, M_PI, maxError: S2Loop.maxIntersectionError) if abcNearlyLinear && abdNearlyLinear { continue } if previousIndex != b1 { crosser.restartAt(point: vertex(b1)) } // Beware, this may return the loop is valid if there is a // "vertex crossing". // TODO(user): Fix that. crosses = crosser.robustCrossing(point: vertex(b2)) > 0 previousIndex = b2; if crosses { // log.info("Edges " + a1 + " and " + b1 + " cross"); // log.info(String.format("Edge locations in degrees: " + "%s-%s and %s-%s", // new S2LatLng(vertex(a1)).toStringDegrees(), // new S2LatLng(vertex(a2)).toStringDegrees(), // new S2LatLng(vertex(b1)).toStringDegrees(), // new S2LatLng(vertex(b2)).toStringDegrees())); return false } } } } return true } private mutating func initOrigin() { // The bounding box does not need to be correct before calling this // function, but it must at least contain vertex(1) since we need to // do a Contains() test on this point below. precondition(bound.contains(point: vertex(1))) // To ensure that every point is contained in exactly one face of a // subdivision of the sphere, all containment tests are done by counting the // edge crossings starting at a fixed point on the sphere (S2::Origin()). // We need to know whether this point is inside or outside of the loop. // We do this by first guessing that it is outside, and then seeing whether // we get the correct containment result for vertex 1. If the result is // incorrect, the origin must be inside the loop. // // A loop with consecutive vertices A,B,C contains vertex B if and only if // the fixed vector R = S2::Ortho(B) is on the left side of the wedge ABC. // The test below is written so that B is inside if C=R but not if A=R. originInside = false // Initialize before calling Contains(). let v1Inside = S2.orderedCCW(a: vertex(1).ortho, b: vertex(0), c: vertex(2), o: vertex(1)) if v1Inside != contains(point: vertex(1)) { originInside = true } } private mutating func initBound() { // The bounding rectangle of a loop is not necessarily the same as the // bounding rectangle of its vertices. First, the loop may wrap entirely // around the sphere (e.g. a loop that defines two revolutions of a // candy-cane stripe). Second, the loop may include one or both poles. // Note that a small clockwise loop near the equator contains both poles. var bounder = RectBounder() for i in 0 ... numVertices { bounder.add(point: vertex(i)) } var b = bounder.bound // Note that we need to initialize bound with a temporary value since // contains() does a bounding rectangle check before doing anything else. bound = .full if contains(point: S2Point(x: 0, y: 0, z: 1)) { b = S2LatLngRect(lat: R1Interval(lo: b.lat.lo, hi: M_PI_2), lng: .full) } // If a loop contains the south pole, then either it wraps entirely // around the sphere (full longitude range), or it also contains the // north pole in which case b.lng().isFull() due to the test above. if b.lng.isFull && contains(point: S2Point(x: 0, y: 0, z: -1)) { b = S2LatLngRect(lat: R1Interval(lo: -M_PI_2, hi: b.lat.hi), lng: b.lng) } bound = b } /** Return the index of a vertex at point "p", or -1 if not found. The return value is in the range 1..num_vertices_ if found. */ private func findVertex(point p: S2Point) -> Int { return vertexToIndex[p] ?? -1 } /** This method encapsulates the common code for loop containment and intersection tests. It is used in three slightly different variations to implement contains(), intersects(), and containsOrCrosses(). In a nutshell, this method checks all the edges of this loop (A) for intersection with all the edges of B. It returns -1 immediately if any edge intersections are found. Otherwise, if there are any shared vertices, it returns the minimum value of the given WedgeRelation for all such vertices (returning immediately if any wedge returns -1). Returns +1 if there are no intersections and no shared vertices. */ private func checkEdgeCrossings(b: S2Loop, relation: WedgeRelation.Type) -> Int { var it = getEdgeIterator(expectedQueries: b.numVertices) var result = 1 // since 'this' usually has many more vertices than 'b', use the index on // 'this' and loop over 'b' for j in 0 ..< b.numVertices { var crosser = EdgeCrosser(a: b.vertex(j), b: b.vertex(j + 1), c: vertex(0)) var previousIndex = -2 it.getCandidates(a: b.vertex(j), b: b.vertex(j + 1)) for i in it { if previousIndex != i - 1 { crosser.restartAt(point: vertex(i)) } previousIndex = i let crossing = crosser.robustCrossing(point: vertex(i + 1)) if crossing < 0 { continue } if crossing > 0 { return -1 } // There is a proper edge crossing. if vertex(i + 1) == (b.vertex(j + 1)) { result = min(result, relation.test(a0: vertex(i), ab1: vertex(i + 1), a2: vertex(i + 2), b0: b.vertex(j), b2: b.vertex(j + 2))) if result < 0 { return result } } } } return result } //////////////////////////////////////////////////////////////////////// // MARK: S2Region //////////////////////////////////////////////////////////////////////// /// Return a bounding spherical cap. public var capBound: S2Cap { return bound.capBound } /// Return a bounding latitude-longitude rectangle. public var rectBound: S2LatLngRect { return bound } /** If this method returns true, the region completely contains the given cell. Otherwise, either the region does not contain the cell or the containment relationship could not be determined. */ public func contains(cell: S2Cell) -> Bool { // It is faster to construct a bounding rectangle for an S2Cell than for // a general polygon. A future optimization could also take advantage of // the fact than an S2Cell is convex. let cellBound = cell.rectBound if !bound.contains(other: cellBound) { return false } let cellLoop = S2Loop(cell: cell, bound: cellBound) return contains(other: cellLoop) } /** If this method returns false, the region does not intersect the given cell. Otherwise, either region intersects the cell, or the intersection relationship could not be determined. */ public func mayIntersect(cell: S2Cell) -> Bool { // It is faster to construct a bounding rectangle for an S2Cell than for // a general polygon. A future optimization could also take advantage of // the fact than an S2Cell is convex. let cellBound = cell.rectBound if !bound.intersects(with: cellBound) { return false } let cellLoop = S2Loop(cell: cell, bound: cellBound) return cellLoop.intersects(with: self) } } public func ==(lhs: S2Loop, rhs: S2Loop) -> Bool { guard lhs.numVertices == rhs.numVertices else { return false } // Compare the two loops' vertices, starting with each loop's // firstLogicalVertex. This allows us to always catch cases where logically // identical loops have different vertex orderings (e.g. ABCD and BCDA). let maxVertices = lhs.numVertices var iThis = lhs.firstLogicalVertex var iOther = rhs.firstLogicalVertex for _ in 0 ..< maxVertices { if lhs.vertex(iThis) != rhs.vertex(iOther) { return false } iThis += 1 iOther += 1 } return true } public func <(lhs: S2Loop, rhs: S2Loop) -> Bool { if lhs.numVertices != rhs.numVertices { return lhs.numVertices < rhs.numVertices } // Compare the two loops' vertices, starting with each loop's // firstLogicalVertex. This allows us to always catch cases where logically // identical loops have different vertex orderings (e.g. ABCD and BCDA). let maxVertices = lhs.numVertices var iThis = lhs.firstLogicalVertex var iOther = rhs.firstLogicalVertex for _ in 0 ..< maxVertices { if lhs.vertex(iThis) != rhs.vertex(iOther) { return lhs.vertex(iThis) < rhs.vertex(iOther) } iThis += 1 iOther += 1 } return false }
19b14e5553d00a04bdc19c9421c71574
37.369898
159
0.692806
false
false
false
false
alobanov/ALFormBuilder
refs/heads/master
FormBuilder/RxViewController.swift
mit
1
// // RxViewController.swift // ALFormBuilder // // Created by Lobanov Aleksey on 27/10/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources class RxViewController: UIViewController, UITableViewDelegate { var bag = DisposeBag() var fb: RxALFormBuilderProtocol! let logger = Atlantis.Logger() // IBOutlet & UI @IBOutlet weak var tableView: UITableView! var testBtn: UIBarButtonItem = { return UIBarButtonItem(title: "Test", style: .plain, target: nil, action: nil) }() override func viewDidLoad() { super.viewDidLoad() // let d = BoolVvv(value: false) // d.change(originalValue: true) // logger.debug("first = \(d.transformForDisplay())") // d.change(originalValue: false) // logger.debug("first = \(d.transformForDisplay())") // Do any additional setup after loading the view. self.configureUI() self.configureTable() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureTable() { self.fb = RxALFormBuilder(compositeFormData: AuthFormDirector.build(), jsonBuilder: ALFormJSONBuilder(predefinedObject: [:])) let datasource = BehaviorSubject<[RxSectionModel]>(value: []) fb.rxDidChangeFormModel.subscribe(onNext: { [weak self] item in if let p = item as? RowCompositeValueTransformable { print("something change in \(item.identifier) to: \(p.value.transformForDisplay() ?? "")") } self?.logger.debug(self?.fb.object(withoutNull: false) ?? [:]) }).disposed(by: bag) fb.rxDidDatasource.bind(to: datasource).disposed(by: bag) fb.rxDidChangeFormState.subscribe(onNext: { isChange in print("something change in all form to: \(isChange)") }).disposed(by: bag) fb.rxDidChangeCompletelyValidation.subscribe(onNext: { [weak self] state in print("all form completely valid: \(state)") self?.testBtn.isEnabled = state }).disposed(by: bag) // fb.didChangeFormModel = { item in // datasource.onNext(FormBuilder.buildRxDataSource(item: item)) // } // // fb.didChangeFormState = { state in // print("something change in all form to: \(state)") // } // // fb.didChangeCompletelyValidation = { state in // print("all form completely valid: \(state)") // } self.fb.prepareDatasource() // Table view let rxDataSource = RxTableViewSectionedAnimatedDataSource<RxSectionModel>() rxDataSource.configureCell = { [weak self] (dataSource, table, idxPath, _) in var item: RxSectionItemModel do { item = try dataSource.model(at: idxPath) as! RxSectionItemModel } catch { return UITableViewCell() } let cellType = item.model.cellType.type let cell = table.dequeueReusableTableCell(forIndexPath: idxPath, andtype: cellType) if let c = cell as? RxCellReloadeble { c.reload(with: item.model) } if var c = cell as? TableReloadable { c.reload = { _ in guard let sSelf = self else { return } let currentOffset = sSelf.tableView.contentOffset sSelf.tableView.beginUpdates() sSelf.tableView.endUpdates() sSelf.tableView.setContentOffset(currentOffset, animated: false) } } cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } rxDataSource.animationConfiguration = AnimationConfiguration(insertAnimation: .fade, reloadAnimation: .none, deleteAnimation: .fade) tableView.rx.setDelegate(self) .disposed(by: bag) tableView.rx.modelSelected(RxSectionItemModel.self).asObservable().subscribe(onNext: { [weak self] model in guard let item = model.model as? RowFormTextComposite else { return } // if let m = self.fb.model(by: "int") as? RowFormTextCompositeOutput { // m.updateAndReload(value: ALIntValue(value: 23)) // } // // if let m = self.fb.model(by: "decimal") as? RowFormTextCompositeOutput { // m.updateAndReload(value: ALFloatValue(value: 23.4)) // } if item.identifier == "Town" { item.updateAndReload(value: ALTitledValue(value: ALTitledTuple("Екатеринбург", 23))) let vc = UIViewController() self?.navigationController?.pushViewController(vc, animated: true) } }).disposed(by: bag) rxDataSource.titleForHeaderInSection = { ds, index in return ds.sectionModels[index].model.header } rxDataSource.titleForFooterInSection = { ds, index in return ds.sectionModels[index].model.footer } datasource .bind(to: tableView.rx.items(dataSource: rxDataSource)) .disposed(by: bag) testBtn.rx.tap .subscribe(onNext: { [weak self] in if let model = self?.fb.model(by: "Town") as? RowFormTextComposite { model.visualisation.detailsText = "Description changed" model.updateAndReload(value: model.value) } }).disposed(by: bag) } func configureUI() { tableView.setupEstimatedRowHeight() tableView.registerCells(by: [ALFBTextViewCell.cellIdentifier, ALFBButtonViewCell.cellIdentifier, ALFBBoolViewCell.cellIdentifier, ALFBPickerViewCell.cellIdentifier, ALFBStaticTextViewCell.cellIdentifier, ALFBPhoneViewCell.cellIdentifier, ALFBHtmlTextViewCell.cellIdentifier], bundle: Bundle.alfb_frameworkBundle()) tableView.registerCells(by: [ALFBTextMultilineViewCell.cellIdentifier]) navigationItem.rightBarButtonItem = testBtn } deinit { print("RxViewController dead") } }
bcaaf3b7b337dd40dd96afb9e0107eef
31.812155
111
0.648426
false
false
false
false
tottakai/RxSwift
refs/heads/develop
Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift
mit
1
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-macOS** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift playgroundShouldContinueIndefinitely() /*: ## Connectable Operators Connectable `Observable` sequences resembles ordinary `Observable` sequences, except that they not begin emitting elements when subscribed to, but instead, only when their `connect()` method is called. In this way, you can wait for all intended subscribers to subscribe to a connectable `Observable` sequence before it begins emitting elements. > Within each example on this page is a commented-out method. Uncomment that method to run the example, and then comment it out again to stop running the example. # Before learning about connectable operators, let's take a look at an example of a non-connectable operator: */ func sampleWithoutConnectableOperators() { printExampleHeader(#function) let interval = Observable<Int>.interval(1, scheduler: MainScheduler.instance) _ = interval .subscribe(onNext: { print("Subscription: 1, Event: \($0)") }) delay(5) { _ = interval .subscribe(onNext: { print("Subscription: 2, Event: \($0)") }) } } //sampleWithoutConnectableOperators() // ⚠️ Uncomment to run this example; comment to stop running /*: > `interval` creates an `Observable` sequence that emits elements after each `period`, on the specified scheduler. [More info](http://reactivex.io/documentation/operators/interval.html) ![](http://reactivex.io/documentation/operators/images/interval.c.png) ---- ## `publish` Converts the source `Observable` sequence into a connectable sequence. [More info](http://reactivex.io/documentation/operators/publish.html) ![](http://reactivex.io/documentation/operators/images/publishConnect.c.png) */ func sampleWithPublish() { printExampleHeader(#function) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .publish() _ = intSequence .subscribe(onNext: { print("Subscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("Subscription 2:, Event: \($0)") }) } delay(6) { _ = intSequence .subscribe(onNext: { print("Subscription 3:, Event: \($0)") }) } } //sampleWithPublish() // ⚠️ Uncomment to run this example; comment to stop running //: > Schedulers are an abstraction of mechanisms for performing work, such as on specific threads or dispatch queues. [More info](https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Schedulers.md) /*: ---- ## `replay` Converts the source `Observable` sequence into a connectable sequence, and will replay `bufferSize` number of previous emissions to each new subscriber. [More info](http://reactivex.io/documentation/operators/replay.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replay.png) */ func sampleWithReplayBuffer() { printExampleHeader(#function) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .replay(5) _ = intSequence .subscribe(onNext: { print("Subscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("Subscription 2:, Event: \($0)") }) } delay(8) { _ = intSequence .subscribe(onNext: { print("Subscription 3:, Event: \($0)") }) } } // sampleWithReplayBuffer() // ⚠️ Uncomment to run this example; comment to stop running /*: ---- ## `multicast` Converts the source `Observable` sequence into a connectable sequence, and broadcasts its emissions via the specified `subject`. */ func sampleWithMulticast() { printExampleHeader(#function) let subject = PublishSubject<Int>() _ = subject .subscribe(onNext: { print("Subject: \($0)") }) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .multicast(subject) _ = intSequence .subscribe(onNext: { print("\tSubscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("\tSubscription 2:, Event: \($0)") }) } delay(6) { _ = intSequence .subscribe(onNext: { print("\tSubscription 3:, Event: \($0)") }) } } //sampleWithMulticast() // ⚠️ Uncomment to run this example; comment to stop running //: [Next](@next) - [Table of Contents](Table_of_Contents)
efbcada67b62df4c5d7e5d519ba8c4ab
36.045113
345
0.658616
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornTime/Resources/SubtitleSettings.swift
gpl-3.0
1
import Foundation import UIKit class SubtitleSettings: NSObject, NSCoding { enum Size: Float { case small = 20.0 case medium = 16.0 case mediumLarge = 12.0 case large = 6.0 static let array = [small, medium, mediumLarge, large] var localizedString: String { switch self { case .small: return "Small".localized case .medium: return "Medium".localized case .mediumLarge: return "Medium Large".localized case .large: return "Large".localized } } } static var encodings: [String: String] { return [ "Universal (UTF-8)": "UTF-8", "Universal (UTF-16)": "UTF-16", "Universal (big endian UTF-16)": "UTF-16BE", "Universal (little endian UTF-16)": "UTF-16LE", "Universal Chinese (GB18030)": "GB18030", "Western European (Latin-1)": "ISO-8859-1", "Western European (Latin-9)": "ISO-8859-15", "Western European (Windows-1252)": "Windows-1252", "Western European (IBM 00850)": "IBM850", "Eastern European (Latin-2)": "ISO-8859-2", "Eastern European (Windows-1250)": "Windows-1250", "Esperanto (Latin-3)": "ISO-8859-3", "Nordic (Latin-6)": "ISO-8859-10", "Cyrillic (Windows-1251)": "Windows-1251", "Russian (KOI8-R)": "KOI8-R", "Ukrainian (KOI8-U)": "KOI8-U", "Arabic (ISO 8859-6)": "ISO-8859-6", "Arabic (Windows-1256)": "Windows-1256", "Greek (ISO 8859-7)": "ISO-8859-7", "Greek (Windows-1253)": "Windows-1253", "Hebrew (ISO 8859-8)": "ISO-8859-8", "Hebrew (Windows-1255)": "Windows-1255", "Turkish (ISO 8859-9)": "ISO-8859-9", "Turkish (Windows-1254)": "Windows-1254", "Thai (TIS 620-2533/ISO 8859-11)": "ISO-8859-11", "Thai (Windows-874)": "Windows-874", "Baltic (Latin-7)": "ISO-8859-13", "Baltic (Windows-1257)": "Windows-1257", "Celtic (Latin-8)": "ISO-8859-14", "South-Eastern European (Latin-10)": "ISO-8859-16", "Simplified Chinese (ISO-2022-CN-EXT)": "ISO-2022-CN-EXT", "Simplified Chinese Unix (EUC-CN)": "EUC-CN", "Japanese (7-bits JIS/ISO-2022-JP-2)": "ISO-2022-JP-2", "Japanese Unix (EUC-JP)": "EUC-JP", "Japanese (Shift JIS)": "Shift_JIS", "Korean (EUC-KR/CP949)": "CP949", "Korean (ISO-2022-KR)": "ISO-2022-KR", "Traditional Chinese (Big5)": "Big5", "Traditional Chinese Unix (EUC-TW)": "ISO-2022-TW", "Hong-Kong Supplementary (HKSCS)": "Big5-HKSCS", "Vietnamese (VISCII)": "VISCII", "Vietnamese (Windows-1258)": "Windows-1258" ] } var size: Size = .medium var color: UIColor = .white var encoding: String = "UTF-8" var language: String? = nil var font: UIFont = UIFont.systemFont(ofSize: CGFloat(Size.medium.rawValue)) var style: UIFont.Style = .normal var subtitlesSelectedForVideo: [Any] = Array() static let shared = SubtitleSettings() override init() { guard let codedData = UserDefaults.standard.data(forKey: "subtitleSettings"), let settings = NSKeyedUnarchiver.unarchiveObject(with: codedData) as? SubtitleSettings else { return } self.size = settings.size self.color = settings.color self.encoding = settings.encoding self.language = settings.language self.font = settings.font self.style = settings.style } func save() { subtitlesSelectedForVideo.removeAll() UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: self), forKey: "subtitleSettings") UserDefaults.standard.synchronize() } required init?(coder aDecoder: NSCoder) { guard let color = aDecoder.decodeObject(of: UIColor.self, forKey: "color"), let rawSize = aDecoder.decodeObject(forKey: "size") as? CGFloat, let size = Size(rawValue: Float(rawSize)), let encoding = aDecoder.decodeObject(of: NSString.self, forKey: "encoding") as String?, let descriptor = aDecoder.decodeObject(of: UIFontDescriptor.self, forKey: "font"), let rawValue = aDecoder.decodeObject(of: NSString.self, forKey: "style") as String?, let style = UIFont.Style(rawValue: rawValue) else { return nil } self.size = size self.color = color self.encoding = encoding self.language = aDecoder.decodeObject(of: NSString.self, forKey: "language") as String? self.font = UIFont(descriptor: descriptor, size: CGFloat(size.rawValue)) self.style = style } func encode(with aCoder: NSCoder) { aCoder.encode(CGFloat(size.rawValue), forKey: "size") aCoder.encode(color, forKey: "color") aCoder.encode(encoding, forKey: "encoding") aCoder.encode(language, forKey: "language") aCoder.encode(font.fontDescriptor, forKey: "font") aCoder.encode(style.rawValue, forKey: "style") } }
1e17a393cbe565b26a03c1320f3f3f5e
40.992126
188
0.570786
false
false
false
false
DrabWeb/Keijiban
refs/heads/master
Keijiban/Keijiban/KJ4CBoard.swift
gpl-3.0
1
// // KJ4CBoard.swift // Keijiban // // Created by Seth on 2016-05-28. // import Cocoa /// Represents a board on 4chan class KJ4CBoard: NSObject { /// The code for this board(a, g, jp, ETC.) var code : String = ""; /// The name of this board var name : String = ""; // Override the print output to be useful override var description : String { return "<Keijiban.KJ4CBoard: /\(code)/ - \(name)>"; } // Init with a code and name init(code : String, name : String) { super.init(); self.code = code; self.name = name; } // Blank init override init() { super.init(); self.code = ""; self.name = ""; } }
bba89125372b23794bb39df623c5f255
18.710526
59
0.514706
false
false
false
false
dclelland/HOWL
refs/heads/master
HOWL/View Controllers/Keyboard/Pitch.swift
mit
1
// // Pitch.swift // HOWL // // Created by Daniel Clelland on 22/05/16. // Copyright © 2016 Daniel Clelland. All rights reserved. // import Foundation struct Pitch { let number: Int init(number: Int) { self.number = number } // MARK: Helpers enum Note: Int { case c = 0 case cSharp = 1 case d = 2 case dSharp = 3 case e = 4 case f = 5 case fSharp = 6 case g = 7 case gSharp = 8 case a = 9 case aSharp = 10 case b = 11 } var note: Note { let mod = number % 12 if (mod < 0) { return Note(rawValue: 12 + mod)! } else { return Note(rawValue: mod)! } } var octave: Int { return number / 12 - 1 } var frequency: Float { return pow(2.0, Float(number - 69) / 12.0) * 440.0 } } // MARK: - Equatable extension Pitch: Equatable {} func ==(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.number == rhs.number } // MARK: - Comparable extension Pitch: Comparable {} func <(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.number < rhs.number } // MARK: - IntegerLiteralConvertible extension Pitch: ExpressibleByIntegerLiteral { init(integerLiteral: Int) { self.init(number: integerLiteral) } } // MARK: - CustomStringConvertible extension Pitch: CustomStringConvertible { var description: String { return note.description + String(octave) } } extension Pitch.Note: CustomStringConvertible { var description: String { switch self { case .c: return "C" case .cSharp: return "C#" case .d: return "D" case .dSharp: return "D#" case .e: return "E" case .f: return "F" case .fSharp: return "F#" case .g: return "G" case .gSharp: return "G#" case .a: return "A" case .aSharp: return "A#" case .b: return "B" } } }
834bccba5d9b8982a0a1f30979288ed0
17.7
58
0.524064
false
false
false
false
tripleCC/GanHuoCode
refs/heads/master
GanHuo/Views/Welfare/TPCPageViewCell.swift
mit
1
// // TPCPageViewCell.swift // GanHuo // // Created by tripleCC on 16/4/16. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit class TPCPageViewCell: UICollectionViewCell, NTTansitionWaterfallGridViewProtocol { @IBOutlet weak var scrollView: UIScrollView! var imageView: UIImageView! var imageURLString: String! { didSet { imageView.alpha = CGFloat(TPCConfiguration.imageAlpha) imageView.kf_setImageWithURL(NSURL(string: imageURLString)!, placeholderImage: UIImage(), optionsInfo: []) { (image, error, cacheType, imageURL) in self.setNeedsLayout() self.layoutIfNeeded() } } } override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } private func setupSubviews() { imageView = UIImageView() imageView.contentMode = UIViewContentMode.ScaleAspectFill addSubview(imageView) } override func layoutSubviews() { super.layoutSubviews() if let image = imageView.image { if image.size.width == 0 { return } let imageHeight = image.size.height * TPCScreenWidth / image.size.width imageView.frame = CGRectMake(0, 0, TPCScreenWidth, imageHeight) imageView.center = CGPoint(x: bounds.width * 0.5, y: bounds.height * 0.5) } } func snapShotForTransition() -> UIImageView! { guard imageView.image != nil else { return UIImageView() } let snapShotView = UIImageView(image: imageView.image) snapShotView.frame = imageView!.frame snapShotView.alpha = CGFloat(TPCConfiguration.imageAlpha) snapShotView.contentMode = UIViewContentMode.ScaleAspectFill snapShotView.clipsToBounds = true return snapShotView } }
dd3614db1adedfa99febcceb3c73b13e
30.507937
159
0.633249
false
false
false
false
plantain-00/demo-set
refs/heads/master
swift-demo/NewsCatcher/Ridge/Ridge/DocType.swift
mit
1
// // DocType.swift // Ridge // // Created by 姚耀 on 15/1/30. // Copyright (c) 2015年 姚耀. All rights reserved. // import Foundation public class DocType: Node { public var name: String public var declaration: String public init(name: String, declaration: String, depth: Int) { self.name = name self.declaration = declaration super.init(depth: depth) } public override func toString(formatting: Formatting, spaceNumber: Int = 4) -> String { if formatting == .None { return "<\(name)\(declaration)>" } return "<\(name)\(declaration)>\n" } }
3f836d6e68c3e0d501d533a26c4ee446
22.296296
91
0.605096
false
false
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/BaseTest/BaseTest/Closeure/ClosureSummary.swift
apache-2.0
1
// // ClosureSummary.swift // BaseTest // // Created by 邬勇鹏 on 2018/6/6. // Copyright © 2018年 raymond. All rights reserved. // import Foundation class ClosureSummary { var num: Int = 10; func TestClosureSummary() { let source = [1, 4, 2, 5, 3] } //MARK: 尾随闭包 @discardableResult func convertArrayToString(arr: Array<Int>, map: (Int)->String) -> String { var result: String = "" arr.forEach { result += map($0) } return result } // func convertArrayToString<T: NSNumber>(arr: Array<T>) -> String func convertArrayToString<T>(arr: Array<T>) -> String where T: NSNumber { return "" } //MARK: 引用捕捉 如果闭包中不改变值可能会使用值传递 func makeIncrementer(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } //MARK: 逃逸闭包 必须使用self. var escapingHandlers: [() -> Void] = [] func changeNumWithHandler(completionHandler: @escaping () -> Void) { print("do something....") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) { self.escapingHandlers.append(completionHandler) } } //MARK: 自动闭包autoclose func changeNumWithAutoHandler(num: Int, handler: @autoclosure () -> String) { print(handler()) } }
8d1d78a472b70e1e5d8476b31cceb4c9
24.101695
83
0.574612
false
false
false
false
segmentio/analytics-ios
refs/heads/master
SegmentTests/UserDefaultsStorageTest.swift
mit
1
// // UserDefaultsStorageTest.swift // Analytics // // Copyright © 2016 Segment. All rights reserved. // @testable import Segment import XCTest class UserDefaultsStorageTest : XCTestCase { var storage : UserDefaultsStorage! override func setUp() { super.setUp() storage = UserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: nil, crypto: nil) } override func tearDown() { super.tearDown() storage.resetAll() } func testPersistsAndLoadsData() { let dataIn = "segment".data(using: String.Encoding.utf8)! storage.setData(dataIn, forKey: "mydata") let dataOut = storage.data(forKey: "mydata") XCTAssertEqual(dataOut, dataIn) let strOut = String(data: dataOut!, encoding: .utf8) XCTAssertEqual(strOut, "segment") } func testPersistsAndLoadsString() { let str = "san francisco" storage.setString(str, forKey: "city") XCTAssertEqual(storage.string(forKey: "city"), str) storage.removeKey("city") XCTAssertNil(storage.string(forKey: "city")) } func testPersistsAndLoadsArray() { let array = [ "san francisco", "new york", "tallinn", ] storage.setArray(array, forKey: "cities") XCTAssertEqual(storage.array(forKey: "cities") as? Array<String>, array) storage.removeKey("cities") XCTAssertNil(storage.array(forKey: "cities")) } func testPersistsAndLoadsDictionary() { let dict = [ "san francisco": "tech", "new york": "finance", "paris": "fashion", ] storage.setDictionary(dict, forKey: "cityMap") XCTAssertEqual(storage.dictionary(forKey: "cityMap") as? Dictionary<String, String>, dict) storage.removeKey("cityMap") XCTAssertNil(storage.dictionary(forKey: "cityMap")) } func testShouldWorkWithCrypto() { let crypto = AES256Crypto(password: "thetrees") let s = UserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: nil, crypto: crypto) let dict = [ "san francisco": "tech", "new york": "finance", "paris": "fashion", ] s.setDictionary(dict, forKey: "cityMap") XCTAssertEqual(s.dictionary(forKey: "cityMap") as? Dictionary<String, String>, dict) s.removeKey("cityMap") XCTAssertNil(s.dictionary(forKey: "cityMap")) } func testShouldWorkWithNamespace() { let crypto = AES256Crypto(password: "thetrees") let s = UserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: "segment", crypto: crypto) let dict = [ "san francisco": "tech", "new york": "finance", "paris": "fashion", ] s.setDictionary(dict, forKey: "cityMap") XCTAssertEqual(s.dictionary(forKey: "cityMap") as? Dictionary<String, String>, dict) s.removeKey("cityMap") XCTAssertNil(s.dictionary(forKey: "cityMap")) } }
b6b94ec035f0ef2269fac48c3c596cd1
30.81
112
0.595096
false
true
false
false