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
cezarywojcik/Operations
refs/heads/development
Sources/Core/Shared/ComposedOperation.swift
mit
1
// // ComposedOperation.swift // Operations // // Created by Daniel Thorpe on 28/08/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation open class ComposedOperation<T: Operation>: GroupOperation { open var operation: T public convenience init(_ composed: T) { self.init(operation: composed) } init(operation composed: T) { self.operation = composed super.init(operations: [composed]) name = "Composed <\(T.self)>" addObserver(WillCancelObserver { [unowned self] operation, errors in guard operation === self else { return } if !errors.isEmpty, let op = self.operation as? AdvancedOperation { op.cancelWithError(OperationError.parentOperationCancelledWithErrors(errors)) } else { self.operation.cancel() } }) } }
5ac6cf4eda57b7bd903765226c569f3b
26.666667
93
0.614458
false
false
false
false
miracl/amcl
refs/heads/master
version3/swift/rom_brainpool.swift
apache-2.0
1
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // rom.swift // // Created by Michael Scott on 12/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // // Note that the original curve has been transformed to an isomorphic curve with A=-3 public struct ROM{ #if D32 // Base Bits= 28 // Brainpool Modulus static public let Modulus:[Chunk] = [0xF6E5377,0x13481D1,0x6202820,0xF623D52,0xD726E3B,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA] static let R2modp:[Chunk] = [0xB9A3787,0x9E04F49,0x8F3CF49,0x2931721,0xF1DBC89,0x54E8C3C,0xF7559CA,0xBB411A3,0x773E15F,0x9] static let MConst:Chunk = 0xEFD89B9 // Brainpool Curve static let CURVE_Cof_I:Int=1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = 0 static let CURVE_B:[Chunk] = [0xEE92B04,0xE58101F,0xF49256A,0xEBC4AF2,0x6B7BF93,0x733D0B7,0x4FE66A7,0x30D84EA,0x62C61C4,0x6] static public let CURVE_Order:[Chunk] = [0x74856A7,0x1E0E829,0x1A6F790,0x7AA3B56,0xD718C39,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA] static public let CURVE_Gx:[Chunk] = [0xE1305F4,0xA191562,0xFBC2B79,0x42C47AA,0x149AFA1,0xB23A656,0x7732213,0xC1CFE7B,0x3E8EB3C,0xA] static public let CURVE_Gy:[Chunk] = [0xB25C9BE,0xABE8F35,0x27001D,0xB6DE39D,0x17E69BC,0xE146444,0xD7F7B22,0x3439C56,0xD996C82,0x2] #endif #if D64 // Base Bits= 56 // Brainpool Modulus static public let Modulus:[Chunk] = [0x13481D1F6E5377,0xF623D526202820,0x909D838D726E3B,0xA1EEA9BC3E660A,0xA9FB57DB] static let R2modp:[Chunk] = [0x9E04F49B9A3787,0x29317218F3CF49,0x54E8C3CF1DBC89,0xBB411A3F7559CA,0x9773E15F] static let MConst:Chunk = 0xA75590CEFD89B9 // Brainpool Curve static let CURVE_Cof_I:Int=1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = 0 static let CURVE_B:[Chunk] = [0xE58101FEE92B04,0xEBC4AF2F49256A,0x733D0B76B7BF93,0x30D84EA4FE66A7,0x662C61C4] static public let CURVE_Order:[Chunk] = [0x1E0E82974856A7,0x7AA3B561A6F790,0x909D838D718C39,0xA1EEA9BC3E660A,0xA9FB57DB] static public let CURVE_Gx:[Chunk] = [0xA191562E1305F4,0x42C47AAFBC2B79,0xB23A656149AFA1,0xC1CFE7B7732213,0xA3E8EB3C] static public let CURVE_Gy:[Chunk] = [0xABE8F35B25C9BE,0xB6DE39D027001D,0xE14644417E69BC,0x3439C56D7F7B22,0x2D996C82] #endif }
fc82e1810c85c336052bbbf5c6e02b63
39.878378
135
0.792066
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/collection_subtype_downcast.swift
apache-2.0
7
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast14array_downcastFT5arrayGSaP___GSqGSaVS_1S__ : // CHECK: bb0([[ARG:%.*]] : $Array<Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs21_arrayConditionalCastu0_rFGSax_GSqGSaq___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Any, S>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func array_downcast(array: [Any]) -> [S]? { return array as? [S] } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast13dict_downcastFT4dictGVs10DictionaryVS_1SP___GSqGS0_S1_Si__ : // CHECK: bb0([[ARG:%.*]] : $Dictionary<S, Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs30_dictionaryDownCastConditionalu2_Rxs8Hashable0_S_rFGVs10Dictionaryxq__GSqGS0_q0_q1___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any, S, Int>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func dict_downcast(dict: [S: Any]) -> [S: Int]? { return dict as? [S: Int] } // It's not actually possible to test this for Sets independent of // the bridging rules.
8fc96887f581f4fcdbdf6ade03f82fea
43.547619
244
0.633351
false
false
false
false
Zewo/TrieRouteMatcher
refs/heads/master
Source/Trie.swift
mit
1
// Trie.swift // // The MIT License (MIT) // // Copyright (c) 2016 Dan Appel // // 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. public struct Trie<Element: Comparable, Payload> { let prefix: Element? var payload: Payload? var ending: Bool var children: [Trie<Element, Payload>] init() { self.prefix = nil self.payload = nil self.ending = false self.children = [] } init(prefix: Element, payload: Payload?, ending: Bool, children: [Trie<Element, Payload>]) { self.prefix = prefix self.payload = payload self.ending = ending self.children = children self.children.sort() } } public func ==<Element, Payload where Element: Comparable>(lhs: Trie<Element, Payload>, rhs: Trie<Element, Payload>) -> Bool { return lhs.prefix == rhs.prefix } public func <<Element, Payload where Element: Comparable>(lhs: Trie<Element, Payload>, rhs: Trie<Element, Payload>) -> Bool { return lhs.prefix < rhs.prefix } extension Trie: Comparable { } extension Trie { var description: String { return pretty(depth: 0) } func pretty(depth: Int) -> String { let key: String if let k = self.prefix { key = "\(k)" } else { key = "head" } let payload: String if let p = self.payload { payload = ":\(p)" } else { payload = "" } let children = self.children .map { $0.pretty(depth: depth + 1) } .reduce("", combine: { $0 + $1}) let pretty = "- \(key)\(payload)" + "\n" + "\(children)" let indentation = (0..<depth).reduce("", combine: {$0.0 + " "}) return "\(indentation)\(pretty)" } } extension Trie { mutating func insert<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType, payload: Payload? = nil) { insert(sequence.makeIterator(), payload: payload) } mutating func insert<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator, payload: Payload? = nil) { var iterator = iterator guard let element = iterator.next() else { self.payload = self.payload ?? payload self.ending = true return } for (index, child) in children.enumerated() { var child = child if child.prefix == element { child.insert(iterator, payload: payload) self.children[index] = child self.children.sort() return } } var new = Trie<Element, Payload>(prefix: element, payload: nil, ending: false, children: []) new.insert(iterator, payload: payload) self.children.append(new) self.children.sort() } } extension Trie { func findLast<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Trie<Element, Payload>? { return findLast(sequence.makeIterator()) } func findLast<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Trie<Element, Payload>? { var iterator = iterator guard let target = iterator.next() else { guard ending == true else { return nil } return self } // binary search var lower = 0 var higher = children.count - 1 while (lower <= higher) { let middle = (lower + higher) / 2 let child = children[middle] guard let current = child.prefix else { continue } if (current == target) { return child.findLast(iterator) } if (current < target) { lower = middle + 1 } if (current > target) { higher = middle - 1 } } return nil } } extension Trie { func findPayload<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Payload? { return findPayload(sequence.makeIterator()) } func findPayload<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Payload? { return findLast(iterator)?.payload } } extension Trie { func contains<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Bool { return contains(sequence.makeIterator()) } func contains<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Bool { return findLast(iterator) != nil } } extension Trie where Payload: Equatable { func findByPayload(_ payload: Payload) -> [Element]? { if self.payload == payload { // not sure what to do if it doesnt have a prefix if let prefix = self.prefix { return [prefix] } return [] } for child in children { if let prefixes = child.findByPayload(payload) { if let prefix = self.prefix { return [prefix] + prefixes } return prefixes } } return nil } } extension Trie { mutating func sort(_ isOrderedBefore: (Trie<Element, Payload>, Trie<Element, Payload>) -> Bool) { self.children = children.map { child in var child = child child.sort(isOrderedBefore) return child } self.children.sort(isOrderedBefore: isOrderedBefore) } }
767fbe093b6c57224351f14811d3d2c9
30.356164
148
0.58468
false
false
false
false
jzucker2/JZToolKit
refs/heads/master
JZToolKit/Classes/Experimental/ObservingViewController.swift
mit
1
// // ObservingViewController.swift // Pods // // Created by Jordan Zucker on 2/19/17. // // import UIKit class ObservingViewController: ToolKitViewController, Observer { public var kvoContext: Int = 0 open class var observerResponses: [String:Selector]? { return nil } public func updateKVO(with actions: KVOActions, oldValue: NSObject? = nil) { guard let observingKeyPaths = type(of: self).observerResponses else { print("No observer responses exist") return } for (keyPath, _) in observingKeyPaths { if actions.contains(.removeOldValue) { oldValue?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext) } if actions.contains(.remove) { observedObject?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext) } if actions.contains(.add) { observedObject?.addObserver(self, forKeyPath: keyPath, options: [.new, .old, .initial], context: &kvoContext) } } } open var observedObject: NSObject? { didSet { print("hey there: \(#function)") updateKVO(with: .propertyObserverActions, oldValue: oldValue) } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // print("self: \(self.debugDescription) \(#function) context: \(context)") if context == &kvoContext { guard let observingKeyPaths = type(of: self).observerResponses else { print("No observing Key Paths exist") return } guard let actualKeyPath = keyPath, let action = observingKeyPaths[actualKeyPath] else { fatalError("we should have had an action for this keypath since we are observing it") } let mainQueueUpdate = DispatchWorkItem(qos: .userInitiated, flags: [.enforceQoS], block: { [weak self] in // _ = self?.perform(action) _ = self?.perform(action) }) DispatchQueue.main.async(execute: mainQueueUpdate) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // open override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // updateKVO(with: .add) // } // // open override func viewDidDisappear(_ animated: Bool) { // super.viewDidDisappear(animated) // updateKVO(with: .remove) // } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { observedObject = nil } }
0bc476f5039f57257b6f53780c1db1c0
34.445783
156
0.587695
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Distortion/Tanh Distortion/AKTanhDistortion.swift
mit
1
// // AKTanhDistortion.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Distortion using a modified hyperbolic tangent function. /// /// - parameter input: Input node to process /// - parameter pregain: Determines the amount of gain applied to the signal before waveshaping. A value of 1 gives slight distortion. /// - parameter postgain: Gain applied after waveshaping /// - parameter postiveShapeParameter: Shape of the positive part of the signal. A value of 0 gets a flat clip. /// - parameter negativeShapeParameter: Like the positive shape parameter, only for the negative part. /// public class AKTanhDistortion: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKTanhDistortionAudioUnit? internal var token: AUParameterObserverToken? private var pregainParameter: AUParameter? private var postgainParameter: AUParameter? private var postiveShapeParameterParameter: AUParameter? private var negativeShapeParameterParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Determines the amount of gain applied to the signal before waveshaping. A value of 1 gives slight distortion. public var pregain: Double = 2.0 { willSet { if pregain != newValue { if internalAU!.isSetUp() { pregainParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.pregain = Float(newValue) } } } } /// Gain applied after waveshaping public var postgain: Double = 0.5 { willSet { if postgain != newValue { if internalAU!.isSetUp() { postgainParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.postgain = Float(newValue) } } } } /// Shape of the positive part of the signal. A value of 0 gets a flat clip. public var postiveShapeParameter: Double = 0.0 { willSet { if postiveShapeParameter != newValue { if internalAU!.isSetUp() { postiveShapeParameterParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.postiveShapeParameter = Float(newValue) } } } } /// Like the positive shape parameter, only for the negative part. public var negativeShapeParameter: Double = 0.0 { willSet { if negativeShapeParameter != newValue { if internalAU!.isSetUp() { negativeShapeParameterParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.negativeShapeParameter = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this distortion node /// /// - parameter input: Input node to process /// - parameter pregain: Determines the amount of gain applied to the signal before waveshaping. A value of 1 gives slight distortion. /// - parameter postgain: Gain applied after waveshaping /// - parameter postiveShapeParameter: Shape of the positive part of the signal. A value of 0 gets a flat clip. /// - parameter negativeShapeParameter: Like the positive shape parameter, only for the negative part. /// public init( _ input: AKNode, pregain: Double = 2.0, postgain: Double = 0.5, postiveShapeParameter: Double = 0.0, negativeShapeParameter: Double = 0.0) { self.pregain = pregain self.postgain = postgain self.postiveShapeParameter = postiveShapeParameter self.negativeShapeParameter = negativeShapeParameter var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x64697374 /*'dist'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKTanhDistortionAudioUnit.self, asComponentDescription: description, name: "Local AKTanhDistortion", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKTanhDistortionAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } pregainParameter = tree.valueForKey("pregain") as? AUParameter postgainParameter = tree.valueForKey("postgain") as? AUParameter postiveShapeParameterParameter = tree.valueForKey("postiveShapeParameter") as? AUParameter negativeShapeParameterParameter = tree.valueForKey("negativeShapeParameter") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.pregainParameter!.address { self.pregain = Double(value) } else if address == self.postgainParameter!.address { self.postgain = Double(value) } else if address == self.postiveShapeParameterParameter!.address { self.postiveShapeParameter = Double(value) } else if address == self.negativeShapeParameterParameter!.address { self.negativeShapeParameter = Double(value) } } } internalAU?.pregain = Float(pregain) internalAU?.postgain = Float(postgain) internalAU?.postiveShapeParameter = Float(postiveShapeParameter) internalAU?.negativeShapeParameter = Float(negativeShapeParameter) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
e0ae79245520b1e2eff0e0ae1ba10c62
38.186813
138
0.624229
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Vender/XLPagerTabStrip/BarPagerTabStripViewController.swift
mit
1
// BarPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2016 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 public struct BarPagerTabStripSettings { public struct Style { public var barBackgroundColor: UIColor? public var selectedBarBackgroundColor: UIColor? public var barHeight: CGFloat = 5 // barHeight is ony set up when the bar is created programatically and not using storyboards or xib files. } public var style = Style() } open class BarPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate { open var settings = BarPagerTabStripSettings() @IBOutlet lazy open var barView: BarView! = { [unowned self] in let barView = BarView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.settings.style.barHeight)) barView.autoresizingMask = .flexibleWidth barView.backgroundColor = .black barView.selectedBar.backgroundColor = .white return barView }() public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() barView.backgroundColor = self.settings.style.barBackgroundColor ?? barView.backgroundColor barView.selectedBar.backgroundColor = self.settings.style.selectedBarBackgroundColor ?? barView.selectedBar.backgroundColor } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self datasource = self } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if barView.superview == nil { view.addSubview(barView) } barView.optionsCount = viewControllers.count barView.moveTo(index: currentIndex, animated: false) } open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() barView.optionsCount = viewControllers.count if isViewLoaded{ barView.moveTo(index: currentIndex, animated: false) } } // MARK: - PagerTabStripDelegate open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { barView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage) } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { barView.moveTo(index: toIndex, animated: true) } }
3b3dc47226a7985f790fcde1a6f52384
40.375
185
0.718278
false
false
false
false
J3D1-WARR10R/WikiRaces
refs/heads/master
WKRKit/WKRKit/Other/WKROperation.swift
mit
2
// // WKROperation.swift // WKRKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation /// Subclass the allows async operation blocks final public class WKROperation: BlockOperation { // MARK: - Types public enum State: String { case isReady, isExecuting, isFinished } // MARK: - Properties public var state = State.isReady { willSet { willChangeValue(forKey: newValue.rawValue) willChangeValue(forKey: state.rawValue) } didSet { didChangeValue(forKey: oldValue.rawValue) didChangeValue(forKey: state.rawValue) } } public override var isReady: Bool { return super.isReady && state == .isReady } public override var isExecuting: Bool { return state == .isExecuting } public override var isFinished: Bool { return state == .isFinished } public override var isAsynchronous: Bool { return true } }
c2cf08f0ba2c4f69e98cf1f55b198a10
20.854167
55
0.618684
false
false
false
false
OscarSwanros/swift
refs/heads/master
stdlib/public/core/ASCII.swift
apache-2.0
4
//===--- ASCII.swift ------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// extension Unicode { @_fixed_layout public enum ASCII {} } extension Unicode.ASCII : Unicode.Encoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = CollectionOfOne<CodeUnit> @_inlineable // FIXME(sil-serialize-all) public static var encodedReplacementCharacter : EncodedScalar { return EncodedScalar(0x1a) // U+001A SUBSTITUTE; best we can do for ASCII } @inline(__always) @_inlineable public static func _isScalar(_ x: CodeUnit) -> Bool { return true } @inline(__always) @_inlineable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { return Unicode.Scalar(_unchecked: UInt32( source.first._unsafelyUnwrappedUnchecked)) } @inline(__always) @_inlineable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { guard source.value < (1&<<7) else { return nil } return EncodedScalar(UInt8(truncatingIfNeeded: source.value)) } @inline(__always) @_inlineable // FIXME(sil-serialize-all) public static func transcode<FromEncoding : Unicode.Encoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) guard (c._storage & 0xFF80 == 0) else { return nil } return EncodedScalar(CodeUnit(c._storage & 0x7f)) } else if _fastPath(FromEncoding.self == UTF8.self) { let c = _identityCast(content, to: UTF8.EncodedScalar.self) let first = c.first.unsafelyUnwrapped guard (first < 0x80) else { return nil } return EncodedScalar(CodeUnit(first)) } return encode(FromEncoding.decode(content)) } @_fixed_layout // FIXME(sil-serialize-all) public struct Parser { @_inlineable // FIXME(sil-serialize-all) public init() { } } public typealias ForwardParser = Parser public typealias ReverseParser = Parser } extension Unicode.ASCII.Parser : Unicode.Parser { public typealias Encoding = Unicode.ASCII /// Parses a single Unicode scalar value from `input`. @_inlineable // FIXME(sil-serialize-all) public mutating func parseScalar<I : IteratorProtocol>( from input: inout I ) -> Unicode.ParseResult<Encoding.EncodedScalar> where I.Element == Encoding.CodeUnit { let n = input.next() if _fastPath(n != nil), let x = n { guard _fastPath(Int8(truncatingIfNeeded: x) >= 0) else { return .error(length: 1) } return .valid(Unicode.ASCII.EncodedScalar(x)) } return .emptyInput } }
dc19c425df71bc2c501761b70800695d
32.053191
80
0.6598
false
false
false
false
CGDevHusky92/CGDataController
refs/heads/master
CGDataController/CGDataController.swift
mit
1
/** * CGDataController.swift * CGDataController * * Created by Charles Gorectke on 9/27/13. * Copyright (c) 2014 Revision Works, LLC. All rights reserved. * * The MIT License (MIT) * * Copyright (c) 2014 Revision Works, LLC * * 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. * * Last updated on 2/22/15 */ import UIKit import CoreData public let kCGDataControllerFinishedSaveNotification = "kCGDataControllerFinishedSaveNotification" public let kCGDataControllerFinishedBackgroundSaveNotification = "kCGDataControllerFinishedBackgroundSaveNotification" public class CGDataController: NSObject { var defaultStoreName: String? var dataStores = [ String : CGDataStore ]() public static var testBundleClass: AnyClass? public class var sharedDataController: CGDataController { struct StaticData { static let data : CGDataController = CGDataController() } return StaticData.data } public class func initSharedDataWithStoreName(storeName: String, makeDefault defaultStore: Bool = false) -> CGDataStore { if let defStore = CGDataController.sharedDataController.defaultStoreName { if defaultStore { CGDataController.sharedDataController.defaultStoreName = storeName } } else { CGDataController.sharedDataController.defaultStoreName = storeName } let dataStore = CGDataStore(sName: storeName) CGDataController.sharedDataController.dataStores.updateValue(dataStore, forKey: storeName) return dataStore } public class func sharedData() -> CGDataStore { let d = CGDataController.sharedDataController if let s = d.defaultStoreName { return self.sharedDataWithName(s) } assert(false, "You must set a store name by calling +(id)initSharedDataWithStoreName: before making calls to +(id)sharedData") } public class func sharedDataWithName(sName: String) -> CGDataStore { let d = CGDataController.sharedDataController if let s = d.dataStores[sName] { return s } assert(false, "You must set a store name by calling +(id)initSharedDataWithStoreName: before making calls to +(id)sharedDataWithName:") } private class func getModelStoreURL(storeName: String, withBundle bundle: NSBundle) -> NSURL? { var modelURL = bundle.URLForResource(storeName, withExtension: "mom") if let mURL = modelURL {} else { modelURL = bundle.URLForResource(storeName, withExtension: "momd") if let mURL = modelURL { modelURL = mURL.URLByAppendingPathComponent("\(storeName).mom") } } return modelURL } public class func modifiedObjectModelWithStoreName(storeName: String) -> NSManagedObjectModel? { let bundle: NSBundle if let tBundle: AnyClass = testBundleClass { bundle = NSBundle(forClass: tBundle) } else { bundle = NSBundle.mainBundle() } let urlTemp = self.getModelStoreURL(storeName, withBundle: bundle) if let modelURL = urlTemp { let modifiableModelTemp = NSManagedObjectModel(contentsOfURL: modelURL) if let modifiableModel = modifiableModelTemp { var entities = [NSEntityDescription]() let modelEntities = modifiableModel.entities as! [NSEntityDescription] for ent in modelEntities { var currentProps = ent.properties let objId = NSAttributeDescription() objId.name = "objectId" objId.attributeType = .StringAttributeType objId.optional = false objId.defaultValue = NSUUID().UUIDString currentProps.append(objId) let createdAt = NSAttributeDescription() createdAt.name = "createdAt" createdAt.attributeType = .DateAttributeType createdAt.optional = false currentProps.append(createdAt) let updatedAt = NSAttributeDescription() updatedAt.name = "updatedAt" updatedAt.attributeType = .DateAttributeType updatedAt.optional = false currentProps.append(updatedAt) let wasDeleted = NSAttributeDescription() wasDeleted.name = "wasDeleted" wasDeleted.attributeType = .BooleanAttributeType wasDeleted.optional = false wasDeleted.defaultValue = NSNumber(bool: false) currentProps.append(wasDeleted) let note = NSAttributeDescription() note.name = "note" note.attributeType = .StringAttributeType note.optional = true currentProps.append(note) let syncStatus = NSAttributeDescription() syncStatus.name = "syncStatus" syncStatus.attributeType = .Integer16AttributeType syncStatus.optional = false syncStatus.defaultValue = NSNumber(integer: 0) currentProps.append(syncStatus) ent.properties = currentProps entities.append(ent) } modifiableModel.entities = entities return modifiableModel } } else { assert(false, "The model could not be found. Check to make sure you have the correct model name and extension.") } return nil } } //// MARK: - Core Data stack // //lazy var applicationDocumentsDirectory: NSURL = { // // The directory the application uses to store the Core Data store file. This code uses a directory named "com.revisionworks.TestData" in the application's documents Application Support directory. // let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) // return urls[urls.count-1] as! NSURL // }() // //lazy var managedObjectModel: NSManagedObjectModel = { // // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. // let modelURL = NSBundle.mainBundle().URLForResource("TestData", withExtension: "momd")! // return NSManagedObjectModel(contentsOfURL: modelURL)! // }() // //lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // // Create the coordinator and store // var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TestData.sqlite") // var error: NSError? = nil // var failureReason = "There was an error creating or loading the application's saved data." // if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { // coordinator = nil // // Report any error we got. // var dict = [String: AnyObject]() // dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" // dict[NSLocalizedFailureReasonErrorKey] = failureReason // dict[NSUnderlyingErrorKey] = error // error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // // Replace this with code to handle the error appropriately. // // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // NSLog("Unresolved error \(error), \(error!.userInfo)") // abort() // } // // return coordinator // }() // //lazy var managedObjectContext: NSManagedObjectContext? = { // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. // let coordinator = self.persistentStoreCoordinator // if coordinator == nil { // return nil // } // var managedObjectContext = NSManagedObjectContext() // managedObjectContext.persistentStoreCoordinator = coordinator // return managedObjectContext // }() // //// MARK: - Core Data Saving support // //func saveContext () { // if let moc = self.managedObjectContext { // var error: NSError? = nil // if moc.hasChanges && !moc.save(&error) { // // Replace this implementation with code to handle the error appropriately. // // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // NSLog("Unresolved error \(error), \(error!.userInfo)") // abort() // } // } //} public class CGDataStore: NSObject { var _masterManagedObjectContext: NSManagedObjectContext? var masterManagedObjectContext: NSManagedObjectContext? { if let m = _masterManagedObjectContext { return m } _masterManagedObjectContext = self.setupManagedObjectContextWithConcurrencyType(.MainQueueConcurrencyType) return _masterManagedObjectContext } var _backgroundManagedObjectContext: NSManagedObjectContext? public var backgroundManagedObjectContext: NSManagedObjectContext? { if let b = _backgroundManagedObjectContext { return b } _backgroundManagedObjectContext = self.setupManagedObjectContextWithConcurrencyType(.PrivateQueueConcurrencyType) return _backgroundManagedObjectContext } var _managedObjectModel: NSManagedObjectModel? var managedObjectModel: NSManagedObjectModel? { if let m = _managedObjectModel { return m } _managedObjectModel = CGDataController.modifiedObjectModelWithStoreName(storeName) return _managedObjectModel } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? var persistentStoreCoordinator: NSPersistentStoreCoordinator? { if let p = _persistentStoreCoordinator { return p } if let model = managedObjectModel { let fileManager = NSFileManager.defaultManager() let docPath = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeURL = docPath.URLByAppendingPathComponent("\(storeName).sqlite") let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] var error: NSError? _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) if let p = _persistentStoreCoordinator { let store = p.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) if let s = store { return _persistentStoreCoordinator } else if let err = error { println("Error: \(err.localizedDescription)") } } } return nil } public let storeName: String public init(sName: String) { storeName = sName super.init() NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextDidSaveNotification, object: nil, queue: nil, usingBlock: { note in if let context = self.masterManagedObjectContext { let notifiedContext = note.object as! NSManagedObjectContext if notifiedContext != context { context.performBlock({_ in context.mergeChangesFromContextDidSaveNotification(note) }) } } }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: nil) } public func save() { if let context = backgroundManagedObjectContext { context.performBlockAndWait({_ in var error: NSError? let saved = context.save(&error) if !saved { if let err = error { println("Error: \(err.localizedDescription)") } } NSNotificationCenter.defaultCenter().postNotificationName(kCGDataControllerFinishedSaveNotification, object: nil) }) } } public func saveMasterContext() { if let context = masterManagedObjectContext { context.performBlockAndWait({_ in var error: NSError? let saved = context.save(&error) if !saved { if let err = error { println("Error: \(err.localizedDescription)") } } NSNotificationCenter.defaultCenter().postNotificationName(kCGDataControllerFinishedSaveNotification, object: nil) }) } } public func resetStore() { self.save() self.saveMasterContext() _backgroundManagedObjectContext = nil _masterManagedObjectContext = nil _managedObjectModel = nil _persistentStoreCoordinator = nil } public func deleteStore() { let fileManager = NSFileManager.defaultManager() let docPath = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeURL = docPath.URLByAppendingPathComponent("\(storeName).sqlite") if let storePath = storeURL.path { let exists = fileManager.fileExistsAtPath(storePath) if exists { var error: NSError? fileManager.removeItemAtPath(storePath, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } else { if let context = self.masterManagedObjectContext { for ct in context.registeredObjects { context.deleteObject(ct as! NSManagedObject) } } } } _persistentStoreCoordinator = nil self.persistentStoreCoordinator } } /* Setup Contexts */ private func setupManagedObjectContextWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext? { if let coord = self.persistentStoreCoordinator { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.performBlockAndWait({_ in context.persistentStoreCoordinator = coord }) return context } return nil } /* Generate Status Dictionary */ public func statusDictionaryForClass(className: String) -> NSDictionary? { if let context = backgroundManagedObjectContext { var error: NSError? let request = NSFetchRequest(entityName: className) let count = context.countForFetchRequest(request, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } else { var ret = NSMutableDictionary() let dateObj = self.managedObjectsForClass(className, sortedByKey: "updatedAt", ascending: false, withFetchLimit: 1) if let d = dateObj { if d.count > 1 { println("Error: Fetch for 1 item returned multiple") } else if d.count == 0 { ret.setObject(NSNumber(integer: count), forKey: "count") ret.setObject("", forKey: "lastUpdatedAt") } else { let obj = d[0] as! CGManagedObject ret.setObject(NSNumber(integer: count), forKey: "count") ret.setObject(obj.updatedAt, forKey: "lastUpdatedAt") } } return ret } } return nil } /* Generate New Object With Class */ public func newManagedObjectForClass(className: String) -> CGManagedObject? { if let context = backgroundManagedObjectContext { let objTemp = NSEntityDescription.insertNewObjectForEntityForName(className, inManagedObjectContext: context) as? CGManagedObject if let obj = objTemp { let date = NSDate() obj.createdAt = date obj.updatedAt = date return obj } else { println("Error") } } return nil } /* Single Object Existence */ public func objectExistsOnDiskWithClass(className: String, andObjectId objId: String) -> Bool { let obj = self.managedObjectForClass(className, withId: objId) if let o = obj { return true } else { return false } } /* Single Managed Object Fetch */ public func managedObjectWithManagedID(objID: NSManagedObjectID) -> CGManagedObject? { if let c = backgroundManagedObjectContext { return c.objectRegisteredForID(objID) as? CGManagedObject } return nil } public func managedObjectForClass(className: String, withId objId: String) -> CGManagedObject? { let objArray = self.managedObjectsForClass(className, sortedByKey: "createdAt", ascending: false, withPredicate: NSPredicate(format: "objectId like %@", objId)) if let a = objArray { if a.count == 0 { return nil } else if a.count > 1 { assert(false, "Error: More than one object has objectId <\(objId)>") } return a[0] as? CGManagedObject } return nil } public func nth(num: Int, managedObjectForClass className: String) -> CGManagedObject? { let objArray = self.managedObjectsForClass(className, sortedByKey: "updatedAt", ascending: false) if let a = objArray { if a.count >= num { return a[num - 1] as? CGManagedObject } } return nil } /* Single Dictionary Fetch */ public func managedObjAsDictionaryWithManagedID(objID: NSManagedObjectID) -> NSDictionary? { if let context = backgroundManagedObjectContext { let manObjTemp = context.objectRegisteredForID(objID) as? CGManagedObject if let manObj = manObjTemp { if let name = manObj.entity.name { return self.managedObjAsDictionaryForClass(name, withId: manObj.objectId as String) } else { return self.managedObjAsDictionaryForClass(manObj.entity.managedObjectClassName, withId: manObj.objectId as String) } } } return nil } public func managedObjAsDictionaryForClass(className: String, withId objId: String) -> NSDictionary? { let objArray = self.managedObjsAsDictionariesForClass(className, sortedByKey: "createdAt", ascending: false, withPredicate: NSPredicate(format: "objectId like %@", objId)) if let a = objArray { if a.count == 0 || a.count > 1 { assert(false, "Error: More than one object has objectId <\(objId)>") } return a[0] as? NSDictionary } return nil } /* Fetch Objects */ public func managedObjectsForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil) -> [AnyObject]? { return self.objectsForClass(className, sortedByKey: key, ascending: ascend, withFetchLimit: limit, withBatchSize: num, withPredicate: predicate, asDictionaries: false) } /* Fetch Objects as Dictionaries for quick lookup */ public func managedObjsAsDictionariesForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil) -> [AnyObject]? { return self.objectsForClass(className, sortedByKey: key, ascending: ascend, withFetchLimit: limit, withBatchSize: num, withPredicate: predicate, asDictionaries: true) } private func objectsForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil, asDictionaries dicts: Bool) -> [AnyObject]? { if let context = backgroundManagedObjectContext { let fetchRequest = NSFetchRequest(entityName: className) fetchRequest.predicate = predicate fetchRequest.fetchBatchSize = num if limit > 0 { fetchRequest.fetchLimit = limit } if let k = key { fetchRequest.sortDescriptors = [ NSSortDescriptor(key: k, ascending: ascend) ] } if dicts { fetchRequest.resultType = .DictionaryResultType } var results: [AnyObject]? var error: NSError? context.performBlockAndWait({_ in results = context.executeFetchRequest(fetchRequest, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } }) return results; } return nil } }
383d4d8cff875c9248b965253994fe9d
46.366599
288
0.638416
false
false
false
false
Paul-van-Klaveren/Alamofire
refs/heads/master
Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift
apache-2.0
15
// ParameterEncoding.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 /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied - parameter parameters: The parameters to apply - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ) } case .JSON: do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try NSPropertyListSerialization.dataWithPropertyList( parameters, format: format, options: options ) mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? "" } }
6e8a4bc3974c1d279a62de889c1b928e
43.460829
124
0.607587
false
false
false
false
BarTabs/bartabs
refs/heads/master
ios-application/Bar Tabs/TypeViewController.swift
gpl-3.0
1
// // drinksViewController.swift // Bar Tabs // // Created by Dexstrum on 3/2/17. // Copyright © 2017 muhlenberg. All rights reserved. /* This view controller gets all of the sub categories (i.e. Beers, Cocktails, Spirits, Mixed Drinks) and displays it in a table view. */ import UIKit import Alamofire import SwiftyJSON var _category: String? class TypeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var menu : JSON? var category: String { return _category ?? "" } @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = category self.automaticallyAdjustsScrollViewInsets = false tableView.delegate = self tableView.dataSource = self fetchData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] self.navigationController?.navigationBar.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.menu?.count) ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if (self.menu != nil) { let jsonVar : JSON = self.menu! let type = jsonVar[indexPath.row].string cell.textLabel?.text = type } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let jsonVar : JSON = self.menu! _type = jsonVar[indexPath.row].string performSegue(withIdentifier: "typeSegue", sender: nil) } func fetchData() { let service = "menu/getmenu" let parameters: Parameters = [ "barID" : 4, "category" : category ] let dataService = DataService(view: self) dataService.fetchData(service: service, parameters: parameters, completion: {(response: JSON) -> Void in self.menu = response self.tableView.reloadData() }) } }
200525051c034f2ba2def24ebfe4385e
27.957895
117
0.636496
false
false
false
false
nkirby/Humber
refs/heads/master
Humber/_src/View Controller/Pull Request List/PullRequestListViewController.swift
mit
1
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import Async import SafariServices import HMCore import HMGithub // ======================================================= class PullRequestListViewController: UITableViewController, NavigationBarUpdating, TableDividerUpdating { // ======================================================= // MARK: - Init, etc... required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.navigationController?.tabBarItem.imageInsets = UIEdgeInsets(top: 4.0, left: 0.0, bottom: -4.0, right: 0.0) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // ======================================================= // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setupNavigationItemTitle() self.setupNavigationBarStyling() self.setupTableView() self.updateTableDivider() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PullRequestListViewController.didChangeTheme), name: Theme.themeChangedNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ======================================================= // MARK: - Setup private func setupNavigationItemTitle() { self.navigationItem.title = "Pull Requests" } private func setupTableView() { self.tableView.backgroundColor = Theme.color(type: .ViewBackgroundColor) } @objc private func didChangeTheme() { self.updateTableDivider() self.setupTableView() self.setupNavigationBarStyling() } // ======================================================= // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } }
914ad93fb841e42ad51b331aa6a3f103
28.328947
180
0.547331
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Blog/WPStyleGuide+Sharing.swift
gpl-2.0
2
import Foundation import Gridicons import WordPressShared /// A WPStyleGuide extension with styles and methods specific to the /// Sharing feature. /// extension WPStyleGuide { /// Create an UIImageView showing the notice gridicon. /// /// - Returns: A UIImageView /// @objc public class func sharingCellWarningAccessoryImageView() -> UIImageView { let imageSize = 20.0 let horizontalPadding = 8.0 let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: imageSize + horizontalPadding, height: imageSize)) imageView.image = UIImage(named: "sharing-notice") imageView.tintColor = jazzyOrange() imageView.contentMode = .right return imageView } /// Creates an icon for the specified service, or a the default social icon. /// /// - Parameters: /// - service: The name of the service. /// /// - Returns: A template UIImage that can be tinted by a UIImageView's tintColor property. /// @objc public class func iconForService(_ service: NSString) -> UIImage { let name = service.lowercased.replacingOccurrences(of: "_", with: "-") var iconName: String // Handle special cases switch name { case "print" : return .gridicon(.print) case "email" : return .gridicon(.mail) case "google-plus-1" : iconName = "social-google-plus" case "press-this" : iconName = "social-wordpress" default : iconName = "social-\(name)" } var image = UIImage(named: iconName) if image == nil { image = UIImage(named: "social-default") } return image!.withRenderingMode(.alwaysTemplate) } /// Get's the tint color to use for the specified service when it is connected. /// /// - Parameters: /// - service: The name of the service. /// /// - Returns: The tint color for the service, or the default color. /// @objc public class func tintColorForConnectedService(_ service: String) -> UIColor { guard let name = SharingServiceNames(rawValue: service) else { return .primary } switch name { case .Facebook: return UIColor(fromRGBAColorWithRed: 59.0, green: 89.0, blue: 152.0, alpha: 1) case .Twitter: return UIColor(fromRGBAColorWithRed: 85, green: 172, blue: 238, alpha: 1) case .Google: return UIColor(fromRGBAColorWithRed: 220, green: 78, blue: 65, alpha: 1) case .LinkedIn: return UIColor(fromRGBAColorWithRed: 0, green: 119, blue: 181, alpha: 1) case .Tumblr: return UIColor(fromRGBAColorWithRed: 53, green: 70, blue: 92, alpha: 1) case .Path: return UIColor(fromRGBAColorWithRed: 238, green: 52, blue: 35, alpha: 1) } } enum SharingServiceNames: String { case Facebook = "facebook" case Twitter = "twitter" case Google = "google_plus" case LinkedIn = "linkedin" case Tumblr = "tumblr" case Path = "path" } }
c5e97bf38c9c8e6a4948ca4c90454038
32.252632
119
0.599557
false
false
false
false
Sherlouk/monzo-vapor
refs/heads/master
Sources/Client.swift
mit
1
import Foundation import Vapor public final class MonzoClient { let publicKey: String let privateKey: String let httpClient: Responder lazy var provider: Provider = { return Provider(client: self) }() // Leaving this code as something that should be investigated! Getting errors with Vapor though. // public convenience init(publicKey: String, privateKey: String, clientFactory: ClientFactoryProtocol) { // let responder: Responder = { // // Attempt to re-use the same client (better performance) // if let port = URI.defaultPorts["https"], // let client = try? clientFactory.makeClient(hostname: "api.monzo.com", port: port, securityLayer: .none) { // return client // } // // // Default Implementation (Will create a new client for every request) // return clientFactory // }() // // self.init(publicKey: publicKey, privateKey: privateKey, httpClient: responder) // } public init(publicKey: String, privateKey: String, httpClient: Responder) { self.publicKey = publicKey self.privateKey = privateKey self.httpClient = httpClient Monzo.setup() } /// Creates a new user with the provided access token required for authenticating all requests public func createUser(userId: String, accessToken: String, refreshToken: String?) -> User { return User(client: self, userId: userId, accessToken: accessToken, refreshToken: refreshToken) } /// Pings the Monzo API and returns true if a valid response was fired back public func ping() -> Bool { let response: String? = try? provider.request(.ping).value(forKey: "ping") return response == "pong" } /// Creates a URI to Monzo's authorisation page, you should redirect users to it in order to authorise usage of their accounts /// /// - Parameters: /// - redirectUrl: The URL that Monzo will redirect the user back to, where you should validate and obtain the access token /// - nonce: An unguessable/random string to prevent against CSRF attacks. Optional, but **recommended**! /// - Returns: The URI to redirect users to public func authorizationURI(redirectUrl: URL, nonce: String?) -> URI { var parameters: [Parameters] = [ .basic("client_id", publicKey), .basic("redirect_uri", redirectUrl.absoluteString), .basic("response_type", "code") ] if let nonce = nonce { parameters.append(.basic("state", nonce)) } let query = parameters.map({ $0.encoded(.urlQuery) }).joined(separator: "&") return URI(scheme: "https", hostname: "auth.getmondo.co.uk", query: query) } /// Validates the user has successfully authorised your client and is capable of making requests /// /// - Parameters: /// - req: The request when the user was redirected back to your server /// - nonce: The nonce used when redirecting the user to Monzo /// - Returns: On success, returns an authenticated user object for further requests public func authenticateUser(_ req: Request, nonce: String?) throws -> User { guard let code = req.query?["code"]?.string, let state = req.query?["state"]?.string else { throw MonzoAuthError.missingParameters } guard state == nonce ?? "" else { throw MonzoAuthError.conflictedNonce } var uri = req.uri uri.query = nil // Remove the query to just get the base URL for comparison let url = try uri.makeFoundationURL() let response = try provider.request(.exchangeToken(self, url, code)) let userId: String = try response.value(forKey: "user_id") let accessToken: String = try response.value(forKey: "access_token") let refreshToken: String? = try? response.value(forKey: "refresh_token") return createUser(userId: userId, accessToken: accessToken, refreshToken: refreshToken) } } final class Monzo { static func setup() { Date.incomingDateFormatters.insert(.rfc3339, at: 0) } }
4089a1f4bc2ad63b4e22f275afae11b7
44.290323
130
0.641026
false
false
false
false
gkaimakas/SwiftyFormsUI
refs/heads/master
SwiftyFormsUI/Classes/TableViews/FormTableView.swift
mit
1
// // FormTableView.swift // Pods // // Created by Γιώργος Καϊμακάς on 14/06/16. // // import Foundation import UIKit open class FormTableView: UITableView { fileprivate enum KeyboardState: Int { case visible = 0 case notVisible = 1 } fileprivate var originalBottonContentInset: CGFloat = 0 fileprivate var keyboardState: KeyboardState = .notVisible public override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) handleKeyboard() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) handleKeyboard() } open func handleKeyboard() { NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func handleKeyboardShow(_ notification: Notification){ self.layoutIfNeeded() if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size { if keyboardState == .notVisible { originalBottonContentInset = self.contentInset.bottom } self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: 0 + keyboardSize.height, right: self.contentInset.right) } UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .visible }) } @objc func handleKeyboardHide(_ notification: Notification){ self.layoutIfNeeded() self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: self.originalBottonContentInset, right: self.contentInset.right) UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .notVisible }) } }
5bb79cb9a10d3d2b59da6e8eb2143220
27.735294
165
0.748721
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/stdlib/XCTest.swift
apache-2.0
2
// RUN: %target-run-stdlib-swift // REQUIRES: executable_test // REQUIRES: objc_interop // FIXME: Add a feature for "platforms that support XCTest". // REQUIRES: OS=macosx import StdlibUnittest import XCTest var XCTestTestSuite = TestSuite("XCTest") // NOTE: When instantiating test cases for a particular test method using the // XCTestCase(selector:) initializer, those test methods must be marked // as dynamic. Objective-C XCTest uses runtime introspection to // instantiate an NSInvocation with the given selector. func execute(observers: [XCTestObservation] = [], _ run: () -> Void) { for observer in observers { XCTestObservationCenter.shared().addTestObserver(observer) } run() for observer in observers { XCTestObservationCenter.shared().removeTestObserver(observer) } } class FailureDescriptionObserver: NSObject, XCTestObservation { var failureDescription: String? func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) { failureDescription = description } } XCTestTestSuite.test("exceptions") { class ExceptionTestCase: XCTestCase { dynamic func test_raises() { NSException(name: NSExceptionName(rawValue: "XCTestTestSuiteException"), reason: nil, userInfo: nil).raise() } } let testCase = ExceptionTestCase(selector: #selector(ExceptionTestCase.test_raises)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } XCTestTestSuite.test("XCTAssertEqual/T") { class AssertEqualTestCase: XCTestCase { dynamic func test_whenEqual_passes() { XCTAssertEqual(1, 1) } dynamic func test_whenNotEqual_fails() { XCTAssertEqual(1, 2) } } let passingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenNotEqual_fails)) let observer = FailureDescriptionObserver() execute(observers: [observer], failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(observer.failureDescription, "XCTAssertEqual failed: (\"1\") is not equal to (\"2\") - ") } XCTestTestSuite.test("XCTAssertEqual/Optional<T>") { class AssertEqualOptionalTestCase: XCTestCase { dynamic func test_whenOptionalsAreEqual_passes() { XCTAssertEqual(Optional(1),Optional(1)) } dynamic func test_whenOptionalsAreNotEqual_fails() { XCTAssertEqual(Optional(1),Optional(2)) } } let passingTestCase = AssertEqualOptionalTestCase(selector: #selector(AssertEqualOptionalTestCase.test_whenOptionalsAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualOptionalTestCase(selector: #selector(AssertEqualOptionalTestCase.test_whenOptionalsAreNotEqual_fails)) let observer = FailureDescriptionObserver() execute(observers: [observer], failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) expectEqual(observer.failureDescription, "XCTAssertEqual failed: (\"Optional(1)\") is not equal to (\"Optional(2)\") - ") } XCTestTestSuite.test("XCTAssertEqual/Array<T>") { class AssertEqualArrayTestCase: XCTestCase { dynamic func test_whenArraysAreEqual_passes() { XCTAssertEqual(["foo", "bar", "baz"], ["foo", "bar", "baz"]) } dynamic func test_whenArraysAreNotEqual_fails() { XCTAssertEqual(["foo", "baz", "bar"], ["foo", "bar", "baz"]) } } let passingTestCase = AssertEqualArrayTestCase(selector: #selector(AssertEqualArrayTestCase.test_whenArraysAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualArrayTestCase(selector: #selector(AssertEqualArrayTestCase.test_whenArraysAreNotEqual_fails)) execute(failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) } XCTestTestSuite.test("XCTAssertEqual/Dictionary<T, U>") { class AssertEqualDictionaryTestCase: XCTestCase { dynamic func test_whenDictionariesAreEqual_passes() { XCTAssertEqual(["foo": "bar", "baz": "flim"], ["baz": "flim", "foo": "bar"]) } dynamic func test_whenDictionariesAreNotEqual_fails() { XCTAssertEqual(["foo": ["bar": "baz"] as NSDictionary], ["foo": ["bar": "flim"] as NSDictionary]) } } let passingTestCase = AssertEqualDictionaryTestCase(selector: #selector(AssertEqualDictionaryTestCase.test_whenDictionariesAreEqual_passes)) execute(passingTestCase.run) let passingTestRun = passingTestCase.testRun! expectEqual(1, passingTestRun.testCaseCount) expectEqual(1, passingTestRun.executionCount) expectEqual(0, passingTestRun.failureCount) expectEqual(0, passingTestRun.unexpectedExceptionCount) expectEqual(0, passingTestRun.totalFailureCount) expectTrue(passingTestRun.hasSucceeded) let failingTestCase = AssertEqualDictionaryTestCase(selector: #selector(AssertEqualDictionaryTestCase.test_whenDictionariesAreNotEqual_fails)) execute(failingTestCase.run) let failingTestRun = failingTestCase.testRun! expectEqual(1, failingTestRun.testCaseCount) expectEqual(1, failingTestRun.executionCount) expectEqual(1, failingTestRun.failureCount) expectEqual(0, failingTestRun.unexpectedExceptionCount) expectEqual(1, failingTestRun.totalFailureCount) expectFalse(failingTestRun.hasSucceeded) } XCTestTestSuite.test("XCTAssertThrowsError") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } } dynamic func test_throws() { XCTAssertThrowsError(try throwSomething()) { error in let nserror = error as NSError XCTAssertEqual(nserror.domain, "MyDomain") XCTAssertEqual(nserror.code, 42) } } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when it does not throw do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } // Now try when it throws the wrong thing do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_throws)) testCase.errorCode = 23 execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(1, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("XCTAsserts with throwing expressions") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws -> String { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } return "Hello" } dynamic func test_withThrowing() { XCTAssertEqual(try throwSomething(), "Hello") } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when the expression throws do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } XCTestTestSuite.test("Test methods that wind up throwing") { class ErrorTestCase: XCTestCase { var doThrow = true var errorCode = 42 dynamic func throwSomething() throws { if doThrow { throw NSError(domain: "MyDomain", code: errorCode, userInfo: nil) } } dynamic func test_withThrowing() throws { try throwSomething() } } // Try success case do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) testCase.doThrow = false execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(0, testRun.unexpectedExceptionCount) expectEqual(0, testRun.totalFailureCount) expectTrue(testRun.hasSucceeded) } // Now try when the expression throws do { let testCase = ErrorTestCase(selector: #selector(ErrorTestCase.test_withThrowing)) execute(testCase.run) let testRun = testCase.testRun! expectEqual(1, testRun.testCaseCount) expectEqual(1, testRun.executionCount) expectEqual(0, testRun.failureCount) expectEqual(1, testRun.unexpectedExceptionCount) expectEqual(1, testRun.totalFailureCount) expectFalse(testRun.hasSucceeded) } } runAllTests()
d871afbeccfef352b002667c86859545
34.444444
144
0.707982
false
true
false
false
firebase/firebase-ios-sdk
refs/heads/master
FirebaseStorage/Sources/StorageListResult.swift
apache-2.0
1
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /** Contains the prefixes and items returned by a `StorageReference.list()` call. */ @objc(FIRStorageListResult) open class StorageListResult: NSObject { /** * The prefixes (folders) returned by a `list()` operation. * * - Returns: A list of prefixes (folders). */ @objc public let prefixes: [StorageReference] /** * The objects (files) returned by a `list()` operation. * * - Returns: A page token if more results are available. */ @objc public let items: [StorageReference] /** * Returns a token that can be used to resume a previous `list()` operation. `nil` * indicates that there are no more results. * * - Returns: A page token if more results are available. */ @objc public let pageToken: String? // MARK: - NSObject overrides @objc override open func copy() -> Any { return StorageListResult(withPrefixes: prefixes, items: items, pageToken: pageToken) } // MARK: - Internal APIs internal convenience init(with dictionary: [String: Any], reference: StorageReference) { var prefixes = [StorageReference]() var items = [StorageReference]() let rootReference = reference.root() if let prefixEntries = dictionary["prefixes"] as? [String] { for prefixEntry in prefixEntries { var pathWithoutTrailingSlash = prefixEntry if prefixEntry.hasSuffix("/") { pathWithoutTrailingSlash = String(prefixEntry.dropLast()) } prefixes.append(rootReference.child(pathWithoutTrailingSlash)) } } if let itemEntries = dictionary["items"] as? [[String: String]] { for itemEntry in itemEntries { if let item = itemEntry["name"] { items.append(rootReference.child(item)) } } } let pageToken = dictionary["nextPageToken"] as? String self.init(withPrefixes: prefixes, items: items, pageToken: pageToken) } internal init(withPrefixes prefixes: [StorageReference], items: [StorageReference], pageToken: String?) { self.prefixes = prefixes self.items = items self.pageToken = pageToken } }
15f318e93a816a2f799959889a099c01
32.130952
90
0.664032
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/master
Tweetometer/AppDelegate.swift
mit
2
// // AppDelegate.swift // TweetsCounter // // Created by Patrick Balestra on 10/19/15. // Copyright © 2015 Patrick Balestra. All rights reserved. // import UIKit import TweetometerKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private lazy var services = AppServices(twitterSession: TwitterSession()) private lazy var appCoordinator = AppCoordinator(window: self.window!, services: services) private lazy var twitterInitializer = TwitterKitInitializer() private var initializers = [DependencyInitializer]() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) initializers = [ twitterInitializer, appCoordinator ] initializers.forEach { $0.start() } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { if let twitterInitializer = initializers.compactMap({ $0 as? TwitterKitInitializer }).first { return twitterInitializer.application(app, open:url, options: options) } return false } }
2e4f07958f4e230c2189f2ff2784cee6
34.594595
145
0.692483
false
false
false
false
krzysztofzablocki/Sourcery
refs/heads/master
SourceryTests/Generating/StencilTemplateSpec.swift
mit
1
import Quick import Nimble import PathKit import SourceryStencil #if SWIFT_PACKAGE import Foundation @testable import SourceryLib #else @testable import Sourcery #endif @testable import SourceryFramework @testable import SourceryRuntime class StencilTemplateSpec: QuickSpec { // swiftlint:disable:next function_body_length override func spec() { describe("StencilTemplate") { func generate(_ template: String) -> String { let arrayAnnotations = Variable(name: "annotated1", typeName: TypeName(name: "MyClass")) arrayAnnotations.annotations = ["Foo": ["Hello", "beautiful", "World"] as NSArray] let singleAnnotation = Variable(name: "annotated2", typeName: TypeName(name: "MyClass")) singleAnnotation.annotations = ["Foo": "HelloWorld" as NSString] return (try? Generator.generate(nil, types: Types(types: [ Class(name: "MyClass", variables: [ Variable(name: "lowerFirstLetter", typeName: TypeName(name: "myClass")), Variable(name: "upperFirstLetter", typeName: TypeName(name: "MyClass")), arrayAnnotations, singleAnnotation ]) ]), functions: [], template: StencilTemplate(templateString: template))) ?? "" } describe("json") { context("given dictionary") { let context = TemplateContext( parserResult: nil, types: Types(types: []), functions: [], arguments: ["json": ["Version": 1] as NSDictionary] ) it("renders unpretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json }}").render(context) expect(result).to(equal("{\"Version\":1}")) } it("renders pretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json:true }}").render(context) expect(result).to(equal("{\n \"Version\" : 1\n}")) } } context("given array") { let context = TemplateContext( parserResult: nil, types: Types(types: []), functions: [], arguments: ["json": ["a", "b"] as NSArray] ) it("renders unpretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json }}").render(context) expect(result).to(equal("[\"a\",\"b\"]")) } it("renders pretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json:true }}").render(context) expect(result).to(equal("[\n \"a\",\n \"b\"\n]")) } } } describe("toArray") { context("given array") { it("doesnt modify the value") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | toArray }}{% endfor %}") expect(result).to(equal("[Hello, beautiful, World]")) } } context("given something") { it("transforms it into array") { let result = generate("{% for key,value in type.MyClass.variables.3.annotations %}{{ value | toArray }}{% endfor %}") expect(result).to(equal("[HelloWorld]")) } } } describe("count") { context("given array") { it("counts it") { let result = generate("{{ type.MyClass.allVariables | count }}") expect(result).to(equal("4")) } } } describe("isEmpty") { context("given empty array") { it("returns true") { let result = generate("{{ type.MyClass.allMethods | isEmpty }}") expect(result).to(equal("true")) } } context("given non-empty array") { it("returns false") { let result = generate("{{ type.MyClass.allVariables | isEmpty }}") expect(result).to(equal("false")) } } } describe("sorted") { context("given array") { it("sorts it") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | sorted:\"description\" }}{% endfor %}") expect(result).to(equal("[beautiful, Hello, World]")) } } } describe("sortedDescending") { context("given array") { it("sorts it descending") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | sortedDescending:\"description\" }}{% endfor %}") expect(result).to(equal("[World, Hello, beautiful]")) } } } describe("reversed") { context("given array") { it("reverses it") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | reversed }}{% endfor %}") expect(result).to(equal("[World, beautiful, Hello]")) } } } context("given string") { it("generates upperFirstLetter") { expect( generate("{{\"helloWorld\" | upperFirstLetter }}")).to(equal("HelloWorld")) } it("generates lowerFirstLetter") { expect(generate("{{\"HelloWorld\" | lowerFirstLetter }}")).to(equal("helloWorld")) } it("generates uppercase") { expect(generate("{{ \"HelloWorld\" | uppercase }}")).to(equal("HELLOWORLD")) } it("generates lowercase") { expect(generate("{{ \"HelloWorld\" | lowercase }}")).to(equal("helloworld")) } it("generates capitalise") { expect(generate("{{ \"helloWorld\" | capitalise }}")).to(equal("Helloworld")) } it("generates deletingLastComponent") { expect(generate("{{ \"/Path/Class.swift\" | deletingLastComponent }}")).to(equal("/Path")) } it("checks for string in name") { expect(generate("{{ \"FooBar\" | contains:\"oo\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | contains:\"xx\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !contains:\"oo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !contains:\"xx\" }}")).to(equal("true")) } it("checks for string in prefix") { expect(generate("{{ \"FooBar\" | hasPrefix:\"Foo\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | hasPrefix:\"Bar\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasPrefix:\"Foo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasPrefix:\"Bar\" }}")).to(equal("true")) } it("checks for string in suffix") { expect(generate("{{ \"FooBar\" | hasSuffix:\"Bar\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | hasSuffix:\"Foo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasSuffix:\"Bar\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasSuffix:\"Foo\" }}")).to(equal("true")) } it("removes instances of a substring") { expect(generate("{{\"helloWorld\" | replace:\"he\",\"bo\" | replace:\"llo\",\"la\" }}")).to(equal("bolaWorld")) expect(generate("{{\"helloWorldhelloWorld\" | replace:\"hello\",\"hola\" }}")).to(equal("holaWorldholaWorld")) expect(generate("{{\"helloWorld\" | replace:\"hello\",\"\" }}")).to(equal("World")) expect(generate("{{\"helloWorld\" | replace:\"foo\",\"bar\" }}")).to(equal("helloWorld")) } } context("given TypeName") { it("generates upperFirstLetter") { expect(generate("{{ type.MyClass.variables.0.typeName }}")).to(equal("myClass")) } it("generates upperFirstLetter") { expect(generate("{{ type.MyClass.variables.0.typeName | upperFirstLetter }}")).to(equal("MyClass")) } it("generates lowerFirstLetter") { expect(generate("{{ type.MyClass.variables.1.typeName | lowerFirstLetter }}")).to(equal("myClass")) } it("generates uppercase") { expect(generate("{{ type.MyClass.variables.0.typeName | uppercase }}")).to(equal("MYCLASS")) } it("generates lowercase") { expect(generate("{{ type.MyClass.variables.1.typeName | lowercase }}")).to(equal("myclass")) } it("generates capitalise") { expect(generate("{{ type.MyClass.variables.1.typeName | capitalise }}")).to(equal("Myclass")) } it("checks for string in name") { expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"my\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"xx\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"my\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"xx\" }}")).to(equal("true")) } it("checks for string in prefix") { expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"my\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"My\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"my\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"My\" }}")).to(equal("true")) } it("checks for string in suffix") { expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"Class\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"class\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"Class\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"class\" }}")).to(equal("true")) } it("removes instances of a substring") { expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"My\" | replace:\"Class\",\"Struct\" }}")).to(equal("MyStruct")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"s\",\"z\" }}")).to(equal("myClazz")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"\" }}")).to(equal("Class")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"foo\",\"bar\" }}")).to(equal("myClass")) } } it("rethrows template parsing errors") { expect { try Generator.generate(nil, types: Types(types: []), functions: [], template: StencilTemplate(templateString: "{% tag %}")) } .to(throwError(closure: { (error) in expect("\(error)").to(equal(": Unknown template tag 'tag'")) })) } it("includes partial templates") { var outputDir = Path("/tmp") outputDir = Stubs.cleanTemporarySourceryDir() let templatePath = Stubs.templateDirectory + Path("Include.stencil") let expectedResult = "// Generated using Sourcery Major.Minor.Patch — https://github.com/krzysztofzablocki/Sourcery\n" + "// DO NOT EDIT\n" + "partial template content\n" expect { try Sourcery(cacheDisabled: true).processFiles(.sources(Paths(include: [Stubs.sourceDirectory])), usingTemplates: Paths(include: [templatePath]), output: Output(outputDir)) }.toNot(throwError()) let result = (try? (outputDir + Sourcery().generatedPath(for: templatePath)).read(.utf8)) expect(result).to(equal(expectedResult)) } } } }
d8f257d346b9987a2eedbd9ba157bf50
48.738182
219
0.47931
false
false
false
false
Azero123/JW-Broadcasting
refs/heads/master
JW Broadcasting/SuperMediaHandler.swift
mit
1
// // test.swift // JW Broadcasting // // Created by Austin Zelenka on 12/21/15. // Copyright © 2015 xquared. All rights reserved. // import UIKit import AVKit class SuperMediaPlayer: NSObject, UIGestureRecognizerDelegate { let playerViewController = AVPlayerViewController() let player=AVQueuePlayer() var statusObserver=false var dismissWhenFinished=true var nextDictionary:NSDictionary?=nil var finishedPlaying:()->Void = { () -> Void in } override init() { super.init() playerViewController.player=player player.addPeriodicTimeObserverForInterval(CMTime(value: 1, timescale: 1), queue: nil, usingBlock: { (time:CMTime) in let playerAsset:AVAsset? = self.player.currentItem != nil ? self.player.currentItem!.asset : nil if (playerAsset != nil && playerAsset!.isKindOfClass(AVURLAsset.self)){ if (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") == nil){ NSUserDefaults.standardUserDefaults().setObject(NSDictionary(), forKey: "saved-media-states") } //NSUserDefaults.standardUserDefaults().setObject(NSDictionary(), forKey: "saved-media-states") let updatedDictionary:NSMutableDictionary=(NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).mutableCopy() as! NSMutableDictionary let seconds=Float(CMTimeGetSeconds(self.player.currentTime())) if (seconds>60*5 && Float(CMTimeGetSeconds(playerAsset!.duration))*Float(0.95)>seconds && CMTimeGetSeconds(playerAsset!.duration)>60*10){ updatedDictionary.setObject(NSNumber(float: seconds), forKey: (playerAsset as! AVURLAsset).URL.path!) NSUserDefaults.standardUserDefaults().setObject(updatedDictionary, forKey: "saved-media-states") } else { updatedDictionary.removeObjectForKey((playerAsset as! AVURLAsset).URL.path!) NSUserDefaults.standardUserDefaults().setObject(updatedDictionary, forKey: "saved-media-states") } } }) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceivePress press: UIPress) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func updatePlayerUsingDictionary(dictionary:NSDictionary){ updatePlayerUsingString( unfold(dictionary, instructions: ["files","last","progressiveDownloadURL"]) as! String) updateMetaDataUsingDictionary(dictionary) } func updatePlayerUsingString(url:String){ updatePlayerUsingURL(NSURL(string: url)!) } func updatePlayerUsingURL(url:NSURL){ let newItem=AVPlayerItem(URL: url) NSNotificationCenter.defaultCenter().removeObserver(self) if (self.player.currentItem != nil){ NSNotificationCenter.defaultCenter().removeObserver(self) NSNotificationCenter.defaultCenter().removeObserver(self.player.currentItem!) //print("replace item \(self.player.currentItem?.observationInfo)") if ("\(self.player.currentItem!.observationInfo)".containsString("(")){ print("still here!") self.player.currentItem!.removeObserver(self, forKeyPath: "status") } print("replace item \(self.player.currentItem!.observationInfo)") } player.removeAllItems() player.insertItem(newItem, afterItem: nil) //player.replaceCurrentItemWithPlayerItem(nil) statusObserver=true //NSNotificationCenter.defaultCenter().addObserver(self, selector: "statusChanged", name: "status", object: newItem) newItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.Prior, context: nil) //newItem.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.Prior, context: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: newItem) } func playerItemDidReachEnd(notification:NSNotification){ print("did reach end \(notification.object) \(notification.object?.observationInfo!)") if ((notification.object?.isKindOfClass(AVPlayerItem)) == true){ if (statusObserver){ print("status observer") notification.object?.removeObserver(self, forKeyPath: "status") } while ("\(notification.object!.observationInfo)".containsString("(")){ print("still here!") notification.object?.removeObserver(self, forKeyPath: "status") } statusObserver=false //NSNotificationCenter.removeObserver(self, forKeyPath: AVPlayerItemDidPlayToEndTimeNotification) //notification.object?.removeObserver(self, forKeyPath: AVPlayerItemDidPlayToEndTimeNotification) if (nextDictionary != nil){ print("but we have more!") self.updatePlayerUsingDictionary(self.nextDictionary!) } else if (dismissWhenFinished){ playerViewController.dismissViewControllerAnimated(true, completion: nil) } } finishedPlaying() } func updateMetaDataUsingDictionary(dictionary:NSDictionary){ fetchDataUsingCache(base+"/"+version+"/categories/"+languageCode+"/\(unfold(dictionary, instructions: ["primaryCategory"])!)?detailed=1", downloaded: { dispatch_async(dispatch_get_main_queue()) { self.updateMetaDataItem(AVMetadataiTunesMetadataKeyGenreID, keySpace: AVMetadataKeySpaceiTunes, value: "\(unfold(base+"/"+version+"/categories/"+languageCode+"/\(unfold(dictionary, instructions: ["primaryCategory"])!)?detailed=1|category|name")!)") } }) var itunesMetaData:Dictionary<String,protocol<NSCopying,NSObjectProtocol>>=[:] itunesMetaData[AVMetadataiTunesMetadataKeySongName]=unfold(dictionary, instructions: ["title"]) as? String //itunesMetaData[AVMetadataiTunesMetadataKeyContentRating]="G" itunesMetaData[AVMetadataiTunesMetadataKeyDescription]="\nPublished by Watchtower Bible and Tract Society of New York, Inc.\n© 2016 Watch Tower Bible and Tract Society of Pennsylvania. All rights reserved." //unfold("\(latestVideosPath)|category|media|\(indexPath.row)|description") as? String itunesMetaData[AVMetadataiTunesMetadataKeyCopyright]="Copyright © 2016 Watch Tower Bible and Tract Society of Pennsylvania" itunesMetaData[AVMetadataiTunesMetadataKeyPublisher]="Watchtower Bible and Tract Society of New York, Inc." let imageURL=unfold(dictionary, instructions: ["images",["lsr","sqr","sqs","cvr",""],["sm","md","lg","xs",""]]) as? String if (imageURL != nil){ let image=UIImagePNGRepresentation(imageUsingCache(imageURL!)!) if (image != nil){ itunesMetaData[AVMetadataiTunesMetadataKeyCoverArt]=NSData(data: image!) } } //unfold(dictionary, instructions: ["title","images","lsr","md"]) for key in NSDictionary(dictionary: itunesMetaData).allKeys { updateMetaDataItem(key as! String, keySpace: AVMetadataKeySpaceiTunes, value: itunesMetaData[key as! String]!) } nextDictionary=dictionary } func updateMetaDataItem(key:String, keySpace:String, value:protocol<NSCopying,NSObjectProtocol>){ if (player.currentItem == nil){ print("player not ready!") return } let metadataItem = AVMutableMetadataItem() metadataItem.locale = NSLocale.currentLocale() metadataItem.key = key metadataItem.keySpace = keySpace metadataItem.value = value player.currentItem!.externalMetadata.append(metadataItem) } func play(){ /* If return to within 30 Seconds than prompt for resume Had to be 5 min in or more Had to be less than 95 % through Video has to be longer than 10 minutes */ playIn(UIApplication.sharedApplication().keyWindow!.rootViewController!) } func playIn(presenter:UIViewController){ let playerAsset = self.player.currentItem!.asset if (playerAsset.isKindOfClass(AVURLAsset.self)){ let urlPath=(playerAsset as! AVURLAsset).URL.path! if (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") != nil && (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).objectForKey(urlPath) != nil){ var seekPoint = CMTimeMake(0, 0) let seconds=(NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).objectForKey(urlPath) as! NSNumber seekPoint=CMTimeMake(Int64(seconds.floatValue), 1) let fromBeginningText=unfold(base+"/"+version+"/translations/"+languageCode+"|translations|\(languageCode)|btnPlayFromBeginning") as? String let resumeText=unfold(base+"/"+version+"/translations/"+languageCode+"|translations|\(languageCode)|btnResume") as? String let alert=UIAlertController(title: "", message: "", preferredStyle: .Alert) alert.view.tintColor = UIColor.greenColor() alert.addAction(UIAlertAction(title: nil, style: .Cancel , handler: nil)) let action=UIAlertAction(title: resumeText, style: .Default, handler: { (action:UIAlertAction) in self.playerViewController.player?.seekToTime(seekPoint) if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } }) alert.addAction(action) alert.addAction(UIAlertAction(title: fromBeginningText, style: .Default, handler: { (action:UIAlertAction) in if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } })) presenter.presentViewController(alert, animated: true, completion: nil) } if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } } else { if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } } } func exitPlayer(){ } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { print("OBSERVER IS PRESENT FRINGE TEAM LOOK OUT!") if (object != nil && object?.isKindOfClass(AVPlayerItem.self)==true && (object as! AVPlayerItem) == player.currentItem && keyPath! == "status"){ object?.removeObserver(self, forKeyPath: "status") statusObserver=false //https://www.jw.org/apps/E_RSSMEDIAMAG?rln=E&rmn=wp&rfm=m4b if (player.status == .ReadyToPlay){ var isAudio = false for track in (player.currentItem!.tracks) { if (track.assetTrack.mediaType == AVMediaTypeAudio){ isAudio=true } if (track.assetTrack.mediaType == AVMediaTypeVideo){ isAudio=false break } } if (isAudio){ if (nextDictionary != nil && playerViewController.contentOverlayView != nil){ fillEmptyVideoSpaceWithDictionary(nextDictionary!) self.nextDictionary=nil } } else { self.nextDictionary=nil } } } } func fillEmptyVideoSpaceWithDictionary(dictionary:NSDictionary){ let imageURL=unfold(dictionary, instructions: ["images",["sqr","sqs","cvr",""],["lg","sm","md","xs",""]]) as? String for subview in (self.playerViewController.contentOverlayView?.subviews)! { subview.removeFromSuperview() } var image:UIImage?=nil let imageView=UIImageView() let backgroundImage=UIImageView() if ((unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "KingdomMelodies"){ image = UIImage(named: "kingdommelodies.png") //imageView.image=image //backgroundImage.image=image } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { if (image == nil){ image=imageUsingCache(imageURL!) } dispatch_async(dispatch_get_main_queue()) { imageView.image=image imageView.frame=CGRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height) backgroundImage.image=image imageView.center=CGPoint(x: (self.playerViewController.contentOverlayView?.frame.size.width)!/2, y: 705-imageView.frame.size.height/2-150) var title=unfold(dictionary, instructions: ["title"]) as? String let extraction=titleExtractor(title!) var visualSongNumber:Int?=nil if ((title?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))>3){ visualSongNumber=Int(title!.substringToIndex(title!.startIndex.advancedBy(3))) } title=extraction["correctedTitle"] let scripturesLabel=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) scripturesLabel.center=CGPoint(x: imageView.center.x, y: 845) scripturesLabel.textAlignment = .Center scripturesLabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) scripturesLabel.text=extraction["parentheses"] self.playerViewController.contentOverlayView?.addSubview(scripturesLabel) let label=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) if (languageCode == "E" && ((unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "Piano" || (unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "Vocal" || (unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "NewSongs")){ label.text="Song \(visualSongNumber!): \(title!)" } else { label.text=(title!) } //imageView.center.y+imageView.frame.size.height/2+90 label.center=CGPoint(x: imageView.center.x, y: 700) label.textAlignment = .Center label.font=UIFont.preferredFontForTextStyle(UIFontTextStyleTitle2) label.clipsToBounds=false //title 3 self.playerViewController.contentOverlayView?.addSubview(label) let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" var albumTitle="" let albumKey=unfold(dictionary, instructions: ["primaryCategory"]) as! String let albums=unfold("\(AudioDataURL)|category|subcategories") as! NSArray for album in albums { if (album["key"] as! String == albumKey){ albumTitle=album["name"] as! String } } //let albumTitle=unfold("\(AudioDataURL)|category|subcategories|\(self.categoryIndex)|name") as! String let Albumlabel=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) Albumlabel.text=categoryTitleCorrection(albumTitle) Albumlabel.center=CGPoint(x: imageView.center.x, y: 775) Albumlabel.textAlignment = .Center Albumlabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) Albumlabel.clipsToBounds=false Albumlabel.textColor=UIColor.darkGrayColor() //title 3 self.playerViewController.contentOverlayView?.addSubview(Albumlabel) } } self.playerViewController.view.backgroundColor=UIColor.clearColor() self.playerViewController.contentOverlayView?.backgroundColor=UIColor.clearColor() let subviews=NSMutableArray(array: (self.playerViewController.view.subviews)) while subviews.count>0{ let subview=subviews.firstObject as! UIView subviews.addObjectsFromArray(subview.subviews) subview.backgroundColor=UIColor.clearColor() subviews.removeObjectAtIndex(0) } imageView.layer.shadowColor=UIColor.blackColor().CGColor imageView.layer.shadowOpacity=0.5 imageView.layer.shadowRadius=20 backgroundImage.frame=(self.playerViewController.contentOverlayView?.bounds)! self.playerViewController.contentOverlayView?.addSubview(backgroundImage) let backgroundEffect=UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) backgroundEffect.frame=(self.playerViewController.contentOverlayView?.bounds)! self.playerViewController.contentOverlayView?.addSubview(backgroundEffect) self.playerViewController.contentOverlayView?.addSubview(imageView) } }
22cd3789fdf70b69d6a4c3231c4bdc48
46.367299
289
0.601011
false
false
false
false
LiulietLee/BilibiliCD
refs/heads/master
BCD/ViewController/ImageViewController.swift
gpl-3.0
1
// // ImageViewController.swift // BCD // // Created by Liuliet.Lee on 17/6/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit import ViewAnimator import MobileCoreServices import MaterialKit import LLDialog class ImageViewController: UIViewController, Waifu2xDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! { didSet { imageView?.accessibilityIgnoresInvertColors = true } } @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var urlLabel: UILabel! @IBOutlet weak var downloadButton: UIBarButtonItem! @IBOutlet weak var pushButton: UIButton! /// Should be disabled for GIF. @IBOutlet weak var scaleButton: UIBarButtonItem! @IBOutlet weak var separator: UIProgressView! @IBOutlet weak var citationStyleControl: UISegmentedControl! @IBOutlet weak var citationTextView: UITextView! @IBOutlet weak var copyButton: UIButton! @IBOutlet var labels: [UILabel]! private let coverInfoProvider = CoverInfoProvider() private let assetProvider = AssetProvider() var cover: BilibiliCover? var itemFromHistory: History? private let manager = HistoryManager() private var loadingView: LoadingView? private var reference: (info: Info?, style: CitationStyle) = (nil, .apa) { didSet { guard let info = reference.info else { return } citationTextView?.attributedText = info.citation(ofStyle: reference.style) titleLabel?.text = info.title authorLabel?.text = "UP主:\(info.author)" urlLabel.text = "URL:\(info.imageURL)" } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isShowingImage = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver( self, selector: #selector(goBackIfNeeded), name: UIApplication.willResignActiveNotification, object: nil ) } @objc private func goBackIfNeeded() { if itemFromHistory?.isHidden == true { navigationController?.popToRootViewController(animated: false) } } override func viewDidLoad() { super.viewDidLoad() isShowingImage = true if let cover = cover { title = cover.shortDescription if itemFromHistory == nil { coverInfoProvider.getCoverInfoBy(cover: cover) { info in DispatchQueue.main.async { [weak self] in if let info = info { self?.updateUIFrom(info: info) } else { self?.cannotFindVideo() } } } } } else { title = NSLocalizedString( "COVER NOT FOUND", value: "开发者把封面弄丢了", comment: "Indicate cover is not there because developer made a mistkae" ) } if let item = itemFromHistory { reference.info = Info( stringID: item.av!, author: item.up!, title: item.title!, imageURL: item.url! ) if item.origin == nil { updateUIFrom(info: reference.info!) } imageView.image = item.uiImage changeTextColor(to: item.isHidden ? .black : .tianyiBlue) animateView() } else { changeTextColor(to: .bilibiliPink) titleLabel.text = "" authorLabel.text = "" urlLabel.text = "" disableButtons() loadingView = LoadingView(frame: view.bounds) view.addSubview(loadingView!) view.bringSubviewToFront(loadingView!) } } private func animateView() { let type = AnimationType.from(direction: .right, offset: ViewAnimatorConfig.offset) scrollView.doAnimation(type: type) } private func changeTextColor(to color: UIColor) { var labelColor = color if #available(iOS 13.0, *), labelColor == UIColor.black { labelColor = .label } labels?.forEach { $0.textColor = labelColor } citationStyleControl?.tintColor = labelColor separator?.progressTintColor = labelColor copyButton?.tintColor = labelColor navigationController?.navigationBar.barTintColor = color } @IBAction func downloadButtonTapped(_ sender: UIBarButtonItem) { saveImage() } @IBAction func titleButtonTapped() { if let cover = cover { UIApplication.shared.open(cover.url) } } @objc private func saveImage() { let image: Image guard let item = itemFromHistory , let url = item.url , let uiImage = imageView?.image , let data = imageView.image?.data() else { return imageSaved(successfully: false, error: nil) } if url.isGIF { image = .gif(uiImage, data: data) } else { image = .normal(uiImage) } ImageSaver.saveImage(image, completionHandler: imageSaved, alternateHandler: #selector(imageSavingFinished(_:didFinishSavingWithError:contextInfo:))) } @objc func imageSavingFinished(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { imageSaved(successfully: error == nil, error: error) } private func imageSaved(successfully: Bool, error: Error?) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } if !successfully || error != nil { LLDialog() .set(title: "啊叻?!") .set(message: "保存出错了Σ(  ̄□ ̄||)") .setNegativeButton(withTitle: "好吧") .setPositiveButton(withTitle: "再试一次", target: self, action: #selector(self.saveImage)) .show() print(error ?? "Unknown error") } else { LLDialog() .set(title: "保存成功!") .set(message: "封面被成功保存(〜 ̄△ ̄)〜") .setPositiveButton(withTitle: "OK") .show() } } } private func enableButtons() { downloadButton.isEnabled = true scaleButton.isEnabled = !reference.info!.imageURL.isGIF pushButton.isEnabled = true } private func disableButtons() { downloadButton.isEnabled = false scaleButton.isEnabled = false pushButton.isEnabled = false } private func updateUIFrom(info: Info) { reference.info = info assetProvider.getImage(fromUrlPath: info.imageURL) { img in if let image = img { DispatchQueue.main.async { [weak self] in self?.imageView.image = image.uiImage switch image { case .gif: self?.scaleButton.isEnabled = false case .normal: self?.scaleButton.isEnabled = true } self?.enableButtons() self?.loadingView?.dismiss() self?.animateView() self?.addItemToDB(image: image) } } else { DispatchQueue.main.async { [weak self] in self?.cannotFindVideo() } } } } func scaleSucceed(scaledImage: UIImage) { imageView.image = scaledImage manager.replaceOriginCover(of: itemFromHistory!, with: scaledImage) scaleButton.isEnabled = false LLDialog() .set(title: "(。・ω・。)") .set(message: "放大完成~") .setPositiveButton(withTitle: "嗯") .show() } private func addItemToDB(image: Image) { DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + .milliseconds(500)) { [info = reference.info!, id = cover!.shortDescription] in self.itemFromHistory = self.manager.addNewHistory( av: id, image: image, title: info.title, up: info.author, url: info.imageURL ) } } private func cannotFindVideo() { titleLabel.text = "啊叻?" authorLabel.text = "视频不见了?" urlLabel.text = "" loadingView?.dismiss() imageView.image = #imageLiteral(resourceName: "novideo_image") } @IBAction func changeCitationFormat(_ sender: UISegmentedControl) { reference.style = CitationStyle(rawValue: sender.selectedSegmentIndex)! } lazy var generator: UINotificationFeedbackGenerator = .init() @IBAction func copyToPasteBoard() { copyButton.resignFirstResponder() do { guard let citation = citationTextView.attributedText else { throw NSError() } let range = NSRange(location: 0, length: citation.length) let rtf = try citation.data(from: range, documentAttributes: [.documentType : NSAttributedString.DocumentType.rtf]) UIPasteboard.general.items = [ [ kUTTypeRTF as String: String(data: rtf, encoding: .utf8)!, kUTTypeUTF8PlainText as String: citation.string ] ] generator.notificationOccurred(.success) display("已复制到剪贴板") } catch { generator.notificationOccurred(.error) display(error) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem if let vc = segue.destination as? DetailViewController { vc.image = imageView.image vc.isHidden = itemFromHistory?.isHidden } else if let vc = segue.destination as? Waifu2xViewController { vc.originImage = imageView.image vc.delegate = self } } }
6af3a31615c8540f952c532f6591e21c
33.703333
157
0.571319
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Swift/Classes/Model/ImageFilter.swift
mit
1
// // ImageFilter.swift // Example // // Created by Slience on 2022/2/18. // #if canImport(GPUImage) import UIKit import VideoToolbox import HXPHPicker import GPUImage struct FilterTools { static func filters() -> [CameraFilter] { [ BeautifyFilter(), InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] } } class BeautifyFilter: CameraFilter { var filterName: String { return "美白" } var filter: GPUImageBeautifyFilter? func prepare(_ size: CGSize) { filter = GPUImageBeautifyFilter(degree: 0.6) } func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? { var cgImage: CGImage? VTCreateCGImageFromCVPixelBuffer(pixelBuffer, options: nil, imageOut: &cgImage) guard let cgImage = cgImage, let bilateralFilter = filter else { return nil } let picture = GPUImagePicture(cgImage: cgImage) picture?.addTarget(bilateralFilter) bilateralFilter.useNextFrameForImageCapture() picture?.processImage() let result = bilateralFilter.newCGImageFromCurrentlyProcessedOutput().takeRetainedValue() return .init(cgImage: result) } func reset() { filter = nil } } #endif
778e4f011b592caba2cfbadfcf312ac1
24.211538
99
0.631579
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/ChatModule/Chat/ViewController/JCGroupSettingViewController.swift
mit
1
// // JCGroupSettingViewController.swift // JChat // // Created by JIGUANG on 2017/4/27. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import JMessage class JCGroupSettingViewController: UIViewController, CustomNavigation { var group: JMSGGroup! override func viewDidLoad() { super.viewDidLoad() _init() } deinit { NotificationCenter.default.removeObserver(self) } private var tableView: UITableView = UITableView(frame: .zero, style: .grouped) fileprivate var memberCount = 0 fileprivate lazy var users: [JMSGUser] = [] fileprivate var isMyGroup = false fileprivate var isNeedUpdate = false //MARK: - private func private func _init() { self.title = "群组信息" view.backgroundColor = .white users = group.memberArray() memberCount = users.count let user = JMSGUser.myInfo() // && group.ownerAppKey == user.appKey! 这里group.ownerAppKey == "" 目测sdk bug if group.owner == user.username { isMyGroup = true } tableView.separatorStyle = .none tableView.delegate = self tableView.dataSource = self tableView.sectionIndexColor = UIColor(netHex: 0x2dd0cf) tableView.sectionIndexBackgroundColor = .clear tableView.register(JCButtonCell.self, forCellReuseIdentifier: "JCButtonCell") tableView.register(JCMineInfoCell.self, forCellReuseIdentifier: "JCMineInfoCell") tableView.register(GroupAvatorCell.self, forCellReuseIdentifier: "GroupAvatorCell") tableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height) view.addSubview(tableView) customLeftBarButton(delegate: self) JMSGGroup.groupInfo(withGroupId: group.gid) { (result, error) in if error == nil { guard let group = result as? JMSGGroup else { return } self.group = group self.isNeedUpdate = true self._updateGroupInfo() } } NotificationCenter.default.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil) } @objc func _updateGroupInfo() { if !isNeedUpdate { let conv = JMSGConversation.groupConversation(withGroupId: group.gid) group = conv?.target as! JMSGGroup } if group.memberArray().count != memberCount { isNeedUpdate = true memberCount = group.memberArray().count } users = group.memberArray() memberCount = users.count tableView.reloadData() } } extension JCGroupSettingViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 4 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 3 case 2: // return 5 return 4 case 3: return 1 default: return 0 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: if isMyGroup { if memberCount > 13 { return 314 } if memberCount > 8 { return 260 } if memberCount > 3 { return 200 } return 100 } else { if memberCount > 14 { return 314 } if memberCount > 9 { return 260 } if memberCount > 4 { return 200 } return 100 } case 1: return 45 case 2: return 40 default: return 45 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.0001 } return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { var cell = tableView.dequeueReusableCell(withIdentifier: "JCGroupSettingCell") as? JCGroupSettingCell if isNeedUpdate { cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group) isNeedUpdate = false } if cell == nil { cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group) } return cell! } if indexPath.section == 3 { return tableView.dequeueReusableCell(withIdentifier: "JCButtonCell", for: indexPath) } if indexPath.section == 1 && indexPath.row == 0 { return tableView.dequeueReusableCell(withIdentifier: "GroupAvatorCell", for: indexPath) } return tableView.dequeueReusableCell(withIdentifier: "JCMineInfoCell", for: indexPath) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.selectionStyle = .none if indexPath.section == 3 { guard let cell = cell as? JCButtonCell else { return } cell.buttonColor = UIColor(netHex: 0xEB424D) cell.buttonTitle = "退出此群" cell.delegate = self return } cell.accessoryType = .disclosureIndicator if indexPath.section == 0 { guard let cell = cell as? JCGroupSettingCell else { return } cell.bindData(self.group) cell.delegate = self cell.accessoryType = .none return } if let cell = cell as? GroupAvatorCell { cell.title = "群头像" cell.bindData(group) } guard let cell = cell as? JCMineInfoCell else { return } if indexPath.section == 2 { if indexPath.row == 1 { cell.delegate = self cell.indexPate = indexPath cell.accessoryType = .none cell.isSwitchOn = group.isNoDisturb cell.isShowSwitch = true } if indexPath.row == 2 { cell.delegate = self cell.indexPate = indexPath cell.accessoryType = .none cell.isSwitchOn = group.isShieldMessage cell.isShowSwitch = true } } if indexPath.section == 1 { let conv = JMSGConversation.groupConversation(withGroupId: self.group.gid) let group = conv?.target as! JMSGGroup switch indexPath.row { case 1: cell.title = "群聊名称" cell.detail = group.displayName() case 2: cell.title = "群描述" cell.detail = group.desc default: break } } else { switch indexPath.row { case 0: cell.title = "聊天文件" case 1: cell.title = "消息免打扰" case 2: cell.title = "消息屏蔽" // case 2: // cell.title = "清理缓存" case 3: cell.title = "清空聊天记录" default: break } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 1 { switch indexPath.row { case 0: let vc = GroupAvatorViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) case 1: let vc = JCGroupNameViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) case 2: let vc = JCGroupDescViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) default: break } } if indexPath.section == 2 { switch indexPath.row { // case 2: // let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清理缓存") // actionSheet.tag = 1001 // actionSheet.show(in: self.view) case 0: let vc = FileManagerViewController() let conv = JMSGConversation.groupConversation(withGroupId: group.gid) vc.conversation = conv navigationController?.pushViewController(vc, animated: true) case 3: let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清空聊天记录") actionSheet.tag = 1001 actionSheet.show(in: self.view) default: break } } } } extension JCGroupSettingViewController: UIAlertViewDelegate { func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { switch buttonIndex { case 1: MBProgressHUD_JChat.showMessage(message: "退出中...", toView: self.view) group.exit({ (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error == nil { self.navigationController?.popToRootViewController(animated: true) } else { MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) default: break } } } extension JCGroupSettingViewController: JCMineInfoCellDelegate { func mineInfoCell(clickSwitchButton button: UISwitch, indexPath: IndexPath?) { if indexPath != nil { switch (indexPath?.row)! { case 1: if group.isNoDisturb == button.isOn { return } // 消息免打扰 group.setIsNoDisturb(button.isOn, handler: { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error != nil { button.isOn = !button.isOn MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) case 2: if group.isShieldMessage == button.isOn { return } // 消息屏蔽 group.setIsShield(button.isOn, handler: { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error != nil { button.isOn = !button.isOn MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) default: break } } } } extension JCGroupSettingViewController: JCButtonCellDelegate { func buttonCell(clickButton button: UIButton) { let alertView = UIAlertView(title: "退出此群", message: "确定要退出此群?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定") alertView.show() } } extension JCGroupSettingViewController: JCGroupSettingCellDelegate { func clickMoreButton(clickButton button: UIButton) { let vc = JCGroupMembersViewController() vc.group = self.group self.navigationController?.pushViewController(vc, animated: true) } func clickAddCell(cell: JCGroupSettingCell) { let vc = JCUpdateMemberViewController() vc.group = group self.navigationController?.pushViewController(vc, animated: true) } func clickRemoveCell(cell: JCGroupSettingCell) { let vc = JCRemoveMemberViewController() vc.group = group self.navigationController?.pushViewController(vc, animated: true) } func didSelectCell(cell: JCGroupSettingCell, indexPath: IndexPath) { let index = indexPath.section * 5 + indexPath.row let user = users[index] if user.isEqual(to: JMSGUser.myInfo()) { navigationController?.pushViewController(JCMyInfoViewController(), animated: true) return } let vc = JCUserInfoViewController() vc.user = user navigationController?.pushViewController(vc, animated: true) } } extension JCGroupSettingViewController: UIActionSheetDelegate { func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { // if actionSheet.tag == 1001 { // // SDK 暂无该功能 // } if actionSheet.tag == 1001 { if buttonIndex == 1 { let conv = JMSGConversation.groupConversation(withGroupId: group.gid) conv?.deleteAllMessages() NotificationCenter.default.post(name: Notification.Name(rawValue: kDeleteAllMessage), object: nil) MBProgressHUD_JChat.show(text: "成功清空", view: self.view) } } } } extension JCGroupSettingViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return true } }
2a88ff5a577b2b593870c8290601cc36
33.570388
159
0.550165
false
false
false
false
ksco/swift-algorithm-club-cn
refs/heads/master
Merge Sort/MergeSort.swift
mit
1
// // Mergesort.swift // // // Created by Kelvin Lau on 2016-02-03. // // func mergeSort(array: [Int]) -> [Int] { guard array.count > 1 else { return array } let middleIndex = array.count / 2 let leftArray = mergeSort(Array(array[0..<middleIndex])) let rightArray = mergeSort(Array(array[middleIndex..<array.count])) return merge(leftPile: leftArray, rightPile: rightArray) } func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] { var leftIndex = 0 var rightIndex = 0 var orderedPile = [Int]() while leftIndex < leftPile.count && rightIndex < rightPile.count { if leftPile[leftIndex] < rightPile[rightIndex] { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } else if leftPile[leftIndex] > rightPile[rightIndex] { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } else { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } } while leftIndex < leftPile.count { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } while rightIndex < rightPile.count { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } return orderedPile } /* This is an iterative bottom-up implementation. Instead of recursively splitting up the array into smaller sublists, it immediately starts merging the individual array elements. As the algorithm works its way up, it no longer merges individual elements but larger and larger subarrays, until eventually the entire array is merged and sorted. To avoid allocating many temporary array objects, it uses double-buffering with just two arrays. */ func mergeSortBottomUp<T>(a: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { let n = a.count var z = [a, a] // the two working arrays var d = 0 // z[d] is used for reading, z[1 - d] for writing var width = 1 while width < n { var i = 0 while i < n { var j = i var l = i var r = i + width let lmax = min(l + width, n) let rmax = min(r + width, n) while l < lmax && r < rmax { if isOrderedBefore(z[d][l], z[d][r]) { z[1 - d][j] = z[d][l] l += 1 } else { z[1 - d][j] = z[d][r] r += 1 } j += 1 } while l < lmax { z[1 - d][j] = z[d][l] j += 1 l += 1 } while r < rmax { z[1 - d][j] = z[d][r] j += 1 r += 1 } i += width*2 } width *= 2 // in each step, the subarray to merge becomes larger d = 1 - d // swap active array } return z[d] }
410e308f0fa3078f644000312b8ddf1e
24.185185
82
0.581985
false
false
false
false
JGiola/swift
refs/heads/main
test/Distributed/distributed_actor_isolation.swift
apache-2.0
4
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -verify-ignore-unknown -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed // TODO(distributed): rdar://82419661 remove -verify-ignore-unknown here, no warnings should be emitted for our // generated code but right now a few are, because of Sendability checks -- need to track it down more. import Distributed import FakeDistributedActorSystems @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- actor LocalActor_1 { let name: String = "alice" var mutable: String = "" distributed func nope() { // expected-error@-1{{'distributed' method can only be declared within 'distributed actor'}} } } struct NotCodableValue { } distributed actor DistributedActor_1 { let name: String = "alice" // expected-note{{access to property 'name' is only permitted within distributed actor 'DistributedActor_1'}} var mutable: String = "alice" // expected-note{{access to property 'mutable' is only permitted within distributed actor 'DistributedActor_1'}} var computedMutable: String { get { "hey" } set { _ = newValue } } distributed let letProperty: String = "" // expected-error{{property 'letProperty' cannot be 'distributed', only computed properties can}} distributed var varProperty: String = "" // expected-error{{property 'varProperty' cannot be 'distributed', only computed properties can}} distributed var computed: String { "computed" } distributed var computedNotCodable: NotCodableValue { // expected-error{{result type 'NotCodableValue' of distributed property 'computedNotCodable' does not conform to serialization requirement 'Codable'}} .init() } distributed var getSet: String { // expected-error{{'distributed' computed property 'getSet' cannot have setter}} get { "computed" } set { _ = newValue } } distributed static func distributedStatic() {} // expected-error{{'distributed' method cannot be 'static'}} distributed class func distributedClass() {} // expected-error@-1{{class methods are only allowed within classes; use 'static' to declare a static method}} // expected-error@-2{{'distributed' method cannot be 'static'}} func hello() {} // expected-note{{distributed actor-isolated instance method 'hello()' declared here}} func helloAsync() async {} // expected-note{{distributed actor-isolated instance method 'helloAsync()' declared here}} func helloAsyncThrows() async throws {} // expected-note{{distributed actor-isolated instance method 'helloAsyncThrows()' declared here}} distributed func distHello() { } // ok distributed func distHelloAsync() async { } // ok distributed func distHelloThrows() throws { } // ok distributed func distHelloAsyncThrows() async throws { } // ok distributed func distInt() async throws -> Int { 42 } // ok distributed func distInt(int: Int) async throws -> Int { int } // ok distributed func distIntString(int: Int, two: String) async throws -> (String) { "\(int) + \(two)" } // ok distributed func dist(notCodable: NotCodableValue) async throws { // expected-error@-1 {{parameter 'notCodable' of type 'NotCodableValue' in distributed instance method does not conform to serialization requirement 'Codable'}} } distributed func distBadReturn(int: Int) async throws -> NotCodableValue { // expected-error@-1 {{result type 'NotCodableValue' of distributed instance method 'distBadReturn' does not conform to serialization requirement 'Codable'}} fatalError() } distributed func varargs(int: Int...) { // expected-error@-1{{cannot declare variadic argument 'int' in distributed instance method 'varargs(int:)'}} } distributed func closure(close: () -> String) { // expected-error@-1{{parameter 'close' of type '() -> String' in distributed instance method does not conform to serialization requirement 'Codable'}} } distributed func noInout(inNOut burger: inout String) { // expected-error@-1{{cannot declare 'inout' argument 'burger' in distributed instance method 'noInout(inNOut:)'}}{{43-49=}} } distributed func distReturnGeneric<T: Codable & Sendable>(item: T) async throws -> T { // ok item } distributed func distReturnGenericWhere<T: Sendable>(item: Int) async throws -> T where T: Codable { // ok fatalError() } distributed func distBadReturnGeneric<T: Sendable>(int: Int) async throws -> T { // expected-error@-1 {{result type 'T' of distributed instance method 'distBadReturnGeneric' does not conform to serialization requirement 'Codable'}} fatalError() } distributed func distGenericParam<T: Codable & Sendable>(value: T) async throws { // ok fatalError() } distributed func distGenericParamWhere<T: Sendable>(value: T) async throws -> T where T: Codable { // ok value } distributed func distBadGenericParam<T: Sendable>(int: T) async throws { // expected-error@-1 {{parameter 'int' of type 'T' in distributed instance method does not conform to serialization requirement 'Codable'}} fatalError() } static func staticFunc() -> String { "" } // ok @MainActor static func staticMainActorFunc() -> String { "" } // ok static distributed func staticDistributedFunc() -> String { // expected-error@-1{{'distributed' method cannot be 'static'}}{10-21=} fatalError() } func test_inside() async throws { _ = self.name _ = self.computedMutable _ = try await self.distInt() _ = try await self.distInt(int: 42) self.hello() _ = await self.helloAsync() _ = try await self.helloAsyncThrows() self.distHello() await self.distHelloAsync() try self.distHelloThrows() try await self.distHelloAsyncThrows() // Hops over to the global actor. _ = await DistributedActor_1.staticMainActorFunc() } } func test_outside( local: LocalActor_1, distributed: DistributedActor_1 ) async throws { // ==== properties _ = distributed.id // ok distributed.id = ActorAddress(parse: "mock://1.1.1.1:8080/#123121") // expected-error{{cannot assign to property: 'id' is immutable}} _ = local.name // ok, special case that let constants are okey let _: String = local.mutable // ok, special case that let constants are okey _ = distributed.name // expected-error{{distributed actor-isolated property 'name' can not be accessed from a non-isolated context}} _ = distributed.mutable // expected-error{{distributed actor-isolated property 'mutable' can not be accessed from a non-isolated context}} // ==== special properties (nonisolated, implicitly replicated) // the distributed actor's special fields may always be referred to _ = distributed.id _ = distributed.actorSystem // ==== static functions _ = distributed.staticFunc() // expected-error{{static member 'staticFunc' cannot be used on instance of type 'DistributedActor_1'}} _ = DistributedActor_1.staticFunc() // ==== non-distributed functions distributed.hello() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} _ = await distributed.helloAsync() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} _ = try await distributed.helloAsyncThrows() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} } // ==== Protocols and static (non isolated functions) protocol P { static func hello() -> String } extension P { static func hello() -> String { "" } } distributed actor ALL: P { } // ==== Codable parameters and return types ------------------------------------ func test_params( distributed: DistributedActor_1 ) async throws { _ = try await distributed.distInt() // ok _ = try await distributed.distInt(int: 42) // ok _ = try await distributed.dist(notCodable: .init()) } // Actor initializer isolation (through typechecking only!) distributed actor DijonMustard { nonisolated init(system: FakeActorSystem) {} // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}} convenience init(conv: FakeActorSystem) { // expected-warning {{initializers in actors are not marked with 'convenience'; this is an error in Swift 6}}{{3-15=}} self.init(system: conv) self.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced from a non-isolated context}} } func f() {} // expected-note {{distributed actor-isolated instance method 'f()' declared here}} nonisolated init(conv2: FakeActorSystem) { // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}} self.init(system: conv2) } } // ==== Larger example with protocols and extensions --------------------------- protocol Greeting: DistributedActor { distributed func greeting() -> String distributed func greetingAsyncThrows() async throws -> String } extension Greeting { func greetLocal(name: String) async throws { // expected-note{{distributed actor-isolated instance method 'greetLocal(name:)' declared here}} try await print("\(greetingAsyncThrows()), \(name)!") // requirement is async throws, things work } func greetLocal2(name: String) { print("\(greeting()), \(name)!") } } extension Greeting where SerializationRequirement == Codable { // okay, uses Codable to transfer arguments. distributed func greetDistributed(name: String) async throws { // okay, we're on the actor try await greetLocal(name: name) } distributed func greetDistributed2(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } func greetDistributedNon(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } } extension Greeting where SerializationRequirement == Codable { nonisolated func greetAliceALot() async throws { try await greetLocal(name: "Alice") // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} } }
ce1e05eab925389086146563cd005481
39.814672
219
0.702677
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/SynthStyleKit.swift
mit
1
// // SynthStyleKit.swift // AnalogSynthX // // Created by Matthew Fecher on 1/9/16. // Copyright (c) 2016 AudioKit. All rights reserved. import UIKit public class SynthStyleKit : NSObject { //// Drawing Methods public class func drawKnobMedium(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob140_base = UIImage(named: "knob140_base.png")! let knob140_indicator = UIImage(named: "knob140_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// knob base Drawing let knobBasePath = UIBezierPath(rect: CGRectMake(5, 5, 70, 70)) CGContextSaveGState(context) knobBasePath.addClip() knob140_base.drawInRect(CGRectMake(5, 5, knob140_base.size.width, knob140_base.size.height)) CGContextRestoreGState(context) //// Indicator Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 40, 40) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let indicatorPath = UIBezierPath(rect: CGRectMake(-35, -35, 70, 70)) CGContextSaveGState(context) indicatorPath.addClip() knob140_indicator.drawInRect(CGRectMake(-35, -35, knob140_indicator.size.width, knob140_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } public class func drawKnobLarge(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob212_base = UIImage(named: "knob212_base.png")! let knob212_indicator = UIImage(named: "knob212_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// Picture Drawing let picturePath = UIBezierPath(rect: CGRectMake(10, 10, 106, 106)) CGContextSaveGState(context) picturePath.addClip() knob212_base.drawInRect(CGRectMake(10, 10, knob212_base.size.width, knob212_base.size.height)) CGContextRestoreGState(context) //// Picture 2 Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 63, 63) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let picture2Path = UIBezierPath(rect: CGRectMake(-53, -53, 106, 106)) CGContextSaveGState(context) picture2Path.addClip() knob212_indicator.drawInRect(CGRectMake(-53, -53, knob212_indicator.size.width, knob212_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } public class func drawKnobSmall(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob120_base = UIImage(named: "knob120_base.png")! let knob120_indicator = UIImage(named: "knob120_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// Picture Drawing let picturePath = UIBezierPath(rect: CGRectMake(5, 5, 60, 60)) CGContextSaveGState(context) picturePath.addClip() knob120_base.drawInRect(CGRectMake(5, 5, knob120_base.size.width, knob120_base.size.height)) CGContextRestoreGState(context) //// Indicator Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 35, 35) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let indicatorPath = UIBezierPath(rect: CGRectMake(-30, -30, 60, 60)) CGContextSaveGState(context) indicatorPath.addClip() knob120_indicator.drawInRect(CGRectMake(-30, -30, knob120_indicator.size.width, knob120_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } }
04aac6d9f28ad204c89ca881acb8bd48
35.927273
119
0.665682
false
false
false
false
shuuchen/Swift-Down-Video
refs/heads/master
source/VideoCollectionViewLayout.swift
mit
1
// // VideoCollectionViewLayout.swift // table_template // // Created by Shuchen Du on 2015/10/12. // Copyright (c) 2015年 Shuchen Du. All rights reserved. // import UIKit protocol PinterestLayoutDelegate { // 1 func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath, withWidth:CGFloat) -> CGFloat // 2 func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat } class VideoCollectionViewLayout: UICollectionViewLayout { // 1 var delegate: PinterestLayoutDelegate! // 2 var numberOfColumns = 2 var cellPadding: CGFloat = 6.0 // 3 private var cache = [UICollectionViewLayoutAttributes]() // 4 private var contentHeight: CGFloat = 0.0 private var contentWidth: CGFloat { let insets = collectionView!.contentInset return CGRectGetWidth(collectionView!.bounds) - (insets.left + insets.right) } }
760af1a5e3c16544079213f183ca682e
26.5
99
0.702392
false
false
false
false
AjaxXu/Everything
refs/heads/master
Gemini/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Disposable.swift
apache-2.0
22
// // Disposable.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-06-02. // Copyright (c) 2014 GitHub. All rights reserved. // /// Represents something that can be “disposed,” usually associated with freeing /// resources or canceling work. public protocol Disposable: class { /// Whether this disposable has been disposed already. var disposed: Bool { get } func dispose() } /// A disposable that only flips `disposed` upon disposal, and performs no other /// work. public final class SimpleDisposable: Disposable { private let _disposed = Atomic(false) public var disposed: Bool { return _disposed.value } public init() {} public func dispose() { _disposed.value = true } } /// A disposable that will run an action upon disposal. public final class ActionDisposable: Disposable { private let action: Atomic<(() -> Void)?> public var disposed: Bool { return action.value == nil } /// Initializes the disposable to run the given action upon disposal. public init(action: () -> Void) { self.action = Atomic(action) } public func dispose() { let oldAction = action.swap(nil) oldAction?() } } /// A disposable that will dispose of any number of other disposables. public final class CompositeDisposable: Disposable { private let disposables: Atomic<Bag<Disposable>?> /// Represents a handle to a disposable previously added to a /// CompositeDisposable. public final class DisposableHandle { private let bagToken: Atomic<RemovalToken?> private weak var disposable: CompositeDisposable? private static let empty = DisposableHandle() private init() { self.bagToken = Atomic(nil) } private init(bagToken: RemovalToken, disposable: CompositeDisposable) { self.bagToken = Atomic(bagToken) self.disposable = disposable } /// Removes the pointed-to disposable from its CompositeDisposable. /// /// This is useful to minimize memory growth, by removing disposables /// that are no longer needed. public func remove() { if let token = bagToken.swap(nil) { disposable?.disposables.modify { bag in guard var bag = bag else { return nil } bag.removeValueForToken(token) return bag } } } } public var disposed: Bool { return disposables.value == nil } /// Initializes a CompositeDisposable containing the given sequence of /// disposables. public init<S: SequenceType where S.Generator.Element == Disposable>(_ disposables: S) { var bag: Bag<Disposable> = Bag() for disposable in disposables { bag.insert(disposable) } self.disposables = Atomic(bag) } /// Initializes a CompositeDisposable containing the given sequence of /// disposables. public convenience init<S: SequenceType where S.Generator.Element == Disposable?>(_ disposables: S) { self.init(disposables.flatMap { $0 }) } /// Initializes an empty CompositeDisposable. public convenience init() { self.init([Disposable]()) } public func dispose() { if let ds = disposables.swap(nil) { for d in ds.reverse() { d.dispose() } } } /// Adds the given disposable to the list, then returns a handle which can /// be used to opaquely remove the disposable later (if desired). public func addDisposable(d: Disposable?) -> DisposableHandle { guard let d = d else { return DisposableHandle.empty } var handle: DisposableHandle? = nil disposables.modify { ds in guard var ds = ds else { return nil } let token = ds.insert(d) handle = DisposableHandle(bagToken: token, disposable: self) return ds } if let handle = handle { return handle } else { d.dispose() return DisposableHandle.empty } } /// Adds an ActionDisposable to the list. public func addDisposable(action: () -> Void) -> DisposableHandle { return addDisposable(ActionDisposable(action: action)) } } /// A disposable that, upon deinitialization, will automatically dispose of /// another disposable. public final class ScopedDisposable: Disposable { /// The disposable which will be disposed when the ScopedDisposable /// deinitializes. public let innerDisposable: Disposable public var disposed: Bool { return innerDisposable.disposed } /// Initializes the receiver to dispose of the argument upon /// deinitialization. public init(_ disposable: Disposable) { innerDisposable = disposable } deinit { dispose() } public func dispose() { innerDisposable.dispose() } } /// A disposable that will optionally dispose of another disposable. public final class SerialDisposable: Disposable { private struct State { var innerDisposable: Disposable? = nil var disposed = false } private let state = Atomic(State()) public var disposed: Bool { return state.value.disposed } /// The inner disposable to dispose of. /// /// Whenever this property is set (even to the same value!), the previous /// disposable is automatically disposed. public var innerDisposable: Disposable? { get { return state.value.innerDisposable } set(d) { let oldState = state.modify { state in var state = state state.innerDisposable = d return state } oldState.innerDisposable?.dispose() if oldState.disposed { d?.dispose() } } } /// Initializes the receiver to dispose of the argument when the /// SerialDisposable is disposed. public init(_ disposable: Disposable? = nil) { innerDisposable = disposable } public func dispose() { let orig = state.swap(State(innerDisposable: nil, disposed: true)) orig.innerDisposable?.dispose() } } /// Adds the right-hand-side disposable to the left-hand-side /// `CompositeDisposable`. /// /// disposable += producer /// .filter { ... } /// .map { ... } /// .start(observer) /// public func +=(lhs: CompositeDisposable, rhs: Disposable?) -> CompositeDisposable.DisposableHandle { return lhs.addDisposable(rhs) } /// Adds the right-hand-side `ActionDisposable` to the left-hand-side /// `CompositeDisposable`. /// /// disposable += { ... } /// public func +=(lhs: CompositeDisposable, rhs: () -> ()) -> CompositeDisposable.DisposableHandle { return lhs.addDisposable(rhs) }
8f79f2755d2e99e97b14015151cf79c0
23.41502
102
0.698721
false
false
false
false
stripe/stripe-ios
refs/heads/master
Tests/Tests/MKPlacemark+PaymentSheetTests.swift
mit
1
// // MKPlacemark+PaymentSheetTests.swift // StripeiOS Tests // // Created by Nick Porter on 6/13/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Contacts import MapKit import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class MKPlacemark_PaymentSheetTests: XCTestCase { // All address dictionaries are based on an actual placemark of an `MKLocalSearchCompletion` func testAsAddress_UnitedStates() { // Search string used to generate address dictionary: "4 Pennsylvania Pl" let addressDictionary = [ CNPostalAddressStreetKey: "4 Pennsylvania Plaza", CNPostalAddressStateKey: "NY", CNPostalAddressCountryKey: "United States", CNPostalAddressISOCountryCodeKey: "US", CNPostalAddressCityKey: "New York", "SubThoroughfare": "4", CNPostalAddressPostalCodeKey: "10001", "Thoroughfare": "Pennsylvania Plaza", CNPostalAddressSubLocalityKey: "Manhattan", CNPostalAddressSubAdministrativeAreaKey: "New York County", "Name": "4 Pennsylvania Plaza", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "New York", country: "US", line1: "4 Pennsylvania Plaza", line2: nil, postalCode: "10001", state: "NY" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Canada() { // Search string used to generate address dictionary: "40 Bay St To" let addressDictionary = [ CNPostalAddressStreetKey: "40 Bay St", CNPostalAddressStateKey: "ON", CNPostalAddressISOCountryCodeKey: "CA", CNPostalAddressCountryKey: "Canada", CNPostalAddressCityKey: "Toronto", "SubThoroughfare": "40", CNPostalAddressPostalCodeKey: "M5J 2X2", "Thoroughfare": "Bay St", CNPostalAddressSubLocalityKey: "Downtown Toronto", CNPostalAddressSubAdministrativeAreaKey: "SubAdministrativeArea", "Name": "40 Bay St", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Toronto", country: "CA", line1: "40 Bay St", line2: nil, postalCode: "M5J 2X2", state: "ON" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Germany() { // Search string used to generate address dictionary: "Rüsternallee 14" let addressDictionary = [ CNPostalAddressStreetKey: "Rüsternallee 14", CNPostalAddressISOCountryCodeKey: "DE", CNPostalAddressCountryKey: "Germany", CNPostalAddressCityKey: "Berlin", CNPostalAddressPostalCodeKey: "14050", "SubThoroughfare": "14", "Thoroughfare": "Rüsternallee", CNPostalAddressSubLocalityKey: "Charlottenburg-Wilmersdorf", CNPostalAddressSubAdministrativeAreaKey: "Berlin", "Name": "Rüsternallee 14", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Berlin", country: "DE", line1: "Rüsternallee 14", line2: nil, postalCode: "14050", state: nil ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Brazil() { // Search string used to generate address dictionary: "Avenida Paulista 500" let addressDictionary = [ CNPostalAddressStreetKey: "Avenida Paulista, 500", CNPostalAddressStateKey: "SP", CNPostalAddressISOCountryCodeKey: "BR", CNPostalAddressCountryKey: "Brazil", CNPostalAddressCityKey: "Paulínia", "SubThoroughfare": "500", CNPostalAddressPostalCodeKey: "13145-089", "Thoroughfare": "Avenida Paulista", CNPostalAddressSubLocalityKey: "Jardim Planalto", "Name": "Avenida Paulista, 500", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Paulínia", country: "BR", line1: "Avenida Paulista, 500", line2: nil, postalCode: "13145-089", state: "SP" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Japan() { // Search string used to generate address dictionary: "Nagatacho 2" let addressDictionary = [ CNPostalAddressStreetKey: "Nagatacho 2-Chōme", CNPostalAddressStateKey: "Tokyo", CNPostalAddressISOCountryCodeKey: "JP", CNPostalAddressCountryKey: "Japan", CNPostalAddressCityKey: "Chiyoda", "Thoroughfare": "Nagatacho 2-Chōme", CNPostalAddressSubLocalityKey: "Nagatacho", "Name": "Nagatacho 2-Chōme", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Chiyoda", country: "JP", line1: "Nagatacho 2-Chōme", line2: nil, postalCode: nil, state: "Tokyo" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Australia() { // Search string used to generate address dictionary: "488 George St Syd" let addressDictionary = [ CNPostalAddressStreetKey: "488 George St", CNPostalAddressStateKey: "NSW", CNPostalAddressISOCountryCodeKey: "AU", CNPostalAddressCountryKey: "Australia", CNPostalAddressCityKey: "Sydney", CNPostalAddressPostalCodeKey: "2000", "SubThoroughfare": "488", "Thoroughfare": "George St", CNPostalAddressSubAdministrativeAreaKey: "Sydney", "Name": "488 George St", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Sydney", country: "AU", line1: "488 George St", line2: nil, postalCode: "2000", state: "NSW" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } }
43e85c763be14b13c587a1c0bc7d2dec
35.784689
96
0.573881
false
true
false
false
omaarr90/healthcare
refs/heads/master
Sources/App/Models/Disease.swift
mit
1
import Vapor import Fluent import Foundation final class Disease: Model { var id: Node? var name: String // var doctors: Children<Doctor> // var symptoms: Children<Symptom> // var exists: Bool = false init(name: String) { self.id = nil //UUID().uuidString.makeNode() self.name = name // self.doctors = self.children(Doctor.self).all() // self.symptoms = symptoms } init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") // doctors = try node.extract("doctors") // symptoms = try node.extract("symptoms") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": name, // "doctors": self.c, // "symptoms": Node(node:symptoms) ]) } } extension Disease { static func mainDisease(symptos: [Int]) throws -> Disease { var mostFrequent = symptos[0] var counts = [Int: Int]() symptos.forEach { counts[$0] = (counts[$0] ?? 0) + 1 } if let (value, _) = counts.max(by: {$0.1 < $1.1}) { mostFrequent = value } return try Disease.find(mostFrequent)! } } extension Disease: Preparation { static func prepare(_ database: Database) throws { try database.create("diseases") { diseases in diseases.id() diseases.string("name") } } static func revert(_ database: Database) throws { try database.delete("diseases") } }
93d2385cac728a43eeb889e97909d9d2
23.880597
62
0.534493
false
false
false
false
adrfer/swift
refs/heads/master
test/decl/protocol/req/optional.swift
apache-2.0
2
// RUN: %target-parse-verify-swift // ----------------------------------------------------------------------- // Declaring optional requirements // ----------------------------------------------------------------------- @objc class ObjCClass { } @objc protocol P1 { optional func method(x: Int) // expected-note 2{{requirement 'method' declared here}} optional var prop: Int { get } // expected-note 2{{requirement 'prop' declared here}} optional subscript (i: Int) -> ObjCClass? { get } // expected-note 2{{requirement 'subscript' declared here}} } // ----------------------------------------------------------------------- // Providing witnesses for optional requirements // ----------------------------------------------------------------------- // One does not have provide a witness for an optional requirement class C1 : P1 { } // ... but it's okay to do so. class C2 : P1 { @objc func method(x: Int) { } @objc var prop: Int = 0 @objc subscript (c: ObjCClass) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // "Near" matches. // ----------------------------------------------------------------------- class C3 : P1 { func method(x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int = 0 // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C4 { } extension C4 : P1 { func method(x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int { return 5 } // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C5 : P1 { } extension C5 { func method(x: Int) { } var prop: Int { return 5 } subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C6 { } extension C6 : P1 { @nonobjc func method(x: Int) { } @nonobjc var prop: Int { return 5 } @nonobjc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // Using optional requirements // ----------------------------------------------------------------------- // Optional method references in generics. func optionalMethodGeneric<T : P1>(t: T) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .None // ... and that we can call it. methodRef!(5) } // Optional property references in generics. func optionalPropertyGeneric<T : P1>(t: T) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .None // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in generics. func optionalSubscriptGeneric<T : P1>(t: T) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .None // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // Optional method references in existentials. func optionalMethodExistential(t: P1) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .None // ... and that we can call it. methodRef!(5) } // Optional property references in existentials. func optionalPropertyExistential(t: P1) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .None // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in existentials. func optionalSubscriptExistential(t: P1) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .None // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // ----------------------------------------------------------------------- // Restrictions on the application of optional // ----------------------------------------------------------------------- // optional cannot be used on non-protocol declarations optional var optError: Int = 10 // expected-error{{'optional' can only be applied to protocol members}} optional struct optErrorStruct { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } optional class optErrorClass { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int = 0 // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } protocol optErrorProtocol { optional func foo(x: Int) // expected-error{{'optional' can only be applied to members of an @objc protocol}} optional associatedtype Assoc // expected-error{{'optional' modifier cannot be applied to this declaration}} {{3-12=}} } @objc protocol optionalInitProto { optional init() // expected-error{{'optional' cannot be applied to an initializer}} }
741c520328e4709399936bb56c8ad6d8
27.430622
126
0.581454
false
false
false
false
jmalesh/CareShare
refs/heads/master
CareShare/CareShare/TableViewCell.swift
mit
1
// // TableViewCell.swift // CareShare // // Created by Jess Malesh on 7/6/16. // Copyright © 2016 Jess Malesh. All rights reserved. // import UIKit import QuartzCore //protocol TableViewCellDelegate //{ // func medListItemDeleted(medListItem: MedListItem) //} class TableViewCell: UITableViewCell { let gradientLayer = CAGradientLayer() var originalCenter = CGPoint() var deleteOnDragRelease = false var delegate: TableViewCellDelegate? var medListItem: MedListItem? required init(coder aDecoder : NSCoder) { fatalError("NSCoding not supported") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) gradientLayer.frame = bounds let color1 = UIColor(white: 1.0, alpha: 0.2).CGColor as CGColorRef let color2 = UIColor(white: 1.0, alpha: 0.1).CGColor as CGColorRef let color3 = UIColor.clearColor().CGColor as CGColorRef let color4 = UIColor(white: 0.0, alpha: 0.1).CGColor as CGColorRef gradientLayer.colors = [color1, color2, color3, color4] gradientLayer.locations = [0.0, 0.01, 0.95, 1.0] layer.insertSublayer(gradientLayer, atIndex: 0) let recognizer = UIPanGestureRecognizer(target: self, action: "handlePan:") recognizer.delegate = self addGestureRecognizer(recognizer) } override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = bounds } func handlePan(recognizer: UIPanGestureRecognizer) { if recognizer.state == .Began { originalCenter = center } if recognizer.state == .Changed { let translation = recognizer.translationInView(self) center = CGPointMake(originalCenter.x + translation.x, originalCenter.y) deleteOnDragRelease = frame.origin.x < -frame.size.width / 2.0 } if recognizer.state == .Ended { let originalFrame = CGRect(x: 0, y: frame.origin.y, width: bounds.size.width, height: bounds.size.height) if !deleteOnDragRelease { UIView.animateWithDuration(0.2, animations: { self.frame = originalFrame}) } } if deleteOnDragRelease { if delegate != nil && medListItem != nil{ delegate!.medListItemDeleted(medListItem!) } } } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = panGestureRecognizer.translationInView(superview!) if fabs(translation.x) > fabs(translation.y) { return true } return false } return false } }
2e9032c8060749814c30e6bd83bbdb91
31.377778
117
0.63315
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dMaterialManager.swift
gpl-3.0
1
// // dMaterialManager.swift // DrakkenEngine // // Created by Allison Lindner on 23/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // internal class dMaterialTexture { internal var texture: dTexture internal var index: Int internal init(texture: dTexture, index: Int) { self.texture = texture self.index = index } } internal class dMaterialData { internal var shader: dShader internal var buffers: [dBufferable] = [] internal var textures: [dMaterialTexture] = [] internal init(shader: dShader) { self.shader = shader } } internal class dMaterialManager { private var _materials: [String : dMaterialData] = [:] internal func create(name: String, shader: String, buffers: [dBufferable], textures: [dMaterialTexture]) { let instancedShader = dCore.instance.shManager.get(shader: shader) let materialData = dMaterialData(shader: instancedShader) materialData.buffers = buffers materialData.textures = textures self._materials[name] = materialData } internal func get(material name: String) -> dMaterialData? { return self._materials[name] } }
e511be7e931360ee672acc35dc7051ab
22.64
68
0.684433
false
false
false
false
wscqs/QSWB
refs/heads/master
DSWeibo/DSWeibo/Classes/Home/User.swift
mit
1
// // User.swift // DSWeibo // // Created by xiaomage on 15/9/13. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit class User: NSObject { /// 用户ID var id: Int = 0 /// 友好显示名称 var name: String? /// 用户头像地址(中图),50×50像素 var profile_image_url: String?{ didSet{ if let urlStr = profile_image_url{ imageURL = NSURL(string: urlStr) } } } /// 用于保存用户头像的URL var imageURL: NSURL? /// 时候是认证, true是, false不是 var verified: Bool = false /// 用户的认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 var verified_type: Int = -1{ didSet{ switch verified_type { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2, 3, 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } } } /// 保存当前用户的认证图片 var verifiedImage: UIImage? /// 会员等级 var mbrank: Int = 0 { didSet{ if mbrank > 0 && mbrank < 7 { mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)") } } } var mbrankImage: UIImage? // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 打印当前模型 var properties = ["id", "name", "profile_image_url", "verified", "verified_type"] override var description: String { let dict = dictionaryWithValuesForKeys(properties) return "\(dict)" } }
c76135c74d567773d5ab0eb914efd2a4
21.95
85
0.514706
false
false
false
false
codefellows/sea-d34-iOS
refs/heads/master
Sample Code/Week 3/GithubToGo/GithubToGo/UserSearchViewController.swift
mit
1
// // UserSearchViewController.swift // GithubToGo // // Created by Bradley Johnson on 4/15/15. // Copyright (c) 2015 BPJ. All rights reserved. // import UIKit class UserSearchViewController: UIViewController,UICollectionViewDataSource, UISearchBarDelegate, UINavigationControllerDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! let imageFetchService = ImageFetchService() var users = [User]() override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.searchBar.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.delegate = self } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.delegate = nil } //MARK: UISeachBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() GithubService.sharedInstance.fetchUsersForSearch(searchBar.text, completionHandler: { (users, error) -> (Void) in self.users = users! self.collectionView.reloadData() }) } func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return text.validForURL() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.users.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as! UserCell cell.imageView.image = nil let user = self.users[indexPath.row] if user.avatarImage != nil { cell.imageView.image = user.avatarImage } else { self.imageFetchService.fetchImageForURL(user.avatarURL, imageViewSize: cell.imageView.frame.size, completionHandler: { (downloadedImage) -> (Void) in cell.imageView.alpha = 0 cell.imageView.transform = CGAffineTransformMakeScale(1.0, 1.0) user.avatarImage = downloadedImage cell.imageView.image = downloadedImage UIView.animateWithDuration(0.4, animations: { () -> Void in cell.imageView.alpha = 1 cell.imageView.transform = CGAffineTransformMakeScale(-2.0, -2.0) }) }) } return cell } func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if toVC is UserDetailViewController { return ToUserDetailAnimationController() } return nil } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowUser" { let destination = segue.destinationViewController as! UserDetailViewController let indexPath = self.collectionView.indexPathsForSelectedItems().first as! NSIndexPath let user = self.users[indexPath.row] destination.selectedUser = user } } }
b0978b3676bc0c3b9cb4c5b099146e5b
33.602041
279
0.729578
false
false
false
false
Daltron/BigBoard
refs/heads/master
Example/BigBoard/ExampleViewController.swift
mit
1
// // ViewController.swift // BigBoard // // Created by Dalton on 04/14/2016. // Copyright (c) 2016 Dalton. All rights reserved. // import UIKit class ExampleViewController: UIViewController, ExampleViewDelegate { var model:ExampleModel! var exampleView:ExampleView! init(){ super.init(nibName: nil, bundle: nil) edgesForExtendedLayout = UIRectEdge() model = ExampleModel() exampleView = ExampleView(delegate: self) view = exampleView title = "BigBoard" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addStockButtonPressed)) navigationItem.rightBarButtonItem?.tintColor = UIColor.white } func addStockButtonPressed() { let addStockController = ExampleAddStockViewController { (stock:BigBoardSearchResultStock) in print("Loading stock with symbol: \(stock.symbol!)") self.model.mapStockWithSymbol(symbol: stock.symbol!, success: { print("Stock successfully mapped.") print("--------------------------") self.exampleView.stocksTableView.reloadData() }, failure: { (error) in print(error) print("--------------------------") }) } navigationController?.pushViewController(addStockController, animated: true) } // MARK: ExampleViewDelegate Implementation func numberOfStocks() -> Int { return model.numberOfStocks() } func stockAtIndex(_ index: Int) -> BigBoardStock { return model.stockAtIndex(index) } func stockSelectedAtIndex(_ index:Int) { let exampleStockDetailsModel = ExampleStockDetailsModel(stock: model.stockAtIndex(index)) let exampleStockDetailsViewController = ExampleStockDetailsViewController(model: exampleStockDetailsModel) navigationController!.pushViewController(exampleStockDetailsViewController, animated: true) } func refreshControllPulled() { model.refreshStocks(success: { self.exampleView.refreshControl.endRefreshing() self.exampleView.stocksTableView.reloadData() }) { (error) in print(error) } } }
91318f41837ba6672db237ffee4e00a6
32.302632
142
0.634927
false
false
false
false
tomasharkema/HoelangTotTrein.iOS
refs/heads/develop
HoelangTotTrein/PickerViewController.swift
apache-2.0
1
// // PickerViewController.swift // HoelangTotTrein // // Created by Tomas Harkema on 15-02-15. // Copyright (c) 2015 Tomas Harkema. All rights reserved. // import UIKit import CoreLocation import Observable typealias SelectStationHandler = (Station) -> Void let PickerAnimationDuration = 0.5 class PickerViewController : UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pickerTitle: UILabel! @IBOutlet weak var searchView: UITextField! @IBOutlet weak var leftMarginSearchField: NSLayoutConstraint! @IBOutlet weak var headerView: UIView! @IBOutlet weak var pulldownIcon: UIImageView! var screenshotImageView:UIImageView! var backdropImageView:UIImageView! var backdrop: UIImage? var willDismiss:Bool = false var isDismissing:Bool = false var mode:StationType! { didSet { pickerTitle?.text = (mode == StationType.From) ? "Van" : "Naar" } } var currentStation:Station! { didSet { reload() } } var selectStationHandler:SelectStationHandler! var mostUsed = [Station]() var stations = [Station]() func reload() { { self.mostUsed = MostUsed.getListByVisited().slice(10) self.stations = TreinTicker.sharedInstance.stations.filter { [weak self] station in return (self?.mostUsed.contains(station) != nil) } } ~> { if let tv = self.tableView { tv.reloadData() self.selectRow() } } } /// MARK: View Lifecycle var locationUpdatedSubscription: EventSubscription<CLLocation>? = Optional.None; override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.clearColor() tableView.backgroundView = nil tableView.delegate = self tableView.dataSource = self backdropImageView = UIImageView(frame: view.bounds) view.insertSubview(backdropImageView, belowSubview: headerView) screenshotImageView = UIImageView(frame: view.bounds) view.insertSubview(screenshotImageView, belowSubview: backdropImageView) // set inital state backdropImageView.image = backdrop pickerTitle.text = (mode == StationType.From) ? "Van" : "Naar" searchView.delegate = self searchView.addTarget(self, action: Selector("textFieldDidChange:"), forControlEvents: UIControlEvents.EditingChanged) searchView.attributedPlaceholder = NSAttributedString(string: "Zoeken...", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor().colorWithAlphaComponent(0.3)]) headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9); backdropImageView.alpha = 0 self.stations = TreinTicker.sharedInstance.stations reload() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) locationUpdatedSubscription = TreinTicker.sharedInstance.locationUpdated += { [weak self] _ in self?.reload() return; } animateMenu(true, animated: true, completion: nil) } override func viewWillDisappear(animated: Bool) { locationUpdatedSubscription?.invalidate() } /// MARK: Show State Animations var showState:Bool = false func animateMenu(state:Bool, animated:Bool, completion:((Bool) -> Void)?) { let show = state if state { self.headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9); backdropImageView.alpha = 0 screenshotImageView.image = backdrop let blurImg = backdrop?.applyBlurWithRadius(20, tintColor: UIColor.clearColor(), saturationDeltaFactor: 1.0, maskImage: nil) backdropImageView.image = blurImg } let fase1:()->() = { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, 0.0), 0.9, 0.9) self.backdropImageView.alpha = 0.25 } let fase2:()->() = { if show { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, 0.0), 1.0, 1.0) self.backdropImageView.alpha = 1 } else { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9) self.backdropImageView.alpha = 0 } } let header:()->() = { self.headerView.transform = show ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) } if animated { UIView.animateKeyframesWithDuration(PickerAnimationDuration, delay: 0, options: UIViewKeyframeAnimationOptions.CalculationModeCubic | UIViewKeyframeAnimationOptions.AllowUserInteraction, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: fase1) UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: fase2) }, completion: completion) UIView.animateWithDuration(PickerAnimationDuration, animations: header) { if $0 { if !show { self.headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) self.backdropImageView.hidden = true } self.isDismissing = false } } } else { header() fase1() fase2() if let c = completion { c(true) } } } /// MARK: Table View Delegation func selectRow() { var indexPath:NSIndexPath? if let station = currentStation { if let index = findIndex(mostUsed, station) { indexPath = NSIndexPath(forRow: index, inSection: 0) } else if let index = findIndex(stations, station) { indexPath = NSIndexPath(forRow: index, inSection: 2) } if let ix = indexPath { if tableView.cellForRowAtIndexPath(ix) != nil { tableView.selectRowAtIndexPath(ix, animated: false, scrollPosition: UITableViewScrollPosition.Middle) } } } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var station:Station if indexPath.section == 0 { station = mostUsed[indexPath.row] } else if indexPath.section == 1 { station = TreinTicker.sharedInstance.closeStations[indexPath.row] } else if indexPath.section == 2 { station = stations[indexPath.row] } else { station = stationsFound()[indexPath.row] } var cell:PickerCellView = self.tableView.dequeueReusableCellWithIdentifier("cell") as! PickerCellView cell.station = station return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 4 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return !isInEditingState() ? mostUsed.count : 0 } else if section == 1 { return !isInEditingState() ? TreinTicker.sharedInstance.closeStations.count : 0 } else if section == 2 { return !isInEditingState() ? stations.count : 0 } else { return isInEditingState() ? stationsFound().count : 0 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cb = selectStationHandler { if indexPath.section == 0 { currentStation = mostUsed[indexPath.row] } else if indexPath.section == 1 { currentStation = TreinTicker.sharedInstance.closeStations[indexPath.row] } else if indexPath.section == 2 { currentStation = stations[indexPath.row] } else { currentStation = stationsFound()[indexPath.row] } searchView.resignFirstResponder() searchView.text = "" } dismissPicker() } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return isInEditingState() ? "" : (mostUsed.count == 0 ? "" : "Meest gebruikt") } else if section == 1 { return isInEditingState() ? "" : (TreinTicker.sharedInstance.closeStations.count == 0 ? "" : "Dichstbij") } else if section == 2 { return isInEditingState() ? "" : (stations.count == 0 ? "" : "A-Z") } return "" } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let headerView = view as! UITableViewHeaderFooterView headerView.textLabel.font = UIFont(name: "VarelaRound-Regular", size: 16.0) headerView.textLabel.textColor = UIColor.blackColor() headerView.contentView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8) headerView.backgroundView = nil } func textFieldDidBeginEditing(textField: UITextField) { UIView.animateWithDuration(0.2) { self.leftMarginSearchField.constant = -self.pickerTitle.bounds.width self.pickerTitle.alpha = 0 self.view.layoutIfNeeded() } } func textFieldDidEndEditing(textField: UITextField) { UIView.animateWithDuration(0.2) { self.leftMarginSearchField.constant = 16 self.pickerTitle.alpha = 1 self.view.layoutIfNeeded() } } func textFieldDidChange(textField:UITextField) { tableView.reloadData() } func stationsFound() -> [Station] { return stations.filter { ($0.name.lang.lowercaseString as NSString).containsString(self.searchView.text.lowercaseString) } } func isInEditingState() -> Bool { return searchView.text != "" } /// MARK: ScrollView Delegation func scrollViewDidScroll(scrollView: UIScrollView) { tableView.alpha = 1 pulldownIcon.alpha = 0 pulldownIcon.transform = CGAffineTransformIdentity if scrollView.contentOffset.y < 0 && !isDismissing { headerView.transform = CGAffineTransformMakeTranslation(0, scrollView.contentOffset.y/2) if scrollView.contentOffset.y < -50 { willDismiss = true scrollView.transform = CGAffineTransformMakeTranslation(0, 10) let progress = min(((-scrollView.contentOffset.y - 50) / 50)/4, 0.5) let scale = 1 - (0.25 * progress) tableView.transform = CGAffineTransformMakeScale(scale, scale) tableView.alpha = 1 - progress pulldownIcon.alpha = min(progress * 10, 1) let scalePulldown = min(progress * 10, 1) pulldownIcon.transform = CGAffineTransformMakeScale(scalePulldown, scalePulldown) } else { willDismiss = false scrollView.transform = CGAffineTransformIdentity } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if willDismiss { self.isDismissing = true dismissPicker() } } /// MARK: Button Delegation @IBAction func closeButton(sender: AnyObject) { if searchView.isFirstResponder() { searchView.text = "" searchView.endEditing(true) tableView.reloadData() } else { dismissPicker() } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func dismissPicker() { searchView.text = "" searchView.endEditing(true) searchView.resignFirstResponder() if let cb = selectStationHandler { cb(currentStation) willDismiss = false } animateMenu(false, animated: true) { _ in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { self.performSegueWithIdentifier("unwindPicker", sender: self) } //self.dismissViewControllerAnimated(true, completion: nil) return; } } }
063493380c33f9b6942c9312c655e474
31.89779
175
0.680914
false
false
false
false
LightD/ivsa-server
refs/heads/master
Sources/App/Middlewares/SessionAuthMiddleware.swift
mit
1
// // DelegatesSessionAuthMiddleware.swift // ivsa // // Created by Light Dream on 30/01/2017. // // import Foundation import HTTP import Vapor import Auth import TurnstileWeb final class SessionAuthMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { // check if the access token is valid guard let _ = try request.sessionAuth.user() else { throw "user wasn't found" } // authenticated and everything, perform the request return try next.respond(to: request) } catch { // if there's an error, we redirect to root page, and that one decides return Response(redirect: "/") } } } public final class SessionAuthHelper { let request: Request init(request: Request) { self.request = request } public var header: Authorization? { guard let authorization = request.headers["Authorization"] else { return nil } return Authorization(header: authorization) } func login(_ credentials: Credentials) throws -> IVSAUser { let user = try IVSAUser.authenticate(credentials: credentials) as! IVSAUser try request.session().data["user_id"] = user.id return user } func logout() throws { try request.session().destroy() } func user() throws -> IVSAUser? { let userId: String? = try request.session().data["user_id"]?.string guard let id = userId else { return nil } guard let user = try IVSAUser.find(id) else { return nil } return user } } extension Request { public var sessionAuth: SessionAuthHelper { let helper = SessionAuthHelper(request: self) return helper } }
33c7411ccb4c2f8127ea9b1025853dff
22.952381
86
0.562127
false
false
false
false
mattermost/ios
refs/heads/master
Mattermost/MattermostApi.swift
apache-2.0
1
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. import Foundation import UIKit protocol MattermostApiProtocol { func didRecieveResponse(_ result: JSON) func didRecieveError(_ message: String) } open class MattermostApi: NSObject { static let API_ROUTE_V4 = "/api/v4" static let API_ROUTE_V3 = "/api/v3" static let API_ROUTE = API_ROUTE_V4 var baseUrl = "" var data: NSMutableData = NSMutableData() var statusCode = 200 var delegate: MattermostApiProtocol? override init() { super.init() self.initBaseUrl() } func initBaseUrl() { let defaults = UserDefaults.standard let url = defaults.string(forKey: CURRENT_URL) if (url != nil && (url!).count > 0) { baseUrl = url! } } func getPing() { return getPing(versionRoute: MattermostApi.API_ROUTE) } func getPing(versionRoute: String) { var endpoint: String = baseUrl + versionRoute if (versionRoute == MattermostApi.API_ROUTE_V3) { endpoint += "/general/ping" } else { endpoint += "/system/ping" } print(endpoint) guard let url = URL(string: endpoint) else { print("Error cannot create URL") DispatchQueue.main.async { self.delegate?.didRecieveError("Invalid URL. Please check to make sure the URL is correct.") } return } let urlRequest = URLRequest(url: url) let session = URLSession.shared let task = session.dataTask(with: urlRequest) { (data, response, error) in var code = 0 if (response as? HTTPURLResponse) != nil { code = (response as! HTTPURLResponse).statusCode } guard error == nil else { print(error!) print("Error: statusCode=\(code) data=\(error!.localizedDescription)") DispatchQueue.main.async { self.delegate?.didRecieveError("\(error!.localizedDescription) [\(code)]") } return } guard let responseData = data else { print("Error: did not receive data") DispatchQueue.main.async { self.delegate?.didRecieveError("Did not receive data from the server.") } return } let json = JSON(data: responseData as Data) if (code == 200) { print("Found API version " + versionRoute) Utils.setProp(API_ROUTE_PROP, value: versionRoute) DispatchQueue.main.async { self.delegate?.didRecieveResponse(json) } } else if (code == 404) { print("Couldn't find V4 API falling back to V3") if (versionRoute != MattermostApi.API_ROUTE_V3) { return self.getPing(versionRoute: MattermostApi.API_ROUTE_V3) } else { DispatchQueue.main.async { self.delegate?.didRecieveError("Couldn't find the correct Mattermost server version.") } } } else { let datastring = NSString(data: responseData as Data, encoding: String.Encoding.utf8.rawValue) print("Error: statusCode=\(code) data=\(datastring!)") if let message = json["message"].string { DispatchQueue.main.async { self.delegate?.didRecieveError(message) } } else { DispatchQueue.main.async { self.delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured (-1)")) } } } } task.resume() } func attachDeviceId() { var endpoint: String = baseUrl + Utils.getProp(API_ROUTE_PROP) if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) { endpoint += "/users/attach_device" } else { endpoint += "/users/sessions/device" } print(endpoint) guard let url = URL(string: endpoint) else { print("Error cannot create URL") return } var urlRequest = URLRequest(url: url) if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) { urlRequest.httpMethod = "POST" } else { urlRequest.httpMethod = "PUT" } urlRequest.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With") urlRequest.httpBody = try! JSON(["device_id": "apple:" + Utils.getProp(DEVICE_TOKEN)]).rawData() let session = URLSession.shared let task = session.dataTask(with: urlRequest) { (data, response, error) in var code = 0 if (response as? HTTPURLResponse) != nil { code = (response as! HTTPURLResponse).statusCode } guard error == nil else { print(error!) print("Error: statusCode=\(code) data=\(error!.localizedDescription)") return } } task.resume() } func connection(_ connection: NSURLConnection!, didFailWithError error: NSError!) { statusCode = error.code print("Error: statusCode=\(statusCode) data=\(error.localizedDescription)") delegate?.didRecieveError("\(error.localizedDescription) [\(statusCode)]") } func connection(_ didReceiveResponse: NSURLConnection!, didReceiveResponse response: URLResponse!) { statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1 self.data = NSMutableData() let mmsid = Utils.getCookie(MATTERM_TOKEN) Utils.setProp(MATTERM_TOKEN, value: mmsid) print(mmsid) if (mmsid == "") { Utils.setProp(CURRENT_USER, value: "") Utils.setProp(MATTERM_TOKEN, value: "") } } func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace?) -> Bool { return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust } func connection(_ connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge?) { if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let credentials = URLCredential(trust: challenge!.protectionSpace.serverTrust!) challenge!.sender!.use(credentials, for: challenge!) } challenge?.sender!.continueWithoutCredential(for: challenge!) } func connection(_ connection: NSURLConnection!, didReceiveData data: Data!) { self.data.append(data) } func connectionDidFinishLoading(_ connection: NSURLConnection!) { let json = JSON(data: data as Data) if (statusCode == 200) { delegate?.didRecieveResponse(json) } else { let datastring = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) print("Error: statusCode=\(statusCode) data=\(datastring!)") if let message = json["message"].string { delegate?.didRecieveError(message) } else { delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured. (-1)")) } } } }
033bc7e9f72274a3fae4223f34a4537b
34.061135
134
0.547266
false
false
false
false
NUKisZ/MyTools
refs/heads/master
MyTools/MyTools/Tools/Const.swift
mit
1
// // Const.swift // MengWuShe // // Created by zhangk on 16/10/17. // Copyright © 2016年 zhangk. All rights reserved. // import UIKit public let kUserDefaults = UserDefaults.standard public let kScreenWidth = UIScreen.main.bounds.size.width //屏幕宽度 public let kScreenHeight = UIScreen.main.bounds.size.height //屏幕高度 public let kDeviceName = UIDevice.current.name //获取设备名称 例如:**的手机 public let kSysName = UIDevice.current.systemName //获取系统名称 例如:iPhone OS public let kSysVersion = UIDevice.current.systemVersion //获取系统版本 例如:9.2 public let kDeviceUUID = (UIDevice.current.identifierForVendor?.uuidString)! //获取设备唯一标识符 例如:FBF2306E-A0D8-4F4B-BDED-9333B627D3E6 public let kDeviceModel = UIDevice.current.model //获取设备的型号 例如:iPhone public let kInfoDic = Bundle.main.infoDictionary! as [String:Any] public let kAppVersion = (Bundle.main.infoDictionary?["CFBundleShortVersionString"])! // 获取App的版本 public let kAppBuildVersion = (Bundle.main.infoDictionary?["CFBundleVersion"])! // 获取App的build版本 public let kAppName = (Bundle.main.infoDictionary?["CFBundleDisplayName"])! // 获取App的名称 //var context = JSContext() //context = web?.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext? public let javaScriptContext = "documentView.webView.mainFrame.javaScriptContext" //微信相关 //获得access_token public let MWSGetAccessToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code" //测试access_token是否有效 public let MWSTestAccessToken = "https://api.weixin.qq.com/sns/auth?access_token=%@&openid=%@" //获得用户信息 public let MWSGetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@"
e6ed9267e9f4a32f0621ef6037322ec1
40.555556
139
0.694652
false
false
false
false
ramunasjurgilas/operation-queue-ios
refs/heads/master
operation-queue-ios/ViewControllers/PendingTasks/PendingTaskOperation.swift
mit
1
// // PendingTaskOperation.swift // operation-queue-ios // // Created by Ramunas Jurgilas on 2017-04-11. // Copyright © 2017 Ramūnas Jurgilas. All rights reserved. // import UIKit class PendingTaskOperation: Operation { var count = 0 let task: Task var executionStart = Date() var currentIteration = 0 var timer: Timer? init(pendingTask: Task) { task = pendingTask super.init() } override func start() { executionStart = Date() task.status = TaskStatus.executing.rawValue try? task.managedObjectContext?.save() isExecuting = true isFinished = false main() } override func main() { print("start on: -> " + Date().debugDescription) for i in currentIteration...30 { DispatchQueue.main.async { [weak self] in self?.task.duration = Int32((self?.executionStart.timeIntervalSinceNow)!) * -1 } currentIteration = i print("Iteration: \(currentIteration)") if isExecuting == false { // count = i print("Is executing: \(i.description) " + isExecuting.description) // isFinished = true return } sleep(1) } DispatchQueue.main.async { [weak self] in self?.task.status = TaskStatus.completed.rawValue self?.task.duration = Int32((self?.executionStart.timeIntervalSinceNow)!) * -1 try? self?.task.managedObjectContext?.save() } print("end " + Date().debugDescription) isFinished = true } func postpone() { timer?.invalidate() task.status = TaskStatus.postponed.rawValue print("Post pone: \(currentIteration)") isExecuting = false isFinished = false timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(resume), userInfo: nil, repeats: false) } func resume() { if task.status != TaskStatus.postponed.rawValue { print("Task is not postponed. Can not resume.") } timer?.invalidate() print("resume operaiton") DispatchQueue.main.async { [weak self] in self?.task.status = TaskStatus.executing.rawValue try? self?.task.managedObjectContext?.save() } DispatchQueue.global(qos: .default).async { [weak self] in self?.isExecuting = true self?.isFinished = false self?.main() } } fileprivate var _executing: Bool = false override var isExecuting: Bool { get { return _executing } set { if _executing != newValue { willChangeValue(forKey: "isExecuting") _executing = newValue didChangeValue(forKey: "isExecuting") } } } fileprivate var _finished: Bool = false; override var isFinished: Bool { get { return _finished } set { if _finished != newValue { willChangeValue(forKey: "isFinished") _finished = newValue didChangeValue(forKey: "isFinished") } } } }
18f15eb53e9c1e1af1640a7d3e93a421
29.172727
128
0.549563
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/Session/Modules/API Request/Sync/Sync+Stickers.swift
mit
1
// // MethodRequest+Stickers.swift // Pelican // // Created by Takanu Kyriako on 17/12/2017. // import Foundation /** This extension handles any kinds of operations involving stickers (including setting group sticker packs). */ extension MethodRequestSync { /** Returns a StickerSet type for the name of the sticker set given, if successful. */ public func getStickerSet(_ name: String) -> StickerSet? { let request = TelegramRequest.getStickerSet(name: name) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) } /** Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). */ public func uploadStickerFile(_ sticker: Sticker, userID: String) -> FileDownload? { guard let request = TelegramRequest.uploadStickerFile(userID: userID, sticker: sticker) else { PLog.error("Can't create uploadStickerFile request.") return nil } let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) } /** Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. */ @discardableResult public func createNewStickerSet(userID: String, name: String, title: String, sticker: Sticker, emojis: String, containsMasks: Bool? = nil, maskPosition: MaskPosition? = nil) -> Bool { let request = TelegramRequest.createNewStickerSet(userID: userID, name: name, title: title, sticker: sticker, emojis: emojis, containsMasks: containsMasks, maskPosition: maskPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Adds a sticker to a sticker set created by the bot. */ @discardableResult public func addStickerToSet(userID: String, name: String, pngSticker: Sticker, emojis: String, maskPosition: MaskPosition? = nil) -> Bool { let request = TelegramRequest.addStickerToSet(userID: userID, name: name, pngSticker: pngSticker, emojis: emojis, maskPosition: maskPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Use this method to move a sticker in a set created by the bot to a specific position. */ @discardableResult public func setStickerPositionInSet(stickerID: String, newPosition: Int) -> Bool { let request = TelegramRequest.setStickerPositionInSet(stickerID: stickerID, position: newPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Use this method to delete a sticker from a set created by the bot. */ @discardableResult public func deleteStickerFromSet(stickerID: String) -> Bool { let request = TelegramRequest.deleteStickerFromSet(stickerID: stickerID) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } }
fde43aa89129e37eb2d551c552ac97e8
32.161616
143
0.681084
false
false
false
false
caicai0/ios_demo
refs/heads/master
tableView/tableView/thirdPart/SnapKit/Constraint.swift
mit
1
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public final class Constraint { internal let sourceLocation: (String, UInt) internal let label: String? private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation private let multiplier: ConstraintMultiplierTarget private var constant: ConstraintConstantTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } private var priority: ConstraintPriorityTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } public var layoutConstraints: [LayoutConstraint] public var isActive: Bool { for layoutConstraint in self.layoutConstraints { if layoutConstraint.isActive { return true } } return false } // MARK: Initialization internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, sourceLocation: (String, UInt), label: String?, multiplier: ConstraintMultiplierTarget, constant: ConstraintConstantTarget, priority: ConstraintPriorityTarget) { self.from = from self.to = to self.relation = relation self.sourceLocation = sourceLocation self.label = label self.multiplier = multiplier self.constant = constant self.priority = priority self.layoutConstraints = [] // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from let layoutFrom = self.from.layoutConstraintItem! // get relation let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute: LayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { switch layoutFromAttribute { case .left: layoutToAttribute = .leftMargin case .right: layoutToAttribute = .rightMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .margins && self.to.attributes == .edges { switch layoutFromAttribute { case .leftMargin: layoutToAttribute = .left case .rightMargin: layoutToAttribute = .right case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { layoutToAttribute = layoutToAttributes[0] } } else { if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top } else { layoutToAttribute = layoutFromAttribute } } #else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else if layoutToAttributes.count > 0 { layoutToAttribute = layoutToAttributes[0] } else { layoutToAttribute = layoutFromAttribute } #endif // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to var layoutTo: AnyObject? = self.to.target // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) // set label layoutConstraint.label = self.label // set priority layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) // set constraint layoutConstraint.constraint = self // append self.layoutConstraints.append(layoutConstraint) } } // MARK: Public @available(*, deprecated:3.0, message:"Use activate().") public func install() { self.activate() } @available(*, deprecated:3.0, message:"Use deactivate().") public func uninstall() { self.deactivate() } public func activate() { self.activateIfNeeded() } public func deactivate() { self.deactivateIfNeeded() } @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } @discardableResult public func update(priority: ConstraintPriority) -> Constraint { self.priority = priority.value return self } @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() -> Void {} @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } // MARK: Internal internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) let requiredPriority = ConstraintPriority.required.value if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) } } } internal func activateIfNeeded(updatingExisting: Bool = false) { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints if updatingExisting { var existingLayoutConstraints: [LayoutConstraint] = [] for constraint in item.constraints { existingLayoutConstraints += constraint.layoutConstraints } for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) item.add(constraints: [self]) } } internal func deactivateIfNeeded() { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) item.remove(constraints: [self]) } }
bb731b4d7d8468f19cbc676356a175ec
39.559322
184
0.619056
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/develop
37--Resurgence/VenuesMenuQuadrat/Pods/QuadratTouch/Source/iOS/TouchAuthorizer.swift
cc0-1.0
3
// // TouchAuthorizer.swift // Quadrat // // Created by Constantine Fry on 12/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import UIKit class TouchAuthorizer : Authorizer { weak var presentingViewController: UIViewController? weak var delegate: SessionAuthorizationDelegate? var authorizationViewController: AuthorizationViewController? func authorize(viewController: UIViewController, delegate: SessionAuthorizationDelegate?, completionHandler: (String?, NSError?) -> Void) { authorizationViewController = AuthorizationViewController(authorizationURL: authorizationURL, redirectURL: redirectURL, delegate: self) authorizationViewController!.shouldControllNetworkActivityIndicator = shouldControllNetworkActivityIndicator let navigationController = AuthorizationNavigationController(rootViewController: authorizationViewController!) navigationController.modalPresentationStyle = .FormSheet delegate?.sessionWillPresentAuthorizationViewController?(authorizationViewController!) viewController.presentViewController(navigationController, animated: true, completion: nil) self.presentingViewController = viewController self.completionHandler = completionHandler self.delegate = delegate } override func finilizeAuthorization(accessToken: String?, error: NSError?) { if authorizationViewController != nil { delegate?.sessionWillDismissAuthorizationViewController?(authorizationViewController!) } presentingViewController?.dismissViewControllerAnimated(true) { self.didDismissViewController(accessToken, error: error) self.authorizationViewController = nil } } func didDismissViewController(accessToken: String?, error: NSError?) { super.finilizeAuthorization(accessToken, error: error) } }
6a8265b88ed3235fb54e8b714843e490
40.208333
118
0.744692
false
false
false
false
bascar2020/ios-truelinc
refs/heads/master
Pods/QRCodeReader.swift/Sources/QRCodeReaderView.swift
gpl-3.0
1
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.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 UIKit final class QRCodeReaderView: UIView, QRCodeReaderDisplayable { lazy var overlayView: UIView = { let ov = ReaderOverlayView() ov.backgroundColor = .clear ov.clipsToBounds = true ov.translatesAutoresizingMaskIntoConstraints = false return ov }() let cameraView: UIView = { let cv = UIView() cv.clipsToBounds = true cv.translatesAutoresizingMaskIntoConstraints = false return cv }() lazy var cancelButton: UIButton? = { let cb = UIButton() cb.translatesAutoresizingMaskIntoConstraints = false cb.setTitleColor(.gray, for: .highlighted) return cb }() lazy var switchCameraButton: UIButton? = { let scb = SwitchCameraButton() scb.translatesAutoresizingMaskIntoConstraints = false return scb }() lazy var toggleTorchButton: UIButton? = { let ttb = ToggleTorchButton() ttb.translatesAutoresizingMaskIntoConstraints = false return ttb }() func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool) { translatesAutoresizingMaskIntoConstraints = false addComponents() cancelButton?.isHidden = !showCancelButton switchCameraButton?.isHidden = !showSwitchCameraButton toggleTorchButton?.isHidden = !showTorchButton guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton else { return } let views = ["cv": cameraView, "ov": overlayView, "cb": cb, "scb": scb, "ttb": ttb] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views)) if showCancelButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views)) } else { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views)) } if showSwitchCameraButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views)) } if showTorchButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views)) } for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) { addConstraint(NSLayoutConstraint(item: overlayView, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0)) } } // MARK: - Convenience Methods private func addComponents() { addSubview(cameraView) addSubview(overlayView) if let scb = switchCameraButton { addSubview(scb) } if let ttb = toggleTorchButton { addSubview(ttb) } if let cb = cancelButton { addSubview(cb) } } }
ca3d24977b869e5157cda5b853542c11
33.469231
169
0.699397
false
false
false
false
PatrickChow/Swift-Awsome
refs/heads/master
News/Modules/Message/ViewController/MessagesListingViewController.swift
mit
1
// // Created by Patrick Chow on 2017/7/19. // Copyright (c) 2017 JIEMIAN. All rights reserved. import UIKit import Foundation import AsyncDisplayKit class MessagesListingViewController: ViewController { open lazy var tableNode: ASTableNode = { let instance = ASTableNode(style: .plain) instance.backgroundColor = UIColor.clear instance.delegate = self instance.dataSource = self instance.frame = self.view.bounds instance.view.separatorStyle = .singleLine instance.view.tableFooterView = UIView() instance.view.separatorInset = .zero instance.view.layoutMargins = .zero instance.view.nv.separatorColor(UIColor(hexNumber: 0xe8e8e8), night: UIColor(hexNumber: 0x4d4d4d)) if #available(iOS 9.0, *) { instance.view.cellLayoutMarginsFollowReadableWidth = false } return instance }() override func viewDidLoad() { super.viewDidLoad() title = "消息" view.addSubnode(tableNode) listingProvider.request(.messages("1")) .filterSuccessfulStatusCodes() .mapJSON() .subscribe { (event) in switch event { case let .next(response): print(response) case let .error(e): print(e) case .completed: print("完成") } } .disposed(by: disposeBag) } } extension MessagesListingViewController: ASTableDelegate, ASTableDataSource { func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return 10 } func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock { return { [weak self] () -> ASCellNode in let cellNode = MessagesListingNode("测试数据") return cellNode } } }
ef0feccbd58e28f18aa19dc5474fb845
27.911765
106
0.598169
false
false
false
false
avito-tech/Paparazzo
refs/heads/master
Paparazzo/Marshroute/PhotoLibrary/Assembly/PhotoLibraryMarshrouteAssemblyImpl.swift
mit
1
import UIKit import Marshroute public final class PhotoLibraryMarshrouteAssemblyImpl: BasePaparazzoAssembly, PhotoLibraryMarshrouteAssembly { public func module( selectedItems: [PhotoLibraryItem], maxSelectedItemsCount: Int?, routerSeed: RouterSeed, configure: (PhotoLibraryModule) -> () ) -> UIViewController { let photoLibraryItemsService = PhotoLibraryItemsServiceImpl() let interactor = PhotoLibraryInteractorImpl( selectedItems: selectedItems, maxSelectedItemsCount: maxSelectedItemsCount, photoLibraryItemsService: photoLibraryItemsService ) let router = PhotoLibraryMarshrouteRouter(routerSeed: routerSeed) let presenter = PhotoLibraryPresenter( interactor: interactor, router: router ) let viewController = PhotoLibraryViewController() viewController.addDisposable(presenter) viewController.setTheme(theme) presenter.view = viewController configure(presenter) return viewController } }
b29797af4ee18b423c99ab178f25c8e2
29.842105
110
0.651024
false
true
false
false
mpurland/Morpheus
refs/heads/master
Morpheus/CollectionDataSource.swift
bsd-3-clause
1
import UIKit import ReactiveCocoa public protocol CollectionDataSource: CollectionViewDataSource { var collectionView: UICollectionView { get } } public class CollectionModelDataSource<Model> { public typealias ReuseTransformer = Model -> ReuseIdentifier public typealias CellConfigurerTransformer = Model -> CollectionCellConfigurer<Model> public let collectionView: UICollectionView public let collectionModel: CollectionModel<Model> public let reuseTransformer: ReuseTransformer public let cellConfigurerTransformer: CellConfigurerTransformer init(collectionView otherCollectionView: UICollectionView, collectionModel otherCollectionModel: CollectionModel<Model>, reuseTransformer otherReuseTransformer: ReuseTransformer, cellConfigurerTransformer otherCellConfigurerTransformer: CellConfigurerTransformer) { collectionView = otherCollectionView collectionModel = otherCollectionModel reuseTransformer = otherReuseTransformer cellConfigurerTransformer = otherCellConfigurerTransformer } }
b0950288f760292bd776a9329faf68fd
45.608696
269
0.815299
false
true
false
false
Aazure/Mr-Ride-iOS
refs/heads/Doharmony
Advanced/Pods/Alamofire/Source/Validation.swift
agpl-3.0
173
// Validation.swift // // Copyright (c) 2014–2016 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 extension Request { /** Used to represent whether validation was successful or encountered an error resulting in a failure. - Success: The validation was successful. - Failure: The validation failed encountering the provided error. */ public enum ValidationResult { case Success case Failure(NSError) } /** A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid. */ public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult /** Validates the request, using the specified closure. If validation fails, subsequent calls to response handlers will have an associated error. - parameter validation: A closure to validate the request. - returns: The request. */ public func validate(validation: Validation) -> Self { delegate.queue.addOperationWithBlock { if let response = self.response where self.delegate.error == nil, case let .Failure(error) = validation(self.request, response) { self.delegate.error = error } } return self } // MARK: - Status Code /** Validates that the response has a status code in the specified range. If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self { return validate { _, response in if acceptableStatusCode.contains(response.statusCode) { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) } } } // MARK: - Content-Type private struct MIMEType { let type: String let subtype: String init?(_ string: String) { let components: [String] = { let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) return split.componentsSeparatedByString("/") }() if let type = components.first, subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(MIME: MIMEType) -> Bool { switch (type, subtype) { case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): return true default: return false } } } /** Validates that the response has a content type in the specified array. If validation fails, subsequent calls to response handlers will have an associated error. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - returns: The request. */ public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self { return validate { _, response in guard let validData = self.delegate.data where validData.length > 0 else { return .Success } if let responseContentType = response.MIMEType, responseMIMEType = MIMEType(responseContentType) { for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { return .Success } } } else { for contentType in acceptableContentTypes { if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { return .Success } } } let failureReason: String if let responseContentType = response.MIMEType { failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) } } // MARK: - Automatic /** Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field. If validation fails, subsequent calls to response handlers will have an associated error. - returns: The request. */ public func validate() -> Self { let acceptableStatusCodes: Range<Int> = 200..<300 let acceptableContentTypes: [String] = { if let accept = request?.valueForHTTPHeaderField("Accept") { return accept.componentsSeparatedByString(",") } return ["*/*"] }() return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) } }
bfc47b5e2b2e2365b52f1deca2883928
36.582011
127
0.617767
false
false
false
false
tjw/swift
refs/heads/master
test/IDE/complete_expr_postfix_begin.swift
apache-2.0
1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_3 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_4 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_5 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_6 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_3 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_1 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_2 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_2 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_3 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_4 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_5 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_6 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_7 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_SELECTOR_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_SELECTOR_1 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_1 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_2 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_3 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_4 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_5 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_SELECTOR_1 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_SELECTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_1 < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_2 > %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_2 < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NO_PLACEHOLDER_NAMES_1 | %FileCheck %s -check-prefix=NO_PLACEHOLDER_NAMES_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_3 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_5 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_6 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_7 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_8 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | %FileCheck %s -check-prefix=MY_ALIAS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | %FileCheck %s -check-prefix=MY_ALIAS_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_1 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_2 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_3 | %FileCheck %s -check-prefix=IN_FOR_EACH_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_4 | %FileCheck %s -check-prefix=IN_FOR_EACH_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_5 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_6 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_7 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_8 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_9 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_10 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_11 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_12 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DEPRECATED_1 | %FileCheck %s -check-prefix=DEPRECATED_1 // // Test code completion at the beginning of expr-postfix. // //===--- Helper types that are used in this test struct FooStruct { } var fooObject : FooStruct func fooFunc() -> FooStruct { return fooObject } enum FooEnum { } class FooClass { } protocol FooProtocol { } typealias FooTypealias = Int // COMMON: Begin completions // Function parameter // COMMON-DAG: Decl[LocalVar]/Local: fooParam[#FooStruct#]{{; name=.+$}} // Global completions // COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // COMMON-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}} // COMMON-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}} // COMMON-DAG: Decl[Protocol]/CurrModule: FooProtocol[#FooProtocol#]{{; name=.+$}} // COMMON-DAG: Decl[TypeAlias]/CurrModule: FooTypealias[#Int#]{{; name=.+$}} // COMMON-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // COMMON-DAG: Keyword[try]/None: try{{; name=.+$}} // COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}} // COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}} // COMMON-DAG: Literal[Nil]/None: nil{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int8[#Int8#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int16[#Int16#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int32[#Int32#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int64[#Int64#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Bool[#Bool#]{{; name=.+$}} // COMMON-DAG: Keyword[#function]/None: #function[#String#]{{; name=.+$}} // COMMON-DAG: Keyword[#file]/None: #file[#String#]{{; name=.+$}} // COMMON-DAG: Keyword[#line]/None: #line[#Int#]{{; name=.+$}} // COMMON-DAG: Keyword[#column]/None: #column[#Int#]{{; name=.+$}} // COMMON: End completions // NO_SELF-NOT: Self // NO_SELF-NOT: self //===--- Test that we can code complete at the beginning of expr-postfix. func testExprPostfixBegin1(fooParam: FooStruct) { #^EXPR_POSTFIX_BEGIN_1^# } func testExprPostfixBegin2(fooParam: FooStruct) { 1 + #^EXPR_POSTFIX_BEGIN_2^# } func testExprPostfixBegin3(fooParam: FooStruct) { fooFunc() 1 + #^EXPR_POSTFIX_BEGIN_3^# } func testExprPostfixBegin4(fooParam: FooStruct) { "\(#^EXPR_POSTFIX_BEGIN_4^#)" } func testExprPostfixBegin3(fooParam: FooStruct) { 1+#^EXPR_POSTFIX_BEGIN_5^# } func testExprPostfixBegin3(fooParam: FooStruct) { for i in 1...#^EXPR_POSTFIX_BEGIN_6^# } //===--- Test that we sometimes ignore the expr-postfix. // In these cases, displaying '.instance*' completion results is technically // valid, but would be extremely surprising. func testExprPostfixBeginIgnored1(fooParam: FooStruct) { fooFunc() #^EXPR_POSTFIX_BEGIN_IGNORED_1^# } func testExprPostfixBeginIgnored2(fooParam: FooStruct) { 123456789 #^EXPR_POSTFIX_BEGIN_IGNORED_2^# } func testExprPostfixBeginIgnored3(fooParam: FooStruct) { 123456789 + fooFunc() #^EXPR_POSTFIX_BEGIN_IGNORED_3^# } //===--- Test that we include function parameters in completion results. func testFindFuncParam1(fooParam: FooStruct, a: Int, b: Float, c: inout Double, d: inout Double) { #^FIND_FUNC_PARAM_1^# // FIND_FUNC_PARAM_1: Begin completions // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: c[#inout Double#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: d[#inout Double#]{{; name=.+$}} // FIND_FUNC_PARAM_1: End completions } func testFindFuncParam2<Foo : FooProtocol>(fooParam: FooStruct, foo: Foo) { #^FIND_FUNC_PARAM_2^# // FIND_FUNC_PARAM_2: Begin completions // FIND_FUNC_PARAM_2-DAG: Decl[GenericTypeParam]/Local: Foo[#Foo#]{{; name=.+$}} // FIND_FUNC_PARAM_2-DAG: Decl[LocalVar]/Local: foo[#FooProtocol#]{{; name=.+$}} // FIND_FUNC_PARAM_2: End completions } struct TestFindFuncParam3_4 { func testFindFuncParam3(a: Int, b: Float, c: Double) { #^FIND_FUNC_PARAM_3^# // FIND_FUNC_PARAM_3: Begin completions // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}} // FIND_FUNC_PARAM_3: End completions } func testFindFuncParam4<U>(a: Int, b: U) { #^FIND_FUNC_PARAM_4^# // FIND_FUNC_PARAM_4: Begin completions // FIND_FUNC_PARAM_4-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_4: End completions } } struct TestFindFuncParam5_6<T> { func testFindFuncParam5(a: Int, b: T) { #^FIND_FUNC_PARAM_5^# // FIND_FUNC_PARAM_5: Begin completions // FIND_FUNC_PARAM_5-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_5: End completions } func testFindFuncParam6<U>(a: Int, b: T, c: U) { #^FIND_FUNC_PARAM_6^# // FIND_FUNC_PARAM_6: Begin completions // FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_6: End completions } } class TestFindFuncParam7 { func testFindFuncParam7(a: Int, b: Float, c: Double) { #^FIND_FUNC_PARAM_7^# // FIND_FUNC_PARAM_7: Begin completions // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam7#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}} // FIND_FUNC_PARAM_7: End completions } } func testFindFuncParamSelector1(a: Int, b x: Float, foo fooParam: FooStruct, bar barParam: inout FooStruct) { #^FIND_FUNC_PARAM_SELECTOR_1^# // FIND_FUNC_PARAM_SELECTOR_1: Begin completions // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: barParam[#inout FooStruct#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1: End completions } //===--- Test that we include constructor parameters in completion results. class TestFindConstructorParam1 { init(a: Int, b: Float) { #^FIND_CONSTRUCTOR_PARAM_1^# // FIND_CONSTRUCTOR_PARAM_1: Begin completions // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam1#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1: End completions } } struct TestFindConstructorParam2 { init(a: Int, b: Float) { #^FIND_CONSTRUCTOR_PARAM_2^# // FIND_CONSTRUCTOR_PARAM_2: Begin completions // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam2#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2: End completions } } class TestFindConstructorParam3 { init<U>(a: Int, b: U) { #^FIND_CONSTRUCTOR_PARAM_3^# // FIND_CONSTRUCTOR_PARAM_3: Begin completions // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam3#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3: End completions } } class TestFindConstructorParam4<T> { init(a: Int, b: T) { #^FIND_CONSTRUCTOR_PARAM_4^# // FIND_CONSTRUCTOR_PARAM_4: Begin completions // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam4<T>#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4: End completions } } class TestFindConstructorParam5<T> { init<U>(a: Int, b: T, c: U) { #^FIND_CONSTRUCTOR_PARAM_5^# // FIND_CONSTRUCTOR_PARAM_5: Begin completions // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam5<T>#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5: End completions } } class TestFindConstructorParamSelector1 { init(a x: Int, b y: Float) { #^FIND_CONSTRUCTOR_PARAM_SELECTOR_1^# // FIND_CONSTRUCTOR_PARAM_SELECTOR_1: Begin completions // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParamSelector1#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: y[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1: End completions } } //===--- Test that we include destructor's 'self' in completion results. class TestFindDestructorParam1 { deinit { #^FIND_DESTRUCTOR_PARAM_1^# // FIND_DESTRUCTOR_PARAM_1: Begin completions // FIND_DESTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam1#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_1: End completions } } class TestFindDestructorParam2<T> { deinit { #^FIND_DESTRUCTOR_PARAM_2^# // FIND_DESTRUCTOR_PARAM_2: Begin completions // FIND_DESTRUCTOR_PARAM_2-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam2<T>#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_2: End completions } } struct TestPlaceholdersInNames { var <#placeholder_in_name1#>: FooStruct func test() { var <#placeholder_in_name2#>: FooStruct #^NO_PLACEHOLDER_NAMES_1^# } // NO_PLACEHOLDER_NAMES_1-NOT: placeholder_in_name } //===--- Test that we don't crash in constructors and destructors in contexts //===--- where they are not allowed. init() { var fooParam = FooStruct() #^IN_INVALID_1^# } init { // Missing parameters var fooParam = FooStruct() #^IN_INVALID_2^# } deinit { var fooParam = FooStruct() #^IN_INVALID_3^# } func testInInvalid5() { var fooParam = FooStruct() init() { #^IN_INVALID_5^# } } func testInInvalid6() { deinit { var fooParam = FooStruct() #^IN_INVALID_6^# } } struct TestInInvalid7 { deinit { var fooParam = FooStruct() #^IN_INVALID_7^# } } func foo() -> Undeclared { var fooParam = FooStruct() #^IN_INVALID_8^# } // MY_ALIAS_1: Decl[TypeAlias]/Local: MyAlias[#(T, T)#]; // MY_ALIAS_1: Decl[LocalVar]/Local/TypeRelation[Identical]: x[#MyAlias<Int>#]; name=x // MY_ALIAS_1: Decl[LocalVar]/Local/TypeRelation[Identical]: y[#(Int, Int)#]; name=y func testGenericTypealias1() { typealias MyAlias<T> = (T, T) let x: MyAlias<Int> = (1, 2) var y: (Int, Int) y = #^GENERIC_TYPEALIAS_1^# } // MY_ALIAS_2: Decl[TypeAlias]/Local: MyAlias[#(T, T)#]; // MY_ALIAS_2: Decl[LocalVar]/Local/TypeRelation[Identical]: x[#(Int, Int)#]; name=x // MY_ALIAS_2: Decl[LocalVar]/Local/TypeRelation[Identical]: y[#MyAlias<Int>#]; name=y func testGenericTypealias2() { typealias MyAlias<T> = (T, T) let x: (Int, Int) = (1, 2) var y: MyAlias<Int> y = #^GENERIC_TYPEALIAS_2^# } func testInForEach1(arg: Int) { let local = 2 for index in #^IN_FOR_EACH_1^# { let inBody = 3 } let after = 4 // IN_FOR_EACH_1-NOT: Decl[LocalVar] // IN_FOR_EACH_1: Decl[LocalVar]/Local: local[#Int#]; // FIXME: shouldn't show 'after' here. // IN_FOR_EACH_1: Decl[LocalVar]/Local: after[#Int#]; // IN_FOR_EACH_1: Decl[LocalVar]/Local: arg[#Int#]; // IN_FOR_EACH_1-NOT: Decl[LocalVar] } func testInForEach2(arg: Int) { let local = 2 for index in 1 ... #^IN_FOR_EACH_2^# { let inBody = 3 } let after = 4 } func testInForEach3(arg: Int) { let local = 2 for index: Int in 1 ... 2 where #^IN_FOR_EACH_3^# { let inBody = 3 } let after = 4 // IN_FOR_EACH_3-NOT: Decl[LocalVar] // IN_FOR_EACH_3: Decl[LocalVar]/Local: index[#Int#]; // IN_FOR_EACH_3-NOT: Decl[LocalVar] // IN_FOR_EACH_3: Decl[LocalVar]/Local: local[#Int#]; // FIXME: shouldn't show 'after' here. // IN_FOR_EACH_3: Decl[LocalVar]/Local: after[#Int#]; // IN_FOR_EACH_3: Decl[LocalVar]/Local: arg[#Int#]; // IN_FOR_EACH_3-NOT: Decl[LocalVar] } func testInForEach4(arg: Int) { let local = 2 for index in 1 ... 2 { #^IN_FOR_EACH_4^# } let after = 4 } func testInForEach5(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_5^#] {} let after = 4 } func testInForEach6(arg: Int) { let local = 2 for index in [1,#^IN_FOR_EACH_6^#] {} let after = 4 } func testInForEach7(arg: Int) { let local = 2 for index in [1:#^IN_FOR_EACH_7^#] {} let after = 4 } func testInForEach8(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_8^#:] {} let after = 4 } func testInForEach9(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_9^#:2] {} let after = 4 } func testInForEach10(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_10^#] {} let after = 4 } func testInForEach11(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_11^#:] {} let after = 4 } func testInForEach12(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_12^#:2] {} let after = 4 } @available(*, deprecated) struct Deprecated { @available(*, deprecated) func testDeprecated() { @available(*, deprecated) let local = 1 @available(*, deprecated) func f() {} #^DEPRECATED_1^# } } // DEPRECATED_1: Begin completions // DEPRECATED_1-DAG: Decl[LocalVar]/Local/NotRecommended: local[#Int#]; // DEPRECATED_1-DAG: Decl[FreeFunction]/Local/NotRecommended: f()[#Void#]; // DEPRECATED_1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: testDeprecated()[#Void#]; // DEPRECATED_1-DAG: Decl[Struct]/CurrModule/NotRecommended: Deprecated[#Deprecated#]; // DEPRECATED_1: End completions
c6408b91aa5033328160dc751580f5bb
43.918406
188
0.678143
false
true
false
false
movielala/VideoThumbnailViewKit
refs/heads/master
VideoThumbnailViewKit/VideoThumbnailView/VideoThumbnailView.swift
mit
2
// // VideoThumbnailView.swift // VideoThumbnailView // // Created by Toygar Dundaralp on 9/29/15. // Copyright (c) 2015 Toygar Dundaralp. All rights reserved. // import UIKit import AVFoundation public class VideoThumbnailView: UIView { private var videoScroll = UIScrollView() private var thumImageView = UIImageView() private var arrThumbViews = NSMutableArray() private var scrollContentWidth = 0.0 private var videoURL = NSURL() private var videoDuration = 0.0 private var activityIndicator = UIActivityIndicatorView() init(frame: CGRect, videoURL url: NSURL, thumbImageWidth thumbWidth: Double) { super.init(frame: frame) self.videoURL = url self.videoDuration = self.getVideoTime(url) activityIndicator = UIActivityIndicatorView( frame: CGRect( x: self.center.x - 15, y: self.frame.size.height / 2 - 15, width: 30.0, height: 30.0)) activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = .White activityIndicator.startAnimating() addSubview(self.activityIndicator) videoScroll = UIScrollView( frame: CGRect( x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)) videoScroll.showsHorizontalScrollIndicator = false videoScroll.showsVerticalScrollIndicator = false videoScroll.bouncesZoom = false videoScroll.bounces = false self.addSubview(videoScroll) self.thumbImageProcessing( videoUrl: videoURL, thumbWidth: thumbWidth) { (thumbImages, error) -> Void in // println(thumbImages) } self.layer.masksToBounds = true } private func thumbImageProcessing( videoUrl url: NSURL, thumbWidth: Double, completion: ((thumbImages: NSMutableArray?, error: NSError?) -> Void)?) { let priority = DISPATCH_QUEUE_PRIORITY_HIGH dispatch_async(dispatch_get_global_queue(priority, 0)) { for index in 0...Int(self.videoDuration) { let thumbXCoords = Double(index) * thumbWidth self.thumImageView = UIImageView( frame: CGRect( x: thumbXCoords, y: 0.0, width: thumbWidth, height: Double(self.frame.size.height))) self.thumImageView.contentMode = .ScaleAspectFit self.thumImageView.backgroundColor = UIColor.clearColor() self.thumImageView.layer.borderColor = UIColor.grayColor().CGColor self.thumImageView.layer.borderWidth = 0.25 self.thumImageView.tag = index self.thumImageView.image = self.generateVideoThumbs( self.videoURL, second: Double(index), thumbWidth: thumbWidth) self.scrollContentWidth = self.scrollContentWidth + thumbWidth self.videoScroll.addSubview(self.thumImageView) self.videoScroll.sendSubviewToBack(self.thumImageView) if let imageView = self.thumImageView as UIImageView? { self.arrThumbViews.addObject(imageView) } } self.videoScroll.contentSize = CGSize( width: Double(self.scrollContentWidth), height: Double(self.frame.size.height)) self.activityIndicator.stopAnimating() completion?(thumbImages: self.arrThumbViews, error: nil) self.videoScroll.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true) } } private func getVideoTime(url: NSURL) -> Float64 { let videoTime = AVURLAsset(URL: url, options: nil) return CMTimeGetSeconds(videoTime.duration) } private func generateVideoThumbs(url: NSURL, second: Float64, thumbWidth: Double) -> UIImage { let asset = AVURLAsset(URL: url, options: nil) let generator = AVAssetImageGenerator(asset: asset) generator.maximumSize = CGSize(width: thumbWidth, height: Double(self.frame.size.height)) generator.appliesPreferredTrackTransform = false let thumbTime = CMTimeMakeWithSeconds(second, 1) do { let ref = try generator.copyCGImageAtTime(thumbTime, actualTime: nil) return UIImage(CGImage: ref) }catch { print(error) } return UIImage() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
a424134c4a68e73cf101f3ba6353d94a
34.108333
96
0.690007
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/minimum-moves-to-equal-array-elements-ii.swift
mit
2
/** * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ * * */ class Solution { func minMoves2(_ nums: [Int]) -> Int { let n = nums.count if n == 0 { return 0 } let list = nums.sorted() let med = list[n/2] var total = 0 for n in list { total += abs(n - med) } return total } } /** * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-i/ * * */ // Date: Wed May 19 08:51:03 PDT 2021 class Solution { func minMoves2(_ nums: [Int]) -> Int { let nums = nums.sorted() let n = nums.count let med = nums[n / 2] let costL = nums.reduce(0) { $0 + abs($1 - med) } return costL } }
b8dbc03de73999a44e5fff857587b6ac
21.176471
74
0.513263
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripeFinancialConnections/StripeFinancialConnectionsTests/FinancialConnectionsSheetTests.swift
mit
1
// // FinancialConnectionsSheetTests.swift // StripeFinancialConnectionsTests // // Created by Vardges Avetisyan on 11/9/21. // import XCTest @testable import StripeFinancialConnections @_spi(STP) import StripeCore @_spi(STP) import StripeCoreTestUtils class EmptyFinancialConnectionsAPIClient: FinancialConnectionsAPIClient { func fetchFinancialConnectionsAccounts(clientSecret: String, startingAfterAccountId: String?) -> Promise<StripeAPI.FinancialConnectionsSession.AccountList> { return Promise<StripeAPI.FinancialConnectionsSession.AccountList>() } func fetchFinancialConnectionsSession(clientSecret: String) -> Promise<StripeAPI.FinancialConnectionsSession> { return Promise<StripeAPI.FinancialConnectionsSession>() } func generateSessionManifest(clientSecret: String, returnURL: String?) -> Promise<FinancialConnectionsSessionManifest> { return Promise<FinancialConnectionsSessionManifest>() } } class EmptySessionFetcher: FinancialConnectionsSessionFetcher { func fetchSession() -> Future<StripeAPI.FinancialConnectionsSession> { return Promise<StripeAPI.FinancialConnectionsSession>() } } class FinancialConnectionsSheetTests: XCTestCase { private let mockViewController = UIViewController() private let mockClientSecret = "las_123345" private let mockAnalyticsClient = MockAnalyticsClient() override func setUpWithError() throws { mockAnalyticsClient.reset() } func testAnalytics() { let sheet = FinancialConnectionsSheet(financialConnectionsSessionClientSecret: mockClientSecret, returnURL: nil, analyticsClient: mockAnalyticsClient) sheet.present(from: mockViewController) { _ in } // Verify presented analytic is logged XCTAssertEqual(mockAnalyticsClient.loggedAnalytics.count, 1) guard let presentedAnalytic = mockAnalyticsClient.loggedAnalytics.first as? FinancialConnectionsSheetPresentedAnalytic else { return XCTFail("Expected `FinancialConnectionsSheetPresentedAnalytic`") } XCTAssertEqual(presentedAnalytic.clientSecret, mockClientSecret) // Mock that financialConnections is completed let host = HostController(api: EmptyFinancialConnectionsAPIClient(), clientSecret: "test", returnURL: nil) sheet.hostController(host, viewController: UIViewController(), didFinish: .canceled) // Verify closed analytic is logged XCTAssertEqual(mockAnalyticsClient.loggedAnalytics.count, 2) guard let closedAnalytic = mockAnalyticsClient.loggedAnalytics.last as? FinancialConnectionsSheetClosedAnalytic else { return XCTFail("Expected `FinancialConnectionsSheetClosedAnalytic`") } XCTAssertEqual(closedAnalytic.clientSecret, mockClientSecret) XCTAssertEqual(closedAnalytic.result, "cancelled") } func testAnalyticsProductUsage() { let _ = FinancialConnectionsSheet(financialConnectionsSessionClientSecret: mockClientSecret, returnURL: nil, analyticsClient: mockAnalyticsClient) XCTAssertEqual(mockAnalyticsClient.productUsage, ["FinancialConnectionsSheet"]) } }
2aad526b0c01d171a8cfa1ee93d1b390
44.114286
161
0.770108
false
true
false
false
Ramesh-P/virtual-tourist
refs/heads/master
Virtual Tourist/FlickrAPIConstants.swift
mit
1
// // FlickrAPIConstants.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 3/2/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation // MARK: FlickrAPIConstants struct Flickr { // MARK: URLs struct Constants { static let apiScheme = "https" static let apiHost = "api.flickr.com" static let apiPath = "/services/rest" } // MARK: Bounding Box struct BoundingBox { static let halfWidth = 1.0 static let halfHeight = 1.0 static let latitudeRange = (-90.0, 90.0) static let longitudeRange = (-180.0, 180.0) } // MARK: Flickr Parameter Keys struct ParameterKeys { static let method = "method" static let apiKey = "api_key" static let sort = "sort" static let boundingBox = "bbox" static let search = "safe_search" static let contentType = "content_type" static let media = "media" static let extras = "extras" static let photosPerPage = "per_page" static let format = "format" static let noJSONCallback = "nojsoncallback" } // MARK: Flickr Parameter Values struct ParameterValues { static let photosSearch = "flickr.photos.search" static let apiKey = "6ebf6fc89a59ca7d25b46f895d25ab0e" static let datePostedAsc = "date-posted-asc" static let datePostedDesc = "date-posted-desc" static let dateTakenAsc = "date-taken-asc" static let dateTakenDesc = "date-taken-desc" static let interestingnessDesc = "interestingness-desc" static let interestingnessAsc = "interestingness-asc" static let relevance = "relevance" static let useSafeSearch = "1" static let photosOnly = "1" static let photos = "photos" static let mediumURL = "url_m" static let photosLimit = "21" static let jsonFormat = "json" static let disableJSONCallback = "1" } // MARK: Flickr Response Keys struct ResponseKeys { static let status = "stat" static let photos = "photos" static let photo = "photo" static let title = "title" static let mediumURL = "url_m" } // MARK: Flickr Response Values struct ResponseValues { static let ok = "ok" } }
a258f378d18c14034e47fe5169caa43d
29.5
63
0.613703
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Sources/EventDetailComponent/Calendar/EventKit/EventKitEventStore.swift
mit
1
import EventKit import EventKitUI import UIKit public class EventKitEventStore: NSObject, EventStore { private let window: UIWindow private let eventStore: EKEventStore private var eventStoreChangedSubscription: NSObjectProtocol? public init(window: UIWindow) { self.window = window self.eventStore = EKEventStore() super.init() eventStoreChangedSubscription = NotificationCenter.default.addObserver( forName: .EKEventStoreChanged, object: eventStore, queue: .main, using: { [weak self] _ in if let strongSelf = self { strongSelf.delegate?.eventStoreChanged(strongSelf) } }) } public var delegate: EventStoreDelegate? public func editEvent(definition event: EventStoreEventDefinition, sender: Any?) { attemptCalendarStoreEdit { [weak self, eventStore] in let calendarEvent = EKEvent(eventStore: eventStore) calendarEvent.title = event.title calendarEvent.location = event.room calendarEvent.startDate = event.startDate calendarEvent.endDate = event.endDate calendarEvent.url = event.deeplinkURL calendarEvent.notes = event.shortDescription calendarEvent.addAlarm(EKAlarm(relativeOffset: -1800)) let editingViewController = EKEventEditViewController() editingViewController.editViewDelegate = self editingViewController.eventStore = eventStore editingViewController.event = calendarEvent switch sender { case let sender as UIBarButtonItem: editingViewController.popoverPresentationController?.barButtonItem = sender case let sender as UIView: editingViewController.popoverPresentationController?.sourceView = sender editingViewController.popoverPresentationController?.sourceRect = sender.bounds default: break } self?.window.rootViewController?.present(editingViewController, animated: true) } } public func removeEvent(identifiedBy eventDefinition: EventStoreEventDefinition) { attemptCalendarStoreEdit { [weak self] in if let event = self?.storeEvent(for: eventDefinition) { do { try self?.eventStore.remove(event, span: .thisEvent) } catch { print("Failed to remove event \(eventDefinition) from calendar. Error=\(error)") } } } } public func contains(eventDefinition: EventStoreEventDefinition) -> Bool { return storeEvent(for: eventDefinition) != nil } private func storeEvent(for eventDefinition: EventStoreEventDefinition) -> EKEvent? { let predicate = eventStore.predicateForEvents( withStart: eventDefinition.startDate, end: eventDefinition.endDate, calendars: nil ) let events = eventStore.events(matching: predicate) return events.first(where: { $0.url == eventDefinition.deeplinkURL }) } private func attemptCalendarStoreEdit(edit: @escaping () -> Void) { if EKEventStore.authorizationStatus(for: .event) == .authorized { edit() } else { requestCalendarEditingAuthorisation(success: edit) } } private func requestCalendarEditingAuthorisation(success: @escaping () -> Void) { eventStore.requestAccess(to: .event) { [weak self] granted, _ in DispatchQueue.main.async { if granted { success() } else { self?.presentNotAuthorizedAlert() } } } } private func presentNotAuthorizedAlert() { let alert = UIAlertController( title: "Not Authorised", message: "Grant Calendar access to Eurofurence in Settings to add events to Calendar.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { _ in if let settingsURL = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(settingsURL) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) window.rootViewController?.present(alert, animated: true) } } extension EventKitEventStore: EKEventEditViewDelegate { public func eventEditViewController( _ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction ) { controller.presentingViewController?.dismiss(animated: true) } }
4e287bf2dbbafccdbfb05884ecf19cbc
35.416058
100
0.607136
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
brave/src/sync/SyncBookmark.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SwiftyJSON import Shared final class SyncBookmark: SyncRecord { // MARK: Declaration for string constants to be used to decode and also serialize. fileprivate struct SerializationKeys { static let isFolder = "isFolder" static let parentFolderObjectId = "parentFolderObjectId" static let site = "site" } // MARK: Properties var isFavorite: Bool = false var isFolder: Bool? = false var parentFolderObjectId: [Int]? var site: SyncSite? convenience init() { self.init(json: nil) } /// Initiates the instance based on the object. /// /// - parameter object: The object of either Dictionary or Array kind that was passed. /// - returns: An initialized instance of the class. convenience init(object: [String: AnyObject]) { self.init(json: JSON(object)) } required init(record: Syncable?, deviceId: [Int]?, action: Int?) { super.init(record: record, deviceId: deviceId, action: action) let bm = record as? Bookmark let unixCreated = Int(bm?.created?.toTimestamp() ?? 0) let unixAccessed = Int(bm?.lastVisited?.toTimestamp() ?? 0) let site = SyncSite() site.title = bm?.title site.customTitle = bm?.customTitle site.location = bm?.url site.creationTime = unixCreated site.lastAccessedTime = unixAccessed // TODO: Does this work? site.favicon = bm?.domain?.favicon?.url self.isFavorite = bm?.isFavorite ?? false self.isFolder = bm?.isFolder self.parentFolderObjectId = bm?.syncParentUUID self.site = site } /// Initiates the instance based on the JSON that was passed. /// /// - parameter json: JSON object from SwiftyJSON. required init(json: JSON?) { super.init(json: json) guard let objectData = self.objectData else { return } let bookmark = json?[objectData.rawValue] isFolder = bookmark?[SerializationKeys.isFolder].bool if let items = bookmark?[SerializationKeys.parentFolderObjectId].array { parentFolderObjectId = items.map { $0.intValue } } site = SyncSite(json: bookmark?[SerializationKeys.site]) } /// Generates description of the object in the form of a NSDictionary. /// /// - returns: A Key value pair containing all valid values in the object. override func dictionaryRepresentation() -> [String: Any] { guard let objectData = self.objectData else { return [:] } // Create nested bookmark dictionary var bookmarkDict = [String: Any]() bookmarkDict[SerializationKeys.isFolder] = isFolder if let value = parentFolderObjectId { bookmarkDict[SerializationKeys.parentFolderObjectId] = value } if let value = site { bookmarkDict[SerializationKeys.site] = value.dictionaryRepresentation() } // Fetch parent, and assign bookmark var dictionary = super.dictionaryRepresentation() dictionary[objectData.rawValue] = bookmarkDict return dictionary } }
fbd73c736156336247cce65b6a5f01a2
35.580645
198
0.645209
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureSettings/Sources/FeatureSettingsUI/PaymentMethods/RemovePaymentMethod/RemovePaymentMethodViewController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import RxSwift import ToolKit final class RemovePaymentMethodViewController: UIViewController { // MARK: - Private IBOutlets @IBOutlet private var titleLabel: UILabel! @IBOutlet private var descriptionLabel: UILabel! @IBOutlet private var badgeImageView: BadgeImageView! @IBOutlet private var buttonView: ButtonView! // MARK: - Injected private let presenter: RemovePaymentMethodScreenPresenter private let disposeBag = DisposeBag() // MARK: - Setup init(presenter: RemovePaymentMethodScreenPresenter) { self.presenter = presenter super.init(nibName: RemovePaymentMethodViewController.objectName, bundle: .module) } required init?(coder: NSCoder) { unimplemented() } override func viewDidLoad() { super.viewDidLoad() buttonView.viewModel = presenter.removeButtonViewModel badgeImageView.viewModel = presenter.badgeImageViewModel titleLabel.content = presenter.titleLabelContent descriptionLabel.content = presenter.descriptionLabelContent presenter.dismissal .emit(weak: self) { (self) in self.dismiss(animated: true, completion: nil) } .disposed(by: disposeBag) presenter.viewDidLoad() } }
e6777d130d866166bbca81e12be9bbe6
28.73913
90
0.703216
false
false
false
false
abakhtin/ABProgressButton
refs/heads/master
ABProgressButton/ABProgressButton.swift
mit
1
// // ABProgreeButton.swift // DreamHome // // Created by Alex Bakhtin on 8/5/15. // Copyright © 2015 bakhtin. All rights reserved. // import UIKit /// ABProgressButton provides functionality for creating custom animation of UIButton during processing some task. /// Should be created in IB as custom class UIButton to prevent title of the button appearing. /// Provides mechanism for color inverting on highlitening and using tintColor for textColor(default behavior for system button) @IBDesignable @objc open class ABProgressButton: UIButton { @IBInspectable open var animationShift: CGSize = CGSize(width: 0.0, height: 0.0) /// **UI configuration. IBInspectable.** Allows change corner radius on default button state. Has default value of 5.0 @IBInspectable open var cornerRadius: CGFloat = 5.0 /// **UI configuration. IBInspectable.** Allows change border width on default button state. Has default value of 3.0 @IBInspectable open var borderWidth: CGFloat = 3.0 /// **UI configuration. IBInspectable.** Allows change border color on default button state. Has default value of control tintColor @IBInspectable open lazy var borderColor: UIColor = { return self.tintColor }() /// **UI configuration. IBInspectable.** Allows change circle radius on processing button state. Has default value of 20.0 @IBInspectable open var circleRadius: CGFloat = 20.0 /// **UI configuration. IBInspectable.** Allows change circle border width on processing button state. Has default value of 3.0 @IBInspectable open var circleBorderWidth: CGFloat = 3.0 /// **UI configuration. IBInspectable.** Allows change circle border color on processing button state. Has default value of control tintColor @IBInspectable open lazy var circleBorderColor: UIColor = { return self.tintColor }() /// **UI configuration. IBInspectable.** Allows change circle background color on processing button state. Has default value of UIColor.whiteColor() @IBInspectable open var circleBackgroundColor: UIColor = UIColor.white /// **UI configuration. IBInspectable.** Allows change circle cut angle on processing button state. /// Should have value between 0 and 360 degrees. Has default value of 45 degrees @IBInspectable open var circleCutAngle: CGFloat = 45.0 /// **UI configuration. IBInspectable.** /// If true, colors of content and background will be inverted on button highlightening. Image should be used as template for correct image color inverting. /// If false you should use default mechanism for text and images highlitening. /// Has default value of true @IBInspectable open var invertColorsOnHighlight: Bool = true /// **UI configuration. IBInspectable.** /// If true, tintColor whould be used for text, else value from UIButton.textColorForState() would be used. /// Has default value of true @IBInspectable open var useTintColorForText: Bool = true /** **Buttons states enum** - .Default: Default state of button with border line. - .Progressing: State of button without content, button has the form of circle with cut angle with rotation animation. */ public enum State { case `default`, progressing } /** **State changing** Should be used to change state of button from one state to another. All transitions between states would be animated. To update progress indicator use `progress` value */ open var progressState: State = .default { didSet { if(progressState == .default) { self.updateToDefaultStateAnimated(true)} if(progressState == .progressing) { self.updateToProgressingState()} self.updateProgressLayer() } } /** **State changing** Should be used to change progress indicator. Should have value from 0.0 to 1.0. `progressState` should be .Progressing to allow change progress(except nil value). */ open var progress: CGFloat? { didSet { if progress != nil { assert(self.progressState == .progressing, "Progress state should be .Progressing while changing progress value") } progress = progress == nil ? nil : min(progress!, CGFloat(1.0)) self.updateProgressLayer() } } // MARK : Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.privateInit() self.registerForNotifications() } override init(frame: CGRect) { super.init(frame: frame) self.privateInit() self.registerForNotifications() } override open func prepareForInterfaceBuilder() { self.privateInit() } deinit { self.unregisterFromNotifications() } fileprivate func privateInit() { if (self.useTintColorForText) { self.setTitleColor(self.tintColor, for: UIControlState()) } if (self.invertColorsOnHighlight) { self.setTitleColor(self.shapeBackgroundColor, for: UIControlState.highlighted) } self.layer.insertSublayer(self.shapeLayer, at: 0) self.layer.insertSublayer(self.crossLayer, at: 1) self.layer.insertSublayer(self.progressLayer, at: 2) self.updateToDefaultStateAnimated(false) } override open func layoutSubviews() { super.layoutSubviews() self.shapeLayer.frame = self.layer.bounds self.updateShapeLayer() self.crossLayer.frame = self.layer.bounds self.progressLayer.frame = self.layer.bounds self.bringSubview(toFront: self.imageView!) } override open var isHighlighted: Bool { didSet { if (self.invertColorsOnHighlight) { self.imageView?.tintColor = isHighlighted ? self.shapeBackgroundColor : self.circleBorderColor } self.crossLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor self.progressLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor if (isHighlighted) { self.shapeLayer.fillColor = (progressState == State.default) ? self.borderColor.cgColor : self.circleBorderColor.cgColor } else { self.shapeLayer.fillColor = (progressState == State.default) ? self.shapeBackgroundColor.cgColor : self.circleBackgroundColor.cgColor } } } // MARK : Methods used to update states fileprivate var shapeLayer = CAShapeLayer() fileprivate lazy var crossLayer: CAShapeLayer = { let crossLayer = CAShapeLayer() crossLayer.path = self.crossPath().cgPath crossLayer.strokeColor = self.circleBorderColor.cgColor return crossLayer }() fileprivate lazy var progressLayer: CAShapeLayer = { let progressLayer = CAShapeLayer() progressLayer.strokeColor = self.circleBorderColor.cgColor progressLayer.fillColor = UIColor.clear.cgColor return progressLayer }() fileprivate lazy var shapeBackgroundColor: UIColor = { return self.backgroundColor ?? self.circleBackgroundColor }() fileprivate func updateToDefaultStateAnimated(_ animated:Bool) { self.shapeLayer.strokeColor = self.borderColor.cgColor; self.shapeLayer.fillColor = self.shapeBackgroundColor.cgColor self.crossLayer.isHidden = true self.animateDefaultStateAnimated(animated) } fileprivate func updateToProgressingState() { self.titleLabel?.alpha = 0.0 self.shapeLayer.strokeColor = self.circleBorderColor.cgColor self.shapeLayer.fillColor = self.circleBackgroundColor.cgColor self.crossLayer.isHidden = false self.animateProgressingState(self.shapeLayer) } fileprivate func updateShapeLayer() { if self.progressState == .default { self.shapeLayer.path = self.defaultStatePath().cgPath } self.crossLayer.path = self.crossPath().cgPath } fileprivate func updateProgressLayer() { self.progressLayer.isHidden = (self.progressState != .progressing || self.progress == nil) if (self.progressLayer.isHidden == false) { let progressCircleRadius = self.circleRadius - self.circleBorderWidth let progressArcAngle = CGFloat(M_PI) * 2 * self.progress! - CGFloat(M_PI_2) let circlePath = UIBezierPath() let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) circlePath.addArc(withCenter: center, radius:progressCircleRadius, startAngle:CGFloat(-M_PI_2), endAngle:progressArcAngle, clockwise:true) circlePath.lineWidth = self.circleBorderWidth let updateProgressAnimation = CABasicAnimation(); updateProgressAnimation.keyPath = "path" updateProgressAnimation.fromValue = self.progressLayer.path updateProgressAnimation.toValue = circlePath.cgPath updateProgressAnimation.duration = progressUpdateAnimationTime self.progressLayer.path = circlePath.cgPath self.progressLayer.add(updateProgressAnimation, forKey: "update progress animation") } } // MARK : Methods used to animate states and transions between them fileprivate let firstStepAnimationTime = 0.3 fileprivate let secondStepAnimationTime = 0.15 fileprivate let textAppearingAnimationTime = 0.2 fileprivate let progressUpdateAnimationTime = 0.1 fileprivate func animateDefaultStateAnimated(_ animated: Bool) { if !animated { self.shapeLayer.path = self.defaultStatePath().cgPath self.titleLabel?.alpha = 1.0 self.showContentImage() } else { self.shapeLayer.removeAnimation(forKey: "rotation animation") let firstStepAnimation = CABasicAnimation(); firstStepAnimation.keyPath = "path" firstStepAnimation.fromValue = self.shapeLayer.path firstStepAnimation.toValue = self.animateToCircleReplacePath().cgPath firstStepAnimation.duration = secondStepAnimationTime self.shapeLayer.path = self.animateToCircleFakeRoundPath().cgPath self.shapeLayer.add(firstStepAnimation, forKey: "first step animation") let secondStepAnimation = CABasicAnimation(); secondStepAnimation.keyPath = "path" secondStepAnimation.fromValue = self.shapeLayer.path! secondStepAnimation.toValue = self.defaultStatePath().cgPath secondStepAnimation.beginTime = CACurrentMediaTime() + secondStepAnimationTime secondStepAnimation.duration = firstStepAnimationTime self.shapeLayer.path = self.defaultStatePath().cgPath self.shapeLayer.add(secondStepAnimation, forKey: "second step animation") let delay = secondStepAnimationTime + firstStepAnimationTime UIView.animate(withDuration: textAppearingAnimationTime, delay: delay, options: UIViewAnimationOptions(), animations: { () -> Void in self.titleLabel?.alpha = 1.0 }, completion: { (complete) -> Void in self.showContentImage() }) } } fileprivate func animateProgressingState(_ layer: CAShapeLayer) { let firstStepAnimation = CABasicAnimation(); firstStepAnimation.keyPath = "path" firstStepAnimation.fromValue = layer.path firstStepAnimation.toValue = self.animateToCircleFakeRoundPath().cgPath firstStepAnimation.duration = firstStepAnimationTime layer.path = self.animateToCircleReplacePath().cgPath layer.add(firstStepAnimation, forKey: "first step animation") let secondStepAnimation = CABasicAnimation(); secondStepAnimation.keyPath = "path" secondStepAnimation.fromValue = layer.path secondStepAnimation.toValue = self.progressingStatePath().cgPath secondStepAnimation.beginTime = CACurrentMediaTime() + firstStepAnimationTime secondStepAnimation.duration = secondStepAnimationTime layer.path = self.progressingStatePath().cgPath layer.add(secondStepAnimation, forKey: "second step animation") let animation = CABasicAnimation(); animation.keyPath = "transform.rotation"; animation.fromValue = 0 * M_PI animation.toValue = 2 * M_PI animation.repeatCount = Float.infinity animation.duration = 1.5 animation.beginTime = CACurrentMediaTime() + firstStepAnimationTime + secondStepAnimationTime layer.add(animation, forKey: "rotation animation") layer.anchorPoint = CGPoint(x: 0.5 + self.animationShift.width / self.bounds.size.width, y: 0.5 + self.animationShift.height / self.bounds.size.height) UIView.animate(withDuration: textAppearingAnimationTime, animations: { () -> Void in self.titleLabel?.alpha = 0.0 self.hideContentImage() }) } // MARK : Pathes creation for different states fileprivate func defaultStatePath() -> UIBezierPath { let bordersPath = UIBezierPath(roundedRect:self.bounds, cornerRadius:self.cornerRadius) bordersPath.lineWidth = self.borderWidth return bordersPath } fileprivate func progressingStatePath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let circlePath = UIBezierPath() let startAngle = self.circleCutAngle/180 * CGFloat(M_PI) let endAngle = 2 * CGFloat(M_PI) circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:startAngle, endAngle:endAngle, clockwise:true) circlePath.lineWidth = self.circleBorderWidth return circlePath } fileprivate func animateToCircleFakeRoundPath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let rect = CGRect(x: center.x - self.circleRadius, y: center.y - self.circleRadius, width: self.circleRadius * 2, height: self.circleRadius * 2) let bordersPath = UIBezierPath(roundedRect: rect, cornerRadius: self.circleRadius) bordersPath.lineWidth = self.borderWidth return bordersPath } fileprivate func animateToCircleReplacePath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let circlePath = UIBezierPath() circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:CGFloat(0.0), endAngle:CGFloat(M_PI * 2), clockwise:true) circlePath.lineWidth = self.circleBorderWidth return circlePath } fileprivate func crossPath() -> UIBezierPath { let crossPath = UIBezierPath() let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let point1 = CGPoint(x: center.x - self.circleRadius/2, y: center.y + self.circleRadius / 2) let point2 = CGPoint(x: center.x + self.circleRadius/2, y: center.y + self.circleRadius / 2) let point3 = CGPoint(x: center.x + self.circleRadius/2, y: center.y - self.circleRadius / 2) let point4 = CGPoint(x: center.x - self.circleRadius/2, y: center.y - self.circleRadius / 2) crossPath.move(to: point1) crossPath.addLine(to: point3) crossPath.move(to: point2) crossPath.addLine(to: point4) crossPath.lineWidth = self.circleBorderWidth return crossPath } // MARK : processing animation stopping while in background // Should be done to prevent animation broken on entering foreground fileprivate func registerForNotifications() { NotificationCenter.default.addObserver(self, selector:#selector(self.applicationDidEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector:#selector(self.applicationWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) } fileprivate func unregisterFromNotifications() { NotificationCenter.default.removeObserver(self) } func applicationDidEnterBackground(_ notification: Notification) { self.pauseLayer(self.layer) } func applicationWillEnterForeground(_ notification: Notification) { self.resumeLayer(self.layer) } fileprivate func pauseLayer(_ layer: CALayer) { let pausedTime = layer.convertTime(CACurrentMediaTime(), from:nil) layer.speed = 0.0 layer.timeOffset = pausedTime } fileprivate func resumeLayer(_ layer: CALayer) { let pausedTime = layer.timeOffset layer.speed = 1.0 layer.timeOffset = 0.0 layer.beginTime = 0.0 let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime layer.beginTime = timeSincePause } // MARK : Content images hiding // The only available way to make images hide is to set the object to nil // If you now any way else please help me here fileprivate var imageForNormalState: UIImage? fileprivate var imageForHighlitedState: UIImage? fileprivate var imageForDisabledState: UIImage? fileprivate func hideContentImage() { self.imageForNormalState = self.image(for: UIControlState()) self.setImage(UIImage(), for: UIControlState()) self.imageForHighlitedState = self.image(for: UIControlState.highlighted) self.setImage(UIImage(), for: UIControlState.highlighted) self.imageForDisabledState = self.image(for: UIControlState.disabled) self.setImage(UIImage(), for: UIControlState.disabled) } fileprivate func showContentImage() { if self.imageForNormalState != nil { self.setImage(self.imageForNormalState, for: UIControlState()); self.imageForNormalState = nil } if self.imageForHighlitedState != nil { self.setImage(self.imageForHighlitedState, for: UIControlState.highlighted) self.imageForHighlitedState = nil } if self.imageForDisabledState != nil { self.setImage(self.imageForDisabledState, for: UIControlState.disabled) self.imageForDisabledState = nil } } }
9b0944858a7ada9a174260f1ff16998d
47.119898
171
0.684409
false
false
false
false
cplaverty/KeitaiWaniKani
refs/heads/master
WaniKaniKit/Extensions/FMDatabaseAdditionsVariadic.swift
mit
1
// // FMDatabaseAdditionsVariadic.swift // FMDB // import Foundation import FMDB extension FMDatabase { /// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods /// /// :param: sql The SQL statement to be used. /// :param: values The NSArray of the arguments to be bound to the ? placeholders in the SQL. /// :param: completionHandler The closure to be used to call the appropriate FMDatabase method to return the desired value. /// /// :returns: This returns the T value if value is found. Returns nil if column is NULL or upon error. private func valueForQuery<T>(_ sql: String, values: [Any]?, completionHandler: (FMResultSet) -> T?) throws -> T? { var result: T? let rs = try executeQuery(sql, values: values) defer { rs.close() } if rs.next() && !rs.columnIndexIsNull(0) { result = completionHandler(rs) } return result } /// This is a rendition of stringForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns string value if value is found. Returns nil if column is NULL or upon error. func stringForQuery(_ sql: String, values: [Any]? = nil) throws -> String? { return try valueForQuery(sql, values: values) { $0.string(forColumnIndex: 0) } } /// This is a rendition of intForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns integer value if value is found. Returns nil if column is NULL or upon error. func intForQuery(_ sql: String, values: [Any]? = nil) throws -> Int32? { return try valueForQuery(sql, values: values) { $0.int(forColumnIndex: 0) } } /// This is a rendition of longForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns long value if value is found. Returns nil if column is NULL or upon error. func longForQuery(_ sql: String, values: [Any]? = nil) throws -> Int? { return try valueForQuery(sql, values: values) { $0.long(forColumnIndex: 0) } } /// This is a rendition of boolForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error. func boolForQuery(_ sql: String, values: [Any]? = nil) throws -> Bool? { return try valueForQuery(sql, values: values) { $0.bool(forColumnIndex: 0) } } /// This is a rendition of doubleForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Double value if value is found. Returns nil if column is NULL or upon error. func doubleForQuery(_ sql: String, values: [Any]? = nil) throws -> Double? { return try valueForQuery(sql, values: values) { $0.double(forColumnIndex: 0) } } /// This is a rendition of dateForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error. func dateForQuery(_ sql: String, values: [Any]? = nil) throws -> Date? { return try valueForQuery(sql, values: values) { $0.date(forColumnIndex: 0) } } /// This is a rendition of dataForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error. func dataForQuery(_ sql: String, values: [Any]? = nil) throws -> Data? { return try valueForQuery(sql, values: values) { $0.data(forColumnIndex: 0) } } }
c08a846dabd20d79e6baefc1f72925a5
42.318966
127
0.642985
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/SoftwareVideoLayerFrameManager.swift
gpl-2.0
1
// // SoftwareVideoLayerFrameManager.swift // Telegram // // Created by Mikhail Filimonov on 26/05/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import Foundation import TGUIKit import Postbox import TelegramCore import SwiftSignalKit import CoreMedia private let applyQueue = Queue() private let workers = ThreadPool(threadCount: 3, threadPriority: 0.2) private var nextWorker = 0 final class SoftwareVideoLayerFrameManager { private var dataDisposable = MetaDisposable() private let source = Atomic<SoftwareVideoSource?>(value: nil) private var baseTimestamp: Double? private var frames: [MediaTrackFrame] = [] private var minPts: CMTime? private var maxPts: CMTime? private let account: Account private let resource: MediaResource private let secondaryResource: MediaResource? private let queue: ThreadPoolQueue private let layerHolder: SampleBufferLayer private var rotationAngle: CGFloat = 0.0 private var aspect: CGFloat = 1.0 private var layerRotationAngleAndAspect: (CGFloat, CGFloat)? private let hintVP9: Bool var onRender:(()->Void)? init(account: Account, fileReference: FileMediaReference, layerHolder: SampleBufferLayer) { var resource = fileReference.media.resource var secondaryResource: MediaResource? self.hintVP9 = fileReference.media.isWebm for attribute in fileReference.media.attributes { if case .Video = attribute { if let thumbnail = fileReference.media.videoThumbnails.first { resource = thumbnail.resource secondaryResource = fileReference.media.resource } } } nextWorker += 1 self.account = account self.resource = resource self.secondaryResource = secondaryResource self.queue = ThreadPoolQueue(threadPool: workers) self.layerHolder = layerHolder } deinit { self.dataDisposable.dispose() } func start() { let secondarySignal: Signal<String?, NoError> if let secondaryResource = self.secondaryResource { secondarySignal = self.account.postbox.mediaBox.resourceData(secondaryResource, option: .complete(waitUntilFetchStatus: false)) |> map { data -> String? in if data.complete { return data.path } else { return nil } } } else { secondarySignal = .single(nil) } let firstReady: Signal<String, NoError> = combineLatest( self.account.postbox.mediaBox.resourceData(self.resource, option: .complete(waitUntilFetchStatus: false)), secondarySignal ) |> mapToSignal { first, second -> Signal<String, NoError> in if let second = second { return .single(second) } else if first.complete { return .single(first.path) } else { return .complete() } } self.dataDisposable.set((firstReady |> deliverOn(applyQueue)).start(next: { [weak self] path in if let strongSelf = self { let _ = strongSelf.source.swap(SoftwareVideoSource(path: path, hintVP9: strongSelf.hintVP9, unpremultiplyAlpha: true)) } })) } func tick(timestamp: Double) { applyQueue.async { if self.baseTimestamp == nil && !self.frames.isEmpty { self.baseTimestamp = timestamp } if let baseTimestamp = self.baseTimestamp { var index = 0 var latestFrameIndex: Int? while index < self.frames.count { if baseTimestamp + self.frames[index].position.seconds + self.frames[index].duration.seconds <= timestamp { latestFrameIndex = index //print("latestFrameIndex = \(index)") } index += 1 } if let latestFrameIndex = latestFrameIndex { let frame = self.frames[latestFrameIndex] for i in (0 ... latestFrameIndex).reversed() { self.frames.remove(at: i) } if self.layerHolder.layer.status == .failed { self.layerHolder.layer.flush() } self.layerHolder.layer.enqueue(frame.sampleBuffer) DispatchQueue.main.async { self.onRender?() } } } self.poll() } } private var polling = false private func poll() { if self.frames.count < 2 && !self.polling, self.source.with ({ $0 != nil }) { self.polling = true let minPts = self.minPts let maxPts = self.maxPts self.queue.addTask(ThreadPoolTask { [weak self] state in if state.cancelled.with({ $0 }) { return } if let strongSelf = self { var frameAndLoop: (MediaTrackFrame?, CGFloat, CGFloat, Bool)? var hadLoop = false for _ in 0 ..< 1 { frameAndLoop = (strongSelf.source.with { $0 })?.readFrame(maxPts: maxPts) if let frameAndLoop = frameAndLoop { if frameAndLoop.0 != nil || minPts != nil { break } else { if frameAndLoop.3 { hadLoop = true } //print("skip nil frame loop: \(frameAndLoop.3)") } } else { break } } if let loop = frameAndLoop?.3, loop { hadLoop = true } applyQueue.async { if let strongSelf = self { strongSelf.polling = false if let (_, rotationAngle, aspect, _) = frameAndLoop { strongSelf.rotationAngle = rotationAngle strongSelf.aspect = aspect } var noFrame = false if let frame = frameAndLoop?.0 { if strongSelf.minPts == nil || CMTimeCompare(strongSelf.minPts!, frame.position) < 0 { var position = CMTimeAdd(frame.position, frame.duration) for _ in 0 ..< 1 { position = CMTimeAdd(position, frame.duration) } strongSelf.minPts = position } strongSelf.frames.append(frame) strongSelf.frames.sort(by: { lhs, rhs in if CMTimeCompare(lhs.position, rhs.position) < 0 { return true } else { return false } }) //print("add frame at \(CMTimeGetSeconds(frame.position))") //let positions = strongSelf.frames.map { CMTimeGetSeconds($0.position) } //print("frames: \(positions)") } else { noFrame = true //print("not adding frames") } if hadLoop { strongSelf.maxPts = strongSelf.minPts strongSelf.minPts = nil //print("loop at \(strongSelf.minPts)") } if strongSelf.source.with ({ $0 == nil }) || noFrame { delay(0.2, onQueue: applyQueue.queue, closure: { [weak strongSelf] in strongSelf?.poll() }) } else { strongSelf.poll() } } } } }) } } }
9dd12aeb6959b8fd7424a69f999fe055
38.849558
139
0.458694
false
false
false
false
rsaenzi/MyMoviesListApp
refs/heads/master
MyMoviesListApp/MyMoviesListApp/AuthInteractor.swift
mit
1
// // AuthInteractor.swift // MyMoviesListApp // // Created by Rigoberto Sáenz Imbacuán on 5/29/17. // Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved. // import Foundation import Moya import SwiftKeychainWrapper typealias GetDeviceCodeCallback = (_ authInfo: GetDeviceCodeResponse?, _ code: APIResponseCode) -> Void typealias GetTokenCallback = (_ success: Bool, _ code: APIResponseCode) -> Void class AuthInteractor { fileprivate var deviceCodeInfo: GetDeviceCodeResponse? func hasSavedCredentials() -> Bool { guard let _: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiAccessToken.rawValue), let _: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiRefreshToken.rawValue) else { return false } return true } func getDeviceCode(using clientId: String, callback: @escaping GetDeviceCodeCallback) { deviceCodeInfo = nil let provider = MoyaProvider<APIService>(endpointClosure: APIService.endpointClosure) provider.request(.getDeviceCode(clientId: clientId)) { [weak self] result in guard let `self` = self else { callback(nil, .referenceError) return } switch result { case let .success(moyaResponse): self.handleSuccessDeviceCode(moyaResponse, callback) case .failure(_): callback(nil, .connectionError) return } } } fileprivate func handleSuccessDeviceCode(_ response: Response, _ callback: GetDeviceCodeCallback) { guard response.statusCode == 200 else { callback(nil, .httpCodeError) return } var json: String = "" do { json = try response.mapString() } catch { callback(nil, .parsingError) return } guard json.characters.count > 0 else { callback(nil, .emptyJsonError) return } guard let result = GetDeviceCodeResponse(JSONString: json) else { callback(nil, .mappingError) return } deviceCodeInfo = result callback(result, .success) } func getToken(callback: @escaping GetTokenCallback) { guard let info = deviceCodeInfo else { callback(false, .missingParameterError) return } let provider = MoyaProvider<APIService>(endpointClosure: APIService.endpointClosure) provider.request(.getToken(code: info.deviceCode, clientId: APICredentials.traktClientId, clientSecret: APICredentials.traktClientSecret)) { [weak self] result in guard let `self` = self else { callback(false, .referenceError) return } switch result { case let .success(moyaResponse): self.handleSuccessToken(moyaResponse, callback) case .failure(_): callback(false, .connectionError) return } } } fileprivate func handleSuccessToken(_ response: Response, _ callback: GetTokenCallback) { var json: String = "" do { json = try response.mapString() } catch { callback(false, .parsingError) return } guard response.statusCode == 200 else { callback(false, .httpCodeError) return } guard json.characters.count > 0 else { callback(false, .emptyJsonError) return } guard let result = GetTokenResponse(JSONString: json) else { callback(false, .mappingError) return } let saveAccessToken: Bool = KeychainWrapper.standard.set(result.accessToken, forKey: KeychainKey.apiAccessToken.rawValue) let saveRefreshToken: Bool = KeychainWrapper.standard.set(result.refreshToken, forKey: KeychainKey.apiRefreshToken.rawValue) guard saveAccessToken, saveRefreshToken else { callback(false, .dataSaveError) return } callback(true, .success) } }
29e4076e5e0c9577f1ab604194eb0818
30.226027
132
0.559553
false
false
false
false
zjzsliyang/Potions
refs/heads/master
Lift/Lift/ViewController.swift
mit
1
// // ViewController.swift // Lift // // Created by Yang Li on 24/04/2017. // Copyright © 2017 Yang Li. All rights reserved. // import UIKit import PSOLib import Buckets class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIPopoverPresentationControllerDelegate { let floorCount = 20 let liftCount = 5 let distanceX: CGFloat = 170 let distanceY: CGFloat = 60 let liftVelocity: Double = 0.3 let liftDelay: Double = 0.5 var upDownButton = [[UIButton]]() var liftDisplay = [UILabel]() var lift = [UIView]() var liftCurrentPosition: [CGFloat] = Array(repeating: 1290.0, count: 5) var liftCurrentButton: [[Bool]] = Array(repeating: Array(repeating: false, count: 20), count: 5) var liftCurrentDirection: [Int] = Array(repeating: 0, count: 5) // 0 represents static, 1 represents Up Direction, -1 represents Down Direction var liftBeingSet: [Bool] = Array(repeating: false, count: 5) var liftDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRandomDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRequestQueue = Queue<Int>() var liftInAnimation: [Int] = Array(repeating: 0, count: 5) // var sAWT: [Double] = Array(repeating: 0, count: 5) // var sART: [Double] = Array(repeating: 0, count: 5) // var sRPC: [Double] = Array(repeating: 0, count: 5) @IBAction func modeChosen(_ sender: UISwitch) { weak var weakSelf = self var fucktimer = Timer() if sender.isOn { fucktimer = Timer(timeInterval: 1, repeats: true) { (fucktimer) in let randomFloor = Int(arc4random() % UInt32((weakSelf?.floorCount)!)) let randomDirection = Int(arc4random() % 2) if (!(weakSelf?.upDownButton[randomFloor][randomDirection].isSelected)!) && (weakSelf?.upDownButton[randomFloor][randomDirection].isEnabled)! { weakSelf?.buttonTapped(sender: self.upDownButton[randomFloor][randomDirection]) } } RunLoop.current.add(fucktimer, forMode: .defaultRunLoopMode) fucktimer.fire() } else { if (fucktimer.isValid) { fucktimer.invalidate() } } } override func viewDidLoad() { super.viewDidLoad() initFloorSign() initUpDownButton() initLiftDisplay() initLift() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let deviceModelName = UIDevice.current.modelName if deviceModelName != "iPad Pro 12.9" { let alertController = UIAlertController(title: "CAUTION", message: "This app can only run on the\n 12.9-inch iPad Pro", preferredStyle: .alert) let alertActionOk = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertActionOk) present(alertController, animated: true, completion: nil) } let timer = Timer(timeInterval: 0.1, repeats: true) { (timer) in for i in 0..<self.liftCount { self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: i), liftIndex: i) self.updateCurrentDirection(liftIndex: i) } } RunLoop.current.add(timer, forMode: .commonModes) timer.fire() } func initLift() { var liftX: CGFloat = 250 for liftIndex in 0..<liftCount { let liftUnit = UIView(frame: CGRect(x: liftX, y: 1290, width: 33.6, height: 45.7)) let liftUnitButton = UIButton(frame: CGRect(x: 0, y: 0, width: liftUnit.frame.width, height: liftUnit.frame.height)) liftUnit.addSubview(liftUnitButton) liftUnitButton.setImage(UIImage(named: "lift"), for: .normal) liftUnitButton.tag = liftIndex liftUnitButton.addTarget(self, action: #selector(popoverChosenView(sender:)), for: .touchUpInside) self.view.addSubview(liftUnit) lift.append(liftUnit) liftX = liftX + distanceX } } func popoverChosenView(sender: UIButton) { let layout = UICollectionViewFlowLayout() let chosenView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 300, height: 240), collectionViewLayout: layout) chosenView.delegate = self chosenView.dataSource = self chosenView.tag = sender.tag liftBeingSet[sender.tag] = true chosenView.register(LiftButtonViewCell.self, forCellWithReuseIdentifier: "cell") chosenView.backgroundColor = UIColor.lightGray let popoverViewController = UIViewController() popoverViewController.modalPresentationStyle = .popover popoverViewController.popoverPresentationController?.sourceView = sender popoverViewController.popoverPresentationController?.sourceRect = sender.bounds popoverViewController.preferredContentSize = chosenView.bounds.size popoverViewController.popoverPresentationController?.delegate = self popoverViewController.view.addSubview(chosenView) self.present(popoverViewController, animated: true, completion: nil) } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { for i in 0..<liftCount { if liftBeingSet[i] { print("current lift: " + String(i)) inLiftScan(liftIndex: i) liftBeingSet[i] = false } } } func inLiftScan(liftIndex: Int) { for i in 0..<floorCount { if liftCurrentButton[liftIndex][i] { liftDestinationDeque[liftIndex].enqueueFirst(i) liftCurrentButton[liftIndex][i] = false } } _ = liftDestinationDeque[liftIndex].sorted() liftAnimation(liftIndex: liftIndex) } func randomGenerateDestination(destinationTag: Int) -> Int { if destinationTag < 0 { return Int(arc4random() % UInt32(abs(destinationTag + 1))) + 1 } else { return floorCount - Int(arc4random() % UInt32(floorCount - destinationTag)) } } func updateCurrentDirection(liftIndex: Int) { if lift[liftIndex].layer.presentation()?.position == nil { liftCurrentDirection[liftIndex] = 0 return } let currentPresentationY = lift[liftIndex].layer.presentation()?.frame.minY if currentPresentationY! < liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 1 } if currentPresentationY! > liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = -1 } if currentPresentationY! == liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 0 } liftCurrentPosition[liftIndex] = currentPresentationY! return } func naiveDispatch() { if liftRequestQueue.isEmpty { return } let currentRequest = liftRequestQueue.dequeue() print("current Request: " + String(currentRequest)) if currentRequest < 0 { var closestLiftDistance = 20 var closestLift = -1 for i in 0..<liftCount { if liftCurrentDirection[i] <= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) { closestLift = i closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(-currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } else { var closestLiftDistance = 20 var closestLift = -1 for j in 0..<liftCount { if liftCurrentDirection[j] >= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) { closestLift = j closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } } /* func SPODispatch() { let spaceMin: [Int] = Array(repeating: 0, count: liftRequestQueue.count) let spaceMax: [Int] = Array(repeating: 5, count: liftRequestQueue.count) let searchSpace = PSOSearchSpace(boundsMin: spaceMin, max: spaceMax) let optimizer = PSOStandardOptimizer2011(for: searchSpace, optimum: 0, fitness: { (positions: UnsafeMutablePointer<Double>?, dimensions: Int32) -> Double in // AWT: Average Waiting Time var liftTempDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var fMax: [Int] = Array(repeating: 0, count: self.liftCount) var fMin: [Int] = Array(repeating: 0, count: self.liftCount) for i in 0..<self.liftRequestQueue.count { switch Int((positions?[i])!) { case 0: liftTempDestinationDeque[0].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[0].first!) case 1: liftTempDestinationDeque[1].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[1].first!) case 2: liftTempDestinationDeque[2].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[2].first!) case 3: liftTempDestinationDeque[3].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[3].first!) default: liftTempDestinationDeque[4].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[4].first!) } } // ART: Average Riding Time // EC: Energy Consumption // Total var sFitnessFunc: Double = 0 return sFitnessFunc }, before: nil, iteration: nil) { (optimizer: PSOStandardOptimizer2011?) in // to do } optimizer?.operation.start() } */ func liftAnimation(liftIndex: Int) { if liftDestinationDeque[liftIndex].isEmpty { return } liftInAnimation[liftIndex] = liftInAnimation[liftIndex] + 1 var destinationFloor: Int = 0 if liftCurrentDirection[liftIndex] == 0 { let currentFloor = getLiftCurrentFloor(liftIndex: liftIndex) if abs(currentFloor - (liftDestinationDeque[liftIndex].first! + 1)) < abs(currentFloor - (liftDestinationDeque[liftIndex].last! + 1)) { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } } else { if liftCurrentDirection[liftIndex] > 0 { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } } print("destination floor: " + String(destinationFloor)) let destinationDistance = CGFloat(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex)) * (distanceY) let destinationTime = liftVelocity * abs(Double(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex))) UIView.animate(withDuration: destinationTime, delay: liftDelay, options: .curveEaseInOut, animations: { self.lift[liftIndex].center.y = self.lift[liftIndex].center.y - destinationDistance }, completion: { (finished) in self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: liftIndex), liftIndex: liftIndex) self.updateUpDownButton(destinationTag: (self.liftCurrentDirection[liftIndex] * destinationFloor), liftIndex: liftIndex) if !self.liftDestinationDeque[liftIndex].isEmpty { self.liftAnimation(liftIndex: liftIndex) } self.liftInAnimation[liftIndex] = self.liftInAnimation[liftIndex] - 1 }) } func updateUpDownButton(destinationTag: Int, liftIndex: Int) { print("destinationTag: " + String(destinationTag)) if destinationTag == 0 { if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][0].isSelected = false upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][1].isSelected = false } return } if destinationTag > 0 { if upDownButton[destinationTag - 1][0].isSelected { upDownButton[destinationTag - 1][0].isSelected = false } } else { if upDownButton[-destinationTag - 1][1].isSelected { upDownButton[-destinationTag - 1][1].isSelected = false } } if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[abs(destinationTag) - 1][0].isSelected = false upDownButton[abs(destinationTag) - 1][1].isSelected = false } } func getLiftCurrentFloor(liftIndex: Int) -> Int { if lift[liftIndex].layer.presentation()?.position != nil { return (Int(floor((1290 - (lift[liftIndex].layer.presentation()!.frame.minY)) / distanceY)) + 1) } else { print("returning model layer position") return (Int(floor((1290 - (lift[liftIndex].layer.model().frame.minY)) / distanceY)) + 1) } } func updateLiftDisplay(currentFloor: Int, liftIndex: Int) { liftDisplay[liftIndex].text = String(currentFloor) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! LiftButtonViewCell cell.liftButton?.setTitle(convertNumber(number: indexPath.row + 1), for: .normal) cell.liftButton?.setTitleColor(UIColor.blue, for: .selected) cell.liftButton?.tag = collectionView.tag cell.liftButton?.addTarget(self, action: #selector(liftButtonTapped(sender:)), for: .touchUpInside) return cell } func liftButtonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected let currentLift = sender.tag let currentFloorButton = convertLetter(letter: sender.currentTitle!) liftCurrentButton[currentLift][currentFloorButton - 1] = !liftCurrentButton[currentLift][currentFloorButton - 1] } func convertLetter(letter: String) -> Int { let asciiLetter = Character(letter).asciiValue if asciiLetter < 65 { return asciiLetter - 48 } else { return asciiLetter - 55 } } func convertNumber(number: Int) -> String { if number < 10 { return String(number) } else { return String(describing: UnicodeScalar(number - 10 + 65)!) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return floorCount } func initFloorSign() { var floorY: CGFloat = 1300 for floorNum in 0..<floorCount { let floorNumView = UIImageView(image: UIImage(named: String(floorNum + 1))) floorNumView.frame = CGRect(x: 36, y: floorY, width: 30, height: 30) floorNumView.contentMode = .scaleAspectFill self.view.addSubview(floorNumView) floorY = floorY - distanceY } } func initLiftDisplay() { var liftDisplayX: CGFloat = 220 for _ in 0..<liftCount { let liftDisplayUnit = UILabel(frame: CGRect(x: liftDisplayX, y: 100, width: 50, height: 50)) liftDisplayUnit.text = String(1) liftDisplayUnit.font = UIFont(name: "Digital-7", size: 50) liftDisplayUnit.textAlignment = .right self.view.addSubview(liftDisplayUnit) liftDisplay.append(liftDisplayUnit) liftDisplayX = liftDisplayX + distanceX } } func initUpDownButton() { var upDownButtonY: CGFloat = 1305 for i in 0..<floorCount { var upDownButtonUnit = [UIButton]() let upDownButtonUp = UIButton(frame: CGRect(x: 90, y: upDownButtonY, width: 25, height: 25)) upDownButtonUp.setImage(UIImage(named: "up"), for: .normal) upDownButtonUp.setImage(UIImage(named: "up-active"), for: .selected) upDownButtonUp.tag = i + 1 upDownButtonUp.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) let upDownButtonDown = UIButton(frame: CGRect(x: 130, y: upDownButtonY, width: 25, height: 25)) upDownButtonDown.setImage(UIImage(named: "down"), for: .normal) upDownButtonDown.setImage(UIImage(named: "down-active"), for: .selected) upDownButtonDown.tag = -(i + 1) upDownButtonDown.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) upDownButtonUnit.append(upDownButtonUp) upDownButtonUnit.append(upDownButtonDown) self.view.addSubview(upDownButtonUp) self.view.addSubview(upDownButtonDown) upDownButton.append(upDownButtonUnit) upDownButtonY = upDownButtonY - distanceY } upDownButton[0][1].isEnabled = false upDownButton[19][0].isEnabled = false } func buttonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { liftRequestQueue.enqueue(sender.tag) naiveDispatch() for i in 0..<liftCount { if liftInAnimation[i] == 0 { liftAnimation(liftIndex: i) } } } } } class LiftButtonViewCell: UICollectionViewCell { var liftButton: UIButton? override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { liftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) liftButton?.titleLabel?.font = UIFont(name: "Elevator Buttons", size: 50) self.addSubview(liftButton!) } } extension Character { var asciiValue: Int { get { let unicodeString = String(self).unicodeScalars return Int(unicodeString[unicodeString.startIndex].value) } } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPad6,7", "iPad6,8": return "iPad Pro 12.9" case "i386", "x86_64": return "Simulator" default: return identifier } } }
0a257b6644a40bb54a669687174c5cfb
38.505219
171
0.685568
false
false
false
false
ReactiveX/RxSwift
refs/heads/develop
Example/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift
gpl-3.0
7
// // UITabBar+Rx.swift // RxCocoa // // Created by Jesse Farless on 5/13/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift /** iOS only */ #if os(iOS) extension Reactive where Base: UITabBar { /// Reactive wrapper for `delegate` message `tabBar(_:willBeginCustomizing:)`. public var willBeginCustomizing: ControlEvent<[UITabBarItem]> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willBeginCustomizing:))) .map { a in return try castOrThrow([UITabBarItem].self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `tabBar(_:didBeginCustomizing:)`. public var didBeginCustomizing: ControlEvent<[UITabBarItem]> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didBeginCustomizing:))) .map { a in return try castOrThrow([UITabBarItem].self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `tabBar(_:willEndCustomizing:changed:)`. public var willEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willEndCustomizing:changed:))) .map { (a: [Any]) -> (([UITabBarItem], Bool)) in let items = try castOrThrow([UITabBarItem].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (items, changed) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `tabBar(_:didEndCustomizing:changed:)`. public var didEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didEndCustomizing:changed:))) .map { (a: [Any]) -> (([UITabBarItem], Bool)) in let items = try castOrThrow([UITabBarItem].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (items, changed) } return ControlEvent(events: source) } } #endif /** iOS and tvOS */ extension Reactive where Base: UITabBar { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<UITabBar, UITabBarDelegate> { RxTabBarDelegateProxy.proxy(for: base) } /// Reactive wrapper for `delegate` message `tabBar(_:didSelect:)`. public var didSelectItem: ControlEvent<UITabBarItem> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didSelect:))) .map { a in return try castOrThrow(UITabBarItem.self, a[1]) } return ControlEvent(events: source) } } #endif
a4de214626e8d14525e7cc775562ef3f
31.347826
110
0.631048
false
false
false
false
tjarratt/Xcode-Better-Refactor-Tools
refs/heads/master
Fake4SwiftKit/Use Cases/Parse Swift Protocol/Dependencies/XMASFakeProtocolPersister.swift
mit
3
import Foundation @objc open class XMASFakeProtocolPersister : NSObject { fileprivate(set) open var fileManager : XMASFileManager fileprivate(set) open var protocolFaker : XMASSwiftProtocolFaking @objc public init(protocolFaker: XMASSwiftProtocolFaking, fileManager: XMASFileManager) { self.fileManager = fileManager self.protocolFaker = protocolFaker } let generatedFakesDir = "fakes" @objc open func persistFakeForProtocol( _ protocolDecl : ProtocolDeclaration, nearSourceFile: String) throws -> FakeProtocolPersistResults { let dirContainingSource = (nearSourceFile as NSString).deletingLastPathComponent let fakesDir = (dirContainingSource as NSString).appendingPathComponent(generatedFakesDir) let fakeFileName = ["Fake", protocolDecl.name, ".swift"].joined(separator: "") let pathToFake = (fakesDir as NSString).appendingPathComponent(fakeFileName) if !fileManager.fileExists(atPath: fakesDir as String, isDirectory: nil) { try self.fileManager.createDirectory( atPath: fakesDir, withIntermediateDirectories: true, attributes: nil) } do { let fileContents = try self.protocolFaker.fakeForProtocol(protocolDecl) let fileData : Data = fileContents.data(using: String.Encoding.utf8)! _ = fileManager.createFile(atPath: pathToFake, contents: fileData, attributes: nil) } catch let error as NSError { throw error } return FakeProtocolPersistResults.init( path: pathToFake, containingDir: generatedFakesDir ) } } @objc open class FakeProtocolPersistResults : NSObject { fileprivate(set) open var pathToFake : String fileprivate(set) open var directoryName : String public init(path: String, containingDir: String) { pathToFake = path directoryName = containingDir super.init() } }
5e5e9bca03d5cb7f48d0fdf25cd7d516
33.793103
98
0.677899
false
false
false
false
jjochen/photostickers
refs/heads/master
MessagesExtension/Services/StickerFlowLayout.swift
mit
1
// // StickerFlowLayout.swift // PhotoStickers // // Created by Jochen Pfeiffer on 09.04.17. // Copyright © 2017 Jochen Pfeiffer. All rights reserved. // import UIKit struct StickerFlowLayout { private static func minimumItemWidth(in _: CGRect) -> CGFloat { return 90 } static func sectionInsets(in _: CGRect) -> UIEdgeInsets { let inset = CGFloat(12) return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) } static func minimumInterItemSpacing(in _: CGRect) -> CGFloat { return 10 } static func minimumLineSpacing(in bounds: CGRect) -> CGFloat { return minimumInterItemSpacing(in: bounds) } static func itemSize(in bounds: CGRect) -> CGSize { let sectionInsets = self.sectionInsets(in: bounds) let minimumInterItemSpacing = self.minimumInterItemSpacing(in: bounds) let minimumItemWidth = self.minimumItemWidth(in: bounds) let numberOfItems = floor((bounds.width - sectionInsets.left - sectionInsets.right + minimumInterItemSpacing) / (minimumItemWidth + minimumInterItemSpacing)) let maxItemWidth = (bounds.size.width - sectionInsets.left - sectionInsets.right - (numberOfItems - 1) * minimumInterItemSpacing) / numberOfItems let sideLength = floor(maxItemWidth) return CGSize(width: sideLength, height: sideLength) } }
309ac7d73c5edba130623dbc125ede99
32.878049
165
0.692585
false
false
false
false
chrisamanse/iOS-NSDate-Utilities
refs/heads/master
NSDate_Extensions/NSDate+Comparable.swift
mit
1
// // NSDate+Comparable.swift // NSDate_Extensions // // Created by Chris Amanse on 5/12/15. // Copyright (c) 2015 Joe Christopher Paul Amanse. All rights reserved. // // This code is licensed under the MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.isEqualToDate(rhs) } extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } public func >(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedDescending } public func <=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs < rhs || lhs.compare(rhs) == .OrderedSame } public func >=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs > rhs || lhs.compare(rhs) == .OrderedSame }
27fcaa255b5afe4784e922909a2b9204
37.102041
81
0.723473
false
false
false
false
ReactiveKit/ReactiveAlamofire
refs/heads/master
Sources/Request.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import ReactiveKit extension DataRequest { public func toSignal() -> Signal<(URLRequest?, HTTPURLResponse?, Data?), NSError> { return Signal { observer in let request = self .response { response in if let error = response.error { observer.failed(error as NSError) } else { observer.next(response.request, response.response, response.data) observer.completed() } } request.resume() return BlockDisposable { request.cancel() } } } public func toSignal<S: DataResponseSerializerProtocol>(_ responseSerializer: S) -> Signal<S.SerializedObject, NSError> { return Signal { observer in let request = self.response(responseSerializer: responseSerializer) { response in switch response.result { case .success(let value): observer.next(value) observer.completed() case .failure(let error): observer.failed(error as NSError) } } request.resume() return BlockDisposable { request.cancel() } } } public func toDataSignal() -> Signal<Data, NSError> { return toSignal(DataRequest.dataResponseSerializer()) } public func toStringSignal(encoding: String.Encoding? = nil) -> Signal<String, NSError> { return toSignal(DataRequest.stringResponseSerializer(encoding: encoding)) } public func toJSONSignal(options: JSONSerialization.ReadingOptions = .allowFragments) -> Signal<Any, NSError> { return toSignal(DataRequest.jsonResponseSerializer(options: options)) } public func toPropertyListSignal(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Signal<Any, NSError> { return toSignal(DataRequest.propertyListResponseSerializer(options: options)) } } /// Streaming API extension DataRequest { public func toStreamingSignal() -> Signal<Data, NSError> { return Signal { observer in let request = self .stream { data in observer.next(data) }.response { response in if let error = response.error { observer.failed(error as NSError) } else { observer.completed() } } request.resume() return BlockDisposable { request.cancel() } } } // public func toStringStreamingSignal(delimiter: String, encoding: String.Encoding = .utf8) -> Signal<String, NSError> { // return toSignal() // .tryMap { data -> ReactiveKit.Result<String, NSError> in // if let string = String(data: data, encoding: encoding) { // return .success(string) // } else { // return .failure(NSError(domain: "toStringStreamingSignal: Could not decode string!", code: 0, userInfo: nil)) // } // } // .flatMapLatest { string in // Signal<String, NSError>.sequence(string.characters.map { String($0) }) // } // .split { character in // character == delimiter // } // .map { // $0.joined(separator: "") // } // } // // public func toJSONStreamingSignal(delimiter: String = "\n", encoding: String.Encoding = .utf8, options: JSONSerialization.ReadingOptions = .allowFragments) -> Signal<Any, NSError> { // return toStringStreamingSignal(delimiter: delimiter, encoding: encoding) // .map { message in // message.trimmingCharacters(in: .whitespacesAndNewlines) // } // .filter { message in // !message.isEmpty // } // .tryMap { message -> ReactiveKit.Result<Any, NSError> in // do { // guard let data = message.data(using: encoding) else { // return .failure(NSError(domain: "toJSONStreamingSignal: Could not encode string!", code: 0, userInfo: nil)) // } // let json = try JSONSerialization.jsonObject(with: data, options: options) // return .success(json) // } catch { // return .failure(error as NSError) // } // } // } } extension SignalProtocol { public func split(_ isDelimiter: @escaping (Element) -> Bool) -> Signal<[Element], Error> { return Signal { observer in var buffer: [Element] = [] return self.observe { event in switch event { case .next(let element): if isDelimiter(element) { observer.next(buffer) buffer.removeAll() } else { buffer.append(element) } case .completed: observer.completed() case .failed(let error): observer.failed(error) } } } } }
72ae83680cd7c9f5c9a53d5f345ea9db
31.657303
185
0.640977
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Client/Frontend/Extensions/DevicePickerViewController.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import SnapKit protocol DevicePickerViewControllerDelegate { func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) } private struct DevicePickerViewControllerUX { static let TableHeaderRowHeight = CGFloat(50) static let TableHeaderTextFont = UIFont.systemFont(ofSize: 16) static let TableHeaderTextColor = UIColor.Photon.Grey50 static let TableHeaderTextPaddingLeft = CGFloat(20) static let DeviceRowTintColor = UIColor.Photon.Green60 static let DeviceRowHeight = CGFloat(50) static let DeviceRowTextFont = UIFont.systemFont(ofSize: 16) static let DeviceRowTextPaddingLeft = CGFloat(72) static let DeviceRowTextPaddingRight = CGFloat(50) } /// The DevicePickerViewController displays a list of clients associated with the provided Account. /// The user can select a number of devices and hit the Send button. /// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. /// That is up to it's delegate, who can listen for cancellation and success events. enum LoadingState { case LoadingFromCache case LoadingFromServer case Loaded } class DevicePickerViewController: UITableViewController { enum DeviceOrClient: Equatable { case client(RemoteClient) case device(RemoteDevice) var identifier: String? { switch self { case .client(let c): return c.fxaDeviceId case .device(let d): return d.id } } public static func == (lhs: DeviceOrClient, rhs: DeviceOrClient) -> Bool { switch (lhs, rhs) { case (.device(let a), .device(let b)): return a.id == b.id && a.lastAccessTime == b.lastAccessTime case (.client(let a), .client(let b)): return a == b // is equatable case (.device(_), .client(_)): return false case (.client(_), .device(_)): return false } } } var devicesAndClients = [DeviceOrClient]() var profile: Profile? var profileNeedsShutdown = true var pickerDelegate: DevicePickerViewControllerDelegate? var loadState = LoadingState.LoadingFromCache var selectedIdentifiers = Set<String>() // Stores DeviceOrClient.identifier // ShareItem has been added as we are now using this class outside of the ShareTo extension to provide Share To functionality // And in this case we need to be able to store the item we are sharing as we may not have access to the // url later. Currently used only when sharing an item from the Tab Tray from a Preview Action. var shareItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() title = Strings.SendToTitle refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem( title: Strings.SendToCancelButton, style: .plain, target: self, action: #selector(cancel) ) tableView.register(DevicePickerTableViewHeaderCell.self, forCellReuseIdentifier: DevicePickerTableViewHeaderCell.CellIdentifier) tableView.register(DevicePickerTableViewCell.self, forCellReuseIdentifier: DevicePickerTableViewCell.CellIdentifier) tableView.register(DevicePickerNoClientsTableViewCell.self, forCellReuseIdentifier: DevicePickerNoClientsTableViewCell.CellIdentifier) tableView.tableFooterView = UIView(frame: .zero) tableView.allowsSelection = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadCachedClients() } override func numberOfSections(in tableView: UITableView) -> Int { if devicesAndClients.isEmpty { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if devicesAndClients.isEmpty { return 1 } else { if section == 0 { return 1 } else { return devicesAndClients.count } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if !devicesAndClients.isEmpty { if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: DevicePickerTableViewHeaderCell.CellIdentifier, for: indexPath) as! DevicePickerTableViewHeaderCell } else { let clientCell = tableView.dequeueReusableCell(withIdentifier: DevicePickerTableViewCell.CellIdentifier, for: indexPath) as! DevicePickerTableViewCell let item = devicesAndClients[indexPath.row] switch item { case .client(let client): clientCell.nameLabel.text = client.name clientCell.clientType = client.type == "mobile" ? .Mobile : .Desktop case .device(let device): clientCell.nameLabel.text = device.name clientCell.clientType = device.type == "mobile" ? .Mobile : .Desktop } if let id = item.identifier { clientCell.checked = selectedIdentifiers.contains(id) } cell = clientCell } } else { if self.loadState == .Loaded { cell = tableView.dequeueReusableCell(withIdentifier: DevicePickerNoClientsTableViewCell.CellIdentifier, for: indexPath) as! DevicePickerNoClientsTableViewCell } else { cell = UITableViewCell(style: .default, reuseIdentifier: "ClientCell") } } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if devicesAndClients.isEmpty || indexPath.section != 1 { return } tableView.deselectRow(at: indexPath, animated: true) guard let id = devicesAndClients[indexPath.row].identifier else { return } if selectedIdentifiers.contains(id) { selectedIdentifiers.remove(id) } else { selectedIdentifiers.insert(id) } UIView.performWithoutAnimation { // if the selected cell is off-screen when the tableview is first shown, the tableview will re-scroll without disabling animation tableView.reloadRows(at: [indexPath], with: .none) } navigationItem.rightBarButtonItem?.isEnabled = !selectedIdentifiers.isEmpty } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if !devicesAndClients.isEmpty { if indexPath.section == 0 { return DevicePickerViewControllerUX.TableHeaderRowHeight } else { return DevicePickerViewControllerUX.DeviceRowHeight } } else { return tableView.frame.height } } fileprivate func ensureOpenProfile() -> Profile { // If we were not given a profile, open the default profile. This happens in case we are called from an app // extension. That also means that we need to shut down the profile, otherwise the app extension will be // terminated when it goes into the background. if let profile = self.profile { // Re-open the profile if it was shutdown. This happens when we run from an app extension, where we must // make sure that the profile is only open for brief moments of time. if profile.isShutdown { profile._reopen() } return profile } let profile = BrowserProfile(localName: "profile") self.profile = profile self.profileNeedsShutdown = true return profile } // Load cached clients from the profile, triggering a sync to fetch newer data. fileprivate func loadCachedClients() { guard let profile = self.ensureOpenProfile() as? BrowserProfile else { return } self.loadState = .LoadingFromCache // Load and display the cached clients. // Don't shut down the profile here: we immediately call `reloadClients`. profile.remoteClientsAndTabs.getRemoteDevices() >>== { devices in profile.remoteClientsAndTabs.getClients().uponQueue(.main) { result in withExtendedLifetime(profile) { guard let clients = result.successValue else { return } self.update(devices: devices, clients: clients, endRefreshing: false) self.reloadClients() } } } } fileprivate func reloadClients() { guard let profile = self.ensureOpenProfile() as? BrowserProfile, let account = profile.getAccount() else { return } self.loadState = .LoadingFromServer account.updateFxADevices(remoteDevices: profile.remoteClientsAndTabs) >>== { profile.remoteClientsAndTabs.getRemoteDevices() >>== { devices in profile.getClients().uponQueue(.main) { result in guard let clients = result.successValue else { return } withExtendedLifetime(profile) { self.loadState = .Loaded // If we are running from an app extension then make sure we shut down the profile as soon as we are // done with it. if self.profileNeedsShutdown { profile._shutdown() } self.loadState = .Loaded self.update(devices: devices, clients: clients, endRefreshing: true) } } } } } fileprivate func update(devices: [RemoteDevice], clients: [RemoteClient], endRefreshing: Bool) { assert(Thread.isMainThread) guard let profile = self.ensureOpenProfile() as? BrowserProfile, let account = profile.getAccount() else { return } let fxaDeviceIds = devices.compactMap { $0.id } let newRemoteDevices = devices.filter { account.commandsClient.sendTab.isDeviceCompatible($0) } func findClient(forDevice device: RemoteDevice) -> RemoteClient? { return clients.find({ $0.fxaDeviceId == device.id }) } let oldRemoteClients = devices.filter { !account.commandsClient.sendTab.isDeviceCompatible($0) } .compactMap { findClient(forDevice: $0) } let fullList = newRemoteDevices.sorted { $0.id ?? "" > $1.id ?? "" }.map { DeviceOrClient.device($0) } + oldRemoteClients.sorted { $0.guid ?? "" > $1.guid ?? "" }.map { DeviceOrClient.client($0) } // Sort the lists, and compare guids and modified, to see if the list has changed and tableview needs reloading. let isSame = fullList.elementsEqual(devicesAndClients) { new, old in new == old // equatable } guard !isSame else { if endRefreshing { refreshControl?.endRefreshing() } return } devicesAndClients = fullList if devicesAndClients.isEmpty { navigationItem.rightBarButtonItem = nil } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.SendToSendButtonTitle, style: .done, target: self, action: #selector(self.send)) navigationItem.rightBarButtonItem?.isEnabled = false } tableView.reloadData() if endRefreshing { refreshControl?.endRefreshing() } } @objc func refresh() { if let refreshControl = self.refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPoint(x: 0, y: height) } reloadClients() } @objc func cancel() { pickerDelegate?.devicePickerViewControllerDidCancel(self) } @objc func send() { guard let profile = self.ensureOpenProfile() as? BrowserProfile else { return } var pickedItems = [DeviceOrClient]() for id in selectedIdentifiers { if let item = devicesAndClients.find({ $0.identifier == id }) { pickedItems.append(item) } } profile.remoteClientsAndTabs.getRemoteDevices().uponQueue(.main) { result in guard let devices = result.successValue else { return } let pickedDevices: [RemoteDevice] = pickedItems.compactMap { item in switch item { case .client(let client): return devices.find { client.fxaDeviceId == $0.id } case .device(let device): return device } } self.pickerDelegate?.devicePickerViewController(self, didPickDevices: pickedDevices) } // Replace the Send button with a loading indicator since it takes a while to sync // up our changes to the server. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(width: 25, height: 25)) loadingIndicator.color = UIColor.Photon.Grey60 loadingIndicator.startAnimating() let customBarButton = UIBarButtonItem(customView: loadingIndicator) self.navigationItem.rightBarButtonItem = customBarButton } } class DevicePickerTableViewHeaderCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewSectionHeader" let nameLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.font = DevicePickerViewControllerUX.TableHeaderTextFont nameLabel.text = Strings.SendToDevicesListTitle nameLabel.textColor = DevicePickerViewControllerUX.TableHeaderTextColor nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(DevicePickerViewControllerUX.TableHeaderTextPaddingLeft) make.centerY.equalTo(self) make.right.equalTo(self) } preservesSuperviewLayoutMargins = false layoutMargins = .zero separatorInset = .zero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ClientType: String { case Mobile = "deviceTypeMobile" case Desktop = "deviceTypeDesktop" } class DevicePickerTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewCell" var nameLabel: UILabel var checked: Bool = false { didSet { self.accessoryType = checked ? .checkmark : .none } } var clientType = ClientType.Mobile { didSet { self.imageView?.image = UIImage(named: clientType.rawValue) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { nameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) nameLabel.font = DevicePickerViewControllerUX.DeviceRowTextFont nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = .byWordWrapping self.tintColor = DevicePickerViewControllerUX.DeviceRowTintColor self.preservesSuperviewLayoutMargins = false self.selectionStyle = .none } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(DevicePickerViewControllerUX.DeviceRowTextPaddingLeft) make.centerY.equalTo(self.snp.centerY) make.right.equalTo(self.snp.right).offset(-DevicePickerViewControllerUX.DeviceRowTextPaddingRight) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class DevicePickerNoClientsTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerNoClientsTableViewCell" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupHelpView(contentView, introText: Strings.SendToNoDevicesFound, showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise. // Move the separator off screen separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
8046cdbe4814c22c9ff6b46a1be70adb
38.986486
187
0.644418
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift
mit
1
// // PreCompLayer.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// A layer that holds another animation composition. final class PreCompLayerModel: LayerModel { /// The reference ID of the precomp. let referenceID: String /// A value that remaps time over time. let timeRemapping: KeyframeGroup<Vector1D>? /// Precomp Width let width: Double /// Precomp Height let height: Double private enum CodingKeys : String, CodingKey { case referenceID = "refId" case timeRemapping = "tm" case width = "w" case height = "h" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PreCompLayerModel.CodingKeys.self) self.referenceID = try container.decode(String.self, forKey: .referenceID) self.timeRemapping = try container.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .timeRemapping) self.width = try container.decode(Double.self, forKey: .width) self.height = try container.decode(Double.self, forKey: .height) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(referenceID, forKey: .referenceID) try container.encode(timeRemapping, forKey: .timeRemapping) try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) } }
2da518848b4de56cb6243429a65f7d05
28.98
108
0.710474
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/01098-no-stacktrace.swift
apache-2.0
65
// 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 // RUN: not %target-swift-frontend %s -typecheck private class B<C> { init(c: C) { s { func g<U>(h: (A, U) -> U) -> (A, U) -> U { } func f() { } } struct d<f : e, g: e where g.h == f.h> { } protocol e { } enum A : String { case b = "" } let c: A? = nil if c == .b {
a4009ae65f99c56e6c18f980e1895bac
23.6
79
0.645528
false
false
false
false
salvonos/CityPicker
refs/heads/master
Pod/Classes/CityPickerClass.swift
mit
1
// // CityPickerClass.swift // Noemi Official // // Created by LIVECT LAB on 13/03/2016. // Copyright © 2016 LIVECT LAB. All rights reserved. // import UIKit class cityPickerClass { class func getNations() -> (nations:[String], allValues:NSDictionary){ var nations = [String]() var allValues = NSDictionary() let podBundle = NSBundle(forClass: self) if let path = podBundle.pathForResource("countriesToCities", ofType: "json") { do { let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe) do { let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let nationsArray = jsonResult.allKeys as! [String] let sortedNations = nationsArray.sort { $0 < $1 } nations = sortedNations allValues = jsonResult } catch {} } catch {} } return (nations, allValues) } }
4b3bc2f9c59ce3b1203d82104dfa1ca3
25.816327
169
0.520548
false
false
false
false
Malecks/PALette
refs/heads/master
Palette/InterfaceIdiom.swift
mit
1
// // InterfaceIdiom.swift // PALette // // Created by Alexander Mathers on 2016-03-26. // Copyright © 2016 Malecks. All rights reserved. // import Foundation import UIKit enum UIUserInterfaceIdiom : Int { case unspecified case phone case pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 }
f6fae90592b355f3cf50ac0c945f6dc5
39.612903
124
0.698173
false
false
false
false
Qmerce/ios-sdk
refs/heads/master
Apester/ViewControllers/Strip/APEMultipleStripsViewController.swift
mit
1
// // APEMultipleStripsViewController.swift // ApisterKitDemo // // Created by Hasan Sa on 24/02/2019. // Copyright © 2019 Apester. All rights reserved. // import UIKit import ApesterKit class APEMultipleStripsViewController: UIViewController { @IBOutlet private weak var collectionView: UICollectionView! { didSet { collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false } } private var channelTokens: [String] = StripConfigurationsFactory.tokens override func viewDidLoad() { super.viewDidLoad() // update stripView delegates channelTokens.forEach { APEViewService.shared.stripView(for: $0)?.delegate = self } } } extension APEMultipleStripsViewController: UICollectionViewDataSource { static let emptyCellsCount = 2 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.channelTokens.count * Self.emptyCellsCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReuseCellIdentifier", for: indexPath) as! APEStripCollectionViewCell if indexPath.row % Self.emptyCellsCount == 0 { let token = self.channelTokens[indexPath.row / Self.emptyCellsCount] let stripView = APEViewService.shared.stripView(for: token) cell.show(stripView: stripView, containerViewController: self) } return cell } } extension APEMultipleStripsViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.row % Self.emptyCellsCount == 0 { let token = self.channelTokens[indexPath.row / Self.emptyCellsCount] let stripView = APEViewService.shared.stripView(for: token) return CGSize(width: collectionView.bounds.width, height: stripView?.height ?? 0) } return CGSize(width: collectionView.bounds.width, height: 220) } } extension APEMultipleStripsViewController: APEStripViewDelegate { func stripView(_ stripView: APEStripView, didCompleteAdsForChannelToken token: String) { } func stripView(_ stripView: APEStripView, didUpdateHeight height: CGFloat) { self.collectionView.reloadData() } func stripView(_ stripView: APEStripView, didFinishLoadingChannelToken token: String) {} func stripView(_ stripView: APEStripView, didFailLoadingChannelToken token: String) { DispatchQueue.main.async { APEViewService.shared.unloadStripViews(with: [token]) self.collectionView.reloadData() } } }
1917f4003432d4c963f7e4cc52fa5042
36.21519
160
0.713946
false
false
false
false
abitofalchemy/auralML
refs/heads/master
Sandbox/STBlueMS_iOS/W2STApp/MainApp/Demo/BlueVoice/W2STBlueVoiceViewController.swift
bsd-3-clause
1
/** My notes: ** https://stackoverflow.com/questions/34361991/saving-recorded-audio-swift ** https://stackoverflow.com/questions/28233219/recording-1-second-audio-ios * * Removing the ASR code * Work to ** */ import Foundation import MediaPlayer import BlueSTSDK import AVFoundation //import UIKit /** * Audio callback called when an audio buffer can be reused * userData: pointer to our SyncQueue with the buffer to reproduce * queue: audio queue where the buffer will be played * buffer: audio buffer that must be filled */ fileprivate func audioCallback(usedData:UnsafeMutableRawPointer?, queue:AudioQueueRef, buffer:AudioQueueBufferRef){ // SampleQueue *ptr = (SampleQueue*) userData let sampleQueuePtr = usedData?.assumingMemoryBound(to: BlueVoiceSyncQueue.self) //NSData* data = sampleQueuePtr->pop(); let data = sampleQueuePtr?.pointee.pop(); //uint8* temp = (uint8*) buffer->mAudioData let temp = buffer.pointee.mAudioData.assumingMemoryBound(to: UInt8.self); //memcpy(temp,data) data?.copyBytes(to: temp, count: Int(buffer.pointee.mAudioDataByteSize)); // Enqueuing an audio queue buffer after writing to disk? AudioQueueEnqueueBuffer(queue, buffer, 0, nil); } public class W2STBlueVoiceViewController: BlueMSDemoTabViewController, BlueVoiceSelectDelegate, BlueSTSDKFeatureDelegate, AVAudioRecorderDelegate, UITableViewDataSource{ /* sa> see below for base decarasion */ private static let ASR_LANG_PREF="W2STBlueVoiceViewController.AsrLangValue" private static let DEFAULT_ASR_LANG=BlueVoiceLangauge.ENGLISH private static let CODEC="ADPCM" private static let SAMPLING_FREQ_kHz = 8; private static let NUM_CHANNELS = UInt32(1); /* * number of byffer that the sysmte will allocate, each buffer will contain * a sample recived trought the ble connection */ private static let NUM_BUFFERS=18; private static let SAMPLE_TYPE_SIZE = UInt32(2)//UInt32(MemoryLayout<UInt16>.size); //each buffer contains 40 audio sample private static let BUFFER_SIZE = (40*SAMPLE_TYPE_SIZE); /** object used to check if the user has an internet connection */ private var mInternetReachability: Reachability?; //////////////////// GUI reference //////////////////////////////////////// @IBOutlet weak var mCodecLabel: UILabel! @IBOutlet weak var mAddAsrKeyButton: UIButton! @IBOutlet weak var mSampligFreqLabel: UILabel! @IBOutlet weak var mAsrStatusLabel: UILabel! @IBOutlet weak var mSelectLanguageButton: UIButton! @IBOutlet weak var mRecordButton: UIButton! @IBOutlet weak var mPlayButton: UIButton! @IBOutlet weak var mAsrResultsTableView: UITableView! @IBOutlet weak var mAsrRequestStatusLabel: UILabel! private var engine:BlueVoiceASREngine?; private var mFeatureAudio:BlueSTSDKFeatureAudioADPCM?; private var mFeatureAudioSync:BlueSTSDKFeatureAudioADPCMSync?; private var mAsrResults:[String] = []; var recordingSession: AVAudioSession! var whistleRecorder: AVAudioRecorder! var whistlePlayer: AVAudioPlayer! var playButton: UIButton! /////////////////// AUDIO ////////////////////////////////////////////////// //https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription private var mAudioFormat = AudioStreamBasicDescription( mSampleRate: Float64(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000), mFormatID: kAudioFormatLinearPCM, mFormatFlags: kLinearPCMFormatFlagIsSignedInteger, mBytesPerPacket: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE * W2STBlueVoiceViewController.NUM_CHANNELS, mFramesPerPacket: 1, mBytesPerFrame: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE*W2STBlueVoiceViewController.NUM_CHANNELS, mChannelsPerFrame: W2STBlueVoiceViewController.NUM_CHANNELS, mBitsPerChannel: UInt32(8) * W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE, mReserved: 0); //audio queue where play the sample private var queue:AudioQueueRef?; //queue of audio buffer to play private var buffers:[AudioQueueBufferRef?] = Array(repeating:nil, count: NUM_BUFFERS) //syncronized queue used to store the audio sample from the node // when an audio buffer is free it will be filled with sample from this object private var mSyncAudioQueue:BlueVoiceSyncQueue?; //variable where store the audio before send to an speech to text service private var mRecordData:Data?; /////////CONTROLLER STATUS//////////// private var mIsMute:Bool=false; private var mIsRecording:Bool=false; override public func viewDidLoad(){ super.viewDidLoad() view.backgroundColor = UIColor.gray //set the constant string mCodecLabel.text = mCodecLabel.text!+W2STBlueVoiceViewController.CODEC mSampligFreqLabel.text = mSampligFreqLabel.text!+String(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz)+" kHz" newLanguageSelected(getDefaultLanguage()); mAsrResultsTableView.dataSource=self; /* ** here I add ** */ recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { self.loadRecordingUI() } else { self.loadFailUI() } } } } catch { self.loadFailUI() } // UI mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) } func loadRecordingUI() { // mRecordButton = UIButton() mRecordButton.translatesAutoresizingMaskIntoConstraints = false mRecordButton.setTitle("Tap to Record", for: .normal) mRecordButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1) mRecordButton.addTarget(self, action: #selector(onRecordButtonPressed(_:)), for: .touchUpInside) // stackView.addArrangedSubview(recordButton) playButton = UIButton() playButton.translatesAutoresizingMaskIntoConstraints = false playButton.setTitle("Tap to Play", for: .normal) playButton.isHidden = true playButton.alpha = 0 playButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1) playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside) // stackView.addArrangedSubview(playButton) } func loadFailUI() { let failLabel = UILabel() failLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) failLabel.text = "Recording failed: please ensure the app has access to your microphone." failLabel.numberOfLines = 0 // self.view.addArrangedSubview(failLabel) self.view.addSubview(failLabel) } class func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } class func getWhistleURL() -> URL { NSLog("test: getting the file url"); return getDocumentsDirectory().appendingPathComponent("whistle.m4a") } /* * enable the ble audio stremaing and initialize the audio queue */ override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); mFeatureAudio = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCM.self) as! BlueSTSDKFeatureAudioADPCM?; mFeatureAudioSync = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCMSync.self) as! BlueSTSDKFeatureAudioADPCMSync?; //if both feature are present enable the audio if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{ audio.add(self); audioSync.add(self); self.node.enableNotification(audio); self.node.enableNotification(audioSync); initAudioQueue(); initRecability(); NSLog(">> audio features ARE present!!") }else{ NSLog(">> both features are not present!!") } } /** * stop the ble audio streaming and the audio queue */ override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated); if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{ deInitAudioQueue(); audio.remove(self); audioSync.remove(self); self.node.disableNotification(audio); self.node.disableNotification(audioSync); } } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated); engine?.destroyListener(); } private func initAudioQueue(){ //create the queue where store the sample mSyncAudioQueue = BlueVoiceSyncQueue(size: W2STBlueVoiceViewController.NUM_BUFFERS); //create the audio queue AudioQueueNewOutput(&mAudioFormat,audioCallback, &mSyncAudioQueue,nil, nil, 0, &queue); //create the system audio buffer that will be filled with the data inside the mSyncAudioQueue for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{ AudioQueueAllocateBuffer(queue!, W2STBlueVoiceViewController.BUFFER_SIZE, &buffers[i]); if let buffer = buffers[i]{ buffer.pointee.mAudioDataByteSize = W2STBlueVoiceViewController.BUFFER_SIZE; memset(buffer.pointee.mAudioData,0,Int(W2STBlueVoiceViewController.BUFFER_SIZE)); AudioQueueEnqueueBuffer(queue!, buffer, 0, nil); } }//for //start playing the audio AudioQueueStart(queue!, nil); mIsMute=false; } /// free the audio initialized audio queues private func deInitAudioQueue(){ AudioQueueStop(queue!, true); for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{ if let buffer = buffers[i]{ AudioQueueFreeBuffer(queue!,buffer); } } } /// function called when the net state change /// /// - Parameter notifier: object where read the net state private func onReachabilityChange(_ notifier:Reachability?){ let netStatus = notifier?.currentReachabilityStatus(); if let status = netStatus{ if(status == NotReachable){ mAsrStatusLabel.text="Disabled"; }else{ NSLog("attemping to load ASR Engine"); loadAsrEngine(getDefaultLanguage()); } } } /// register this class as a observer of the net state private func initRecability(){ NotificationCenter.default.addObserver(forName:Notification.Name.reachabilityChanged, object:nil, queue:nil) { notification in if(!(notification.object is Reachability)){ return; } let notificaitonObj = notification.object as! Reachability?; self.onReachabilityChange(notificaitonObj); } mInternetReachability = Reachability.forInternetConnection(); mInternetReachability?.startNotifier(); onReachabilityChange(mInternetReachability); } private func deInitRecability(){ mInternetReachability?.stopNotifier(); } /// get the selected language for the asr engine /// /// - Returns: <#return value description#> public func getDefaultLanguage()->BlueVoiceLangauge{ // let lang = loadAsrLanguage(); return W2STBlueVoiceViewController.DEFAULT_ASR_LANG; } /// called when the user select a new language for the asr /// it store this information an reload the engine /// /// - Parameter language: language selected public func newLanguageSelected(_ language:BlueVoiceLangauge){ // loadAsrEngine(language); // storeAsrLanguage(language); mSelectLanguageButton.setTitle(language.rawValue, for:UIControlState.normal) } /// load the language from the user preference /// /// - Returns: language stored in the preference or the default one // private func loadAsrLanguage()->BlueVoiceLangauge?{ // let userPref = UserDefaults.standard; // let langString = userPref.string(forKey: W2STBlueVoiceViewController.ASR_LANG_PREF); // if let str = langString{ // return BlueVoiceLangauge(rawValue: str); // } // return nil; // } /// store in the preference the selected language /// /// - Parameter language: language to store private func storeAsrLanguage(_ language:BlueVoiceLangauge){ let userPref = UserDefaults.standard; userPref.setValue(language.rawValue, forKey:W2STBlueVoiceViewController.ASR_LANG_PREF); } /// register this class as a delegate of the BlueVoiceSelectLanguageViewController /// /// - Parameters: /// - segue: segue to prepare /// - sender: object that start the segue override public func prepare(for segue: UIStoryboardSegue, sender: Any?) { let dest = segue.destination as? BlueVoiceSelectLanguageViewController; if let dialog = dest{ dialog.delegate=self; } } /// call when the user press the mute button, it mute/unmute the audio /// /// - Parameter sender: button where the user click @IBAction func onMuteButtonClick(_ sender: UIButton) { var img:UIImage?; if(!mIsMute){ img = UIImage(named:"volume_off"); AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); }else{ img = UIImage(named:"volume_on"); AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); } mIsMute = !mIsMute; sender.setImage(img, for:.normal); } /// check that the audio engine has a valid service key /// /// - Returns: true if the service has a valid service key or it does not need a key, /// false otherwise private func checkAsrKey() -> Bool{ if let engine = engine{ if(engine.needAuthKey && !engine.hasLoadedAuthKey()){ showErrorMsg("Please add the engine key", title: "Engine Fail", closeController: false); return false;// orig bool is False }else{ return true; } } return false; } /// Start the voice to text, if the engine can manage the continuos recognition private func onContinuousRecognizerStart(){ // NSLog("Entered on cont recognizer start"); // guard checkAsrKey() else{ // return; // } // mRecordButton.setTitle("Stop recongition", for: .normal); // if(!mIsMute){ // AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); // } // engine?.startListener(); // mIsRecording=true; } /// Stop a continuos recognition private func onContinuousRecognizerStop(){ // mIsRecording=false; // if(!mIsMute){ // AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); // } // if let engine = engine{ // engine.stopListener(); // setRecordButtonTitle(engine); // } } /// Start a non continuos voice to text service private func onRecognizerStart(){ /* Unused: guard checkAsrKey() else{ return; }*/ if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); } let audioURL = W2STBlueVoiceViewController.getWhistleURL() print(audioURL.absoluteString) mRecordData = Data(); engine?.startListener(); mIsRecording=true; let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { // 5 whistleRecorder = try AVAudioRecorder(url: audioURL, settings: settings) whistleRecorder.delegate = self whistleRecorder.record() } catch { finishRecording(success: false) } } /// Stop a non continuos voice to text service, and send the recorded data /// to the service private func onRecognizerStop(){ print ("RECOGNIZER STOP..."); mIsRecording=false; mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) // print (mIsRecording); if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); } if let engine = engine{ if(mRecordData != nil){ print ("Data is not nil"); // _ = engine.sendASRRequest(audio: mRecordData!, callback: self); mRecordData=nil; } engine.stopListener(); setRecordButtonTitle(engine); print ("setRecordButtonTitle") } } /// set the starting value for the record button /// who is calling on this? /// - Parameter asrEngine: voice to text engine that will be used private func setRecordButtonTitle(_ asrEngine: BlueVoiceASREngine!){ let recorTitle = asrEngine.hasContinuousRecognizer ? "Start recongition" : "Keep press to record" print ("mIsRecording:",mIsRecording) mRecordButton.setTitle(recorTitle, for: .normal); } /// call when the user release the record button, it stop a non contiuos /// voice to text /// /// - Parameter sender: button released @IBAction func onRecordButtonRelease(_ sender: UIButton) { if (engine?.hasContinuousRecognizer == false){ print ("onRecordButton Released") // onRecognizerStop(); } } /// call when the user press the record buttom, it start the voice to text /// service /// /// - Parameter sender: button pressed @IBAction func onRecordButtonPressed(_ sender: UIButton) { print("Button Pressed"); // engine?.hasContinousRecognizer does not work, so it will be taken out for now // if let hasContinuousRecognizer = engine?.hasContinuousRecognizer{ // if (hasContinuousRecognizer){ // if(mIsRecording){ // NSLog("Is recording"); // onContinuousRecognizerStop(); // }else{ // onContinuousRecognizerStart(); // // }//if isRecording // }else{ if (mIsRecording) { onRecognizerStop() mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) mRecordButton.setTitle("Keep Pressed to Record!!!!!!!", for: .normal); }else{ onRecognizerStart(); // in this func we set the mIsRecording mRecordButton.setTitle("Stop Recording", for: .normal); mRecordButton.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1) engine?.startListener(); mIsRecording=true; } // }//if hasContinuos // }else{ print ("not engine has cont recognizer"); }//if let if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); } }//onRecordButtonPressed public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { NSLog("audioRecorderDidFinishRecording"); if !flag { finishRecording(success: false) } } /// call when the user press the add key button, it show the popup to insert /// the key /// /// - Parameter sender: button pressed @IBAction func onAddAsrKeyButtonClick(_ sender: UIButton) { let insertKeyDialog = engine?.getAuthKeyDialog(); if let viewContoller = insertKeyDialog { viewContoller.modalPresentationStyle = .popover; self.present(viewContoller, animated: false, completion: nil); let presentationController = viewContoller.popoverPresentationController; presentationController?.sourceView = sender; presentationController?.sourceRect = sender.bounds }//if let } /// create a new voice to text service that works with the selected language /// /// - Parameter language: voice language private func loadAsrEngine(_ language:BlueVoiceLangauge){ if(engine != nil){ engine!.destroyListener(); } let samplingRateHz = UInt((W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000)) engine = BlueVoiceASREngineUtil.getEngine(samplingRateHz:samplingRateHz,language: language); if let asrEngine = engine{ mAsrStatusLabel.text = asrEngine.name; mAddAsrKeyButton.isHidden = !asrEngine.needAuthKey; let asrTitle = asrEngine.hasLoadedAuthKey() ? "Change Service Key" : "Add Service Key"; mAddAsrKeyButton.setTitle(asrTitle, for:UIControlState.normal) setRecordButtonTitle(asrEngine); } } func finishRecording(success: Bool) { view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1) whistleRecorder.stop() whistleRecorder = nil if success { mRecordButton.setTitle("(again)Tap to Re-record", for: .normal) // if playButton.isHidden { // UIView.animate(withDuration: 0.35) { [unowned self] in // self.playButton.isHidden = false // self.playButton.alpha = 1 // } // } // navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTapped)) } else { mRecordButton.setTitle("(start)Tap to Record", for: .normal) let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } func playTapped() { let audioURL = W2STBlueVoiceViewController.getWhistleURL() do { whistlePlayer = try AVAudioPlayer(contentsOf: audioURL) whistlePlayer.play() } catch { let ac = UIAlertController(title: "Playback failed", message: "Problem playing your whistle; please try re-recording.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } /////////////////////// BlueSTSDKFeatureDelegate /////////////////////////// /// call when the BlueSTSDKFeatureAudioADPCM has new data, it will enque the data /// to be play by the sistem and send it to the asr service if it is recording the audio /// /// - Parameters: /// - feature: feature that generate the new data /// - sample: new data private func didAudioUpdate(_ feature: BlueSTSDKFeatureAudioADPCM, sample: BlueSTSDKFeatureSample){ let sampleData = BlueSTSDKFeatureAudioADPCM.getLinearPCMAudio(sample); if let data = sampleData{ mSyncAudioQueue?.push(data: data) if(mIsRecording){ // if(engine!.hasContinuousRecognizer){ // _ = engine!.sendASRRequest(audio: data, callback: self); // }else{ if(mRecordData != nil){ objc_sync_enter(mRecordData); mRecordData?.append(data); objc_sync_exit(mRecordData); // }// mRecordData!=null } } // else { print ("not recording");} //if is Recording }//if data!=null } /// call when the BlueSTSDKFeatureAudioADPCMSync has new data, it is used to /// correclty decode the data from the the BlueSTSDKFeatureAudioADPCM feature /// /// - Parameters: /// - feature: feature that generate new data /// - sample: new data private func didAudioSyncUpdate(_ feature: BlueSTSDKFeatureAudioADPCMSync, sample: BlueSTSDKFeatureSample){ // NSLog("test"); mFeatureAudio?.audioManager.setSyncParam(sample); } /// call when a feature gets update /// /// - Parameters: /// - feature: feature that get update /// - sample: new feature data public func didUpdate(_ feature: BlueSTSDKFeature, sample: BlueSTSDKFeatureSample) { if(feature .isKind(of: BlueSTSDKFeatureAudioADPCM.self)){ self.didAudioUpdate(feature as! BlueSTSDKFeatureAudioADPCM, sample: sample); } if(feature .isKind(of: BlueSTSDKFeatureAudioADPCMSync.self)){ self.didAudioSyncUpdate(feature as! BlueSTSDKFeatureAudioADPCMSync, sample: sample); } } //////////////////////////BlueVoiceAsrRequestCallback/////////////////////////// /// callback call when the asr engin has a positive results, the reult table /// will be updated wit the new results /// /// - Parameter text: world say from the user func onAsrRequestSuccess(withText text:String ){ print("ASR Success:"+text); mAsrResults.append(text); DispatchQueue.main.async { self.mAsrResultsTableView.reloadData(); self.mAsrRequestStatusLabel.isHidden=true; } } /// callback when some error happen during the voice to text translation /// /// - Parameter error: error during the voice to text translation func onAsrRequestFail(error:BlueVoiceAsrRequestError){ print("ASR Fail:"+error.rawValue.description); DispatchQueue.main.async { self.mAsrRequestStatusLabel.text = error.description; self.mAsrRequestStatusLabel.isHidden=false; if(self.mIsRecording){ //if an error happen during the recording, stop it if(self.engine!.hasContinuousRecognizer){ self.onContinuousRecognizerStop(); }else{ self.onRecognizerStop(); } } } } /////////////////////// TABLE VIEW DATA DELEGATE ///////////////////////// public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return mAsrResults.count; } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ var cell = tableView.dequeueReusableCell(withIdentifier: "AsrResult"); if (cell == nil){ cell = UITableViewCell(style: .default, reuseIdentifier: "AsrResult"); cell?.selectionStyle = .none; } cell?.textLabel?.text=mAsrResults[indexPath.row]; return cell!; } }
7a91797bd31aab92e45f4cf77acec021
36.782205
160
0.610053
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
refs/heads/master
DNSwiftProject/DNSwiftProject/Classes/Expend/DNTool/LocalNotificationHelper.swift
apache-2.0
1
// // LocalNotificationHelper.swift // DNSwiftProject // // Created by mainone on 16/12/23. // Copyright © 2016年 wjn. All rights reserved. // https://github.com/AhmettKeskin/LocalNotificationHelper import UIKit import AVKit class LocalNotificationHelper: NSObject { let LOCAL_NOTIFICATION_CATEGORY : String = "LocalNotificationCategory" // MARK: - Shared Instance class func sharedInstance() -> LocalNotificationHelper { struct Singleton { static var sharedInstance = LocalNotificationHelper() } return Singleton.sharedInstance } // MARK: - Schedule Notification func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, userInfo: [NSObject: AnyObject]?) { let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, soundName: String, userInfo: [NSObject: AnyObject]?){ let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, soundName: String, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } // MARK: - Present Notification func presentNotificationWithKey(key: String, title: String, message: String, soundName: String, userInfo: [NSObject: AnyObject]?) { let notification = notificationWithTitle(key: key, title: title, message: message, date: nil, userInfo: ["key" as NSObject: key as AnyObject], soundName: nil, hasAction: true) UIApplication.shared.presentLocalNotificationNow(notification) } // MARK: - Create Notification func notificationWithTitle(key : String, title: String, message: String, date: NSDate?, userInfo: [NSObject: AnyObject]?, soundName: String?, hasAction: Bool) -> UILocalNotification { var dct : Dictionary<String,AnyObject> = userInfo as! Dictionary<String,AnyObject> dct["key"] = String(stringLiteral: key) as AnyObject? let notification = UILocalNotification() notification.alertAction = title notification.alertBody = message notification.userInfo = dct notification.soundName = soundName ?? UILocalNotificationDefaultSoundName notification.fireDate = date as Date? notification.hasAction = hasAction return notification } func getNotificationWithKey(key : String) -> UILocalNotification { var notif : UILocalNotification? for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ notif = notification break } return notif! } func cancelNotification(key : String){ for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ UIApplication.shared.cancelLocalNotification(notification) break } } func getAllNotifications() -> [UILocalNotification]? { return UIApplication.shared.scheduledLocalNotifications } func cancelAllNotifications() { UIApplication.shared.cancelAllLocalNotifications() } func registerUserNotificationWithActionButtons(actions : [UIUserNotificationAction]){ let category = UIMutableUserNotificationCategory() category.identifier = LOCAL_NOTIFICATION_CATEGORY category.setActions(actions, for: UIUserNotificationActionContext.default) let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: NSSet(object: category) as? Set<UIUserNotificationCategory>) UIApplication.shared.registerUserNotificationSettings(settings) } func registerUserNotification(){ let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) } func createUserNotificationActionButton(identifier : String, title : String) -> UIUserNotificationAction{ let actionButton = UIMutableUserNotificationAction() actionButton.identifier = identifier actionButton.title = title actionButton.activationMode = UIUserNotificationActivationMode.background actionButton.isAuthenticationRequired = true actionButton.isDestructive = false return actionButton } }
d90fee0e9ce443b75a023591c9bd7d76
44.438462
190
0.701541
false
false
false
false
gnachman/iTerm2
refs/heads/master
SearchableComboListView/SearchableComboListViewController.swift
gpl-2.0
2
// // SearchableComboListViewController.swift // SearchableComboListView // // Created by George Nachman on 1/24/20. // import AppKit @objc(iTermSearchableComboListViewControllerDelegate) protocol SearchableComboListViewControllerDelegate: NSObjectProtocol { func searchableComboListViewController(_ listViewController: SearchableComboListViewController, didSelectItem item: SearchableComboViewItem?) } class SearchableComboListViewController: NSViewController { @IBOutlet public weak var tableView: SearchableComboTableView! @IBOutlet public weak var searchField: NSSearchField! @IBOutlet public weak var visualEffectView: NSVisualEffectView! private var closeOnSelect = true @objc(delegate) @IBOutlet public weak var delegate: SearchableComboListViewControllerDelegate? let groups: [SearchableComboViewGroup] public var selectedItem: SearchableComboViewItem? { didSet { let _ = view tableViewController!.selectedTag = selectedItem?.tag ?? -1 } } public var insets: NSEdgeInsets { let frame = view.convert(searchField.bounds, from: searchField) return NSEdgeInsets(top: NSMaxY(view.bounds) - NSMaxY(frame), left: NSMinX(frame), bottom: 0, right: NSMaxX(view.bounds) - NSMaxX(frame)) } public var tableViewController: SearchableComboTableViewController? init(groups: [SearchableComboViewGroup]) { self.groups = groups super.init(nibName: "SearchableComboView", bundle: Bundle(for: SearchableComboListViewController.self)) } override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { preconditionFailure() } required init?(coder: NSCoder) { preconditionFailure() } public override func awakeFromNib() { tableViewController = SearchableComboTableViewController(tableView: tableView, groups: groups) tableViewController?.delegate = self visualEffectView.blendingMode = .behindWindow; visualEffectView.material = .menu; visualEffectView.state = .active; } func item(withTag tag: Int) -> SearchableComboViewItem? { for group in groups { for item in group.items { if item.tag == tag { return item } } } return nil } } extension SearchableComboListViewController: NSTextFieldDelegate { @objc(controlTextDidChange:) public func controlTextDidChange(_ obj: Notification) { tableViewController?.filter = searchField.stringValue } public override func viewWillAppear() { view.window?.makeFirstResponder(searchField) } } extension SearchableComboListViewController: SearchableComboTableViewControllerDelegate { func searchableComboTableViewController(_ tableViewController: SearchableComboTableViewController, didSelectItem item: SearchableComboViewItem?) { selectedItem = item delegate?.searchableComboListViewController(self, didSelectItem: item) if closeOnSelect { view.window?.orderOut(nil) } } func searchableComboTableViewControllerGroups(_ tableViewController: SearchableComboTableViewController) -> [SearchableComboViewGroup] { return groups } } extension SearchableComboListViewController: SearchableComboListSearchFieldDelegate { func searchFieldPerformKeyEquivalent(with event: NSEvent) -> Bool { guard let window = searchField.window else { return false } guard let firstResponder = window.firstResponder else { return false } guard let textView = firstResponder as? NSTextView else { return false } guard window.fieldEditor(false, for: nil) != nil else { return false } guard searchField == textView.delegate as? NSSearchField else { return false } let mask: NSEvent.ModifierFlags = [.shift, .control, .option, .command] guard event.modifierFlags.intersection(mask) == [] else { return super.performKeyEquivalent(with: event) } if event.keyCode == 125 /* down arrow */ || event.keyCode == 126 /* up arrow */ { // TODO: Prevent reentrancy? closeOnSelect = false tableView.window?.makeFirstResponder(tableView) tableView.keyDown(with: event) closeOnSelect = true return true } return super.performKeyEquivalent(with: event) } }
e8a70e1607d3718958e45ad41ed9d25e
35.19084
140
0.659776
false
false
false
false
bradhowes/vhtc
refs/heads/master
VariableHeightTableCells/UINib+Extensions.swift
mit
1
// // UINib+Extensions.swift // VariableHeightTableCells // // Created by Brad Howes on 8/1/17. // Copyright © 2017 Brad Howes. All rights reserved. // import UIKit /** Internal class that allows us to find the bundle that contains it. */ private class OurBundle: NSObject { static let name = "BundleName" /// Obtain the Bundle that contains ourselves and our resources public static var bundle: Bundle = { // This is convoluted to support instantiation within Xcode due to IB processing and CocoaPods processing which // will have different results. // let bundle = Bundle(for: OurBundle.self) if let path = bundle.path(forResource: OurBundle.name, ofType: "bundle") { if let inner = Bundle(path: path) { // This is the result for proper CocoaPods support // return inner } } // This is the result for non-CocoaPods (e.g. Xcode) support // return bundle }() } extension UINib { /** Instantiate a new NIB using a CellIdent enumeration to determine which one. Only works if the CellIdent's `rawString` value is the same as the name of a NIB file in the main bundle. - parameter ident: the NIB to load */ convenience init(ident: CellIdent) { let nibName: String = ident.rawValue self.init(nibName: nibName, bundle: OurBundle.bundle) } /** Generic class method that will instantiate a NIB based on the given kind value, where T is the view class name for instance in the NIB. - parameter kind: the key to work with - returns: instance of T */ class func instantiate<T>(ident: CellIdent) -> T { return UINib(ident: ident).instantiate(withOwner: nil, options: nil)[0] as! T } }
55d921ac14e38b890a64ac53ae3083f3
28.31746
119
0.63346
false
false
false
false
ruslanskorb/CoreStore
refs/heads/master
CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV1.swift
mit
1
// // OrganismV1.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/21. // Copyright © 2018 John Rommel Estropia. All rights reserved. // import Foundation import CoreData class OrganismV1: NSManagedObject, OrganismProtocol { @NSManaged var dna: Int64 @NSManaged var hasHead: Bool @NSManaged var hasTail: Bool // MARK: OrganismProtocol func mutate() { self.hasHead = arc4random_uniform(2) == 1 self.hasTail = arc4random_uniform(2) == 1 } }
4033c98efcffd42657db0bbd0765ad0e
20.08
63
0.654649
false
false
false
false
findmybusnj/findmybusnj-swift
refs/heads/master
findmybusnj-widget/Presenters/WidgetBannerPresenter.swift
gpl-3.0
1
// // WidgetBannerPresenter.swift // findmybusnj // // Created by David Aghassi on 2/21/17. // Copyright © 2017 David Aghassi. All rights reserved. // import UIKit // Dependencies import SwiftyJSON import findmybusnj_common /** Class for managing the next bus banner at the top of the widget */ class WidgetBannerPresenter: ETAPresenter { var sanitizer = JSONSanitizer() /** Assigns the banner the proper string based on the current arrival information */ func assignTextForArrivalBanner(label: UILabel, json: JSON) { label.text = "The next bus will be" let arrivalCase = determineArrivalCase(json: json) switch arrivalCase { case "Arrived": label.text = "The next bus has \(arrivalCase.lowercased())" return case"Arriving": label.text = "The next bus is \(arrivalCase.lowercased())" return case "Delay": label.text = "\(label.text ?? "") delayed" return default: let arrivalTime = sanitizer.getSanitizedArrivaleTimeAsInt(json) label.text = "\(label.text ?? "") \(arrivalTime.description) min." return } } // no-ops since they aren't used by this presenter func formatCellForPresentation(_ cell: UITableViewCell, json: JSON) {} func assignArrivalTimeForJson(_ cell: UITableViewCell, json: JSON) {} func assignBusAndRouteTextForJson(_ cell: UITableViewCell, json: JSON) {} }
0a31f9b938d892aca0c639851566a12a
27.428571
80
0.691314
false
false
false
false
cikelengfeng/Jude
refs/heads/master
Jude/Antlr4/atn/LexerCustomAction.swift
mit
2
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// Executes a custom lexer action by calling {@link org.antlr.v4.runtime.Recognizer#action} with the /// rule and action indexes assigned to the custom action. The implementation of /// a custom action is added to the generated code for the lexer in an override /// of {@link org.antlr.v4.runtime.Recognizer#action} when the grammar is compiled. /// /// <p>This class may represent embedded actions created with the <code>{...}</code> /// syntax in ANTLR 4, as well as actions created for lexer commands where the /// command argument could not be evaluated when the grammar was compiled.</p> /// /// - Sam Harwell /// - 4.2 public final class LexerCustomAction: LexerAction { fileprivate let ruleIndex: Int fileprivate let actionIndex: Int /// Constructs a custom lexer action with the specified rule and action /// indexes. /// /// - parameter ruleIndex: The rule index to use for calls to /// {@link org.antlr.v4.runtime.Recognizer#action}. /// - parameter actionIndex: The action index to use for calls to /// {@link org.antlr.v4.runtime.Recognizer#action}. public init(_ ruleIndex: Int, _ actionIndex: Int) { self.ruleIndex = ruleIndex self.actionIndex = actionIndex } /// Gets the rule index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. /// /// - returns: The rule index for the custom action. public func getRuleIndex() -> Int { return ruleIndex } /// Gets the action index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. /// /// - returns: The action index for the custom action. public func getActionIndex() -> Int { return actionIndex } /// {@inheritDoc} /// /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CUSTOM}. public override func getActionType() -> LexerActionType { return LexerActionType.custom } /// Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} /// index at the time the action is executed. /// /// <p>Custom actions are position-dependent since they may represent a /// user-defined embedded action which makes calls to methods like /// {@link org.antlr.v4.runtime.Lexer#getText}.</p> /// /// - returns: This method returns {@code true}. override public func isPositionDependent() -> Bool { return true } /// {@inheritDoc} /// /// <p>Custom actions are implemented by calling {@link org.antlr.v4.runtime.Lexer#action} with the /// appropriate rule and action indexes.</p> override public func execute(_ lexer: Lexer) throws { try lexer.action(nil, ruleIndex, actionIndex) } override public var hashValue: Int { var hash: Int = MurmurHash.initialize() hash = MurmurHash.update(hash, getActionType().rawValue) hash = MurmurHash.update(hash, ruleIndex) hash = MurmurHash.update(hash, actionIndex) return MurmurHash.finish(hash, 3) } } public func ==(lhs: LexerCustomAction, rhs: LexerCustomAction) -> Bool { if lhs === rhs { return true } return lhs.ruleIndex == rhs.ruleIndex && lhs.actionIndex == rhs.actionIndex }
c6fceb89a4bc5d3af6bc815962437f1e
35.181818
103
0.666667
false
false
false
false
google/JacquardSDKiOS
refs/heads/main
JacquardSDK/Classes/IMUDataCollection/IMUModuleProtocol.swift
apache-2.0
1
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Combine import Foundation /// Information about the current state of IMU session download. public enum IMUSessionDownloadState { /// Downloading of session is in progress, contains progress percentage. case downloading(Int) /// Session has been downloaded, contains downloaded file path. case downloaded(URL) } /// Metadata for a recorded IMU session. /// /// All data collected as part of a data collection session can be organized with the following hierarchy: /// Campaign /// - Group /// - Session /// - Subject (User) /// A campaign sets the overall goal for a data collection exercise. /// Campaigns may contain one or more groups which in turn can contain one or more session which may contain one or more subjects. /// For example, Campaign 1234 consists of motion data gathered while the subject is walking. /// Data collection for Group 5 under campaign 1234 is recorded at 2pm on July 15 2021 and has 10 subjects/users. /// Group 5 may carry out multiple Sessions. Therefore, each data collection session needs to be labelled with the /// campaign identifier, group identifier, session identifier and subject identifier. public struct IMUSessionInfo: Codable { /// Unique indentfier for the IMU recording. public let sessionID: String /// Identifies the Campaign of a recording session. public let campaignID: String /// Identifies the group or setting of a recording session. public let groupID: String /// Product used for recording the IMU Data. public let productID: String /// Indentfier for the Subject/User performing the motion. public let subjectID: String // This can be used to validate the size of the downloaded raw file. let fsize: UInt32 // CRC16 (CCITT) of the data file. let crc16: UInt32 init(trial: Google_Jacquard_Protocol_DataCollectionTrialList) { self.sessionID = trial.trialID self.campaignID = trial.campaignID self.groupID = trial.sessionID self.productID = trial.productID guard let trialData = trial.trialData.first, let sensorData = trialData.sensorData.first else { preconditionFailure("Cannot have a session without trial or sensor data") } self.subjectID = trialData.subjectID self.fsize = sensorData.fsize self.crc16 = sensorData.crc16 } init(metadata: Google_Jacquard_Protocol_DataCollectionMetadata) { self.sessionID = metadata.trialID self.campaignID = metadata.campaignID self.groupID = metadata.sessionID self.productID = metadata.productID self.subjectID = metadata.subjectID self.fsize = 0 self.crc16 = 0 } } /// Provides an interface to perform various operations related to IMU. public protocol IMUModule { /// Configures the tag for IMU data access. /// /// Before accessing IMU data, the tag must have IMU module loaded and activated. /// This method will perform all required steps asynchronously and publish when /// completed. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule activation was /// successful or will publish a `ModuleError` in case of an error. func initialize() -> AnyPublisher<Void, ModuleError> /// Activates the module. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule activation was /// successful or a `ModuleError` in case of failure. func activateModule() -> AnyPublisher<Void, ModuleError> /// Deactivates the module. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule deactivation was /// successful or a `ModuleError` in case of failure. func deactivateModule() -> AnyPublisher<Void, ModuleError> /// Starts recording IMU data. /// /// Parameters cannot be empty, /// - Parameters: /// - sessionID: Unique id provided by the client app. Should be non empty & less than 30 characters. /// - campaignID: Identifies the Campaign of a recording session. Should be non empty & less than 30 characters. /// - groupID: Identifies the Group or setting of a recording session. Should be non empty & less than 30 characters. /// - productID: Identifies the Product used for recording the IMU Data. Should be non empty & less than 30 characters. /// - subjectID: Indentfier for the Subject/User performing the motion. Should be non empty & less than 30 characters. /// - Returns: Any publisher with a `DataCollectionStatus` Result. Verify status to confirm IMU recording was started /// or return an error if recording could not be started. func startRecording( sessionID: String, campaignID: String, groupID: String, productID: String, subjectID: String ) -> AnyPublisher<DataCollectionStatus, Error> /// Stops the current IMU recording session. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMU recording was stopped /// or will publish an error if recording could not be stopped. func stopRecording() -> AnyPublisher<Void, Error> /// Requests Tag to send IMU sessions. /// /// - Returns: Any publisher that publishes `IMUSessionInfo` objects available on the tag, /// or will publish an error if List sessions request was not acknowledged by the Tag. func listSessions() -> AnyPublisher<IMUSessionInfo, Error> /// Deletes a particular session from the device. /// /// - Parameter session: IMU session to delete. /// - Returns: Any publisher with a `Void` Result, indicating that session was erased /// or will publish an error if the session could not be erased from the tag. func eraseSession(session: IMUSessionInfo) -> AnyPublisher<Void, Error> /// Deletes all sessions from the device. /// /// - Returns: Any publisher with a `Void` Result, indicating that all sessions were erased /// or will publish an error if the sessions could not be erased from the tag. func eraseAllSessions() -> AnyPublisher<Void, Error> /// Retrieves data for an IMUSesion. /// /// - Parameter session: IMU session for which data download will be done. /// - Returns: Any publisher with `IMUSesionDownloadState` as Result, /// `IMUSesionDownloadState.downloading` indicates the progress of download. /// `IMUSesionDownloadState.downloaded` contains the URL path of the downloaded file . /// will publish an error if the session data could not be fetched. func downloadIMUSessionData( session: IMUSessionInfo ) -> AnyPublisher<IMUSessionDownloadState, Error> /// Will stop the current IMU session downloading. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMU session download was stopped. /// or will publish an error if downloading could not be stopped. func stopDownloading() -> AnyPublisher<Void, Error> /// Retrieves data for an IMUSession. /// /// - Parameter path: File path of the downloaded IMU session file. /// - Returns: Any publisher with a `bool` and `IMUSessionData` as Result. /// Bool indicates if file was fully parsed, publisher will publish an error if the session data could not be parsed. func parseIMUSession( path: URL ) -> AnyPublisher<(fullyParsed: Bool, session: IMUSessionData), Error> /// Retrieves data for an IMUSession. /// /// - Parameter session: IMU session to be parsed. /// - Returns: Any publisher with a `bool` and `IMUSessionData` as Result. /// Bool indicates if file was fully parsed, publisher will publish an error if the session data could not be parsed. func parseIMUSession( session: IMUSessionInfo ) -> AnyPublisher<(fullyParsed: Bool, session: IMUSessionData), Error> }
8fe990db0e91f7077a5f03e4430f6d45
42.62234
130
0.726131
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/Utility/AppAppearance.swift
gpl-2.0
1
import UIKit /// Encapsulates UIUserInterfaceStyle getting and setting for the app's /// main window. Allows users to override the interface style for the app. /// struct AppAppearance { /// The default interface style if not overridden static let `default`: UIUserInterfaceStyle = .unspecified private static var currentWindow: UIWindow? { return WordPressAppDelegate.shared?.window } /// The current user interface style used by the app static var current: UIUserInterfaceStyle { return currentWindow?.overrideUserInterfaceStyle ?? .unspecified } /// Overrides the app's current appeareance with the specified style. /// If no style is provided, the app's appearance will be overridden /// by any preference that may be currently saved in user defaults. /// static func overrideAppearance(with style: UIUserInterfaceStyle? = nil) { guard let window = currentWindow else { return } if let style = style { trackEvent(with: style) savedStyle = style } window.overrideUserInterfaceStyle = style ?? savedStyle } // MARK: - Tracks private static func trackEvent(with style: UIUserInterfaceStyle) { WPAnalytics.track(.appSettingsAppearanceChanged, properties: [Keys.styleTracksProperty: style.appearanceDescription]) } // MARK: - Persistence /// Saves or gets the current interface style preference. /// If no style has been saved, returns the default. /// private static var savedStyle: UIUserInterfaceStyle { get { guard let rawValue = UserPersistentStoreFactory.instance().object(forKey: Keys.appAppearanceDefaultsKey) as? Int, let style = UIUserInterfaceStyle(rawValue: rawValue) else { return AppAppearance.default } return style } set { UserPersistentStoreFactory.instance().set(newValue.rawValue, forKey: Keys.appAppearanceDefaultsKey) } } enum Keys { static let styleTracksProperty = "style" static let appAppearanceDefaultsKey = "app-appearance-override" } } extension UIUserInterfaceStyle { var appearanceDescription: String { switch self { case .light: return NSLocalizedString("Light", comment: "Title for the app appearance setting for light mode") case .dark: return NSLocalizedString("Dark", comment: "Title for the app appearance setting for dark mode") case .unspecified: return NSLocalizedString("System default", comment: "Title for the app appearance setting (light / dark mode) that uses the system default value") @unknown default: return "" } } static var allStyles: [UIUserInterfaceStyle] { return [.light, .dark, .unspecified] } }
18ac99dd115a1090d57d57e6ec668a5d
33.678571
158
0.661517
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/Model/DotLottie/Zip/FileManager+ZIP.swift
apache-2.0
2
// // FileManager+ZIP.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension FileManager { /// The default permissions for newly added entries. static let defaultFilePermissions = UInt16(0o644) class func attributes(from entry: ZipEntry) -> [FileAttributeKey: Any] { let centralDirectoryStructure = entry.centralDirectoryStructure let fileTime = centralDirectoryStructure.lastModFileTime let fileDate = centralDirectoryStructure.lastModFileDate let defaultPermissions = defaultFilePermissions var attributes = [.posixPermissions: defaultPermissions] as [FileAttributeKey: Any] // Certain keys are not yet supported in swift-corelibs #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) attributes[.modificationDate] = Date(dateTime: (fileDate, fileTime)) #endif let externalFileAttributes = centralDirectoryStructure.externalFileAttributes let permissions = permissions(for: externalFileAttributes) attributes[.posixPermissions] = NSNumber(value: permissions) return attributes } class func permissions(for externalFileAttributes: UInt32) -> UInt16 { let permissions = mode_t(externalFileAttributes >> 16) & ~S_IFMT let defaultPermissions = defaultFilePermissions return permissions == 0 ? defaultPermissions : UInt16(permissions) } /// Unzips the contents at the specified source URL to the destination URL. /// /// - Parameters: /// - sourceURL: The file URL pointing to an existing ZIP file. /// - destinationURL: The file URL that identifies the destination directory of the unzip operation. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. func unzipItem(at sourceURL: URL, to destinationURL: URL) throws { guard (try? sourceURL.checkResourceIsReachable()) == true else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path]) } guard let archive = ZipArchive(url: sourceURL) else { throw ZipArchive.ArchiveError.unreadableArchive } for entry in archive { let path = entry.path let entryURL = destinationURL.appendingPathComponent(path) guard entryURL.isContained(in: destinationURL) else { throw CocoaError( .fileReadInvalidFileName, userInfo: [NSFilePathErrorKey: entryURL.path]) } let crc32: UInt32 = try archive.extract(entry, to: entryURL) func verifyChecksumIfNecessary() throws { if crc32 != entry.checksum { throw ZipArchive.ArchiveError.invalidCRC32 } } try verifyChecksumIfNecessary() } } // MARK: - Helpers func createParentDirectoryStructure(for url: URL) throws { let parentDirectoryURL = url.deletingLastPathComponent() try createDirectory(at: parentDirectoryURL, withIntermediateDirectories: true, attributes: nil) } } extension Date { fileprivate init(dateTime: (UInt16, UInt16)) { var msdosDateTime = Int(dateTime.0) msdosDateTime <<= 16 msdosDateTime |= Int(dateTime.1) var unixTime = tm() unixTime.tm_sec = Int32((msdosDateTime & 31) * 2) unixTime.tm_min = Int32((msdosDateTime >> 5) & 63) unixTime.tm_hour = Int32((Int(dateTime.1) >> 11) & 31) unixTime.tm_mday = Int32((msdosDateTime >> 16) & 31) unixTime.tm_mon = Int32((msdosDateTime >> 21) & 15) unixTime.tm_mon -= 1 // UNIX time struct month entries are zero based. unixTime.tm_year = Int32(1980 + (msdosDateTime >> 25)) unixTime.tm_year -= 1900 // UNIX time structs count in "years since 1900". let time = timegm(&unixTime) self = Date(timeIntervalSince1970: TimeInterval(time)) } } #if swift(>=4.2) #else #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) #else // The swift-corelibs-foundation version of NSError.swift was missing a convenience method to create // error objects from error codes. (https://github.com/apple/swift-corelibs-foundation/pull/1420) // We have to provide an implementation for non-Darwin platforms using Swift versions < 4.2. extension CocoaError { fileprivate static func error(_ code: CocoaError.Code, userInfo: [AnyHashable: Any]? = nil, url: URL? = nil) -> Error { var info: [String: Any] = userInfo as? [String: Any] ?? [:] if let url = url { info[NSURLErrorKey] = url } return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info) } } #endif #endif extension URL { fileprivate func isContained(in parentDirectoryURL: URL) -> Bool { // Ensure this URL is contained in the passed in URL let parentDirectoryURL = URL(fileURLWithPath: parentDirectoryURL.path, isDirectory: true).standardized return standardized.absoluteString.hasPrefix(parentDirectoryURL.absoluteString) } }
5ae7fde363ace73c841455c7230f09d7
37.515385
121
0.7144
false
false
false
false
Senspark/ee-x
refs/heads/master
src/ios/ee/firebase_core/FirebaseInitializer.swift
mit
1
// // FirebaseCoreBridge.swift // Pods // // Created by eps on 6/26/20. // private let kTag = "\(FirebaseInitializer.self)" class FirebaseInitializer { private static let _sharedInstance = FirebaseInitializer() private let _logger = PluginManager.instance.logger private var _initialized = false public class var instance: FirebaseInitializer { return _sharedInstance } private init() { _logger.info("\(kTag): constructor") } public func initialize() -> Bool { if _initialized { return true } _initialized = true FirebaseApp.configure() return true } }
34ac672185811ae971b307a657a13213
19.8125
62
0.621622
false
false
false
false
Electrode-iOS/ELWebService
refs/heads/master
Source/Core/ServiceTaskResult.swift
mit
2
// // ServiceTaskResult.swift // ELWebService // // Created by Angelo Di Paolo on 11/5/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import Foundation /// Represents the result of a service task. public enum ServiceTaskResult { /// Defines an empty task result case empty /// Defines a task result as a value case value(Any) /// Defines a task resulting in an error case failure(Error) func taskValue() throws -> Any? { switch self { case .failure(let error): throw error case .empty: return nil case .value(let value): return value } } } // MARK: - Objective-C Interop extension ServiceTaskResult { /// Initialize a service task result value from an Obj-C result init(objCHandlerResult result: ObjCHandlerResult?) { if let error = result?.error { self = .failure(error) } else if let value = result?.value { self = .value(value) } else { self = .empty } } } /// Represents the result of a Obj-C response handler @objc public final class ObjCHandlerResult: NSObject { /// The resulting value fileprivate(set) var value: AnyObject? /// The resulting error fileprivate(set) var error: NSError? @objc public class func resultWithValue(_ value: AnyObject) -> ObjCHandlerResult { return ObjCHandlerResult(value: value) } @objc public class func resultWithError(_ error: NSError) -> ObjCHandlerResult { return ObjCHandlerResult(error: error) } /// Initialize a result with a value fileprivate init(value: AnyObject) { self.value = value } /// Initialize a result with an error fileprivate init(error: NSError) { self.error = error } }
c090fb30e7cf083a4180eaefaf90baba
25.42029
86
0.628634
false
false
false
false
dbahat/conventions-ios
refs/heads/sff
Conventions/Conventions/feedback/ConventionFeedbackViewController.swift
apache-2.0
1
// // ConventionFeedbackViewController.swift // Conventions // // Created by David Bahat on 7/22/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation import Firebase class ConventionFeedbackViewController: BaseViewController, FeedbackViewProtocol { @IBOutlet private weak var contentView: UIView! @IBOutlet private weak var filledEventsFeedbackLabel: UILabel! @IBOutlet private weak var seperatorView: UIView! @IBOutlet private weak var sendAllFeedbackDescriptionLabel: UILabel! @IBOutlet private weak var sendFeedbackContainer: UIView! @IBOutlet private weak var sendFeedbackContainerHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var feedbackView: FeedbackView! @IBOutlet private weak var feedbackViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var submittedEventsTabledView: UITableView! @IBOutlet private weak var submittedEventsTableViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var eventsToSubmitTableView: UITableView! @IBOutlet private weak var eventsToSubmitHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var submitAllFeedbacksButtonIndicator: UIActivityIndicatorView! @IBOutlet private weak var submitAllFeedbacksButton: UIButton! @IBOutlet private weak var fillEventFeedbackTitleLabel: UILabel! @IBOutlet private weak var fillEventFeedbackMessageLabel: UILabel! @IBOutlet private weak var filledFeedbacksTitleLabel: UILabel! @IBOutlet private weak var conventionFeedbackTitleLabel: UILabel! @IBOutlet private weak var generalFeedbackTitleLabel: UILabel! @IBOutlet private weak var toastView: UIView! private let submittedEventsDataSource = EventsTableDataSource() private let eventsToSubmitDataSource = EventsTableDataSource() private var userInputs: UserInput.Feedback { get { return Convention.instance.feedback.conventionInputs } } override func viewDidLoad() { super.viewDidLoad() feedbackView.delegate = self feedbackView.setHeaderHidden(true) feedbackView.textColor = Colors.textColor feedbackView.buttonColor = Colors.buttonColor feedbackView.linkColor = Colors.feedbackLinksColorConvention feedbackView.setFeedback( questions: Convention.instance.feedbackQuestions, answers: userInputs.answers, isSent: userInputs.isSent) // In this view the feedbackView should always be expended. // Note - should be done after setting the questions/answers, since they affect the view height. feedbackView.state = .expended // Need to set the view height constrant only after we set the // feedback and it's collapsed state, since its size changes based on the questions and state feedbackViewHeightConstraint.constant = feedbackView.getHeight() initializeEventsTableViews() navigationItem.title = "פידבק לכנס" submitAllFeedbacksButton.setTitleColor(Colors.buttonColor, for: UIControl.State()) fillEventFeedbackTitleLabel.textColor = Colors.textColor fillEventFeedbackMessageLabel.textColor = Colors.textColor filledFeedbacksTitleLabel.textColor = Colors.textColor conventionFeedbackTitleLabel.textColor = Colors.textColor generalFeedbackTitleLabel.textColor = Colors.textColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(ConventionFeedbackViewController.keyboardFrameWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Saving to the filesystem only when leaving the screen, since we don't want to save // on each small change inside free-text questions Convention.instance.feedback.save() NotificationCenter.default.removeObserver(self) } func feedbackProvided(_ feedback: FeedbackAnswer) { // If the answer already exists, override it if let existingAnswerIndex = userInputs.answers.firstIndex(where: {$0.questionText == feedback.questionText}) { userInputs.answers.remove(at: existingAnswerIndex) } userInputs.answers.append(feedback) Convention.instance.feedback.save() feedbackView.setSendButtonEnabled(userInputs.answers.count > 0) } func feedbackCleared(_ feedback: FeedbackQuestion) { guard let existingAnswerIndex = userInputs.answers.firstIndex(where: {$0.questionText == feedback.question}) else { // no existing answer means nothing to clear return } userInputs.answers.remove(at: existingAnswerIndex); feedbackView.setSendButtonEnabled(userInputs.answers.count > 0) } func sendFeedbackWasClicked() { // Force close the keyboard view.endEditing(true) Convention.instance.conventionFeedbackForm.submit(conventionName: Convention.displayName, answers: userInputs.answers, callback: { success in Convention.instance.feedback.conventionInputs.isSent = success self.feedbackView.setFeedbackAsSent(success) Analytics.logEvent("ConventionFeedback", parameters: [ "name": "SendAttempt" as NSObject, "full_text": success ? "success" : "failure" as NSObject ]) if !success { TTGSnackbar(message: "לא ניתן לשלוח את הפידבק. נסה שנית מאוחר יותר", duration: TTGSnackbarDuration.middle, superView: self.toastView).show() return } // Cancel the convention feedback reminder notifications (so the user won't see it again) NotificationsSchedualer.removeConventionFeedback() NotificationsSchedualer.removeConventionFeedbackLastChance() // filter un-answered questions and animate the possible layout height change self.feedbackView.removeAnsweredQuestions(self.userInputs.answers) self.feedbackViewHeightConstraint.constant = self.feedbackView.getHeight() UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) }) } func feedbackViewHeightDidChange(_ newHeight: CGFloat) { feedbackViewHeightConstraint.constant = newHeight } // Resize the screen to be at the height minus the keyboard, so that the keyboard won't hide the user's feedback @objc func keyboardFrameWillChange(_ notification: Notification) { let keyboardBeginFrame = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue let keyboardEndFrame = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardFrameEndUserInfoKey)! as AnyObject).cgRectValue let animationCurve = UIView.AnimationCurve(rawValue: ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardAnimationCurveUserInfoKey)! as AnyObject).intValue) let animationDuration: TimeInterval = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardAnimationDurationUserInfoKey)! as AnyObject).doubleValue UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(animationCurve!) var newFrame = self.view.frame let keyboardFrameEnd = self.view.convert(keyboardEndFrame!, to: nil) let keyboardFrameBegin = self.view.convert(keyboardBeginFrame!, to: nil) newFrame.origin.y -= (keyboardFrameBegin.origin.y - keyboardFrameEnd.origin.y) self.view.frame = newFrame; UIView.commitAnimations() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let eventViewController = segue.destination as? EventViewController; if let event = sender as? ConventionEvent { eventViewController?.event = event } } @IBAction fileprivate func submitAllEventsFeedbackWasTapped(_ sender: UIButton) { submitAllFeedbacksButton.isHidden = true submitAllFeedbacksButtonIndicator.isHidden = false var submittedEventsCount = 0; for event in eventsToSubmitDataSource.events { event.submitFeedback({success in if !success { TTGSnackbar(message: "לא ניתן לשלוח את הפידבק. נסה שנית מאוחר יותר", duration: TTGSnackbarDuration.middle, superView: self.toastView) .show(); return } submittedEventsCount += 1; if submittedEventsCount == self.eventsToSubmitDataSource.events.count { self.submitAllFeedbacksButton.isHidden = false self.submitAllFeedbacksButtonIndicator.isHidden = true // reset the tableViews to reflect the new changes in submitted events self.initializeEventsTableViews() self.submittedEventsTabledView.reloadData() self.eventsToSubmitTableView.reloadData() } }) } } fileprivate func initializeEventsTableViews() { submittedEventsDataSource.events = Convention.instance.events.getAll().filter({$0.didSubmitFeedback()}) submittedEventsTableViewHeightConstraint.constant = CGFloat(102 * submittedEventsDataSource.events.count) submittedEventsTabledView.dataSource = submittedEventsDataSource submittedEventsTabledView.delegate = submittedEventsDataSource submittedEventsDataSource.referencingViewController = self eventsToSubmitDataSource.events = Convention.instance.events.getAll().filter({ ($0.feedbackAnswers.count > 0 || $0.attending) && $0.canFillFeedback() && !$0.didSubmitFeedback() && !Convention.instance.isFeedbackSendingTimeOver()}) eventsToSubmitHeightConstraint.constant = CGFloat(102 * eventsToSubmitDataSource.events.count) eventsToSubmitTableView.dataSource = eventsToSubmitDataSource eventsToSubmitTableView.delegate = eventsToSubmitDataSource eventsToSubmitDataSource.referencingViewController = self if eventsToSubmitDataSource.events.count == 0 && submittedEventsDataSource.events.count == 0 { sendFeedbackContainerHeightConstraint.constant = 81 sendFeedbackContainer.isHidden = false submitAllFeedbacksButton.isHidden = true seperatorView.isHidden = true filledEventsFeedbackLabel.isHidden = true sendAllFeedbackDescriptionLabel.text = "בחר אירועים שהיית בהם דרך התוכניה ומלא עליהם פידבק" } else if eventsToSubmitDataSource.events.count == 0 { sendFeedbackContainerHeightConstraint.constant = 0 sendFeedbackContainer.isHidden = true } else { sendFeedbackContainerHeightConstraint.constant = eventsToSubmitHeightConstraint.constant + 116 sendFeedbackContainer.isHidden = false } } class EventsTableDataSource : NSObject, UITableViewDataSource, UITableViewDelegate { var events = Array<ConventionEvent>() weak var referencingViewController: UIViewController? func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let event = events[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: EventTableViewCell.self)) as! EventTableViewCell cell.setEvent(event) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let event = events[indexPath.row] referencingViewController?.performSegue(withIdentifier: "ConventionFeedbackToEventSegue", sender: event) } } }
2f8c8cf2a00d99d1c4aee8dfcbc504f7
46.773585
203
0.687204
false
false
false
false
digoreis/swift-proposal-analyzer
refs/heads/master
swift-proposal-analyzer.playground/Pages/SE-0004.xcplaygroundpage/Contents.swift
mit
1
/*: # Remove the `++` and `--` operators * Proposal: [SE-0004](0004-remove-pre-post-inc-decrement.md) * Author: [Chris Lattner](https://github.com/lattner) * Status: **Implemented (Swift 3)** * Commit: [apple/swift@8e12008](https://github.com/apple/swift/commit/8e12008d2b34a605f8766310f53d5668f3d50955) ## Introduction The increment/decrement operators in Swift were added very early in the development of Swift, as a carry-over from C. These were added without much consideration, and haven't been thought about much since then. This document provides a fresh look at them, and ultimately recommends we just remove them entirely, since they are confusing and not carrying their weight. As a quick refresher, there are four operators in this family: ```swift let a = ++x // pre-increment - returns input value after mutation let b = x++ // post-increment - returns copy of input value before mutation let c = --x // pre-decrement - returns input value after mutation let d = x-- // post-decrement - returns copy of input value before mutation ``` However, the result value of these operators are frequently ignored. ## Advantages of These Operators The primary advantage of these operators is their expressive capability. They are shorthand for (e.g.) `x += 1` on a numeric type, or `x.advance()` on an iterator-like value. When the return value is needed, the Swift `+=` operator cannot be used in-line, since (unlike C) it returns `Void`. The second advantage of Swift supporting this family of operators is continuity with C, and other common languages in the extended C family (C++, Objective-C, Java, C#, Javascript, etc). People coming to Swift from these other languages may reasonably expect these operators to exist. That said, there are also popular languages which have kept the majority of C operators but dropped these (e.g. Python). ## Disadvantages of These Operators 1. These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language. 2. Their expressive advantage is minimal - `x++` is not much shorter than `x += 1`. 3. Swift already deviates from C in that the `=`, `+=` and other assignment-like operations returns `Void` (for a number of reasons). These operators are inconsistent with that model. 4. Swift has powerful features that eliminate many of the common reasons you'd use `++i` in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the `for-in` loop, ranges, `enumerate`, `map`, etc. 5. Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand. 6. While Swift has well defined order of evaluation, any code that depended on it (like `foo(++a, a++)`) would be undesirable even if it was well-defined. 7. These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc. Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?" ## Proposed Approach We should just drop these operators entirely. In terms of roll-out, we should deprecate them in the Spring Swift 2.x release (with a nice Fixit hint to cover common cases), and remove them completely in Swift 3. ## Alternatives considered Simplest alternative: we could keep them. More interesting to consider, we could change these operators to return Void. This solves some of the problems above, but introduces a new question: once the result is gone, the difference between the prefix and postfix form also vanishes. Given that, we would have to pick between these unfortunate choices: 1) Keep both `x++` and `++x` in the language, even though they do the same thing. 2) Drop one of `x++` or `++x`. C++ programmers generally prefer the prefix forms, but everyone else generally prefers the postfix forms. Dropping either one would be a significant deviation from C. Despite considering these options carefully, they still don't justify the complexity that the operators add to Swift. ---------- [Previous](@previous) | [Next](@next) */
e8c6e9106e0403e648e65d73c5e27446
39.775701
111
0.758194
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
refs/heads/master
PrivacyLocation/Extensions/CLLocationManager+Rx.swift
mit
5
// // CLLocationManager+Rx.swift // RxExample // // Created by Carlos García on 8/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import CoreLocation import RxSwift import RxCocoa extension Reactive where Base: CLLocationManager { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var delegate: DelegateProxy<CLLocationManager, CLLocationManagerDelegate> { return RxCLLocationManagerDelegateProxy.proxy(for: base) } // MARK: Responding to Location Events /** Reactive wrapper for `delegate` message. */ public var didUpdateLocations: Observable<[CLLocation]> { return RxCLLocationManagerDelegateProxy.proxy(for: base).didUpdateLocationsSubject.asObservable() } /** Reactive wrapper for `delegate` message. */ public var didFailWithError: Observable<Error> { return RxCLLocationManagerDelegateProxy.proxy(for: base).didFailWithErrorSubject.asObservable() } #if os(iOS) || os(macOS) /** Reactive wrapper for `delegate` message. */ public var didFinishDeferredUpdatesWithError: Observable<Error?> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didFinishDeferredUpdatesWithError:))) .map { a in return try castOptionalOrThrow(Error.self, a[1]) } } #endif #if os(iOS) // MARK: Pausing Location Updates /** Reactive wrapper for `delegate` message. */ public var didPauseLocationUpdates: Observable<Void> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManagerDidPauseLocationUpdates(_:))) .map { _ in return () } } /** Reactive wrapper for `delegate` message. */ public var didResumeLocationUpdates: Observable<Void> { return delegate.methodInvoked( #selector(CLLocationManagerDelegate.locationManagerDidResumeLocationUpdates(_:))) .map { _ in return () } } // MARK: Responding to Heading Events /** Reactive wrapper for `delegate` message. */ public var didUpdateHeading: Observable<CLHeading> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateHeading:))) .map { a in return try castOrThrow(CLHeading.self, a[1]) } } // MARK: Responding to Region Events /** Reactive wrapper for `delegate` message. */ public var didEnterRegion: Observable<CLRegion> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didEnterRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } /** Reactive wrapper for `delegate` message. */ public var didExitRegion: Observable<CLRegion> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didExitRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) || os(macOS) /** Reactive wrapper for `delegate` message. */ @available(OSX 10.10, *) public var didDetermineStateForRegion: Observable<(state: CLRegionState, region: CLRegion)> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didDetermineState:for:))) .map { a in let stateNumber = try castOrThrow(NSNumber.self, a[1]) let state = CLRegionState(rawValue: stateNumber.intValue) ?? CLRegionState.unknown let region = try castOrThrow(CLRegion.self, a[2]) return (state: state, region: region) } } /** Reactive wrapper for `delegate` message. */ public var monitoringDidFailForRegionWithError: Observable<(region: CLRegion?, error: Error)> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:monitoringDidFailFor:withError:))) .map { a in let region = try castOptionalOrThrow(CLRegion.self, a[1]) let error = try castOrThrow(Error.self, a[2]) return (region: region, error: error) } } /** Reactive wrapper for `delegate` message. */ public var didStartMonitoringForRegion: Observable<CLRegion> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didStartMonitoringFor:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) // MARK: Responding to Ranging Events /** Reactive wrapper for `delegate` message. */ public var didRangeBeaconsInRegion: Observable<(beacons: [CLBeacon], region: CLBeaconRegion)> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didRangeBeacons:in:))) .map { a in let beacons = try castOrThrow([CLBeacon].self, a[1]) let region = try castOrThrow(CLBeaconRegion.self, a[2]) return (beacons: beacons, region: region) } } /** Reactive wrapper for `delegate` message. */ public var rangingBeaconsDidFailForRegionWithError: Observable<(region: CLBeaconRegion, error: Error)> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:rangingBeaconsDidFailFor:withError:))) .map { a in let region = try castOrThrow(CLBeaconRegion.self, a[1]) let error = try castOrThrow(Error.self, a[2]) return (region: region, error: error) } } // MARK: Responding to Visit Events /** Reactive wrapper for `delegate` message. */ @available(iOS 8.0, *) public var didVisit: Observable<CLVisit> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didVisit:))) .map { a in return try castOrThrow(CLVisit.self, a[1]) } } #endif // MARK: Responding to Authorization Changes /** Reactive wrapper for `delegate` message. */ public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> { return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:))) .map { a in let number = try castOrThrow(NSNumber.self, a[1]) return CLAuthorizationStatus(rawValue: Int32(number.intValue)) ?? .notDetermined } } } fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T { guard let returnValue = object as? T else { throw RxCocoaError.castingError(object: object, targetType: resultType) } return returnValue } fileprivate func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T? { if NSNull().isEqual(object) { return nil } guard let returnValue = object as? T else { throw RxCocoaError.castingError(object: object, targetType: resultType) } return returnValue }
44f78aeb4619f28804c10dbca169d6b3
31.342105
130
0.641307
false
false
false
false
nua-schroers/AccessibilityExamples
refs/heads/master
AccessibilityExamples/ViewWithSwitch.swift
mit
1
// // ViewWithSwitch.swift // AccessibilityExamples // // Created by Dr. Wolfram Schroers on 3/1/15. // Copyright (c) 2015 Wolfram Schroers. All rights reserved. // import UIKit /// This is a view which contains a description label and a switch. /// The entire view shall be accessible and behave like a switch that can be /// turned. /// /// Note that we do NOT want to access the individual sub-elements /// (i.e., the label and the switch) individually when VoiceOver is active. We only want to deal with /// the entire cell. class ViewWithSwitch: CustomView { /// MARK: Properties var textLabel = UILabel() var theSwitch = UISwitch() /// MARK: Configuration methods override func setup() { super.setup() // View setup (nothing to do with Accessibility). let powerSettingText = NSLocalizedString("Power setting", comment: "") self.textLabel.text = powerSettingText self.textLabel.frame = CGRect(x: 5, y: 5, width: 200, height: 50) self.theSwitch.frame = CGRect(x: 205, y: 5, width: 50, height: 50) self.addSubview(self.textLabel) self.addSubview(self.theSwitch) // Accessibility setup. self.isAccessibilityElement = true // The entire view shall be accessible. self.textLabel.isAccessibilityElement = false // But the label and the switch shall not be. self.theSwitch.isAccessibilityElement = false self.accessibilityLabel = powerSettingText // This is the standard label text of this view. self.accessibilityHint = "Double tap to activate or deactivate" // This is the hint. // This view shall behave as a button with VoiceOver. self.accessibilityTraits = UIAccessibilityTraits(rawValue: super.accessibilityTraits.rawValue | UIAccessibilityTraits.button.rawValue) self.updateAccessibility() } override func updateAccessibility() { super.updateAccessibility() // The value is the current setting and we use a custom text here. self.accessibilityValue = self.theSwitch.isOn ? "active" : "inactive" } /// MARK: UIAccessibilityAction /// This method is automagically called when the user double-taps /// while the view is highlighted. /// /// Note that this method is NOT used at all if VoiceOver is /// turned off! override func accessibilityActivate() -> Bool { // Toggle the switch. let newValue = !self.theSwitch.isOn self.theSwitch.setOn(newValue, animated: true) // Update the accessibility value. self.updateAccessibility() // Inform the user of the new situation. UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: "") // Return whether the action was successful (in this case is it always is). return true } }
87adfb10e91d77718e98ee5f6d4a35d5
35.1125
142
0.677051
false
false
false
false
s1Moinuddin/TextFieldWrapper
refs/heads/master
Example/Pods/TextFieldWrapper/TextFieldWrapper/Classes/Protocols/Zoomable.swift
mit
2
// // Zoomable.swift // TextFieldWrapper // // Created by Shuvo on 7/29/17. // Copyright © 2017 Shuvo. All rights reserved. // import UIKit protocol Zoomable {} extension Zoomable where Self:UIView { private func addPerspectiveTransformToParentSubviews() { let scale: CGFloat = 0.8 var transform3D = CATransform3DIdentity transform3D.m34 = -1/500 transform3D = CATransform3DScale(transform3D, scale, scale, 1) //let asdf = self.window?.rootViewController if let topController = window?.visibleViewController() { if let parentView = topController.view { parentView.subviews.forEach({ (mySubview) in if (mySubview != self && !(mySubview is UIVisualEffectView) && !(mySubview is UITableView)) { mySubview.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 0.5)) mySubview.layer.transform = transform3D } }) } } } private func removePerspectiveTransformFromParentSubviews() { if let topController = window?.visibleViewController() { if let parentView = topController.view { parentView.subviews.forEach({ (mySubview) in if mySubview != self { mySubview.layer.transform = CATransform3DIdentity } }) } } } func zoomIn(duration:TimeInterval, scale: CGFloat) { UIView.animate(withDuration: duration) { [weak self] in self?.backgroundColor = UIColor.white self?.layer.borderColor = UIColor.gray.cgColor self?.layer.borderWidth = 2.0 self?.layer.cornerRadius = 4.0 self?.layer.isOpaque = true self?.transform = CGAffineTransform(scaleX: scale, y: scale) self?.addPerspectiveTransformToParentSubviews() } } func zoomOut(duration:TimeInterval) { UIView.animate(withDuration: duration) { [weak self] in self?.layer.borderColor = UIColor.clear.cgColor self?.layer.borderWidth = 0 self?.layer.cornerRadius = 0 self?.layer.isOpaque = false self?.transform = .identity self?.removePerspectiveTransformFromParentSubviews() } } }
e3138dd8de9255908de3b70f20f8ddac
33.4
113
0.578904
false
false
false
false
rnine/AMCoreAudio
refs/heads/develop
Source/Internal/AudioHardware.swift
mit
1
// // AudioHardware.swift // SimplyCoreAudio // // Created by Ruben on 7/9/15. // Copyright © 2015 9Labs. All rights reserved. // import CoreAudio.AudioHardwareBase import Foundation import os.log /// This class allows subscribing to hardware-related audio notifications. /// /// For a comprehensive list of supported notifications, see `AudioHardwareEvent`. final class AudioHardware { // MARK: - Fileprivate Properties fileprivate var allKnownDevices = [AudioDevice]() fileprivate var isRegisteredForNotifications = false // MARK: - Internal Functions /// Enables device monitoring so events like the ones below are generated: /// /// - added or removed device /// - new default input device /// - new default output device /// - new default system output device /// /// - SeeAlso: `disableDeviceMonitoring()` func enableDeviceMonitoring() { registerForNotifications() for device in AudioDevice.allDevices() { add(device: device) } } /// Disables device monitoring. /// /// - SeeAlso: `enableDeviceMonitoring()` func disableDeviceMonitoring() { for device in allKnownDevices { remove(device: device) } unregisterForNotifications() } } // MARK: - Fileprivate Functions fileprivate extension AudioHardware { func add(device: AudioDevice) { allKnownDevices.append(device) } func remove(device: AudioDevice) { allKnownDevices.removeAll { $0 == device } } // MARK: - Notification Book-keeping func registerForNotifications() { if isRegisteredForNotifications { unregisterForNotifications() } var address = AudioObjectPropertyAddress( mSelector: kAudioObjectPropertySelectorWildcard, mScope: kAudioObjectPropertyScopeWildcard, mElement: kAudioObjectPropertyElementWildcard ) let systemObjectID = AudioObjectID(kAudioObjectSystemObject) let selfPtr = Unmanaged.passUnretained(self).toOpaque() if noErr != AudioObjectAddPropertyListener(systemObjectID, &address, propertyListener, selfPtr) { os_log("Unable to add property listener for systemObjectID: %@.", systemObjectID) } else { isRegisteredForNotifications = true } } func unregisterForNotifications() { guard isRegisteredForNotifications else { return } var address = AudioObjectPropertyAddress( mSelector: kAudioObjectPropertySelectorWildcard, mScope: kAudioObjectPropertyScopeWildcard, mElement: kAudioObjectPropertyElementWildcard ) let systemObjectID = AudioObjectID(kAudioObjectSystemObject) let selfPtr = Unmanaged.passUnretained(self).toOpaque() if noErr != AudioObjectRemovePropertyListener(systemObjectID, &address, propertyListener, selfPtr) { os_log("Unable to remove property listener for systemObjectID: %@.", systemObjectID) } else { isRegisteredForNotifications = false } } } // MARK: - C Convention Functions private func propertyListener(objectID: UInt32, numInAddresses: UInt32, inAddresses : UnsafePointer<AudioObjectPropertyAddress>, clientData: Optional<UnsafeMutableRawPointer>) -> Int32 { let _self = Unmanaged<AudioHardware>.fromOpaque(clientData!).takeUnretainedValue() let address = inAddresses.pointee let notificationCenter = NotificationCenter.default switch address.mSelector { case kAudioObjectPropertyOwnedObjects: // Get the latest device list let latestDeviceList = AudioDevice.allDevices() let addedDevices = latestDeviceList.filter { (audioDevice) -> Bool in !(_self.allKnownDevices.contains { $0 == audioDevice }) } let removedDevices = _self.allKnownDevices.filter { (audioDevice) -> Bool in !(latestDeviceList.contains { $0 == audioDevice }) } // Add new devices for device in addedDevices { _self.add(device: device) } // Remove old devices for device in removedDevices { _self.remove(device: device) } let userInfo: [AnyHashable: Any] = [ "added": addedDevices, "removed": removedDevices ] notificationCenter.post(name: Notifications.deviceListChanged.name, object: _self, userInfo: userInfo) case kAudioHardwarePropertyDefaultInputDevice: notificationCenter.post(name: Notifications.defaultInputDeviceChanged.name, object: _self) case kAudioHardwarePropertyDefaultOutputDevice: notificationCenter.post(name: Notifications.defaultOutputDeviceChanged.name, object: _self) case kAudioHardwarePropertyDefaultSystemOutputDevice: notificationCenter.post(name: Notifications.defaultSystemOutputDeviceChanged.name, object: _self) default: break } return noErr }
b6358ce653d5ef9dacb46840dc06bca3
31.528662
110
0.665949
false
false
false
false
erikmartens/NearbyWeather
refs/heads/develop
NearbyWeather/Scenes/Weather Station Meteorology Details Scene/Table Cells/Weather Station Meteorology Details Header/WeatherStationMeteorologyDetailsHeaderCellModel.swift
mit
1
// // WeatherStationCurrentInformationHeaderCellModel.swift // NearbyWeather // // Created by Erik Maximilian Martens on 13.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit struct WeatherStationMeteorologyDetailsHeaderCellModel { let weatherConditionSymbolImage: UIImage? let weatherConditionTitle: String? let weatherConditionSubtitle: String? let temperature: String? let daytimeStatus: String? let backgroundColor: UIColor init( weatherConditionSymbolImage: UIImage? = nil, weatherConditionTitle: String? = nil, weatherConditionSubtitle: String? = nil, temperature: String? = nil, daytimeStatus: String? = nil, backgroundColor: UIColor = Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundDay ) { self.weatherConditionSymbolImage = weatherConditionSymbolImage self.weatherConditionTitle = weatherConditionTitle self.weatherConditionSubtitle = weatherConditionSubtitle self.temperature = temperature self.daytimeStatus = daytimeStatus self.backgroundColor = backgroundColor } init( weatherInformationDTO: WeatherInformationDTO, temperatureUnitOption: TemperatureUnitOption, dimensionalUnitsOption: DimensionalUnitOption, isBookmark: Bool ) { let isDayTime = MeteorologyInformationConversionWorker.isDayTime(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) let isDayTimeString = MeteorologyInformationConversionWorker.isDayTimeString(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) let dayCycleStrings = MeteorologyInformationConversionWorker.dayCycleTimeStrings(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) self.init( weatherConditionSymbolImage: MeteorologyInformationConversionWorker.weatherConditionSymbol( fromWeatherCode: weatherInformationDTO.weatherCondition.first?.identifier, isDayTime: isDayTime ), weatherConditionTitle: weatherInformationDTO.weatherCondition.first?.conditionName?.capitalized, weatherConditionSubtitle: weatherInformationDTO.weatherCondition.first?.conditionDescription?.capitalized, temperature: MeteorologyInformationConversionWorker.temperatureDescriptor( forTemperatureUnit: temperatureUnitOption, fromRawTemperature: weatherInformationDTO.atmosphericInformation.temperatureKelvin ), daytimeStatus: String .begin(with: isDayTimeString) .append(contentsOf: dayCycleStrings?.currentTimeString, delimiter: .space) .ifEmpty(justReturn: nil), backgroundColor: (isDayTime ?? true) ? Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundDay : Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundNight ) } }
275b9b11d8569811b4a0a4361d7bd40d
44.28125
192
0.796411
false
false
false
false
JGiola/swift
refs/heads/main
test/TypeCoercion/protocols.swift
apache-2.0
9
// RUN: %target-typecheck-verify-swift protocol MyPrintable { func print() } protocol Titled { var title : String { get set } } struct IsPrintable1 : FormattedPrintable, Titled, Document { var title = "" func print() {} func print(_: TestFormat) {} } // Printability is below struct IsPrintable2 { } struct IsNotPrintable1 { } struct IsNotPrintable2 { func print(_: Int) -> Int {} } struct Book : Titled { var title : String } struct Lackey : Titled { var title : String { get {} set {} } } struct Number { var title : Int } func testPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, inp1: IsNotPrintable1, inp2: IsNotPrintable2, op: OtherPrintable) { var p : MyPrintable = ip1 // okay let _: MyPrintable & Titled = Book(title: "") // expected-error@-1 {{value of type 'Book' does not conform to specified type 'MyPrintable'}} p = ip1 // okay p = ip2 // okay p = inp1 // expected-error{{cannot assign value of type 'IsNotPrintable1' to type 'any MyPrintable'}} let _: MyPrintable = inp1 // expected-error@-1 {{value of type 'IsNotPrintable1' does not conform to specified type 'MyPrintable'}} p = inp2 // expected-error{{cannot assign value of type 'IsNotPrintable2' to type 'any MyPrintable'}} p = op // expected-error{{value of type 'any OtherPrintable' does not conform to 'MyPrintable' in assignment}} _ = p } func testTitledCoercion(_ ip1: IsPrintable1, book: Book, lackey: Lackey, number: Number, ip2: IsPrintable2) { var t : Titled = ip1 // okay t = ip1 t = book t = lackey t = number // expected-error{{cannot assign value of type 'Number' to type 'any Titled'}} t = ip2 // expected-error{{cannot assign value of type 'IsPrintable2' to type 'any Titled'}} _ = t } extension IsPrintable2 : MyPrintable { func print() {} } protocol OtherPrintable { func print() } struct TestFormat {} protocol FormattedPrintable : MyPrintable { func print(_: TestFormat) } struct NotFormattedPrintable1 { func print(_: TestFormat) { } } func testFormattedPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, fp: inout FormattedPrintable, p: inout MyPrintable, op: inout OtherPrintable, nfp1: NotFormattedPrintable1) { fp = ip1 fp = ip2 // expected-error{{cannot assign value of type 'IsPrintable2' to type 'any FormattedPrintable'}} fp = nfp1 // expected-error{{cannot assign value of type 'NotFormattedPrintable1' to type 'any FormattedPrintable'}} p = fp op = fp // expected-error{{value of type 'any FormattedPrintable' does not conform to 'OtherPrintable' in assignment}} fp = op // expected-error{{value of type 'any OtherPrintable' does not conform to 'FormattedPrintable' in assignment}} } protocol Document : Titled, MyPrintable { } func testMethodsAndVars(_ fp: FormattedPrintable, f: TestFormat, doc: inout Document) { fp.print(f) fp.print() doc.title = "Gone with the Wind" doc.print() } func testDocumentCoercion(_ doc: inout Document, ip1: IsPrintable1, l: Lackey) { doc = ip1 doc = l // expected-error{{cannot assign value of type 'Lackey' to type 'any Document'}} } // Check coercion of references. func refCoercion(_ p: inout MyPrintable) { } var p : MyPrintable = IsPrintable1() var fp : FormattedPrintable = IsPrintable1() // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{10-28=MyPrintable}} var ip1 : IsPrintable1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{11-23=MyPrintable}} refCoercion(&p) refCoercion(&fp) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} do { var fp_2 = fp // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{11-11=: MyPrintable}} var ip1_2 = ip1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{12-12=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { var fp_2 : FormattedPrintable = fp, ip1_2 = ip1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{14-32=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{44-44=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { var fp_2, fp_3 : FormattedPrintable // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{20-38=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{20-38=MyPrintable}} fp_2 = fp fp_3 = fp refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&fp_3) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} } do { func wrapRefCoercion1(fp_2: inout FormattedPrintable, ip1_2: inout IsPrintable1) { // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{31-55=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{32-50=MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } } do { // Make sure we don't add the fix-it for tuples: var (fp_2, ip1_2) = (fp, ip1) refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { // Make sure we don't add the fix-it for vars in different scopes: enum ParentScope { static var fp_2 = fp } refCoercion(&ParentScope.fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} } protocol IntSubscriptable { subscript(i: Int) -> Int { get } } struct IsIntSubscriptable : IntSubscriptable { subscript(i: Int) -> Int { get {} set {} } } struct IsDoubleSubscriptable { subscript(d: Double) -> Int { get {} set {} } } struct IsIntToStringSubscriptable { subscript(i: Int) -> String { get {} set {} } } func testIntSubscripting(i_s: inout IntSubscriptable, iis: IsIntSubscriptable, ids: IsDoubleSubscriptable, iiss: IsIntToStringSubscriptable) { var x = i_s[17] i_s[5] = 7 // expected-error{{cannot assign through subscript: subscript is get-only}} i_s = iis i_s = ids // expected-error{{cannot assign value of type 'IsDoubleSubscriptable' to type 'any IntSubscriptable'}} i_s = iiss // expected-error{{cannot assign value of type 'IsIntToStringSubscriptable' to type 'any IntSubscriptable'}} } protocol MyREPLPrintable { func myReplPrint() } extension Int : MyREPLPrintable { func myReplPrint() {} } extension String : MyREPLPrintable { func myReplPrint() {} } func doREPLPrint(_ p: MyREPLPrintable) { p.myReplPrint() } func testREPLPrintable() { let i : Int = 1 _ = i as MyREPLPrintable doREPLPrint(i) doREPLPrint(1) doREPLPrint("foo") } // Bool coercion if true as Bool {}
da154c439e3b596dbe1616df619abb67
36.971545
170
0.682368
false
false
false
false
HLoveMe/HExtension-swift
refs/heads/master
HExtension/HExtension/newsModel.swift
apache-2.0
1
// // newsModel.swift // HExtension // // Created by space on 16/1/8. // Copyright © 2016年 Space. All rights reserved. // class newsModel: KeyValueModel { var ID:Int = 0 var title:String? var mediatype:Int = 0 var type:String? var time:String? var indexdetail:String? var smallpic:String? var replycount:Int = 0 var pagecount:Int = 0 var jumppage:Int = 0 var lasttime:String? var updatetime:String? var coverimages:[String]? var newstype:Int = 0 var urls:[String]? var imgUrls:[String]? { get{ if self.urls != nil { }else{ let range = indexdetail!.range(of: "http://") let str = indexdetail!.substring(from: (range?.lowerBound)!) self.urls = str.components(separatedBy: ",") } return urls } } override func propertyNameInDictionary() -> [String : String]? { return ["ID":"id"] } }
fdc0651977311cab4575e87d414186a0
22.697674
76
0.541708
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/RectNode.swift
mit
1
// // RectNode.swift // lottie-swift // // Created by Brandon Withrow on 1/21/19. // import Foundation import CoreGraphics final class RectNodeProperties: NodePropertyMap, KeypathSearchable { var keypathName: String init(rectangle: Rectangle) { self.keypathName = rectangle.name self.direction = rectangle.direction self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.position.keyframes)) self.size = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.size.keyframes)) self.cornerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.cornerRadius.keyframes)) self.keypathProperties = [ "Position" : position, "Size" : size, "Roundness" : cornerRadius ] self.properties = Array(keypathProperties.values) } let keypathProperties: [String : AnyNodeProperty] let properties: [AnyNodeProperty] let direction: PathDirection let position: NodeProperty<Vector3D> let size: NodeProperty<Vector3D> let cornerRadius: NodeProperty<Vector1D> } final class RectangleNode: AnimatorNode, PathNode { let properties: RectNodeProperties let pathOutput: PathOutputNode init(parentNode: AnimatorNode?, rectangle: Rectangle) { self.properties = RectNodeProperties(rectangle: rectangle) self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) self.parentNode = parentNode } // MARK: Animator Node var propertyMap: NodePropertyMap & KeypathSearchable { return properties } let parentNode: AnimatorNode? var hasLocalUpdates: Bool = false var hasUpstreamUpdates: Bool = false var lastUpdateFrame: CGFloat? = nil var isEnabled: Bool = true { didSet{ self.pathOutput.isEnabled = self.isEnabled } } func rebuildOutputs(frame: CGFloat) { let size = properties.size.value.sizeValue * 0.5 let radius = min(min(properties.cornerRadius.value.cgFloatValue, size.width) , size.height) let position = properties.position.value.pointValue var bezierPath = BezierPath() let points: [CurveVertex] if radius <= 0 { /// No Corners points = [ /// Lead In CurveVertex(point: CGPoint(x: size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 1 CurveVertex(point: CGPoint(x: size.width, y: size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 2 CurveVertex(point: CGPoint(x: -size.width, y: size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 3 CurveVertex(point: CGPoint(x: -size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 4 CurveVertex(point: CGPoint(x: size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), ] } else { let controlPoint = radius * EllipseNode.ControlPointConstant points = [ /// Lead In CurveVertex( CGPoint(x: radius, y: 0), CGPoint(x: radius, y: 0), CGPoint(x: radius, y: 0)) .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), /// Corner 1 CurveVertex( CGPoint(x: radius, y: 0), // In tangent CGPoint(x: radius, y: 0), // Point CGPoint(x: radius, y: controlPoint)) .translated(CGPoint(x: -radius, y: -radius)) .translated(CGPoint(x: size.width, y: size.height)) .translated(position), CurveVertex( CGPoint(x: controlPoint, y: radius), // In tangent CGPoint(x: 0, y: radius), // Point CGPoint(x: 0, y: radius)) // Out Tangent .translated(CGPoint(x: -radius, y: -radius)) .translated(CGPoint(x: size.width, y: size.height)) .translated(position), /// Corner 2 CurveVertex( CGPoint(x: 0, y: radius), // In tangent CGPoint(x: 0, y: radius), // Point CGPoint(x: -controlPoint, y: radius))// Out tangent .translated(CGPoint(x: radius, y: -radius)) .translated(CGPoint(x: -size.width, y: size.height)) .translated(position), CurveVertex( CGPoint(x: -radius, y: controlPoint), // In tangent CGPoint(x: -radius, y: 0), // Point CGPoint(x: -radius, y: 0)) // Out tangent .translated(CGPoint(x: radius, y: -radius)) .translated(CGPoint(x: -size.width, y: size.height)) .translated(position), /// Corner 3 CurveVertex( CGPoint(x: -radius, y: 0), // In tangent CGPoint(x: -radius, y: 0), // Point CGPoint(x: -radius, y: -controlPoint)) // Out tangent .translated(CGPoint(x: radius, y: radius)) .translated(CGPoint(x: -size.width, y: -size.height)) .translated(position), CurveVertex( CGPoint(x: -controlPoint, y: -radius), // In tangent CGPoint(x: 0, y: -radius), // Point CGPoint(x: 0, y: -radius)) // Out tangent .translated(CGPoint(x: radius, y: radius)) .translated(CGPoint(x: -size.width, y: -size.height)) .translated(position), /// Corner 4 CurveVertex( CGPoint(x: 0, y: -radius), // In tangent CGPoint(x: 0, y: -radius), // Point CGPoint(x: controlPoint, y: -radius)) // Out tangent .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), CurveVertex( CGPoint(x: radius, y: -controlPoint), // In tangent CGPoint(x: radius, y: 0), // Point CGPoint(x: radius, y: 0)) // Out tangent .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), ] } let reversed = properties.direction == .counterClockwise let pathPoints = reversed ? points.reversed() : points for point in pathPoints { bezierPath.addVertex(reversed ? point.reversed() : point) } bezierPath.close() pathOutput.setPath(bezierPath, updateFrame: frame) } }
dd212ec578b8b1b05aefab2f02af467c
34.611702
113
0.601643
false
false
false
false
arnav-gudibande/SwiftTweet
refs/heads/master
Swifter-master/Swifter/SwifterOAuthClient.swift
apache-2.0
2
// // SwifterOAuthClient.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Accounts internal class SwifterOAuthClient: SwifterClientProtocol { struct OAuth { static let version = "1.0" static let signatureMethod = "HMAC-SHA1" } var consumerKey: String var consumerSecret: String var credential: SwifterCredential? var dataEncoding: NSStringEncoding init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.dataEncoding = NSUTF8StringEncoding } init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret) self.credential = SwifterCredential(accessToken: credentialAccessToken) self.dataEncoding = NSUTF8StringEncoding } func get(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { let url = NSURL(string: path, relativeToURL: baseURL)! let request = SwifterHTTPRequest(URL: url, method: .GET, parameters: parameters) request.headers = ["Authorization": self.authorizationHeaderForMethod(.GET, url: url, parameters: parameters, isMediaUpload: false)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.start() return request } func post(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { let url = NSURL(string: path, relativeToURL: baseURL)! var parameters = parameters var postData: NSData? var postDataKey: String? if let key: Any = parameters[Swifter.DataParameters.dataKey] { if let keyString = key as? String { postDataKey = keyString postData = parameters[postDataKey!] as? NSData parameters.removeValueForKey(Swifter.DataParameters.dataKey) parameters.removeValueForKey(postDataKey!) } } var postDataFileName: String? if let fileName: Any = parameters[Swifter.DataParameters.fileNameKey] { if let fileNameString = fileName as? String { postDataFileName = fileNameString parameters.removeValueForKey(fileNameString) } } let request = SwifterHTTPRequest(URL: url, method: .POST, parameters: parameters) request.headers = ["Authorization": self.authorizationHeaderForMethod(.POST, url: url, parameters: parameters, isMediaUpload: postData != nil)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.encodeParameters = postData == nil if postData != nil { let fileName = postDataFileName ?? "media.jpg" request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName) } request.start() return request } func authorizationHeaderForMethod(method: HTTPMethodType, url: NSURL, parameters: Dictionary<String, Any>, isMediaUpload: Bool) -> String { var authorizationParameters = Dictionary<String, Any>() authorizationParameters["oauth_version"] = OAuth.version authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod authorizationParameters["oauth_consumer_key"] = self.consumerKey authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = NSUUID().UUIDString authorizationParameters["oauth_token"] ??= self.credential?.accessToken?.key for (key, value) in parameters where key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } let combinedParameters = authorizationParameters +| parameters let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken) var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] authorizationParameterComponents.sortInPlace { $0 < $1 } var headerComponents = [String]() for component in authorizationParameterComponents { let subcomponent = component.componentsSeparatedByString("=") as [String] if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } return "OAuth " + headerComponents.joinWithSeparator(", ") } func oauthSignatureForMethod(method: HTTPMethodType, url: NSURL, parameters: Dictionary<String, Any>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String { let tokenSecret: NSString = token?.secret.urlEncodedStringWithEncoding() ?? "" let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding() let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] parameterComponents.sortInPlace { $0 < $1 } let parameterString = parameterComponents.joinWithSeparator("&") let encodedParameterString = parameterString.urlEncodedStringWithEncoding() let encodedURL = url.absoluteString.urlEncodedStringWithEncoding() let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" // let signature = signatureBaseString.SHA1DigestWithKey(signingKey) return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions([]) } }
3b5c329e860ef65d9f4cc485a89cc5ab
45.523529
316
0.716273
false
false
false
false
fredfoc/OpenWit
refs/heads/master
OpenWit/Classes/OpenWitMessageExtension.swift
mit
1
// // OpenWitMessageExtension.swift // OpenWit // // Created by fauquette fred on 24/11/16. // Copyright © 2016 Fred Fauquette. All rights reserved. // import Foundation import Moya import ObjectMapper // MARK: - an extension to handle message analyse extension OpenWit { /// get message recognition for WIT /// /// - Parameters: /// - message: a String with your message /// - messageId: optional id of message /// - threadId: optional thread of the message /// - context: optional context of the message /// - completion: completion closure public func message(_ message: String, messageId: String? = nil, threadId: String? = nil, context: Mappable? = nil, completion: @escaping (_ result: OpenWitResult<OpenWitMessageModel, OpenWitError>) -> ()) { guard let serviceManager = try? OpenWitServiceManager(WitToken: WITTokenAcces, serverToken: WITServerTokenAcces, isMocked: isMocked) else { completion(OpenWitResult(failure: OpenWitError.tokenIsUndefined)) return } guard message.isNotTooLong else { completion(OpenWitResult(failure: OpenWitError.messageTooLong)) return } _ = serviceManager.provider.requestObject(OpenWitService.message(apiVersion: apiVersion, message: message, messageId: messageId, threadId: threadId, context: context), completion: completion) } }
1382327e19bcba6644944a3d7071f712
39.652174
147
0.520856
false
false
false
false
dnseitz/YAPI
refs/heads/master
YAPI/YAPITests/YelpV2PhoneSearchResponseTests.swift
mit
1
// // YelpPhoneSearchResponseTests.swift // YAPI // // Created by Daniel Seitz on 9/12/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import XCTest @testable import YAPI class YelpPhoneSearchResponseTests: YAPIXCTestCase { func test_ValidResponse_ParsedFromEncodedJSON() { do { let dict = try self.dictFromBase64(ResponseInjections.yelpValidPhoneSearchResponse) let response = YelpV2SearchResponse(withJSON: dict) XCTAssertNil(response.region) XCTAssertNotNil(response.total) XCTAssert(response.total == 2316) XCTAssertNotNil(response.businesses) XCTAssert(response.businesses!.count == 1) XCTAssert(response.wasSuccessful == true) XCTAssert(response.error == nil) } catch { XCTFail() } } func test_ErrorResponse_ParsedFromEncodedJSON() { do { let dict = try self.dictFromBase64(ResponseInjections.yelpErrorResponse) let response = YelpV2SearchResponse(withJSON: dict) XCTAssertNil(response.region) XCTAssertNil(response.total) XCTAssertNil(response.businesses) XCTAssertNotNil(response.error) guard case .invalidParameter(field: "location") = response.error! else { return XCTFail("Wrong error type given: \(response.error!)") } XCTAssert(response.wasSuccessful == false) } catch { XCTFail() } } }
dab954bffbd7295141ffde81a0945038
27.24
89
0.684136
false
true
false
false
nsafai/tipcalculator
refs/heads/master
calculator/TipViewController.swift
mit
1
// // ViewController.swift // calculator // // Created by Nicolai Safai on 1/23/16. // Copyright © 2016 Lime. All rights reserved. // import UIKit class TipViewController: UIViewController { @IBOutlet weak var billAmountField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var whiteView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. billAmountField.becomeFirstResponder() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let defaults = NSUserDefaults.standardUserDefaults() tipControl.selectedSegmentIndex = defaults.integerForKey("default_tip_index") // visually change selected index if default has changed in defaults onEdit(self) // update the tip amount if default tip % has been changed } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEdit(sender: AnyObject) { var tipPercentages = [0.1, 0.15, 0.2] let chosenTip = tipPercentages[tipControl.selectedSegmentIndex] if let billAmount = Double(billAmountField.text!) { // print(billAmount) let tipAmount = billAmount*chosenTip let totalAmount = billAmount+tipAmount tipLabel.text = String(format:"$%.2f", tipAmount) totalLabel.text = String(format:"$%.2f", totalAmount) // topView.center.x = topView.center.x+100 // billAmountField.center.y = billAmountField.center.y+100 } else { tipLabel.text = "" totalLabel.text = "" } } @IBAction func onTap(sender: AnyObject) { // view.endEditing(true) } }
0d73115d6d612d53a30d5fbe3ba481a0
29.909091
154
0.636275
false
false
false
false