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
mpatelCAS/MDAlamofireCheck
refs/heads/master
Pods/Alamofire/Source/Error.swift
mit
2
// Error.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. public struct Error { /// The domain used for creating all Alamofire errors. public static let Domain = "com.alamofire.error" /// The custom error codes generated by Alamofire. public enum Code: Int { case InputStreamReadFailed = -6000 case OutputStreamWriteFailed = -6001 case ContentTypeValidationFailed = -6002 case StatusCodeValidationFailed = -6003 case DataSerializationFailed = -6004 case StringSerializationFailed = -6005 case JSONSerializationFailed = -6006 case PropertyListSerializationFailed = -6007 } static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } }
2aad712b076632ba5a3dd7b6c49471e4
45.34
85
0.721623
false
false
false
false
apple/swift-driver
refs/heads/main
Sources/SwiftOptions/DriverKind.swift
apache-2.0
1
//===--------------- DriverKind.swift - Swift Driver Kind -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Describes which mode the driver is in. public enum DriverKind: String, CaseIterable { case interactive = "swift" case batch = "swiftc" } extension DriverKind { public var usage: String { switch self { case .interactive: return "swift" case .batch: return "swiftc" } } }
3ce86cf6a9d9ac3cb6c5b3fc018b17ae
28.678571
80
0.596871
false
false
false
false
rockgarden/swift_language
refs/heads/swift3
Playground/Design-Patterns.playground/Design-Patterns.playground/section-22.swift
mit
1
protocol PropertyObserver : class { func willChangePropertyName(propertyName:String, newPropertyValue:AnyObject?) func didChangePropertyName(propertyName:String, oldPropertyValue:AnyObject?) } class TestChambers { weak var observer:PropertyObserver? var testChamberNumber: Int = 0 { willSet(newValue) { observer?.willChangePropertyName("testChamberNumber", newPropertyValue:newValue) } didSet { observer?.didChangePropertyName("testChamberNumber", oldPropertyValue:oldValue) } } } class Observer : PropertyObserver { func willChangePropertyName(propertyName: String, newPropertyValue: AnyObject?) { if newPropertyValue as? Int == 1 { println("Okay. Look. We both said a lot of things that you're going to regret.") } } func didChangePropertyName(propertyName: String, oldPropertyValue: AnyObject?) { if oldPropertyValue as? Int == 0 { println("Sorry about the mess. I've really let the place go since you killed me.") } } }
95b15d6fce920fbbcd4efd14a9e1a421
32.65625
94
0.683086
false
true
false
false
codestergit/swift
refs/heads/master
test/SILGen/struct_resilience.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_struct // Resilient structs are always address-only // CHECK-LABEL: sil hidden @_T017struct_resilience26functionWithResilientTypes010resilient_A04SizeVAE_A2Ec1ftF : $@convention(thin) (@in Size, @owned @callee_owned (@in Size) -> @out Size) -> @out Size // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@in Size) -> @out Size): func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_T016resilient_struct4SizeV1wSifg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) // CHECK: [[FN:%.*]] = function_ref @_T016resilient_struct4SizeV1wSifs : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]]) s2.w = s.w // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_T016resilient_struct4SizeV1hSifg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: [[COPIED_CLOSURE:%.*]] = copy_value %2 // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: apply [[COPIED_CLOSURE]](%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // Use materializeForSet for inout access of properties in resilient structs // from a different resilience domain func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden @_T017struct_resilience18resilientInOutTesty0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> () func resilientInOutTest(_ s: inout Size) { // CHECK: function_ref @_T017struct_resilience9inoutFuncySizF // CHECK: function_ref @_T016resilient_struct4SizeV1wSifm inoutFunc(&s.w) // CHECK: return } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden @_T017struct_resilience28functionWithFixedLayoutTypes010resilient_A05PointVAE_A2Ec1ftF : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point): func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[COPIED_CLOSURE:%.*]] = copy_value %1 // CHECK: [[NEW_POINT:%.*]] = apply [[COPIED_CLOSURE]](%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden @_T017struct_resilience39functionWithFixedLayoutOfResilientTypes010resilient_A09RectangleVAE_A2Ec1ftF : $@convention(thin) (@in Rectangle, @owned @callee_owned (@in Rectangle) -> @out Rectangle) -> @out Rectangle // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@in Rectangle) -> @out Rectangle): func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil @_T017struct_resilience6MySizeV10expirationSifgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_T017struct_resilience6MySizeV10expirationSifsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_T017struct_resilience6MySizeV10expirationSifmZ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1dSifg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1dSifs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1dSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1wSifg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1wSifs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1wSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var w: Int // Read-only instance stored property // CHECK-LABEL: sil @_T017struct_resilience6MySizeV1hSifg : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Static stored property // CHECK-LABEL: sil @_T017struct_resilience6MySizeV9copyrightSifgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_T017struct_resilience6MySizeV9copyrightSifsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_T017struct_resilience6MySizeV9copyrightSifmZ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var copyright: Int = 0 } // CHECK-LABEL: sil @_T017struct_resilience28functionWithMyResilientTypesAA0E4SizeVAD_A2Dc1ftF : $@convention(thin) (@in MySize, @owned @callee_owned (@in MySize) -> @out MySize) -> @out MySize public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [trivial] [[SRC_ADDR]] : $*Int // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [trivial] [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow %2 // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize // CHECK: apply [[CLOSURE_COPY]](%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience25publicTransparentFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int @_transparent public func publicTransparentFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @_T017struct_resilience6MySizeV1wSifg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience30publicTransparentLocalFunctionSiycAA6MySizeVF : $@convention(thin) (@in MySize) -> @owned @callee_owned () -> Int @_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int { // CHECK-LABEL: sil shared [serialized] @_T017struct_resilience30publicTransparentLocalFunctionSiycAA6MySizeVFSiycfU_ : $@convention(thin) (@owned { var MySize }) -> Int // CHECK: function_ref @_T017struct_resilience6MySizeV1wSifg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK: return {{.*}} : $Int return { s.w } } // CHECK-LABEL: sil hidden [transparent] @_T017struct_resilience27internalTransparentFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int // CHECK: bb0([[ARG:%.*]] : $*MySize): @_transparent func internalTransparentFunction(_ s: MySize) -> Int { // The body of an internal transparent function will not be inlined into // other resilience domains, so we can access storage directly // CHECK: [[W_ADDR:%.*]] = struct_element_addr [[ARG]] : $*MySize, #MySize.w // CHECK-NEXT: [[RESULT:%.*]] = load [trivial] [[W_ADDR]] : $*Int // CHECK-NEXT: destroy_addr [[ARG]] // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [serialized] [always_inline] @_T017struct_resilience26publicInlineAlwaysFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int @inline(__always) public func publicInlineAlwaysFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @_T017struct_resilience6MySizeV1wSifg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // Make sure that @_versioned entities can be resilient @_versioned struct VersionedResilientStruct { @_versioned let x: Int @_versioned let y: Int @_versioned init(x: Int, y: Int) { self.x = x self.y = y } } // CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience27useVersionedResilientStructAA0deF0VADF : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct @_versioned @_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct) -> VersionedResilientStruct { // CHECK: function_ref @_T017struct_resilience24VersionedResilientStructVACSi1x_Si1ytcfC // CHECK: function_ref @_T017struct_resilience24VersionedResilientStructV1ySifg // CHECK: function_ref @_T017struct_resilience24VersionedResilientStructV1xSifg return VersionedResilientStruct(x: s.y, y: s.x) }
244d0070b563d6ccfb7b95a721548a73
46.273859
239
0.672782
false
false
false
false
safx/MioDashboard-swift
refs/heads/swift-2
MioDashboard-swift/RootViewController.swift
mit
1
// // RootViewController.swift // MioDashboard-swift // // Created by Safx Developer on 2015/05/17. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import UIKit import IIJMioKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dataDidLoad() { pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) pageViewController!.delegate = self let startingViewController: DataViewController = modelController.viewControllerAtIndex(0, storyboard: storyboard!)! let viewControllers = [startingViewController] pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) pageViewController!.dataSource = modelController addChildViewController(pageViewController!) view.addSubview(pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = view.bounds if UIDevice.currentDevice().userInterfaceIdiom == .Pad { pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0) } pageViewController!.view.frame = pageViewRect pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. view.gestureRecognizers = pageViewController!.gestureRecognizers } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let client = MIORestClient.sharedClient if client.authorized { getData() } else { let status = client.loadAccessToken() if status == .Success { getData() } else { authorize { [weak self] err in if err != nil { self?.getData() } } } } } private func authorize(closure: MIORestClient.OAuthCompletionClosure) { let app = UIApplication.sharedApplication() let window = app.windows[0] as UIWindow let view = window.rootViewController!.view MIORestClient.sharedClient.authorizeInView(view!, closure: closure) } private func getData() { MIORestClient.sharedClient.getMergedInfo { [weak self] (response, error) -> Void in if let s = self, r = response, info = r.couponInfo { s.modelController.pageData = info s.dataDidLoad() } } } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) { // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here. let currentViewController = pageViewController.viewControllers![0] let viewControllers = [currentViewController] pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) pageViewController.doubleSided = false return .Min } // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. let currentViewController = pageViewController.viewControllers![0] as! DataViewController let viewControllers: [UIViewController] let indexOfCurrentViewController = modelController.indexOfViewController(currentViewController) if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) { let nextViewController = modelController.pageViewController(pageViewController, viewControllerAfterViewController: currentViewController) viewControllers = [currentViewController, nextViewController!] } else { let previousViewController = modelController.pageViewController(pageViewController, viewControllerBeforeViewController: currentViewController) viewControllers = [previousViewController!, currentViewController] } pageViewController.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in () }) return .Mid } }
e28f772702a9d97ff0cf605bd89b948d
43.507692
329
0.691842
false
false
false
false
alvinvarghese/DeLorean
refs/heads/master
DeLorean/Emitter.swift
mit
1
// // Emitter.swift // Bonto.ch // // Created by Junior B. on 13/02/15. // Copyright (c) 2015 Bonto.ch . All rights reserved. // import Foundation protocol Subscribable { typealias S func subscribe(subscription: Subscription<S>) } /** An `Emitter` is a generalized mechanism for push-based notification. In other resources it is also known as the observer design pattern. An `Emitter` is an object that represents a source that sends notifications or events (also know as producer). A `Subscription` object represents the class that receives them (the consumer). */ public class Emitter<T>: Subscribable { typealias S = T /// The array containing all subscriptions var subscribers: Array<Subscription<T>> /// The current result var current: Result<T>? /// A boolean indicating if the emitter has completed var completed: Bool = false /// The scheduler where callbacks are performed var scheduler: Scheduler = Scheduler.Default /// An eventual delay on all callbacks (0 means no delay) var delay: Delay = 0 /// Internal callbacks are used to perform actions on connected emitters typealias InternalCallback = (result: Result<T>?) -> () /// The array containing all the internal callbacks var callbacks: [InternalCallback] = Array<InternalCallback>() public init () { self.subscribers = Array<Subscription<T>>() } deinit { for element in self.subscribers { element.emitter = nil } self.subscribers.removeAll() } /** Init an Emitter with the given Scheduler. :param: scheduler The scheduler to use. */ init (scheduler: Scheduler) { self.subscribers = Array<Subscription<T>>() self.scheduler = scheduler } /** Init an Emitter with the given Scheduler. :param: scheduler The scheduler to use, if empty the default one is used. :param: task The task to perform taking the emitter as parameter. */ init (scheduler: Scheduler = Scheduler.Default, task: (emitter: Emitter<T>) -> ()) { self.subscribers = Array<Subscription<T>>() self.scheduler = scheduler self.scheduler.schedule(){ task(emitter: self) } } /** Init an Emitter with the given Scheduler. :param: scheduler The scheduler to use, if empty the default one is used. :param: task The task to perform returning an instance of Result. */ init (scheduler: Scheduler = Scheduler.Default, task: () -> (Result<T>?)) { self.subscribers = Array<Subscription<T>>() self.scheduler = scheduler self.scheduler.schedule(){ if let result = task() { switch result { case .Error(let e): self.error(e) case .Value(let v): self.emit(v.value) } } else { self.complete() } } } /** Delay the emit of N seconds. :param: seconds The number of seconds. :returns: The current Emitter */ public func delayOf(seconds: Double) -> Emitter<T> { synchronized(self) { self.delay = delayFromSeconds(seconds) } return self } /// Perform all scheduled callbacks internal func performCallbacks(result: Result<T>?) { if let res = result { for callback in self.callbacks { self.scheduler.schedule(self.delay) { callback(result: res) } } if result == nil || result?.error != nil { self.callbacks.removeAll() } } } /** Returns an empty subscription ready to be configured. :returns: An empty instance of Subscription. */ public func subscription() -> Subscription<T> { let subscription = Subscription<T>() self.subscribe(subscription) return subscription } /** Subscribe a Subscription to the current Emitter. If the current Emitter has completed or has an error, the dedicated callback will be fired immediately on the passed subscription. In both cases the subscription will be immediately canceled. :param: subscription The instance of Subscription to subscribe. */ public func subscribe(subscription: Subscription<T>) { if subscription.emitter != nil { return } self.subscribers.append(subscription) subscription.emitter = self self.scheduler.schedule(self.delay) { subscription.onSubscribe() } if let result = self.current { switch (result) { case .Error(let e): self.scheduler.schedule(self.delay) { subscription.onError(e) subscription.cancel() } case .Value(let val): self.scheduler.schedule(self.delay) { subscription.onNext(val.value) if self.completed { subscription.onComplete() subscription.cancel() } } } } } /** Cancel a certain Subscription. :param: subscription The subscription to cancel. */ public func cancel(subscriber: Subscription<T>) { subscriber.emitter = nil self.subscribers.unsafeRemoveObject(subscriber) } // MARK: - Fundamentals /** Emit a value to all subscribers, on the given scheduler. :param: val The value to emit. */ public func emit(val: T) { synchronized(self) { if !self.completed { self.current = Result(val) for s in self.subscribers { self.scheduler.schedule(self.delay) { s.onNext(val) } } self.performCallbacks(self.current) } } } /** Send an error to all subscribers, on the given scheduler. :param: e The error to emit. */ public func error(e: NSError) { synchronized(self) { if !self.completed { self.completed = true self.current = Result(e) for s in self.subscribers { self.scheduler.schedule(self.delay) { s.onError(e) s.cancel() } return } self.performCallbacks(self.current) } } } /** Complete the emitter sending performing the dedicated callback on all subscribers, using the given scheduler. :note: Once an emitter is completed, all subscriptions are canceled. */ public func complete() { synchronized(self) { if !self.completed { self.completed = true for s in self.subscribers { self.scheduler.schedule(self.delay) { s.onComplete() s.cancel() } return } self.performCallbacks(nil) } } } } // MARK: - Monadic Operations extension Emitter { /** Creates a new `Emitter` by applying a filter function to the successful result of this emitter, returning a new emitter as the result of the function. If this emitter is completed or has an error, the new one will be either completed or terminated with and error. :param: f The filter function of type `(T) -> (Bool)` to perform. :returns: The new `Emitter` object. */ public func filter(f: (value: T) -> Bool) -> Emitter<T> { let emitter = Emitter<T>(scheduler: self.scheduler) let callback : InternalCallback = { result in if let r = result { switch (r) { case .Value(let v) where f(value: v.value): emitter.emit(v.value) case .Error(let e): emitter.error(e) default: break } } else { emitter.complete() } } self.callbacks.append(callback) return emitter } /** Creates a new `Emitter` by applying a function to this emitter. If this emitter is completed or has an error, the new one will be either completed or terminated with and error. :param: f The function of type `(T) -> (U)` to perform. :returns: The new `Emitter` object. */ public func map<U>(f: (value: T) -> U) -> Emitter<U> { let emitter = Emitter<U>(scheduler: self.scheduler) let callback : InternalCallback = { result in if let r = result { switch (r) { case .Value(let v): emitter.emit(f(value: v.value)) case .Error(let e): emitter.error(e) } } else { emitter.complete() } } self.callbacks.append(callback) return emitter } /** Creates a new `Emitter` that emits emitters by applying a function to this emitter. If this emitter is completed or has an error, the new one will be either completed or terminated with and error. :param: f The function of type `(T) -> Emitter(U)` to perform. :returns: The new `Emitter` object. */ public func flatMap<U>(f: (value: T) -> Emitter<U>) -> Emitter<U> { let emitter = Emitter<U>(scheduler: self.scheduler) let innerCallback : (Result<U>?) -> () = { result in if let r = result { switch (r) { case .Value(let v): emitter.emit(v.value) case .Error(let e): emitter.error(e) } } else { emitter.complete() } } let callback : InternalCallback = { result in if let r = result { switch (r) { case .Value(let v): emitter.callbacks.append(innerCallback) case .Error(let e): emitter.error(e) } } else { emitter.complete() } } self.callbacks.append(callback) return emitter } /** Creates a new `Emitter` that emits all the values of this and that emitter. :param: that The emitter to merge with. :returns: The new `Emitter` object. */ public func merge(that: Emitter<T>) -> Emitter<T> { let emitter = Emitter<T>(scheduler: self.scheduler) let callback : InternalCallback = { result in if let r = result { switch (r) { case .Value(let v): emitter.emit(v.value) case .Error(let e): emitter.error(e) } } else { emitter.complete() } } self.callbacks.append(callback) that.callbacks.append(callback) return emitter } } // MARK: - Class Functions extension Emitter { /** Returns an emitter that emits just one value and completes. :param: v The value to emit. */ public class func just(v: T) -> Emitter<T> { let e = Emitter<T>() e.emit(v) e.complete() return e } public class func infinite() -> Emitter<Int> { return self.range(0, Int.max - 1, 1.99)! } public class func range(to: Int) -> Emitter<Int>? { return self.range(0, to, 1.99) } public class func range(from: Int, _ to: Int, _ interval: NSTimeInterval) -> Emitter<Int>? { let emitter = Emitter<Int>() if to > from { Scheduler.BackgroundScheduler.schedule(){ for i in from ... to { emitter.emit(i) NSThread.sleepForTimeInterval(interval) } emitter.complete() } } else { return nil } return emitter } }
9e742d56ff346250fa4b4e80d4af934b
28.08945
116
0.522826
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
EurofurenceTests/Activity/Resuming/URL/WhenResumingKnowledgeEntryURL_WithParentGroup.swift
mit
1
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class WhenResumingKnowledgeEntryURL_WithParentGroup: XCTestCase { func testTheActivityIsResumed() { let contentLinksService = StubContentLinksService() let contentRouter = CapturingContentRouter() let intentResumer = ActivityResumer(contentLinksService: contentLinksService, contentRouter: contentRouter) let knowledgeEntry = KnowledgeEntryIdentifier.random let knowledgeGroup = KnowledgeGroupIdentifier.random let url = URL.random contentLinksService.stub(.knowledge(knowledgeEntry, knowledgeGroup), for: url) let activity = URLActivityDescription(url: url) let handled = intentResumer.resume(activity: activity) let resumedKnowledgePairing = contentRouter.resumedKnowledgePairing XCTAssertTrue(handled) XCTAssertEqual(knowledgeEntry, resumedKnowledgePairing?.entry) XCTAssertEqual(knowledgeGroup, resumedKnowledgePairing?.group) } }
ba03c219c11c83575e9c2ee52b50abb7
40.153846
115
0.757009
false
true
false
false
inket/stts
refs/heads/master
stts/Services/Super/StatusCastService.swift
mit
1
// // StatusCastService.swift // stts // import Foundation import Kanna typealias StatusCastService = BaseStatusCastService & RequiredServiceProperties & RequiredStatusCastProperties protocol RequiredStatusCastProperties {} class BaseStatusCastService: BaseService { private enum StatusCastStatus: String, CaseIterable { case available case unavailable case informational case monitored case identified case investigating case degraded case maintenance var serviceStatus: ServiceStatus { switch self { case .available: return .good case .unavailable: return .major case .informational, .monitored, .identified: return .notice case .investigating, .degraded: return .minor case .maintenance: return .maintenance } } } override func updateStatus(callback: @escaping (BaseService) -> Void) { guard let realSelf = self as? StatusCastService else { fatalError("BaseStatusCastService should not be used directly.") } let statusURL = realSelf.url loadData(with: statusURL) { [weak self] data, _, error in guard let strongSelf = self else { return } defer { callback(strongSelf) } guard let data = data else { return strongSelf._fail(error) } guard let doc = try? HTML(html: data, encoding: .utf8) else { return strongSelf._fail("Couldn't parse response") } // Not all StatusCast services support this format or this method of looking for status… let statuses: [(ServiceStatus, String?)] = doc.css(".status-list-component-status-text").map { element in for status in StatusCastStatus.allCases { if element.className?.contains("component-\(status.rawValue)") == true { return ( status.serviceStatus, element.innerHTML?.trimmingCharacters(in: .whitespacesAndNewlines) ) } } return (.undetermined, nil) } guard let worstStatus = statuses.max(by: { $0.0 < $1.0 }) else { return strongSelf._fail("Unexpected response") } self?.status = worstStatus.0 self?.message = worstStatus.1 ?? "Unexpected response" } } }
208bd2963a796f64ce5b3f0ae83e229a
32.24359
117
0.566525
false
false
false
false
daaavid/TIY-Assignments
refs/heads/master
18--Mutt-Cutts/MuttCutts/MuttCutts/PopoverViewController.swift
cc0-1.0
1
// // PopoverViewController.swift // MuttCutts // // Created by david on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class PopoverViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var firstLocationTextField: UITextField! @IBOutlet weak var secondLocationTextField: UITextField! var delegate: PopoverViewControllerDelegate? var locationArr = [String]() override func viewDidLoad() { super.viewDidLoad() if firstLocationTextField.text! == "" { firstLocationTextField.becomeFirstResponder() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func searchButton(sender: UIButton) { search() } func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text?.componentsSeparatedByString(",").count == 2 { switch textField { case firstLocationTextField: secondLocationTextField.becomeFirstResponder() default: secondLocationTextField.resignFirstResponder() rc = true search() } } else { switch textField { case firstLocationTextField: firstLocationTextField.placeholder = "Enter a valid City, State" default: secondLocationTextField.placeholder = "Enter a valid City, State" } } return rc } func search() { if firstLocationTextField.text != nil && secondLocationTextField.text != nil { let firstLocation = firstLocationTextField.text! let secondLocation = secondLocationTextField.text! locationArr.append(firstLocation); locationArr.append(secondLocation) UIApplication.sharedApplication().networkActivityIndicatorVisible = true delegate?.search(firstLocation, secondLocation: secondLocation) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
2d2dde5f84092427822357bd39213313
27.16129
106
0.611684
false
false
false
false
material-motion/material-motion-pop-swift
refs/heads/develop
src/popSpringToStream.swift
apache-2.0
1
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import ReactiveMotion import pop // In order to support POP's vector-based properties we create specialized connectPOPSpring methods. // Each specialized method is expected to read from and write to a POP vector value. /** Create a motion observable that will emit T values on the main thread simulating the provided spring parameters. */ public func pop<T>(_ spring: SpringShadow<T>) -> (MotionObservable<T>) { return MotionObservable("POP spring", args: [spring.enabled, spring.state, spring.initialValue, spring.initialVelocity, spring.destination, spring.tension, spring.friction, spring.mass, spring.suggestedDuration, spring.threshold]) { observer in let popProperty = POPMutableAnimatableProperty() popProperty.threshold = spring.threshold.value if let observer = observer as? MotionObserver<CGPoint> { popProperty.readBlock = { _, toWrite in let value = spring.initialValue.value as! CGPoint toWrite![0] = value.x toWrite![1] = value.y } popProperty.writeBlock = { _, toRead in observer.next(CGPoint(x: toRead![0], y: toRead![1])) } } else if let observer = observer as? MotionObserver<CGFloat> { popProperty.readBlock = { _, toWrite in toWrite![0] = spring.initialValue.value as! CGFloat } popProperty.writeBlock = { _, toRead in observer.next(toRead![0]) } } else { assertionFailure("Unsupported type") } return configureSpringAnimation(popProperty, spring: spring) } } private func configureSpringAnimation<T>(_ property: POPAnimatableProperty, spring: SpringShadow<T>) -> () -> Void { var destination: T? let createAnimation: () -> POPSpringAnimation = { let animation = POPSpringAnimation() animation.property = property animation.dynamicsFriction = spring.friction.value animation.dynamicsTension = spring.tension.value animation.velocity = spring.initialVelocity.value animation.toValue = destination animation.removedOnCompletion = false animation.animationDidStartBlock = { anim in spring.state.value = .active } animation.completionBlock = { anim, finished in spring.state.value = .atRest } return animation } var animation: POPSpringAnimation? let destinationSubscription = spring.destination.subscribeToValue { value in destination = value animation?.toValue = destination animation?.isPaused = false } let key = NSUUID().uuidString let someObject = NSObject() let activeSubscription = spring.enabled.dedupe().subscribeToValue { enabled in if enabled { if animation == nil { animation = createAnimation() // animationDidStartBlock is invoked at the turn of the run loop, potentially leaving this stream // in an at rest state even though it's effectively active. To ensure that the stream is marked // active until the run loop turns we immediately send an .active state to the observer. spring.state.value = .active someObject.pop_add(animation, forKey: key) } } else { if animation != nil { animation = nil someObject.pop_removeAnimation(forKey: key) } } } return { someObject.pop_removeAnimation(forKey: key) destinationSubscription.unsubscribe() activeSubscription.unsubscribe() } }
ee647d12c5f61ea48753196570b10ce0
32.855932
246
0.709637
false
false
false
false
intonarumori/FloatingLabelTextField
refs/heads/master
Example/Source/Example2/InsetsExampleViewController.swift
mit
1
// // InsetsExampleViewController.swift // FloatingLabelTextField // // Created by Daniel Langh on 2017. 02. 07.. // Copyright © 2017. rumori. All rights reserved. // import UIKit import FloatingLabelTextField class InsetsExampleViewController: UIViewController { @IBOutlet var textField: FloatingLabelIconTextField! // MARK: - User actions @IBAction func resignResponder() { textField.resignFirstResponder() } // MARK: - @IBAction func textInsetsTopChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.textInsetsTop = 0 case 1: textField.textInsetsTop = 5 default: textField.textInsetsTop = 10 } } @IBAction func textInsetsBottomChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.textInsetsBottom = 0 case 1: textField.textInsetsBottom = 5 default: textField.textInsetsBottom = 10 } } @IBAction func textInsetsLeftChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.textInsetsLeft = 0 case 1: textField.textInsetsLeft = 5 default: textField.textInsetsLeft = 10 } } @IBAction func textInsetsRightChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.textInsetsRight = 0 case 1: textField.textInsetsRight = 5 default: textField.textInsetsRight = 10 } } // MARK: - @IBAction func iconChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.iconImage = nil default: textField.iconImage = #imageLiteral(resourceName: "Doc") } } // MARK: - @IBAction func iconInsetsTopChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.iconInsetsTop = 0 case 1: textField.iconInsetsTop = 5 default: textField.iconInsetsTop = 10 } } @IBAction func iconInsetsBottomChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.iconInsetsBottom = 0 case 1: textField.iconInsetsBottom = 5 default: textField.iconInsetsBottom = 10 } } @IBAction func iconInsetsLeftChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.iconInsetsLeft = 0 case 1: textField.iconInsetsLeft = 5 default: textField.iconInsetsLeft = 10 } } @IBAction func iconInsetsRightChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.iconInsetsRight = 0 case 1: textField.iconInsetsRight = 5 default: textField.iconInsetsRight = 10 } } // MARK: - @IBAction func lineHeightChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: textField.lineHeight = 0 case 1: textField.lineHeight = 1 default: textField.lineHeight = 2 } } }
7a97793c71ac7a1ffa385b351a467a91
24.653333
74
0.599532
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Foundation/AdBlocking/AdblockingModule.swift
mpl-2.0
2
// // AdblockingModule.swift // Client // // Created by Tim Palade on 2/24/17. // Copyright © 2017 Mozilla. All rights reserved. // import Foundation import JavaScriptCore class AdblockingModule: NSObject { //MARK: Constants fileprivate let adBlockPrefName = "cliqz-adb" //MARK: - Singltone static let sharedInstance = AdblockingModule() override init() { super.init() } //MARK: - Public APIs func initModule() { } func setAdblockEnabled(_ value: Bool, timeout: Int = 0) { Engine.sharedInstance.setPref(self.adBlockPrefName, prefValue: value ? 1 : 0) } func isAdblockEnabled() -> Bool { let result = Engine.sharedInstance.getPref(self.adBlockPrefName) if let r = result as? Bool { return r } return false } //if url is blacklisted I do not block ads. func isUrlBlackListed(_ url:String) -> Bool { let response = Engine.sharedInstance.getBridge().callAction("adblocker:isDomainInBlacklist", args: [url]) if let result = response["result"] as? Bool { return result } return false } func toggleUrl(_ url: URL){ if let host = url.host { let urlString = url.absoluteString Engine.sharedInstance.getBridge().callAction("adblocker:toggleUrl", args: [urlString, host]) } } func getAdBlockingStatistics(_ tabId: Int) -> [(String, Int)] { var adblockingStatistics = [(String, Int)]() if let tabBlockInfo = getAdBlockingInfo(tabId) { if let adDict = tabBlockInfo["advertisersList"] { if let dict = adDict as? Dictionary<String, Array<String>> { dict.keys.forEach({company in adblockingStatistics.append((company, dict[company]?.count ?? 0)) }) } } } return adblockingStatistics.sorted { $0.1 == $1.1 ? $0.0.lowercased() < $1.0.lowercased() : $0.1 > $1.1 } } //MARK: - Private Helpers func getAdBlockingInfo(_ tabId: Int) -> [AnyHashable: Any]! { let response = Engine.sharedInstance.getBridge().callAction("adblocker:getAdBlockInfoForTab", args: [tabId]) if let result = response["result"] { return result as? Dictionary } else { return [:] } } }
be356b8effda0a8633de8887946e2de7
27.870588
116
0.573757
false
false
false
false
ivngar/TDD-TodoList
refs/heads/master
TDD-TodoListTests/InputViewControllerTests.swift
mit
1
// // InputViewControllerTests.swift // TDD-TodoListTests // // Created by Ivan Garcia on 27/6/17. // Copyright © 2017 Ivan Garcia. All rights reserved. // import XCTest import CoreLocation @testable import TDD_TodoList class InputViewControllerTests: XCTestCase { var placemark: MockPlacemark! var sut: InputViewController! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. let storyboard = UIStoryboard(name: "Main", bundle: nil) sut = storyboard.instantiateViewController(withIdentifier: "InputViewController") as! InputViewController _ = sut.view } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_HasTitleTextField() { XCTAssertNotNil(sut.titleTextField) } func test_HasDateTextField() { XCTAssertNotNil(sut.dateTextField) } func test_HasAddressTextField() { XCTAssertNotNil(sut.addressTextField) } func test_HasDescriptionTextField() { XCTAssertNotNil(sut.descriptionTextField) } func test_HasSaveButton() { XCTAssertNotNil(sut.saveButton) } func test_Save_UsesGeocoderToGetCoordinateFromAddress() { let mockSut = MockInputViewController() mockSut.titleTextField = UITextField() mockSut.dateTextField = UITextField() mockSut.locationTextField = UITextField() mockSut.addressTextField = UITextField() mockSut.descriptionTextField = UITextField() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy" let timestamp = 1456095600.0 let date = Date(timeIntervalSince1970: timestamp) mockSut.titleTextField.text = "Foo" mockSut.dateTextField.text = dateFormatter.string(from: date) mockSut.locationTextField.text = "Bar" mockSut.addressTextField.text = "Infinite Loop 1, Cupertino" mockSut.descriptionTextField.text = "Baz" let mockGeocoder = MockGeocoder() mockSut.geocoder = mockGeocoder mockSut.itemManager = ItemManager() let dismissExpectation = expectation(description: "Dismiss") mockSut.completionHandler = { dismissExpectation.fulfill() } mockSut.save() placemark = MockPlacemark() let coordinate = CLLocationCoordinate2DMake(37.3316851, -122.0300674) placemark.mockCoordinate = coordinate mockGeocoder.completionHandler?([placemark], nil) waitForExpectations(timeout: 1, handler: nil) let item = mockSut.itemManager?.item(at: 0) let testItem = ToDoItem(title: "Foo", itemDescription: "Baz", timestamp: timestamp, location: Location(name: "Bar", coordinate: coordinate)) XCTAssertEqual(item, testItem) mockSut.itemManager?.removeAll() } func test_SaveButtonHasSaveAction() { let saveButton: UIButton = sut.saveButton guard let actions = saveButton.actions(forTarget: sut, forControlEvent: .touchUpInside) else { XCTFail(); return } XCTAssertTrue(actions.contains("save")) } func test_Geocoder_FetchesCoordinates() { let geocoderAnswer = expectation(description: "Geocoder") CLGeocoder().geocodeAddressString("Infinite Loop 1, Cupertino") { (placemarks, error) in let coordinate = placemarks?.first?.location?.coordinate guard let latitude = coordinate?.latitude else { XCTFail() return } guard let longitude = coordinate?.longitude else { XCTFail() return } XCTAssertEqualWithAccuracy(latitude, 37.3316, accuracy: 0.001) XCTAssertEqualWithAccuracy(longitude, -122.0300, accuracy: 0.001) geocoderAnswer.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func test_Save_DismissesViewController() { let mockInputViewController = MockInputViewController() mockInputViewController.titleTextField = UITextField() mockInputViewController.dateTextField = UITextField() mockInputViewController.locationTextField = UITextField() mockInputViewController.addressTextField = UITextField() mockInputViewController.descriptionTextField = UITextField() mockInputViewController.titleTextField.text = "Test Title" mockInputViewController.save() XCTAssertTrue(mockInputViewController.dismissGotCalled) } } extension InputViewControllerTests { class MockGeocoder: CLGeocoder { var completionHandler: CLGeocodeCompletionHandler? override func geocodeAddressString(_ addressString: String, completionHandler: @escaping CLGeocodeCompletionHandler) { self.completionHandler = completionHandler } } class MockPlacemark: CLPlacemark { var mockCoordinate: CLLocationCoordinate2D? override var location: CLLocation? { guard let coordinate = mockCoordinate else { return CLLocation() } return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) } } class MockInputViewController: InputViewController { var dismissGotCalled = false var completionHandler: (() -> Void)? override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { dismissGotCalled = true completionHandler?() } } }
5c75f05abd7ed6c5359867f5d9fe242a
31.252941
122
0.695605
false
true
false
false
haskelash/molad
refs/heads/master
Molad/Views/ClockFaceMethods.swift
mit
1
// // ClockFaceMethods.swift // Molad // // Created by Haskel Ash on 5/29/17. // Copyright © 2017 HaskelAsh. All rights reserved. // import UIKit extension ClockView { internal func drawClock(rect: CGRect, ctx: CGContext, radius: CGFloat, border: CGFloat) { let center = CGPoint(x: rect.midX, y: rect.midY) //clock circle ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: .pi*2, clockwise: true) ctx.setFillColor(UIColor.white.cgColor) ctx.setStrokeColor(UIColor.black.cgColor) ctx.setLineWidth(border) ctx.drawPath(using: .fillStroke) //center circle ctx.addArc(center: center, radius: 5, startAngle: 0, endAngle: .pi*2, clockwise: true) ctx.setFillColor(UIColor.black.cgColor) ctx.drawPath(using: .fill) } internal func drawTicks(rect: CGRect, ctx: CGContext, radius: CGFloat, border: CGFloat) { let tickStartPoints = pointsAroundCircle(rect: rect, radius: radius, ticks: 48) let path = CGMutablePath() for (i, point) in tickStartPoints.enumerated() { let fraction: CGFloat = i % 2 == 0 ? 0.08 : 0.05 let tickEndX = point.x + fraction*(rect.midX - point.x) let tickEndY = point.y + fraction*(rect.midY - point.y) path.move(to: point) path.addLine(to: CGPoint(x: tickEndX, y: tickEndY)) ctx.addPath(path) } ctx.setLineWidth(border/2) ctx.strokePath() } }
83cd9388fd06b00aa815e2494f13245a
32.98
67
0.554444
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/SDK/SpriteKit/SpriteKit.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import SpriteKit import simd // SpriteKit defines SKColor using a macro. #if os(macOS) public typealias SKColor = NSColor #elseif os(iOS) || os(tvOS) || os(watchOS) public typealias SKColor = UIColor #endif // this class only exists to allow AnyObject lookup of _copyImageData // since that method only exists in a private header in SpriteKit, the lookup // mechanism by default fails to accept it as a valid AnyObject call @objc class _SpriteKitMethodProvider : NSObject { override init() { _sanityCheckFailure("don't touch me") } @objc func _copyImageData() -> NSData! { return nil } } @available(iOS, introduced: 10.0) @available(macOS, introduced: 10.12) @available(tvOS, introduced: 10.0) @available(watchOS, introduced: 3.0) extension SKWarpGeometryGrid { /// Create a grid of the specified dimensions, source and destination positions. /// /// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The /// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1). /// /// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content. /// /// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to /// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and /// correspond to positions outside of the native undistorted bounds. /// /// Source and destination positions are provided in row-major order starting from the top-left. /// For example the indices for a 2x2 grid would be as follows: /// /// [0]---[1]---[2] /// | | | /// [3]---[4]---[5] /// | | | /// [6]---[7]---[8] /// /// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with /// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with /// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from /// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to public convenience init(columns: Int, rows: Int, sourcePositions: [simd.float2] = [float2](), destinationPositions: [simd.float2] = [float2]()) { let requiredElementsCount = (columns + 1) * (rows + 1) switch (destinationPositions.count, sourcePositions.count) { case (0, 0): self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil) case (let dests, 0): _precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions) case (0, let sources): _precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil) case (let dests, let sources): _precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions) } } public func replacingBySourcePositions(positions source: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingSourcePositions(source) } public func replacingByDestinationPositions(positions destination: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingDestPositions(destination) } }
b7af398ebdbaa2afb4f9f8adae76dbc0
47.423529
147
0.685131
false
false
false
false
benlangmuir/swift
refs/heads/master
test/Generics/sr11100.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -debug-generic-signatures 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/53495 protocol P1 { associatedtype A } protocol P2 { associatedtype C: P1 } // CHECK: sr11100.(file).Q@ // CHECK-NEXT: Requirement signature: <Self where Self.[Q]X == Self.[Q]X.[P1]A, Self.[Q]Y : P2, Self.[Q]X.[P1]A == Self.[Q]Y.[P2]C> protocol Q { associatedtype X associatedtype Y : P2 where X == X.A, X.A == Y.C }
d442176c0b674ef62cb337aac20f0510
24.333333
131
0.655702
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
Floral/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift
apache-2.0
3
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Represents a success result of an image downloading progress. public struct ImageLoadingResult { /// The downloaded image. public let image: Image /// Original URL of the image request. public let url: URL? /// The raw data received from downloader. public let originalData: Data } /// Represents a task of an image downloading process. public struct DownloadTask { /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task /// for the same URL resource at the same time. /// /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through. /// You can use them to identify the cancelled task. public let sessionTask: SessionDataTask /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled. /// To cancel a `DownloadTask`, use `cancel` instead. public let cancelToken: SessionDataTask.CancelToken /// Cancel this task if it is running. It will do nothing if this task is not running. /// /// - Note: /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created /// and returned when you call related methods, but it will share the session downloading task with a previous task. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask` /// does not affect other `DownloadTask`s. /// /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`. public func cancel() { sessionTask.cancel(token: cancelToken) } } extension DownloadTask { enum WrappedTask { case download(DownloadTask) case dataProviding func cancel() { switch self { case .download(let task): task.cancel() case .dataProviding: break } } var value: DownloadTask? { switch self { case .download(let task): return task case .dataProviding: return nil } } } } /// Represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { // MARK: Singleton /// The default downloader. public static let `default` = ImageDownloader(name: "default") // MARK: Public Properties /// The duration before the downloading is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't /// specify the `authenticationChallengeResponder`. /// /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of /// `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// /// You could change the configuration before a downloading task starts. /// A configuration without persistent storage for caches is requested for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session.invalidateAndCancel() session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) } } /// Whether the download requests should use pipeline or not. Default is false. open var requestsUsePipelining = false /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? private let name: String private let sessionDelegate: SessionDelegate private var session: URLSession // MARK: Initializers /// Creates a downloader with name. /// /// - Parameter name: The name for the downloader. It should not be empty. public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. " + "A downloader with empty name is not permitted.") } self.name = name sessionDelegate = SessionDelegate() session = URLSession( configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) authenticationChallengeResponder = self setupSessionHandler() } deinit { session.invalidateAndCancel() } private func setupSessionHandler() { sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2) } sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader( self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3) } sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in return (self.delegate ?? self).isValidStatusCode(code, for: self) } sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in let (url, result) = value do { let value = try result.get() self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil) } catch { self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error) } } sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in guard let url = task.task.originalRequest?.url else { return task.mutableData } return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url) } } @discardableResult func downloadImage( with url: URL, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { // Creates default request. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) request.httpShouldUsePipelining = requestsUsePipelining if let requestModifier = options.requestModifier { // Modifies request before sending. guard let r = requestModifier.modified(for: request) else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest))) } return nil } request = r } // There is a possibility that request modifier changed the url to `nil` or empty. // In this case, throw an error. guard let url = request.url, !url.absoluteString.isEmpty else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request)))) } return nil } // Wraps `completionHandler` to `onCompleted` respectively. let onCompleted = completionHandler.map { block -> Delegate<Result<ImageLoadingResult, KingfisherError>, Void> in let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>() delegate.delegate(on: self) { (_, callback) in block(callback) } return delegate } // SessionDataTask.TaskCallback is a wrapper for `onCompleted` and `options` (for processor info) let callback = SessionDataTask.TaskCallback( onCompleted: onCompleted, options: options ) // Ready to start download. Add it to session task manager (`sessionHandler`) let downloadTask: DownloadTask if let existingTask = sessionDelegate.task(for: url) { downloadTask = sessionDelegate.append(existingTask, url: url, callback: callback) } else { let sessionDataTask = session.dataTask(with: request) sessionDataTask.priority = options.downloadPriority downloadTask = sessionDelegate.add(sessionDataTask, url: url, callback: callback) } let sessionTask = downloadTask.sessionTask // Start the session task if not started yet. if !sessionTask.started { sessionTask.onTaskDone.delegate(on: self) { (self, done) in // Underlying downloading finishes. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback] let (result, callbacks) = done // Before processing the downloaded data. do { let value = try result.get() self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: value.1, error: nil ) } catch { self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: nil, error: error ) } switch result { // Download finished. Now process the data to an image. case .success(let (data, response)): let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: options.processingQueue) processor.onImageProcessed.delegate(on: self) { (self, result) in // `onImageProcessed` will be called for `callbacks.count` times, with each // `SessionDataTask.TaskCallback` as the input parameter. // result: Result<Image>, callback: SessionDataTask.TaskCallback let (result, callback) = result if let image = try? result.get() { self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) } let imageResult = result.map { ImageLoadingResult(image: $0, url: url, originalData: data) } let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(imageResult) } } processor.process() case .failure(let error): callbacks.forEach { callback in let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(.failure(error)) } } } } delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) sessionTask.resume() } return downloadTask } // MARK: Dowloading Task /// Downloads an image with a URL and option. /// /// - Parameters: /// - url: Target URL. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue /// defined in `.callbackQueue` in `options` parameter. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. @discardableResult open func downloadImage( with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var info = KingfisherParsedOptionsInfo(options) if let block = progressBlock { info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } return downloadImage( with: url, options: info, completionHandler: completionHandler) } } // MARK: Cancelling Task extension ImageDownloader { /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers /// for all not-yet-finished downloading tasks. /// /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask` /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url, /// use `ImageDownloader.cancel(url:)`. public func cancelAll() { sessionDelegate.cancelAll() } /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for /// all not-yet-finished downloading tasks for the URL. /// /// - Parameter url: The URL which you want to cancel downloading. public func cancel(url: URL) { sessionDelegate.cancel(url: url) } } // Use the default implementation from extension of `AuthenticationChallengeResponsable`. extension ImageDownloader: AuthenticationChallengeResponsable {} // Use the default implementation from extension of `ImageDownloaderDelegate`. extension ImageDownloader: ImageDownloaderDelegate {}
348764bbf5625b3bf10cf197ca3c7e80
42.051491
120
0.641194
false
false
false
false
gvsucis/mobile-app-dev-book
refs/heads/master
iOS/ch10/TraxyApp/TraxyApp/AudioViewController.swift
gpl-3.0
1
// // AudioViewController.swift // TraxyApp // // Created by Jonathan Engelsma on 9/11/17. // Copyright © 2017 Jonathan Engelsma. All rights reserved. // import UIKit import AVFoundation class AudioViewController: UIViewController { @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var playButton: UIButton! var recording = false var playing = false var entry : JournalEntry? var journal : Journal! let playImage = UIImage(named: "play") let stopImage = UIImage(named: "stop") let recordImage = UIImage(named: "record") var captionEntryCtrl : JournalEntryConfirmationViewController? var recorder: AVAudioRecorder! var player: AVAudioPlayer! var audioTimer:Timer! var audioFileUrl:URL! weak var delegate : AddJournalEntryDelegate? override func viewDidLoad() { super.viewDidLoad() self.playButton.isEnabled = false self.setSessionPlayback() if self.entry == nil { self.entry = JournalEntry(key: nil, type: .audio, caption: "", url: "", thumbnailUrl: "", date: Date(), lat: 0.0, lng: 0.0) } self.saveButton.isEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveButtonPressed(_ sender: UIBarButtonItem) { if let del = self.delegate { if let (caption,date,_) = (self.captionEntryCtrl?.extractFormValues()) { if var e = self.entry { e.url = self.recorder.url.absoluteString e.caption = caption e.date = date del.save(entry: e) } } } _ = self.navigationController?.popViewController(animated: true) } @IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) { _ = self.navigationController?.popViewController(animated: true) } @IBAction func playButtonPressed(_ sender: UIButton) { if self.playing { self.playButton.setImage(self.playImage, for: .normal) self.recordButton.isEnabled = true self.playing = false self.player.stop() } else { self.playButton.setImage(self.stopImage, for: .normal) self.recordButton.isEnabled = false self.playing = true self.setSessionPlayback() self.play() } } func play() { var url:URL? if self.recorder != nil { url = self.recorder.url } else { url = self.audioFileUrl! } do { self.player = try AVAudioPlayer(contentsOf: url!) player.delegate = self player.prepareToPlay() player.volume = 1.0 player.play() } catch let error as NSError { self.player = nil print(error.localizedDescription) } } @IBAction func recordButtonPressed(_ sender: UIButton) { if self.recording { self.recordButton.setImage(self.recordImage, for: .normal) self.playButton.isEnabled = true self.recording = false self.recorder.stop() } else { // Note we adjust the UI in recordIfPermitted, as we don't know // at this point if permissions have been granted. if recorder == nil { self.recordIfPermitted(setup: true) } else { self.recordIfPermitted(setup: false) } } } @objc func updateTimeLabel(timer:Timer) { if self.recorder.isRecording { let min = Int(recorder.currentTime / 60) let sec = Int(recorder.currentTime.truncatingRemainder(dividingBy: 60)) let s = String(format: "%02d:%02d", min, sec) self.timeLabel.text = s recorder.updateMeters() } } func recordIfPermitted(setup:Bool) { let session:AVAudioSession = AVAudioSession.sharedInstance() if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in DispatchQueue.main.async { if granted { self.setSessionPlayAndRecord() if setup { self.setupRecorder() } self.recorder.record() self.audioTimer = Timer.scheduledTimer(timeInterval: 0.1, target:self, selector:#selector(AudioViewController.updateTimeLabel(timer:)), userInfo:nil,repeats:true) // we're rolling! update the UI self.recordButton.setImage(self.stopImage, for: .normal) self.playButton.isEnabled = false self.recording = true } else { self.displaySettingsAppAlert() } } }) } else { // technically, this happens when the device doesn't have a mic. self.displaySettingsAppAlert() } } func displaySettingsAppAlert() { let avc = UIAlertController(title: "Mic Permission Required", message: "You need to provide this app permissions to use your microphone for this feature. You can do this by going to your Settings app and going to Privacy -> Microphone", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default ) {action in UIApplication.shared.open(NSURL(string: UIApplication.openSettingsURLString)! as URL, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) avc.addAction(settingsAction) avc.addAction(cancelAction) self.present(avc, animated: true, completion: nil) } func setupRecorder() { let format = DateFormatter() format.dateFormat="yyyy-MM-dd-HH-mm-ss" let currentFileName = "audio-\\(format.string(from: Date())).m4a" let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] self.audioFileUrl = documentsDirectory.appendingPathComponent(currentFileName) if FileManager.default.fileExists(atPath: audioFileUrl.absoluteString) { print("File \(audioFileUrl.absoluteString) already exists!") } let recordSettings:[String : AnyObject] = [ AVFormatIDKey: NSNumber(value: kAudioFormatMPEG4AAC), AVEncoderAudioQualityKey : NSNumber(value:AVAudioQuality.max.rawValue), AVEncoderBitRateKey : NSNumber(value:320000), AVNumberOfChannelsKey: NSNumber(value:2), AVSampleRateKey : NSNumber(value:44100.0) ] do { recorder = try AVAudioRecorder(url: audioFileUrl, settings: recordSettings) recorder.delegate = self recorder.isMeteringEnabled = true recorder.prepareToRecord() } catch let error as NSError { recorder = nil print(error.localizedDescription) } } func setSessionPlayback() { let session:AVAudioSession = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback))) } catch let error as NSError { print(error.localizedDescription) } do { try session.setActive(true) } catch let error as NSError { print(error.localizedDescription) } } func setSessionPlayAndRecord() { let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playAndRecord))) } catch let error as NSError { print(error.localizedDescription) } do { try session.setActive(true) } catch let error as NSError { print(error.localizedDescription) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "setupAudioCaptionForm" { if let destCtrl = segue.destination as? JournalEntryConfirmationViewController { destCtrl.type = .audio destCtrl.entry = self.entry destCtrl.journal = self.journal self.captionEntryCtrl = destCtrl } } } } extension AudioViewController : AVAudioRecorderDelegate { func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { self.saveButton.isEnabled = true self.recordButton.isEnabled = true self.playButton.isEnabled = true self.playButton.setImage(self.playImage, for: .normal) self.recordButton.setImage(self.recordImage, for: .normal) } func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { if let e = error { print("\(e.localizedDescription)") } } } extension AudioViewController : AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { self.recordButton.isEnabled = true self.playButton.isEnabled = true self.playButton.setImage(self.playImage, for: .normal) self.recordButton.setImage(self.recordImage, for: .normal) } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { if let e = error { print("\(e.localizedDescription)") } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String { return input.rawValue }
6e25ffce390dc1f78c59559d1d5a51e9
36.301003
268
0.590962
false
false
false
false
emadhegab/MHProgressButton
refs/heads/master
MHProgressButton/ViewController.swift
mit
1
// // ViewController.swift // MHProgressButton // // Created by Mohamed Emad Abdalla Hegab on 19.04.17. // Copyright © 2017 MohamedHegab. All rights reserved. // import UIKit class ViewController: UIViewController { var timer: Timer? var i = 0.0 @IBOutlet weak var progressButton: MHProgressButton! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupButtonView() } func setupButtonView() { progressButton.layer.cornerRadius = progressButton.frame.height / 2 progressButton.clipsToBounds = true } override func viewDidLoad() { super.viewDidLoad() } @IBAction func startProgress() { i = 0.0 progressButton.setTitle("Loading...", for: .normal) timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(update), userInfo: nil, repeats: true) } @objc func update () { self.progressButton.linearLoadingWith(progress: CGFloat(i)) i += 1 if i > 100 { timer?.invalidate() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f0f0cf38f27bedca88aff3242f02d37b
23.607843
129
0.639044
false
false
false
false
149393437/Templates
refs/heads/master
Templates/File Templates/Source/Cocoa Class.xctemplate/NSViewControllerSwift/___FILEBASENAME___.swift
mit
2
// ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ //                          _oo8oo_ //                         o8888888o //                         88" . "88 //                         (| -_- |) //                         0\  =  /0 //                       ___/'==='\___ //                     .' \\|     |// '. //                    / \\|||  :  |||// \ //                   / _||||| -:- |||||_ \ //                  |   | \\\  -  /// |   | //                  | \_|  ''\---/''  |_/ | //                  \  .-\__  '-'  __/-.  / //                ___'. .'  /--.--\  '. .'___ //             ."" '<  '.___\_<|>_/___.'  >' "". //            | | :  `- \`.:`\ _ /`:.`/ -`  : | | //            \  \ `-.   \_ __\ /__ _/   .-` /  / //        =====`-.____`.___ \_____/ ___.`____.-`===== //                          `=---=` // //                  佛祖保佑         永无bug // _ _ // ___| |__ __ _ _ __ __ _ ___| |__ ___ _ __ __ _ //|_ / '_ \ / _` | '_ \ / _` |/ __| '_ \ / _ \ '_ \ / _` | // / /| | | | (_| | | | | (_| | (__| | | | __/ | | | (_| | ///___|_| |_|\__,_|_| |_|\__, |\___|_| |_|\___|_| |_|\__, | // |___/ |___/ //小张诚技术博客http://blog.sina.com.cn/u/2914098025 //github代码地址https://github.com/149393437 //欢迎加入iOS研究院 QQ群号305044955 你的关注就是我开源的动力 import Cocoa class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaSubclass___ { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
6aedba9647e2a24c143083bd234a10ea
32.638298
68
0.191018
false
false
false
false
roberthein/Observable
refs/heads/master
Example/Observable/Views/Slider.swift
mit
1
import Foundation import UIKit import Observable class Slider: UISlider { @MutableObservable var positionValue: CGFloat = 0 var position: Observable<CGFloat> { return _positionValue } override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false minimumValue = 0 maximumValue = 100 tintColor = UIColor(red: 95/255, green: 20/255, blue: 255/255, alpha: 1) addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func sliderValueChanged(_ slider: UISlider) { positionValue = CGFloat(value / maximumValue) } }
43973e8f17b8ff139b8a3520926e33fb
26.366667
86
0.639464
false
false
false
false
daande/RSBarcodes_Swift
refs/heads/master
Pods/RSBarcodes_Swift/Source/RSCode128Generator.swift
mit
4
// // RSCode128Generator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit public enum RSCode128GeneratorCodeTable: Int { case Auto = 0 case A, B, C } // http://www.barcodeisland.com/code128.phtml // http://courses.cs.washington.edu/courses/cse370/01au/minirproject/BarcodeBattlers/barcodes.html public class RSCode128Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator { class RSCode128GeneratorAutoCodeTable { var startCodeTable = RSCode128GeneratorCodeTable.Auto var sequence:Array<Int> = [] } var codeTable: RSCode128GeneratorCodeTable var codeTableSize: Int var autoCodeTable: RSCode128GeneratorAutoCodeTable public init(codeTable:RSCode128GeneratorCodeTable) { self.codeTable = codeTable self.codeTableSize = CODE128_CHARACTER_ENCODINGS.count self.autoCodeTable = RSCode128GeneratorAutoCodeTable() } public convenience override init() { self.init(codeTable: .Auto) } func startCodeTableValue(startCodeTable: RSCode128GeneratorCodeTable) -> Int { switch self.autoCodeTable.startCodeTable { case .A: return self.codeTableSize - 4 case .B: return self.codeTableSize - 3 case .C: return self.codeTableSize - 2 default: switch startCodeTable { case .A: return self.codeTableSize - 4 case .B: return self.codeTableSize - 3 case .C: return self.codeTableSize - 2 default: return 0 } } } func middleCodeTableValue(codeTable:RSCode128GeneratorCodeTable) -> Int { switch codeTable { case .A: return self.codeTableSize - 6 case .B: return self.codeTableSize - 7 case .C: return self.codeTableSize - 8 default: return 0 } } func calculateContinousDigits(contents:String, defaultCodeTable:RSCode128GeneratorCodeTable, range:Range<Int>) { var isFinished = false if range.endIndex == contents.length() { isFinished = true } let length = range.endIndex - range.startIndex if (range.startIndex == 0 && length >= 4) || (range.startIndex > 0 && length >= 6) { var isOrphanDigitUsed = false // Use START C when continous digits are found from range.location == 0 if range.startIndex == 0 { self.autoCodeTable.startCodeTable = .C } else { if length % 2 == 1 { let digitValue = CODE128_ALPHABET_STRING.location(contents[range.startIndex]) self.autoCodeTable.sequence.append(digitValue) isOrphanDigitUsed = true } self.autoCodeTable.sequence.append(self.middleCodeTableValue(.C)) } // Insert all xx combinations for i in 0..<length / 2 { let startIndex = range.startIndex + i * 2 let digitValue = contents.substring(isOrphanDigitUsed ? startIndex + 1 : startIndex, length: 2).toInt()! self.autoCodeTable.sequence.append(digitValue) } if (length % 2 == 1 && !isOrphanDigitUsed) || !isFinished { self.autoCodeTable.sequence.append(self.middleCodeTableValue(defaultCodeTable)) } if length % 2 == 1 && !isOrphanDigitUsed { let digitValue = CODE128_ALPHABET_STRING.location(contents[range.endIndex - 1]) self.autoCodeTable.sequence.append(digitValue) } if !isFinished { let characterValue = CODE128_ALPHABET_STRING.location(contents[range.endIndex]) self.autoCodeTable.sequence.append(characterValue) } } else { for i in range.startIndex...(isFinished ? range.endIndex - 1 : range.endIndex) { let characterValue = CODE128_ALPHABET_STRING.location(contents[i]) self.autoCodeTable.sequence.append(characterValue) } } } func calculateAutoCodeTable(contents:String) { if self.codeTable == .Auto { // Select the short code table A as default code table var defaultCodeTable: RSCode128GeneratorCodeTable = .A // Determine whether to use code table B let CODE128_ALPHABET_STRING_A = CODE128_ALPHABET_STRING.substring(0, length: 64) for i in 0..<contents.length() { if CODE128_ALPHABET_STRING_A.location(contents[i]) == NSNotFound && defaultCodeTable == .A { defaultCodeTable = .B break } } var continousDigitsStartIndex:Int = NSNotFound for i in 0..<contents.length() { let character = contents[i] var continousDigitsRange:Range<Int> = Range<Int>(start: 0, end: 0) if DIGITS_STRING.location(character) == NSNotFound { // Non digit found if continousDigitsStartIndex != NSNotFound { continousDigitsRange = Range<Int>(start: continousDigitsStartIndex, end: i) } else { let characterValue = CODE128_ALPHABET_STRING.location(character) self.autoCodeTable.sequence.append(characterValue) } } else { // Digit found if continousDigitsStartIndex == NSNotFound { continousDigitsStartIndex = i } else if i == contents.length() - 1 { continousDigitsRange = Range<Int>(start: continousDigitsStartIndex, end: i + 1) } } if continousDigitsRange.endIndex - continousDigitsRange.startIndex != 0 { self.calculateContinousDigits(contents, defaultCodeTable: defaultCodeTable, range: continousDigitsRange) continousDigitsStartIndex = NSNotFound } } if self.autoCodeTable.startCodeTable == .Auto { self.autoCodeTable.startCodeTable = defaultCodeTable } } } func encodeCharacterString(characterString:String) -> String { return CODE128_CHARACTER_ENCODINGS[CODE128_ALPHABET_STRING.location(characterString)] } override public func initiator() -> String { switch self.codeTable { case .Auto: return CODE128_CHARACTER_ENCODINGS[self.startCodeTableValue(self.autoCodeTable.startCodeTable)] default: return CODE128_CHARACTER_ENCODINGS[self.startCodeTableValue(self.codeTable)] } } override public func terminator() -> String { return CODE128_CHARACTER_ENCODINGS[self.codeTableSize - 1] + "11" } override public func isValid(contents: String) -> Bool { if contents.length() > 0 { for i in 0..<contents.length() { if CODE128_ALPHABET_STRING.location(contents[i]) == NSNotFound { return false } } switch self.codeTable { case .Auto: self.calculateAutoCodeTable(contents) fallthrough case .B: return true case .A: let CODE128_ALPHABET_STRING_A = CODE128_ALPHABET_STRING.substring(0, length: 64) for i in 0..<contents.length() { if CODE128_ALPHABET_STRING_A.location(contents[i]) == NSNotFound { return false } } return true case .C: if contents.length() % 2 == 0 && contents.isNumeric() { return true } return false } } return false } override public func barcode(contents: String) -> String { var barcode = "" switch self.codeTable { case .Auto: for i in 0..<self.autoCodeTable.sequence.count { barcode += CODE128_CHARACTER_ENCODINGS[self.autoCodeTable.sequence[i]] } case .A, .B: for i in 0..<contents.length() { barcode += self.encodeCharacterString(contents[i]) } case .C: for i in 0..<contents.length() { if i % 2 == 1 { continue } else { let value = contents.substring(i, length: 2).toInt()! barcode += CODE128_CHARACTER_ENCODINGS[value] } } } barcode += self.checkDigit(contents) return barcode } // MARK: RSCheckDigitGenerator public func checkDigit(contents: String) -> String { var sum = 0 switch self.codeTable { case .Auto: sum += self.startCodeTableValue(self.autoCodeTable.startCodeTable) for i in 0..<self.autoCodeTable.sequence.count { sum += self.autoCodeTable.sequence[i] * (i + 1) } case .A: sum = -1 // START A = self.codeTableSize - 4 = START B - 1 fallthrough case .B: sum += self.codeTableSize - 3 // START B for i in 0..<contents.length() { let characterValue = CODE128_ALPHABET_STRING.location(contents[i]) sum += characterValue * (i + 1) } case .C: sum += self.codeTableSize - 2 // START C for i in 0..<contents.length() { if i % 2 == 1 { continue } else { let value = contents.substring(i, length: 2).toInt()! sum += value * (i / 2 + 1) } } } return CODE128_CHARACTER_ENCODINGS[sum % 103] } let CODE128_ALPHABET_STRING = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~" let CODE128_CHARACTER_ENCODINGS = [ "11011001100", "11001101100", "11001100110", "10010011000", "10010001100", "10001001100", "10011001000", "10011000100", "10001100100", "11001001000", "11001000100", "11000100100", "10110011100", "10011011100", "10011001110", "10111001100", "10011101100", "10011100110", "11001110010", "11001011100", "11001001110", "11011100100", "11001110100", "11101101110", "11101001100", "11100101100", "11100100110", "11101100100", "11100110100", "11100110010", "11011011000", "11011000110", "11000110110", "10100011000", "10001011000", "10001000110", "10110001000", "10001101000", "10001100010", "11010001000", "11000101000", "11000100010", "10110111000", "10110001110", "10001101110", "10111011000", "10111000110", "10001110110", "11101110110", "11010001110", "11000101110", "11011101000", "11011100010", "11011101110", "11101011000", "11101000110", "11100010110", "11101101000", "11101100010", "11100011010", "11101111010", "11001000010", "11110001010", "10100110000", // 64 // Visible character encoding for code table A ended. "10100001100", "10010110000", "10010000110", "10000101100", "10000100110", "10110010000", "10110000100", "10011010000", "10011000010", "10000110100", "10000110010", "11000010010", "11001010000", "11110111010", "11000010100", "10001111010", "10100111100", "10010111100", "10010011110", "10111100100", "10011110100", "10011110010", "11110100100", "11110010100", "11110010010", "11011011110", "11011110110", "11110110110", "10101111000", "10100011110", "10001011110", // Visible character encoding for code table B ended. "10111101000", "10111100010", "11110101000", "11110100010", "10111011110", // to C from A, B (size - 8) "10111101110", // to B from A, C (size - 7) "11101011110", // to A from B, C (size - 6) "11110101110", "11010000100", // START A (size - 4) "11010010000", // START B (size - 3) "11010011100", // START C (size - 2) "11000111010" // STOP (size - 1) ] }
fe6933026b91c7fafea6ac480e70c7a7
33.409669
133
0.521556
false
false
false
false
J-Mendes/Bliss-Assignement
refs/heads/master
Bliss-Assignement/Bliss-Assignement/Views/ProgressHUD.swift
lgpl-3.0
1
// // ProgressHUD.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import UIKit import JGProgressHUD class ProgressHUD: NSObject { private class func createProgressHUD() -> JGProgressHUD { let hud: JGProgressHUD = JGProgressHUD(style: .Dark) hud.interactionType = .BlockAllTouches hud.animation = JGProgressHUDFadeZoomAnimation() hud.backgroundColor = UIColor.init(white: 0.0, alpha: 0.4) hud.textLabel.font = UIFont.systemFontOfSize(14.0) hud.HUDView.layer.shadowColor = UIColor.blackColor().CGColor hud.HUDView.layer.shadowOffset = CGSizeZero hud.HUDView.layer.shadowOpacity = 0.4 hud.HUDView.layer.shadowRadius = 8.0 return hud } class func showProgressHUD(view: UIView, text: String = "", isSquared: Bool = true) { let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDsInView(view) as! [JGProgressHUD] if allHuds.count > 0 { let hud: JGProgressHUD = allHuds.first! hud.indicatorView = JGProgressHUDIndeterminateIndicatorView(HUDStyle: hud.style) hud.textLabel.text = text hud.square = isSquared } else { let newHud: JGProgressHUD = self.createProgressHUD() newHud.indicatorView = JGProgressHUDIndeterminateIndicatorView(HUDStyle: newHud.style) newHud.textLabel.text = text newHud.square = isSquared newHud.showInView(view) } } class func showSuccessHUD(view: UIView, text: String = "Success") { let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDsInView(view) as! [JGProgressHUD] if allHuds.count > 0 { let hud: JGProgressHUD = allHuds.first! hud.indicatorView = JGProgressHUDSuccessIndicatorView() hud.textLabel.text = text hud.dismissAfterDelay(3.0) } else { let newHud: JGProgressHUD = self.createProgressHUD() newHud.indicatorView = JGProgressHUDSuccessIndicatorView() newHud.textLabel.text = text newHud.showInView(view) newHud.dismissAfterDelay(3.0) } } class func showErrorHUD(view: UIView, text: String = "Error") { let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDsInView(view) as! [JGProgressHUD] if allHuds.count > 0 { let hud: JGProgressHUD = allHuds.first! hud.indicatorView = JGProgressHUDErrorIndicatorView() hud.textLabel.text = text hud.dismissAfterDelay(3.0) } else { let newHud: JGProgressHUD = self.createProgressHUD() newHud.indicatorView = JGProgressHUDErrorIndicatorView() newHud.textLabel.text = text newHud.showInView(view) newHud.dismissAfterDelay(3.0) } } class func dismissAllHuds(view: UIView) { JGProgressHUD.allProgressHUDsInView(view).forEach{ ($0 as! JGProgressHUD).dismiss() } } }
ec2969fb2b3815a89475c8a8b6482bbe
38.265823
100
0.641199
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureApp/Sources/FeatureAppUI/DeepLinking/DeepLinkCoordinator.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import Combine import DIKit import FeatureActivityUI import FeatureDashboardUI import protocol FeatureOnboardingUI.OnboardingRouterAPI import struct FeatureOnboardingUI.PromotionView import FeatureReferralDomain import FeatureReferralUI import FeatureSettingsUI import FeatureTransactionDomain import FeatureTransactionUI import FeatureWalletConnectDomain import MoneyKit import PlatformKit import PlatformUIKit import SwiftUI import ToolKit import UIComponentsKit import UIKit public final class DeepLinkCoordinator: Session.Observer { private let app: AppProtocol private let coincore: CoincoreAPI private let exchangeProvider: ExchangeProviding private let kycRouter: KYCRouting private let payloadFactory: CryptoTargetPayloadFactoryAPI private let window: TopMostViewControllerProviding private let transactionsRouter: TransactionsRouterAPI private let analyticsRecording: AnalyticsEventRecorderAPI private let onboardingRouter: OnboardingRouterAPI private let walletConnectService: () -> WalletConnectServiceAPI private var bag: Set<AnyCancellable> = [] // We can't resolve those at initialization private let accountsRouter: () -> AccountsRouting init( app: AppProtocol, coincore: CoincoreAPI, exchangeProvider: ExchangeProviding, kycRouter: KYCRouting, payloadFactory: CryptoTargetPayloadFactoryAPI, topMostViewControllerProvider: TopMostViewControllerProviding, transactionsRouter: TransactionsRouterAPI, analyticsRecording: AnalyticsEventRecorderAPI, walletConnectService: @escaping () -> WalletConnectServiceAPI, onboardingRouter: OnboardingRouterAPI, accountsRouter: @escaping () -> AccountsRouting ) { self.accountsRouter = accountsRouter self.app = app self.coincore = coincore self.exchangeProvider = exchangeProvider self.kycRouter = kycRouter self.payloadFactory = payloadFactory self.window = topMostViewControllerProvider self.transactionsRouter = transactionsRouter self.analyticsRecording = analyticsRecording self.walletConnectService = walletConnectService self.onboardingRouter = onboardingRouter } var observers: [AnyCancellable] { [ activity, buy, asset, qr, send, kyc, referrals, walletConnect, onboarding, promotion ] } public func start() { for observer in observers { observer.store(in: &bag) } } public func stop() { bag = [] } private lazy var activity = app.on(blockchain.app.deep_link.activity) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.showActivity(_:), on: self) private lazy var buy = app.on(blockchain.app.deep_link.buy) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.showTransactionBuy(_:), on: self) private lazy var send = app.on(blockchain.app.deep_link.send) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.showTransactionSend(_:), on: self) private lazy var asset = app.on(blockchain.app.deep_link.asset) .sink(to: DeepLinkCoordinator.showAsset, on: self) private lazy var qr = app.on(blockchain.app.deep_link.qr) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.qr(_:), on: self) private lazy var kyc = app.on(blockchain.app.deep_link.kyc) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.kyc(_:), on: self) private lazy var verifyEmail = app.on(blockchain.app.deep_link.kyc.verify.email) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.verifyEmail(_:), on: self) private lazy var referrals = app.on(blockchain.app.deep_link.referral) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.handleReferral, on: self) // Debouncing prevents the popup from being dismissed private lazy var walletConnect = app.on(blockchain.app.deep_link.walletconnect) .debounce(for: .seconds(1), scheduler: DispatchQueue.global(qos: .background)) .receive(on: DispatchQueue.main) .sink(to: DeepLinkCoordinator.handleWalletConnect, on: self) private lazy var onboarding = app.on(blockchain.app.deep_link.onboarding.post.sign.up) .receive(on: DispatchQueue.main) .flatMap { [weak self] _ -> AnyPublisher<Void, Never> in guard let self = self, let viewController = self.window.topMostViewController else { return .empty() } return self.onboardingRouter.presentPostSignUpOnboarding(from: viewController).mapToVoid() } .subscribe() private lazy var promotion = app.on(blockchain.ux.onboarding.promotion.launch.story) { @MainActor [app, window] event in guard let vc = window.topMostViewController else { return } let ref: Tag.Reference = try event.context.decode(event.tag) let id = try ref.tag.as(blockchain.ux.onboarding.type.promotion) try await vc.present(PromotionView(id, ux: app.get(id.story.key(to: ref.context))).app(app)) } .subscribe() func kyc(_ event: Session.Event) { guard let tier = try? event.context.decode(blockchain.app.deep_link.kyc.tier, as: KYC.Tier.self), let topViewController = window.topMostViewController else { return } kycRouter .presentEmailVerificationAndKYCIfNeeded(from: topViewController, requiredTier: tier) .subscribe() .store(in: &bag) } func verifyEmail(_ event: Session.Event) { guard let topViewController = window.topMostViewController else { return } kycRouter.presentEmailVerificationIfNeeded(from: topViewController) .subscribe() .store(in: &bag) } func qr(_ event: Session.Event) { let qrCodeScannerView = QRCodeScannerView() window .topMostViewController? .present(qrCodeScannerView) } func handleWalletConnect(_ event: Session.Event) { guard let uri = try? event.context.decode( blockchain.app.deep_link.walletconnect.uri, as: String.self ) else { return } walletConnectService().connect(uri) } func handleReferral(_ event: Session.Event) { app.publisher( for: blockchain.user.referral.campaign, as: Referral.self ) .receive(on: DispatchQueue.main) .compactMap(\.value) .sink(receiveValue: { referral in self.presentReferralCampaign(referral) }) .store(in: &bag) } private func presentReferralCampaign(_ referral: Referral) { analyticsRecording.record(event: AnalyticsEvents .New .Deeplinking .walletReferralProgramClicked()) let referralView = ReferFriendView(store: .init( initialState: .init(referralInfo: referral), reducer: ReferFriendModule.reducer, environment: .init( mainQueue: .main, analyticsRecorder: DIKit.resolve() ) )) window .topMostViewController? .present(referralView) } func showAsset(_ event: Session.Event) { let cryptoCurrency = ( try? event.context.decode(blockchain.app.deep_link.asset.code) as CryptoCurrency ) ?? .bitcoin app.post(event: blockchain.ux.asset[cryptoCurrency.code].select) } func showTransactionBuy(_ event: Session.Event) { do { let cryptoCurrency = try event.context.decode(blockchain.app.deep_link.buy.crypto.code) as CryptoCurrency coincore .cryptoAccounts(for: cryptoCurrency) .receive(on: DispatchQueue.main) .flatMap { [weak self] accounts -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .just(.abandoned) } return self .transactionsRouter .presentTransactionFlow(to: .buy(accounts.first)) } .subscribe() .store(in: &bag) } catch { transactionsRouter.presentTransactionFlow(to: .buy(nil)) .subscribe() .store(in: &bag) } } func showTransactionSend(_ event: Session.Event) { // If there is no crypto currency, show landing send. guard let cryptoCurrency = try? event.context.decode( blockchain.app.deep_link.send.crypto.code, as: CryptoCurrency.self ) else { showTransactionSendLanding() return } showTransactionSend( cryptoCurrency: cryptoCurrency, destination: try? event.context.decode( blockchain.app.deep_link.send.destination, as: String.self ) ) } private func showTransactionSendLanding() { transactionsRouter .presentTransactionFlow(to: .send(nil, nil)) .subscribe() .store(in: &bag) } private func showTransactionSend( cryptoCurrency: CryptoCurrency, destination: String? ) { let defaultAccount = coincore.cryptoAccounts(for: cryptoCurrency) .map(\.first) .eraseError() let target = transactionTarget( from: destination, cryptoCurrency: cryptoCurrency ) .optional() .replaceError(with: nil) .eraseError() defaultAccount .zip(target) .receive(on: DispatchQueue.main) .flatMap { [weak self] defaultAccount, target -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .just(.abandoned) } return self .transactionsRouter .presentTransactionFlow(to: .send(defaultAccount, target)) } .subscribe() .store(in: &bag) } /// Creates transaction target from given string. private func transactionTarget( from string: String?, cryptoCurrency: CryptoCurrency ) -> AnyPublisher<CryptoReceiveAddress, Error> { payloadFactory .create(fromString: string, asset: cryptoCurrency) .eraseError() .flatMap { target -> AnyPublisher<CryptoReceiveAddress, Error> in switch target { case .bitpay(let address): return BitPayInvoiceTarget .make(from: address, asset: cryptoCurrency) .map { $0 as CryptoReceiveAddress } .eraseError() .eraseToAnyPublisher() case .address(let cryptoReceiveAddress): return .just(cryptoReceiveAddress) } } .eraseToAnyPublisher() } func showActivity(_ event: Session.Event) { app.post(event: blockchain.ux.home.tab[blockchain.ux.user.activity].select) } }
7f91f1f914f4485d6a0df8723f6db66b
33.835329
124
0.62269
false
false
false
false
SummerHH/swift3.0WeBo
refs/heads/master
WeBo/Classes/View/HomeView/PicCollectionView.swift
apache-2.0
1
// // PicCollectionView.swift // WeBo // // Created by Apple on 16/11/7. // Copyright © 2016年 叶炯. All rights reserved. // import UIKit import SDWebImage let cellID = "cell" class PicCollectionView: UICollectionView { //MARK:- 定义属性 var picURL: [URL] = [URL]() { didSet { self.reloadData() } } //MARK:- 系统的回调函数 override func awakeFromNib() { super.awakeFromNib() self.dataSource = self self.delegate = self self.register(UINib.init(nibName: "PicCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellID) } } //MARK:- collectionView的数据源方法 extension PicCollectionView: UICollectionViewDataSource, UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.picURL.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建 cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! PicCollectionViewCell cell.picURL = picURL[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { DLog("Item 被点击了\(indexPath.item)") // 1.获取通知需要传递的参数 let userInfo = [ShowPhotoBrowserIndexKey : indexPath, ShowPhotoBrowserUrlsKey : picURL] as [String : Any] // 2.发出通知 NotificationCenter.default.post(name: Notification.Name(rawValue: ShowPhotoBrowserNote), object: self, userInfo: userInfo) } } extension PicCollectionView : AnimatorPresentedDelegate { func startRect(_ indexPath: IndexPath) -> CGRect { // 1.获取cell let cell = self.cellForItem(at: indexPath)! // 2.获取cell的frame let startFrame = self.convert(cell.frame, to: UIApplication.shared.keyWindow!) return startFrame } func endRect(_ indexPath: IndexPath) -> CGRect { // 1.获取该位置的image对象 let picURL = self.picURL[indexPath.item] let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURL.absoluteString) // 2.计算结束后的frame let w = UIScreen.main.bounds.width let h = w / (image?.size.width)! * (image?.size.height)! var y : CGFloat = 0 if h > UIScreen.main.bounds.height { y = 0 } else { y = (UIScreen.main.bounds.height - h) * 0.5 } return CGRect(x: 0, y: y, width: w, height: h) } func imageView(_ indexPath: IndexPath) -> UIImageView { // 1.创建UIImageView对象 let imageView = UIImageView() // 2.获取该位置的image对象 let picURL = self.picURL[indexPath.item] let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURL.absoluteString) // 3.设置imageView的属性 imageView.image = image imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView } }
9346fe194ebe643628571568f6d63ecc
29.358491
130
0.627408
false
false
false
false
demetrio812/EurekaCreditCard
refs/heads/master
Example/Pods/Eureka/Source/Core/Core.swift
mit
1
// Core.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: Row internal class RowDefaults { static var cellUpdate = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var cellSetup = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var onCellHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var onCellUnHighlight = Dictionary<String, (BaseCell, BaseRow) -> Void>() static var rowInitialization = Dictionary<String, BaseRow -> Void>() static var rawCellUpdate = Dictionary<String, Any>() static var rawCellSetup = Dictionary<String, Any>() static var rawOnCellHighlight = Dictionary<String, Any>() static var rawOnCellUnHighlight = Dictionary<String, Any>() static var rawRowInitialization = Dictionary<String, Any>() } // MARK: FormCells public struct CellProvider<Cell: BaseCell where Cell: CellType> { /// Nibname of the cell that will be created. public private (set) var nibName: String? /// Bundle from which to get the nib file. public private (set) var bundle: NSBundle! public init(){} public init(nibName: String, bundle: NSBundle? = nil){ self.nibName = nibName self.bundle = bundle ?? NSBundle(forClass: Cell.self) } /** Creates the cell with the specified style. - parameter cellStyle: The style with which the cell will be created. - returns: the cell */ func createCell(cellStyle: UITableViewCellStyle) -> Cell { if let nibName = self.nibName { return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell } return Cell.init(style: cellStyle, reuseIdentifier: nil) } } /** Enumeration that defines how a controller should be created. - Callback->VCType: Creates the controller inside the specified block - NibFile: Loads a controller from a nib file in some bundle - StoryBoard: Loads the controller from a Storyboard by its storyboard id */ public enum ControllerProvider<VCType: UIViewController>{ /** * Creates the controller inside the specified block */ case Callback(builder: (() -> VCType)) /** * Loads a controller from a nib file in some bundle */ case NibFile(name: String, bundle: NSBundle?) /** * Loads the controller from a Storyboard by its storyboard id */ case StoryBoard(storyboardId: String, storyboardName: String, bundle: NSBundle?) func createController() -> VCType { switch self { case .Callback(let builder): return builder() case .NibFile(let nibName, let bundle): return VCType.init(nibName: nibName, bundle:bundle ?? NSBundle(forClass: VCType.self)) case .StoryBoard(let storyboardId, let storyboardName, let bundle): let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? NSBundle(forClass: VCType.self)) return sb.instantiateViewControllerWithIdentifier(storyboardId) as! VCType } } } /** * Responsible for the options passed to a selector view controller */ public struct DataProvider<T: Equatable> { public let arrayData: [T]? public init(arrayData: [T]){ self.arrayData = arrayData } } /** Defines how a controller should be presented. - Show?: Shows the controller with `showViewController(...)`. - PresentModally?: Presents the controller modally. - SegueName?: Performs the segue with the specified identifier (name). - SegueClass?: Performs a segue from a segue class. */ public enum PresentationMode<VCType: UIViewController> { /** * Shows the controller, created by the specified provider, with `showViewController(...)`. */ case Show(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) /** * Presents the controller, created by the specified provider, modally. */ case PresentModally(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) /** * Performs the segue with the specified identifier (name). */ case SegueName(segueName: String, completionCallback: (UIViewController->())?) /** * Performs a segue from a segue class. */ case SegueClass(segueClass: UIStoryboardSegue.Type, completionCallback: (UIViewController->())?) case Popover(controllerProvider: ControllerProvider<VCType>, completionCallback: (UIViewController->())?) public var completionHandler: (UIViewController ->())? { switch self{ case .Show(_, let completionCallback): return completionCallback case .PresentModally(_, let completionCallback): return completionCallback case .SegueName(_, let completionCallback): return completionCallback case .SegueClass(_, let completionCallback): return completionCallback case .Popover(_, let completionCallback): return completionCallback } } /** Present the view controller provided by PresentationMode. Should only be used from custom row implementation. - parameter viewController: viewController to present if it makes sense (normally provided by createController method) - parameter row: associated row - parameter presentingViewController: form view controller */ public func presentViewController(viewController: VCType!, row: BaseRow, presentingViewController:FormViewController){ switch self { case .Show(_, _): presentingViewController.showViewController(viewController, sender: row) case .PresentModally(_, _): presentingViewController.presentViewController(viewController, animated: true, completion: nil) case .SegueName(let segueName, _): presentingViewController.performSegueWithIdentifier(segueName, sender: row) case .SegueClass(let segueClass, _): let segue = segueClass.init(identifier: row.tag, source: presentingViewController, destination: viewController) presentingViewController.prepareForSegue(segue, sender: row) segue.perform() case .Popover(_, _): guard let porpoverController = viewController.popoverPresentationController else { fatalError() } porpoverController.sourceView = porpoverController.sourceView ?? presentingViewController.tableView porpoverController.sourceRect = porpoverController.sourceRect ?? row.baseCell.frame presentingViewController.presentViewController(viewController, animated: true, completion: nil) } } /** Creates the view controller specified by presentation mode. Should only be used from custom row implementation. - returns: the created view controller or nil depending on the PresentationMode type. */ public func createController() -> VCType? { switch self { case .Show(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller case .PresentModally(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller case .Popover(let controllerProvider, let completionCallback): let controller = controllerProvider.createController() controller.modalPresentationStyle = .Popover let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.completionCallback = callback } return controller default: return nil } } } /** * Protocol to be implemented by custom formatters. */ public protocol FormatterProtocol { func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition } //MARK: Predicate Machine enum ConditionType { case Hidden, Disabled } /** Enumeration that are used to specify the disbaled and hidden conditions of rows - Function: A function that calculates the result - Predicate: A predicate that returns the result */ public enum Condition { /** * Calculate the condition inside a block * * @param Array of tags of the rows this function depends on * @param Form->Bool The block that calculates the result * * @return If the condition is true or false */ case Function([String], Form->Bool) /** * Calculate the condition using a NSPredicate * * @param NSPredicate The predicate that will be evaluated * * @return If the condition is true or false */ case Predicate(NSPredicate) } extension Condition : BooleanLiteralConvertible { /** Initialize a condition to return afixed boolean value always */ public init(booleanLiteral value: Bool){ self = Condition.Function([]) { _ in return value } } } extension Condition : StringLiteralConvertible { /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(stringLiteral value: String){ self = .Predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(unicodeScalarLiteral value: String) { self = .Predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(extendedGraphemeClusterLiteral value: String) { self = .Predicate(NSPredicate(format: value)) } } //MARK: Errors /** Errors thrown by Eureka - DuplicatedTag: When a section or row is inserted whose tag dows already exist */ public enum EurekaError : ErrorType { case DuplicatedTag(tag: String) } //Mark: FormViewController /** * A protocol implemented by FormViewController */ public protocol FormViewControllerProtocol { var tableView: UITableView? { get } func beginEditing<T:Equatable>(cell: Cell<T>) func endEditing<T:Equatable>(cell: Cell<T>) func insertAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation func deleteAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation func reloadAnimationOldRows(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation func insertAnimationForSections(sections : [Section]) -> UITableViewRowAnimation func deleteAnimationForSections(sections : [Section]) -> UITableViewRowAnimation func reloadAnimationOldSections(oldSections: [Section], newSections:[Section]) -> UITableViewRowAnimation } /** * Navigation options for a form view controller. */ public struct RowNavigationOptions : OptionSetType { private enum NavigationOptions : Int { case Disabled = 0, Enabled = 1, StopDisabledRow = 2, SkipCanNotBecomeFirstResponderRow = 4 } public let rawValue: Int public init(rawValue: Int){ self.rawValue = rawValue} private init(_ options:NavigationOptions ){ self.rawValue = options.rawValue } /// No navigation. public static let Disabled = RowNavigationOptions(.Disabled) /// Full navigation. public static let Enabled = RowNavigationOptions(.Enabled) /// Break navigation when next row is disabled. public static let StopDisabledRow = RowNavigationOptions(.StopDisabledRow) /// Break navigation when next row cannot become first responder. public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.SkipCanNotBecomeFirstResponderRow) } /** * Defines the configuration for the keyboardType of FieldRows. */ public struct KeyboardReturnTypeConfiguration { /// Used when the next row is available. public var nextKeyboardType = UIReturnKeyType.Next /// Used if next row is not available. public var defaultKeyboardType = UIReturnKeyType.Default public init(){} public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType){ self.nextKeyboardType = nextKeyboardType self.defaultKeyboardType = defaultKeyboardType } } /** * Options that define when an inline row should collapse. */ public struct InlineRowHideOptions : OptionSetType { private enum _InlineRowHideOptions : Int { case Never = 0, AnotherInlineRowIsShown = 1, FirstResponderChanges = 2 } public let rawValue: Int public init(rawValue: Int){ self.rawValue = rawValue} private init(_ options:_InlineRowHideOptions ){ self.rawValue = options.rawValue } /// Never collapse automatically. Only when user taps inline row. public static let Never = InlineRowHideOptions(.Never) /// Collapse qhen another inline row expands. Just one inline row will be expanded at a time. public static let AnotherInlineRowIsShown = InlineRowHideOptions(.AnotherInlineRowIsShown) /// Collapse when first responder changes. public static let FirstResponderChanges = InlineRowHideOptions(.FirstResponderChanges) } /// View controller that shows a form. public class FormViewController : UIViewController, FormViewControllerProtocol { @IBOutlet public var tableView: UITableView? private lazy var _form : Form = { [weak self] in let form = Form() form.delegate = self return form }() public var form : Form { get { return _form } set { _form.delegate = nil tableView?.endEditing(false) _form = newValue _form.delegate = self if isViewLoaded() && tableView?.window != nil { tableView?.reloadData() } } } /// Accessory view that is responsible for the navigation between rows lazy public var navigationAccessoryView : NavigationAccessoryView = { [unowned self] in let naview = NavigationAccessoryView(frame: CGRectMake(0, 0, self.view.frame.width, 44.0)) naview.tintColor = self.view.tintColor return naview }() /// Defines the behaviour of the navigation between rows public var navigationOptions : RowNavigationOptions? private var tableViewStyle: UITableViewStyle = .Grouped public init(style: UITableViewStyle) { super.init(nibName: nil, bundle: nil) tableViewStyle = style } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func viewDidLoad() { super.viewDidLoad() if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(.FlexibleHeight) if #available(iOS 9.0, *){ tableView?.cellLayoutMarginsFollowReadableWidth = false } } if tableView?.superview == nil { view.addSubview(tableView!) } if tableView?.delegate == nil { tableView?.delegate = self } if tableView?.dataSource == nil { tableView?.dataSource = self } tableView?.estimatedRowHeight = BaseRow.estimatedRowHeight } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let selectedIndexPaths = tableView?.indexPathsForSelectedRows ?? [] tableView?.reloadRowsAtIndexPaths(selectedIndexPaths, withRowAnimation: .None) selectedIndexPaths.forEach { tableView?.selectRowAtIndexPath($0, animated: false, scrollPosition: .None) } let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in selectedIndexPaths.forEach { self?.tableView?.deselectRowAtIndexPath($0, animated: context.isAnimated()) } } let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in if context.isCancelled() { selectedIndexPaths.forEach { self?.tableView?.selectRowAtIndexPath($0, animated: false, scrollPosition: .None) } } } if let coordinator = transitionCoordinator() { coordinator.animateAlongsideTransitionInView(parentViewController?.view, animation: deselectionAnimation, completion: reselection) } else { selectedIndexPaths.forEach { tableView?.deselectRowAtIndexPath($0, animated: false) } } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) let baseRow = sender as? BaseRow baseRow?.prepareForSegue(segue) } /** Returns the navigation accessory view if it is enabled. Returns nil otherwise. */ public func inputAccessoryViewForRow(row: BaseRow) -> UIView? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard row.baseCell.cellCanBecomeFirstResponder() else { return nil} navigationAccessoryView.previousButton.enabled = nextRowForRow(row, withDirection: .Up) != nil navigationAccessoryView.doneButton.target = self navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:)) navigationAccessoryView.previousButton.target = self navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.target = self navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.enabled = nextRowForRow(row, withDirection: .Down) != nil return navigationAccessoryView } //MARK: FormDelegate public func rowValueHasBeenChanged(row: BaseRow, oldValue: Any?, newValue: Any?) {} //MARK: FormViewControllerProtocol /** Called when a cell becomes first responder */ public final func beginEditing<T:Equatable>(cell: Cell<T>) { cell.row.highlightCell() guard let _ = tableView where (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return } let row = cell.baseRow let inlineRow = row._inlineRow for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } /** Called when a cell resigns first responder */ public final func endEditing<T:Equatable>(cell: Cell<T>) { cell.row.unhighlightCell() } /** Returns the animation for the insertion of the given rows. */ public func insertAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation { return .Fade } /** Returns the animation for the deletion of the given rows. */ public func deleteAnimationForRows(rows: [BaseRow]) -> UITableViewRowAnimation { return .Fade } /** Returns the animation for the reloading of the given rows. */ public func reloadAnimationOldRows(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the insertion of the given sections. */ public func insertAnimationForSections(sections: [Section]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the deletion of the given sections. */ public func deleteAnimationForSections(sections: [Section]) -> UITableViewRowAnimation { return .Automatic } /** Returns the animation for the reloading of the given sections. */ public func reloadAnimationOldSections(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation { return .Automatic } //MARK: TextField and TextView Delegate public func textInputShouldBeginEditing<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputDidBeginEditing<T>(textInput: UITextInput, cell: Cell<T>) { if let row = cell.row as? KeyboardReturnHandler { let nextRow = nextRowForRow(cell.row, withDirection: .Down) if let textField = textInput as? UITextField { textField.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } else if let textView = textInput as? UITextView { textView.returnKeyType = nextRow != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } } } public func textInputShouldEndEditing<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputDidEndEditing<T>(textInput: UITextInput, cell: Cell<T>) { } public func textInput<T>(textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool { return true } public func textInputShouldClear<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { return true } public func textInputShouldReturn<T>(textInput: UITextInput, cell: Cell<T>) -> Bool { if let nextRow = nextRowForRow(cell.row, withDirection: .Down){ if nextRow.baseCell.cellCanBecomeFirstResponder(){ nextRow.baseCell.cellBecomeFirstResponder() return true } } tableView?.endEditing(true) return true } //MARK: Private private var oldBottomInset : CGFloat? } extension FormViewController : UITableViewDelegate { //MARK: UITableViewDelegate public func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { return indexPath } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard tableView == self.tableView else { return } let row = form[indexPath] // row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds. if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() { self.tableView?.endEditing(true) } row.didSelect() } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.rowHeight } public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.estimatedRowHeight } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return form[section].header?.viewForSection(form[section], type: .Header) } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return form[section].footer?.viewForSection(form[section], type:.Footer) } public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let height = form[section].header?.height { return height() } guard let view = form[section].header?.viewForSection(form[section], type: .Header) else{ return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let height = form[section].footer?.height { return height() } guard let view = form[section].footer?.viewForSection(form[section], type: .Footer) else{ return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } } extension FormViewController : UITableViewDataSource { //MARK: UITableViewDataSource public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return form.count } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form[section].count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { form[indexPath].updateCell() return form[indexPath].baseCell } public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form[section].header?.title } public func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form[section].footer?.title } } extension FormViewController: FormDelegate { //MARK: FormDelegate public func sectionsHaveBeenAdded(sections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.insertSections(atIndexes, withRowAnimation: insertAnimationForSections(sections)) tableView?.endUpdates() } public func sectionsHaveBeenRemoved(sections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.deleteSections(atIndexes, withRowAnimation: deleteAnimationForSections(sections)) tableView?.endUpdates() } public func sectionsHaveBeenReplaced(oldSections oldSections:[Section], newSections: [Section], atIndexes: NSIndexSet){ tableView?.beginUpdates() tableView?.reloadSections(atIndexes, withRowAnimation: reloadAnimationOldSections(oldSections, newSections: newSections)) tableView?.endUpdates() } public func rowsHaveBeenAdded(rows: [BaseRow], atIndexPaths: [NSIndexPath]) { tableView?.beginUpdates() tableView?.insertRowsAtIndexPaths(atIndexPaths, withRowAnimation: insertAnimationForRows(rows)) tableView?.endUpdates() } public func rowsHaveBeenRemoved(rows: [BaseRow], atIndexPaths: [NSIndexPath]) { tableView?.beginUpdates() tableView?.deleteRowsAtIndexPaths(atIndexPaths, withRowAnimation: deleteAnimationForRows(rows)) tableView?.endUpdates() } public func rowsHaveBeenReplaced(oldRows oldRows:[BaseRow], newRows: [BaseRow], atIndexPaths: [NSIndexPath]){ tableView?.beginUpdates() tableView?.reloadRowsAtIndexPaths(atIndexPaths, withRowAnimation: reloadAnimationOldRows(oldRows, newRows: newRows)) tableView?.endUpdates() } } extension FormViewController : UIScrollViewDelegate { //MARK: UIScrollViewDelegate public func scrollViewWillBeginDragging(scrollView: UIScrollView) { tableView?.endEditing(true) } } extension FormViewController { //MARK: KeyBoard Notifications /** Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary. */ public func keyboardWillShow(notification: NSNotification){ guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return } let keyBoardInfo = notification.userInfo! let keyBoardFrame = table.window!.convertRect((keyBoardInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue)!, toView: table.superview) let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets oldBottomInset = oldBottomInset ?? tableInsets.bottom if newBottomInset > oldBottomInset { tableInsets.bottom = newBottomInset scrollIndicatorInsets.bottom = tableInsets.bottom UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue)!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets if let selectedRow = table.indexPathForCell(cell) { table.scrollToRowAtIndexPath(selectedRow, atScrollPosition: .None, animated: false) } UIView.commitAnimations() } } /** Called when the keyboard will disappear. Adjusts insets of the tableView. */ public func keyboardWillHide(notification: NSNotification){ guard let table = tableView, let oldBottom = oldBottomInset else { return } let keyBoardInfo = notification.userInfo! var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets tableInsets.bottom = oldBottom scrollIndicatorInsets.bottom = tableInsets.bottom oldBottomInset = nil UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue)!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } } public enum Direction { case Up, Down } extension FormViewController { //MARK: Navigation Methods func navigationDone(sender: UIBarButtonItem) { tableView?.endEditing(true) } func navigationAction(sender: UIBarButtonItem) { navigateToDirection(sender == navigationAccessoryView.previousButton ? .Up : .Down) } public func navigateToDirection(direction: Direction){ guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return } guard let currentIndexPath = tableView?.indexPathForCell(currentCell) else { assertionFailure(); return } guard let nextRow = nextRowForRow(form[currentIndexPath], withDirection: direction) else { return } if nextRow.baseCell.cellCanBecomeFirstResponder(){ tableView?.scrollToRowAtIndexPath(nextRow.indexPath()!, atScrollPosition: .None, animated: false) nextRow.baseCell.cellBecomeFirstResponder(direction) } } private func nextRowForRow(currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard let nextRow = direction == .Down ? form.nextRowForRow(currentRow) : form.previousRowForRow(currentRow) else { return nil } if nextRow.isDisabled && options.contains(.StopDisabledRow) { return nil } if !nextRow.baseCell.cellCanBecomeFirstResponder() && !nextRow.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow){ return nil } if (!nextRow.isDisabled && nextRow.baseCell.cellCanBecomeFirstResponder()){ return nextRow } return nextRowForRow(nextRow, withDirection:direction) } } extension FormViewControllerProtocol { //MARK: Helpers func makeRowVisible(row: BaseRow){ guard let cell = row.baseCell, indexPath = row.indexPath(), tableView = tableView else { return } if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height){ tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true) } } }
a485f1a53fd142c150863d7bfc9e05e9
38.816282
352
0.677921
false
false
false
false
davidear/PasswordMenu
refs/heads/master
PasswordMenu/Model/ModelFactory.swift
mit
1
// // ModelFactory.swift // PasswordMenu // // Created by DaiFengyi on 15/11/23. // Copyright © 2015年 DaiFengyi. All rights reserved. // import UIKit class ModelFactory: NSObject { class func element(type: String) -> Element { let ele = Element.MR_createEntity() ele.leftText = type switch type { case "文本": ele.type = "text" case "密码": ele.type = "password" // todo // case "日期": // ele.type = "date" // case "图像": // ele.type = "image" default: break } return ele } class func elementTypeList() -> [String] { return ["文本", "密码"] } }
0d2f6e89e46a4f41199c74440d1bf0c4
20
53
0.495798
false
false
false
false
LoganWright/Genome
refs/heads/master
Packages/Node-1.0.1/Sources/Node/Core/Node+Literals.swift
mit
2
extension Node: ExpressibleByNilLiteral { public init(nilLiteral value: Void) { self = .null } } extension Node: ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension Node: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self = value.makeNode(context: EmptyNode) } } extension Node: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self = value.makeNode(context: EmptyNode) } } extension Node: ExpressibleByStringLiteral { public init(unicodeScalarLiteral value: String) { self.init(value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(value) } public init(stringLiteral value: String) { self.init(value) } } extension Node: ExpressibleByArrayLiteral { public init(arrayLiteral elements: Node...) { self = .array(elements) } } extension Node: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Node)...) { var object = [String : Node](minimumCapacity: elements.count) elements.forEach { key, value in object[key] = value } self = .object(object) } }
5bfd4cd76f4880891c29cc396701ec6e
24.037736
69
0.670686
false
false
false
false
tsc000/SCCycleScrollView
refs/heads/master
SCCycleScrollView/SCCycleScrollView/Source/SCCycleScrollView.swift
mit
1
// // SCCycleScrollView.swift // SCCycleScrollView // // Created by 童世超 on 2017/6/19. // Copyright © 2017年 童世超. All rights reserved. // import UIKit public enum CycleScrollViewCellStyle: String{ case image = "图片" case title = "文字" case mix = "图片和文字" case custom = "自定义" } public enum CycleScrollViewPageControlStyle: String{ case classic = "系统样式" case none = "无" case custom = "自定义" } open class SCCycleScrollView: UIView { //MARK: - SCCycleScrollView属性接口 //>>>>>>>>>>>>>>>>>>>>>> SCCycleScrollView属性接口 >>>>>>>>>>>>>>>>>>>>>>>>>>> /// 占位图片 open var placeholderImage: UIImage? /// cell类型:图片类型和文字类型 open var cellType: CycleScrollViewCellStyle? /// SCCycleScrollView代理 open var delegate: SCCycleScrollViewDelegate? { didSet { registerCell() } } /// 轮播图滚动方向,默认水平 open var scrollDirection: UICollectionView.ScrollDirection = .horizontal /// 定时时间间隔,默认1.0秒 open var timeInterval: CGFloat = 1.0 /// 只有一张图片时是否隐藏pageControl,默认隐藏 open var isHiddenOnlyPage: Bool = true //MARK: - title属性接口 //>>>>>>>>>>>>>>>>>>>>>> title属性接口 >>>>>>>>>>>>>>>>>>>>>>>>>>> /// 文字颜色,默认非纯白(在图片类型和文字类型中通用) open var titleColor: UIColor = UIColor(red: 0xe5 / 255.0, green: 0xf0 / 255.0, blue: 0xf4 / 255.0, alpha: 1.0) /// 文字大小,默认18(在图片类型和文字类型中通用) open var titleFont: UIFont = UIFont.systemFont(ofSize: 18) /// 文字左侧边距,默认10 open var titleLeftMargin: CGFloat = 10 /// 文字背景条颜色,默认黑色 open var titleContainerBackgroundColor: UIColor? = UIColor.black /// 文字背景条透明度,默认0.6 open var titleContainerAlpha: CGFloat = 0.6 //MARK: - pageControl属性接口 //>>>>>>>>>>>>>>>>>>>>>> pageControl属性接口 >>>>>>>>>>>>>>>>>>>>>>>>>>> /// 当前指示器样式,默认系统自带 open var pageControlStyle: CycleScrollViewPageControlStyle = .classic /// 当前指示器颜色,默认白色 open var currentPageIndicatorTintColor: UIColor = UIColor.white /// 非选中指示器颜色,默认亮灰色 open var pageIndicatorTintColor: UIColor = UIColor.lightGray open var pageControlOrigin: CGPoint = CGPoint(x: 0, y: 0) { didSet { if pageControlStyle == .classic { pageControl.frame.origin = pageControlOrigin } } } /// 外界获取pageControl的size(只读) open var pageControlSize: CGSize { get { if pageControlStyle == .classic { return pageControl.frame.size } else { return CGSize(width: 0, height: 0) } } } //>>>>>>>>>>>>>>>>>>>>>> 数据源 >>>>>>>>>>>>>>>>>>>>>>>>>>> /// 图片数据源 open var imageArray: [Any]? { didSet { guard let cellType = cellType else { return } switch cellType { case .title://如果是文字轮播,直接返回,防止出错 return case .mix, .image, .custom: if let images = imageArray, images.count > 0 { if pageControlStyle == .classic { if images.count >= 2 { pageControl.isHidden = false } pageControl.numberOfPages = images.count pageControl.frame.size.width = pageControl.size(forNumberOfPages: pageControl.numberOfPages).width } internalImageArray = imageArray } else { //[] 或 nil internalImageArray = [""] as [AnyObject] pageControl.numberOfPages = 1 pageControl.frame.size.width = pageControl.size(forNumberOfPages: pageControl.numberOfPages).width } if cellType == .mix { configureInternalTitleArray() } } setNeedsLayout() collectionView.reloadData() } } /// 文字数据源 open var titleArray: [String]? { didSet { //如果是图片轮播,直接返回,防止出错 if cellType == .image { return } if let array = titleArray, array.count > 0 { internalTitleArray = titleArray } else { //[] 或 nil internalTitleArray = [""] } if cellType == .mix { configureInternalTitleArray() } else { setNeedsLayout() collectionView.reloadData() } } } //MARK: - 私有属性 ////////////////////// 私有属性 ////////////////////// fileprivate var currentPage: Int = 0 fileprivate var timer: Timer? fileprivate var internalImageArray: [Any]? fileprivate var internalTitleArray: [String]? //MARK: - 方法 //>>>>>>>>>>>>>>>>>>>>>> 方法 >>>>>>>>>>>>>>>>>>>>>>>>>>> /// 创建图片 /// /// - Parameters: /// - frame: 轮播图位置 /// - delegate: SCCycleScrollView代理 /// - imageArray: 图片数据源,默认值nil /// - placeholderImage: 占位图片 /// - Returns: 返回SCCycleScrollView对象 open class func cycleScrollView(frame: CGRect, delegate: SCCycleScrollViewDelegate?, imageArray: [AnyObject]? = nil, pageControlStyle: CycleScrollViewPageControlStyle = .classic, placeholderImage: UIImage?) -> SCCycleScrollView { let cycleScrollView = SCCycleScrollView(frame: frame) cycleScrollView.pageControlStyle = pageControlStyle cycleScrollView.placeholderImage = placeholderImage cycleScrollView.delegate = delegate cycleScrollView.cellType = .image cycleScrollView.imageArray = imageArray return cycleScrollView } /// 创建文字轮播图 /// /// - Parameters: /// - frame: 轮播图位置 /// - delegate: SCCycleScrollView代理 /// - titleArray: 文字数据源,默认值nil /// - Returns: 返回SCCycleScrollView对象 open class func cycleScrollView(frame: CGRect, delegate: SCCycleScrollViewDelegate?, titleArray: [String]? = []) -> SCCycleScrollView { let cycleScrollView = SCCycleScrollView(frame: frame) cycleScrollView.pageControlStyle = .none cycleScrollView.cellType = .title cycleScrollView.delegate = delegate cycleScrollView.titleArray = titleArray return cycleScrollView } /// 创建图片和文字轮播图 /// /// - Parameters: /// - frame: 轮播图位置 /// - delegate: SCCycleScrollView代理 /// - imageArray: 图片数据源,默认值nil /// - titleArray: 文字数据源,默认值nil /// - placeholderImage: 占位图片 /// - Returns: 返回SCCycleScrollView对象 open class func cycleScrollView(frame: CGRect, delegate: SCCycleScrollViewDelegate?, imageArray: [AnyObject]? = nil, titleArray: [String]? = [], pageControlStyle: CycleScrollViewPageControlStyle = .classic, placeholderImage: UIImage?) -> SCCycleScrollView { let cycleScrollView = SCCycleScrollView(frame: frame) cycleScrollView.pageControlStyle = pageControlStyle cycleScrollView.placeholderImage = placeholderImage cycleScrollView.cellType = .mix cycleScrollView.delegate = delegate cycleScrollView.imageArray = imageArray cycleScrollView.titleArray = titleArray return cycleScrollView } //MARK: - Event @objc private func roll() { currentPage = currentPage + 1 let count = (cellType != .title) ? (internalImageArray?.count ?? 0) : (internalTitleArray?.count ?? 0) switch scrollDirection { case .horizontal: if collectionView.contentOffset.x == CGFloat(count * String.cycleCount - 1) * self.frame.size.width { currentPage = currentPage / 2 } case .vertical: if collectionView.contentOffset.y == CGFloat(count * String.cycleCount - 1) * self.frame.size.height { currentPage = currentPage / 2 } } let indexPath = IndexPath(item: currentPage, section:0) collectionView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: true) } //MARK: - Logic private func registerCell() { let validationResult: AnyClass? = self.delegate?.cellType?(for: self) let respondsValidation = self.delegate?.responds(to: #selector(SCCycleScrollViewDelegate.cellType(for:))) let respondsConfigure = self.delegate?.responds(to: #selector(SCCycleScrollViewDelegate.configureCollectionViewCell(cell:atIndex:for:))) guard let _ = respondsConfigure, let _ = respondsValidation, let _ = validationResult, cellType == .custom else { return } self.collectionView.register(validationResult.self, forCellWithReuseIdentifier: .cycleScrollViewID) } private func configureCycleScrollView(scrollEnabled: Bool, pageHidden: Bool, timerBlock: (() -> Void)) { flowLayout.scrollDirection = scrollDirection switch self.cellType { case .image?, .mix?, .custom?: //经过imageArray的处理保证了internalImageArray一定非空 currentPage = String.cycleCount * (internalImageArray?.count ?? 0) / 2 case .title?: //经过titleArray的处理保证了internalTitleArray一定非空 currentPage = String.cycleCount * (internalTitleArray?.count ?? 0) / 2 collectionView.backgroundColor = UIColor.clear case .none: break } let indexPath = IndexPath(item: currentPage, section:0) collectionView.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: false) collectionView.isScrollEnabled = scrollEnabled if pageControlStyle == .classic && (cellType != .title) { pageControl.isHidden = pageHidden } timerBlock() } /// 根据internalImageArray配置internalTitleArray private func configureInternalTitleArray() { if internalTitleArray == nil { internalTitleArray = [] } //将文字数组个数和图片数组个数设置成一致,只能比其多,不能少 if let imageCount = internalImageArray?.count, let titleCount = internalTitleArray?.count, imageCount > titleCount { for _ in 0..<(imageCount - titleCount) { internalTitleArray?.append("") } } } //配置cell private func configureCell(cell: SCCycleScrollViewCell, atIndexPath indexPath: IndexPath, scrollViewStyle: CycleScrollViewCellStyle) { if scrollViewStyle == .title { if let count = internalTitleArray?.count, count > 0 { cell.title = internalTitleArray?[indexPath.row % count] } } else if scrollViewStyle == .mix { cell.placeholderImage = placeholderImage if let count = internalImageArray?.count, count > 0 { cell.image = internalImageArray?[indexPath.row % count] cell.title = internalTitleArray?[indexPath.row % count] } } cell.titleFont = titleFont cell.titleColor = titleColor cell.titleLeftMargin = titleLeftMargin cell.titleContainerAlpha = titleContainerAlpha cell.titleContainerBackgroundColor = titleContainerBackgroundColor } fileprivate func setupTimer() { guard timer == nil else { return } timer = Timer(timeInterval: TimeInterval(timeInterval), target: self, selector: #selector(roll), userInfo: nil, repeats: true) RunLoop.current.add(timer!, forMode: RunLoop.Mode.common) } fileprivate func invalidateTimer() { guard timer != nil else { return } timer?.invalidate() timer = nil } private func initial() { //不加会不正常,这个是automaticallyAdjustsScrollViewInsets的影响 addSubview(UIView()) let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) flowLayout.itemSize = self.frame.size collectionView.frame = frame collectionView.collectionViewLayout = flowLayout collectionView.delegate = self collectionView.dataSource = self } override open func layoutSubviews() { super.layoutSubviews() switch self.cellType { case .image?, .mix?: //图片, 图片+文字 guard let count = internalImageArray?.count, count > 1 else { configureCycleScrollView(scrollEnabled: false, pageHidden: isHiddenOnlyPage, timerBlock: invalidateTimer) return } case .title?: //文字 guard let count = internalTitleArray?.count, count > 1 else { configureCycleScrollView(scrollEnabled: false, pageHidden: isHiddenOnlyPage, timerBlock: invalidateTimer) return } case .custom?: guard let count = internalImageArray?.count, count > 1 else { configureCycleScrollView(scrollEnabled: false, pageHidden: isHiddenOnlyPage, timerBlock: invalidateTimer) return } case .none: break } configureCycleScrollView(scrollEnabled: true, pageHidden: false, timerBlock: setupTimer) } override init(frame: CGRect) { super.init(frame: frame) initial() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - GET private lazy var flowLayout: UICollectionViewFlowLayout = { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 return flowLayout }() fileprivate lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.null, collectionViewLayout: UICollectionViewLayout()) collectionView.isPagingEnabled = true collectionView.scrollsToTop = false //清除collectionView背景色,否则文字背景条的透明度不起作用 collectionView.backgroundColor = UIColor.white collectionView.bounces = false collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.register(SCCycleScrollViewCell.self, forCellWithReuseIdentifier: .cycleScrollViewID) addSubview(collectionView) return collectionView }() fileprivate lazy var pageControl: UIPageControl = { let frame = CGRect(x: 0, y: 0, width: 0, height: 6) let pageControl = UIPageControl(frame: frame) pageControl.currentPageIndicatorTintColor = UIColor.white //默认指示器颜色 pageControl.pageIndicatorTintColor = UIColor.lightGray addSubview(pageControl) return pageControl }() } //MARK: - UICollectionViewDataSource UICollectionViewDataSource extension SCCycleScrollView: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = (cellType != .title) ? (internalImageArray?.count ?? 0) : (internalTitleArray?.count ?? 0) return count * String.cycleCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: .cycleScrollViewID, for: indexPath) let respondsConfigure = self.delegate?.responds(to: #selector(SCCycleScrollViewDelegate.configureCollectionViewCell(cell:atIndex:for:))) let respondsValidation = self.delegate?.responds(to: #selector(SCCycleScrollViewDelegate.cellType(for:))) var validationResult: AnyClass? if let respondsValidation = respondsValidation, respondsValidation { validationResult = self.delegate?.cellType?(for: self) } if let respondsConfigure = respondsConfigure, let respondsValidation = respondsValidation, let _ = validationResult, respondsConfigure && respondsValidation, cellType == .custom { return cell } /***********************************自带cell配置*********************************************/ let cycyleScrollViewCell = cell as! SCCycleScrollViewCell if let type = cellType { switch type { case .image: cycyleScrollViewCell.placeholderImage = placeholderImage if let count = internalImageArray?.count, count > 0 { cycyleScrollViewCell.image = internalImageArray?[indexPath.row % count] } case .title: configureCell(cell: cycyleScrollViewCell, atIndexPath: indexPath, scrollViewStyle: type) case .mix: configureCell(cell: cycyleScrollViewCell, atIndexPath: indexPath, scrollViewStyle: type) default: break } cycyleScrollViewCell.cellType = cellType } return cycyleScrollViewCell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let count = (cellType != .title) ? (internalImageArray?.count ?? 0) : (internalTitleArray?.count ?? 0) guard count != 0 else { return } delegate?.cycleScrollView?(self, didSelectItemAt: indexPath.row % count) } } //MARK: - UIScrollViewDelegate extension SCCycleScrollView: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollDirection == .horizontal { currentPage = Int((scrollView.contentOffset.x + scrollView.frame.width / 2.0) / scrollView.frame.width) } else { currentPage = Int((scrollView.contentOffset.y + scrollView.frame.height / 2.0) / scrollView.frame.height) } guard let count = internalImageArray?.count, count > 0 else { return } if pageControlStyle == .classic { pageControl.currentPage = currentPage % count } else if pageControlStyle == .custom { self.delegate?.cycleScrollView?(self, didScroll: scrollView, atIndex: currentPage % count) } } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { invalidateTimer() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { setupTimer() } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let count = (cellType != .title) ? (internalImageArray?.count ?? 0) : (internalTitleArray?.count ?? 0) guard count != 0 else { return } delegate?.cycleScrollView?(self, didScroll2ItemAt: currentPage % count) } } fileprivate extension String { static let cycleScrollViewID = "SCCycleScrollViewID" static let cycleCount = 1000 } @objc public protocol SCCycleScrollViewDelegate: NSObjectProtocol { @objc optional func cycleScrollView(_ cycleScrollView: SCCycleScrollView, didSelectItemAt index: Int) @objc optional func cycleScrollView(_ cycleScrollView: SCCycleScrollView, didScroll2ItemAt index: Int) //如果实现自定义pageControl实现此代理方法 @objc optional func cycleScrollView(_ cycleScrollView: SCCycleScrollView, didScroll scrollView: UIScrollView, atIndex index: NSInteger) //如果自定义cell需要实现下面两个代理方法 @objc optional func configureCollectionViewCell(cell: UICollectionViewCell, atIndex index: NSInteger, for cycleScrollView: SCCycleScrollView) @objc optional func cellType(for cycleScrollView: SCCycleScrollView) -> AnyClass }
abca1168b3bc5d994006797799c972fe
35.717391
146
0.598727
false
false
false
false
Ivacker/swift
refs/heads/master
test/SourceKit/CursorInfo/cursor_getter.swift
apache-2.0
20
var t1 : Bool { return true } var t2 : Bool { get { return true } } var t3 : Bool { get { return true } set {} } struct S1 { subscript(i: Int) -> Bool { return true } } // Checks that we don't crash. // RUN: %sourcekitd-test -req=cursor -pos=1:15 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=1:17 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=2:15 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=2:17 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=2:21 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=2:23 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:15 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:17 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:21 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:23 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:37 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=3:41 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=6:29 %s -- %s | FileCheck %s // RUN: %sourcekitd-test -req=cursor -pos=6:31 %s -- %s | FileCheck %s // CHECK: <empty cursor info>
57c2cc035b88b879150e9f74357fcb51
50.166667
70
0.617264
false
true
false
false
wyp767363905/GiftSay
refs/heads/master
GiftSay/GiftSay/classes/category/categoryDetail/model/NCDModel.swift
mit
1
// // NCDModel.swift // GiftSay // // Created by qianfeng on 16/9/5. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit import SwiftyJSON class NCDModel: NSObject { var code: NSNumber? var data: NCDDataModel? var message: String? class func parseModel(data: NSData) -> NCDModel { let jsonData = JSON(data: data) let model = NCDModel() model.code = jsonData["code"].number model.message = jsonData["message"].string model.data = NCDDataModel.parseModel(jsonData["data"]) return model } } class NCDDataModel: NSObject { var items: Array<NCDItemsModel>? var paging: NCDPagingModel? class func parseModel(jsonData: JSON) -> NCDDataModel { let model = NCDDataModel() var array = Array<NCDItemsModel>() for (_,subjson) in jsonData["items"] { let itemsModel = NCDItemsModel.parseModel(subjson) array.append(itemsModel) } model.items = array model.paging = NCDPagingModel.parseModel(jsonData["paging"]) return model } } class NCDItemsModel: NSObject { var ad_monitors: NSArray?// var author: NCDAuthorModel? var column: NCDColumnModel? var content_type: NSNumber? var content_url: String? var cover_image_url: String? var cover_webp_url: String? var created_at: NSNumber? var editor_id: NSNumber? var feature_list: NSArray?// var hidden_cover_image: Bool? var id: NSNumber? var labels: NSArray?// var liked: Bool? var likes_count: NSNumber? var published_at: NSNumber? var share_msg: String? var short_title: String? var status: NSNumber? var template: String? var title: String? var type: String? var updated_at: NSNumber? var url: String? class func parseModel(jsonData: JSON) -> NCDItemsModel { let model = NCDItemsModel() model.content_type = jsonData["content_type"].number model.content_url = jsonData["content_url"].string model.cover_image_url = jsonData["cover_image_url"].string model.cover_webp_url = jsonData["cover_webp_url"].string model.created_at = jsonData["created_at"].number model.editor_id = jsonData["editor_id"].number model.hidden_cover_image = jsonData["hidden_cover_image"].bool model.id = jsonData["id"].number model.liked = jsonData["liked"].bool model.likes_count = jsonData["likes_count"].number model.published_at = jsonData["published_at"].number model.share_msg = jsonData["share_msg"].string model.short_title = jsonData["short_title"].string model.status = jsonData["status"].number model.template = jsonData["template"].string model.title = jsonData["title"].string model.type = jsonData["type"].string model.updated_at = jsonData["updated_at"].number model.url = jsonData["url"].string model.author = NCDAuthorModel.parseModel(jsonData["author"]) model.column = NCDColumnModel.parseModel(jsonData["column"]) return model } } class NCDAuthorModel: NSObject { var avatar_url: String? var avatar_webp_url: NSNull? var created_at: NSNumber? var id: NSNumber? var nickname: String? class func parseModel(jsonData: JSON) -> NCDAuthorModel { let model = NCDAuthorModel() model.avatar_url = jsonData["avatar_url"].string model.avatar_webp_url = jsonData["avatar_webp_url"].null model.created_at = jsonData["created_at"].number model.id = jsonData["id"].number model.nickname = jsonData["nickname"].string return model } } class NCDColumnModel: NSObject { var banner_image_url: String? var category: String? var cover_image_url: String? var created_at: NSNumber? var desc: String? //description var id: NSNumber? var order: NSNumber? var post_published_at: NSNumber? var status: NSNumber? var subtitle: String? var title: String? var updated_at: NSNumber? class func parseModel(jsonData: JSON) -> NCDColumnModel { let model = NCDColumnModel() model.banner_image_url = jsonData["banner_image_url"].string model.category = jsonData["category"].string model.cover_image_url = jsonData["cover_image_url"].string model.created_at = jsonData["created_at"].number model.desc = jsonData["description"].string model.id = jsonData["id"].number model.order = jsonData["order"].number model.post_published_at = jsonData["post_published_at"].number model.status = jsonData["status"].number model.subtitle = jsonData["subtitle"].string model.title = jsonData["title"].string model.updated_at = jsonData["updated_at"].number return model } } class NCDPagingModel: NSObject { var next_url: String? class func parseModel(jsonData: JSON) -> NCDPagingModel { let model = NCDPagingModel() model.next_url = jsonData["next_url"].string return model } }
050eb786f3a5085eb790d52f5c9a3b71
24.040179
70
0.589945
false
false
false
false
colemancda/XcodeServerSDK
refs/heads/swift-2
XcodeServerSDK/API Routes/XcodeServer+Integration.swift
mit
1
// // XcodeServer+Integration.swift // XcodeServerSDK // // Created by Mateusz Zając on 01.07.2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation // MARK: - XcodeSever API Routes for Integrations management extension XcodeServer { // MARK: Bot releated integrations /** XCS API call for getting a list of filtered integrations for bot. Available queries: - **last** - find last integration for bot - **from** - find integration based on date range - **number** - find integration for bot by its number - parameter botId: ID of bot. - parameter query: Query which should be used to filter integrations. - parameter integrations: Optional array of integrations returned from XCS. - parameter error: Optional error. */ public final func getBotIntegrations(botId: String, query: [String: String], completion: (integrations: [Integration]?, error: NSError?) -> ()) { let params = [ "bot": botId ] self.sendRequestWithMethod(.GET, endpoint: .Integrations, params: params, query: query, body: nil) { (response, body, error) -> () in if error != nil { completion(integrations: nil, error: error) return } if let body = (body as? NSDictionary)?["results"] as? NSArray { let integrations: [Integration] = XcodeServerArray(body) completion(integrations: integrations, error: nil) } else { completion(integrations: nil, error: Error.withInfo("Wrong body \(body)")) } } } /** XCS API call for firing integration for specified bot. - parameter botId: ID of the bot. - parameter integration: Optional object of integration returned if run was successful. - parameter error: Optional error. */ public final func postIntegration(botId: String, completion: (integration: Integration?, error: NSError?) -> ()) { let params = [ "bot": botId ] self.sendRequestWithMethod(.POST, endpoint: .Integrations, params: params, query: nil, body: nil) { (response, body, error) -> () in if error != nil { completion(integration: nil, error: error) return } if let body = body as? NSDictionary { let integration = Integration(json: body) completion(integration: integration, error: nil) } else { completion(integration: nil, error: Error.withInfo("Wrong body \(body)")) } } } // MARK: General integrations methods /** XCS API call for retrievieng all available integrations on server. - parameter integrations: Optional array of integrations. - parameter error: Optional error. */ public final func getIntegrations(completion: (integrations: [Integration]?, error: NSError?) -> ()) { self.sendRequestWithMethod(.GET, endpoint: .Integrations, params: nil, query: nil, body: nil) { (response, body, error) -> () in guard error == nil else { completion(integrations: nil, error: error) return } guard let integrationsBody = (body as? NSDictionary)?["results"] as? NSArray else { completion(integrations: nil, error: Error.withInfo("Wrong body \(body)")) return } let integrations: [Integration] = XcodeServerArray(integrationsBody) completion(integrations: integrations, error: nil) } } /** XCS API call for retrievieng specified Integration. - parameter integrationId: ID of integration which is about to be retrieved. - parameter completion: - Optional retrieved integration. - Optional operation error. */ public final func getIntegration(integrationId: String, completion: (integration: Integration?, error: NSError?) -> ()) { let params = [ "integration": integrationId ] self.sendRequestWithMethod(.GET, endpoint: .Integrations, params: params, query: nil, body: nil) { (response, body, error) -> () in guard error == nil else { completion(integration: nil, error: error) return } guard let integrationBody = body as? NSDictionary else { completion(integration: nil, error: Error.withInfo("Wrong body \(body)")) return } let integration = Integration(json: integrationBody) completion(integration: integration, error: nil) } } /** XCS API call for canceling specified integration. - parameter integrationId: ID of integration. - parameter success: Integration cancelling success indicator. - parameter error: Optional operation error. */ public final func cancelIntegration(integrationId: String, completion: (success: Bool, error: NSError?) -> ()) { let params = [ "integration": integrationId ] self.sendRequestWithMethod(.POST, endpoint: .CancelIntegration, params: params, query: nil, body: nil) { (response, body, error) -> () in if error != nil { completion(success: false, error: error) return } completion(success: true, error: nil) } } // TODO: Methods about to be implemented... // public func reportQueueSizeAndEstimatedWaitingTime(integration: Integration, completion: ((queueSize: Int, estWait: Double), NSError?) -> ()) { //TODO: we need to call getIntegrations() -> filter pending and running Integrations -> get unique bots of these integrations -> query for the average integration time of each bot -> estimate, based on the pending/running integrations, how long it will take for the passed in integration to finish }
ae1c646876f464b4bdad1fd1b89045a5
36.727811
301
0.57851
false
false
false
false
pjk1129/SONetwork
refs/heads/master
Demo/SwiftOne/Classes/UI/Home/SOGoodsViewCell.swift
mit
1
// // SOGoodsViewCell.swift // SwiftOne // // Created by JK.PENG on 2017/3/23. // Copyright © 2017年 XXXXX. All rights reserved. // import UIKit import Kingfisher class SOGoodsViewCell: UICollectionViewCell { // MARK:- 构造函数 override init(frame: CGRect) { super.init(frame: frame) self.contentView.backgroundColor = UIColor.white self.contentView.addSubview(imageView) self.contentView.addSubview(bottomLine) self.contentView.addSubview(rightLine) self.contentView.addSubview(mTitleLab) self.contentView.addSubview(mFanLab) self.contentView.addSubview(mPriceLab) self.contentView.addSubview(mRebateLab) bottomLine.frame = CGRect(x: 0, y: self.contentView.bounds.size.height-lineSize, width: self.contentView.bounds.size.width, height: lineSize) rightLine.frame = CGRect(x: self.contentView.bounds.size.width-lineSize, y: 0, width: lineSize, height: self.contentView.bounds.size.height) mTitleLab.frame = CGRect(x: imageView.frame.minX, y: imageView.frame.maxY+11, width: imageView.frame.width, height: 30) mFanLab.frame = CGRect(x: imageView.frame.minX, y: bottomLine.frame.minY-20, width: 12, height: 12) mRebateLab.frame = CGRect(x: mFanLab.frame.maxX+4, y: mFanLab.frame.minY, width: 100, height: 12) mPriceLab.frame = CGRect(x: imageView.frame.minX-3, y: mFanLab.frame.minY-20, width: imageView.frame.width, height: 14) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func updateData(item:SOGoodsItem){ guard item != goodsItem else { return } goodsItem = item mTitleLab.text = goodsItem?.name mPriceLab.text = "¥" + (goodsItem?.price)! mRebateLab.text = (goodsItem?.rebateMoney)! + "元" if ((goodsItem?.img) != nil) { let url = URL(string: (goodsItem?.img)!) imageView.kf.setImage(with: url) } } var goodsItem: SOGoodsItem? private let lineSize = 1/UIScreen.main.scale //MARK:- 懒加载属性 lazy var imageView:UIImageView = { let width = kScreenW/2 - 10 let imgView = UIImageView(frame: CGRect(x: 5, y: 5, width: width, height: width)) imgView.backgroundColor = UIColor.clear imgView.translatesAutoresizingMaskIntoConstraints = false return imgView }() lazy var mRebateLab:UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.left label.textColor = UIColor.so_withHex(hexString: "ff4800") label.font = UIFont.systemFont(ofSize: 14) label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var mFanLab:UILabel = { let label = UILabel() label.text = "返" label.backgroundColor = UIColor.so_withHex(hexString: "ff4a00") label.textAlignment = NSTextAlignment.center label.textColor = UIColor.white label.adjustsFontSizeToFitWidth = true label.font = UIFont.boldSystemFont(ofSize: 9) label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var mPriceLab:UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.left label.textColor = UIColor.so_withHex(hexString: "666666") label.adjustsFontSizeToFitWidth = true label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var mTitleLab:UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.font = UIFont.systemFont(ofSize: 12) label.textAlignment = NSTextAlignment.left label.textColor = UIColor.so_withHex(hexString: "333333") label.numberOfLines = 2 label.lineBreakMode = NSLineBreakMode.byTruncatingTail label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var bottomLine:UIView = { let line = UIView(frame: CGRect.zero) line.backgroundColor = UIColor.so_withHex(hexString: "eeeeee") return line }() lazy var rightLine:UIView = { let line = UIView(frame: CGRect.zero) line.backgroundColor = UIColor.so_withHex(hexString: "eeeeee") return line }() }
d6d66459102f05b1a5fccfed12eb34b8
36.396694
149
0.649724
false
false
false
false
zenangst/Faker
refs/heads/master
Pod/Tests/Specs/Generators/NameSpec.swift
mit
1
import Quick import Nimble class NameSpec: QuickSpec { override func spec() { describe("Name") { var name: Name! beforeEach { let parser = Parser(locale: "en-TEST") name = Name(parser: parser) } describe("#name") { it("returns the correct text") { let text = name.name() expect(text).to(equal("Mr. Vadym Markov")) } } describe("#firstName") { it("returns the correct text") { let firstName = name.firstName() expect(firstName).to(equal("Vadym")) } } describe("#lastName") { it("returns the correct text") { let lastName = name.lastName() expect(lastName).to(equal("Markov")) } } describe("#prefix") { it("returns the correct text") { let prefix = name.prefix() expect(prefix).to(equal("Mr.")) } } describe("#suffix") { it("returns the correct text") { let suffix = name.suffix() expect(suffix).to(equal("I")) } } describe("#title") { it("returns the correct text") { let title = name.title() expect(title).to(equal("Lead Mobility Engineer")) } } } } }
951f10951b8eb312dc8e73a75bcf5c8c
21.327586
59
0.498842
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/Room/VoiceMessages/VoiceMessageMediaServiceProvider.swift
apache-2.0
1
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import MediaPlayer @objc public class VoiceMessageMediaServiceProvider: NSObject, VoiceMessageAudioPlayerDelegate, VoiceMessageAudioRecorderDelegate { private enum Constants { static let roomAvatarImageSize: CGSize = CGSize(width: 600, height: 600) static let roomAvatarFontSize: CGFloat = 40.0 static let roomAvatarMimetype: String = "image/jpeg" } private var roomAvatarLoader: MXMediaLoader? private let audioPlayers: NSMapTable<NSString, VoiceMessageAudioPlayer> private let audioRecorders: NSHashTable<VoiceMessageAudioRecorder> private var displayLink: CADisplayLink! // Retain active audio players(playing or paused) so it doesn't stop playing on timeline cell reuse // and we can pause/resume players on switching rooms. private var activeAudioPlayers: Set<VoiceMessageAudioPlayer> // Keep reference to currently playing player for remote control. private var currentlyPlayingAudioPlayer: VoiceMessageAudioPlayer? @objc public static let sharedProvider = VoiceMessageMediaServiceProvider() private var roomAvatar: UIImage? @objc public var currentRoomSummary: MXRoomSummary? { didSet { // set avatar placeholder for now roomAvatar = AvatarGenerator.generateAvatar(forMatrixItem: currentRoomSummary?.roomId, withDisplayName: currentRoomSummary?.displayname, size: Constants.roomAvatarImageSize.width, andFontSize: Constants.roomAvatarFontSize) guard let avatarUrl = currentRoomSummary?.avatar else { return } if let cachePath = MXMediaManager.thumbnailCachePath(forMatrixContentURI: avatarUrl, andType: Constants.roomAvatarMimetype, inFolder: currentRoomSummary?.roomId, toFitViewSize: Constants.roomAvatarImageSize, with: MXThumbnailingMethodCrop), FileManager.default.fileExists(atPath: cachePath) { // found in the cache, load it roomAvatar = MXMediaManager.loadThroughCache(withFilePath: cachePath) } else { // cancel previous loader first roomAvatarLoader?.cancel() roomAvatarLoader = nil guard let mediaManager = currentRoomSummary?.mxSession.mediaManager else { return } // not found in the cache, download it roomAvatarLoader = mediaManager.downloadThumbnail(fromMatrixContentURI: avatarUrl, withType: Constants.roomAvatarMimetype, inFolder: currentRoomSummary?.roomId, toFitViewSize: Constants.roomAvatarImageSize, with: MXThumbnailingMethodCrop, success: { filePath in if let filePath = filePath { self.roomAvatar = MXMediaManager.loadThroughCache(withFilePath: filePath) } self.roomAvatarLoader = nil }, failure: { error in self.roomAvatarLoader = nil }) } } } private override init() { audioPlayers = NSMapTable<NSString, VoiceMessageAudioPlayer>(valueOptions: .weakMemory) audioRecorders = NSHashTable<VoiceMessageAudioRecorder>(options: .weakMemory) activeAudioPlayers = Set<VoiceMessageAudioPlayer>() super.init() displayLink = CADisplayLink(target: WeakTarget(self, selector: #selector(handleDisplayLinkTick)), selector: WeakTarget.triggerSelector) displayLink.isPaused = true displayLink.add(to: .current, forMode: .common) } @objc func audioPlayerForIdentifier(_ identifier: String) -> VoiceMessageAudioPlayer { if let audioPlayer = audioPlayers.object(forKey: identifier as NSString) { return audioPlayer } let audioPlayer = VoiceMessageAudioPlayer() audioPlayer.registerDelegate(self) audioPlayers.setObject(audioPlayer, forKey: identifier as NSString) return audioPlayer } @objc func audioRecorder() -> VoiceMessageAudioRecorder { let audioRecorder = VoiceMessageAudioRecorder() audioRecorder.registerDelegate(self) audioRecorders.add(audioRecorder) return audioRecorder } @objc func pauseAllServices() { pauseAllServicesExcept(nil) } // MARK: - VoiceMessageAudioPlayerDelegate func audioPlayerDidStartPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { currentlyPlayingAudioPlayer = audioPlayer activeAudioPlayers.insert(audioPlayer) setUpRemoteCommandCenter() pauseAllServicesExcept(audioPlayer) } func audioPlayerDidStopPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { if currentlyPlayingAudioPlayer == audioPlayer { currentlyPlayingAudioPlayer = nil tearDownRemoteCommandCenter() } activeAudioPlayers.remove(audioPlayer) } func audioPlayerDidFinishPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { if currentlyPlayingAudioPlayer == audioPlayer { currentlyPlayingAudioPlayer = nil tearDownRemoteCommandCenter() } activeAudioPlayers.remove(audioPlayer) } // MARK: - VoiceMessageAudioRecorderDelegate func audioRecorderDidStartRecording(_ audioRecorder: VoiceMessageAudioRecorder) { pauseAllServicesExcept(audioRecorder) } // MARK: - Private private func pauseAllServicesExcept(_ service: AnyObject?) { for audioRecorder in audioRecorders.allObjects { if audioRecorder === service { continue } audioRecorder.stopRecording() } guard let audioPlayersEnumerator = audioPlayers.objectEnumerator() else { return } for case let audioPlayer as VoiceMessageAudioPlayer in audioPlayersEnumerator { if audioPlayer === service { continue } audioPlayer.pause() } } @objc private func handleDisplayLinkTick() { updateNowPlayingInfoCenter() } private func setUpRemoteCommandCenter() { displayLink.isPaused = false UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() commandCenter.playCommand.isEnabled = true commandCenter.playCommand.removeTarget(nil) commandCenter.playCommand.addTarget { [weak self] event in guard let audioPlayer = self?.currentlyPlayingAudioPlayer else { return MPRemoteCommandHandlerStatus.commandFailed } audioPlayer.play() return MPRemoteCommandHandlerStatus.success } commandCenter.pauseCommand.isEnabled = true commandCenter.pauseCommand.removeTarget(nil) commandCenter.pauseCommand.addTarget { [weak self] event in guard let audioPlayer = self?.currentlyPlayingAudioPlayer else { return MPRemoteCommandHandlerStatus.commandFailed } audioPlayer.pause() return MPRemoteCommandHandlerStatus.success } commandCenter.skipForwardCommand.isEnabled = true commandCenter.skipForwardCommand.removeTarget(nil) commandCenter.skipForwardCommand.addTarget { [weak self] event in guard let audioPlayer = self?.currentlyPlayingAudioPlayer, let skipEvent = event as? MPSkipIntervalCommandEvent else { return MPRemoteCommandHandlerStatus.commandFailed } audioPlayer.seekToTime(audioPlayer.currentTime + skipEvent.interval) return MPRemoteCommandHandlerStatus.success } commandCenter.skipBackwardCommand.isEnabled = true commandCenter.skipBackwardCommand.removeTarget(nil) commandCenter.skipBackwardCommand.addTarget { [weak self] event in guard let audioPlayer = self?.currentlyPlayingAudioPlayer, let skipEvent = event as? MPSkipIntervalCommandEvent else { return MPRemoteCommandHandlerStatus.commandFailed } audioPlayer.seekToTime(audioPlayer.currentTime - skipEvent.interval) return MPRemoteCommandHandlerStatus.success } } private func tearDownRemoteCommandCenter() { displayLink.isPaused = true UIApplication.shared.endReceivingRemoteControlEvents() let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default() nowPlayingInfoCenter.nowPlayingInfo = nil } private func updateNowPlayingInfoCenter() { guard let audioPlayer = currentlyPlayingAudioPlayer else { return } let artwork = MPMediaItemArtwork(boundsSize: Constants.roomAvatarImageSize) { [weak self] size in return self?.roomAvatar ?? UIImage() } let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default() nowPlayingInfoCenter.nowPlayingInfo = [MPMediaItemPropertyTitle: audioPlayer.displayName ?? VectorL10n.voiceMessageLockScreenPlaceholder, MPMediaItemPropertyArtist: currentRoomSummary?.displayname as Any, MPMediaItemPropertyArtwork: artwork, MPMediaItemPropertyPlaybackDuration: audioPlayer.duration as Any, MPNowPlayingInfoPropertyElapsedPlaybackTime: audioPlayer.currentTime as Any] } }
3f6db3fb6c70db644ff01539fb835565
42.522556
145
0.5948
false
false
false
false
tiagomartinho/webhose-cocoa
refs/heads/master
webhose-cocoa/WebhoseTests/WebhosePostSpec.swift
mit
1
@testable import Webhose import Quick import Nimble class WebhosePostSpec: QuickSpec { let aKey = "aKey" let aQuery = "aQuery" override func spec() { describe("the Webhose Client") { let client = WebhoseClient(key: self.aKey) context("when the response is incorrect") { beforeEach { WebhoseStub.stubIncorrectResponse() } it("has empty post list") { var posts: [WebhosePost]? client.search(self.aQuery) { response in posts = response.posts } expect(posts?.count).toEventually(equal(0)) } } context("when the response is correct") { beforeEach { WebhoseStub.stubCorrectResponse() } it("has not empty post list") { var posts: [WebhosePost]? client.search(self.aQuery) { response in posts = response.posts } expect(posts?.count).toEventually(equal(2)) } it("has an uuid") { var post: WebhosePost? client.search(self.aQuery) { response in post = response.posts.first } let expectedUUID = "7ac79ae99e3e9aa8acce5ce36ae34ed3443fc3d0" expect(post?.uuid).toEventually(equal(expectedUUID)) } it("has an url") { var post: WebhosePost? client.search(self.aQuery) { response in post = response.posts.first } let expectedURL = URL(string: "http://omgili.com/r/")! expect(post?.url).toEventually(equal(expectedURL)) } it("has a publication date") { var post: WebhosePost? client.search(self.aQuery) { response in post = response.posts.first } let expectedDate = WebhosePostSpec.buildExpectedDate() expect(post?.published).toEventually(equal(expectedDate)) } } } } static func buildExpectedDate() -> Date { let calendar = NSCalendar(identifier: .gregorian) var components = DateComponents() components.year = 2016 components.month = 3 components.day = 18 components.hour = 19 components.minute = 31 components.second = 0 components.timeZone = TimeZone(secondsFromGMT: 0) return calendar!.date(from: components)! } }
8122b505fe88297ec2334d745dcee3bd
35.269231
81
0.481796
false
false
false
false
JaSpa/swift
refs/heads/master
test/Interpreter/SDK/Reflection_KVO.swift
apache-2.0
26
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // rdar://problem/19060227 import Foundation class ObservedValue: NSObject { dynamic var amount = 0 } class ValueObserver: NSObject { private var observeContext = 0 let observedValue: ObservedValue init(value: ObservedValue) { observedValue = value super.init() observedValue.addObserver(self, forKeyPath: "amount", options: .new, context: &observeContext) } deinit { observedValue.removeObserver(self, forKeyPath: "amount") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &observeContext { if let change_ = change { if let amount = change_[.newKey] as? Int { print("Observed value updated to \(amount)") } } } } } let value = ObservedValue() value.amount = 42 let observer = ValueObserver(value: value) // CHECK: updated to 43 value.amount += 1 // CHECK: amount: 43 dump(value)
d53bc25564b4d042fbc76b62433ff97b
21.744681
148
0.695978
false
false
false
false
larryhou/swift
refs/heads/master
ForceTouch/ForceTouch/ViewController.swift
mit
1
// // ViewController.swift // ForceTouch // // Created by larryhou on 24/10/2017. // Copyright © 2017 larryhou. All rights reserved. // import UIKit class TouchAnchor: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else {return} context.saveGState() let thickness: CGFloat = 2 color.setStroke() context.setLineWidth(thickness) let halo = CGMutablePath() halo.addEllipse(in: bounds.insetBy(dx: thickness / 2, dy: thickness / 2)) context.addPath(halo) context.strokePath() color.setFill() let circle = CGMutablePath() circle.addEllipse(in: bounds.insetBy(dx: bounds.width / 4, dy: bounds.height / 4)) context.addPath(circle) context.fillPath() context.restoreGState() } var color: UIColor = .green { didSet { setNeedsDisplay() } } } class ViewController: UIViewController { var pool: [TouchAnchor] = [] var anchors: [UITouch: TouchAnchor] = [:] override func viewDidLoad() { super.viewDidLoad() view.isMultipleTouchEnabled = true switch traitCollection.forceTouchCapability { case .available:print("forceTouch available") case .unavailable:print("forceTouch unavailable") case .unknown:print("forceTouch unknown") } if traitCollection.forceTouchCapability == .available { } else { } } var feedback: UISelectionFeedbackGenerator! override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if feedback == nil { feedback = UISelectionFeedbackGenerator() } feedback.prepare() for touch in touches { let anchor: TouchAnchor if pool.count > 0 { anchor = pool.remove(at: 0) } else { anchor = TouchAnchor() } anchor.isUserInteractionEnabled = false anchor.layer.removeAllAnimations() anchor.transform = CGAffineTransform.identity anchor.alpha = 1.0 let diameter = touch.majorRadius * 2 * 2 let center = touch.location(in: view) var frame = anchor.frame frame.origin = CGPoint(x: center.x - diameter / 2, y: center.y - diameter / 2) frame.size = CGSize(width: diameter, height: diameter) anchor.frame = frame anchor.setNeedsDisplay() view.addSubview(anchor) anchors[touch] = anchor } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let center = touch.location(in: view) if let anchor = self.anchors[touch] { var frame = anchor.frame frame.origin = CGPoint(x: center.x - frame.width / 2, y: center.y - frame.height / 2) anchor.frame = frame let r: CGFloat, g: CGFloat let percent = touch.force / touch.maximumPossibleForce if percent > 0.5 { let ratio = (percent - 0.5) / 0.5 r = 1 g = 1 - ratio } else { let ratio = percent / 0.5 r = ratio g = 1 } anchor.color = UIColor(red: r, green: g, blue: 0, alpha: 1) } } // feedback.selectionChanged() // feedback.prepare() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { UIView.animate(withDuration: 0.2, animations: { [unowned self] in for touch in touches { if let anchor = self.anchors[touch] { anchor.alpha = 0 anchor.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } } }) { [unowned self] (_) in for touch in touches { if let anchor = self.anchors[touch] { self.pool.append(anchor) self.anchors.removeValue(forKey: touch) } } } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchesEnded(touches, with: event) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
4b4e5fe749c372c8e93e44346eaff9f3
28.670807
101
0.545949
false
false
false
false
mbogh/xcode-live-rendering
refs/heads/master
Xcode Live Rendering/LiveView.swift
mit
1
// // LiveView.swift // Xcode Live Rendering // // Created by Morten Bøgh on 21/07/14. // Copyright (c) 2014 Morten Bøgh. All rights reserved. // import UIKit @IBDesignable class LiveView: UIView { private var titleLabel = UILabel() private var avatarImageView = UIImageView() @IBInspectable internal var title: String = "" { didSet { self.titleLabel.text = title } } @IBInspectable internal var avatarImage: UIImage = UIImage() { didSet { let size = self.avatarImage.size let rect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) var path = UIBezierPath(ovalInRect: rect) path.addClip() self.avatarImage.drawInRect(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.avatarImageView.image = image } } required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } private func commonInit() { self.addSubview(self.avatarImageView) self.avatarImageView.contentMode = .ScaleAspectFit self.avatarImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.avatarImageView.clipsToBounds = true self.addConstraint(NSLayoutConstraint(item: self.avatarImageView, attribute: .Top, relatedBy: .GreaterThanOrEqual, toItem: self, attribute: .Top, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: self.avatarImageView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: self.avatarImageView, attribute: .Trailing, multiplier: 1.0, constant: 10.0)) self.addSubview(self.titleLabel) self.titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) self.titleLabel.setContentCompressionResistancePriority(self.avatarImageView.contentCompressionResistancePriorityForAxis(.Vertical) + 1, forAxis: .Vertical) self.titleLabel.textAlignment = .Center self.addConstraint(NSLayoutConstraint(item: self.titleLabel, attribute: .Top, relatedBy: .Equal, toItem: self.avatarImageView, attribute: .Bottom, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: self.titleLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: self.titleLabel, attribute: .Trailing, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .GreaterThanOrEqual, toItem: self.titleLabel, attribute: .Bottom, multiplier: 1.0, constant: 10.0)) } }
5bc93384493e8f9538c4131e2c6ae219
47.276923
188
0.691523
false
false
false
false
VinlorJiang/DouYuWL
refs/heads/master
DouYuWL/DouYuWL/Classes/Home/View/RecommendCycleView.swift
mit
1
// // RecommendCycleView.swift // DouYuWL // // Created by dinpay on 2017/7/25. // Copyright © 2017年 apple. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { var cycleTimer : Timer? // MARK:- 懒加载装着CycleModel模型的数组 var cycleModels : [CycleModel]? { didSet { // 1. 刷新collectionView collectionView.reloadData() // 2. 设置pageControl的个数 pageControl.numberOfPages = cycleModels?.count ?? 0 // 3. 默认滚动到中间某个位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 4. 添加定时器 removeCycleTimer() addCycleTimer() } } // MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! // MARK: 系统回调函数 override func awakeFromNib() { super.awakeFromNib() // 设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // collectionView.dataSource = self // collectionView.delegate = self // 注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() // 设置collectionView的layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size // layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = 0 // layout.scrollDirection = .horizontal // collectionView.isPagingEnabled = true // collectionView.showsHorizontalScrollIndicator = false } } extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (self.cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count] // cell.cyleModel = cycleModel // cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.orange return cell } } // MARK:- 遵守UICollectionView的代理协议 extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1. 获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 // 2. 计算pageController的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } // MARK:- 对定时器的操作方法 extension RecommendCycleView { fileprivate func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollTotNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } fileprivate func removeCycleTimer() { cycleTimer?.invalidate() cycleTimer = nil } @objc private func scrollTotNext() { let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width // 滚动到该位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
37c34a090a5b4ade038a83f1f25937f7
32.857143
130
0.658228
false
false
false
false
UncleJoke/Spiral
refs/heads/master
Spiral/Shape.swift
mit
2
// // Shape.swift // Spiral // // Created by 杨萧玉 on 14-7-12. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import UIKit import SpriteKit enum PathOrientation:Int { case right = 0 case down case left case up } func randomPath() -> PathOrientation{ let pathNum = Int(arc4random_uniform(4)) return PathOrientation(rawValue: pathNum)! } class Shape: SKSpriteNode { var radius:CGFloat = 10 var moveSpeed:CGFloat = 60 var pathOrientation:PathOrientation = randomPath() var lineNum = 0 let speedUpBase:CGFloat = 50 var light = SKLightNode() required init(coder: NSCoder) { fatalError("NSCoding not supported") } init(name aName:String,imageName:String) { super.init(texture: SKTexture(imageNamed: imageName),color:SKColor.clearColor(), size: CGSizeMake(radius*2, radius*2)) // physicsBody = SKPhysicsBody(texture: texture, size: size) physicsBody = SKPhysicsBody(circleOfRadius: radius) physicsBody!.usesPreciseCollisionDetection = true physicsBody!.collisionBitMask = mainSceneCategory physicsBody!.contactTestBitMask = playerCategory|killerCategory|scoreCategory|shieldCategory|reaperCategory moveSpeed += Data.sharedData.speedScale * speedUpBase name = aName zPosition = 100 physicsBody?.angularDamping = 0 physicsBody?.linearDamping = 0 physicsBody?.restitution = 1 // physicsBody?.restitution = 1 physicsBody?.friction = 1 normalTexture = texture?.textureByGeneratingNormalMap() light.enabled = false addChild(light) } func runInOrdinaryMap(map:OrdinaryMap) { let distance = calDistanceInOrdinaryMap(map) let duration = distance / moveSpeed let rotate = SKAction.rotateByAngle(distance/10, duration: Double(duration)) let move = SKAction.moveTo(map.points[lineNum+1], duration: Double(duration)) let group = SKAction.group([rotate,move]) self.runAction(group, completion:{ self.lineNum++ if self.lineNum==map.points.count-1 { if self is Player{ Data.sharedData.gameOver = true } else{ self.removeFromParent() } } else { self.runInOrdinaryMap(map) } }) } func calDistanceInOrdinaryMap(map:OrdinaryMap)->CGFloat{ if self.lineNum==map.points.count { return 0 } switch lineNum%4{ case 0: return position.y-map.points[lineNum+1].y case 1: return position.x-map.points[lineNum+1].x case 2: return map.points[lineNum+1].y-position.y case 3: return map.points[lineNum+1].x-position.x default: return 0 } } func runInZenMap(map:ZenMap){ let distance = calDistanceInZenMap(map) let duration = distance/moveSpeed let rotate = SKAction.rotateByAngle(distance/10, duration: Double(duration)) let move = SKAction.moveTo(map.points[pathOrientation]![lineNum+1], duration: Double(duration)) let group = SKAction.group([rotate,move]) self.runAction(group, completion: { self.lineNum++ if self.lineNum==map.points[self.pathOrientation]!.count-1 { if self is Player{ Data.sharedData.gameOver = true } else{ self.removeFromParent() } } else { self.runInZenMap(map) } }) } func calDistanceInZenMap(map:ZenMap)->CGFloat{ if self.lineNum==map.points[pathOrientation]!.count { return 0 } let turnNum:Int switch pathOrientation { case .right: turnNum = lineNum case .down: turnNum = lineNum + 1 case .left: turnNum = lineNum + 2 case .up: turnNum = lineNum + 3 } switch turnNum%4{ case 0: return map.points[pathOrientation]![lineNum+1].x-position.x case 1: return position.y-map.points[pathOrientation]![lineNum+1].y case 2: return position.x-map.points[pathOrientation]![lineNum+1].x case 3: return map.points[pathOrientation]![lineNum+1].y-position.y default: return 0 } } }
6b1376f5074c4b379e564c62df25b209
30.272109
126
0.581249
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Activity/FormattableContent/Ranges/ActivityRange.swift
gpl-2.0
2
import Foundation extension FormattableRangeKind { static let `default` = FormattableRangeKind("default") static let theme = FormattableRangeKind("theme") static let plugin = FormattableRangeKind("plugin") } class ActivityRange: FormattableContentRange, LinkContentRange { var range: NSRange var kind: FormattableRangeKind { return internalKind ?? .default } var url: URL? { return internalUrl } private var internalUrl: URL? private var internalKind: FormattableRangeKind? init(kind: FormattableRangeKind? = nil, range: NSRange, url: URL?) { self.range = range self.internalUrl = url self.internalKind = kind } }
3f43e97b13e986246183bf5ef77d32ad
23.448276
72
0.684062
false
false
false
false
thePsguy/Nyan-Tunes
refs/heads/master
Nyan Tunes/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Nyan Tunes // // Created by Pushkar Sharma on 25/09/2016. // Copyright © 2016 thePsguy. All rights reserved. // import UIKit import CoreData import VK_ios_sdk import MediaPlayer import Crashlytics import Fabric @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. initRemoteEvents() Fabric.with([Crashlytics.self, Answers.self]) return true } func initRemoteEvents(){ UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() commandCenter.pauseCommand.isEnabled = true commandCenter.pauseCommand.addTarget(handler: AudioManager.sharedInstance.togglePlay) commandCenter.playCommand.isEnabled = true commandCenter.playCommand.addTarget(handler: AudioManager.sharedInstance.togglePlay) commandCenter.nextTrackCommand.isEnabled = true commandCenter.nextTrackCommand.addTarget(handler: AudioManager.sharedInstance.nextTrack) commandCenter.previousTrackCommand.isEnabled = true commandCenter.previousTrackCommand.addTarget(handler: AudioManager.sharedInstance.previousTrack) } 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. } // func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // VKSdk.processOpen(url, fromApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!) // return true // } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { VKSdk.processOpen(url, fromApplication: sourceApplication) return true } }
542d8d382913767147bac493ff09593e
46.225
285
0.736633
false
false
false
false
totocaster/JSONFeed
refs/heads/master
Classes/JSONFeedItem.swift
mit
1
// // JSONFeedItem.swift // JSONFeed // // Created by Toto Tvalavadze on 2017/05/18. // Copyright © 2017 Toto Tvalavadze. All rights reserved. // import Foundation public struct JSONFeedItem { /// Unique for that item for that feed over time. If an item is ever updated, the id should be unchanged. public let id: String /// URL of the resource described by the item. It’s the permalink. This may be the same as the `id`. public let url: URL? /// URL of a page elsewhere. This is especially useful for linkblogs. If `url` links to where you’re talking about a thing, then `externalUrl` links to the thing you’re talking about. public let externalUrl: URL? /// Plain text title of item. Microblog items in particular may omit titles. public let title: String? /// This is the plain text of the item. A Twitter-like service might use it. public let contentText: String? /// A Twitter-like service might use `contentText`, while a blog might use `contentHtml`. Use whichever makes sense for your resource. public let contentHtml: String? /// lain text sentence or two describing the item. This might be presented in a timeline, for instance, where a detail view would display all of `contentHtml` or `contentText`. public let summary: String? /// URL of the main image for the item. public let image: URL? /// URL of an image to use as a banner. Some blogging systems (such as Medium) display a different banner image chosen to go with each post, but that image wouldn’t otherwise appear in the `contentHtml`. public let bannerImage: URL? /// Date item was published.`contentHtml` /// - warning: If formating was wrong from publisher's side, date of parsing is set. public let date: Date /// Specifies the modification date.Date /// - warning: If formating was wrong from publisher's side, date of parsing is set. public let dateModified: Date? /// Specifies the feed author. The author object has several members, see `JSONFeedAuthor`. public let author: JSONFeedAuthor? /// Tags tend to be just one word, but they may be anything. /// - note: they are not the equivalent of Twitter hashtags. Some blogging systems and other feed formats call these categories. public let tags: [String] = [] // Lists related resources. Podcasts, for instance, would include an attachment that’s an audio or video file. See `JSONFeedAttachment`. public let attachments: [JSONFeedAttachment] // MARK: - Parsing internal init?(json: JsonDictionary) { let keys = JSONFeedSpecV1Keys.Item.self guard let id = json[keys.id] as? String else { return nil } // items without id will be discarded, per spec self.id = id let contentText = json[keys.contentText] as? String let contentHtml = json[keys.contentHtml] as? String if contentHtml == nil && contentText == nil { return nil } else { self.contentHtml = contentHtml self.contentText = contentText } self.url = URL(for: keys.url, inJson: json) self.externalUrl = URL(for: keys.externalUrl, inJson: json) self.title = json[keys.title] as? String self.summary = json[keys.summary] as? String self.image = URL(for: keys.image, inJson: json) self.bannerImage = URL(for: keys.bannerImage, inJson: json) if let dateString = json[keys.datePublished] as? String, let date = ISO8601DateFormatter().date(from: dateString) { self.date = date } else { self.date = Date() // per spec } if let dateModifiedString = json[keys.dateModified] as? String, let dateModified = ISO8601DateFormatter().date(from: dateModifiedString) { self.dateModified = dateModified } else { self.dateModified = nil } if let authorJson = json[keys.author] as? JsonDictionary { self.author = JSONFeedAuthor(json: authorJson) } else { self.author = nil } if let attachmentsJson = json[keys.attachments] as? [JsonDictionary] { self.attachments = attachmentsJson.flatMap(JSONFeedAttachment.init) } else { self.attachments = [] } } }
e1f4a06deb8578de62f6e6d3aad127db
39.563636
207
0.644554
false
false
false
false
baquiax/ImageProcessor
refs/heads/master
ImageProcessor.playground/Sources/ImageProcessor.swift
mit
1
import Foundation import UIKit public enum Colors { case Red case Green case Blue } public class ImageProcessor { private var image : RGBAImage? private static var DefaultFilters : [String : Filter] = [ "increase 50% of brightness": Brightness(increaseFactor: 0.5), "increase contrast by 2": Contrast(factor: 2), "gamma 1.5": Gamma(gamma: 1.5), "middle threshold": Threshold (minimumLevel: 127), "duplicate intensity of red": IncreaseIntensity(increaseFactor: 1, color: Colors.Red), "invert": Invert() ] public init (image : RGBAImage) { self.image = image; } func applyFilter(filter: Filter){ self.image = filter.apply(self.image!) } public func applyFilter(filter filter: Filter) -> RGBAImage { applyFilter(filter) return self.image! } public func applyFilters(filters filters: Array<Filter>) -> RGBAImage { for index in 0...filters.count - 1 { self.applyFilter(filters[index]) } return self.image! } public func applyDefaultFilter(name n : String) -> RGBAImage { let filter : Filter? = ImageProcessor.DefaultFilters[ n.lowercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) ] if (filter != nil) { print("Applying default filter: \(n)") self.applyFilter(filter!); } return self.image! } }
45ddb1b37eb1302ca25fb33fb7864e63
29.387755
154
0.620296
false
false
false
false
lgw51/AFNetworking-WGKit
refs/heads/master
AFNetworking+WGKit/WGURLSession.swift
mit
1
// // WGURLSession.swift // Sample // // Created by 7owen on 2016/12/14. // Copyright © 2016年 7owen. All rights reserved. // import UIKit import AFNetworking public typealias WGURLSessionEditRequest = (URLRequest) -> URLRequest public typealias WGURLSessionCompletionHandler = (HTTPURLResponse?, Any?, Error?) -> Void public typealias WGURLSessionErrorPreHandler = (HTTPURLResponse?, Any?, Error?) -> Error? public typealias WGURLSessionResponsePreHandler = (HTTPURLResponse?, Any?, Error?) -> Any? public protocol WGURLSessionDomainResolution { func query(with domain: String) -> String? } final public class WGURLSession: NSObject { public static var defaultManager: AFHTTPSessionManager? public static var defaultErrorHandlerBlock: WGURLSessionErrorPreHandler? public static var defaultResponseHandlerBlock: WGURLSessionResponsePreHandler? public static func request(_ request: WGURLSessionRequest, sessionManager: AFHTTPSessionManager? = defaultManager, errorPreHandler: WGURLSessionErrorPreHandler? = defaultErrorHandlerBlock, responsePreHandler:WGURLSessionResponsePreHandler? = defaultResponseHandlerBlock, domainResolution: WGURLSessionDomainResolution? = nil, completionHandler:@escaping WGURLSessionCompletionHandler) { var urlRequest:URLRequest? switch request { case let request as URLRequest: if let domainResolution = domainResolution { var mRequest = request if let url = request.url, let host = url.host, let ip = domainResolution.query(with: host) { mRequest.addValue(host, forHTTPHeaderField: "Host") let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.host = ip mRequest.url = urlComponents?.url } urlRequest = mRequest } case var requestContext as WGURLRequestContext: if let domainResolution = domainResolution, let host = requestContext.serverInfo.host { requestContext.connectIPAddress = domainResolution.query(with:host) } urlRequest = requestContext.generateURLRequest() default:() } if let request = urlRequest { var manager:AFHTTPSessionManager if sessionManager != nil { manager = sessionManager! } else { manager = AFHTTPSessionManager() } let task = manager.dataTask(with: request, completionHandler: { (response, responseObj, error) in guard let httpResponse = response as? HTTPURLResponse else { completionHandler(nil,responseObj,error) return } if error == nil { var aResponseObj = responseObj if let responseHandlerBlock = responsePreHandler { aResponseObj = responseHandlerBlock(httpResponse, responseObj, error) } completionHandler(httpResponse, aResponseObj, error) } else { var aError = error if let errorHandlerBlock = errorPreHandler { aError = errorHandlerBlock(httpResponse, responseObj, error) } completionHandler(httpResponse,responseObj,aError) } }) task.resume() } else { completionHandler(nil,nil,nil) } } } public protocol WGURLSessionRequest { } extension URLRequest: WGURLSessionRequest { } extension WGURLRequestContext: WGURLSessionRequest { }
981c94ba96f0d9407e2fd4e96a6f0262
39.902174
390
0.631943
false
false
false
false
noear/SiteD
refs/heads/master
ios/sited/sited/src/SdJscript.swift
apache-2.0
1
// // SdJscript.swift // ddcat // // Created by 谢月甲 on 15/10/8. // Copyright © 2015年 noear. All rights reserved. // import Foundation import SWXMLHash class SdJscript: NSObject { var require:SdNode; var code:String; private var s:SdSource; init(source:SdSource, node:XMLIndexer) { self.s = source; self.code = node.element!.attributes["code"]!; self.require = Util.createNode(source).buildForNode(node["require"]); } func loadJs(js:JsEngine){ if (!require.isEmpty()) { // for(SdNode n1 in require.items){ // Util.dohttp(<#T##source: SdSource##SdSource#>, isUpdate: <#T##Bool#>, url: <#T##String#>, params: <#T##Dictionary<String, String>#>, config: <#T##SdNode#>, callback: <#T##((code: Int, text: String) -> ())##((code: Int, text: String) -> ())##(code: Int, text: String) -> ()#>) // } // for(SdNode n1 in _require.items){ // [Util doHttp:_s url:n1.url params:nil config:n1 callback:^(int code, NSString *text) { // if(code==0){ // [js loadJs:text]; // } // }]; // } } } }
e3a46df489d2646965eaac0b596bd56c
31
293
0.519342
false
true
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ZoomAndPanAChart/PanAndZoomChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // PanAndZoomChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class PanAndZoomChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(3), max: SCIGeneric(6)) let yAxis = SCINumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) let ds1 = SCIXyDataSeries(xType: .double, yType: .double) let ds2 = SCIXyDataSeries(xType: .double, yType: .double) let ds3 = SCIXyDataSeries(xType: .double, yType: .double) let data1 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.01, pointCount: 1000, freq: 10) let data2 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.024, pointCount: 1000, freq: 10) let data3 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.049, pointCount: 1000, freq: 10) ds1.appendRangeX(data1!.xValues, y: data1!.yValues, count: data1!.size) ds2.appendRangeX(data2!.xValues, y: data2!.yValues, count: data2!.size) ds3.appendRangeX(data3!.xValues, y: data3!.yValues, count: data3!.size) SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds1, brushColor: 0x77279B27, strokeColor: 0xFF177B17)) self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds2, brushColor: 0x77FF1919, strokeColor: 0xFFDD0909)) self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds3, brushColor: 0x771964FF, strokeColor: 0xFF0944CF)) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()]) } } fileprivate func getRenderableSeriesWith(_ dataSeries: SCIXyDataSeries, brushColor: UInt32, strokeColor: UInt32) -> SCIFastMountainRenderableSeries { let rSeries = SCIFastMountainRenderableSeries() rSeries.strokeStyle = SCISolidPenStyle(colorCode: strokeColor, withThickness: 1) rSeries.areaStyle = SCISolidBrushStyle(colorCode: brushColor) rSeries.dataSeries = dataSeries rSeries.addAnimation(SCIWaveRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) return rSeries } }
918d94a49655cc9e9af7f116f667dc78
56.637931
158
0.674843
false
false
false
false
vanjakom/photo-db
refs/heads/master
photodb view/photodb view/MungoLabApiClient.swift
mit
1
// // MungoLabApiClient.swift // photodb view // // Created by Vanja Komadinovic on 1/23/16. // Copyright © 2016 mungolab.com. All rights reserved. // import Foundation class MungLabApiClient { class func asyncApiRequest(_ url: String, request: Dictionary<String, AnyObject>, callback: @escaping (Dictionary<String, AnyObject>?) -> Void) throws -> Void { let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: url)! as URL) urlRequest.httpMethod = "POST" urlRequest.timeoutInterval = 10.0 urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let data: Data = try JSONSerialization.data(withJSONObject: request, options: JSONSerialization.WritingOptions()) urlRequest.httpBody = data as Data URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in guard let _: NSData = data as NSData?, let _: URLResponse = response , error == nil else { callback(nil) return } do { let responseDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, AnyObject> callback(responseDict) } catch { callback(nil) }}.resume() } class func asyncRenderRequest(_ url: String, request: Dictionary<String, AnyObject>, callback: @escaping (Data?) -> Void) throws -> Void { let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: url)! as URL) urlRequest.httpMethod = "POST" urlRequest.timeoutInterval = 10.0 urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let data: Data = try JSONSerialization.data(withJSONObject: request, options: JSONSerialization.WritingOptions()) urlRequest.httpBody = data URLSession.shared.dataTask(with: urlRequest as URLRequest, completionHandler: { (data, response, error) -> Void in guard let _: Data = data, let _: URLResponse = response , error == nil else { callback(nil) return } callback(data!) }) .resume() } }
edab6d6933b59e2e5f236f8381eaf234
39.440678
164
0.611903
false
false
false
false
zcfsmile/Swifter
refs/heads/master
BasicSyntax/001Playground.playground/Contents.swift
mit
1
import Foundation import UIKit //: 苹果为推动 Swift 的发展花了很大的力气,Playground 就是其中的一个。Playground 大大降低了 Swift 的学习门槛,它可以实时执行 swift 代码,并将结果显示出来,并且还有各种交互来加深你对 swift 语法的理解。 //: ## Source 目录 //: 此目录下的源文件会被编译成模块(module)并自动导入到 Playground 中,并且这个编译只会进行一次(或者我们对该目录下的文件进行修改的时候会重新编译),而不是每次你敲入一个字母的时候就编译一次。这将会大大提高代码执行的效率。 //: > Note //: > 由于此目录下的文件都是被编译成模块导入的,只有被设置成 public 的类型,属性或方法才能在 Playground 中使用。 //: ## 资源 //: ### 独立资源 //: 放置在每一个 Resources 目录资源是每个 Playground 独立的资源。这些资源是直接放置在 `mainBundle` 中的,可以使用如下代码来获取资源路径。 if let path = Bundle.main.path(forResource: "0", ofType: "jpg") { print(path) } //: 如果是图片资源 let image = UIImage.init(named: "0.jpg") let imageV = UIImageView.init(image: image) //: ### 共享资源 //: 共享资源需要将资源存放在 `~/Documents/Shared Playground Data` 下。 //: 使用的时候,需要先导入 `PlaygroundSupport` 模块。 import PlaygroundSupport let sharedFileURL = PlaygroundSupport.playgroundSharedDataDirectory.appendingPathComponent("example.json") print(sharedFileURL) //: ### 异步执行 //: Palyground 中的代码是顶层代码,也就是说是在全局作用域中,这些代码是从上到下执行的。 //: 因此当我们在 Playground 中执行网络或耗时的异步操作时都无法获得我们想要的结果。 /*: 为了让程序在代码执行结束后继续执行,我们可以使用`PlaygroundPage.current.needsIndefiniteExecution = true`,这句代码会让程序一直执行下去,当我们获取到需要的结果的时候,可以停止,`PlaygroundPage.current.finishExecution()` */ //: 下面的代码示例表示执行一个异步的网络请求: PlaygroundPage.current.needsIndefiniteExecution = true let url = URL.init(string: "https://devimages-cdn.apple.com/assets/elements/icons/swift/swift-64x64_2x.png") let task = URLSession.shared.dataTask(with: url!) { (data, _, _) in let image = UIImage(data: data!)! print(image) PlaygroundPage.current.finishExecution() } task.resume() //: ### 支持 Markdown //: 菜单 Editor → Show Rendered Markup 下切换是否进行 markdown 渲染。 //: 更多的 MarkDown 格式可以参考 [Markup Formatting Reference](https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/index.html#//apple_ref/doc/uid/TP40016497) //: 关于更多的 Playground 使用可以参考 [Xcode Helper -- Use Playground](https://help.apple.com/xcode/mac/8.0/#/dev188e45167)
2f90eb6a95ac8142e7a638bb0d50b2e0
32.949153
198
0.761857
false
false
false
false
LamGiauKhongKhoTeam/LGKK
refs/heads/master
Modules/FlagKit/CountryPicker.swift
mit
1
// // CountryPicker.swift // drivethrough // // Created by Nguyen Minh on 3/29/17. // Copyright © 2017 SP. All rights reserved. // import UIKit import libPhoneNumber_iOS protocol CountryPickerDelegate: class { func countryPhoneCodePicker(picker: CountryPicker, didSelectCountryCountryWithName name: String, countryCode: String, phoneCode: String) } struct Country { var code: String? var name: String? var phoneCode: String? init(code: String?, name: String?, phoneCode: String?) { self.code = code self.name = name self.phoneCode = phoneCode } } class CountryPicker: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource { var countries: [Country]! var countryPhoneCodeDelegate: CountryPickerDelegate? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { super.dataSource = self; super.delegate = self; countries = countryNamesByCode() } // MARK: - Country Methods func setCountry(code: String) { var row = 0 for index in 0..<countries.count { if countries[index].code?.uppercased() == code.uppercased() { row = index break } } self.selectRow(row, inComponent: 0, animated: true) } fileprivate func countryNamesByCode() -> [Country] { var countries = [Country]() for code in NSLocale.isoCountryCodes { if let countryName = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: code) { let phoneNumberUtil = NBPhoneNumberUtil.sharedInstance() let num = phoneNumberUtil?.getCountryCode(forRegion: code) let phoneCode: String = String(format: "+%d", (num?.intValue)!) if phoneCode != "+0" { let country = Country(code: code, name: countryName, phoneCode: phoneCode) countries.append(country) } } } countries = countries.sorted(by: { (c1, c2) -> Bool in return c1.name! < c2.name! }) return countries } // MARK: - Picker Methods func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return countries.count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var resultView: CountryView if view == nil { resultView = (Bundle.main.loadNibNamed("CountryView", owner: self, options: nil)![0] as! CountryView) } else { resultView = view as! CountryView } resultView.setup(country: countries[row]) return resultView } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let country = countries[row] if let countryPhoneCodeDelegate = countryPhoneCodeDelegate { countryPhoneCodeDelegate.countryPhoneCodePicker(picker: self, didSelectCountryCountryWithName: country.name!, countryCode: country.code!, phoneCode: country.phoneCode!) } } }
2349878f637c7f3d5500e7ed7b6744e1
30.522523
180
0.607031
false
false
false
false
DungeonKeepers/DnDInventoryManager
refs/heads/master
DnDInventoryManager/DnDInventoryManager/CampaignsTableViewController.swift
mit
1
// // CampaignsTableViewController.swift // DnDInventoryManager // // Created by Adrian Kenepah-Martin on 4/12/17. // Copyright © 2017 Mike Miksch. All rights reserved. // import UIKit import CloudKit class CampaignsTableViewController: UITableViewController { var campaignsList: Array<CKRecord> = [] @IBOutlet weak var campaignsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() fetchCampaigns() } // MARK: fetchCampaigns Function func fetchCampaigns() { campaignsList = Array<CKRecord>() let publicDatabase = CKContainer.default().publicCloudDatabase let predicate = NSPredicate(value: true) let query = CKQuery(recordType: "Campaigns", predicate: predicate) query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] publicDatabase.perform(query, inZoneWith: nil) { (results, error) in if error != nil { OperationQueue.main.addOperation { print("Error: \(error.debugDescription)") } } else { if let results = results { for result in results { self.campaignsList.append(result) } } OperationQueue.main.addOperation { self.tableView.reloadData() } } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return campaignsList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CampaignCell", for: indexPath) as UITableViewCell let noteRecord: CKRecord = campaignsList[(indexPath.row)] cell.textLabel?.text = noteRecord.value(forKey: "name") as? String cell.imageView?.image = noteRecord.value(forKey: "img") as? UIImage return cell } }
e557dbb8c5fa91f53507fc823d097cda
32.013699
115
0.612033
false
false
false
false
Finb/V2ex-Swift
refs/heads/master
View/V2FPSLabel.swift
mit
2
// // V2FPSLabel.swift // V2ex-Swift // // Created by huangfeng on 1/15/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit //重写自 YYFPSLabel //https://github.com/ibireme/YYText/blob/master/Demo/YYTextDemo/YYFPSLabel.m class V2FPSLabel: UILabel { fileprivate var _link :CADisplayLink? fileprivate var _count:Int = 0 fileprivate var _lastTime:TimeInterval = 0 fileprivate let _defaultSize = CGSize(width: 55, height: 20); override init(frame: CGRect) { var targetFrame = frame if frame.size.width == 0 && frame.size.height == 0{ targetFrame.size = _defaultSize } super.init(frame: targetFrame) self.layer.cornerRadius = 5 self.clipsToBounds = true self.textAlignment = .center self.isUserInteractionEnabled = false self.textColor = UIColor.white self.backgroundColor = UIColor(white: 0, alpha: 0.7) self.font = UIFont(name: "Menlo", size: 14) weak var weakSelf = self _link = CADisplayLink(target: weakSelf!, selector:#selector(V2FPSLabel.tick(_:)) ); _link!.add(to: RunLoop.main, forMode:RunLoop.Mode.common) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @objc func tick(_ link:CADisplayLink) { if _lastTime == 0 { _lastTime = link.timestamp return } _count += 1 let delta = link.timestamp - _lastTime if delta < 1 { return } _lastTime = link.timestamp let fps = Double(_count) / delta _count = 0 let progress = fps / 60.0; self.textColor = UIColor(hue: CGFloat(0.27 * ( progress - 0.2 )) , saturation: 1, brightness: 0.9, alpha: 1) self.text = "\(Int(fps+0.5))FPS" } }
73a42f8afaf9811695929b17c634f531
28.375
116
0.581915
false
false
false
false
JGiola/swift
refs/heads/main
test/Serialization/Recovery/implementation-only-missing.swift
apache-2.0
11
// Recover from missing types hidden behind an importation-only when indexing // a system module. // rdar://problem/52837313 // RUN: %empty-directory(%t) //// Build the private module, the public module and the client app normally. //// Force the public module to be system with an underlying Clang module. // RUN: %target-swift-frontend -emit-module -DPRIVATE_LIB %s -module-name private_lib -emit-module-path %t/private_lib.swiftmodule // RUN: %target-swift-frontend -emit-module -DPUBLIC_LIB %s -module-name public_lib -emit-module-path %t/public_lib.swiftmodule -I %t -I %S/Inputs/implementation-only-missing -import-underlying-module //// The client app should build OK without the private module. Removing the //// private module is superfluous but makes sure that it's not somehow loaded. // RUN: rm %t/private_lib.swiftmodule // RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -index-system-modules -index-store-path %t // RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -D FAIL_TYPECHECK -verify // RUN: %target-swift-frontend -emit-sil -DCLIENT_APP %s -I %t -module-name client //// Printing the public module should not crash when checking for overrides of //// methods from the private module. // RUN: %target-swift-ide-test -print-module -module-to-print=public_lib -source-filename=x -skip-overrides -I %t #if PRIVATE_LIB @propertyWrapper public struct IoiPropertyWrapper<V> { var content: V public init(_ v: V) { content = v } public var wrappedValue: V { return content } } public struct HiddenGenStruct<A: HiddenProtocol> { public init() {} } public protocol HiddenProtocol { associatedtype Value } public protocol HiddenProtocol2 {} public protocol HiddenProtocolWithOverride { func hiddenOverride() } public class HiddenClass {} #elseif PUBLIC_LIB @_implementationOnly import private_lib struct LibProtocolConstraint { } protocol LibProtocolTABound { } struct LibProtocolTA: LibProtocolTABound { } protocol LibProtocol { associatedtype TA: LibProtocolTABound = LibProtocolTA func hiddenRequirement<A>( param: HiddenGenStruct<A> ) where A.Value == LibProtocolConstraint } extension LibProtocol where TA == LibProtocolTA { func hiddenRequirement<A>( param: HiddenGenStruct<A> ) where A.Value == LibProtocolConstraint { } } public struct PublicStruct: LibProtocol { typealias TA = LibProtocolTA public init() { } public var nonWrappedVar: String = "some text" } struct StructWithOverride: HiddenProtocolWithOverride { func hiddenOverride() {} } internal protocol RefinesHiddenProtocol: HiddenProtocol { } public struct PublicStructConformsToHiddenProtocol: RefinesHiddenProtocol { public typealias Value = Int public init() { } } public class SomeClass { func funcUsingIoiType(_ a: HiddenClass) {} } // Check that we recover from a reference to an implementation-only // imported type in a protocol composition. rdar://78631465 protocol CompositionMemberInheriting : HiddenProtocol2 {} protocol CompositionMemberSimple {} protocol InheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {} struct StructInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {} class ClassInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {} protocol InheritingFromCompositionDirect : CompositionMemberSimple & HiddenProtocol2 {} #elseif CLIENT_APP import public_lib var s = PublicStruct() print(s.nonWrappedVar) var p = PublicStructConformsToHiddenProtocol() print(p) #if FAIL_TYPECHECK // Access to a missing member on an AnyObject triggers a typo correction // that looks at *all* class members. rdar://79427805 class ClassUnrelatedToSomeClass {} var something = ClassUnrelatedToSomeClass() as AnyObject something.triggerTypoCorrection = 123 // expected-error {{value of type 'AnyObject' has no member 'triggerTypoCorrection'}} #endif #endif
f4aa6c324be3bf8c7f9bc52581ff397e
29.561538
200
0.762648
false
false
false
false
JaySonGD/SwiftDayToDay
refs/heads/master
监听区域/监听区域/ViewController.swift
mit
1
// // ViewController.swift // 监听区域 // // Created by czljcb on 16/3/10. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController { lazy var location: CLLocationManager = { let location = CLLocationManager() location.delegate = self if #available(iOS 8.0, *){ location.requestAlwaysAuthorization() if #available(iOS 9.0, *){ location.allowsBackgroundLocationUpdates = true } } return location }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion.self){ let center = CLLocationCoordinate2D(latitude: 12.12, longitude: 12.12) let region = CLCircularRegion(center: center, radius: 100000, identifier: "json") location.startMonitoringForRegion(region) } location.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: CLLocationManagerDelegate{ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print(locations.last) } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { print(region.identifier) } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { print(region.identifier) } }
9bacb40a785f62a7fff0f8609768ddf0
25.911765
98
0.617277
false
false
false
false
KrishMunot/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00429-vtable.swift
apache-2.0
4
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse } struct S { static let i: B<Q<T where A""" } } import Foundation return "\(g, e) return true struct d: U -> T) { }() extension NSSet { class B protocol e == { x } func g<T) { } typealias e : d = b: a { self) protocol e = T, b = b: A? = b> T struct B<Q<T](") let f : c> (b let c : AnyObject, AnyObject) { } struct d: T.B class A : A> (self)? var d = [unowned self.dynamicType) import Foundation c> { let c: a = b: T : NSObject { func f.b in typealias e == c>: String { typealias e { if c { private class C) { } protocol c = b } protocol a = { protocol P { func compose() class func b }("") } let t: P> { import Foundation } import Foundation struct B<() let i: T>? = A>() let c } protocol P { } } d.h import Foundation S<T -> { } } d.c() } enum S<T>Bool
4306b810fc89da590df325bbc42c45a9
15.608696
78
0.647469
false
false
false
false
CodaFi/swift
refs/heads/main
test/SILOptimizer/devirt_dependent_types.swift
apache-2.0
70
// RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s protocol Bar { associatedtype Element } class FooImplBase<OutputElement> { func virtualMethod() -> FooImplBase<OutputElement> { fatalError("implement") } } final class FooImplDerived<Input : Bar> : FooImplBase<Input.Element> { init(_ input: Input) {} override func virtualMethod() -> FooImplBase<Input.Element> { return self } } struct BarImpl : Bar { typealias Element = Int } // Check that all calls can be devirtualized and later on inlined. // CHECK-LABEL: sil {{.*}}zzz // CHECK: bb0 // CHECK-NOT: bb1 // CHECK-NOT: function_ref // CHECK-NOT: class_method // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: return public func zzz() { let xs = BarImpl() var source: FooImplBase<Int> = FooImplDerived(xs) source = source.virtualMethod() source = source.virtualMethod() source = source.virtualMethod() }
0452c8439a1c656e02cbbfc92497404a
20.571429
70
0.687638
false
false
false
false
alexandresoliveira/IosSwiftExamples
refs/heads/master
CardApp/CardApp/ViewController.swift
gpl-3.0
1
// // ViewController.swift // CardApp // // Created by Alexandre Salvador de Oliveira on 13/01/2018. // Copyright © 2018 Alexandre Salvador de Oliveira. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scroll: UIScrollView! @IBOutlet weak var greenView: UIView! @IBOutlet weak var purpleView: UIView! @IBOutlet weak var blueView: UIView! override func viewDidLoad() { super.viewDidLoad() addCardViews() addActionViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func addCardViews() { let margins = scroll.layoutMarginsGuide var lastCardView: CardView? = nil for _ in 0...8 { let cardView: CardView = CardView() cardView.backgroundColor = UIColor.white scroll.addSubview(cardView) cardView.translatesAutoresizingMaskIntoConstraints = false cardView.heightAnchor.constraint(equalToConstant: 150).isActive = true cardView.widthAnchor.constraint(equalToConstant: scroll.bounds.width - 32).isActive = true cardView.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true if lastCardView != nil { cardView.topAnchor.constraint(equalTo: (lastCardView?.bottomAnchor)!, constant: 16.0).isActive = true } else { cardView.topAnchor.constraint(equalTo: scroll.topAnchor, constant: 8.0).isActive = true } lastCardView = cardView } let newHeightScroll: CGFloat = 150.0 * 10 scroll.contentSize = CGSize(width: scroll.bounds.width, height: newHeightScroll) } private func addActionViews() { let tapG = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapGreen)) greenView.addGestureRecognizer(tapG) let tapP = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapPurple)) purpleView.addGestureRecognizer(tapP) let tapB = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapBlue)) blueView.addGestureRecognizer(tapB) } @objc func tapGreen() { alert("Green Tap") } @objc func tapPurple() { alert("Purple Tap") } @objc func tapBlue() { alert("Blue Tap") } private func alert(_ msg: String) { let alert = UIAlertController(title: "Alert", message: msg, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
103462f37802037b775b3f4b742b1059
34.935065
117
0.656306
false
false
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/StudyNote/StudyNote/YYText/SNTextFieldInputSummaryViewController.swift
apache-2.0
1
// // SNTextFieldInputSummaryViewController.swift // StudyNote // // Created by wuyp on 2019/6/27. // Copyright © 2019 Raymond. All rights reserved. // import UIKit import RxSwift import RxCocoa class SNTextFieldInputSummaryViewController: UIViewController { @objc private lazy dynamic var inputTF: UITextField = { let tf = UITextField(frame: CGRect(x: 50, y: 100, width: 200, height: 30)) tf.layer.borderWidth = 1 tf.layer.borderColor = UIColor.red.cgColor tf.keyboardType = UIKeyboardType.numberPad if #available(iOS 12, *) { tf.textContentType = UITextContentType.oneTimeCode } return tf }() private let bag = DisposeBag() @objc override dynamic func viewDidLoad() { super.viewDidLoad() self.view.addSubview(inputTF) rxBinding() } @objc private dynamic func rxBinding() { inputTF.rx.controlEvent(.editingChanged).subscribe { (_) in print("------测试") }.disposed(by: bag) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { } }
57e31dcf4669ce7c8d66cc4ad34d5b02
24.608696
82
0.610357
false
false
false
false
CoderST/XMLYDemo
refs/heads/master
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/ListViewController/Controller/ListViewController.swift
mit
1
// // 5000 ListViewController.swift // XMLYDemo // // Created by xiudou on 2016/12/21. // Copyright © 2016年 CoderST. All rights reserved. // 榜单 import UIKit private let ListViewCellIdentifier = "ListViewCellIdentifier" private let FocusViewReusableViewHeadIdentifier = "FocusViewReusableViewHeadIdentifier" private let FocusViewReusableViewFootIdentifier = "FocusViewReusableViewFootIdentifier" private let headCellHeight : CGFloat = 160 class ListViewController: UIViewController { fileprivate lazy var listVM : ListViewModel = ListViewModel() fileprivate lazy var focusView : FocusView = FocusView() // MARK:- 属性 fileprivate var collectionView : UICollectionView! override func viewDidLoad() { super.viewDidLoad() setupUI() // getListVCDate() } } extension ListViewController { fileprivate func setupUI() { // 1 设置collectionView setupCollectionView() // 2 设置焦点图 setupFocusView() // 3 设置collectionView间距 collectionView.contentInset = UIEdgeInsets(top: headCellHeight, left: 0, bottom: 0, right: 0) // 4 设置刷新 let refresh = STRefreshHeader(refreshingTarget: self, refreshingAction: #selector(refreshHeaderAction)) collectionView.mj_header = refresh refresh!.ignoredScrollViewContentInsetTop = headCellHeight collectionView.mj_header.beginRefreshing() } fileprivate func setupFocusView(){ collectionView.addSubview(focusView) focusView.backgroundColor = UIColor.orange focusView.frame = CGRect(x: 0, y: -headCellHeight, width: collectionView.frame.width, height: headCellHeight) } fileprivate func setupCollectionView() { // 设置layout属性 let layout = UICollectionViewFlowLayout() layout.headerReferenceSize = CGSize(width: stScreenW, height: sHeaderReferenceHeight) layout.footerReferenceSize = CGSize(width: stScreenW, height: 10) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 // 创建UICollectionView collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: stScreenH - 64 - 44 - 49), collectionViewLayout: layout) // 设置数据源 collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor(r: 245, g: 245, b: 245) // 注册head collectionView.register(ListHeadReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: FocusViewReusableViewHeadIdentifier) // foot collectionView.register(ListFootReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: FocusViewReusableViewFootIdentifier) // 注册展示cell collectionView.register(ListViewCell.self, forCellWithReuseIdentifier: ListViewCellIdentifier) // 注册普通cell view.addSubview(collectionView) } } // MARK:- 刷新相关 extension ListViewController { func refreshHeaderAction() { getListVCDate() } } extension ListViewController { fileprivate func getListVCDate() { listVM.getlistData { if let model = self.listVM.focusModelArray.first{ self.focusView.focusModel = model } self.collectionView.reloadData() self.collectionView.mj_header.endRefreshing() } } } extension ListViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ let count = listVM.listModelArray.count return count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = listVM.listModelArray[section] return group.list.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ListViewCellIdentifier, for: indexPath) as! ListViewCell cell.listModel = listVM.listModelArray[indexPath.section].list[indexPath.item] return cell } } extension ListViewController : UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width, height: 75) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader{ let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: FocusViewReusableViewHeadIdentifier, for: indexPath) as!ListHeadReusableView headerView.title = listVM.listModelArray[indexPath.section].title return headerView }else { let footView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: FocusViewReusableViewFootIdentifier, for: indexPath) as!ListFootReusableView return footView } } }
828df5fe4c2d3f698627a276209e9f00
34.075472
188
0.691053
false
false
false
false
artursDerkintis/YouTube
refs/heads/master
YouTube/ChannelProvider.swift
mit
1
// // ChannelProvider.swift // YouTube // // Created by Arturs Derkintis on 1/28/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ChannelProvider: NSObject { func getVideosOfChannel(channelId: String, accessToken : String?, pageToken : String?, completion: (nextPageToken: String?, items : [Item]) -> Void){ let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=\(channelId)&key=\(kYoutubeKey)&order=date&type=video" var params = Dictionary<String, AnyObject>() params["maxResults"] = 30 if let pageToken = pageToken{ params["pageToken"] = pageToken } if let token = accessToken{ params["access_token"] = token } let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!, parameters : params).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) //print("JSON: \(json)") if let array = json["items"].array{ self.parseItems(array, completion: { (items) -> Void in let nextpagetoken = json["nextPageToken"].string completion(nextPageToken: nextpagetoken, items: items) }) } } case .Failure(let error): print(error) } } } func parseItems(objects : [JSON], completion : (items : [Item]) -> Void){ var items = [Item]() for object in objects{ let item = Item() items.append(item) self.parseItem(object, item: item, completion: { (item) -> Void in let amount = items.filter({ (item) -> Bool in return item.type != .None }) if amount.count == objects.count{ completion(items: items) } }) } } func parseItem(object : JSON, item : Item, completion : (item : Item) -> Void){ if let kind = object["id"]["kind"].string{ switch kind{ case "youtube#video": let videoId = object["id"]["videoId"].string let video = Video() video.getVideoDetails(videoId!, completion: { (videoDetails) -> Void in video.videoDetails = videoDetails item.video = video completion(item: item) }) break default: item.type = .Unrecognized break } } } } func haveISubscribedToChannel(id: String, token : String, completion : (Bool) -> Void){ let url = "https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&access_token=\(token)&forChannelId=\(id)" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) if let array = json["items"].array{ print(array.count == 0 ? "empty" : "full") completion(array.count == 0 ? false : true) } } case .Failure(let error): print(error) } } } func getSubscritionId(channelId : String, token : String?, completion:(subscriptionId : String) -> Void){ let url = "https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&access_token=\(token ?? "")&forChannelId=\(channelId)" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) if let array = json["items"].array{ if let id = array[0]["id"].string{ completion(subscriptionId: id) } } } break case .Failure(let error): print(error) break } } }
7c8b9c470ff04cfc8cdf3d6364616c6f
36.246154
154
0.527784
false
false
false
false
maxim-pervushin/HyperHabit
refs/heads/master
HyperHabit/Common/Data/DataManager.swift
mit
1
// // Created by Maxim Pervushin on 23/11/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import Foundation class DataManager { // MARK: DataManager public static let changedNotification = "DataManagerChangedNotification" init(cache: Cache, service: Service) { self.cache = cache self.service = service self.cache.changesObserver = self timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction:", userInfo: nil, repeats: true) timer.fire() } // MARK: DataManager private private var cache: Cache private var service: Service private var timer: NSTimer! private var saveHabitsAfter = 0 private var saveReportsAfter = 0 @objc private func timerAction(timer: NSTimer) { if saveHabitsAfter <= 0 { saveHabitsAfter = Int.max syncHabits() } else { saveHabitsAfter-- } if saveReportsAfter <= 0 { saveReportsAfter = Int.max syncReports() } else { saveReportsAfter-- } } private func changed() { NSNotificationCenter.defaultCenter().postNotificationName(DataManager.changedNotification, object: self) } private func syncHabits() { if !service.available { self.saveHabitsAfter = 30 return } dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { () -> Void in // Save habits if self.cache.habitsByIdToSave.count > 0 { let habits = self.cache.habitsByIdToSave.values // Remove selected habits from habits-to-save to avoid save attempt from another thread for habit in habits { self.cache.habitsByIdToSave[habit.id] = nil } do { try self.service.saveHabits(Array(habits)) } catch { // Put habits-to-save back if something goes wrong for habit in habits { self.cache.habitsByIdToSave[habit.id] = habit } print("ERROR: Unable to save habits") } } // Load habits do { let habits = try self.service.getHabits() var habitsById = [String: Habit]() for habit in habits { habitsById[habit.id] = habit } self.cache.habitsById = habitsById self.changed() } catch { print("ERROR: Unable to load habits") } self.saveHabitsAfter = 30 } } private func syncReports() { if !service.available { self.saveReportsAfter = 30 return } dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { // Save reports if self.cache.reportsByIdToSave.count > 0 { let reports = self.cache.reportsByIdToSave.values // Remove selected reports from reports-to-save to avoid save attempt from another thread for report in reports { self.cache.reportsByIdToSave[report.id] = nil } do { try self.service.saveReports(Array(reports)) } catch { // Put reports-to-save back if something goes wrong for report in reports { self.cache.reportsByIdToSave[report.id] = report } print("ERROR: Unable to save reports") } } // Delete reports if self.cache.reportsByIdToDelete.count > 0 { let reports = self.cache.reportsByIdToDelete.values // Remove selected reports from reports-to-delete to avoid delete attempt from another thread for report in reports { self.cache.reportsByIdToDelete[report.id] = nil } do { try self.service.deleteReports(Array(reports)) } catch { // Put reports-to-delete back if something goes wrong for report in reports { self.cache.reportsByIdToDelete[report.id] = report } print("ERROR: Unable to delete reports") } } // Load reports do { let reports = try self.service.getReports() var reportsById = [String: Report]() for report in reports { reportsById[report.id] = report } self.cache.reportsById = reportsById self.changed() } catch { print("ERROR: Unable to load reports") } self.saveReportsAfter = 30 } } func clearCache() { cache.clear() } } extension DataManager: DataProvider { var habits: [Habit] { return Array(cache.habitsById.values.filter { return $0.active }) } func saveHabit(habit: Habit) -> Bool { let activeHabit = habit.activeHabit cache.habitsById[habit.id] = activeHabit cache.habitsByIdToSave[habit.id] = activeHabit saveHabitsAfter = 2 changed() return true } func deleteHabit(habit: Habit) -> Bool { let inactiveHabit = habit.inactiveHabit cache.habitsById[habit.id] = inactiveHabit cache.habitsByIdToSave[habit.id] = inactiveHabit saveHabitsAfter = 2 changed() return true } var reports: [Report] { return Array(cache.reportsById.values) } func reportsForDate(date: NSDate) -> [Report] { let dateComponent = date.dateComponent return Array(cache.reportsById.values.filter { return $0.date.dateComponent == dateComponent }) } func saveReport(report: Report) -> Bool { cache.reportsById[report.id] = report cache.reportsByIdToSave[report.id] = report cache.reportsByIdToDelete[report.id] = nil saveReportsAfter = 2 changed() return true } func deleteReport(report: Report) -> Bool { cache.reportsById[report.id] = nil cache.reportsByIdToSave[report.id] = nil cache.reportsByIdToDelete[report.id] = report saveReportsAfter = 2 changed() return true } func reportsFiltered(habit: Habit?, fromDate: NSDate, toDate: NSDate) -> [Report] { var result = [Report]() let fromTimeInterval = fromDate.timeIntervalSince1970 let toTimeInterval = toDate.timeIntervalSince1970 for report in cache.reportsById.values { let reportTimeInterval = report.date.timeIntervalSince1970 if reportTimeInterval >= fromTimeInterval && reportTimeInterval < toTimeInterval { if let habit = habit { if habit.name == report.habitName { result.append(report) } } else { result.append(report) } } } return result } } extension DataManager: ChangesObserver { func observableChanged(observable: AnyObject) { if let _ = observable as? Cache { NSNotificationCenter.defaultCenter().postNotificationName(DataManager.changedNotification, object: self) } } }
be10e6933821cfb72f1f1c698945524b
29.380392
127
0.543377
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
refs/heads/master
Example/Pods/SKPhotoBrowser/SKPhotoBrowser/SKToolbar.swift
apache-2.0
1
// // SKToolbar.swift // SKPhotoBrowser // // Created by 鈴木 啓司 on 2016/08/12. // Copyright © 2016年 suzuki_keishi. All rights reserved. // import Foundation // helpers which often used private let bundle = Bundle(for: SKPhotoBrowser.self) class SKToolbar: UIToolbar { var toolCounterLabel: UILabel! var toolCounterButton: UIBarButtonItem! var toolPreviousButton: UIBarButtonItem! var toolNextButton: UIBarButtonItem! var toolActionButton: UIBarButtonItem! fileprivate weak var browser: SKPhotoBrowser? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) self.browser = browser setupApperance() setupPreviousButton() setupNextButton() setupCounterLabel() setupActionButton() setupToolbar() } func updateToolbar(_ currentPageIndex: Int) { guard let browser = browser else { return } if browser.numberOfPhotos > 1 { toolCounterLabel.text = "\(currentPageIndex + 1) / \(browser.numberOfPhotos)" } else { toolCounterLabel.text = nil } toolPreviousButton.isEnabled = (currentPageIndex > 0) toolNextButton.isEnabled = (currentPageIndex < browser.numberOfPhotos - 1) } } private extension SKToolbar { func setupApperance() { backgroundColor = .clear clipsToBounds = true isTranslucent = true setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) // toolbar if !(browser?.showToolBar)! { isHidden = true } } func setupToolbar() { guard let browser = browser else { return } let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) var items = [UIBarButtonItem]() items.append(flexSpace) if browser.numberOfPhotos > 1 && SKPhotoBrowserOptions.displayBackAndForwardButton { items.append(toolPreviousButton) } if SKPhotoBrowserOptions.displayCounterLabel { items.append(flexSpace) items.append(toolCounterButton) items.append(flexSpace) } else { items.append(flexSpace) } if browser.numberOfPhotos > 1 && SKPhotoBrowserOptions.displayBackAndForwardButton { items.append(toolNextButton) } items.append(flexSpace) if SKPhotoBrowserOptions.displayAction { items.append(toolActionButton) } setItems(items, animated: false) } func setupPreviousButton() { let previousBtn = SKPreviousButton(frame: frame) previousBtn.addTarget(browser, action: #selector(SKPhotoBrowser.gotoPreviousPage), for: .touchUpInside) toolPreviousButton = UIBarButtonItem(customView: previousBtn) } func setupNextButton() { let nextBtn = SKNextButton(frame: frame) nextBtn.addTarget(browser, action: #selector(SKPhotoBrowser.gotoNextPage), for: .touchUpInside) toolNextButton = UIBarButtonItem(customView: nextBtn) } func setupCounterLabel() { toolCounterLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 95, height: 40)) toolCounterLabel.textAlignment = .center toolCounterLabel.backgroundColor = .clear toolCounterLabel.shadowColor = SKToolbarOptions.textShadowColor toolCounterLabel.shadowOffset = CGSize(width: 0.0, height: 1.0) toolCounterLabel.font = SKToolbarOptions.font toolCounterLabel.textColor = SKToolbarOptions.textColor toolCounterButton = UIBarButtonItem(customView: toolCounterLabel) } func setupActionButton() { toolActionButton = UIBarButtonItem(barButtonSystemItem: .action, target: browser, action: #selector(SKPhotoBrowser.actionButtonPressed)) toolActionButton.tintColor = UIColor.white } } class SKToolbarButton: UIButton { let insets: UIEdgeInsets = UIEdgeInsets(top: 13.25, left: 17.25, bottom: 13.25, right: 17.25) func setup(_ imageName: String) { backgroundColor = .clear imageEdgeInsets = insets translatesAutoresizingMaskIntoConstraints = true autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] contentMode = .center let image = UIImage(named: "SKPhotoBrowser.bundle/images/\(imageName)", in: bundle, compatibleWith: nil) ?? UIImage() setImage(image, for: UIControlState()) } } class SKPreviousButton: SKToolbarButton { let imageName = "btn_common_back_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } } class SKNextButton: SKToolbarButton { let imageName = "btn_common_forward_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } }
7d540f976cc84f67d1016049f204f9c0
32.368098
144
0.6492
false
false
false
false
remirobert/Dotzu
refs/heads/master
Framework/Dotzu/Dotzu/ListCrashesViewController.swift
mit
2
// // ListCrashesViewController.swift // exampleWindow // // Created by Remi Robert on 31/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class ListCrashesViewController: UIViewController { @IBOutlet weak var tableview: UITableView! @IBOutlet weak var labelEmpty: UILabel! let datasource = ListLogDataSource<LogCrash>() @objc func deleteCrashes() { let _ = StoreManager<LogCrash>(store: .crash).reset() datasource.reset() datasource.reloadData() tableview.reloadData() labelEmpty.isHidden = datasource.count > 0 } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(ListCrashesViewController.deleteCrashes)) LogViewNotification.countCrash = 0 title = "Crash sessions" tableview.registerCellWithNib(cell: CrashListTableViewCell.self) tableview.estimatedRowHeight = 50 tableview.rowHeight = UITableViewAutomaticDimension tableview.delegate = self tableview.dataSource = datasource tableview.tableFooterView = UIView() datasource.reloadData() labelEmpty.isHidden = datasource.count > 0 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let controller = segue.destination as? DetailCrashTableViewController, let crash = sender as? LogCrash else {return} controller.crash = crash } } extension ListCrashesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let crash = datasource[indexPath.row] else {return} performSegue(withIdentifier: "detailCrashSegue", sender: crash) } }
28efae65e9355b8712459dc6164ab537
33.929825
119
0.662481
false
false
false
false
NUKisZ/MyTools
refs/heads/master
BeeFun/Pods/GDPerformanceView-Swift/GDPerformanceView-Swift/GDPerformanceMonitoring/GDWindowViewController.swift
mit
2
// // Copyright © 2017 Gavrilov Daniil // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit internal class GDWindowViewController: UIViewController { // MARK: Private Properties private var selectedStatusBarHidden: Bool = false private var selectedStatusBarStyle: UIStatusBarStyle = UIStatusBarStyle.default // MARK: Properties Overriders override var prefersStatusBarHidden: Bool { get { return self.selectedStatusBarHidden } } override var preferredStatusBarStyle: UIStatusBarStyle { get { return self.selectedStatusBarStyle } } // MARK: Init Methods & Superclass Overriders override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .clear } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Public Methods internal func configureStatusBarAppearance(prefersStatusBarHidden: Bool, preferredStatusBarStyle: UIStatusBarStyle) { self.selectedStatusBarHidden = prefersStatusBarHidden self.selectedStatusBarStyle = preferredStatusBarStyle } }
b89366987767384f61323bcbaf924e91
33.287879
121
0.714096
false
false
false
false
Urinx/Device-9
refs/heads/master
Device 9/Device 9/WorksTableViewController.swift
apache-2.0
1
// // WorksTableViewController.swift // Device 9 // // Created by Eular on 9/21/15. // Copyright © 2015 Eular. All rights reserved. // import UIKit class WorksTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let headerView = UIView() let back = UIButton() let title = UILabel() headerView.frame = CGRectMake(0, 0, view.bounds.width, 100) back.frame = CGRectMake(20, 35, 30, 30) back.setImage(UIImage(named: "back-100"), forState: .Normal) back.addTarget(self, action: "back", forControlEvents: .TouchUpInside) headerView.addSubview(back) title.frame = CGRectMake(self.view.bounds.width/2 - 60, 30, 120, 40) title.text = "Our Apps" title.font = UIFont(name: title.font.familyName, size: 25) title.textAlignment = .Center headerView.addSubview(title) tableView.tableHeaderView = headerView } func back() { self.navigationController?.popViewControllerAnimated(true) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var url = "" switch indexPath.row { case 0: url = "http://urinx.github.io/app/writetyper" case 1: url = "https://github.com/Urinx/Iconista/blob/master/README.md" case 2: url = "http://pre.im/1820" case 3: url = "http://pre.im/40fb" default: break } UIApplication.sharedApplication().openURL(NSURL(string: url)!) } override func prefersStatusBarHidden() -> Bool { return true } }
7f7fe89ae8b917bf6a96c38553815371
28.819672
101
0.601979
false
false
false
false
brynbellomy/Funky
refs/heads/master
Pods/Funky/src/Functions.File.swift
mit
2
// // Functions.File.swift // Funky // // Created by bryn austin bellomy on 2015 Feb 9. // Copyright (c) 2015 bryn austin bellomy. All rights reserved. // import Foundation private let kPathSeparator: Character = "/" // // MARK: - File functions // /** Equivalent to the Unix `basename` command. Returns the last path component of `path`. */ public func basename(path:String) -> String { return (path as NSString).lastPathComponent } /** Equivalent to the Unix `extname` command. Returns the path extension of `path`. */ public func extname(path:String) -> String { return (path as NSString).pathExtension } /** Equivalent to the Unix `dirname` command. Returns the parent directory of the file or directory residing at `path`. */ public func dirname(path:String) -> String { return (path as NSString).stringByDeletingLastPathComponent } /** Returns an array of the individual components of `path`. The path separator is assumed to be `/`, as Swift currently only runs on OSX/iOS. */ public func pathComponents(path:String) -> [String] { return path.characters.split { $0 == kPathSeparator }.map(String.init) } /** Returns the relative path (`from` -> `to`). */ public func relativePath(from from:String, to:String) -> String { let fromParts = pathComponents(from) let toParts = pathComponents(to) // let sharedParts = zipseq(fromParts, toParts) // |> takeWhile(==) // |> mapTo(takeLeft) let relativeFromParts = Array(fromParts.suffix(Int.max)) let relativeToParts = Array(toParts.suffix(Int.max)) var relativeParts: [String] = [] for _ in relativeFromParts { relativeParts.append("..") } relativeParts.appendContentsOf(relativeToParts) return relativeParts |> joinWith("\(kPathSeparator)") }
6045cc76dd4a177893f2ca9facecceb1
22.556962
90
0.668458
false
false
false
false
HongliYu/firefox-ios
refs/heads/master
Client/Frontend/Widgets/ToggleButton.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit private struct UX { static let BackgroundColor = UIColor.Photon.Purple60 // The amount of pixels the toggle button will expand over the normal size. This results in the larger -> contract animation. static let ExpandDelta: CGFloat = 5 static let ShowDuration: TimeInterval = 0.4 static let HideDuration: TimeInterval = 0.2 static let BackgroundSize = CGSize(width: 32, height: 32) } class ToggleButton: UIButton { func setSelected(_ selected: Bool, animated: Bool = true) { self.isSelected = selected if animated { animateSelection(selected) } } fileprivate func updateMaskPathForSelectedState(_ selected: Bool) { let path = CGMutablePath() if selected { var rect = CGRect(size: UX.BackgroundSize) rect.center = maskShapeLayer.position path.addEllipse(in: rect) } else { path.addEllipse(in: CGRect(origin: maskShapeLayer.position, size: .zero)) } self.maskShapeLayer.path = path } fileprivate func animateSelection(_ selected: Bool) { var endFrame = CGRect(size: UX.BackgroundSize) endFrame.center = maskShapeLayer.position if selected { let animation = CAKeyframeAnimation(keyPath: "path") let startPath = CGMutablePath() startPath.addEllipse(in: CGRect(origin: maskShapeLayer.position, size: .zero)) let largerPath = CGMutablePath() let largerBounds = endFrame.insetBy(dx: -UX.ExpandDelta, dy: -UX.ExpandDelta) largerPath.addEllipse(in: largerBounds) let endPath = CGMutablePath() endPath.addEllipse(in: endFrame) animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) animation.values = [ startPath, largerPath, endPath ] animation.duration = UX.ShowDuration self.maskShapeLayer.path = endPath self.maskShapeLayer.add(animation, forKey: "grow") } else { let animation = CABasicAnimation(keyPath: "path") animation.duration = UX.HideDuration animation.fillMode = kCAFillModeForwards let fromPath = CGMutablePath() fromPath.addEllipse(in: endFrame) animation.fromValue = fromPath animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let toPath = CGMutablePath() toPath.addEllipse(in: CGRect(origin: self.maskShapeLayer.bounds.center, size: .zero)) self.maskShapeLayer.path = toPath self.maskShapeLayer.add(animation, forKey: "shrink") } } lazy fileprivate var backgroundView: UIView = { let view = UIView() view.isUserInteractionEnabled = false view.layer.addSublayer(self.backgroundLayer) return view }() lazy fileprivate var maskShapeLayer: CAShapeLayer = { let circle = CAShapeLayer() return circle }() lazy fileprivate var backgroundLayer: CALayer = { let backgroundLayer = CALayer() backgroundLayer.backgroundColor = UX.BackgroundColor.cgColor backgroundLayer.mask = self.maskShapeLayer return backgroundLayer }() override init(frame: CGRect) { super.init(frame: frame) contentMode = .redraw insertSubview(backgroundView, belowSubview: imageView!) } override func layoutSubviews() { super.layoutSubviews() let zeroFrame = CGRect(size: frame.size) backgroundView.frame = zeroFrame // Make the gradient larger than normal to allow the mask transition to show when it blows up // a little larger than the resting size backgroundLayer.bounds = backgroundView.frame.insetBy(dx: -UX.ExpandDelta, dy: -UX.ExpandDelta) maskShapeLayer.bounds = backgroundView.frame backgroundLayer.position = CGPoint(x: zeroFrame.midX, y: zeroFrame.midY) maskShapeLayer.position = CGPoint(x: zeroFrame.midX, y: zeroFrame.midY) updateMaskPathForSelectedState(isSelected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
edf44054e5d2b09df438202aad997ec4
35.488
129
0.6492
false
false
false
false
Clustox/swift-style-guidelines
refs/heads/master
ToDoList-Swift/ToDoList/ItemsList/ViewControllerDataSource.swift
mit
1
// // ViewControllerDataSource.swift // ToDoList // // Created by Saira on 8/11/16. // Copyright © 2016 Saira. All rights reserved. // import Foundation import UIKit import CoreData /// Data Source for To-Do Items List final class ViewControllerDataSource: NSObject { /// Tableview to display To-do items weak var tableView: UITableView? /// Activity Log that will be displayed in the table view var toDoItems = [ManagedToDoItem]() init(tableView: UITableView) { self.tableView = tableView super.init() self.tableView?.dataSource = self fetchItems() } /** Fetches To-Do list saved in Cored data and shows them in list */ func fetchItems() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let entityDescription = NSEntityDescription.entityForName("ToDoItem", inManagedObjectContext: managedContext) let fetchRequest = NSFetchRequest() fetchRequest.entity = entityDescription do { let results = try managedContext.executeFetchRequest(fetchRequest) if let managedResults = results as? [ManagedToDoItem] { toDoItems += managedResults } self.tableView?.reloadData() } catch let error as NSError { assertionFailure(error.localizedDescription) } } /** Inserts new item and reloads the table view after insertion - parameter item: Name of newly inserted To-Do Item */ func insertItem(name: String) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let entityDescription = NSEntityDescription.entityForName("ToDoItem", inManagedObjectContext: managedContext) let managedItem = ManagedToDoItem(entity: entityDescription!, insertIntoManagedObjectContext: managedContext) managedItem.name = name do { try managedContext.save() self.toDoItems.append(managedItem) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } dispatch_async(dispatch_get_main_queue()) { self.tableView?.reloadData() } } } } extension ViewControllerDataSource: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return toDoItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let item: ManagedToDoItem = self.toDoItems[indexPath.row] else { fatalError("No Item at indexPath, check data source.") } guard let cell = tableView.dequeueReusableCellWithIdentifier("to_do_cell") as? ToDoItemCell else { fatalError("No cell with this identifier") } cell.configure(withItem: item) return cell } }
1c9b052d4a522422905920dc7221de9d
31.457944
109
0.60812
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Gesture/CheckPlease/CheckPlease/CGPointUtils.swift
mit
1
// // CGPointUtils.swift // CheckPlease // // Created by Domenico on 02/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit func degreesToRadians(_ degrees:CGFloat) -> CGFloat { return CGFloat(M_PI * Double(degrees)/180) } func radiansToDegrees(_ radians:CGFloat) -> CGFloat { return CGFloat(180 * Double(radians)/M_PI) } func distanceBetweenPoints(_ first:CGPoint, second:CGPoint) -> CGFloat { let deltaX = second.x - first.x let deltaY = second.y - first.y return sqrt(deltaX * deltaX + deltaY * deltaY) } func angleBetweenPoint(_ first:CGPoint, second:CGPoint) -> CGFloat { let height = fabs(second.y - first.y) let width = fabs(second.x - first.x) let radians = atan(height/width) return radiansToDegrees(radians) } func angleBetweenLines(_ line1Start:CGPoint, line1End:CGPoint, line2Start:CGPoint, line2End:CGPoint) -> CGFloat { let a = line1End.x - line1Start.x; let b = line1End.y - line1Start.y; let c = line2End.x - line2Start.x; let d = line2End.y - line2Start.y; let firstPart = (a*c) + (b*d) let secondPart = sqrt(a*a + b*b) let thirdPart = sqrt(c*c + d*d) let radians = acos((firstPart) / ((secondPart) * (thirdPart))); return radiansToDegrees(radians); }
12b652cd72b5339e2dc865eebf4c3510
28.767442
113
0.670313
false
false
false
false
Norod/Filterpedia
refs/heads/swift-3
Filterpedia/customFilters/EightBit.swift
gpl-3.0
1
// // EightBit.swift // Filterpedia // // Created by Simon Gladman on 07/02/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage class EightBit: CIFilter { var inputImage: CIImage? var inputPaletteIndex: CGFloat = 4 var inputScale: CGFloat = 8 override func setDefaults() { inputPaletteIndex = 4 inputScale = 8 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Eight Bit", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputPaletteIndex": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 4, kCIAttributeDescription: "0: Spectrum (Dim). 1: Spectrum (Bright). 2: VIC-20. 3: C-64. 4: Apple II ", kCIAttributeDisplayName: "Palette Index", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 4, kCIAttributeType: kCIAttributeTypeInteger], "inputScale": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 8, kCIAttributeDisplayName: "Scale", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let paletteIndex = max(min(EightBit.palettes.count - 1, Int(inputPaletteIndex)), 0) let palette = EightBit.palettes[paletteIndex] var kernelString = "kernel vec4 thresholdFilter(__sample image)" kernelString += "{ \n" kernelString += " vec2 uv = samplerCoord(image); \n" kernelString += " float dist = distance(image.rgb, \(palette.first!.toVectorString())); \n" kernelString += " vec3 returnColor = \(palette.first!.toVectorString());\n " for paletteColor in palette where paletteColor != palette.first! { kernelString += "if (distance(image.rgb, \(paletteColor.toVectorString())) < dist) \n" kernelString += "{ \n" kernelString += " dist = distance(image.rgb, \(paletteColor.toVectorString())); \n" kernelString += " returnColor = \(paletteColor.toVectorString()); \n" kernelString += "} \n" } kernelString += " return vec4(returnColor, 1.0) ; \n" kernelString += "} \n" guard let kernel = CIColorKernel(string: kernelString) else { return nil } let extent = inputImage.extent let final = kernel.apply(withExtent: extent, arguments: [inputImage.applyingFilter("CIPixellate", withInputParameters: [kCIInputScaleKey: inputScale])]) return final } // MARK: Palettes // ZX Spectrum Dim static let dimSpectrumColors = [ RGB(r: 0x00, g: 0x00, b: 0x00), RGB(r: 0x00, g: 0x00, b: 0xCD), RGB(r: 0xCD, g: 0x00, b: 0x00), RGB(r: 0xCD, g: 0x00, b: 0xCD), RGB(r: 0x00, g: 0xCD, b: 0x00), RGB(r: 0x00, g: 0xCD, b: 0xCD), RGB(r: 0xCD, g: 0xCD, b: 0x00), RGB(r: 0xCD, g: 0xCD, b: 0xCD)] // ZX Spectrum Bright static let brightSpectrumColors = [ RGB(r: 0x00, g: 0x00, b: 0x00), RGB(r: 0x00, g: 0x00, b: 0xFF), RGB(r: 0xFF, g: 0x00, b: 0x00), RGB(r: 0xFF, g: 0x00, b: 0xFF), RGB(r: 0x00, g: 0xFF, b: 0x00), RGB(r: 0x00, g: 0xFF, b: 0xFF), RGB(r: 0xFF, g: 0xFF, b: 0x00), RGB(r: 0xFF, g: 0xFF, b: 0xFF)] // VIC-20 static let vic20Colors = [ RGB(r: 0, g: 0, b: 0), RGB(r: 255, g: 255, b: 255), RGB(r: 141, g: 62, b: 55), RGB(r: 114, g: 193, b: 200), RGB(r: 128, g: 52, b: 139), RGB(r: 85, g: 160, b: 73), RGB(r: 64, g: 49, b: 141), RGB(r: 170, g: 185, b: 93), RGB(r: 139, g: 84, b: 41), RGB(r: 213, g: 159, b: 116), RGB(r: 184, g: 105, b: 98), RGB(r: 135, g: 214, b: 221), RGB(r: 170, g: 95, b: 182), RGB(r: 148, g: 224, b: 137), RGB(r: 128, g: 113, b: 204), RGB(r: 191, g: 206, b: 114) ] // C-64 static let c64Colors = [ RGB(r: 0, g: 0, b: 0), RGB(r: 255, g: 255, b: 255), RGB(r: 136, g: 57, b: 50), RGB(r: 103, g: 182, b: 189), RGB(r: 139, g: 63, b: 150), RGB(r: 85, g: 160, b: 73), RGB(r: 64, g: 49, b: 141), RGB(r: 191, g: 206, b: 114), RGB(r: 139, g: 84, b: 41), RGB(r: 87, g: 66, b: 0), RGB(r: 184, g: 105, b: 98), RGB(r: 80, g: 80, b: 80), RGB(r: 120, g: 120, b: 120), RGB(r: 148, g: 224, b: 137), RGB(r: 120, g: 105, b: 196), RGB(r: 159, g: 159, b: 159) ] // Apple II static let appleIIColors = [ RGB(r: 0, g: 0, b: 0), RGB(r: 114, g: 38, b: 64), RGB(r: 64, g: 51, b: 127), RGB(r: 228, g: 52, b: 254), RGB(r: 14, g: 89, b: 64), RGB(r: 128, g: 128, b: 128), RGB(r: 27, g: 154, b: 254), RGB(r: 191, g: 179, b: 255), RGB(r: 64, g: 76, b: 0), RGB(r: 228, g: 101, b: 1), RGB(r: 128, g: 128, b: 128), RGB(r: 241, g: 166, b: 191), RGB(r: 27, g: 203, b: 1), RGB(r: 191, g: 204, b: 128), RGB(r: 141, g: 217, b: 191), RGB(r: 255, g: 255, b: 255) ] static let palettes = [dimSpectrumColors, brightSpectrumColors, vic20Colors, c64Colors, appleIIColors] } struct RGB: Equatable { let r:UInt8 let g:UInt8 let b:UInt8 func toVectorString() -> String { return "vec3(\(Double(self.r) / 255), \(Double(self.g) / 255), \(Double(self.b) / 255))" } } func ==(lhs: RGB, rhs: RGB) -> Bool { return lhs.toVectorString() == rhs.toVectorString() }
2004c1e706ab4c8cd649085526f1b6ba
31.37156
119
0.525719
false
false
false
false
jeffreybergier/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/NotificationCenterDetachmentRule.swift
mit
1
// // NotificationCenterDetachmentRule.swift // SwiftLint // // Created by Marcelo Fabri on 01/15/17. // Copyright © 2017 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct NotificationCenterDetachmentRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "notification_center_detachment", name: "Notification Center Detachment", description: "An object should only remove itself as an observer in `deinit`.", nonTriggeringExamples: NotificationCenterDetachmentRuleExamples.swift3NonTriggeringExamples, triggeringExamples: NotificationCenterDetachmentRuleExamples.swift3TriggeringExamples ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .class else { return [] } return violationOffsets(file: file, dictionary: dictionary).map { offset in StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: offset)) } } func violationOffsets(file: File, dictionary: [String: SourceKitRepresentable]) -> [Int] { return dictionary.substructure.flatMap { subDict -> [Int] in guard let kindString = subDict.kind, let kind = SwiftExpressionKind(rawValue: kindString) else { return [] } // complete detachment is allowed on `deinit` if kind == .other, SwiftDeclarationKind(rawValue: kindString) == .functionMethodInstance, subDict.name == "deinit" { return [] } if kind == .call, subDict.name == methodName, parameterIsSelf(dictionary: subDict, file: file), let offset = subDict.offset { return [offset] } return violationOffsets(file: file, dictionary: subDict) } } private var methodName: String = { switch SwiftVersion.current { case .two, .twoPointThree: return "NSNotificationCenter.defaultCenter.removeObserver" case .three: return "NotificationCenter.default.removeObserver" } }() private func parameterIsSelf(dictionary: [String: SourceKitRepresentable], file: File) -> Bool { guard let bodyOffset = dictionary.bodyOffset, let bodyLength = dictionary.bodyLength else { return false } let range = NSRange(location: bodyOffset, length: bodyLength) let tokens = file.syntaxMap.tokens(inByteRange: range) let types = tokens.flatMap { SyntaxKind(rawValue: $0.type) } guard types == [.keyword], let token = tokens.first else { return false } let body = file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length) return body == "self" } }
b881a8e0e675612c08a7ed96fff55a6f
35.931818
107
0.627385
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/Parse/invalid.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift func foo(_ a: Int) { // expected-error @+1 {{invalid character in source file}} {{8-9= }} foo(<\a\>) // expected-error {{invalid character in source file}} {{10-11= }} // expected-error @-1 {{'<' is not a prefix unary operator}} // expected-error @-2 {{'>' is not a postfix unary operator}} } // rdar://15946844 func test1(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }} func test2(inout let x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }} func test3(f : (inout _ x : Int) -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} func test3() { undeclared_func( // expected-error {{use of unresolved identifier 'undeclared_func'}} } // expected-error {{expected expression in list of expressions}} func runAction() {} // expected-note {{did you mean 'runAction'?}} // rdar://16601779 func foo() { runAction(SKAction.sequence() // expected-error {{use of unresolved identifier 'SKAction'}} expected-error {{expected ',' separator}} {{32-32=,}} skview! // expected-error @-1 {{use of unresolved identifier 'skview'}} } super.init() // expected-error {{'super' cannot be used outside of class members}} switch state { // expected-error {{use of unresolved identifier 'state'}} let duration : Int = 0 // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} case 1: break } func testNotCoveredCase(x: Int) { switch x { let y = "foo" // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} switch y { case "bar": blah blah // ignored } case "baz": // expected-error {{expression pattern of type 'String' cannot match values of type 'Int'}} break case 1: break default: break } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block; do you want to add a default case?}} #if true // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} case 1: break case "foobar": // ignored break default: break #endif } } // rdar://18926814 func test4() { let abc = 123 _ = " >> \( abc } ) << " // expected-error {{expected ',' separator}} {{18-18=,}} expected-error {{expected expression in list of expressions}} expected-error {{extra tokens after interpolated string expression}} } // rdar://problem/18507467 func d(_ b: String -> <T>() -> T) {} // expected-error {{expected type for function result}} // <rdar://problem/22143680> QoI: terrible diagnostic when trying to form a generic protocol protocol Animal<Food> { // expected-error {{protocols do not allow generic parameters; use associated types instead}} func feed(_ food: Food) // expected-error {{use of undeclared type 'Food'}} } // SR-573 - Crash with invalid parameter declaration class Starfish {} struct Salmon {} func f573(s Starfish, // expected-error {{parameter requires an explicit type}} _ ss: Salmon) -> [Int] {} func g573() { f573(Starfish(), Salmon()) } func SR698(_ a: Int, b: Int) {} SR698(1, b: 2,) // expected-error {{unexpected ',' separator}} // SR-979 - Two inout crash compiler func SR979a(a : inout inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} func SR979b(inout inout b: Int) {} // expected-error {{inout' before a parameter name is not allowed, place it before the parameter type instead}} {{13-18=}} {{28-28=inout }} // expected-error@-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{19-25=}} func SR979c(let a: inout Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}} func SR979d(let let a: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}} // expected-error @-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-21=}} func SR979e(inout x: inout String) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}} func SR979f(var inout x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} // expected-error @-1 {{parameters may not have the 'var' specifier}} {{13-16=}}{{3-3=var x = x\n }} x += 10 } func SR979g(inout i: inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}} func SR979h(let inout x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} // expected-error @-1 {{'let' as a parameter attribute is not allowed}} class VarTester { init(var a: Int, var b: Int) {} // expected-error {{parameters may not have the 'var' specifier}} {{8-11=}} {{33-33= var a = a }} // expected-error @-1 {{parameters may not have the 'var' specifier}} {{20-24=}} {{33-33= var b = b }} func x(var b: Int) { //expected-error {{parameters may not have the 'var' specifier}} {{12-15=}} {{9-9=var b = b\n }} b += 10 } } func repeat() {} // expected-error @-1 {{keyword 'repeat' cannot be used as an identifier here}} // expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{6-12=`repeat`}} let for = 2 // expected-error @-1 {{keyword 'for' cannot be used as an identifier here}} // expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{5-8=`for`}} func dog cow() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-13=dogcow}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-13=dogCow}} func cat Mouse() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-15=catMouse}} func friend ship<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-17=friendship}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-17=friendShip}} func were wolf() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-5=werewolf}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-5=wereWolf}} func hammer leavings<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-9=hammerleavings}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-9=hammerLeavings}} prefix operator % prefix func %<T>(x: T) -> T { return x } // No error expected - the < is considered an identifier but is peeled off by the parser. struct Weak<T: class> { // expected-error {{'class' constraint can only appear on protocol declarations}} // expected-note@-1 {{did you mean to constrain 'T' with the 'AnyObject' protocol?}} {{16-21=AnyObject}} weak var value: T // expected-error {{'weak' may not be applied to non-class-bound 'T'; consider adding a protocol conformance that has a class bound}} } let x: () = () !() // expected-error {{missing argument for parameter #1 in call}} !(()) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}} !(x) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}} !x // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}}
abd4b1b47b93471bfae20128730a6d2d
52.603896
216
0.671351
false
false
false
false
vzhikserg/GoHappy
refs/heads/master
src/app/ios/KooKoo/KooKoo/TrackingViewController.swift
bsd-2-clause
1
// // TrackingViewController.swift // KooKoo // // Created by Channa Karunathilake on 6/25/16. // Copyright © 2016 KooKoo. All rights reserved. // import UIKit import SwiftLocation import ZAlertView class TrackingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var disabledButtons: [UIButton]! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var passengersCountLabel: UILabel! @IBOutlet weak var waveView: UIView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var minusButton: UIButton! @IBOutlet weak var codeButton: UIButton! var passengerCount = 0; var locationRequest: LocationRequest? var zones = [String]() var passengerCountForZone = [Int]() var lastZone: String? //Demo zones for the presentation private var tempZoneIndex = 0 private var simulatedZones = ["Klagenfurt", "Krumpendorf", "Pörtschach", "Velden", "Villach", "Spittal a.d. Drau"] private var viewHasAppeared = false override func viewDidLoad() { super.viewDidLoad() passengersCountLabel.alpha = 0 startSimulatedTracking() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if viewHasAppeared { return } stopButton.alpha = 0 tableView.alpha = 0 addButton.alpha = 0 codeButton.alpha = 0 minusButton.alpha = 0 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if viewHasAppeared { return } viewHasAppeared = true stopButton.popIn { (finished) in self.animateWave() UIView.animateWithDuration(0.2, animations: { self.tableView.alpha = 1 }) } addButton.alpha = 0 addButton.transform = CGAffineTransformIdentity codeButton.alpha = 0 codeButton.transform = CGAffineTransformIdentity UIView.animateWithDuration(0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { let t = CGFloat(0 * M_PI / 180.0) self.codeButton.alpha = 0.75 self.codeButton.transform = CGAffineTransformMakeTranslation(100 * cos(t), -100 * sin(t)) }, completion: nil) UIView.animateWithDuration(0.8, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { let t = CGFloat(-45 * M_PI / 180.0) self.addButton.alpha = 0.75 self.addButton.transform = CGAffineTransformMakeTranslation(100 * cos(t), -100 * sin(t)) }, completion: nil) var delay = 0.2 var startAngle = 180.0 for button in disabledButtons { UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { let t = CGFloat(startAngle * M_PI / 180.0) button.alpha = 0.6 button.transform = CGAffineTransformMakeTranslation(100 * cos(t), -100 * sin(t)) }, completion: nil) startAngle -= 30 delay += 0.05 } } func animateWave() { waveView.alpha = 0.95 waveView.transform = CGAffineTransformIdentity UIView.animateWithDuration(1.5, delay: 0, options: [], animations: { self.waveView.transform = CGAffineTransformMakeScale(1.5, 1.5) self.waveView.alpha = 0 }) { (finished) in self.animateWave() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() applyStyles() } func applyStyles() { stopButton.layer.cornerRadius = stopButton.bounds.width / 2 waveView.layer.cornerRadius = waveView.bounds.width / 2 passengersCountLabel.layer.cornerRadius = passengersCountLabel.bounds.width / 2 addButton.layer.cornerRadius = addButton.bounds.width / 2 addButton.layer.masksToBounds = true codeButton.layer.cornerRadius = codeButton.bounds.width / 2 codeButton.layer.masksToBounds = true minusButton.layer.cornerRadius = minusButton.bounds.width / 2 minusButton.layer.masksToBounds = true passengersCountLabel.layer.masksToBounds = true for button in disabledButtons { button.layer.cornerRadius = button.bounds.width / 2 button.layer.masksToBounds = true } } @IBAction func didTapStopButton(sender: AnyObject) { stopTracking() } @IBAction func didTapCodeButton(sender: AnyObject) { let transition: CATransition = CATransition() transition.duration = 0.15 transition.type = kCATransitionFade navigationController?.view.layer.addAnimation(transition, forKey: nil) performSegueWithIdentifier("code", sender: self) } @IBAction func didTapAddButton(sender: AnyObject) { passengerCount += 1 passengersCountLabel.text = "+\(passengerCount)" passengersCountLabel.popIn(nil) if passengerCount == 1 { minusButton.alpha = 0 minusButton.transform = CGAffineTransformIdentity UIView.animateWithDuration(0.8, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { let t = CGFloat(-67 * M_PI / 180.0) self.minusButton.alpha = 0.75 self.minusButton.transform = CGAffineTransformMakeTranslation(100 * cos(t), -100 * sin(t)) }, completion: nil) } } @IBAction func didTapMinusButton(sender: AnyObject) { passengerCount -= 1 passengersCountLabel.text = "+\(passengerCount)" if passengerCount == 0 { UIView.animateWithDuration(0.2, animations: { self.passengersCountLabel.alpha = 0 self.passengersCountLabel.transform = CGAffineTransformMakeScale(0.5, 0.5) self.minusButton.alpha = 0 self.minusButton.transform = CGAffineTransformIdentity }) } else { passengersCountLabel.popIn(nil) } } func startTracking() { LocationManager.shared.allowsBackgroundEvents = true //TODO: change continouous to distance locationRequest = LocationManager.shared.observeLocations(.Block, frequency: .Continuous, onSuccess: { (location) in APIClient.shared.sendLocation(location, completion: { (response, error) in guard error == nil else { return } guard let dict = response as? [String: AnyObject] else { return } if let tempZones = dict["Zones"] as? [[String: AnyObject]] { if self.tempZoneIndex < tempZones.count { let currentZone = tempZones[self.tempZoneIndex]["Name"] as! String if self.lastZone != currentZone { self.zones.insert(currentZone, atIndex: 0) self.passengerCountForZone.insert(self.passengerCount, atIndex: 0) self.lastZone = currentZone self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic) } } else { } } }) }) { (error) in print(error) } } func startSimulatedTracking() { guard simulatedZones.count > 0 else { return } let z = simulatedZones.removeFirst() zones.insert(z, atIndex: 0) passengerCountForZone.insert(passengerCount, atIndex: 0) tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic) self.performSelector(#selector(startSimulatedTracking), withObject: nil, afterDelay: NSTimeInterval(5 * zones.count)) } func stopTracking() { LocationManager.shared.allowsBackgroundEvents = false locationRequest?.stop() let transition: CATransition = CATransition() transition.duration = 0.25 transition.type = kCATransitionFade navigationController?.view.layer.addAnimation(transition, forKey: nil) navigationController?.popViewControllerAnimated(false) } // MARK: - func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return zones.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(String(ZoneCell), forIndexPath: indexPath) if let zoneCell = cell as? ZoneCell { zoneCell.zoneNameLabel.text = zones[indexPath.row] let coef = 1 / CGFloat(indexPath.row + 1) let scaleCoef = 1 - (CGFloat(indexPath.row) / 5) zoneCell.zoneNameLabel.alpha = coef zoneCell.bulletView.transform = CGAffineTransformMakeScale(scaleCoef, scaleCoef) zoneCell.zoneLabel.text = (indexPath.row == 0) ? "Zone" : "" zoneCell.topLine.hidden = (indexPath.row == 0) zoneCell.bottomLine.hidden = (indexPath.row == zones.count - 1) zoneCell.countLabel.hidden = (passengerCountForZone[indexPath.row] == 0) zoneCell.countLabel.text = "+\(passengerCountForZone[indexPath.row])" } return cell } }
5e53e2550716ebf7e1c2b9caf9d8a7cd
32.439024
130
0.551422
false
false
false
false
woolsweater/pdxcocoaheads.com
refs/heads/develop
Tests/App/MeetupEventTests.swift
mit
1
import XCTest @testable import App import Vapor import Mustache // Equality for `MeetupEvent` so that arrays of them can be tested func ==(lhs: MeetupEvent, rhs: MeetupEvent) -> Bool { return (lhs.name == rhs.name && lhs.time == rhs.time && lhs.utcOffset == rhs.utcOffset && lhs.rsvpCount == rhs.rsvpCount && lhs.link == rhs.link) } extension MeetupEvent: Equatable {} /** Test unpacking of JSON into arrays of `MeetupEvent`s */ class UnpackEventTests: XCTestCase { let sampleObject: [String : JSONRepresentable] = ["name" : "Discussion", "time" : 1234, "utc_offset" : 5678, "yes_rsvp_count" : 9, "link" : "http://example.com"] let event = MeetupEvent(name: "Discussion", time: 1234, utcOffset: 5678, rsvpCount: 9, link: "http://example.com") // Non-array JSON -> no results func testNoUnpackOfNonarray() { var object = self.sampleObject object.removeAll() let json = JSON(object) XCTAssertThrowsError(try unpackMeetupEvents(fromJSON: json)) } // Empty input -> empty output func testEmptyArrayUnpacksEmpty() { let json = JSON([]) let unpacked = try! unpackMeetupEvents(fromJSON: json) XCTAssertTrue(unpacked.isEmpty) } // Single malformed input -> empty output func testMissingDataUnpacksEmpty() { var object = self.sampleObject object.removeValue(forKey: "name") let json = JSON([JSON(object)]) let unpacked = try! unpackMeetupEvents(fromJSON: json) XCTAssertTrue(unpacked.isEmpty) } // Two good entries, one bad -> skip the bad func testSomeGoodData() { var badObject = self.sampleObject badObject.removeValue(forKey: "name") let json = JSON([JSON(self.sampleObject), JSON(badObject), JSON(self.sampleObject)]) let expected = [self.event, self.event] let unpacked = try! unpackMeetupEvents(fromJSON: json) XCTAssertEqual(unpacked, expected) } // Good data successfully unpacks func testGoodData() { let json = JSON([JSON(self.sampleObject), JSON(self.sampleObject)]) let expected = [self.event, self.event] let unpacked = try! unpackMeetupEvents(fromJSON: json) XCTAssertEqual(unpacked, expected) } } /** Ensure `mustacheBox(forKey:)` returns expected values. */ class EventMustacheBoxTests: XCTestCase { let event = MeetupEvent(name: "Discussion", time: 1234, utcOffset: 5678, rsvpCount: 9, link: "http://example.com") func testMustacheBoxName() { let key = "name" let expected = "Discussion" let boxValue = event.mustacheBox(forKey: key).value XCTAssertTrue((boxValue as? String) == expected) } func testMustacheBoxTime() { let key = "time" let expected = 1234 let boxValue = event.mustacheBox(forKey: key).value XCTAssertTrue((boxValue as? Int) == expected) } func testMustacheBoxUtcOffset() { let key = "utcOffset" let expected = 5678 let boxValue = event.mustacheBox(forKey: key).value XCTAssertTrue((boxValue as? Int) == expected) } func testMustacheBoxRsvpCount() { let key = "rsvpCount" let expected = 9 let boxValue = event.mustacheBox(forKey: key).value XCTAssertTrue((boxValue as? Int) == expected) } func testMustacheBoxLink() { let key = "link" let expected = "http://example.com" let boxValue = event.mustacheBox(forKey: key).value XCTAssertTrue((boxValue as? String) == expected) } }
7988f96e30874bef94450f739eb30377
28.4375
76
0.545412
false
true
false
false
manju3157/TestingSDK
refs/heads/master
Example/TestingSDK/ViewController.swift
mit
1
// // ViewController.swift // TestingSDK // // Created by [email protected] on 08/29/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import OPGFramework class ViewController: UIViewController { var surveyListArray : NSArray! // Array of OPGSurvey Class from Previous ViewController var surveyObj : OPGSurvey! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let sdk = OPGSDK() var obj: OPGAuthenticate do { obj = try sdk.authenticate("", password: "") print(obj); } catch{ print("Authentication Failed") /* @"Error Occured. Contact Support!" */ } // let bundlePath = Bundle.main.path(forResource: "OPGResourceBundle", ofType: "bundle") // print("Bundle path: \(String(describing: bundlePath))") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if(segue.identifier == "embedTakeSurvey") // { // // Get TakeSurveyViewController view // let viewController : TakeSurveyViewController = segue.destination as! TakeSurveyViewController // viewController.survey=self.surveyObj // } // // } }
daeba6cc6d05673cb86bd547bd6f5993
27
114
0.615434
false
false
false
false
daniel-beard/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/ClosingBraceRule.swift
mit
1
// // ClosingBraceRule.swift // SwiftLint // // Created by Yasuhiro Inami on 2015-12-19. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import Foundation import SourceKittenFramework private let whitespaceAndNewlineCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() extension File { private func violatingClosingBraceRanges() -> [NSRange] { return matchPattern( "(\\}\\s+\\))", excludingSyntaxKinds: SyntaxKind.commentAndStringKinds() ) } } public struct ClosingBraceRule: CorrectableRule, ConfigProviderRule { public var config = SeverityConfig(.Warning) public init() {} public static let description = RuleDescription( identifier: "closing_brace", name: "Closing Brace Spacing", description: "Closing brace with closing parenthesis " + "should not have any whitespaces in the middle.", nonTriggeringExamples: [ "[].map({ })" ], triggeringExamples: [ "[].map({ ↓} )" ], corrections: [ "[].map({ } )\n": "[].map({ })\n" ] ) public func validateFile(file: File) -> [StyleViolation] { return file.violatingClosingBraceRanges().map { StyleViolation(ruleDescription: self.dynamicType.description, severity: config.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correctFile(file: File) -> [Correction] { let violatingRanges = file.ruleEnabledViolatingRanges( file.violatingClosingBraceRanges(), forRule: self ) return writeToFile(file, violatingRanges: violatingRanges) } private func writeToFile(file: File, violatingRanges: [NSRange]) -> [Correction] { var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reverse() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .stringByReplacingCharactersInRange(indexRange, withString: "})") adjustedLocations.insert(violatingRange.location, atIndex: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: self.dynamicType.description, location: Location(file: file, characterOffset: $0)) } } }
e126f209054f6cb429bef434f24b02cc
31.3375
96
0.618477
false
false
false
false
honghaoz/Swift-Google-Maps-API
refs/heads/master
GooglePlaces/GooglePlacesTests/PlaceAutocompleteTests.swift
mit
1
// // PlaceAutocompleteTests.swift // GooglePlacesTests // // Created by Honghao Zhang on 2016-02-12. // Copyright © 2016 Honghao Zhang. All rights reserved. // import XCTest @testable import GooglePlaces class PlaceAutocompleteTests: XCTestCase { typealias LocationCoordinate2D = GoogleMapsService.LocationCoordinate2D override func setUp() { super.setUp() GooglePlaces.provide(apiKey: "AIzaSyDftpY3fi6x_TL4rntL8pgZb-A8mf6D0Ss") } override func tearDown() { super.tearDown() } func testAPIIsInvalid() { let expectation = self.expectation(description: "results") GooglePlaces.provide(apiKey: "fake_key") GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in XCTAssertNotNil(error) XCTAssertNotNil(response) XCTAssertNotNil(response?.errorMessage) XCTAssertEqual(response?.status, GooglePlaces.StatusCode.requestDenied) expectation.fulfill() } waitForExpectations(timeout: 5.0, handler: nil) } func testAPIIsValid() { let expectation = self.expectation(description: "results") GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in XCTAssertNil(error) XCTAssertNotNil(response) XCTAssertEqual(response?.status, GooglePlaces.StatusCode.ok) expectation.fulfill() } waitForExpectations(timeout: 5.0, handler: nil) } func testResultsReturned() { let expectation = self.expectation(description: "It has at least one result returned for `pub`") GooglePlaces.placeAutocomplete(forInput: "pub") { (response, error) -> Void in XCTAssertNil(error) XCTAssertNotNil(response) XCTAssertEqual(response!.status, GooglePlaces.StatusCode.ok) XCTAssertTrue(response!.predictions.count > 0) expectation.fulfill() } waitForExpectations(timeout: 5.0, handler: nil) } func testResultsMatchedSubstrings() { let expectation = self.expectation(description: "It has at least one result returned for `pub`") let query = "Pub" GooglePlaces.placeAutocomplete(forInput: query, locationCoordinate: LocationCoordinate2D(latitude: 43.4697354, longitude: -80.5397377), radius: 10000) { (response, error) -> Void in XCTAssertNil(error) XCTAssertNotNil(response) XCTAssertEqual(response!.status, GooglePlaces.StatusCode.ok) XCTAssertTrue(response!.predictions.count > 0) guard let predictions = response?.predictions else { XCTAssert(false, "prediction is nil") return } for prediction in predictions { XCTAssertEqual(prediction.matchedSubstring[0].length, query.count) guard let description = prediction.description, let length = prediction.matchedSubstring[0].length, let offset = prediction.matchedSubstring[0].offset else { XCTAssert(false, "length/offset is nil") return } let start = description.index(description.startIndex, offsetBy: offset) let end = description.index(description.startIndex, offsetBy: offset + length) let substring = description.substring(with: start ..< end) XCTAssertEqual(substring.lowercased(), query.lowercased()) } expectation.fulfill() } waitForExpectations(timeout: 5.0, handler: nil) } }
b53cad26967ad7997c112671a37c7ad5
35.653846
189
0.613326
false
true
false
false
I-SYST/EHAL
refs/heads/master
OSX/exemples/SensorTagDemo/SensorTagDemo/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // SensorTagDemo // // Created by Nguyen Hoan Hoang on 2017-10-22. // Copyright © 2017 I-SYST inc. All rights reserved. // import Cocoa import AppKit//QuartzCore import CoreBluetooth import simd class ViewController: NSViewController, CBCentralManagerDelegate { var bleCentral : CBCentralManager! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. bleCentral = CBCentralManager(delegate: self, queue: DispatchQueue.main) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } //@IBOutlet weak var graphView : GraphView! @IBOutlet weak var tempLabel: NSTextField! @IBOutlet weak var humiLabel : NSTextField! @IBOutlet weak var pressLabel : NSTextField! @IBOutlet weak var rssiLabel : NSTextField! @IBOutlet weak var aqiLabel : NSTextField! // MARK: BLE Central func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData : [String : Any], rssi RSSI: NSNumber) { // print("PERIPHERAL NAME: \(String(describing: peripheral.name))\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n") //print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n") //print("IDENTIFIER: \(peripheral.identifier)\n") if advertisementData[CBAdvertisementDataManufacturerDataKey] == nil { return } // print("PERIPHERAL NAME: \(String(describing: peripheral.name))\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n") //sensorData.text = sensorData.text + "FOUND PERIPHERALS: \(peripheral) AdvertisementData: \(advertisementData) RSSI: \(RSSI)\n" var manId = UInt16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&manId, range: NSMakeRange(0, 2)) if manId != 0x177 { return } // print("PERIPHERAL NAME: \(String(describing: peripheral.name))\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n") //print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n") var type = UInt8(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&type, range: NSMakeRange(2, 1)) switch (type) { case 1: // TPH sensor data var press = Int32(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&press, range: NSMakeRange(3, 4)) pressLabel.stringValue = String(format:"%.3f KPa", Float(press) / 1000.0) var temp = Int16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&temp, range: NSMakeRange(7, 2)) tempLabel.stringValue = String(format:"%.2f C", Float(temp) / 100.0) var humi = UInt16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&humi, range: NSMakeRange(9, 2)) humiLabel.stringValue = String(format:"%d%%", humi / 100) break case 2: // Gas sensor data var gasResistance = UInt32(0) var gasAQI = UInt16(0) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&gasResistance, range: NSMakeRange(3, 4)) (advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&gasAQI, range: NSMakeRange(7, 2)) aqiLabel.stringValue = String(format:"%d", gasAQI) print("Gas resistance value : \(gasResistance) AQI \(gasAQI)") break case 10: print("Motion detected") break default: break } rssiLabel.stringValue = String( describing: RSSI) //graphView.add(double3(Double(temp) / 100.0, Double(press) / 100000.0, Double(humi) / 100.0)) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { peripheral.discoverServices(nil) print("Connected to peripheral") } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { print("disconnected from peripheral") } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { } func scanPeripheral(_ sender: CBCentralManager) { print("Scan for peripherals") sender.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true]) } @objc func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOff: print("CoreBluetooth BLE hardware is powered off") //self.sensorData.text = "CoreBluetooth BLE hardware is powered off\n" break case .poweredOn: print("CoreBluetooth BLE hardware is powered on and ready") //self.sensorData.text = "CoreBluetooth BLE hardware is powered on and ready\n" // We can now call scanForBeacons //let lastPeripherals = central.retrieveConnectedPeripherals(withServices: nil) //if lastPeripherals.count > 0 { // let device = lastPeripherals.last as CBPeripheral; //connectingPeripheral = device; //centralManager.connectPeripheral(connectingPeripheral, options: nil) //} scanPeripheral(central) //bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil) break case .resetting: print("CoreBluetooth BLE hardware is resetting") //self.sensorData.text = "CoreBluetooth BLE hardware is resetting\n" break case .unauthorized: print("CoreBluetooth BLE state is unauthorized") //self.sensorData.text = "CoreBluetooth BLE state is unauthorized\n" break case .unknown: print("CoreBluetooth BLE state is unknown") //self.sensorData.text = "CoreBluetooth BLE state is unknown\n" break case .unsupported: print("CoreBluetooth BLE hardware is unsupported on this platform") //self.sensorData.text = "CoreBluetooth BLE hardware is unsupported on this platform\n" break default: break } } }
c7a337a6e64d2fd02f9f2f90b36c8503
39.182353
136
0.620553
false
false
false
false
fenggmy/ofo
refs/heads/master
ofo/ofo/Controller/DrawerViewController.swift
mit
1
// // ViewController.swift // ofo // // Created by 马异峰 on 2017/10/6. // Copyright © 2017年 Yifeng. All rights reserved. // import UIKit import FTIndicator import SWRevealViewController class DrawerViewController: UIViewController,MAMapViewDelegate,AMapSearchDelegate,AMapNaviWalkManagerDelegate { var mapView : MAMapView! var search : AMapSearchAPI! var pin : MyPinAnnotation! var pinView : MAAnnotationView! var nearBySearch = true var start,end : CLLocationCoordinate2D! var walkManager : AMapNaviWalkManager! @IBOutlet weak var panelView: UIView! @IBAction func locationBtnTap(_ sender: UIButton) { nearBySearch = true searchBikeNearBy() } //:搜索周边小黄车 func searchBikeNearBy() { searchCustomerLocation(mapView.userLocation.coordinate) } func searchCustomerLocation(_ center:CLLocationCoordinate2D) { let request = AMapPOIAroundSearchRequest() request.location = AMapGeoPoint.location(withLatitude: CGFloat(center.latitude), longitude: CGFloat(center.longitude)) request.keywords = "餐厅" request.radius = 500 request.requireExtension = true search.aMapPOIAroundSearch(request) } override func viewDidLoad() { super.viewDidLoad() // let x = view.bounds.height // print(x) mapView = MAMapView(frame: view.bounds) view.addSubview(mapView) view.addSubview(panelView) mapView.delegate = self mapView.zoomLevel = 17 mapView.showsUserLocation = true mapView.userTrackingMode = .follow search = AMapSearchAPI() search.delegate = self walkManager = AMapNaviWalkManager() walkManager.delegate = self self.navigationItem.titleView = UIImageView(image: #imageLiteral(resourceName: "Login_Logo")) self.navigationItem.leftBarButtonItem?.image = #imageLiteral(resourceName: "user_center_icon").withRenderingMode(.alwaysOriginal) self.navigationItem.rightBarButtonItem?.image = #imageLiteral(resourceName: "gift_icon").withRenderingMode(.alwaysOriginal) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) if let revealVC = revealViewController() { revealVC.rearViewRevealWidth = self.view.bounds.width * 0.8 navigationItem.leftBarButtonItem?.target = revealVC navigationItem.leftBarButtonItem?.action = #selector(SWRevealViewController.revealToggle(_:)) view.addGestureRecognizer(revealVC.panGestureRecognizer()) view.addGestureRecognizer(revealVC.tapGestureRecognizer()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:大头针动画 func pinAnimation() { //:坠落动画,y轴加位移 let endFrame = pinView.frame pinView.frame = endFrame.offsetBy(dx: 0, dy: -15) /* usingSpringWithDamping:震动幅度 initialSpringVelocity:初始速度 animations:具体动画 completion:完成之后做什么 */ UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { self.pinView.frame = endFrame }, completion: nil) } //MARK:Map View Delegate /// 将获取到的导航路线转换成地图上绘制折线所需要的元素 /// /// - Parameters: /// - mapView: mapView /// - overlay: overlay /// - Returns: 返回绘制好的折线 func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! { if overlay is MAPolyline { //:一旦规划路线后,大头针就不在屏幕中心了 pin.isLockedToScreen = false //:路线规划后,将当前视图移到该路线上,只对该路线有兴趣 mapView.visibleMapRect = overlay.boundingMapRect let renderer = MAPolylineRenderer(overlay: overlay) renderer?.lineWidth = 8.0 renderer?.strokeColor = UIColor.green return renderer } return nil } /// 选中小黄车之后规划路线 /// /// - Parameters: /// - mapView: mapView /// - view: 地图上的标注(小黄车的图标) func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) { start = pin.coordinate end = view.annotation.coordinate let startPoint = AMapNaviPoint.location(withLatitude: CGFloat(start.latitude), longitude: CGFloat(start.longitude))! let endPoint = AMapNaviPoint.location(withLatitude: CGFloat(end.latitude), longitude: CGFloat(end.longitude))! walkManager.calculateWalkRoute(withStart: [startPoint], end: [endPoint]) } /// 对红包车以及普通车做一个弹出动画 /// /// - Parameters: /// - mapView: mapView /// - views: 所有的有坐标的标注 func mapView(_ mapView: MAMapView!, didAddAnnotationViews views: [Any]!) { let aViews = views as! [MAAnnotationView] for aView in aViews{ //:首先将大头针排除在外 guard aView.annotation is MAPointAnnotation else{ continue } aView.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: [], animations: { aView.transform = .identity }, completion: nil) } } /// 用户移动地图的交互 /// /// - Parameters: /// - mapView: mapView /// - wasUserAction: 是否是用户的动作 func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) { if wasUserAction { pin.isLockedToScreen = true pinAnimation() searchCustomerLocation(mapView.centerCoordinate) } } /// 地图初始化完成后 /// /// - Parameter mapView: mapView func mapInitComplete(_ mapView: MAMapView!) { pin = MyPinAnnotation() pin.coordinate = mapView.centerCoordinate pin.lockedScreenPoint = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2) pin.isLockedToScreen = true mapView.addAnnotation(pin) // mapView.showAnnotations([pin], animated: true) //:启动app时就进行搜索 searchBikeNearBy() } /// 自定义大头针视图 /// /// - Parameters: /// - mapView: mapView /// - annotation: 标注 /// - Returns: 大头针视图 func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! { //:用户自定义的位置,不需要自定义 if annotation is MAUserLocation { return nil } if annotation is MyPinAnnotation { let reuseId = "anchor" var av = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if av == nil{ av = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) } av?.image = #imageLiteral(resourceName: "homePage_wholeAnchor") av?.canShowCallout = false //:给大头针一个引用 pinView = av return av } let reUseId = "myId" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reUseId) as? MAPinAnnotationView if annotationView == nil { annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reUseId) } if annotation.title == "正常可用" { annotationView?.image = #imageLiteral(resourceName: "HomePage_nearbyBike") }else{ annotationView?.image = #imageLiteral(resourceName: "HomePage_nearbyBikeRedPacket") } annotationView?.canShowCallout = true annotationView?.animatesDrop = true return annotationView } //MARK:Map Search Delegate //:搜索周边完成后的处理 func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) { guard response.count > 0 else { print("周边没有小黄车") return } var annotations : [MAPointAnnotation] = [] annotations = response.pois.map{ let annotation = MAPointAnnotation() annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees($0.location.latitude), longitude: CLLocationDegrees($0.location.longitude)) if $0.distance < 100 { annotation.title = "红包区域内开锁任意小黄车" annotation.subtitle = "骑行10分钟可获得现金红包" } else{ annotation.title = "正常可用" } return annotation } mapView.addAnnotations(annotations) if nearBySearch { mapView.showAnnotations(annotations, animated: true) nearBySearch = !nearBySearch } } //MARK: AMapNaviWalkManagerDelegate 导航的代理 func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) { //print("步行路线规划成功") //:将地图上的线移除掉 mapView.removeOverlays(mapView.overlays) var coordinates = walkManager.naviRoute!.routeCoordinates!.map { return CLLocationCoordinate2D(latitude: CLLocationDegrees($0.latitude), longitude: CLLocationDegrees($0.longitude)) } let polyLine = MAPolyline(coordinates: &coordinates, count: UInt(coordinates.count)) mapView.add(polyLine) //:提示用距离和时间 let walkMinute = walkManager.naviRoute!.routeTime / 60 var timeDesc = "1分钟以内" if walkMinute > 0 { //:将数字转换为字符串 timeDesc = walkMinute.description + "分钟" } let hintTitle = "步行" + timeDesc let hintSubtitle = "距离" + walkManager.naviRoute!.routeLength.description + "米" /* 系统的提示功能 let alertController = UIAlertController(title: hintTitle, message: hintSubtitle, preferredStyle: .alert) let action = UIAlertAction(title: "ok", style: .default, handler: nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) */ //:第三方的提示功能 FTIndicator.setIndicatorStyle(.dark) FTIndicator.showNotification(with: #imageLiteral(resourceName: "TimeIcon"), title: hintTitle, message: hintSubtitle) } //MARK:静态tableview override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if segue.identifier == "staticTableViewController" && segue.destination .isKind(of: MenuController.self) { // // } } }
e6d688c1d4de1be91c8ede91a546852c
33.431746
162
0.607505
false
false
false
false
resmio/TastyTomato
refs/heads/main
TastyTomato/Code/Extensions/Public/UIImage/UIImage (Scaled).swift
mit
1
// // UIImage (Scaled).swift // TastyTomato // // Created by Jan Nash on 7/28/16. // Copyright © 2016 resmio. All rights reserved. // import UIKit // MARK: // Public public extension UIImage { func scaledByFactor(_ factor: CGFloat) -> UIImage { return self._scaledByFactor(factor) } func scaledToSize(_ size: CGSize) -> UIImage { return self._scaledToSize(size) } } // MARK: // Private private extension UIImage { func _scaledByFactor(_ factor: CGFloat) -> UIImage { return self._scaledToSize(self.size.scaledByFactor(factor)) } func _scaledToSize(_ size: CGSize) -> UIImage { if size == self.size { return self } let isOpaque: Bool = self.cgImage!.alphaInfo == .none let renderingMode: RenderingMode = self.renderingMode UIGraphicsBeginImageContextWithOptions(size, isOpaque, 0) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let result: UIImage = UIGraphicsGetImageFromCurrentImageContext()!.withRenderingMode(renderingMode) UIGraphicsEndImageContext() return result } }
0a52c1c703f4ede9d6cd680dd1c657d0
26.162791
107
0.639555
false
false
false
false
mrlegowatch/RolePlayingCore
refs/heads/development
CharacterGenerator/CharacterGenerator/Player/TraitCell/AlignmentCell.swift
mit
1
// // AlignmentCell.swift // CharacterGenerator // // Created by Brian Arnold on 7/9/17. // Copyright © 2017 Brian Arnold. All rights reserved. // import UIKit import RolePlayingCore class AlignmentCell : UICollectionViewCell, TraitConfigurable { @IBOutlet weak var textView: UILabel! @IBOutlet weak var labelView: UILabel! func configure(_ characterSheet: CharacterSheet, at indexPath: IndexPath) { let keyPath = characterSheet.keys[indexPath.section][indexPath.row] as! KeyPath<Player, Alignment?> let alignment = characterSheet.player[keyPath: keyPath] let alignmentString = alignment != nil ? "\(alignment!)" : "unaligned" textView.text = alignmentString labelView.text = NSLocalizedString(characterSheet.labelKeys[indexPath.section][indexPath.row], comment: "").localizedUppercase } }
5a46f7e66f7e0144bc7b436a4a2d473a
33.52
134
0.717265
false
true
false
false
CodaFi/swift
refs/heads/main
test/SILGen/property_wrappers_constrained_extension.swift
apache-2.0
22
// RUN: %target-swift-emit-silgen -primary-file %s | %FileCheck %s @propertyWrapper public struct Horse<Value> { private var stored: Value public var wrappedValue: Value { get { stored } set { stored = newValue } } public init(wrappedValue initialValue: Value) { stored = initialValue } public var projectedValue: Self { mutating get { self } set { self = newValue } } } public protocol Fuzzball {} public struct Cat : Fuzzball {} public struct Dog<Pet : Fuzzball> { @Horse public var foo: Int = 17 } extension Dog where Pet == Cat { public init() {} } // CHECK-LABEL: sil [ossa] @$s39property_wrappers_constrained_extension3DogVA2A3CatVRszrlEACyAEGycfC : $@convention(method) (@thin Dog<Cat>.Type) -> Dog<Cat> { // CHECK: [[FN:%.*]] = function_ref @$s39property_wrappers_constrained_extension3DogV4_foo33_{{.*}}LLAA5HorseVySiGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : Fuzzball> () -> Int // CHECK: apply [[FN]]<Cat>() : $@convention(thin) <τ_0_0 where τ_0_0 : Fuzzball> () -> Int
2286c423f312e15835c0ab8f7bfd7298
27.305556
180
0.678782
false
false
false
false
CodaFi/swift-compiler-crashes
refs/heads/master
crashes-fuzzing/08349-llvm-densemap-llvm-loop.swift
mit
11
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A : (object2: Int -> U)) let i: c<T where g struct c : a<T { class A<b struct d<T: C { class A<S : C { init() { } let h = b var d = 0 } println(object2: A : T] { func f<T : A { init() { init()"\() -> { } class A { init() struct d<S : C { struct c : A<d> } struct B)"\() struct d<T> let h = 0 class A<T where g: NSObject { init() func f<S : a<T where T : c<T! { init(" } init(v: B? { class A<T: A { class d } protocol B : () -> U)"\(object2: C { protocol B : A<T> struct d func g protocol a { let a { struct B? { class B : A<T where g var d = 0 let i: A { func c protocol B : (v: c<T : A : C { class A<T where g } func g func a)) println() -> U)) init(object2: T> struct d<T! { struct c : (" protocol B : NSObject { class C(v: A { struct B) init(object2: c<T.B<T { class C(v: d var d = b("\() func f<T> var e: Int -> U)))) init()"\(" } } let h = B) struct Q<S : A<T! { let h = b(v: (T: NSObject { class B : T: (T: C { } static let h = b struct c : C { func a) init(" let i: (object2: a)" struct D : A<T : Int -> U))) var d = b> { println(object2: A { } } let h = b("\()))) var e: A { protocol B : A { func c<T.B<b() } class d func f: NSObject { } class A<T: NSObject { protocol B : c class A : NSObject { let i: T> class A<T.B? { struct d> static let a { var d = b class c let h = b() { class d: a<T: A<T : C { class A<S : A { struct B<T where g: A<T : (object2: () { class A { var e: T] { func c let a { class A { static let i: A<T! { } var d = b> { } class c struct c : A<T where g: NSObject { class B : B<T where g: A<T where g class B : c<T : C { println(v: C { let i: NSObject { func a<T : A { } static let i: B)) struct Q<T { class B : A<T) { struct Q<T where T : c protocol a { let h = B<S : C { class C(v: A { init(v: A : NSObject { println() -> { init(T] { protocol a { class B : NSObject { init() -> { init(" } class C(object2: c } init(object2: A : (f<S : c<T : C { func c } class c } protocol a { init(f<T : c protocol B : T) -> { init(object2: A<T] { class c<T> class C()" protocol a { } struct B) struct B) func a)" class A { struct D : Int -> { } struct B<T { class A { class A :
7519da4b665b32ca9ddb77f97fe03b29
13.18125
87
0.568092
false
false
false
false
dobleuber/my-swift-exercises
refs/heads/master
Project26/Project26/GameViewController.swift
mit
1
// // GameViewController.swift // Project26 // // Created by Wbert Castro on 8/08/17. // Copyright © 2017 Wbert Castro. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
b4b93927b8ee5084ae4b8d5c175b207e
24.327273
77
0.580043
false
false
false
false
dreamsxin/swift
refs/heads/master
test/SILGen/partial_apply_init.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s class C { init(x: Int) {} required init(required: Double) {} } class D { required init(required: Double) {} } protocol P { init(proto: String) } extension P { init(protoExt: Float) { self.init(proto: "") } } // CHECK-LABEL: sil hidden @_TF18partial_apply_init24class_init_partial_apply func class_init_partial_apply(c: C.Type) { // Partial applications at the static metatype use the direct (_TTd) thunk. // CHECK: function_ref @_TTdFC18partial_apply_init1CC let xC: (Int) -> C = C.init // CHECK: function_ref @_TTdFC18partial_apply_init1CC let requiredC: (Double) -> C = C.init // Partial applications to a dynamic metatype must be dynamically dispatched and use // the normal thunk. // CHECK: function_ref @_TFC18partial_apply_init1CC let requiredM: (Double) -> C = c.init } // CHECK-LABEL: sil shared [thunk] @_TTdFC18partial_apply_init1CC // CHECK: function_ref @_TFC18partial_apply_init1CC // CHECK-LABEL: sil shared [thunk] @_TTdFC18partial_apply_init1CC // CHECK: function_ref @_TFC18partial_apply_init1CC // CHECK-LABEL: sil shared [thunk] @_TFC18partial_apply_init1CC // CHECK: class_method %0 : $@thick C.Type, #C.init!allocator.1 // CHECK-LABEL: sil hidden @_TF18partial_apply_init28archetype_init_partial_apply func archetype_init_partial_apply<T: C where T: P>(t: T.Type) { // Archetype initializations are always dynamic, whether applied to the type or a metatype. // CHECK: function_ref @_TFC18partial_apply_init1CC let requiredT: (Double) -> T = T.init // CHECK: function_ref @_TFP18partial_apply_init1PC let protoT: (String) -> T = T.init // CHECK: function_ref @_TFE18partial_apply_initPS_1PC let protoExtT: (Float) -> T = T.init // CHECK: function_ref @_TFC18partial_apply_init1CC let requiredM: (Double) -> T = t.init // CHECK: function_ref @_TFP18partial_apply_init1PC let protoM: (String) -> T = t.init // CHECK: function_ref @_TFE18partial_apply_initPS_1PC let protoExtM: (Float) -> T = t.init } // CHECK-LABEL: sil shared [thunk] @_TFP18partial_apply_init1PC // CHECK: witness_method $Self, #P.init!allocator.1 // CHECK-LABEL: sil shared [thunk] @_TFE18partial_apply_initPS_1PC // CHECK: function_ref @_TFE18partial_apply_initPS_1PC
a0361d760654e0654c1fd7cdef0bee2f
34.318182
93
0.69112
false
false
false
false
boytpcm123/ImageDownloader
refs/heads/master
ImageDownloader/ImageDownloader/Downloader.swift
apache-2.0
1
// // Downloader.swift // ImageDownloader // // Created by ninjaKID on 2/27/17. // Copyright © 2017 ninjaKID. All rights reserved. // import Foundation import SSZipArchive class Downloader { class func downloadImageWithURL(url:String) -> UIImage! { let data = NSData(contentsOf: NSURL(string: url)! as URL) return UIImage(data: data! as Data) } static func downloadFileZip() { if let fileUrl = URL(string: Const.urlFileZip) { // check if it exists before downloading it if FileManager().fileExists(atPath: Const.pathZipFile.path) { print("The file already exists at path") readFile(atPath: Const.pathFolderName.path) } else { // if the file doesn't exist // just download the data from your url URLSession.shared.downloadTask(with: fileUrl, completionHandler: { (location, response, error) in // after downloading your data you need to save it to your destination url guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let location = location, error == nil else { return } do { try FileManager.default.moveItem(at: location, to: Const.pathZipFile) print("file saved") // Unzip SSZipArchive.unzipFile(atPath: Const.pathZipFile.path, toDestination: Const.documentsUrl.path) readFile(atPath: Const.pathFolderName.path) } catch let error as NSError { print(error.localizedDescription) } }).resume() } } } static func readFile(atPath: String) { var items: [String] do { items = try FileManager.default.contentsOfDirectory(atPath: atPath) } catch { return } for (_, item) in items.enumerated() { if item.hasSuffix("json") { if let name:String = (item.components(separatedBy: ".").first) { let filePath = Const.pathFolderName.appendingPathComponent(name).appendingPathExtension("json").path //print(filePath) let arrayFile = getDataFile(filePath) let fileDownload: FileDownload = FileDownload(nameFile: name, pathFile: filePath, numberOfContent: arrayFile.count, dataOfContent: arrayFile) Common.ListFileDownload.append(fileDownload) } } } // let jsonItems = items.filter({ return $0.hasSuffix("json") }) // Common.ListFileDownload = jsonItems.map({ return FileDownload(nameFile: $0.components(separatedBy: ".").first!, numberOfContent: 0) }) //Post a notification NotificationCenter.default.post(name: Const.notificationDownloadedZip, object: nil) } static func getDataFile(_ filePath: String) -> [String] { do { if let data = NSData(contentsOfFile: filePath) { let jsons = try JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) return jsons as! [String] } else { print("error cannot read data") } } catch { print("error cannot find file") } return [] } }
dcecf4f79ed3db3d753c3fe9fbcc022d
32.324786
161
0.510131
false
false
false
false
tonyarnold/ReactiveCocoa
refs/heads/master
ReactiveCocoa/Swift/Flatten.swift
mit
1
// // Flatten.swift // ReactiveCocoa // // Created by Neil Pankey on 11/30/15. // Copyright © 2015 GitHub. All rights reserved. // /// Describes how multiple producers should be joined together. public enum FlattenStrategy: Equatable { /// The producers should be merged, so that any value received on any of the /// input producers will be forwarded immediately to the output producer. /// /// The resulting producer will complete only when all inputs have completed. case Merge /// The producers should be concatenated, so that their values are sent in the /// order of the producers themselves. /// /// The resulting producer will complete only when all inputs have completed. case Concat /// Only the events from the latest input producer should be considered for /// the output. Any producers received before that point will be disposed of. /// /// The resulting producer will complete only when the producer-of-producers and /// the latest producer has completed. case Latest } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner producer fails, the returned signal will /// forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { switch strategy { case .Merge: return self.merge() case .Concat: return self.concat() case .Latest: return self.switchToLatest() } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner producer fails, the returned producer will /// forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { switch strategy { case .Merge: return self.merge() case .Concat: return self.concat() case .Latest: return self.switchToLatest() } } } extension SignalType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner signal emits an error, the returned /// signal will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { return self.map(SignalProducer.init).flatten(strategy) } } extension SignalProducerType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner signal emits an error, the returned /// producer will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return self.map(SignalProducer.init).flatten(strategy) } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal which sends all the values from producer signal emitted from /// `signal`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers fail, the returned signal will forward /// that failure immediately /// /// The returned signal completes only when `signal` and all producers /// emitted from `signal` complete. private func concat() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer in self.observeConcat(observer) } } private func observeConcat(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? { let state = ConcatState(observer: observer, disposable: disposable) return self.observe { event in switch event { case let .Next(value): state.enqueueSignalProducer(value.producer) case let .Failed(error): observer.sendFailed(error) case .Completed: // Add one last producer to the queue, whose sole job is to // "turn out the lights" by completing `observer`. state.enqueueSignalProducer(SignalProducer.empty.on(completed: { observer.sendCompleted() })) case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Returns a producer which sends all the values from each producer emitted from /// `producer`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers emit an error, the returned producer will emit /// that error. /// /// The returned producer completes only when `producer` and all producers /// emitted from `producer` complete. private func concat() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, disposable in self.startWithSignal { signal, signalDisposable in disposable += signalDisposable signal.observeConcat(observer, disposable) } } } } extension SignalProducerType { /// `concat`s `next` onto `self`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return SignalProducer<SignalProducer<Value, Error>, Error>(values: [self.producer, next]).flatten(.Concat) } } private final class ConcatState<Value, Error: ErrorType> { /// The observer of a started `concat` producer. let observer: Observer<Value, Error> /// The top level disposable of a started `concat` producer. let disposable: CompositeDisposable? /// The active producer, if any, and the producers waiting to be started. let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([]) init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable?) { self.observer = observer self.disposable = disposable } func enqueueSignalProducer(producer: SignalProducer<Value, Error>) { if let d = disposable where d.disposed { return } var shouldStart = true queuedSignalProducers.modify { // An empty queue means the concat is idle, ready & waiting to start // the next producer. var queue = $0 shouldStart = queue.isEmpty queue.append(producer) return queue } if shouldStart { startNextSignalProducer(producer) } } func dequeueSignalProducer() -> SignalProducer<Value, Error>? { if let d = disposable where d.disposed { return nil } var nextSignalProducer: SignalProducer<Value, Error>? queuedSignalProducers.modify { // Active producers remain in the queue until completed. Since // dequeueing happens at completion of the active producer, the // first producer in the queue can be removed. var queue = $0 if !queue.isEmpty { queue.removeAtIndex(0) } nextSignalProducer = queue.first return queue } return nextSignalProducer } /// Subscribes to the given signal producer. func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) { signalProducer.startWithSignal { signal, disposable in let handle = self.disposable?.addDisposable(disposable) ?? nil signal.observe { event in switch event { case .Completed, .Interrupted: handle?.remove() if let nextSignalProducer = self.dequeueSignalProducer() { self.startNextSignalProducer(nextSignalProducer) } default: self.observer.action(event) } } } } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer /// added earlier. Returns a Signal that will forward events from the inner producers as they arrive. private func merge() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { relayObserver in self.observeMerge(relayObserver) } } private func observeMerge(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? { let inFlight = Atomic(1) let decrementInFlight: () -> () = { let orig = inFlight.modify { $0 - 1 } if orig == 1 { observer.sendCompleted() } } return self.observe { event in switch event { case let .Next(producer): producer.startWithSignal { innerSignal, innerDisposable in inFlight.modify { $0 + 1 } let handle = disposable?.addDisposable(innerDisposable) ?? nil innerSignal.observe { event in switch event { case .Completed, .Interrupted: handle?.remove() decrementInFlight() default: observer.action(event) } } } case let .Failed(error): observer.sendFailed(error) case .Completed: decrementInFlight() case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer /// added earlier. Returns a Signal that will forward events from the inner producers as they arrive. private func merge() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { relayObserver, disposable in self.startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observeMerge(relayObserver, disposable) } } } } extension SignalType { /// Merges the given signals into a single `Signal` that will emit all values /// from each of them, and complete when all of them have completed. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public static func merge<S: SequenceType where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<Value, Error> { let producer = SignalProducer<Signal<Value, Error>, Error>(values: signals) var result: Signal<Value, Error>! producer.startWithSignal { (signal, _) in result = signal.flatten(.Merge) } return result } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// An error sent on `signal` or the latest inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `signal` and the latest inner /// signal have both completed. private func switchToLatest() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer in self.observeSwitchToLatest(observer, SerialDisposable()) } } private func observeSwitchToLatest(observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? { let state = Atomic(LatestState<Value, Error>()) return self.observe { event in switch event { case let .Next(innerProducer): innerProducer.startWithSignal { innerSignal, innerDisposable in state.modify { // When we replace the disposable below, this prevents the // generated Interrupted event from doing any work. var state = $0 state.replacingInnerSignal = true return state } latestInnerDisposable.innerDisposable = innerDisposable state.modify { var state = $0 state.replacingInnerSignal = false state.innerSignalComplete = false return state } innerSignal.observe { event in switch event { case .Interrupted: // If interruption occurred as a result of a new producer // arriving, we don't want to notify our observer. let original = state.modify { var state = $0 if !state.replacingInnerSignal { state.innerSignalComplete = true } return state } if !original.replacingInnerSignal && original.outerSignalComplete { observer.sendCompleted() } case .Completed: let original = state.modify { var state = $0 state.innerSignalComplete = true return state } if original.outerSignalComplete { observer.sendCompleted() } default: observer.action(event) } } } case let .Failed(error): observer.sendFailed(error) case .Completed: let original = state.modify { var state = $0 state.outerSignalComplete = true return state } if original.innerSignalComplete { observer.sendCompleted() } case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// An error sent on `signal` or the latest inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `signal` and the latest inner /// signal have both completed. private func switchToLatest() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, disposable in let latestInnerDisposable = SerialDisposable() disposable.addDisposable(latestInnerDisposable) self.startWithSignal { signal, signalDisposable in signal.observeSwitchToLatest(observer, latestInnerDisposable) } } } } private struct LatestState<Value, Error: ErrorType> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false } extension SignalType { /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created producers fail, the returned signal /// will forward that failure immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created signals emit an error, the returned /// signal will forward that error immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } } extension SignalProducerType { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// If `self` or any of the created producers fail, the returned producer /// will forward that failure immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting signals (into a producer of values), according to the /// semantics of the given strategy. /// /// If `self` or any of the created signals emit an error, the returned /// producer will forward that error immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } } extension SignalType { /// Catches any failure that may occur on the input signal, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> { return Signal { observer in self.observeFlatMapError(handler, observer, SerialDisposable()) } } private func observeFlatMapError<F>(handler: Error -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? { return self.observe { event in switch event { case let .Next(value): observer.sendNext(value) case let .Failed(error): handler(error).startWithSignal { signal, disposable in serialDisposable.innerDisposable = disposable signal.observe(observer) } case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType { /// Catches any failure that may occur on the input producer, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> { return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable.addDisposable(serialDisposable) self.startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observeFlatMapError(handler, observer, serialDisposable) } } } }
2fb01afaa28e388a8c535bbe0ad29fee
32.454874
167
0.715712
false
false
false
false
3DprintFIT/octoprint-ios-client
refs/heads/dev
OctoPhone/View Related/Print Profile/FormTextInputView.swift
mit
1
// // FormTextInputView.swift // OctoPhone // // Created by Josef Dolezal on 04/04/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import SnapKit import ReactiveSwift /// Form text input with description and optional suffix label class FormTextInputView: UIView { struct Layout { static let sideMargin: CGFloat = 15 static let padding: CGFloat = 7 static let minTextFieldSize = 28 } weak var descriptionLabel: UILabel! weak var textField: UITextField! weak var suffixLabel: UILabel! override var intrinsicContentSize: CGSize { return CGSize(width: 100, height: Layout.padding + descriptionLabel.frame.height + Layout.padding + textField.frame.height + Layout.padding) } // MARK: - Initializers init() { super.init(frame: .zero) let descriptionLabel = UILabel() let textField = UITextField() let suffixLabel = UILabel() addSubview(descriptionLabel) addSubview(textField) addSubview(suffixLabel) self.descriptionLabel = descriptionLabel self.textField = textField self.suffixLabel = suffixLabel createLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Internal logic private func createLayout() { descriptionLabel.font = UIFont.preferredFont(forTextStyle: .caption1) suffixLabel.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal) descriptionLabel.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview().inset( UIEdgeInsets(top: Layout.padding, left: Layout.sideMargin, bottom: 0, right: Layout.sideMargin)) } textField.snp.makeConstraints { make in make.top.equalTo(descriptionLabel.snp.bottom).offset(Layout.padding) make.leading.equalTo(descriptionLabel) make.trailing.equalTo(suffixLabel.snp.leading).offset(-Layout.padding) make.height.greaterThanOrEqualTo(Layout.minTextFieldSize) make.bottom.equalToSuperview().inset(Layout.padding) } suffixLabel.snp.makeConstraints { make in make.lastBaseline.equalTo(textField) make.trailing.equalToSuperview().inset(Layout.sideMargin) } } }
c428ab728ef3a19be3889ca3fd96c3ee
28.903614
93
0.652297
false
false
false
false
al7/ALSpotlightView
refs/heads/master
ALSpotlightView/ViewController.swift
mit
1
/* Copyright (c) 2015 al7dev - Alex Leite. All rights reserved. */ import UIKit class ViewController: UIViewController { //MARK- View lifecycle override func loadView() { self.view = UIView(frame: UIScreen.mainScreen().bounds) self.view.backgroundColor = UIColor.whiteColor() let label = UILabel(frame: self.view.bounds) label.textAlignment = .Center label.autoresizingMask = .FlexibleWidth | .FlexibleHeight label.numberOfLines = 0 label.lineBreakMode = .ByWordWrapping label.text = "Tap Anywhere in screen\nto see Spotlight View" self.view.addSubview(label) } override func viewDidLoad() { super.viewDidLoad() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onTap:") tapGestureRecognizer.numberOfTapsRequired = 1 self.view.addGestureRecognizer(tapGestureRecognizer) } //MARK- Tap Gesture Recognizer func onTap(sender: UITapGestureRecognizer) { let location = sender.locationInView(self.view) var spotlightCenter = CGPointZero spotlightCenter.x = location.x / self.view.bounds.size.width spotlightCenter.y = location.y / self.view.bounds.size.height let spotlightView = ALSpotlightView(spotlightCenter: spotlightCenter) spotlightView.onTapHandler = { spotlightView.hide() } spotlightView.show() } }
5534e2303444d06c79313a38acb1cae7
28.94
89
0.653975
false
false
false
false
boluomeng/Charts
refs/heads/Swift-3.0
ChartsRealm/Classes/Data/RealmBarLineScatterCandleBubbleDataSet.swift
apache-2.0
1
// // RealmBarLineScatterCandleBubbleDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import Charts import Realm import Realm.Dynamic open class RealmBarLineScatterCandleBubbleDataSet: RealmBaseDataSet, IBarLineScatterCandleBubbleChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors open var highlightColor = NSUIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0) open var highlightLineWidth = CGFloat(0.5) open var highlightLineDashPhase = CGFloat(0.0) open var highlightLineDashLengths: [CGFloat]? // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> Any { let copy = super.copyWithZone(zone) as! RealmBarLineScatterCandleBubbleDataSet copy.highlightColor = highlightColor copy.highlightLineWidth = highlightLineWidth copy.highlightLineDashPhase = highlightLineDashPhase copy.highlightLineDashLengths = highlightLineDashLengths return copy } }
0e5647ca2ad27529218cd3c2410bc458
28.581395
108
0.720126
false
false
false
false
ArchimboldiMao/remotex-iOS
refs/heads/master
remotex-iOS/Model/PlatformModel.swift
apache-2.0
2
// // PlatformModel.swift // remotex-iOS // // Created by archimboldi on 10/05/2017. // Copyright © 2017 me.archimboldi. All rights reserved. // import UIKit struct PlatformModel { let platformID: Int let platformName: String let summaryText: String let homeURL: URL? let lastSyncedAt: Date? init?(dictionary: JSONDictionary) { guard let platformID = dictionary["id"] as? Int, let platformName = dictionary["name"] as? String, let homeURL = dictionary["home_url"] as? String, let summaryText = dictionary["summary"] as? String, let lastSyncString = dictionary["last_sync"] as? String else { print("error parsing JSON within PlatformModel Init") return nil } self.platformID = platformID self.platformName = platformName self.summaryText = summaryText if homeURL.hasPrefix("http") { self.homeURL = URL(string: homeURL)! } else { self.homeURL = nil } self.lastSyncedAt = Date.dateWithRFC3339String(from: lastSyncString) } } extension PlatformModel { func attrStringForPlatformName(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.TagForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: platformName, attributes: attr) } func attrStringForSummaryText(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.TitleForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: summaryText, attributes: attr) } }
514e38755ba114f61d0317ef29dd110a
33.884615
270
0.667034
false
false
false
false
bpyamasinn/CircleAnimation
refs/heads/master
Classes/CircleAnimationView.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 bpyamasinn. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit @IBDesignable public class CircleAnimationView: UIView { @IBInspectable public var lineCount: Int = 2 @IBInspectable public var fromLineWidth: CGFloat = 1.0 @IBInspectable public var toLineWidth: CGFloat = 2.0 @IBInspectable public var fromOpacity: CGFloat = 1.0 @IBInspectable public var toOpacity: CGFloat = 0 @IBInspectable public var fromScale: CGFloat = 1.0 @IBInspectable public var toScale: CGFloat = 1.6 @IBInspectable public var repeatCount: Int = 10 { didSet { if(self.repeatCount == 0){ repeatCount = Int.max } } } @IBInspectable public var duration: Float = 3.0 @IBInspectable public var delay: Float = 1.5 @IBInspectable public var lineAnimationDelay: Float = 0.3 @IBInspectable public var lineColor: UIColor = UIColor.redColor() @IBInspectable public var mediaTiming: CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) public override func layoutSubviews() { super.layoutSubviews() self.layer.sublayers = nil self.layer.speed = 1.0 for i in 1...self.lineCount { let layer = CALayer() // make square if(self.bounds.height < self.bounds.width) { //horizontal rectangle layer.frame = CGRectMake((self.bounds.width - self.bounds.height/2)-self.bounds.width/2, 0, self.bounds.height, self.bounds.height) } else if(self.bounds.height > self.bounds.width) { //Vertical Rectangle layer.frame = CGRectMake(0, (self.bounds.height - self.bounds.width/2)-self.bounds.height/2, self.bounds.width, self.bounds.width) } else { //Square layer.frame = self.bounds } layer.cornerRadius = layer.frame.width / 2.0 layer.borderColor = self.lineColor.CGColor layer.borderWidth = self.fromLineWidth layer.opacity = 0 let hover : CABasicAnimation = CABasicAnimation(keyPath:"transform") hover.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(self.fromScale, self.fromScale, 1)) hover.toValue = NSValue(CATransform3D: CATransform3DMakeScale(self.toScale, self.toScale, 1)) let borderWidth = CABasicAnimation(keyPath:"borderWidth") borderWidth.fromValue = self.fromLineWidth borderWidth.toValue = self.toLineWidth let alphaAnimation = CABasicAnimation(keyPath:"opacity") alphaAnimation.fromValue = self.fromOpacity alphaAnimation.toValue = self.toOpacity hover.duration = CFTimeInterval(Float(self.duration)-self.delay) borderWidth.duration = CFTimeInterval(Float(self.duration)-self.delay) alphaAnimation.duration = CFTimeInterval(Float(self.duration)-self.delay) let animationGroup = CAAnimationGroup() animationGroup.animations = [hover, borderWidth, alphaAnimation] animationGroup.beginTime = CACurrentMediaTime() + CFTimeInterval(self.lineAnimationDelay*Float(i)) animationGroup.duration = CFTimeInterval(self.duration) animationGroup.repeatCount = Float(self.repeatCount) animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animationGroup.removedOnCompletion = false layer.addAnimation(animationGroup, forKey: "animation") self.layer.insertSublayer(layer, atIndex: UInt32(i)) } } public func stopAnimation() { self.layer.speed = 0.0; self.layer.timeOffset = self.layer.convertTime(CACurrentMediaTime(), fromLayer: nil); } }
040add3ea2f1f9c88830e75c8a330810
39.309091
135
0.758177
false
false
false
false
umich-software-prototyping-clinic/ios-app
refs/heads/master
iOS app/ViewController.swift
mit
1
import UIKit class LoginViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UITableViewDelegate, UITableViewDataSource { let button = UIButton() let resetPasswordButton = UIButton() let printButton = UIButton() let userListButton = UIButton() let exampleTitle = UILabel() var userArray: [String] = [] var emailArray: [String] = [] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() let tableView: UITableView = UITableView() tableView.frame = CGRectMake(0, 50, 320, 200); tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(tableView) self.view.addSubview(exampleTitle) exampleTitle.backgroundColor = UIColor.lightGrayColor() exampleTitle.sizeToHeight(30) exampleTitle.sizeToWidth(600) exampleTitle.pinToTopEdgeOfSuperview(20) exampleTitle.centerHorizontallyInSuperview() exampleTitle.font = UIFont(name: "AvenirNext-DemiBold", size: 30) exampleTitle.textAlignment = NSTextAlignment.Center exampleTitle.text = "Example App" exampleTitle.textColor = UIColor.whiteColor() self.view.addSubview(button) button.backgroundColor = UIColor.darkGrayColor() button.sizeToHeight(40) button.sizeToWidth(100) button.pinToBottomEdgeOfSuperview() button.setTitle("Logout", forState: UIControlState.Normal) button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) button.addTarget(self, action: "logoutAction", forControlEvents: .TouchUpInside) self.view.addSubview(resetPasswordButton) resetPasswordButton.backgroundColor = UIColor.darkGrayColor() resetPasswordButton.pinToBottomEdgeOfSuperview() resetPasswordButton.sizeToHeight(40) resetPasswordButton.sizeToWidth(100) resetPasswordButton.positionToTheRightOfItem(button, offset: 5) resetPasswordButton.setTitle("Reset Pswd", forState: UIControlState.Normal) resetPasswordButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) resetPasswordButton.addTarget(self, action: "resetAction", forControlEvents: .TouchUpInside) self.view.addSubview(printButton) printButton.backgroundColor = UIColor.darkGrayColor() printButton.sizeToHeight(40) printButton.sizeToWidth(100) printButton.pinToRightEdgeOfSuperview() printButton.pinToBottomEdgeOfSuperview() printButton.setTitle("Print Text", forState: UIControlState.Normal) printButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) printButton.addTarget(self, action: "printAction", forControlEvents: .TouchUpInside) self.view.addSubview(userListButton) userListButton.backgroundColor = UIColor.darkGrayColor() userListButton.sizeToHeight(40) userListButton.sizeToWidth(100) userListButton.positionToTheLeftOfItem(printButton, offset: 5) userListButton.pinToBottomEdgeOfSuperview() userListButton.setTitle("User List", forState: UIControlState.Normal) userListButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) userListButton.addTarget(self, action: "userListAction", forControlEvents: .TouchUpInside) //Create table view //Retrieve list of all users let query:PFQuery=PFQuery(className: "_User"); query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error:NSError?) -> Void in if !(error != nil) { for(var i=0;i<objects!.count;i++){ let object=objects![i] as! PFObject; let name = object.objectForKey("username") as! String; let email = object.objectForKey("email") as! String; self.userArray.append(name) self.emailArray.append(email) tableView.reloadData() } } } // Do any additional setup after loading the view. }//func func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell") as UITableViewCell cell.textLabel?.text = userArray[indexPath.row] cell.detailTextLabel?.text = emailArray[indexPath.row] return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }//func //MARK: Parse Login //If no user logged in then parse login view opens func loginSetup() { if (PFUser.currentUser() == nil) { let loginViewController = PFLogInViewController() loginViewController.delegate = self let signupViewController = PFSignUpViewController() signupViewController.delegate = self loginViewController.signUpController = signupViewController loginViewController.fields = ([PFLogInFields.LogInButton, PFLogInFields.SignUpButton, PFLogInFields.UsernameAndPassword, PFLogInFields.PasswordForgotten , PFLogInFields.DismissButton]) // let signupTitle = UILabel() // signupTitle.text = "Barter Signup" //loginLogo let loginLogoImageView = UIImageView() loginLogoImageView.image = UIImage(named: "swap") loginLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit //signupLogo let signupLogoImageView = UIImageView() signupLogoImageView.image = UIImage(named: "swap") signupLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit loginViewController.view.backgroundColor = UIColor.whiteColor() signupViewController.view.backgroundColor = UIColor.whiteColor() loginViewController.logInView?.logo = loginLogoImageView signupViewController.signUpView?.logo = signupLogoImageView self.presentViewController(loginViewController, animated: true, completion: nil) }//if }//func //Checks if username and password are empty func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { if (!username.isEmpty || !password.isEmpty) { return true }//if else { return false }//else }//func //Closes login view after user logs in func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for login error func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { print("Failed to login....") }//func //MARK: Parse SignUp //Closes signup view after user signs in func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for signup error func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { print("Failed to signup") }//func //Checks if user cancelled signup func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { print("User dismissed signup") }//func //Logs out user func logoutAction() { print("logging out") PFUser.logOut() self.loginSetup() }//func func printAction() { print("clicked") let PVC = printViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func userListAction() { print("clicked") let PVC = LoginViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func resetAction() { print("clicked") let RVC = resetPasswordViewController() self.presentViewController(RVC, animated: false, completion: nil) }//func } //LoginViewController
03f4af621608d088931a7494893e45cc
36.485597
197
0.646135
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
3-Fibonacci/3-Fibonacci/Dimension.swift
mit
1
// // Dimension.swift // 3-Fibonacci // // Created by FlyElephant on 16/12/12. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation // 顺时针打印矩阵 class Dimension { func printMatrixClockwisly(data:[[Int]]?,rows:Int,cols:Int) { if data == nil || rows <= 0 { return; } var start:Int = 0 while start <= rows/2 && start <= cols/2 { printMatrixInCircle(data:data!,rows:rows,cols:cols,start:start) start += 1 } } func printMatrixInCircle(data:[[Int]],rows:Int,cols:Int,start:Int) { let endX:Int = cols - 1 - start //最大列 let endY:Int = rows - 1 - start // 最大行 // 从左到右打印行 for i in start...endX { let value:Int = data[start][i] print("\(value)", terminator: " ") } if start < endY { // 从上到下打印列 for i in start+1...endY { let value:Int = data[i][endX] print("\(value)", terminator: " ") } } if start < endX && start+1 < endY { // 从右向左打印行 for i in (start..<endX).reversed() { let value:Int = data[endY][i] print("\(value)", terminator: " ") } } if start < endX && start+1 < endY { // 从下到上打印行 for i in (start+1..<endY).reversed() { let value:Int = data[i][start] print("\(value)", terminator: " ") } } } }
f544694a44fbfb63cf4769fba5edc4a0
24.301587
75
0.446675
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Macie/Macie_Paginator.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Macie { /// Lists all Amazon Macie Classic member accounts for the current Amazon Macie Classic master account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listMemberAccountsPaginator<Result>( _ input: ListMemberAccountsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListMemberAccountsResult, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listMemberAccounts, tokenKey: \ListMemberAccountsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listMemberAccountsPaginator( _ input: ListMemberAccountsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListMemberAccountsResult, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMemberAccounts, tokenKey: \ListMemberAccountsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all the S3 resources associated with Amazon Macie Classic. If memberAccountId isn't specified, the action lists the S3 resources associated with Amazon Macie Classic for the current master account. If memberAccountId is specified, the action lists the S3 resources associated with Amazon Macie Classic for the specified member account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listS3ResourcesPaginator<Result>( _ input: ListS3ResourcesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListS3ResourcesResult, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listS3Resources, tokenKey: \ListS3ResourcesResult.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listS3ResourcesPaginator( _ input: ListS3ResourcesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListS3ResourcesResult, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listS3Resources, tokenKey: \ListS3ResourcesResult.nextToken, on: eventLoop, onPage: onPage ) } } extension Macie.ListMemberAccountsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Macie.ListMemberAccountsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension Macie.ListS3ResourcesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Macie.ListS3ResourcesRequest { return .init( maxResults: self.maxResults, memberAccountId: self.memberAccountId, nextToken: token ) } }
1501ff2d018ea8414fea3fbfa660a882
42.492958
350
0.645078
false
false
false
false
GEOSwift/GEOSwift
refs/heads/issue212
GEOSwift/GEOS/WKBConvertible.swift
mit
2
import Foundation import geos public protocol WKBConvertible { func wkb() throws -> Data } protocol WKBConvertibleInternal: WKBConvertible, GEOSObjectConvertible {} extension WKBConvertibleInternal { public func wkb() throws -> Data { let context = try GEOSContext() let writer = try WKBWriter(context: context) return try writer.write(self) } } extension Point: WKBConvertible, WKBConvertibleInternal {} extension LineString: WKBConvertible, WKBConvertibleInternal {} extension Polygon.LinearRing: WKBConvertible, WKBConvertibleInternal {} extension Polygon: WKBConvertible, WKBConvertibleInternal {} extension MultiPoint: WKBConvertible, WKBConvertibleInternal {} extension MultiLineString: WKBConvertible, WKBConvertibleInternal {} extension MultiPolygon: WKBConvertible, WKBConvertibleInternal {} extension GeometryCollection: WKBConvertible, WKBConvertibleInternal {} extension Geometry: WKBConvertible, WKBConvertibleInternal {} private final class WKBWriter { private let context: GEOSContext private let writer: OpaquePointer init(context: GEOSContext) throws { guard let writer = GEOSWKBWriter_create_r(context.handle) else { throw GEOSError.libraryError(errorMessages: context.errors) } self.context = context self.writer = writer } deinit { GEOSWKBWriter_destroy_r(context.handle, writer) } func write(_ geometry: GEOSObjectConvertible) throws -> Data { let geosObject = try geometry.geosObject(with: context) var bufferCount = 0 guard let bufferPointer = GEOSWKBWriter_write_r( context.handle, writer, geosObject.pointer, &bufferCount) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { bufferPointer.deallocate() } return Data(buffer: UnsafeBufferPointer(start: bufferPointer, count: bufferCount)) } }
0d6d6b9efd4924d04c8ce62efb170e74
35.018519
90
0.731105
false
false
false
false
swift-lang/swift-t
refs/heads/master
stc/tests/750-pragma-1.swift
apache-2.0
1
/* * Test that we can define new work types and use them for foreign * functions. */ import io; pragma worktypedef a_new_work_type; @dispatch=a_new_work_type (void o) f1(int i) "turbine" "0.0" [ "puts \"f1(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; // Should not be case-sensitive @dispatch=A_NEW_WORK_TYPE (void o) f2(int i) "turbine" "0.0" [ "puts \"f2(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; @dispatch=WORKER (void o) f3(int i) "turbine" "0.0" [ "puts \"f3(<<i>>) ran on $turbine::mode ([ adlb::comm_rank ])\"" ]; main () { foreach i in [0:100] { f1(i); f2(i); f3(i); } // Try to trick into running in wrong context f1(-1) => f2(-1) => f3(-1); f3(-2) => f1(-2) => f2(-2); f1(-3) => f3(-3) => f2(-3); }
0661a7f0b9c16850cc67b55367646ed1
16.456522
66
0.534247
false
false
false
false
TucoBZ/GitHub_APi_Test
refs/heads/master
GitHub_API/RepositoryViewController.swift
mit
1
// // RepositoryViewController.swift // GitHub_API // // Created by Túlio Bazan da Silva on 11/01/16. // Copyright © 2016 TulioBZ. All rights reserved. // import UIKit import PINRemoteImage final class RepositoryViewController: UIViewController { // MARK: - Variables var repo : Array<Repository>? var filteredArray : Array<Repository>? var connection : APIConnection? var searchController : UISearchController! var shouldShowSearchResults = false @IBOutlet var tableView: UITableView! // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() repo = [] filteredArray = [] configureSearchController() configureConnection() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureConnection(){ connection = APIConnection.init(connectionDelegate: self, currentView: self.view) connection?.getRepositories(0) } func configureSearchController() { // Initialize and perform a minimum configuration to the search controller. searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search here..." searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() // Place the search bar view to the tableview headerview. tableView.tableHeaderView = searchController.searchBar } } // MARK: - UITableViewDelegate extension RepositoryViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {} } // MARK: - UITableViewDataSource extension RepositoryViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if shouldShowSearchResults { return filteredArray?.count ?? 0 } return repo?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() if let reuseblecell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? UITableViewCell { if shouldShowSearchResults { //Repository Name and Description if let name = filteredArray?[indexPath.row].name{ reuseblecell.textLabel?.text = name } if let description = filteredArray?[indexPath.row].description { reuseblecell.detailTextLabel?.text = description } } else { //Repository Name and Description if let description = repo?[indexPath.row].description{ reuseblecell.detailTextLabel?.text = description } if let name = repo?[indexPath.row].name,let id = repo?[indexPath.row].id{ reuseblecell.textLabel?.text = "\(name) - ID: \(id)" if repo!.count-1 == indexPath.row{ connection?.getRepositories(id) } } } //Image reuseblecell.imageView?.image = UIImage(named: "githubPlaceHolder") cell = reuseblecell } return cell } } // MARK: - UISearchBarDelegate extension RepositoryViewController: UISearchBarDelegate { func updateSearchResultsForSearchController(searchController: UISearchController) {} } // MARK: - UISearchResultsUpdating extension RepositoryViewController: UISearchResultsUpdating { func searchBarTextDidBeginEditing(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] } func searchBarCancelButtonClicked(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !shouldShowSearchResults { shouldShowSearchResults = true connection?.searchForRepositories(searchBar.text!) } searchController.searchBar.resignFirstResponder() } } // MARK: - ConnectionDelegate extension RepositoryViewController: ConnectionDelegate { func updatedUsers(users: Array<User>) {} func updatedSearchUsers(users: Array<User>) {} func updatedRepositories(repositories: Array<Repository>) { repo?.appendAll(repositories) tableView?.reloadData() } func updatedSearchRepositories(repositories: Array<Repository>){ filteredArray = repositories tableView?.reloadData() } }
86a642596cf65eb1c21e159eb3614980
32.804054
128
0.652808
false
false
false
false
wybosys/n2
refs/heads/master
src.swift/ui/N2Graphics.swift
bsd-3-clause
1
struct CGPadding { init(t:CGFloat, b:CGFloat, l:CGFloat, r:CGFloat) { self.left = l self.right = r self.top = t self.bottom = b } var left:CGFloat, right:CGFloat, bottom:CGFloat, top:CGFloat var width: CGFloat { return self.left + self.right } var height: CGFloat { return self.top + self.bottom } static var zeroPadding: CGPadding { return CGPadding(t:0, b:0, l:0, r:0) } } protocol CGRectExt { mutating func apply(pad:CGPadding) -> CGRect mutating func offset(pt:CGPoint) -> CGRect } extension CGRect : CGRectExt { mutating func apply(pad:CGPadding) -> CGRect { self.size.width -= pad.width self.size.height -= pad.height self.origin.x += pad.left self.origin.y += pad.top return self } mutating func offset(pt:CGPoint) -> CGRect { self.origin.x += pt.x self.origin.y += pt.y return self } }
0af1852c6e4bcf980b3f06065853c2ad
18.207547
64
0.560904
false
false
false
false