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
tlax/looper
refs/heads/master
looper/View/Camera/More/VCameraMoreCellActionsOption.swift
mit
1
import UIKit class VCameraMoreCellActionsOption:UICollectionViewCell { private weak var imageView:UIImageView! private let kAlphaSelected:CGFloat = 0.3 private let kAlphaNotSelected:CGFloat = 1 override init(frame:CGRect) { super.init(frame:frame) backgroundColor = UIColor.clear clipsToBounds = true let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.center self.imageView = imageView addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { alpha = kAlphaSelected } else { alpha = kAlphaNotSelected } } //MARK: public func config(model:MCameraMoreItemActionsOption) { imageView.image = model.image hover() } }
e8511888172fa555835a5e9c8b53632c
19.647887
67
0.561392
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Shared/DeferredUtils.swift
mpl-2.0
11
/* 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 Deferred // Haskell, baby. // Monadic bind/flatMap operator for Deferred. precedencegroup MonadicBindPrecedence { associativity: left higherThan: MonadicDoPrecedence lowerThan: BitwiseShiftPrecedence } precedencegroup MonadicDoPrecedence { associativity: left higherThan: MultiplicationPrecedence } infix operator >>== : MonadicBindPrecedence infix operator >>> : MonadicDoPrecedence @discardableResult public func >>== <T, U>(x: Deferred<Maybe<T>>, f: @escaping (T) -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return chainDeferred(x, f: f) } // A termination case. public func >>== <T>(x: Deferred<Maybe<T>>, f: @escaping (T) -> Void) { return x.upon { result in if let v = result.successValue { f(v) } } } // Monadic `do` for Deferred. @discardableResult public func >>> <T, U>(x: Deferred<Maybe<T>>, f: @escaping () -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return x.bind { res in if res.isSuccess { return f() } return deferMaybe(res.failureValue!) } } // Another termination case. public func >>> <T>(x: Deferred<Maybe<T>>, f: @escaping () -> Void) { return x.upon { res in if res.isSuccess { f() } } } /** * Returns a thunk that return a Deferred that resolves to the provided value. */ public func always<T>(_ t: T) -> () -> Deferred<Maybe<T>> { return { deferMaybe(t) } } public func deferMaybe<T>(_ s: T) -> Deferred<Maybe<T>> { return Deferred(value: Maybe(success: s)) } public func deferMaybe<T>(_ e: MaybeErrorType) -> Deferred<Maybe<T>> { return Deferred(value: Maybe(failure: e)) } public typealias Success = Deferred<Maybe<Void>> @discardableResult public func succeed() -> Success { return deferMaybe(()) } /** * Return a single Deferred that represents the sequential chaining * of f over the provided items. */ public func walk<T>(_ items: [T], f: @escaping (T) -> Success) -> Success { return items.reduce(succeed()) { success, item -> Success in success >>> { f(item) } } } /** * Like `all`, but thanks to its taking thunks as input, each result is * generated in strict sequence. Fails immediately if any result is failure. */ public func accumulate<T>(_ thunks: [() -> Deferred<Maybe<T>>]) -> Deferred<Maybe<[T]>> { if thunks.isEmpty { return deferMaybe([]) } let combined = Deferred<Maybe<[T]>>() var results: [T] = [] results.reserveCapacity(thunks.count) var onValue: ((T) -> Void)! var onResult: ((Maybe<T>) -> Void)! // onValue and onResult both hold references to each other niling them out before exiting breaks a reference cycle // We also cannot use unowned here because the thunks are not class types. onValue = { t in results.append(t) if results.count == thunks.count { onResult = nil combined.fill(Maybe(success: results)) } else { thunks[results.count]().upon(onResult) } } onResult = { r in if r.isFailure { onValue = nil combined.fill(Maybe(failure: r.failureValue!)) return } onValue(r.successValue!) } thunks[0]().upon(onResult) return combined } /** * Take a function and turn it into a side-effect that can appear * in a chain of async operations without producing its own value. */ public func effect<T, U>(_ f: @escaping (T) -> U) -> (T) -> Deferred<Maybe<T>> { return { t in _ = f(t) return deferMaybe(t) } } /** * Return a single Deferred that represents the sequential chaining of * f over the provided items, with the return value chained through. */ public func walk<T, U, S: Sequence>(_ items: S, start: Deferred<Maybe<U>>, f: @escaping (T, U) -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> where S.Iterator.Element == T { let fs = items.map { item in return { val in f(item, val) } } return fs.reduce(start, >>==) } /** * Like `all`, but doesn't accrue individual values. */ extension Array where Element: Success { public func allSucceed() -> Success { return all(self).bind { results -> Success in if let failure = results.find({ $0.isFailure }) { return deferMaybe(failure.failureValue!) } return succeed() } } } public func chainDeferred<T, U>(_ a: Deferred<Maybe<T>>, f: @escaping (T) -> Deferred<Maybe<U>>) -> Deferred<Maybe<U>> { return a.bind { res in if let v = res.successValue { return f(v) } return Deferred(value: Maybe<U>(failure: res.failureValue!)) } } public func chainResult<T, U>(_ a: Deferred<Maybe<T>>, f: @escaping (T) -> Maybe<U>) -> Deferred<Maybe<U>> { return a.map { res in if let v = res.successValue { return f(v) } return Maybe<U>(failure: res.failureValue!) } } public func chain<T, U>(_ a: Deferred<Maybe<T>>, f: @escaping (T) -> U) -> Deferred<Maybe<U>> { return chainResult(a, f: { Maybe<U>(success: f($0)) }) } /// Defer-ifies a block to an async dispatch queue. public func deferDispatchAsync<T>(_ queue: DispatchQueue, f: @escaping () -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() queue.async(execute: { f().upon { result in deferred.fill(result) } }) return deferred }
0168451068f4c6eb370100f9e03d1555
27.648241
171
0.608139
false
false
false
false
shahmishal/swift
refs/heads/master
test/type/opaque.swift
apache-2.0
1
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify %s protocol P { func paul() mutating func priscilla() } protocol Q { func quinn() } extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } class C {} class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {} } let property: some P = 1 let deflessLet: some P // expected-error{{has no initializer}} var deflessVar: some P // expected-error{{has no initializer}} struct GenericProperty<T: P> { var x: T var property: some P { return x } } let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}} var computedProperty: some P { get { return 1 } set { _ = newValue + 1 } // TODO expected-error{{}} expected-note{{}} } struct SubscriptTest { subscript(_ x: Int) -> some P { return x } } func bar() -> some P { return 1 } func bas() -> some P & Q { return 1 } func zim() -> some C { return D() } func zang() -> some C & P & Q { return D() } func zung() -> some AnyObject { return D() } func zoop() -> some Any { return D() } func zup() -> some Any & P { return D() } func zip() -> some AnyObject & P { return D() } func zorp() -> some Any & C & P { return D() } func zlop() -> some C & AnyObject & P { return D() } // Don't allow opaque types to propagate by inference into other global decls' // types struct Test { let inferredOpaque = bar() // expected-error{{inferred type}} let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}} let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}} } //let zingle = {() -> some P in 1 } // FIXME ex/pected-error{{'some' types are only implemented}} // Invalid positions typealias Foo = some P // expected-error{{'some' types are only implemented}} func blibble(blobble: some P) {} // expected-error{{'some' types are only implemented}} let blubble: () -> some P = { 1 } // expected-error{{'some' types are only implemented}} func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}} func blab() -> (P, some Q) { return (1, 2) } // expected-error{{'some' types are only implemented}} func blob() -> (some P) -> P { return { $0 } } // expected-error{{'some' types are only implemented}} func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only implemented}} func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only implemented}} expected-error{{cannot convert}} protocol OP: some P {} // expected-error{{'some' types are only implemented}} func foo() -> some P { let x = (some P).self // expected-error*{{}} return 1 } // Invalid constraints let zug: some Int = 1 // FIXME expected-error{{must specify only}} let zwang: some () = () // FIXME expected-error{{must specify only}} let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}} // Type-checking of expressions of opaque type func alice() -> some P { return 1 } func bob() -> some P { return 1 } func grace<T: P>(_ x: T) -> some P { return x } func typeIdentity() { do { var a = alice() a = alice() a = bob() // expected-error{{}} a = grace(1) // expected-error{{}} a = grace("two") // expected-error{{}} } do { var af = alice af = alice af = bob // expected-error{{}} af = grace // expected-error{{}} } do { var b = bob() b = alice() // expected-error{{}} b = bob() b = grace(1) // expected-error{{}} b = grace("two") // expected-error{{}} } do { var gi = grace(1) gi = alice() // expected-error{{}} gi = bob() // expected-error{{}} gi = grace(2) gi = grace("three") // expected-error{{}} } do { var gs = grace("one") gs = alice() // expected-error{{}} gs = bob() // expected-error{{}} gs = grace(2) // expected-error{{}} gs = grace("three") } // The opaque type should conform to its constraining protocols do { let gs = grace("one") var ggs = grace(gs) ggs = grace(gs) } // The opaque type should expose the members implied by its protocol // constraints do { var a = alice() a.paul() a.priscilla() } } func recursion(x: Int) -> some P { if x == 0 { return 0 } return recursion(x: x - 1) } // FIXME: We need to emit a better diagnostic than the failure to convert Never to opaque. func noReturnStmts() -> some P { fatalError() } // expected-error{{cannot convert return expression of type 'Never' to return type 'some P'}} expected-error{{no return statements}} func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}} if true { return 0 // expected-note{{underlying type 'Int'}} } else { return "" // expected-note{{underlying type 'String'}} } } struct MismatchedReturnTypesSubscript { subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } } func jan() -> some P { return [marcia(), marcia(), marcia()] } func marcia() -> some P { return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}} } protocol R { associatedtype S: P, Q // expected-note*{{}} func r_out() -> S func r_in(_: S) } extension Int: R { func r_out() -> String { return "" } func r_in(_: String) {} } func candace() -> some R { return 0 } func doug() -> some R { return 0 } func gary<T: R>(_ x: T) -> some R { return x } func sameType<T>(_: T, _: T) {} func associatedTypeIdentity() { let c = candace() let d = doug() var cr = c.r_out() cr = candace().r_out() cr = doug().r_out() // expected-error{{}} var dr = d.r_out() dr = candace().r_out() // expected-error{{}} dr = doug().r_out() c.r_in(cr) c.r_in(c.r_out()) c.r_in(dr) // expected-error{{}} c.r_in(d.r_out()) // expected-error{{}} d.r_in(cr) // expected-error{{}} d.r_in(c.r_out()) // expected-error{{}} d.r_in(dr) d.r_in(d.r_out()) cr.paul() cr.priscilla() cr.quinn() dr.paul() dr.priscilla() dr.quinn() sameType(cr, c.r_out()) sameType(dr, d.r_out()) sameType(cr, dr) // expected-error{{}} sameType(gary(candace()).r_out(), gary(candace()).r_out()) sameType(gary(doug()).r_out(), gary(doug()).r_out()) sameType(gary(doug()).r_out(), gary(candace()).r_out()) // expected-error{{}} } func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } func redeclaration() -> Any { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} struct RedeclarationTest { func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some P { return 0 } // expected-note 2{{previously declared}} subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some Q { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> P { return 0 } } func diagnose_requirement_failures() { struct S { var foo: some P { return S() } // expected-note {{declared here}} // expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}} subscript(_: Int) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}} } func bar() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}} } static func baz(x: String) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}} } } func fn() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}} } } func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}} return 42 as Double // expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}} } func recursive_func_is_invalid_opaque() { func rec(x: Int) -> some P { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} if x == 0 { return rec(x: 0) } return rec(x: x - 1) } } func closure() -> some P { _ = { return "test" } return 42 } protocol HasAssocType { associatedtype Assoc func assoc() -> Assoc } struct GenericWithOpaqueAssoc<T>: HasAssocType { func assoc() -> some Any { return 0 } } struct OtherGeneric<X, Y, Z> { var x: GenericWithOpaqueAssoc<X>.Assoc var y: GenericWithOpaqueAssoc<Y>.Assoc var z: GenericWithOpaqueAssoc<Z>.Assoc } protocol P_51641323 { associatedtype T var foo: Self.T { get } } func rdar_51641323() { struct Foo: P_51641323 { var foo: some P_51641323 { {} } // expected-error@-1 {{return type of property 'foo' requires that '() -> ()' conform to 'P_51641323'}} // expected-note@-2 {{opaque return type declared here}} } } // Protocol requirements cannot have opaque return types protocol OpaqueProtocolRequirement { // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{20-26=<#AssocType#>}} func method() -> some P // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{13-19=<#AssocType#>}} var prop: some P { get } // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>\n}}{{18-24=<#AssocType#>}} subscript() -> some P { get } } func testCoercionDiagnostics() { var opaque = foo() opaque = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaque = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} opaque = computedProperty // expected-error {{cannot assign value of type 'some P' (type of 'computedProperty') to type 'some P' (result of 'foo()')}} {{none}} opaque = SubscriptTest()[0] // expected-error {{cannot assign value of type 'some P' (result of 'SubscriptTest.subscript(_:)') to type 'some P' (result of 'foo()')}} {{none}} var opaqueOpt: Optional = opaque // FIXME: It would be nice to show the "from" info here as well. opaqueOpt = bar() // expected-error {{cannot assign value of type 'some P' to type '(some P)?'}} {{none}} opaqueOpt = () // expected-error {{cannot assign value of type '()' to type '(some P)?'}} {{none}} } var globalVar: some P = 17 let globalLet: some P = 38 struct Foo { static var staticVar: some P = 17 static let staticLet: some P = 38 var instanceVar: some P = 17 let instanceLet: some P = 38 } protocol P_52528543 { init() associatedtype A: Q_52528543 var a: A { get } } protocol Q_52528543 { associatedtype B // expected-note 2 {{associated type 'B'}} var b: B { get } } extension P_52528543 { func frob(a_b: A.B) -> some P_52528543 { return self } } func foo<T: P_52528543>(x: T) -> some P_52528543 { return x .frob(a_b: x.a.b) .frob(a_b: x.a.b) // expected-error {{cannot convert}} } struct GenericFoo<T: P_52528543, U: P_52528543> { let x: some P_52528543 = T() let y: some P_52528543 = U() mutating func bump() { var xab = f_52528543(x: x) xab = f_52528543(x: y) // expected-error{{cannot assign}} } } func f_52528543<T: P_52528543>(x: T) -> T.A.B { return x.a.b } func opaque_52528543<T: P_52528543>(x: T) -> some P_52528543 { return x } func invoke_52528543<T: P_52528543, U: P_52528543>(x: T, y: U) { let x2 = opaque_52528543(x: x) let y2 = opaque_52528543(x: y) var xab = f_52528543(x: x2) xab = f_52528543(x: y2) // expected-error{{cannot assign}} } protocol Proto {} struct I : Proto {} dynamic func foo<S>(_ s: S) -> some Proto { return I() } @_dynamicReplacement(for: foo) func foo_repl<S>(_ s: S) -> some Proto { return I() }
b5b9cc36f60a23c104fd13ba1b1542a9
28.316456
180
0.626151
false
false
false
false
fgengine/quickly
refs/heads/master
Quickly/Observer/QObserver.swift
mit
1
// // Quickly // public final class QObserver< T > { private var _items: [Item] private var _isForeached: Bool private var _addingItems: [Item] private var _removingItems: [Item] public init() { self._items = [] self._isForeached = false self._addingItems = [] self._removingItems = [] } public func add(_ observer: T, priority: UInt) { if self._isForeached == true { let item = Item(priority: priority, observer: observer) self._addingItems.append(item) } else { if let index = self._index(observer) { self._items[index].priority = priority } else { self._items.append(Item(priority: priority, observer: observer)) } self._postAdd() } } public func remove(_ observer: T) { guard let index = self._index(observer) else { return } if self._isForeached == true { self._removingItems.append(self._items[index]) } else { self._items.remove(at: index) } } public func notify(_ closure: (_ observer: T) -> Void) { if self._isForeached == false { self._isForeached = true self._items.forEach({ closure($0.observer) }) self._isForeached = false self._postNotify() } else { self._items.forEach({ closure($0.observer) }) } } public func notify(priorities: [UInt], closure: (_ observer: T) -> Void) { if self._isForeached == false { self._isForeached = true for priority in priorities { let items = self._items.filter({ return $0.priority == priority }) items.forEach({ closure($0.observer) }) } self._isForeached = false self._postNotify() } else { for priority in priorities { let items = self._items.filter({ return $0.priority == priority }) items.forEach({ closure($0.observer) }) } } } public func reverseNotify(_ closure: (_ observer: T) -> Void) { if self._isForeached == false { self._isForeached = true self._items.reversed().forEach({ closure($0.observer) }) self._isForeached = false self._postNotify() } else { self._items.reversed().forEach({ closure($0.observer) }) } } public func reverseNotify(priorities: [UInt], closure: (_ observer: T) -> Void) { if self._isForeached == false { self._isForeached = true for priority in priorities { let items = self._items.filter({ return $0.priority == priority }) items.reversed().forEach({ closure($0.observer) }) } self._isForeached = false self._postNotify() } else { for priority in priorities { let items = self._items.filter({ return $0.priority == priority }) items.reversed().forEach({ closure($0.observer) }) } } } private func _index(_ observer: T) -> Int? { let pointer = Unmanaged.passUnretained(observer as AnyObject).toOpaque() return self._items.firstIndex(where: { return $0.pointer == pointer }) } private func _index(_ item: Item) -> Int? { return self._items.firstIndex(where: { return $0.pointer == item.pointer }) } private func _postNotify() { if self._removingItems.count > 0 { for item in self._removingItems { if let index = self._index(item) { self._items.remove(at: index) } } self._removingItems.removeAll() } if self._addingItems.count > 0 { for item in self._addingItems { if let index = self._index(item) { self._items[index].priority = item.priority } else { self._items.append(item) } } self._addingItems.removeAll() self._postAdd() } } private func _postAdd() { self._items.sort(by: { return $0.priority < $1.priority }) } private final class Item { var priority: UInt var pointer: UnsafeMutableRawPointer var observer: T { get { return Unmanaged< AnyObject >.fromOpaque(self.pointer).takeUnretainedValue() as! T } } init(priority: UInt, observer: T) { self.priority = priority self.pointer = Unmanaged.passUnretained(observer as AnyObject).toOpaque() } init(priority: UInt, pointer: UnsafeMutableRawPointer) { self.priority = priority self.pointer = pointer } } }
eaf973adfb6622df3753c2c19f9c98f2
29.792899
102
0.494427
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Data/Procedure.swift
apache-2.0
1
// // Procedure.swift // LispKit // // Created by Matthias Zenger on 21/01/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Atomics /// /// Procedures encapsulate functions that can be applied to arguments. Procedures have an /// identity, a name, and a definition in the form of property `kind`. There are four kinds /// of procedure definitions: /// 1. Primitives: Built-in procedures /// 2. Closures: User-defined procedures, e.g. via `lambda`. Closure are either anonymous, /// they are named, or they are continuations /// 3. Parameters: Parameter objects, which can be mutated for the duration of a /// dynamic extent /// 4. Transformers: User-defined macro transformers defined via `syntax-rules` /// 5. Raw continuations: Continuations generated by `call-with-current-continuation` /// are modeled as closures of closure type `continuation`. Internally, they use /// raw continuations for encapsulating the state of a virtual machine. /// public final class Procedure: Reference, CustomStringConvertible { /// Count procedure objects public static let count = ManagedAtomic<UInt>(0) /// There are four kinds of procedures: /// 1. Primitives: Built-in procedures /// 2. Closures: User-defined procedures, e.g. via `lambda` /// 3. Parameters: Parameter objects, which can be mutated for the duration of a /// dynamic extent /// 4. Transformers: User-defined macro transformers defined via `syntax-rules` /// 5. Raw continuations: Continuations generated by `call-with-current-continuation` /// are modeled as closures of closure type `continuation`. Internally, they use /// raw continuations for encapsulating the state of a virtual machine. public enum Kind { case primitive(String, Implementation, FormCompiler?) case closure(ClosureType, Expr, Exprs, Code) case parameter(Tuple) case transformer(SyntaxRules) case rawContinuation(VirtualMachineState) } /// There are three types of closures: /// 1. Anonymous closures: closures that are not named /// 2. Named closures: Closures that are given a name /// 3. Continuations: These are unnamed closures generated by `call-with-current-continuation` public enum ClosureType { case anonymous case named(String) case continuation } /// There are three different types of primitive implementations: /// 1. Evaluators: They turn the arguments into code that the VM executes /// 2. Applicators: They map the arguments to a continuation procedure and an argument list /// 3. Native implementations: They map the arguments into a result value // TODO: Remove evaluators; they can be represented as applicators returning a newly // generated procedure without arguments. public enum Implementation { case eval((Arguments) throws -> Code) case apply((Arguments) throws -> (Procedure, Exprs)) case native0(() throws -> Expr) case native1((Expr) throws -> Expr) case native2((Expr, Expr) throws -> Expr) case native3((Expr, Expr, Expr) throws -> Expr) case native4((Expr, Expr, Expr, Expr) throws -> Expr) case native0O((Expr?) throws -> Expr) case native1O((Expr, Expr?) throws -> Expr) case native2O((Expr, Expr, Expr?) throws -> Expr) case native3O((Expr, Expr, Expr, Expr?) throws -> Expr) case native0OO((Expr?, Expr?) throws -> Expr) case native1OO((Expr, Expr?, Expr?) throws -> Expr) case native2OO((Expr, Expr, Expr?, Expr?) throws -> Expr) case native3OO((Expr, Expr, Expr, Expr?, Expr?) throws -> Expr) case native0R((Arguments) throws -> Expr) case native1R((Expr, Arguments) throws -> Expr) case native2R((Expr, Expr, Arguments) throws -> Expr) case native3R((Expr, Expr, Expr, Arguments) throws -> Expr) } /// Identifier public let id: UInt = Procedure.count.wrappingIncrementThenLoad(ordering: .relaxed) /// Procedure kind public let kind: Kind /// Is this procedure traced; i.e. should the virtual machine print debugging information /// for this procedure? public var traced: Bool = false /// A tag that defines the last GC cyle in which this object was marked (by following the /// root set references); for optimization purposes internal final var tag: UInt8 = 0 /// Internal initializer for copying primitive procedures private init(_ name: String, _ impl: Implementation, _ fcomp: FormCompiler?) { self.kind = .primitive(name, impl, fcomp) } /// Initializer for primitive evaluators public init(_ name: String, _ proc: @escaping (Arguments) throws -> Code, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .eval(proc), compiler) } /// Initializer for primitive evaluators public init(_ name: String, _ compiler: @escaping FormCompiler, in context: Context) { self.kind = .primitive(name, .eval( { [unowned context] (args: Arguments) throws -> Code in let expr = Expr.pair( .symbol(Symbol(context.symbols.intern(name), context.global)), .makeList(args)) return try Compiler.compile(expr: .pair(expr, .null), in: context.global, optimize: true) }), compiler) } /// Initializer for primitive applicators public init(_ name: String, _ proc: @escaping (Arguments) throws -> (Procedure, Exprs), _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .apply(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping () throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native0(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native1(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native2(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native3(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr, Expr) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native4(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native0O(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native1O(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native2O(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native3O(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr?, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native0OO(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr?, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native1OO(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr?, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native2OO(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr, Expr?, Expr?) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native3OO(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Arguments) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native0R(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Arguments) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native1R(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Arguments) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native2R(proc), compiler) } /// Initializer for primitive procedures public init(_ name: String, _ proc: @escaping (Expr, Expr, Expr, Arguments) throws -> Expr, _ compiler: FormCompiler? = nil) { self.kind = .primitive(name, .native3R(proc), compiler) } /// Initializer for closures public init(_ type: ClosureType, _ tag: Expr, _ captured: Exprs, _ code: Code) { self.kind = .closure(type, tag, captured, code) } /// Initializer for closures public init(_ type: ClosureType, _ captured: Exprs, _ code: Code) { self.kind = .closure(type, .undef, captured, code) } /// Initializer for closures public init(_ code: Code) { self.kind = .closure(.anonymous, .undef, [], code) } /// Initializer for named closures public init(_ name: String, _ code: Code) { self.kind = .closure(.named(name), .undef, [], code) } /// Initializer for parameters public init(_ setter: Expr, _ initial: Expr) { self.kind = .parameter(Tuple(setter, initial)) } /// Initializer for parameters public init(_ tuple: Tuple) { self.kind = .parameter(tuple) } /// Initializer for continuations public init(_ vmState: VirtualMachineState) { self.kind = .rawContinuation(vmState) } /// Initializer for transformers public init(_ rules: SyntaxRules) { self.kind = .transformer(rules) } public override init() { preconditionFailure() } /// Returns the name of this procedure. This method either returns the name of a primitive /// procedure or the identity as a hex string. public var name: String { switch self.kind { case .primitive(let str, _, _): return str case .closure(.named(let str), _, _, _): return Context.simplifiedDescriptions ? str : "\(str)@\(self.id)" default: return "<closure \(self.id)>" } } /// Returns the name of this procedure. This method either returns the name of a primitive /// procedure or the identity as a hex string or `nil` if there is no available name. public var embeddedName: String { switch self.kind { case .primitive(let str, _, _): return str case .closure(.named(let str), _, _, _): return Context.simplifiedDescriptions ? str : "\(str)@\(self.id)" default: return "\(self.id)" } } /// Returns the original name of this procedure if it exists and is known. public var originalName: String? { switch self.kind { case .primitive(let str, _, _): return str case .closure(.named(let str), _, _, _): return str default: return nil } } /// Return a renamed procedure (if renaming is possible) public func renamed(to name: String, force: Bool = false) -> Procedure? { switch self.kind { case .primitive(_, let impl, let fcomp): guard force else { return nil } let res = Procedure(name, impl, fcomp) res.traced = self.traced return res case .closure(let type, let tag, let captured, let code): if case .continuation = type { return nil } else if !force, case .named(_) = type { return nil } let res = Procedure(.named(name), tag, captured, code) res.traced = self.traced return res default: return nil } } /// Arities are either exact or they are referring to a lower bound. public enum Arity { case exact(Int) case atLeast(Int) } /// Returns the arity. public var arity: [Arity] { switch self.kind { case .primitive(_, let impl, _): switch impl { case .eval(_): return [.atLeast(0)] case .apply(_): return [.atLeast(0)] case .native0(_): return [.exact(0)] case .native1(_): return [.exact(1)] case .native2(_): return [.exact(2)] case .native3(_): return [.exact(3)] case .native4(_): return [.exact(4)] case .native0O(_): return [.exact(0), .exact(1)] case .native1O(_): return [.exact(1), .exact(2)] case .native2O(_): return [.exact(2), .exact(3)] case .native3O(_): return [.exact(3), .exact(4)] case .native0OO(_): return [.exact(0), .exact(1), .exact(2)] case .native1OO(_): return [.exact(1), .exact(2), .exact(3)] case .native2OO(_): return [.exact(2), .exact(3), .exact(4)] case .native3OO(_): return [.exact(3), .exact(4), .exact(5)] case .native0R(_): return [.atLeast(0)] case .native1R(_): return [.atLeast(1)] case .native2R(_): return [.atLeast(2)] case .native3R(_): return [.atLeast(3)] } case .closure(.continuation, _, _, _): return [.exact(1)] case .closure(_, _, _, let code): return code.arity case .parameter(_): return [.exact(0), .exact(1)] case .transformer(_): return [.exact(1)] case .rawContinuation(_): return [.exact(1)] } } /// Returns `true` if the given arity is accepted by the procedure. public func arityAccepted(_ n: Int) -> Bool { switch self.kind { case .primitive(_, let impl, _): switch impl { case .eval(_), .apply(_), .native0R(_): return true case .native0(_): return n == 0 case .native1(_): return n == 1 case .native2(_): return n == 2 case .native3(_): return n == 3 case .native4(_): return n == 4 case .native0O(_): return n <= 1 case .native1O(_): return n == 1 || n == 2 case .native2O(_): return n == 2 || n == 3 case .native3O(_): return n == 3 || n == 4 case .native0OO(_): return n <= 2 case .native1OO(_): return n >= 1 && n <= 3 case .native2OO(_): return n >= 2 && n <= 4 case .native3OO(_): return n >= 3 && n <= 5 case .native1R(_): return n >= 1 case .native2R(_): return n >= 2 case .native3R(_): return n >= 3 } case .closure(.continuation, _, _, _): return n == 1 case .closure(_, _, _, let code): return code.arityAccepted(n) case .parameter(_): return n <= 1 case .transformer(_): return n == 1 case .rawContinuation(_): return n == 1 } } /// A textual description public var description: String { return "«procedure \(self.name)»" } /// Returns a textual representation of the disassembled code public func disassembled(all: Bool = true) -> String? { var builder = StringBuilder() var procToDisassemble: [Procedure] = [self] var i = 0 while i < procToDisassemble.count { let proc = procToDisassemble[i] switch proc.kind { case .closure(_, _, let captured, let code): if !builder.isEmpty { builder.appendNewline() } builder.append("====== \(Expr.procedure(proc).description) ======") builder.appendNewline() builder.append(code.description) if captured.count > 0 { builder.append("CAPTURED:") for n in captured.indices { builder.appendNewline() builder.append(n, width: 5, alignRight: true) builder.append(": ") builder.append(captured[n].description) } builder.appendNewline() } if all { for expr in code.constants { if case .procedure(let proc) = expr { procToDisassemble.append(proc) } } } case .rawContinuation(let vmState): if !builder.isEmpty { builder.appendNewline() } builder.append("====== \(Expr.procedure(proc).description) ======") builder.appendNewline() builder.append(vmState.description) builder.appendNewline() builder.append(vmState.registers.code.description) if vmState.registers.captured.count > 0 { builder.append("CAPTURED:") for n in vmState.registers.captured.indices { builder.appendNewline() builder.append(n, width: 5, alignRight: true) builder.append(": ") builder.append(vmState.registers.captured[n].description) } builder.appendNewline() } if all { for expr in vmState.registers.code.constants { if case .procedure(let proc) = expr { procToDisassemble.append(proc) } } } default: break } i += 1 } let res = builder.description return res.count > 0 ? res : nil } } public typealias Arguments = ArraySlice<Expr> public extension Arguments { var values: Expr { switch self.count { case 0: return .void case 1: return self.first! default: var res = Expr.null var idx = self.endIndex while idx > self.startIndex { idx = self.index(before: idx) res = .pair(self[idx], res) } return .values(res) } } } public extension ArraySlice { func optional(_ fst: Element, _ snd: Element) -> (Element, Element)? { switch self.count { case 0: return (fst, snd) case 1: return (self[self.startIndex], snd) case 2: return (self[self.startIndex], self[self.startIndex + 1]) default: return nil } } func optional(_ fst: Element, _ snd: Element, _ trd: Element) -> (Element, Element, Element)? { switch self.count { case 0: return (fst, snd, trd) case 1: return (self[self.startIndex], snd, trd) case 2: return (self[self.startIndex], self[self.startIndex + 1], trd) case 3: return (self[self.startIndex], self[self.startIndex + 1], self[self.startIndex + 2]) default: return nil } } func optional(_ fst: Element, _ snd: Element, _ trd: Element, _ fth: Element) -> (Element, Element, Element, Element)? { switch self.count { case 0: return (fst, snd, trd, fth) case 1: return (self[self.startIndex], snd, trd, fth) case 2: return (self[self.startIndex], self[self.startIndex + 1], trd, fth) case 3: return (self[self.startIndex], self[self.startIndex + 1], self[self.startIndex + 2], fth) case 4: return (self[self.startIndex], self[self.startIndex + 1], self[self.startIndex + 2], self[self.startIndex + 3]) default: return nil } } func required2() -> (Element, Element)? { guard self.count == 2 else { return nil } return (self[self.startIndex], self[self.startIndex + 1]) } func required3() -> (Element, Element, Element)? { guard self.count == 3 else { return nil } return (self[self.startIndex], self[self.startIndex + 1], self[self.startIndex + 2]) } } /// /// A `FormCompiler` is a function that compiles an expression for a given compiler in a /// given environment and tail position returning a boolean which indicates whether the /// expression has resulted in a tail call. /// public typealias FormCompiler = (Compiler, Expr, Env, Bool) throws -> Bool
1f49fc21a8d9e951bf703510debb8549
32.841945
99
0.582001
false
false
false
false
recruit-lifestyle/Sidebox
refs/heads/master
Pod/Classes/View/SBTableView.swift
mit
1
// // SBTableView.swift // Pods // // Created by Nonchalant on 2015/07/30. // Copyright (c) 2015 Nonchalant. All rights reserved. // import UIKit public class SBTableView: UITableView, UITableViewDelegate { private let ___dataSource = SBDataSource() private var edit = false override init(frame: CGRect) { super.init(frame: frame) initializer() } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) initializer() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializer() } public func initializer() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "removeIcon:", name: "sbRemove", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "edit:", name: "sbEdit", object: nil) self.delegate = self self.dataSource = ___dataSource self.backgroundColor = .whiteColor() self.rowHeight = 60.0 self.separatorStyle = .None self.clipsToBounds = false let leftLine = UIView(frame: CGRectMake(0.0, -self.frame.size.height/2.0, 1.0, self.frame.size.height*2)) leftLine.backgroundColor = .grayColor() self.addSubview(leftLine) } final func focus(hover: Bool) { if (hover) { self.backgroundColor = .grayColor() self.alpha = 0.2 } else { self.backgroundColor = .whiteColor() self.alpha = 1.0 } } final func derive(derive: Bool) { if (derive) { self.center = CGPointMake(UIScreen.mainScreen().bounds.width - self.frame.size.width/2.0, self.center.y) } else { self.center = CGPointMake(UIScreen.mainScreen().bounds.width + self.frame.size.width/2.0, self.center.y) } } // MARK: - NSNotification final func removeIcon(notification: NSNotification?) { if let userInfo = notification!.userInfo, index = userInfo["id"] as? Int { if let cell = self.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) { cell.alpha = 0 } self.beginUpdates() self.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade) self.endUpdates() self.reloadData() } } // MARK: - UITableViewDelegate public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
9176faf2c80860514d9d0881c576ee89
32.085366
131
0.613712
false
false
false
false
KasunApplications/susi_iOS
refs/heads/master
Susi/Controllers/TrainingViewController/TrainingVCMethods.swift
apache-2.0
1
// // TrainingVCMethods.swift // Susi // // Created by Chashmeet Singh on 2017-08-04. // Copyright © 2017 FOSSAsia. All rights reserved. // import UIKit import Material extension TrainingViewController { func setupNavBar() { if let navbar = navigationController?.navigationBar { navbar.barTintColor = UIColor.hexStringToUIColor(hex: "#4184F3") } UIApplication.shared.statusBarView?.backgroundColor = UIColor.hexStringToUIColor(hex: "#4184F3") } func addCancelNavItem() { navigationItem.title = ControllerConstants.trainHotword navigationItem.titleLabel.textColor = .white let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelTapped(_:))) cancelButton.tintColor = .white navigationItem.rightBarButtonItems = [cancelButton] } func cancelTapped(_ sender: Any) { dismiss(animated: true, completion: nil) } func addTargets() { finishLaterButton.addTarget(self, action: #selector(cancelTapped(_:)), for: .touchUpInside) } }
120fd1331057278c75f0e7b5367a67d8
28.105263
125
0.681736
false
false
false
false
shergin/PeterParker
refs/heads/master
Sources/PeterParker/Routing/RouteType.swift
mit
1
// // RouteType.swift // PeterParker // // Created by Valentin Shergin on 5/16/16. // Copyright © 2016 The PeterParker Authors. All rights reserved. // import Foundation import PeterParkerPrivate.ifaddrs /// Mapping of messages operating on routing table /// /// See [route(4)](https://www.freebsd.org/cgi/man.cgi?query=route&sektion=4&apropos=0&manpath=FreeBSD+10.3-RELEASE+and+Ports) public enum RouteType: CUnsignedChar { case add = 1 case delete case change case get case losing case redirect case miss case lock case oldAdd case oldDel case resolve case newAddress case deleteAddress case interfaceInfo case newMembershipAddress case deleteMembershipAddress case getSilent case interfaceInfo2 case newMembershipAddress2 case get2 } extension RouteType { public init(_ _routeType: CUnsignedChar) { self = RouteType(rawValue: _routeType)! } }
f66f7d89133f25807922b8dc4a487eeb
21.093023
126
0.702105
false
false
false
false
JaSpa/swift
refs/heads/master
test/Constraints/dictionary_literal.swift
apache-2.0
9
// RUN: %target-typecheck-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class Dictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: Dictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} useDictStringInt([4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}} useDictStringInt([nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}} useDictStringInt([7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' cannot be used with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}} var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type 'Dictionary<AnyHashable, Any>'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}} }
c74149b9e160b24763f4885da2f4b76a
43.234043
200
0.655604
false
false
false
false
bazelbuild/tulsi
refs/heads/master
src/TulsiGenerator/RuleEntry.swift
apache-2.0
1
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Models the label and type of a single supported Bazel target. /// See http://bazel.build/docs/build-ref.html#targets. public class RuleInfo: Equatable, Hashable, CustomDebugStringConvertible { public let label: BuildLabel public let type: String /// Set of BuildLabels referencing targets that are required by this RuleInfo. For example, test /// hosts for XCTest targets. public let linkedTargetLabels: Set<BuildLabel> public var hashValue: Int { return label.hashValue ^ type.hashValue } public var debugDescription: String { return "\(Swift.type(of: self))(\(label) \(type))" } init(label: BuildLabel, type: String, linkedTargetLabels: Set<BuildLabel>) { self.label = label self.type = type self.linkedTargetLabels = linkedTargetLabels } func equals(_ other: RuleInfo) -> Bool { guard Swift.type(of: self) == Swift.type(of: other) else { return false } return self.type == other.type && self.label == other.label } } /// Encapsulates data about a file that may be a Bazel input or output. public class BazelFileInfo: Equatable, Hashable, CustomDebugStringConvertible { public enum TargetType: Int { case sourceFile case generatedFile } /// The path to this file relative to rootPath. public let subPath: String /// The root of this file's path (typically used to indicate the path to a generated file's root). public let rootPath: String /// The type of this file. public let targetType: TargetType /// Whether or not this file object is a directory. public let isDirectory: Bool public lazy var fullPath: String = { [unowned self] in return NSString.path(withComponents: [self.rootPath, self.subPath]) }() public lazy var uti: String? = { [unowned self] in return self.subPath.pbPathUTI }() public lazy var hashValue: Int = { [unowned self] in return self.subPath.hashValue &+ self.rootPath.hashValue &+ self.targetType.hashValue &+ self.isDirectory.hashValue }() init?(info: AnyObject?) { guard let info = info as? [String: AnyObject] else { return nil } guard let subPath = info["path"] as? String, let isSourceFile = info["src"] as? Bool else { assertionFailure("Aspect provided a file info dictionary but was missing required keys") return nil } self.subPath = subPath if let rootPath = info["root"] as? String { // Patch up self.rootPath = rootPath } else { self.rootPath = "" } self.targetType = isSourceFile ? .sourceFile : .generatedFile self.isDirectory = info["is_dir"] as? Bool ?? false } init(rootPath: String, subPath: String, isDirectory: Bool, targetType: TargetType) { self.rootPath = rootPath self.subPath = subPath self.isDirectory = isDirectory self.targetType = targetType } // MARK: - CustomDebugStringConvertible public lazy var debugDescription: String = { [unowned self] in return "{\(self.fullPath) \(self.isDirectory ? "<DIR> " : "")\(self.targetType)}" }() } public func ==(lhs: BazelFileInfo, rhs: BazelFileInfo) -> Bool { return lhs.targetType == rhs.targetType && lhs.rootPath == rhs.rootPath && lhs.subPath == rhs.subPath && lhs.isDirectory == rhs.isDirectory } /// Models the full metadata of a single supported Bazel target. /// See http://bazel.build/docs/build-ref.html#targets. public final class RuleEntry: RuleInfo { // Include paths are represented by a string and a boolean indicating whether they should be // searched recursively or not. public typealias IncludePath = (String, Bool) /// Mapping of BUILD file type to Xcode Target type for non-bundled types. static let BuildTypeToTargetType = [ "cc_binary": PBXTarget.ProductType.Application, "cc_library": PBXTarget.ProductType.StaticLibrary, "cc_test": PBXTarget.ProductType.Tool, // macos_command_line_application is not a bundled type in our rules as it does not contain // any resources, so we must explicitly list it here. "macos_command_line_application": PBXTarget.ProductType.Tool, "objc_library": PBXTarget.ProductType.StaticLibrary, "swift_library": PBXTarget.ProductType.StaticLibrary, ] /// Keys for a RuleEntry's attributes map. Definitions may be found in the Bazel Build /// Encyclopedia (see http://bazel.build/docs/be/overview.html). // Note: This set of must be kept in sync with the tulsi_aspects aspect. public enum Attribute: String { case bridging_header // Contains defines that were specified by the user on the commandline or are built into // Bazel itself. case compiler_defines case copts case datamodels case enable_modules case has_swift_dependency case has_swift_info case launch_storyboard case pch case swift_language_version case swift_toolchain case swiftc_opts // Contains various files that are used as part of the build process but need no special // handling in the generated Xcode project. For example, asset_catalog, storyboard, and xibs // attributes all end up as supporting_files. case supporting_files // For the {platform}_unit_test and {platform}_ui_test rules, contains a label reference to the // ios_application target to be used as the test host when running the tests. case test_host } /// Bazel attributes for this rule (e.g., "binary": <some label> on an ios_application). public let attributes: [Attribute: AnyObject] /// Artifacts produced by Bazel when this rule is built. public let artifacts: [BazelFileInfo] /// Objective-C defines to be applied to this rule by Bazel. public let objcDefines: [String]? /// Swift defines to be applied to this rule by Bazel. public let swiftDefines: [String]? /// Source files associated with this rule. public let sourceFiles: [BazelFileInfo] /// Non-ARC source files associated with this rule. public let nonARCSourceFiles: [BazelFileInfo] /// Paths to directories that will include header files. public let includePaths: [IncludePath]? /// Set of the labels that this rule depends on. public let dependencies: Set<BuildLabel> /// Set of the labels that this test rule's binary depends on. public let testDependencies: Set<BuildLabel> /// Set of ios_application extension labels that this rule utilizes. public let extensions: Set<BuildLabel> /// Set of ios_application app clip labels that this rule utilizes. public let appClips: Set<BuildLabel> /// .framework bundles provided by this rule. public let frameworkImports: [BazelFileInfo] /// List of implicit artifacts that are generated by this rule. public let secondaryArtifacts: [BazelFileInfo] /// The Swift language version used by this target. public let swiftLanguageVersion: String? /// The swift toolchain argument used by this target. public let swiftToolchain: String? /// List containing the transitive swiftmodules on which this rule depends. public let swiftTransitiveModules: [BazelFileInfo] /// List containing the transitive ObjC modulemaps on which this rule depends. public let objCModuleMaps: [BazelFileInfo] /// Module name to use in Xcode instead of the default. public let moduleName: String? /// The deployment platform target for this target. public let deploymentTarget: DeploymentTarget? /// Set of labels that this rule depends on but does not require. /// TODO(b/71904309): Remove this once test_suite fetching via Aspect is stable. // NOTE(abaire): This is a hack used for test_suite rules, where the possible expansions retrieved // via queries are filtered by the existence of the selected labels extracted via the normal // aspect path. Ideally the aspect would be able to directly express the relationship between the // test_suite and the test rules themselves, but that expansion is done prior to the application // of the aspect. public var weakDependencies = Set<BuildLabel>() /// Set of labels that this test_suite depends on. If this target is not a test_suite, returns /// an empty set. This maps directly to the `tests` attribute of the test_suite. public var testSuiteDependencies: Set<BuildLabel> { guard type == "test_suite" else { return Set() } // Legacy support for expansion of test_suite via a Bazel query. If a Bazel query is used, // `dependencies` will be empty and `weakDependencies` will contain the test_suite's // dependencies. Otherwise, `dependencies` will contain the test_suite's dependencies. guard dependencies.isEmpty else { return dependencies } return weakDependencies } /// The BUILD file that this rule was defined in. public let buildFilePath: String? // The CFBundleIdentifier associated with the target for this rule, if any. public let bundleID: String? /// The bundle name associated with the target for this rule, if any. public let bundleName: String? /// The product type for this rule (only for targets With AppleBundleInfo). let productType: PBXTarget.ProductType? /// The CFBundleIdentifier of the watchOS extension target associated with this rule, if any. public let extensionBundleID: String? /// The NSExtensionPointIdentifier of the extension associated with this rule, if any. public let extensionType: String? /// Xcode version used during the aspect run. Only set for bundled and runnable targets. public let xcodeVersion: String? /// Returns the set of non-versioned artifacts that are not source files. public var normalNonSourceArtifacts: [BazelFileInfo] { var artifacts = [BazelFileInfo]() if let description = attributes[.launch_storyboard] as? [String: AnyObject], let fileTarget = BazelFileInfo(info: description as AnyObject?) { artifacts.append(fileTarget) } if let fileTargets = parseFileDescriptionListAttribute(.supporting_files) { artifacts.append(contentsOf: fileTargets) } return artifacts } /// Returns the set of artifacts for which a versioned group should be created in the generated /// Xcode project. public var versionedNonSourceArtifacts: [BazelFileInfo] { if let fileTargets = parseFileDescriptionListAttribute(.datamodels) { return fileTargets } return [] } /// The full set of input and output artifacts for this rule. public var projectArtifacts: [BazelFileInfo] { var artifacts = sourceFiles artifacts.append(contentsOf: nonARCSourceFiles) artifacts.append(contentsOf: frameworkImports) artifacts.append(contentsOf: normalNonSourceArtifacts) artifacts.append(contentsOf: versionedNonSourceArtifacts) return artifacts } private(set) lazy var pbxTargetType: PBXTarget.ProductType? = { [unowned self] in if let productType = self.productType { return productType } return RuleEntry.BuildTypeToTargetType[self.type] }() /// Returns the value to be used as the Xcode SDKROOT for the build target generated for this /// RuleEntry. private(set) lazy var XcodeSDKRoot: String? = { [unowned self] in guard type != "cc_binary" && type != "cc_test" else { return PlatformType.macos.deviceSDK } if let platformType = self.deploymentTarget?.platform { return platformType.deviceSDK } return PlatformType.ios.deviceSDK }() init(label: BuildLabel, type: String, attributes: [String: AnyObject], artifacts: [BazelFileInfo] = [], sourceFiles: [BazelFileInfo] = [], nonARCSourceFiles: [BazelFileInfo] = [], dependencies: Set<BuildLabel> = Set(), testDependencies: Set<BuildLabel> = Set(), frameworkImports: [BazelFileInfo] = [], secondaryArtifacts: [BazelFileInfo] = [], weakDependencies: Set<BuildLabel>? = nil, extensions: Set<BuildLabel>? = nil, appClips: Set<BuildLabel>? = nil, bundleID: String? = nil, bundleName: String? = nil, productType: PBXTarget.ProductType? = nil, extensionBundleID: String? = nil, platformType: String? = nil, osDeploymentTarget: String? = nil, buildFilePath: String? = nil, objcDefines: [String]? = nil, swiftDefines: [String]? = nil, includePaths: [IncludePath]? = nil, swiftLanguageVersion: String? = nil, swiftToolchain: String? = nil, swiftTransitiveModules: [BazelFileInfo] = [], objCModuleMaps: [BazelFileInfo] = [], moduleName: String? = nil, extensionType: String? = nil, xcodeVersion: String? = nil) { var checkedAttributes = [Attribute: AnyObject]() for (key, value) in attributes { guard let checkedKey = Attribute(rawValue: key) else { print("Tulsi rule \(label.value) - Ignoring unknown attribute key \(key)") assertionFailure("Unknown attribute key \(key)") continue } checkedAttributes[checkedKey] = value } self.attributes = checkedAttributes let parsedPlatformType: PlatformType? if let platformTypeStr = platformType { parsedPlatformType = PlatformType(rawValue: platformTypeStr) } else { parsedPlatformType = nil } self.artifacts = artifacts self.sourceFiles = sourceFiles self.nonARCSourceFiles = nonARCSourceFiles self.dependencies = dependencies self.testDependencies = testDependencies self.frameworkImports = frameworkImports self.secondaryArtifacts = secondaryArtifacts if let weakDependencies = weakDependencies { self.weakDependencies = weakDependencies } self.extensions = extensions ?? Set() self.appClips = appClips ?? Set() self.bundleID = bundleID self.bundleName = bundleName self.productType = productType self.extensionBundleID = extensionBundleID var deploymentTarget: DeploymentTarget? = nil if let platform = parsedPlatformType, let osVersion = osDeploymentTarget { deploymentTarget = DeploymentTarget(platform: platform, osVersion: osVersion) } self.deploymentTarget = deploymentTarget self.buildFilePath = buildFilePath self.objcDefines = objcDefines self.moduleName = moduleName self.swiftDefines = swiftDefines self.includePaths = includePaths self.swiftLanguageVersion = swiftLanguageVersion self.swiftToolchain = swiftToolchain self.swiftTransitiveModules = swiftTransitiveModules self.xcodeVersion = xcodeVersion // Swift targets may have a generated Objective-C module map for their Swift generated header. // Unfortunately, this breaks Xcode's indexing (it doesn't really make sense to ask SourceKit // to index some source files in a module while at the same time giving it a compiled version // of the same module), so we must exclude it. // // We must do the same thing for tests, except that it may apply to multiple modules as we // combine sources from potentially multiple targets into one test target. let targetsToAvoid = testDependencies + [label] let moduleMapsToAvoid = targetsToAvoid.compactMap { (targetLabel: BuildLabel) -> String? in return targetLabel.asFileName } if !moduleMapsToAvoid.isEmpty { self.objCModuleMaps = objCModuleMaps.filter { moduleMapFileInfo in let moduleMapPath = moduleMapFileInfo.fullPath for mapToAvoid in moduleMapsToAvoid { if moduleMapPath.hasSuffix("\(mapToAvoid).modulemaps/module.modulemap") || moduleMapPath.hasSuffix("\(mapToAvoid).swift.modulemap") { return false } } return true } } else { self.objCModuleMaps = objCModuleMaps } self.extensionType = extensionType var linkedTargetLabels = Set<BuildLabel>() if let hostLabelString = self.attributes[.test_host] as? String { linkedTargetLabels.insert(BuildLabel(hostLabelString)) } super.init(label: label, type: type, linkedTargetLabels: linkedTargetLabels) } convenience init(label: String, type: String, attributes: [String: AnyObject], artifacts: [BazelFileInfo] = [], sourceFiles: [BazelFileInfo] = [], nonARCSourceFiles: [BazelFileInfo] = [], dependencies: Set<BuildLabel> = Set(), testDependencies: Set<BuildLabel> = Set(), frameworkImports: [BazelFileInfo] = [], secondaryArtifacts: [BazelFileInfo] = [], weakDependencies: Set<BuildLabel>? = nil, extensions: Set<BuildLabel>? = nil, appClips: Set<BuildLabel>? = nil, bundleID: String? = nil, bundleName: String? = nil, productType: PBXTarget.ProductType? = nil, extensionBundleID: String? = nil, platformType: String? = nil, osDeploymentTarget: String? = nil, buildFilePath: String? = nil, objcDefines: [String]? = nil, swiftDefines: [String]? = nil, includePaths: [IncludePath]? = nil, swiftLanguageVersion: String? = nil, swiftToolchain: String? = nil, swiftTransitiveModules: [BazelFileInfo] = [], objCModuleMaps: [BazelFileInfo] = [], moduleName: String? = nil, extensionType: String? = nil, xcodeVersion: String? = nil) { self.init(label: BuildLabel(label), type: type, attributes: attributes, artifacts: artifacts, sourceFiles: sourceFiles, nonARCSourceFiles: nonARCSourceFiles, dependencies: dependencies, testDependencies: testDependencies, frameworkImports: frameworkImports, secondaryArtifacts: secondaryArtifacts, weakDependencies: weakDependencies, extensions: extensions, appClips: appClips, bundleID: bundleID, bundleName: bundleName, productType: productType, extensionBundleID: extensionBundleID, platformType: platformType, osDeploymentTarget: osDeploymentTarget, buildFilePath: buildFilePath, objcDefines: objcDefines, swiftDefines: swiftDefines, includePaths: includePaths, swiftLanguageVersion: swiftLanguageVersion, swiftToolchain: swiftToolchain, swiftTransitiveModules: swiftTransitiveModules, objCModuleMaps: objCModuleMaps, moduleName: moduleName, extensionType: extensionType, xcodeVersion: xcodeVersion) } // MARK: Private methods private func parseFileDescriptionListAttribute(_ attribute: RuleEntry.Attribute) -> [BazelFileInfo]? { guard let descriptions = attributes[attribute] as? [[String: AnyObject]] else { return nil } var fileTargets = [BazelFileInfo]() for description in descriptions { guard let target = BazelFileInfo(info: description as AnyObject?) else { assertionFailure("Failed to resolve file description to a file target") continue } fileTargets.append(target) } return fileTargets } override func equals(_ other: RuleInfo) -> Bool { guard super.equals(other), let entry = other as? RuleEntry else { return false } return deploymentTarget == entry.deploymentTarget } } // MARK: - Equatable public func ==(lhs: RuleInfo, rhs: RuleInfo) -> Bool { return lhs.equals(rhs) }
fe1c3a2ba067429477171894f4c49a01
37.277154
104
0.682143
false
true
false
false
remirobert/MyCurrency
refs/heads/master
MyCurrency/CurrencyVertex.swift
mit
1
// // CurrencyVertex.swift // MyCurrency // // Created by Remi Robert on 07/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit class CurrencyVertex: Equatable { let currency: Currency var edges = [RateEdge]() init(currency: Currency) { self.currency = currency } } func ==(vertex1: CurrencyVertex, vertex2: CurrencyVertex) -> Bool { return vertex1.currency == vertex2.currency }
be3a1455c53314a8fb00605b41fcdea0
18.652174
67
0.659292
false
false
false
false
Dev-MJ/SlippingNaviController
refs/heads/master
SlippingNaviController/SlippingPopTransition.swift
mit
1
// // SlippingPopTransition.swift // SlippingNaviController // // Created by Dev.MJ on 08/05/2017. // Copyright © 2017 Dev.MJ. All rights reserved. // import UIKit class SlippingPopTransition: NSObject {} extension SlippingPopTransition: UIViewControllerAnimatedTransitioning { //required. Duration of the transition animation func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } //required. 애니메이터 객체에 전환 애니메이션을 수행하도록 지시. func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { //transitionContext : transition에 관한 정보를 포함한 context object. //transition이 시작할 때 보이는 VC guard let startVC = transitionContext.viewController(forKey: .from) else { return } //transition이 끝난 뒤에 보이는 VC guard let endVC = transitionContext.viewController(forKey: .to) else { return } ///The view in which the animated transition should take place. let containerView = transitionContext.containerView if let endView = endVC.view, let startView = startVC.view { containerView.addSubview(endView) containerView.bringSubview(toFront: startView) endView.frame = transitionContext.finalFrame(for: endVC) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveLinear, animations: { startVC.view.frame = CGRect(x: endVC.view.frame.width, y: startVC.view.frame.origin.y, width: startVC.view.frame.width, height: startVC.view.frame.height) }, completion: { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } }
0b0a4fd9b0dea5f973a506ddd05a18c7
39.632653
107
0.631341
false
false
false
false
ayking/tasty-imitation-keyboard
refs/heads/master
Keyboard/CatboardBanner.swift
bsd-3-clause
4
// // CatboardBanner.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 10/5/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit /* This is the demo banner. The banner is needed so that the top row popups have somewhere to go. Might as well fill it with something (or leave it blank if you like.) */ class CatboardBanner: ExtraView { var catSwitch: UISwitch = UISwitch() var catLabel: UILabel = UILabel() required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode) self.addSubview(self.catSwitch) self.addSubview(self.catLabel) self.catSwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) self.catSwitch.transform = CGAffineTransformMakeScale(0.75, 0.75) self.catSwitch.addTarget(self, action: Selector("respondToSwitch"), forControlEvents: UIControlEvents.ValueChanged) self.updateAppearance() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setNeedsLayout() { super.setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() self.catSwitch.center = self.center self.catLabel.center = self.center self.catLabel.frame.origin = CGPointMake(self.catSwitch.frame.origin.x + self.catSwitch.frame.width + 8, self.catLabel.frame.origin.y) } func respondToSwitch() { NSUserDefaults.standardUserDefaults().setBool(self.catSwitch.on, forKey: kCatTypeEnabled) self.updateAppearance() } func updateAppearance() { if self.catSwitch.on { self.catLabel.text = "😺" self.catLabel.alpha = 1 } else { self.catLabel.text = "🐱" self.catLabel.alpha = 0.5 } self.catLabel.sizeToFit() } }
f3d96d9dc5d3dfcb1944d8c003ad332d
29.850746
142
0.652637
false
false
false
false
grandiere/box
refs/heads/master
box/Model/Help/Antivirus/MHelpAntivirusIntro.swift
mit
1
import UIKit class MHelpAntivirusIntro:MHelpProtocol { private let attributedString:NSAttributedString init() { let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:20), NSForegroundColorAttributeName:UIColor.white] let attributesDescription:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:18), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)] let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpAntivirusIntro_title", comment:""), attributes:attributesTitle) let stringDescription:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpAntivirusIntro_description", comment:""), attributes:attributesDescription) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringDescription) attributedString = mutableString } var message:NSAttributedString { get { return attributedString } } var image:UIImage { get { return #imageLiteral(resourceName: "assetHelpAntivirusIntro") } } }
9e2da183089150483b61e2e4aff174b2
30.113636
84
0.653031
false
false
false
false
urbanthings/urbanthings-sdk-apple
refs/heads/master
UnitTests/UrbanThingsAPI/UrbanThingsAPITests.swift
apache-2.0
1
// // UrbanThingsAPITests.swift // UrbanThingsAPITests // // Created by Mark Woollard on 25/04/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import XCTest import CoreLocation @testable import UTAPI let ApiTestKey = "A VALID API KEY" class UrbanThingsAPITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGetImportSources() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTImportSourcesRequest()) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetTransitStops() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitStopsRequest(center:CLLocationCoordinate2D(latitude:51.0, longitude:0.0), radius:5000)) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetPlacePoints() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTPlacePointsRequest(center:CLLocationCoordinate2D(latitude:51.0, longitude:0), radius:5000)) { data, error in if let data = data { for placePoint in data.placePoints { print("\(placePoint.name)") } } else { print("\(error)") } expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetPlacesList() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTPlacesListRequest(name:"Piccadilly", location:CLLocationCoordinate2D(latitude: 51, longitude: 0))) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetTransitRouteInfoByStopId() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitRoutesByStopRequest(stopID: "490009277Y")) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetAgency() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitAgencyRequest(agencyID: "TFL")) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetAgencies() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitAgenciesRequest(importSource: "ABC")) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetTrips() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitTripsRequest(tripID:"BLT_T_1634523", includePolylines:true, includeStopCoordinates:true)) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetStopCalls() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitStopCallsRequest(stopID:"BLT:755")) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testGetTripGroups() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTTransitTripGroupRequest(routeID: "BLT_R_7867")) { (data, error) in expectation.fulfill() } waitForExpectationsWithTimeout(60) { error in } } func testRTIReport() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTRealtimeReportRequest(stopID: "1400ZZBBSHF0")) { (data, error) in expectation.fulfill() } waitForExpectationsWithTimeout(60) { error in } } func testRTIStopboard() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTRealtimeStopboardRequest(stopID: "1400ZZBBSHF0")) { (data, error) in expectation.fulfill() } waitForExpectationsWithTimeout(60) { error in } } func testRTIResourceStatus() { let sut = UrbanThingsAPI(apiKey: ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTRealtimeResourceStatusRequest(stopID: "1400ZZBBSHF0")) { (data, error) in expectation.fulfill() } waitForExpectationsWithTimeout(60) { error in } } func testGetDirections() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTDirectionsRequest( origin: TestPlacePoint(primaryCode: "SUNNYMEADS", name:"Sunnymeads Station", location: CLLocationCoordinate2D(latitude: 51.4702933, longitude:-0.5615487)), destination: TestPlacePoint(primaryCode: "OFFICE", name:"Office", location: CLLocationCoordinate2D(latitude: 51.5291205, longitude:-0.0802295)))) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } func testAppSearch() { let sut = UrbanThingsAPI(apiKey:ApiTestKey) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTAppSearchRequest(query:"Sunnymeads Station", location: CLLocationCoordinate2D(latitude: 51.4702933, longitude:-0.5615487))) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } func testAppAgencies() { struct ExampleService: Service { let endpoint: String = "http://example.dev.api.urbanthings.io/api" let version: String = "3-a" } let sut = UrbanThingsAPI(apiKey:ApiTestKey, service: ExampleService()) let expectation = expectationWithDescription("Waiting for API response") let _ = sut.sendRequest(UTAppAgenciesRequest()) { data, error in expectation.fulfill() } waitForExpectationsWithTimeout(30) { error in } } }
60c4a9b53d710ecc8171cbbc4851d72b
31.262295
174
0.643166
false
true
false
false
Alamofire/Alamofire
refs/heads/master
Tests/ValidationTests.swift
mit
2
// // ValidationTests.swift // // Copyright (c) 2014-2018 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. // @testable import Alamofire import Foundation import XCTest final class StatusCodeValidationTestCase: BaseTestCase { func testThatValidationForRequestWithAcceptableStatusCodeResponseSucceeds() { // Given let endpoint = Endpoint.status(200) let expectation1 = expectation(description: "request should return 200 status code") let expectation2 = expectation(description: "download should return 200 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(statusCode: 200..<300) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(statusCode: 200..<300) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() { // Given let endpoint = Endpoint.status(404) let expectation1 = expectation(description: "request should return 404 status code") let expectation2 = expectation(description: "download should return 404 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(statusCode: [200]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(statusCode: [200]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableStatusCode, true) XCTAssertEqual(error?.responseCode, 404) } } func testThatValidationForRequestWithNoAcceptableStatusCodesFails() { // Given let endpoint = Endpoint.status(201) let expectation1 = expectation(description: "request should return 201 status code") let expectation2 = expectation(description: "download should return 201 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(statusCode: []) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(statusCode: []) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableStatusCode, true) XCTAssertEqual(error?.responseCode, 201) } } } // MARK: - final class ContentTypeValidationTestCase: BaseTestCase { func testThatValidationForRequestWithAcceptableContentTypeResponseSucceeds() { // Given let endpoint = Endpoint.ip let expectation1 = expectation(description: "request should succeed and return ip") let expectation2 = expectation(description: "download should succeed and return ip") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: ["application/json"]) .validate(contentType: ["application/json; charset=utf-8"]) .validate(contentType: ["application/json; q=0.8; charset=utf-8"]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["application/json"]) .validate(contentType: ["application/json; charset=utf-8"]) .validate(contentType: ["application/json; q=0.8; charset=utf-8"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() { // Given let endpoint = Endpoint.ip let expectation1 = expectation(description: "request should succeed and return ip") let expectation2 = expectation(description: "download should succeed and return ip") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: ["*/*"]) .validate(contentType: ["application/*"]) .validate(contentType: ["*/json"]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["*/*"]) .validate(contentType: ["application/*"]) .validate(contentType: ["*/json"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() { // Given let endpoint = Endpoint.xml let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableContentType, true) XCTAssertEqual(error?.responseContentType, "application/xml") XCTAssertEqual(error?.acceptableContentTypes?.first, "application/octet-stream") } } func testThatContentTypeValidationFailureSortsPossibleContentTypes() { // Given let endpoint = Endpoint.xml let requestDidCompleteExpectation = expectation(description: "request should succeed and return xml") let downloadDidCompleteExpectation = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? let acceptableContentTypes = [// Sorted in a random order, not alphabetically "application/octet-stream", "image/gif", "image/x-xbitmap", "image/tiff", "image/jpg", "image/x-bmp", "image/jpeg", "image/x-icon", "image/jp2", "image/png", "image/ico", "image/bmp", "image/x-ms-bmp", "image/x-win-bitmap"] // When AF.request(endpoint) .validate(contentType: acceptableContentTypes) .response { resp in requestError = resp.error requestDidCompleteExpectation.fulfill() } AF.download(endpoint) .validate(contentType: acceptableContentTypes) .response { resp in downloadError = resp.error downloadDidCompleteExpectation.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) let expectedAcceptableContentTypes = [// Sorted in a specific order, alphabetically "application/octet-stream", "image/bmp", "image/gif", "image/ico", "image/jp2", "image/jpeg", "image/jpg", "image/png", "image/tiff", "image/x-bmp", "image/x-icon", "image/x-ms-bmp", "image/x-win-bitmap", "image/x-xbitmap"] for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableContentType, true) XCTAssertEqual(error?.responseContentType, "application/xml") XCTAssertEqual(error?.acceptableContentTypes, expectedAcceptableContentTypes) } } func testThatValidationForRequestWithNoAcceptableContentTypeResponseFails() { // Given let endpoint = Endpoint.xml let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: []) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: []) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableContentType, true) XCTAssertEqual(error?.responseContentType, "application/xml") XCTAssertEqual(error?.acceptableContentTypes?.isEmpty, true) } } func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() { // Given let endpoint = Endpoint.status(204) let expectation1 = expectation(description: "request should succeed and return no data") let expectation2 = expectation(description: "download should succeed and return no data") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: []) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: []) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceedsWhenResponseIsNil() { // Given class MockManager: Session { override func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { let request = MockDataRequest(convertible: convertible, underlyingQueue: rootQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: self) perform(request) return request } override func download(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil, to destination: DownloadRequest.Destination?) -> DownloadRequest { let request = MockDownloadRequest(downloadable: .request(convertible), underlyingQueue: rootQueue, serializationQueue: serializationQueue, eventMonitor: eventMonitor, interceptor: interceptor, delegate: self, destination: destination ?? MockDownloadRequest.defaultDestination) perform(request) return request } } class MockDataRequest: DataRequest { override var response: HTTPURLResponse? { MockHTTPURLResponse(url: request!.url!, statusCode: 204, httpVersion: "HTTP/1.1", headerFields: nil) } } class MockDownloadRequest: DownloadRequest { override var response: HTTPURLResponse? { MockHTTPURLResponse(url: request!.url!, statusCode: 204, httpVersion: "HTTP/1.1", headerFields: nil) } } class MockHTTPURLResponse: HTTPURLResponse { override var mimeType: String? { nil } } let manager: Session = { let configuration: URLSessionConfiguration = { let configuration = URLSessionConfiguration.ephemeral configuration.headers = HTTPHeaders.default return configuration }() return MockManager(configuration: configuration) }() let endpoint = Endpoint.method(.delete) let expectation1 = expectation(description: "request should be stubbed and return 204 status code") let expectation2 = expectation(description: "download should be stubbed and return 204 status code") var requestResponse: DataResponse<Data?, AFError>? var downloadResponse: DownloadResponse<URL?, AFError>? // When manager.request(endpoint) .validate(contentType: ["*/*"]) .response { resp in requestResponse = resp expectation1.fulfill() } manager.download(endpoint) .validate(contentType: ["*/*"]) .response { resp in downloadResponse = resp expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestResponse?.response) XCTAssertNotNil(requestResponse?.data) XCTAssertNil(requestResponse?.error) XCTAssertEqual(requestResponse?.response?.statusCode, 204) XCTAssertNil(requestResponse?.response?.mimeType) XCTAssertNotNil(downloadResponse?.response) XCTAssertNotNil(downloadResponse?.fileURL) XCTAssertNil(downloadResponse?.error) XCTAssertEqual(downloadResponse?.response?.statusCode, 204) XCTAssertNil(downloadResponse?.response?.mimeType) } } // MARK: - final class MultipleValidationTestCase: BaseTestCase { func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() { // Given let endpoint = Endpoint.ip let expectation1 = expectation(description: "request should succeed and return ip") let expectation2 = expectation(description: "request should succeed and return ip") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() { // Given let endpoint = Endpoint.xml let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(statusCode: 400..<600) .validate(contentType: ["application/octet-stream"]) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(statusCode: 400..<600) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableStatusCode, true) XCTAssertEqual(error?.responseCode, 200) } } func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() { // Given let endpoint = Endpoint.xml let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(contentType: ["application/octet-stream"]) .validate(statusCode: 400..<600) .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .validate(statusCode: 400..<600) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableContentType, true) XCTAssertEqual(error?.responseContentType, "application/xml") XCTAssertEqual(error?.acceptableContentTypes?.first, "application/octet-stream") } } } // MARK: - final class AutomaticValidationTestCase: BaseTestCase { func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() { // Given let urlRequest = Endpoint.ip.modifying(\.headers, to: [.accept("application/json")]) let expectation1 = expectation(description: "request should succeed and return ip") let expectation2 = expectation(description: "download should succeed and return ip") var requestError: AFError? var downloadError: AFError? // When AF.request(urlRequest).validate().response { resp in requestError = resp.error expectation1.fulfill() } AF.download(urlRequest).validate().response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() { // Given let request = Endpoint.status(404) let expectation1 = expectation(description: "request should return 404 status code") let expectation2 = expectation(description: "download should return 404 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(request) .validate() .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(request) .validate() .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableStatusCode, true) XCTAssertEqual(error?.responseCode, 404) } } func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() { // Given let urlRequest = Endpoint.ip.modifying(\.headers, to: [.accept("application/*")]) let expectation1 = expectation(description: "request should succeed and return ip") let expectation2 = expectation(description: "download should succeed and return ip") var requestError: AFError? var downloadError: AFError? // When AF.request(urlRequest).validate().response { resp in requestError = resp.error expectation1.fulfill() } AF.download(urlRequest).validate().response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() { // Given var urlRequest = Endpoint.xml.urlRequest let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5" urlRequest.headers["Accept"] = headerValue let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "request should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(urlRequest).validate().response { resp in requestError = resp.error expectation1.fulfill() } AF.download(urlRequest).validate().response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() { // Given let urlRequest = Endpoint.xml.modifying(\.headers, to: [.accept("application/json")]) let expectation1 = expectation(description: "request should succeed and return xml") let expectation2 = expectation(description: "download should succeed and return xml") var requestError: AFError? var downloadError: AFError? // When AF.request(urlRequest).validate().response { resp in requestError = resp.error expectation1.fulfill() } AF.download(urlRequest).validate().response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestError) XCTAssertNotNil(downloadError) for error in [requestError, downloadError] { XCTAssertEqual(error?.isUnacceptableContentType, true) XCTAssertEqual(error?.responseContentType, "application/xml") XCTAssertEqual(error?.acceptableContentTypes?.first, "application/json") } } } // MARK: - private enum ValidationError: Error { case missingData, missingFile, fileReadFailed } extension DataRequest { func validateDataExists() -> Self { validate { _, _, data in guard data != nil else { return .failure(ValidationError.missingData) } return .success(()) } } func validate(with error: Error) -> Self { validate { _, _, _ in .failure(error) } } } extension DownloadRequest { func validateDataExists() -> Self { validate { [unowned self] _, _, _ in let fileURL = self.fileURL guard let validFileURL = fileURL else { return .failure(ValidationError.missingFile) } do { _ = try Data(contentsOf: validFileURL) return .success(()) } catch { return .failure(ValidationError.fileReadFailed) } } } func validate(with error: Error) -> Self { validate { _, _, _ in .failure(error) } } } // MARK: - final class CustomValidationTestCase: BaseTestCase { func testThatCustomValidationClosureHasAccessToServerResponseData() { // Given let endpoint = Endpoint() let expectation1 = expectation(description: "request should return 200 status code") let expectation2 = expectation(description: "download should return 200 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate { _, _, data in guard data != nil else { return .failure(ValidationError.missingData) } return .success(()) } .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate { _, _, fileURL in guard let fileURL = fileURL else { return .failure(ValidationError.missingFile) } do { _ = try Data(contentsOf: fileURL) return .success(()) } catch { return .failure(ValidationError.fileReadFailed) } } .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatCustomValidationCanThrowCustomError() { // Given let endpoint = Endpoint() let expectation1 = expectation(description: "request should return 200 status code") let expectation2 = expectation(description: "download should return 200 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate { _, _, _ in .failure(ValidationError.missingData) } .validate { _, _, _ in .failure(ValidationError.missingFile) } // should be ignored .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate { _, _, _ in .failure(ValidationError.missingFile) } .validate { _, _, _ in .failure(ValidationError.fileReadFailed) } // should be ignored .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertEqual(requestError?.asAFError?.underlyingError as? ValidationError, .missingData) XCTAssertEqual(downloadError?.asAFError?.underlyingError as? ValidationError, .missingFile) } func testThatValidationExtensionHasAccessToServerResponseData() { // Given let endpoint = Endpoint() let expectation1 = expectation(description: "request should return 200 status code") let expectation2 = expectation(description: "download should return 200 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validateDataExists() .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validateDataExists() .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } func testThatValidationExtensionCanThrowCustomError() { // Given let endpoint = Endpoint() let expectation1 = expectation(description: "request should return 200 status code") let expectation2 = expectation(description: "download should return 200 status code") var requestError: AFError? var downloadError: AFError? // When AF.request(endpoint) .validate(with: ValidationError.missingData) .validate(with: ValidationError.missingFile) // should be ignored .response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(with: ValidationError.missingFile) .validate(with: ValidationError.fileReadFailed) // should be ignored .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertEqual(requestError?.asAFError?.underlyingError as? ValidationError, .missingData) XCTAssertEqual(downloadError?.asAFError?.underlyingError as? ValidationError, .missingFile) } }
29f1196fcdc591cab9888acfaf2efd83
32.61658
121
0.596917
false
false
false
false
Colormark/BLButton
refs/heads/master
BLIcon.swift
mit
1
// // BLIcon.swift need FontAwesome // fourshaonian // // Created by FangYan on 16/5/23. // Copyright © 2016年 yousi.inc. All rights reserved. // import UIKit @IBDesignable public class BLIcon: UILabel { @IBInspectable var Icon : String = "fa-arrow-down" { didSet { commonInit() } } @IBInspectable var Size : Int = 12 { didSet { commonInit() } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit (){ self.font = UIFont.fontAwesomeOfSize(CGFloat(self.Size)) let iconName = self.Icon self.text = String.fontAwesomeIconWithName(FontAwesome.fromCode(iconName)!) } }
9ada7a564d198e3e31412b168faaba06
19.372093
83
0.577626
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
SyncTests/TestBookmarkModel.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 Deferred import Foundation import Shared @testable import Storage @testable import Sync import XCTest // Thieved mercilessly from TestSQLiteBookmarks. private func getBrowserDBForFile(filename: String, files: FileAccessor) -> BrowserDB? { let db = BrowserDB(filename: filename, files: files) // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if db.createOrUpdate(BrowserTable()) != .Success { return nil } return db } class TestBookmarkModel: FailFastTestCase { let files = MockFiles() override func tearDown() { do { try self.files.removeFilesInDirectory() } catch { } super.tearDown() } private func getBrowserDB(name: String) -> BrowserDB? { let file = "TBookmarkModel\(name).db" print("DB file named: \(file)") return getBrowserDBForFile(file, files: self.files) } func getSyncableBookmarks(name: String) -> MergedSQLiteBookmarks? { guard let db = self.getBrowserDB(name) else { XCTFail("Couldn't get prepared DB.") return nil } return MergedSQLiteBookmarks(db: db) } func testBookmarkEditableIfNeverSyncedAndEmptyBuffer() { guard let bookmarks = self.getSyncableBookmarks("A") else { XCTFail("Couldn't get bookmarks.") return } // Set a local bookmark let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!) XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!) let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertTrue(menuFolder.current[0]!.isEditable) } func testBookmarkEditableIfNeverSyncedWithBufferedChanges() { guard let bookmarks = self.getSyncableBookmarks("B") else { XCTFail("Couldn't get bookmarks.") return } let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() // Add a buffer into the buffer let mirrorDate = NSDate.now() - 100000 bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["BBB"]), BookmarkMirrorItem.bookmark("BBB", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "BBB", description: nil, URI: "http://BBB.com", tags: "", keyword: nil) ]).succeeded() XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!) // Check to see if we're editable let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertTrue(menuFolder.current[0]!.isEditable) } func testBookmarksEditableWithEmptyBufferAndRemoteBookmark() { guard let bookmarks = self.getSyncableBookmarks("C") else { XCTFail("Couldn't get bookmarks.") return } // Add a bookmark to the menu folder in our mirror let mirrorDate = NSDate.now() - 100000 bookmarks.populateMirrorViaBuffer([ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["CCC"]), BookmarkMirrorItem.bookmark("CCC", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "CCC", description: nil, URI: "http://CCC.com", tags: "", keyword: nil) ], atDate: mirrorDate) // Set a local bookmark let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!) // Check to see if we're editable let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 2) XCTAssertTrue(menuFolder.current[0]!.isEditable) XCTAssertTrue(menuFolder.current[1]!.isEditable) } func testBookmarksNotEditableForUnmergedChanges() { guard let bookmarks = self.getSyncableBookmarks("D") else { XCTFail("Couldn't get bookmarks.") return } // Add a bookmark to the menu folder in our mirror let mirrorDate = NSDate.now() - 100000 bookmarks.populateMirrorViaBuffer([ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE"]), BookmarkMirrorItem.bookmark("EEE", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "EEE", description: nil, URI: "http://EEE.com", tags: "", keyword: nil) ], atDate: mirrorDate) bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded() // Add some unmerged bookmarks into the menu folder in the buffer. bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]), BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil) ]).succeeded() XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!) // Check to see that we can't edit these bookmarks let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertFalse(menuFolder.current[0]!.isEditable) } func testLocalBookmarksEditableWhileHavingUnmergedChangesAndEmptyMirror() { guard let bookmarks = self.getSyncableBookmarks("D") else { XCTFail("Couldn't get bookmarks.") return } bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded() // Add some unmerged bookmarks into the menu folder in the buffer. let mirrorDate = NSDate.now() - 100000 bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]), BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil) ]).succeeded() // Local bookmark should be editable let mobileFolder = bookmarks.mobileFolder() XCTAssertEqual(mobileFolder.current.count, 2) XCTAssertTrue(mobileFolder.current[1]!.isEditable) } } private extension MergedSQLiteBookmarks { func isMirrorEmpty() -> Deferred<Maybe<Bool>> { return self.local.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksMirror)") } func wipeLocal() { self.local.db.run(["DELETE FROM \(TableBookmarksLocalStructure)", "DELETE FROM \(TableBookmarksLocal)"]).succeeded() } func populateMirrorViaBuffer(items: [BookmarkMirrorItem], atDate mirrorDate: Timestamp) { self.applyRecords(items).succeeded() // … and add the root relationships that will be missing (we don't do those for the buffer, // so we need to manually add them and move them across). self.buffer.db.run([ "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MenuFolderGUID)', 0),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.ToolbarFolderGUID)', 1),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.UnfiledFolderGUID)', 2),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MobileFolderGUID)', 3)", ].joined(" ")).succeeded() // Move it all to the mirror. self.local.db.moveBufferToMirrorForTesting() } func menuFolder() -> BookmarksModel { return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MenuFolderGUID).value.successValue! } func mobileFolder() -> BookmarksModel { return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MobileFolderGUID).value.successValue! } }
43c64825c8c6244dc70820b72b7b54c3
48.370192
233
0.681858
false
true
false
false
HWdan/DYTV
refs/heads/master
DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift
mit
1
// // BaseViewController.swift // DYTV // // Created by hegaokun on 2017/4/12. // Copyright © 2017年 AAS. All rights reserved. // import UIKit class BaseViewController: UIViewController { //MARK:- 定义属性 var contentView: UIView? //MARK:- 懒加载 fileprivate lazy var animImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.center.y = (kStausBarH + kNavigationBarH + kTitleViewH + kTabbarH) * 1.7 imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX return imageView }() //MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } //MARK:- 设置 UI extension BaseViewController { func setupUI() { //隐藏内容的 View contentView?.isHidden = true view.addSubview(animImageView) animImageView.startAnimating() view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadDtaaFinished() { animImageView.stopAnimating() animImageView.isHidden = true contentView?.isHidden = false } }
a785c5d52437b6198265a76fa57f3abd
25.714286
104
0.629488
false
false
false
false
suyup/FileScreenshot
refs/heads/master
DocInteraction/TableViewController.swift
mit
1
// // TableViewController.swift // DocInteraction // // Created by span on 3/3/17. // Copyright © 2017 x. All rights reserved. // import MobileCoreServices import UIKit import QuickLook let sampleDocs: [String] = [ "Text Document.txt", "Image Document.jpg", "PDF Document.pdf", "HTML Document.html" ] class TableViewController: UITableViewController { fileprivate var dirWatcher: DirectoryWatcher! fileprivate var documents: [URL] = [] fileprivate var docInteractionController: UIDocumentInteractionController! override func viewDidLoad() { super.viewDidLoad() if let watcher = DirectoryWatcher.watchFolderWithPath(FileManager.default.documentDir, delegate: self) { self.dirWatcher = watcher self.directoryDidChange(self.dirWatcher) } else { fatalError("cannot initiate directory watcher") } self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(TableViewController.addPressed(_:))) } // Mark: override func numberOfSections(in tableView: UITableView) -> Int { return self.documents.count > 0 ? 2 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return sampleDocs.count } else { return self.documents.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Sample Documents" } else { return "Document Folder" } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 58.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! let fileURL = self.fileURL(at: indexPath) self.setupDocInteractionController(url: fileURL) cell.imageView?.image = self.docInteractionController.icons.last cell.textLabel?.text = fileURL.lastPathComponent if let fileAttributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path), let fileSize = fileAttributes[FileAttributeKey.size] as? NSNumber { let fileSizeStr = ByteCountFormatter.string(fromByteCount: fileSize.int64Value, countStyle: .file) let uti = self.docInteractionController.uti ?? "unknown" cell.detailTextLabel?.text = "\(fileSizeStr) - \(uti)" } let gesture = UILongPressGestureRecognizer(target: self, action: #selector(TableViewController.handleLongPress(_:))) cell.imageView?.addGestureRecognizer(gesture) cell.imageView?.isUserInteractionEnabled = true return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let url = self.fileURL(at: indexPath) self.setupDocInteractionController(url: url) let uti = self.docInteractionController.uti ?? "unknown" let controller: UIViewController if uti == kUTTypePlainText as String { controller = EditorController(url: url) } else { controller = WebViewController(url: url) } self.navigationController?.pushViewController(controller, animated: true) } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == 0 { return nil } let rowAction = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in let url = self.fileURL(at: indexPath) try? FileManager.default.removeItem(at: url) } return [rowAction] } // Mark: fileprivate func fileURL(at indexPath: IndexPath) -> URL { var fileURL: URL if indexPath.section == 0 { let path = Bundle.main.path(forResource: sampleDocs[indexPath.row], ofType: nil) fileURL = URL(fileURLWithPath: path!) } else { fileURL = self.documents[indexPath.row] } return fileURL } fileprivate func setupDocInteractionController(url: URL) { if self.docInteractionController == nil { let dic = UIDocumentInteractionController(url: url) self.docInteractionController = dic } else { self.docInteractionController.url = url } } func handleLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { if let indexPath = self.tableView.indexPathForRow(at: sender.location(in: self.tableView)), let view = sender.view { let fileURL = self.fileURL(at: indexPath) self.setupDocInteractionController(url: fileURL) let res = self.docInteractionController.presentOpenInMenu(from: view.frame, in: view, animated: true) precondition(res, "display open in fails") } } } func addPressed(_ sender: UIBarButtonItem) { self.present(self.addFileAlertController, animated: true, completion: nil) } fileprivate var addFileAlertController: UIAlertController { let alert = UIAlertController(title: "Add", message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { action in if var text = alert.textFields?.first?.text?.trimmingCharacters(in: .illegalCharacters) { if text.characters.count == 0 { text = alert.textFields!.first!.placeholder! } self.addNewFile(name: text) } } alert.addAction(okAction) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addTextField { textField in textField.placeholder = "New File" } return alert } fileprivate func addNewFile(name: String) { let path = (FileManager.default.documentDir as NSString).appendingPathComponent("\(name).txt") let data = "new file".data(using: .utf8) FileManager.default.createFile(atPath: path, contents: data, attributes: nil) } } extension TableViewController: DirectoryWatcherDelegate { func directoryDidChange(_ folderWatcher: DirectoryWatcher) { self.documents.removeAll(keepingCapacity: true) let docDirPath = FileManager.default.documentDir let docDirContents = (try? FileManager.default.contentsOfDirectory(atPath: docDirPath)) ?? [] for filename in docDirContents { let filePath = (docDirPath as NSString).appendingPathComponent(filename) let fileURL = URL(fileURLWithPath: filePath) var isDirectory: ObjCBool = false if FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory), !isDirectory.boolValue { self.documents.append(fileURL) } } self.tableView.reloadData() } }
0c202da0223b26cf022ba5cb75375612
36.744898
119
0.638821
false
false
false
false
paulo17/Find-A-Movie-iOS
refs/heads/master
FindAMovie/Image.swift
gpl-2.0
1
// // Image.swift // FindAMovie // // Created by Paul on 11/06/2015. // Copyright (c) 2015 Hetic. All rights reserved. // import Foundation /** * Image class */ class Image { var id: Int var file_path: String? var width: Int? var height: Int? /** Initialize a new image - parameter id: Int - parameter file_path: String (optional) - parameter width: Int (optional) - parameter height: Int (optional) */ init(id: Int, file_path: String?, width: Int?, height: Int?){ self.id = id if let path = file_path { self.file_path = path } if let w = width { self.width = w } if let h = height { self.height = h } } /** Return image URL using file_path - returns: NSURL (optional) */ func getImageURL(size size: String = "w185") -> NSURL? { if let image = self.file_path { let api = MovieDbService() let imageURL = NSURL(string: api.movieDbImageUrl + size + "/" + image) return imageURL } return nil } }
ecbd5a43009805f0b722b55df8ab39c1
18.384615
82
0.478157
false
false
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Reading-阅读/Controller/Read/JENReadSerialViewController.swift
mit
1
// // JENReadSerialViewController.swift // ONE_Swift // // Created by 任玉祥 on 16/5/4. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENReadSerialViewController: JENReadTableViewController { override var readItems: [AnyObject] { get { return readList.serial } } override var readType: JENReadType { get { return .Serial } } override var pastListEndDate: String { get { return "2016-01" } } } // MARK: - tableView protocol extension JENReadSerialViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> JENReadCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) cell.serial = readItems[indexPath.row] as! JENReadSerialItem return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let serialVc = JENSerialDetailViewController() guard let detail_id = (readItems[indexPath.row] as! JENReadSerialItem).content_id else { return } serialVc.detail_id = detail_id navigationController?.pushViewController(serialVc, animated: true) } }
0eafcc08a84e3bce9231ee4f159a9bba
28.5
114
0.691438
false
false
false
false
manavgabhawala/UberSDK
refs/heads/master
Shared/UberUser.swift
apache-2.0
1
// // UberUser.swift // UberSDK // // Created by Manav Gabhawala on 6/13/15. // // import Foundation /// The User Profile endpoint returns information about the Uber user that has authorized with the application. @objc public final class UberUser : NSObject, JSONCreateable, UberObjectHasImage { /// First name of the Uber user. @objc public let firstName : String /// Last name of the Uber user. @objc public let lastName : String /// Email address of the Uber user. @objc public let email : String /// Image URL of the Uber user. @objc public let imageURL : NSURL? /// Promo code of the Uber user. @objc public let promoCode : String? /// Unique identifier of the Uber user. @objc public let UUID : String @objc public override var description : String { get { return "Uber User \(firstName) \(lastName)" } } public required init?(JSON: [NSObject: AnyObject]) { guard let firstName = JSON["first_name"] as? String, let lastName = JSON["last_name"] as? String, let email = JSON["email"] as? String, let UUID = JSON["uuid"] as? String else { self.firstName = "" self.lastName = "" self.email = "" self.imageURL = nil self.promoCode = nil self.UUID = "" super.init() return nil } self.firstName = firstName self.lastName = lastName self.email = email self.UUID = UUID if let URL = JSON["picture"] as? String { imageURL = NSURL(string: URL) } else { imageURL = nil } promoCode = JSON["promo_code"] as? String super.init() } }
13f01c495ff971720bfc58a34a22e815
24.283333
172
0.669525
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/CacheDBWriterHelper.swift
mit
1
import Foundation final class CacheDBWriterHelper { static func fetchOrCreateCacheGroup(with groupKey: String, in moc: NSManagedObjectContext) -> CacheGroup? { return cacheGroup(with: groupKey, in: moc) ?? createCacheGroup(with: groupKey, in: moc) } static func fetchOrCreateCacheItem(with url: URL, itemKey: String, variant: String?, in moc: NSManagedObjectContext) -> CacheItem? { return cacheItem(with: itemKey, variant: variant, in: moc) ?? createCacheItem(with: url, itemKey: itemKey, variant: variant, in: moc) } static func cacheGroup(with key: String, in moc: NSManagedObjectContext) -> CacheGroup? { let fetchRequest: NSFetchRequest<CacheGroup> = CacheGroup.fetchRequest() fetchRequest.predicate = NSPredicate(format: "key == %@", key) fetchRequest.fetchLimit = 1 do { guard let group = try moc.fetch(fetchRequest).first else { return nil } return group } catch let error { fatalError(error.localizedDescription) } } static func createCacheGroup(with groupKey: String, in moc: NSManagedObjectContext) -> CacheGroup? { guard let entity = NSEntityDescription.entity(forEntityName: "CacheGroup", in: moc) else { return nil } let group = CacheGroup(entity: entity, insertInto: moc) group.key = groupKey return group } static func cacheItem(with itemKey: String, variant: String?, in moc: NSManagedObjectContext) -> CacheItem? { let predicate: NSPredicate if let variant = variant { predicate = NSPredicate(format: "key == %@ && variant == %@", itemKey, variant) } else { predicate = NSPredicate(format: "key == %@", itemKey) } let fetchRequest: NSFetchRequest<CacheItem> = CacheItem.fetchRequest() fetchRequest.predicate = predicate fetchRequest.fetchLimit = 1 do { guard let item = try moc.fetch(fetchRequest).first else { return nil } return item } catch let error { fatalError(error.localizedDescription) } } static func createCacheItem(with url: URL, itemKey: String, variant: String?, in moc: NSManagedObjectContext) -> CacheItem? { guard let entity = NSEntityDescription.entity(forEntityName: "CacheItem", in: moc) else { return nil } let item = CacheItem(entity: entity, insertInto: moc) item.key = itemKey item.variant = variant item.url = url item.date = Date() return item } static func isCached(itemKey: CacheController.ItemKey, variant: String?, in moc: NSManagedObjectContext, completion: @escaping (Bool) -> Void) { return moc.perform { let isCached = CacheDBWriterHelper.cacheItem(with: itemKey, variant: variant, in: moc) != nil completion(isCached) } } static func allDownloadedVariantItems(itemKey: CacheController.ItemKey, in moc: NSManagedObjectContext) -> [CacheItem] { let fetchRequest: NSFetchRequest<CacheItem> = CacheItem.fetchRequest() fetchRequest.predicate = NSPredicate(format: "key == %@ && isDownloaded == YES", itemKey) do { return try moc.fetch(fetchRequest) } catch { return [] } } static func allVariantItems(itemKey: CacheController.ItemKey, in moc: NSManagedObjectContext) -> [CacheItem] { let fetchRequest: NSFetchRequest<CacheItem> = CacheItem.fetchRequest() fetchRequest.predicate = NSPredicate(format: "key == %@", itemKey) do { return try moc.fetch(fetchRequest) } catch { return [] } } static func save(moc: NSManagedObjectContext, completion: (_ result: SaveResult) -> Void) { guard moc.hasChanges else { completion(.success) return } do { try moc.save() completion(.success) } catch let error { assertionFailure("Error saving cache moc: \(error)") completion(.failure(error)) } } }
cbe3a20cead64c2e4bd70c783be5c4ce
36.614035
148
0.608675
false
false
false
false
colourful987/JustMakeGame-FlappyBird
refs/heads/master
Code/L03/FlappyBird-End/FlappyBird/GameScene.swift
mit
1
// // GameScene.swift // FlappyBird // // Created by pmst on 15/10/4. // Copyright (c) 2015年 pmst. All rights reserved. // import SpriteKit enum Layer: CGFloat { case Background case Foreground case Player } class GameScene: SKScene { // MARK: - 常量 let kGravity:CGFloat = -1500.0 let kImpulse:CGFloat = 400 let kGroundSpeed:CGFloat = 150.0 let worldNode = SKNode() var playableStart:CGFloat = 0 var playableHeight:CGFloat = 0 let player = SKSpriteNode(imageNamed: "Bird0") var lastUpdateTime :NSTimeInterval = 0 var dt:NSTimeInterval = 0 var playerVelocity = CGPoint.zero // MARK: - 变量 // MARK: - 音乐 let dingAction = SKAction.playSoundFileNamed("ding.wav", waitForCompletion: false) let flapAction = SKAction.playSoundFileNamed("flapping.wav", waitForCompletion: false) let whackAction = SKAction.playSoundFileNamed("whack.wav", waitForCompletion: false) let fallingAction = SKAction.playSoundFileNamed("falling.wav", waitForCompletion: false) let hitGroundAction = SKAction.playSoundFileNamed("hitGround.wav", waitForCompletion: false) let popAction = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false) let coinAction = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false) override func didMoveToView(view: SKView) { addChild(worldNode) setupBackground() setupForeground() setupPlayer() } // MARK: Setup Method func setupBackground(){ // 1 let background = SKSpriteNode(imageNamed: "Background") background.anchorPoint = CGPointMake(0.5, 1) background.position = CGPointMake(size.width/2.0, size.height) background.zPosition = Layer.Background.rawValue worldNode.addChild(background) // 2 playableStart = size.height - background.size.height playableHeight = background.size.height } func setupForeground() { for i in 0..<2{ let foreground = SKSpriteNode(imageNamed: "Ground") foreground.anchorPoint = CGPoint(x: 0, y: 1) // 改动1 foreground.position = CGPoint(x: CGFloat(i) * size.width, y: playableStart) foreground.zPosition = Layer.Foreground.rawValue // 改动2 foreground.name = "foreground" worldNode.addChild(foreground) } } func setupPlayer(){ player.position = CGPointMake(size.width * 0.2, playableHeight * 0.4 + playableStart) player.zPosition = Layer.Player.rawValue worldNode.addChild(player) } // MARK: - GamePlay func flapPlayer(){ // 发出一次煽动翅膀的声音 runAction(flapAction) // 重新设定player的速度!! playerVelocity = CGPointMake(0, kImpulse) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { flapPlayer() } // MARK: - Updates override func update(currentTime: CFTimeInterval) { if lastUpdateTime > 0{ dt = currentTime - lastUpdateTime }else{ dt = 0 } lastUpdateTime = currentTime updatePlayer() updateForeground() } func updatePlayer(){ // 只有Y轴上的重力加速度为-1500 let gravity = CGPoint(x: 0, y: kGravity) let gravityStep = gravity * CGFloat(dt) //计算dt时间下速度的增量 playerVelocity += gravityStep //计算当前速度 // 位置计算 let velocityStep = playerVelocity * CGFloat(dt) //计算dt时间中下落或上升距离 player.position += velocityStep //计算player的位置 // 倘若Player的Y坐标位置在地面上了就不能再下落了 直接设置其位置的y值为地面的表层坐标 if player.position.y - player.size.height/2 < playableStart { player.position = CGPoint(x: player.position.x, y: playableStart + player.size.height/2) } } func updateForeground(){ worldNode.enumerateChildNodesWithName("foreground") { (node, stop) -> Void in if let foreground = node as? SKSpriteNode{ let moveAmt = CGPointMake(-self.kGroundSpeed * CGFloat(self.dt), 0) foreground.position += moveAmt if foreground.position.x < -foreground.size.width{ foreground.position += CGPoint(x: foreground.size.width * CGFloat(2), y: 0) } } } } }
07b1752a2bd50d9b530430d3128cb503
28.163399
100
0.613402
false
false
false
false
renatoguarato/cidadaoalerta
refs/heads/master
apps/ios/cidadaoalerta/cidadaoalerta/DetalhesEmpenhoViewController.swift
gpl-3.0
1
// // DetalhesEmpenhoViewController.swift // cidadaoalerta // // Created by Renato Guarato on 26/03/16. // Copyright © 2016 Renato Guarato. All rights reserved. // import UIKit class DetalhesEmpenhoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var items = [DetalheTabela]() override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell") self.tableView.dataSource = self self.tableView.delegate = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 160.0 self.automaticallyAdjustsScrollViewInsets = false self.items = [DetalheTabela("Número Empenho", "2008NE800004"), DetalheTabela("Situação", "Registrado SIAFI"), DetalheTabela("Tipo de Nota", "Empenho Original"), DetalheTabela("Valor", "R$ 2.301.592,83")] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnVoltar(sender: UIBarButtonItem) { self.navigationController?.popViewControllerAnimated(true) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DetailViewCell let empenho = self.items[indexPath.row] cell.lblColunaDetalheEmpenho.text = empenho.coluna cell.lblValorDetalheEmpenho.text = empenho.valor return cell } }
b0b6240be5025ac6fd56c098bed443a1
30.59322
211
0.684013
false
false
false
false
apple/swift-format
refs/heads/main
Sources/generate-pipeline/PipelineGenerator.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation /// Generates the extensions to the lint and format pipelines. final class PipelineGenerator: FileGenerator { /// The rules collected by scanning the formatter source code. let ruleCollector: RuleCollector /// Creates a new pipeline generator. init(ruleCollector: RuleCollector) { self.ruleCollector = ruleCollector } func write(into handle: FileHandle) throws { handle.write( """ //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file is automatically generated with generate-pipeline. Do Not Edit! import SwiftFormatCore import SwiftFormatRules import SwiftSyntax /// A syntax visitor that delegates to individual rules for linting. /// /// This file will be extended with `visit` methods in Pipelines+Generated.swift. class LintPipeline: SyntaxVisitor { /// The formatter context. let context: Context /// Stores lint and format rule instances, indexed by the `ObjectIdentifier` of a rule's /// class type. var ruleCache = [ObjectIdentifier: Rule]() /// Creates a new lint pipeline. init(context: Context) { self.context = context super.init(viewMode: .sourceAccurate) } """ ) for (nodeType, lintRules) in ruleCollector.syntaxNodeLinters.sorted(by: { $0.key < $1.key }) { handle.write( """ override func visit(_ node: \(nodeType)) -> SyntaxVisitorContinueKind { """) for ruleName in lintRules.sorted() { handle.write( """ visitIfEnabled(\(ruleName).visit, for: node) """) } handle.write( """ return .visitChildren } """) } handle.write( """ } extension FormatPipeline { func visit(_ node: Syntax) -> Syntax { var node = node """ ) for ruleName in ruleCollector.allFormatters.map({ $0.typeName }).sorted() { handle.write( """ node = \(ruleName)(context: context).visit(node) """) } handle.write( """ return node } } """) } }
27eabae0830990b3de7fc4092fb8b4b6
26.283333
98
0.544288
false
false
false
false
openbuild-sheffield/jolt
refs/heads/master
Sources/RouteAuth/repository.UserLinkRole.swift
gpl-2.0
1
import OpenbuildMysql import OpenbuildRepository import OpenbuildSingleton public class RepositoryUserLinkRole: OpenbuildMysql.OBMySQL { public init() throws { guard let connectionDetails = OpenbuildSingleton.Manager.getConnectionDetails( module: "auth", name: "role", type: "mysql" )else{ throw RepoError.connection( messagePublic: "Connection details not found for RouteAuth:Auth", messageDev: "Connection details not found for RouteAuth:Auth auth:role:mysql" ) } try super.init( connectionParams: connectionDetails.connectionParams as! MySQLConnectionParams, database: connectionDetails.connectionDetails.db ) } public func install() throws -> Bool { let installed = try super.tableExists(table: "userLinkRole") if installed == false { print("installed: \(installed)") let installSQL = String(current: #file, path: "SQL/userLinkRole.sql") print("DOING CREATE TABLE:") print(installSQL!) let created = try super.tableCreate(statement: installSQL!) print("created: \(created)") let insertSQL = String(current: #file, path: "SQL/userLinkRoleInsert.sql") print("INSERT DATA:") print(insertSQL!) let results = insert( statement: insertSQL! ) print(results) } else { print("installed: \(installed)") } //TODO - upgrades return true } public func addRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{ let results = insert( statement: "INSERT INTO userLinkRole (user_id, role_id) VALUES (?, ?)", params: [user.user_id!, role.role_id!] ) if results.error == true { role.errors["insert"] = results.errorMessage } else if results.affectedRows! != 1 { role.errors["insert"] = "Failed to insert." } return role } public func deleteRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{ let results = insert( statement: "DELETE FROM userLinkRole WHERE user_id = ? AND role_id = ?", params: [user.user_id!, role.role_id!] ) if results.error == true { role.errors["delete"] = results.errorMessage } else if results.affectedRows! != 1 { role.errors["delete"] = "Failed to insert." } return role } }
ca03c40907b152795783be43a9bdd4a3
25.168317
95
0.569644
false
false
false
false
lieonCX/Live
refs/heads/master
Live/ViewModel/User/EarningsViewModel.swift
mit
1
// // EarningsViewModel.swift // Live // // Created by lieon on 2017/7/27. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import Foundation import PromiseKit class EarningsViewModel { var moneyReocod: [MoneyRecord]? var currentPage: Int = 0 var lastRequstCount: Int = 0 var pickUpInitial: PickupIntialModel? /// 哆豆提现 func requestApplyPickUp(with param: ApplyPickUpParam) -> Promise<NullDataResponse> { let req: Promise<NullDataResponse> = RequestManager.request(.endpoint(MoneyPath.applyPickUp, param: param)) return req } /// 哆豆提现初始化信息 func requestPicupInitialInfo() -> Promise<PickupInitialResponse> { let req: Promise<PickupInitialResponse> = RequestManager.request(Router.endpoint(MoneyPath.getPickupInfo, param: nil) ) return req } /// 提现充值记录 func requestMoneyRecord(with param: MoneyInoutRecordParam) -> Promise<MoneyRecordGroupResponse> { let req: Promise<MoneyRecordGroupResponse> = RequestManager.request(Router.endpoint(MoneyPath.getMoneyLogList, param: param) ) return req } }
5e6fe58e7d519000e2c5be297618ae9a
29.864865
132
0.696147
false
false
false
false
EugeneNaloiko/gmnav
refs/heads/master
Example/Pods/GooglePlacesAPI/Source/Google Places API/Types.swift
mit
4
// // Types.swift // GooglePlaces // // Created by Honghao Zhang on 2016-02-12. // Copyright © 2016 Honghao Zhang. All rights reserved. // import Foundation public extension GooglePlaces { public enum PlaceType: String { case geocode = "geocode" case address = "address" case establishment = "establishment" case regions = "(regions)" case cities = "(cities)" } }
a33edf6d647a12e6fc601805d4a2372f
21.421053
56
0.617371
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingStreamsViewController.swift
gpl-2.0
2
import Foundation import WordPressShared /// This class will simply render the collection of Streams available for a given NotificationSettings /// collection. /// A Stream represents a possible way in which notifications are communicated. /// For instance: Push Notifications / WordPress.com Timeline / Email /// class NotificationSettingStreamsViewController: UITableViewController { // MARK: - Private Properties /// NotificationSettings being rendered /// private var settings: NotificationSettings? /// Notification Streams /// private var sortedStreams: [NotificationSettings.Stream]? /// Indicates whether push notifications have been disabled, in the device, or not. /// private var pushNotificationsAuthorized = true { didSet { tableView.reloadData() } } /// TableViewCell's Reuse Identifier /// private let reuseIdentifier = WPTableViewCell.classNameWithoutNamespaces() /// Number of Sections /// private let emptySectionCount = 0 /// Number of Rows /// private let rowsCount = 1 convenience init(settings: NotificationSettings) { self.init(style: .grouped) setupWithSettings(settings) } deinit { stopListeningToNotifications() } override func viewDidLoad() { super.viewDidLoad() setupTableView() startListeningToNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRowWithAnimation(true) refreshPushAuthorizationStatus() WPAnalytics.track(.openedNotificationSettingStreams) } // MARK: - Setup Helpers private func startListeningToNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshPushAuthorizationStatus), name: .UIApplicationDidBecomeActive, object: nil) } private func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } private func setupTableView() { // Empty Back Button navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .plain, target: nil, action: nil) // Hide the separators, whenever the table is empty tableView.tableFooterView = UIView() // Style! WPStyleGuide.configureColors(for: view, andTableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) } // MARK: - Public Helpers func setupWithSettings(_ streamSettings: NotificationSettings) { // Title switch streamSettings.channel { case let .blog(blogId): _ = blogId title = streamSettings.blog?.settings?.name ?? streamSettings.channel.description() case .other: title = NSLocalizedString("Other Sites", comment: "Other Notifications Streams Title") default: // Note: WordPress.com is not expected here! break } // Structures settings = streamSettings sortedStreams = streamSettings.streams.sorted { $0.kind.description() > $1.kind.description() } tableView.reloadData() } // MARK: - UITableView Delegate Methods override func numberOfSections(in tableView: UITableView) -> Int { return sortedStreams?.count ?? emptySectionCount } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowsCount } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? WPTableViewCell if cell == nil { cell = WPTableViewCell(style: .value1, reuseIdentifier: reuseIdentifier) } configureCell(cell!, indexPath: indexPath) return cell! } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return footerForStream(streamAtSection(section)) } override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionFooter(view) } // MARK: - UITableView Delegate Methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let stream = streamAtSection(indexPath.section) let detailsViewController = NotificationSettingDetailsViewController(settings: settings!, stream: stream) navigationController?.pushViewController(detailsViewController, animated: true) } // MARK: - Helpers private func configureCell(_ cell: UITableViewCell, indexPath: IndexPath) { let stream = streamAtSection(indexPath.section) let disabled = stream.kind == .Device && pushNotificationsAuthorized == false cell.imageView?.image = imageForStreamKind(stream.kind) cell.imageView?.tintColor = WPStyleGuide.greyLighten10() cell.textLabel?.text = stream.kind.description() cell.detailTextLabel?.text = disabled ? NSLocalizedString("Off", comment: "Disabled") : String() cell.accessoryType = .disclosureIndicator WPStyleGuide.configureTableViewCell(cell) } private func streamAtSection(_ section: Int) -> NotificationSettings.Stream { return sortedStreams![section] } private func imageForStreamKind(_ streamKind: NotificationSettings.Stream.Kind) -> UIImage? { let imageName: String switch streamKind { case .Email: imageName = "notifications-email" case .Timeline: imageName = "notifications-bell" case .Device: imageName = "notifications-phone" } return UIImage(named: imageName)?.withRenderingMode(.alwaysTemplate) } // MARK: - Disabled Push Notifications Helpers func refreshPushAuthorizationStatus() { PushNotificationsManager.shared.loadAuthorizationStatus { authorized in self.pushNotificationsAuthorized = authorized } } private func displayPushNotificationsAlert() { let title = NSLocalizedString("Push Notifications have been turned off in iOS Settings", comment: "Displayed when Push Notifications are disabled (iOS 7)") let message = NSLocalizedString("To enable notifications:\n\n" + "1. Open **iOS Settings**\n" + "2. Tap **Notifications**\n" + "3. Select **WordPress**\n" + "4. Turn on **Allow Notifications**", comment: "Displayed when Push Notifications are disabled (iOS 7)") let button = NSLocalizedString("Dismiss", comment: "Dismiss the AlertView") let alert = AlertView(title: title, message: message, button: button, completion: nil) alert.show() } // MARK: - Footers private func footerForStream(_ stream: NotificationSettings.Stream) -> String { switch stream.kind { case .Device: return NSLocalizedString("Settings for push notifications that appear on your mobile device.", comment: "Descriptive text for the Push Notifications Settings") case .Email: return NSLocalizedString("Settings for notifications that are sent to the email tied to your account.", comment: "Descriptive text for the Email Notifications Settings") case .Timeline: return NSLocalizedString("Settings for notifications that appear in the Notifications tab.", comment: "Descriptive text for the Notifications Tab Settings") } } }
9dcfb9c6868ee183cca80058b4b12fb5
34.751111
147
0.655644
false
false
false
false
QuaereVeritatem/TopHackIncStartup
refs/heads/master
TopHackIncStartUp/EventData.swift
mit
1
// // EventData.swift // TopHackIncStartUp // // Created by Robert Martin on 10/8/16. // Copyright © 2016 Robert Martin. All rights reserved. // import Foundation class EventData{ static let sharedInstance = EventData() struct hackIncEvent: JSONSerializable { var name: String //program name var progUrl: String? //website...should be an optional var progType: ProgTypes? //should be an optional var areaLoc: AreaLoc? //location should be optional var logo: String? //should be an optional in case no logo added var dateOrTimeFrame: TimeFrame? //should be optional } enum ProgTypes: String, JSONSerializable { case accelerator = "accelerator" case hackathon = "hackathon" case bootcamp = "bootcamp" case incubator = "incubator" case startUpPitch = "startUpPitch" case networking = "networking" } enum AreaLoc: String, JSONSerializable { case Worldwide = "Worldwide" case Dallas = "Dallas" case Nationwide = "Nationwide" case Austin = "Austin" case Mountainview = "Mountainview" case SanFran_NYC = "SanFran_NYC" case NYC = "NYC" } enum TimeFrame: String, JSONSerializable { case yearly = "yearly" case monthly = "monthly" case weekly = "weekly" case January = "January" case February = "February" case March = "March" case April = "April" case May = "May" case June = "June" case July = "July" case August = "August" case September = "September" case October = "October" case November = "November" case December = "December" } var progTypesArray: [String] = ["accelerator", "hackathon", "bootcamp", "incubator", "startUpPitch", "networking"] var areaLocArray: [String] = ["Worldwide", "Dallas", "Nationwide", "Austin", "Mountainview", "SanFran_NYC", "NYC"] var timeFrameArray: [String] = ["Yearly", "Monthly", "Weekly", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] var testEvent: hackIncEvent = hackIncEvent(name: "", progUrl: "", progType: ProgTypes.hackathon, areaLoc: AreaLoc.Worldwide, logo: "", dateOrTimeFrame: TimeFrame.monthly) var besthackIncEvent = [ hackIncEvent(name: "AngelHack", progUrl: "http://angelhack.com", progType: ProgTypes.hackathon, areaLoc: AreaLoc.Worldwide, logo: "angelHack", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "StartUpWeekend", progUrl: "https://StartUpWeekend.org", progType: ProgTypes.hackathon, areaLoc: AreaLoc.Worldwide, logo: "startUpWeekend", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "TechStars", progUrl: "http://techStars.com", progType: ProgTypes.accelerator, areaLoc: AreaLoc.Worldwide, logo: "techStars", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "TechWildCatters", progUrl: "http://techwildcatters.com", progType: ProgTypes.accelerator, areaLoc: AreaLoc.Dallas, logo: "techWildcatters", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "HealthWildcatters", progUrl: "http://healthwildcatters.com", progType: ProgTypes.accelerator, areaLoc: AreaLoc.Dallas, logo: "healthWildcatters1", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "AngelPad", progUrl: "https://angelpad.org", progType: ProgTypes.accelerator, areaLoc: AreaLoc.SanFran_NYC, logo: "angelPad", dateOrTimeFrame: TimeFrame.yearly), hackIncEvent(name: "IronYard", progUrl: "https://theironYard.com", progType: ProgTypes.bootcamp, areaLoc: AreaLoc.Nationwide, logo: "ironYard", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "Capital Factory", progUrl: "https://capitalfactory.com", progType: ProgTypes.accelerator, areaLoc: AreaLoc.Austin, logo: "capitalFactory", dateOrTimeFrame: TimeFrame.monthly), hackIncEvent(name: "Y Combinator", progUrl: "https://ycombinator.com", progType: ProgTypes.accelerator, areaLoc: AreaLoc.Mountainview, logo: "yCombinator", dateOrTimeFrame: TimeFrame.yearly), hackIncEvent(name: "DevPost", progUrl: "https://devpost.com", progType: ProgTypes.hackathon, areaLoc: AreaLoc.Worldwide, logo: "DevPostLogo", dateOrTimeFrame: TimeFrame.weekly), hackIncEvent(name: "Guild of Software Architects", progUrl: "https://guildsa.org", progType: ProgTypes.bootcamp, areaLoc: AreaLoc.Dallas, logo: "GSA", dateOrTimeFrame: TimeFrame.yearly) ] }
ae324c9742f59fa97e9347aedd93768f
47.744444
207
0.712788
false
false
false
false
kalanyuz/SwiftR
refs/heads/master
CommonSource/common/CountView.swift
apache-2.0
1
// // HalfCircleMeterView.swift // NativeSigP // // Created by Kalanyu Zintus-art on 10/5/15. // Copyright © 2017 KalanyuZ. All rights reserved. // #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } @IBDesignable open class CountView: SRView { open var titleField : SRLabel? open var countField : SRLabel? open var title : String = "" { didSet { #if os(macOS) self.titleField?.stringValue = self.title #elseif os(iOS) self.titleField?.text = self.title #endif } } open var directionValue : Int? { get { return NumberFormatter().number(from: self.countText)?.intValue } set { if let countNumber = NumberFormatter().string(from: NSNumber(value: newValue! as Int)) { if newValue > 0 { self.countText = "+\(countNumber)" } else if newValue <= 0 { self.countText = countNumber } } else { self.countText = "0" } } } open var countText : String = "0" { didSet { //already has layout constraints, no need for frame adjustment //TODO:size adjustments for readability #if os(macOS) countField?.stringValue = self.countText #elseif os(iOS) countField?.text = self.countText #endif } } required public init?(coder: NSCoder) { super.init(coder: coder) titleField = SRLabel(frame: CGRect.zero) countField = SRLabel(frame: CGRect.zero) titleField?.textColor = SRColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1) countField?.textColor = SRColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1) self.addSubview(titleField!) self.addSubview(countField!) self.titleField?.font = SRFont.boldSystemFont(ofSize: 20) self.countField?.font = SRFont.systemFont(ofSize: 100) self.countField?.translatesAutoresizingMaskIntoConstraints = false var countFieldConstraint = NSLayoutConstraint(item: self.countField!, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) self.addConstraint(countFieldConstraint) countFieldConstraint = NSLayoutConstraint(item: self.countField!, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) self.addConstraint(countFieldConstraint) self.titleField?.translatesAutoresizingMaskIntoConstraints = false let titleFieldConstraint = NSLayoutConstraint(item: self.titleField!, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) self.addConstraint(titleFieldConstraint) #if os(macOS) countField?.stringValue = "0" titleField?.stringValue = "Title" self.wantsLayer = true #elseif os(macOS) countField?.text = "0" titleField?.text = "Title" #endif } #if os(macOS) override open func layout() { super.layout() countField?.font = SRFont.boldSystemFont(ofSize: resizeFontWithString(countField!.stringValue)) } #endif fileprivate func resizeFontWithString(_ title: String) -> CGFloat { // defer { // Swift.print(textSize, self.bounds, displaySize) // } let smallestSize : CGFloat = 100 let largestSize : CGFloat = 200 var textSize = CGSize.zero var displaySize = smallestSize while displaySize < largestSize { let nsTitle = NSString(string: title) let attributes = [NSFontAttributeName: SRFont.boldSystemFont(ofSize: displaySize)] #if os(macOS) textSize = nsTitle.size(withAttributes: attributes) #elseif os(iOS) textSize = nsTitle.size(attributes: attributes) #endif if textSize.width < self.bounds.width * 0.8 { displaySize += 1 } else { return displaySize } } return largestSize } }
5836d7c0d885f604310d4c2428b9f186
29.494048
180
0.628148
false
false
false
false
ben-ng/swift
refs/heads/master
test/stdlib/TestCalendar.swift
apache-2.0
1
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g // RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestCalendar // RUN: %target-run %t/TestCalendar > %t.txt // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import FoundationBridgeObjC #if FOUNDATION_XCTEST import XCTest class TestCalendarSuper : XCTestCase { } #else import StdlibUnittest class TestCalendarSuper { } #endif class TestCalendar : TestCalendarSuper { func test_copyOnWrite() { var c = Calendar(identifier: .gregorian) let c2 = c expectEqual(c, c2) // Change the weekday and check result let firstWeekday = c.firstWeekday let newFirstWeekday = firstWeekday < 7 ? firstWeekday + 1 : firstWeekday - 1 c.firstWeekday = newFirstWeekday expectEqual(newFirstWeekday, c.firstWeekday) expectEqual(c2.firstWeekday, firstWeekday) expectNotEqual(c, c2) // Change the time zone and check result let c3 = c expectEqual(c, c3) let tz = c.timeZone // Use two different identifiers so we don't fail if the current time zone happens to be the one returned let aTimeZoneId = TimeZone.knownTimeZoneIdentifiers[1] let anotherTimeZoneId = TimeZone.knownTimeZoneIdentifiers[0] let newTz = tz.identifier == aTimeZoneId ? TimeZone(identifier: anotherTimeZoneId)! : TimeZone(identifier: aTimeZoneId)! c.timeZone = newTz expectNotEqual(c, c3) } func test_bridgingAutoupdating() { let tester = CalendarBridgingTester() do { let c = Calendar.autoupdatingCurrent let result = tester.verifyAutoupdating(c) expectTrue(result) } // Round trip an autoupdating calendar do { let c = tester.autoupdatingCurrentCalendar() let result = tester.verifyAutoupdating(c) expectTrue(result) } } func test_equality() { let autoupdating = Calendar.autoupdatingCurrent let autoupdating2 = Calendar.autoupdatingCurrent expectEqual(autoupdating, autoupdating2) let current = Calendar.current expectNotEqual(autoupdating, current) // Make a copy of current var current2 = current expectEqual(current, current2) // Mutate something (making sure we don't use the current time zone) if current2.timeZone.identifier == "America/Los_Angeles" { current2.timeZone = TimeZone(identifier: "America/New_York")! } else { current2.timeZone = TimeZone(identifier: "America/Los_Angeles")! } expectNotEqual(current, current2) // Mutate something else current2 = current expectEqual(current, current2) current2.locale = Locale(identifier: "MyMadeUpLocale") expectNotEqual(current, current2) } func test_properties() { // Mainly we want to just make sure these go through to the NSCalendar implementation at this point. if #available(iOS 8.0, OSX 10.7, *) { var c = Calendar(identifier: .gregorian) // Use english localization c.locale = Locale(identifier: "en_US") c.timeZone = TimeZone(identifier: "America/Los_Angeles")! expectEqual("AM", c.amSymbol) expectEqual("PM", c.pmSymbol) expectEqual(["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"], c.quarterSymbols) expectEqual(["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"], c.standaloneQuarterSymbols) expectEqual(["BC", "AD"], c.eraSymbols) expectEqual(["Before Christ", "Anno Domini"], c.longEraSymbols) expectEqual(["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], c.veryShortMonthSymbols) expectEqual(["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], c.veryShortStandaloneMonthSymbols) expectEqual(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], c.shortMonthSymbols) expectEqual(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], c.shortStandaloneMonthSymbols) expectEqual(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], c.monthSymbols) expectEqual(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], c.standaloneMonthSymbols) expectEqual(["Q1", "Q2", "Q3", "Q4"], c.shortQuarterSymbols) expectEqual(["Q1", "Q2", "Q3", "Q4"], c.shortStandaloneQuarterSymbols) expectEqual(["S", "M", "T", "W", "T", "F", "S"], c.veryShortStandaloneWeekdaySymbols) expectEqual(["S", "M", "T", "W", "T", "F", "S"], c.veryShortWeekdaySymbols) expectEqual(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], c.shortStandaloneWeekdaySymbols) expectEqual(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], c.shortWeekdaySymbols) expectEqual(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], c.standaloneWeekdaySymbols) expectEqual(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], c.weekdaySymbols) // The idea behind these tests is not to test calendrical math, but to simply verify that we are getting some kind of result from calling through to the underlying Foundation and ICU logic. If we move that logic into this struct in the future, then we will need to expand the test cases. // This is a very special Date in my life: the exact moment when I wrote these test cases and therefore knew all of the answers. let d = Date(timeIntervalSince1970: 1468705593.2533731) let earlierD = c.date(byAdding: DateComponents(day: -10), to: d)! expectEqual(1..<29, c.minimumRange(of: .day)) expectEqual(1..<54, c.maximumRange(of: .weekOfYear)) expectEqual(0..<60, c.range(of: .second, in: .minute, for: d)) var d1 = Date() var ti : TimeInterval = 0 expectTrue(c.dateInterval(of: .day, start: &d1, interval: &ti, for: d)) expectEqual(Date(timeIntervalSince1970: 1468652400.0), d1) expectEqual(86400, ti) if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let dateInterval = c.dateInterval(of: .day, for: d) expectEqual(DateInterval(start: d1, duration: ti), dateInterval) } expectEqual(15, c.ordinality(of: .hour, in: .day, for: d)) expectEqual(Date(timeIntervalSince1970: 1468791993.2533731), c.date(byAdding: .day, value: 1, to: d)) expectEqual(Date(timeIntervalSince1970: 1468791993.2533731), c.date(byAdding: DateComponents(day: 1), to: d)) expectEqual(Date(timeIntervalSince1970: 946627200.0), c.date(from: DateComponents(year: 1999, month: 12, day: 31))) let comps = c.dateComponents([.year, .month, .day], from: Date(timeIntervalSince1970: 946627200.0)) expectEqual(1999, comps.year) expectEqual(12, comps.month) expectEqual(31, comps.day) expectEqual(10, c.dateComponents([.day], from: d, to: c.date(byAdding: DateComponents(day: 10), to: d)!).day) expectEqual(30, c.dateComponents([.day], from: DateComponents(year: 1999, month: 12, day: 1), to: DateComponents(year: 1999, month: 12, day: 31)).day) expectEqual(2016, c.component(.year, from: d)) expectEqual(Date(timeIntervalSince1970: 1468652400.0), c.startOfDay(for: d)) expectEqual(.orderedSame, c.compare(d, to: d + 10, toGranularity: .minute)) expectFalse(c.isDate(d, equalTo: d + 10, toGranularity: .second)) expectTrue(c.isDate(d, equalTo: d + 10, toGranularity: .day)) expectFalse(c.isDate(earlierD, inSameDayAs: d)) expectTrue(c.isDate(d, inSameDayAs: d)) expectFalse(c.isDateInToday(earlierD)) expectFalse(c.isDateInYesterday(earlierD)) expectFalse(c.isDateInTomorrow(earlierD)) expectTrue(c.isDateInWeekend(d)) // 😢 expectTrue(c.dateIntervalOfWeekend(containing: d, start: &d1, interval: &ti)) if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let thisWeekend = DateInterval(start: Date(timeIntervalSince1970: 1468652400.0), duration: 172800.0) expectEqual(thisWeekend, DateInterval(start: d1, duration: ti)) expectEqual(thisWeekend, c.dateIntervalOfWeekend(containing: d)) } expectTrue(c.nextWeekend(startingAfter: d, start: &d1, interval: &ti)) if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let nextWeekend = DateInterval(start: Date(timeIntervalSince1970: 1469257200.0), duration: 172800.0) expectEqual(nextWeekend, DateInterval(start: d1, duration: ti)) expectEqual(nextWeekend, c.nextWeekend(startingAfter: d)) } // Enumeration var count = 0 var exactCount = 0 // Find the days numbered '31' after 'd', allowing the algorithm to move to the next day if required c.enumerateDates(startingAfter: d, matching: DateComponents(day: 31), matchingPolicy: .nextTime) { result, exact, stop in // Just stop some arbitrary time in the future if result! > d + 86400*365 { stop = true } count += 1 if exact { exactCount += 1 } } /* Optional(2016-07-31 07:00:00 +0000) Optional(2016-08-31 07:00:00 +0000) Optional(2016-10-01 07:00:00 +0000) Optional(2016-10-31 07:00:00 +0000) Optional(2016-12-01 08:00:00 +0000) Optional(2016-12-31 08:00:00 +0000) Optional(2017-01-31 08:00:00 +0000) Optional(2017-03-01 08:00:00 +0000) Optional(2017-03-31 07:00:00 +0000) Optional(2017-05-01 07:00:00 +0000) Optional(2017-05-31 07:00:00 +0000) Optional(2017-07-01 07:00:00 +0000) Optional(2017-07-31 07:00:00 +0000) */ expectEqual(count, 13) expectEqual(exactCount, 8) expectEqual(Date(timeIntervalSince1970: 1469948400.0), c.nextDate(after: d, matching: DateComponents(day: 31), matchingPolicy: .nextTime)) expectEqual(Date(timeIntervalSince1970: 1468742400.0), c.date(bySetting: .hour, value: 1, of: d)) expectEqual(Date(timeIntervalSince1970: 1468656123.0), c.date(bySettingHour: 1, minute: 2, second: 3, of: d, matchingPolicy: .nextTime)) expectTrue(c.date(d, matchesComponents: DateComponents(month: 7))) expectFalse(c.date(d, matchesComponents: DateComponents(month: 7, day: 31))) } } func test_AnyHashableContainingCalendar() { let values: [Calendar] = [ Calendar(identifier: .gregorian), Calendar(identifier: .japanese), Calendar(identifier: .japanese) ] let anyHashables = values.map(AnyHashable.init) expectEqual(Calendar.self, type(of: anyHashables[0].base)) expectEqual(Calendar.self, type(of: anyHashables[1].base)) expectEqual(Calendar.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSCalendar() { if #available(iOS 8.0, *) { let values: [NSCalendar] = [ NSCalendar(identifier: .gregorian)!, NSCalendar(identifier: .japanese)!, NSCalendar(identifier: .japanese)!, ] let anyHashables = values.map(AnyHashable.init) expectEqual(Calendar.self, type(of: anyHashables[0].base)) expectEqual(Calendar.self, type(of: anyHashables[1].base)) expectEqual(Calendar.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } } #if !FOUNDATION_XCTEST var CalendarTests = TestSuite("TestCalendar") CalendarTests.test("test_copyOnWrite") { TestCalendar().test_copyOnWrite() } CalendarTests.test("test_bridgingAutoupdating") { TestCalendar().test_bridgingAutoupdating() } CalendarTests.test("test_equality") { TestCalendar().test_equality() } CalendarTests.test("test_properties") { TestCalendar().test_properties() } CalendarTests.test("test_AnyHashableContainingCalendar") { TestCalendar().test_AnyHashableContainingCalendar() } CalendarTests.test("test_AnyHashableCreatedFromNSCalendar") { TestCalendar().test_AnyHashableCreatedFromNSCalendar() } runAllTests() #endif
daabcd49a90c51d52dfce4107265ca13
46.555184
299
0.593572
false
true
false
false
Harekaze/Harekaze-iOS
refs/heads/master
Harekaze/Models/Channel.swift
bsd-3-clause
1
/** * * Channel.swift * Harekaze * Created by Yuki MIZUNO on 2016/07/10. * * Copyright (c) 2016-2018, Yuki MIZUNO * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ import RealmSwift import ObjectMapper class Channel: Object, Mappable { // MARK: - Managed instance fileds @objc dynamic var channel: Int = 0 @objc dynamic var id: String = "" @objc dynamic var name: String = "" @objc dynamic var number: Int = 0 @objc dynamic var sid: Int = 0 @objc dynamic var type: String = "" // MARK: - Primary key definition override static func primaryKey() -> String? { return "id" } // MARK: - Class initialization required convenience init?(map: Map) { self.init() mapping(map: map) } // MARK: - JSON value mapping func mapping(map: Map) { channel <- (map["channel"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) id <- map["id"] name <- map["name"] number <- map["n"] sid <- map["sid"] type <- map["type"] } }
c1f8a31a28b4574d72b305dbddc20553
34.542857
114
0.715032
false
false
false
false
josherick/DailySpend
refs/heads/master
DailySpend/DayReviewViewController.swift
mit
1
// // DayReviewViewController.swift // DailySpend // // Created by Josh Sherick on 10/22/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import UIKit import CoreData class DayReviewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let appDelegate = (UIApplication.shared.delegate as! AppDelegate) var context: NSManagedObjectContext { return appDelegate.persistentContainer.viewContext } var adjustments: [(desc: String, amount: String)]! var expenses: [(desc: String, amount: String)]! var formattedPause: (desc: String, range: String)? var reviewCell: ReviewTableViewCell! var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() adjustments = day.sortedAdjustments?.map { adj in let formattedAmount = String.formatAsCurrency(amount: adj.amountPerDay!)! return (desc: adj.shortDescription!, amount: formattedAmount) } ?? [] expenses = day.sortedExpenses?.map { exp in let formattedAmount = String.formatAsCurrency(amount: exp.amount!)! return (desc: exp.shortDescription!, amount: formattedAmount) } ?? [] if let pause = day.pause { formattedPause = (desc: pause.shortDescription!, range: pause.humanReadableRange()) } reviewCell = ReviewTableViewCell(style: .default, reuseIdentifier: nil) var reviewCellData = [ReviewCellDatum]() let yesterday = Day.get(context: context, calDay: day.calendarDay!.subtract(days: 1)) let carriedFromYesterday = yesterday?.leftToCarry() ?? 0 let formattedYesterdayCarry = String.formatAsCurrency(amount: carriedFromYesterday)! reviewCellData.append(ReviewCellDatum(description: "Yesterday's Balance", value: formattedYesterdayCarry, color: carriedFromYesterday < 0 ? .overspent : .black, sign: .None)) if !adjustments.isEmpty { let totalAdjustments = day.totalAdjustments() let formattedAdjustments = String.formatAsCurrency(amount: totalAdjustments)! reviewCellData.append(ReviewCellDatum(description: "Adjustments", value: formattedAdjustments, color: .black, sign: totalAdjustments < 0 ? .Minus : .Plus)) } if !expenses.isEmpty { let totalExpenses = day.totalExpenses() let formattedExpenses = String.formatAsCurrency(amount: totalExpenses)! reviewCellData.append(ReviewCellDatum(description: "Expenses", value: formattedExpenses, color: .black, sign: totalExpenses < 0 ? .Minus : .Plus)) } // day.leftToCarry() takes into account pauses, but it'll have to // recalculate yesterday's carry, which we already have, so just use // that. let leftToCarry = day.pause == nil ? day.leftToCarry() : carriedFromYesterday let formattedCarry = String.formatAsCurrency(amount: leftToCarry)! reviewCellData.append(ReviewCellDatum(description: "Today's Balance", value: formattedCarry, color: leftToCarry < 0 ? .overspent : .black, sign: .None)) if day.pause != nil { reviewCell.showPausedNote(true) } reviewCell.setLabelData(reviewCellData) tableView = UITableView(frame: view.bounds, style: .grouped) tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } enum DayReviewCellType { case ReviewCell case PauseCell case AdjustmentCell case ExpenseCell } func cellTypeForSection(_ section: Int) -> DayReviewCellType { if section == 1 { if day.pause != nil { return .PauseCell } else if !adjustments.isEmpty { return .AdjustmentCell } else { return .ExpenseCell } } if section == 2 { if !adjustments.isEmpty { return .AdjustmentCell } else { return .ExpenseCell } } if section == 3 { return .ExpenseCell } return .ReviewCell } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "value") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "value") } cell.detailTextLabel?.textColor = UIColor.black switch cellTypeForSection(indexPath.section) { case .ReviewCell: return reviewCell case .PauseCell: cell.textLabel!.text = formattedPause!.desc cell.detailTextLabel!.text = formattedPause!.range case .AdjustmentCell: cell.textLabel!.text = adjustments[indexPath.row].desc cell.detailTextLabel!.text = adjustments[indexPath.row].amount case .ExpenseCell: cell.textLabel!.text = expenses[indexPath.row].desc cell.detailTextLabel!.text = expenses[indexPath.row].amount } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch cellTypeForSection(section) { case .PauseCell: return "Pause" case .AdjustmentCell: return "Adjustments" case .ExpenseCell: return "Expenses" case .ReviewCell: return nil } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch cellTypeForSection(indexPath.section) { case .ReviewCell: return reviewCell.desiredHeightForCurrentState() default: return 44 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch cellTypeForSection(section) { case .PauseCell: return 1 case .AdjustmentCell: return adjustments.count case .ExpenseCell: return expenses.count case .ReviewCell: return 1 } } func numberOfSections(in tableView: UITableView) -> Int { return 1 + (day.pause == nil ? 0 : 1) + (adjustments.isEmpty ? 0 : 1) + (expenses.isEmpty ? 0 : 1) } }
7eecefa05206c9e079b40849d8b2a9ac
36.121212
100
0.565578
false
false
false
false
tlax/looper
refs/heads/master
looper/View/Camera/Crop/VCameraCropImage.swift
mit
1
import UIKit class VCameraCropImage:UIView { let imageSize:CGFloat var imageRatio:CGFloat weak var thumbTopLeft:VCameraCropImageThumb! weak var thumbTopRight:VCameraCropImageThumb! weak var thumbBottomLeft:VCameraCropImageThumb! weak var thumbBottomRight:VCameraCropImageThumb! private weak var controller:CCameraCrop! private weak var imageView:UIImageView! private weak var background:VBorder! private weak var label:UILabel! private weak var layoutImageBottom:NSLayoutConstraint! private weak var layoutImageLeft:NSLayoutConstraint! private weak var layoutImageRight:NSLayoutConstraint! private weak var viewMover:VCameraCropImageMover! private weak var draggingThumb:VCameraCropImageThumb? private weak var draggingMover:VCameraCropImageMover? private let attributes:[String:AnyObject] private let stringTimes:NSAttributedString private var minDistance:CGFloat private var hadLayout:Bool private var shadesCreated:Bool private let kTimes:String = " x " private let thumbSize_2:CGFloat private let kTopMargin:CGFloat = 60 private let kMinMargin:CGFloat = 40 private let kThumbSize:CGFloat = 48 private let kBackgroundMargin:CGFloat = -3 private let kLabelHeight:CGFloat = 70 init(controller:CCameraCrop) { hadLayout = false shadesCreated = false imageRatio = 0 minDistance = 0 thumbSize_2 = kThumbSize / 2.0 if let imageSize:CGFloat = controller.record.items.first?.image.size.width { self.imageSize = imageSize } else { self.imageSize = 0 } let attributesTimes:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:16), NSForegroundColorAttributeName:UIColor.black] attributes = [ NSFontAttributeName:UIFont.bold(size:28), NSForegroundColorAttributeName:UIColor.genericLight] stringTimes = NSAttributedString( string:kTimes, attributes:attributesTimes) super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let background:VBorder = VBorder(color:UIColor.black) self.background = background let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.image = controller.record.items.first?.image self.imageView = imageView let thumbTopLeft:VCameraCropImageThumb = VCameraCropImageThumb.topLeft() self.thumbTopLeft = thumbTopLeft let thumbTopRight:VCameraCropImageThumb = VCameraCropImageThumb.topRight() self.thumbTopRight = thumbTopRight let thumbBottomLeft:VCameraCropImageThumb = VCameraCropImageThumb.bottomLeft() self.thumbBottomLeft = thumbBottomLeft let thumbBottomRight:VCameraCropImageThumb = VCameraCropImageThumb.bottomRight() self.thumbBottomRight = thumbBottomRight let viewMover:VCameraCropImageMover = VCameraCropImageMover() self.viewMover = viewMover let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.center self.label = label addSubview(label) addSubview(background) addSubview(imageView) addSubview(viewMover) addSubview(thumbTopLeft) addSubview(thumbTopRight) addSubview(thumbBottomLeft) addSubview(thumbBottomRight) thumbTopLeft.initConstraints(size:kThumbSize) thumbTopRight.initConstraints(size:kThumbSize) thumbBottomLeft.initConstraints(size:kThumbSize) thumbBottomRight.initConstraints(size:kThumbSize) NSLayoutConstraint.equals( view:background, toView:imageView, margin:kBackgroundMargin) NSLayoutConstraint.topToTop( view:imageView, toView:self, constant:kTopMargin) layoutImageBottom = NSLayoutConstraint.bottomToBottom( view:imageView, toView:self) layoutImageLeft = NSLayoutConstraint.leftToLeft( view:imageView, toView:self) layoutImageRight = NSLayoutConstraint.rightToRight( view:imageView, toView:self) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.bottomToBottom( view:label, toView:self) NSLayoutConstraint.equalsHorizontal( view:label, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { if !hadLayout { let width:CGFloat = bounds.maxX if width > 0 { hadLayout = true let height:CGFloat = bounds.maxY let width_margin:CGFloat = width - kMinMargin let width_margin2:CGFloat = width_margin - kMinMargin let imageMaxY:CGFloat = width_margin2 + kTopMargin let marginBottom:CGFloat = height - imageMaxY imageRatio = width_margin2 / imageSize minDistance = ceil(imageRatio * MCamera.kImageMinSize) layoutImageLeft.constant = kMinMargin layoutImageRight.constant = -kMinMargin layoutImageBottom.constant = -marginBottom thumbTopLeft.position( positionX:kMinMargin, positionY:kTopMargin) thumbTopRight.position( positionX:width_margin, positionY:kTopMargin) thumbBottomLeft.position( positionX:kMinMargin, positionY:imageMaxY) thumbBottomRight.position( positionX:width_margin, positionY:imageMaxY) } } super.layoutSubviews() } override func touchesBegan(_ touches:Set<UITouch>, with event:UIEvent?) { if draggingThumb == nil { guard let touch:UITouch = touches.first else { return } if let draggingMover:VCameraCropImageMover = touch.view as? VCameraCropImageMover { self.draggingMover = draggingMover let point:CGPoint = touch.location(in:self) let pointX:CGFloat = point.x let pointY:CGFloat = point.y let posTop:CGFloat = thumbTopLeft.positionY let posBottom:CGFloat = thumbBottomLeft.positionY let posLeft:CGFloat = thumbTopLeft.positionX let posRight:CGFloat = thumbTopRight.positionX let deltaTop:CGFloat = pointY - posTop let deltaBottom:CGFloat = posBottom - pointY let deltaLeft:CGFloat = pointX - posLeft let deltaRight:CGFloat = posRight - pointX draggingMover.start( deltaTop:deltaTop, deltaBottom:deltaBottom, deltaLeft:deltaLeft, deltaRight:deltaRight) } else if let draggingThumb:VCameraCropImageThumb = touch.view as? VCameraCropImageThumb { bringSubview(toFront:draggingThumb) draggingThumb.state(selected:true) self.draggingThumb = draggingThumb } } } override func touchesMoved(_ touches:Set<UITouch>, with event:UIEvent?) { guard let touch:UITouch = touches.first else { return } let point:CGPoint = touch.location(in:self) if let _:VCameraCropImageMover = self.draggingMover { movingMover(point:point) } else if let draggingThumb:VCameraCropImageThumb = self.draggingThumb { switch draggingThumb.location { case VCameraCropImageThumb.Location.topLeft: movingTopLeft(point:point) break case VCameraCropImageThumb.Location.topRight: movingTopRight(point:point) break case VCameraCropImageThumb.Location.bottomLeft: movingBottomLeft(point:point) break case VCameraCropImageThumb.Location.bottomRight: movingBottomRight(point:point) break } print() } } override func touchesCancelled(_ touches:Set<UITouch>, with event:UIEvent?) { draggingEnded() } override func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?) { draggingEnded() } //MARK: private private func draggingEnded() { viewMover.clear() draggingThumb?.state(selected:false) draggingThumb = nil draggingMover = nil } private func movingMover(point:CGPoint) { guard let deltaTop:CGFloat = viewMover.deltaTop, let deltaBottom:CGFloat = viewMover.deltaBottom, let deltaLeft:CGFloat = viewMover.deltaLeft, let deltaRight:CGFloat = viewMover.deltaRight else { return } let newPointX:CGFloat = point.x let newPointY:CGFloat = point.y let minTop:CGFloat = thumbTopLeft.originalY let maxBottom:CGFloat = thumbBottomLeft.originalY let minLeft:CGFloat = thumbTopLeft.originalX let maxRight:CGFloat = thumbTopRight.originalX var newTop:CGFloat = newPointY - deltaTop var newBottom:CGFloat = newPointY + deltaBottom var newLeft:CGFloat = newPointX - deltaLeft var newRight:CGFloat = newPointX + deltaRight if newTop < minTop { let delta:CGFloat = minTop - newTop newTop = minTop newBottom += delta } else if newBottom > maxBottom { let delta:CGFloat = newBottom - maxBottom newBottom = maxBottom newTop -= delta } if newLeft < minLeft { let delta:CGFloat = minLeft - newLeft newLeft = minLeft newRight += delta } else if newRight > maxRight { let delta:CGFloat = newRight - maxRight newRight = maxRight newLeft -= delta } thumbTopLeft.position( positionX:newLeft, positionY:newTop) thumbTopRight.position( positionX:newRight, positionY:newTop) thumbBottomLeft.position( positionX:newLeft, positionY:newBottom) thumbBottomRight.position( positionX:newRight, positionY:newBottom) } private func movingTopLeft(point:CGPoint) { var pointX:CGFloat = point.x var pointY:CGFloat = point.y let originalX:CGFloat = thumbTopLeft.originalX let originalY:CGFloat = thumbTopLeft.originalY let rightX:CGFloat = thumbTopRight.positionX let bottomY:CGFloat = thumbBottomLeft.positionY if pointX < originalX { pointX = originalX } if pointY < originalY { pointY = originalY } var deltaX:CGFloat = rightX - pointX var deltaY:CGFloat = bottomY - pointY if deltaX < minDistance { deltaX = minDistance } if deltaY < minDistance { deltaY = minDistance } let minDelta:CGFloat = min(deltaX, deltaY) pointX = rightX - minDelta pointY = bottomY - minDelta thumbTopLeft.position( positionX:pointX, positionY:pointY) thumbTopRight.position( positionX:rightX, positionY:pointY) thumbBottomLeft.position( positionX:pointX, positionY:bottomY) } private func movingTopRight(point:CGPoint) { var pointX:CGFloat = point.x var pointY:CGFloat = point.y let originalX:CGFloat = thumbTopRight.originalX let originalY:CGFloat = thumbTopRight.originalY let leftX:CGFloat = thumbTopLeft.positionX let bottomY:CGFloat = thumbBottomRight.positionY if pointX > originalX { pointX = originalX } if pointY < originalY { pointY = originalY } var deltaX:CGFloat = pointX - leftX var deltaY:CGFloat = bottomY - pointY if deltaX < minDistance { deltaX = minDistance } if deltaY < minDistance { deltaY = minDistance } let minDelta:CGFloat = min(deltaX, deltaY) pointX = leftX + minDelta pointY = bottomY - minDelta thumbTopRight.position( positionX:pointX, positionY:pointY) thumbTopLeft.position( positionX:leftX, positionY:pointY) thumbBottomRight.position( positionX:pointX, positionY:bottomY) } private func movingBottomLeft(point:CGPoint) { var pointX:CGFloat = point.x var pointY:CGFloat = point.y let originalX:CGFloat = thumbBottomLeft.originalX let originalY:CGFloat = thumbBottomLeft.originalY let rightX:CGFloat = thumbBottomRight.positionX let topY:CGFloat = thumbTopLeft.positionY if pointX < originalX { pointX = originalX } if pointY > originalY { pointY = originalY } var deltaX:CGFloat = rightX - pointX var deltaY:CGFloat = pointY - topY if deltaX < minDistance { deltaX = minDistance } if deltaY < minDistance { deltaY = minDistance } let minDelta:CGFloat = min(deltaX, deltaY) pointX = rightX - minDelta pointY = topY + minDelta thumbBottomLeft.position( positionX:pointX, positionY:pointY) thumbBottomRight.position( positionX:rightX, positionY:pointY) thumbTopLeft.position( positionX:pointX, positionY:topY) } private func movingBottomRight(point:CGPoint) { var pointX:CGFloat = point.x var pointY:CGFloat = point.y let originalX:CGFloat = thumbBottomRight.originalX let originalY:CGFloat = thumbBottomRight.originalY let leftX:CGFloat = thumbBottomLeft.positionX let topY:CGFloat = thumbTopRight.positionY if pointX > originalX { pointX = originalX } if pointY > originalY { pointY = originalY } var deltaX:CGFloat = pointX - leftX var deltaY:CGFloat = pointY - topY if deltaX < minDistance { deltaX = minDistance } if deltaY < minDistance { deltaY = minDistance } let minDelta:CGFloat = min(deltaX, deltaY) pointX = leftX + minDelta pointY = topY + minDelta thumbBottomRight.position( positionX:pointX, positionY:pointY) thumbBottomLeft.position( positionX:leftX, positionY:pointY) thumbTopRight.position( positionX:pointX, positionY:topY) } //MARK: public func print() { let posRight:CGFloat = thumbTopRight.positionX let posLeft:CGFloat = thumbTopLeft.positionX let deltaPos:CGFloat = posRight - posLeft let size:Int = Int(ceil(deltaPos / imageRatio)) let string:String = "\(size)" let stringSize:NSAttributedString = NSAttributedString( string:string, attributes:attributes) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringSize) mutableString.append(stringTimes) mutableString.append(stringSize) label.attributedText = mutableString } func createShades() { if !shadesCreated { shadesCreated = true let shadeTop:VCameraCropImageShade = VCameraCropImageShade.borderBottom() let shadeBottom:VCameraCropImageShade = VCameraCropImageShade.borderTop() let shadeLeft:VCameraCropImageShade = VCameraCropImageShade.borderRight() let shadeRight:VCameraCropImageShade = VCameraCropImageShade.borderLeft() let shadeCornerTopLeft:VCameraCropImageShade = VCameraCropImageShade.noBorder() let shadeCornerTopRight:VCameraCropImageShade = VCameraCropImageShade.noBorder() let shadeCornerBottomLeft:VCameraCropImageShade = VCameraCropImageShade.noBorder() let shadeCornerBottomRight:VCameraCropImageShade = VCameraCropImageShade.noBorder() insertSubview(shadeTop, aboveSubview:imageView) insertSubview(shadeBottom, aboveSubview:imageView) insertSubview(shadeLeft, aboveSubview:imageView) insertSubview(shadeRight, aboveSubview:imageView) insertSubview(shadeCornerTopLeft, aboveSubview:imageView) insertSubview(shadeCornerTopRight, aboveSubview:imageView) insertSubview(shadeCornerBottomLeft, aboveSubview:imageView) insertSubview(shadeCornerBottomRight, aboveSubview:imageView) NSLayoutConstraint.topToTop( view:shadeTop, toView:background) NSLayoutConstraint.bottomToTop( view:shadeTop, toView:thumbTopLeft, constant:thumbSize_2) NSLayoutConstraint.leftToLeft( view:shadeTop, toView:thumbTopLeft, constant:thumbSize_2) NSLayoutConstraint.rightToRight( view:shadeTop, toView:thumbTopRight, constant:-thumbSize_2) NSLayoutConstraint.topToBottom( view:shadeBottom, toView:thumbBottomLeft, constant:-thumbSize_2) NSLayoutConstraint.bottomToBottom( view:shadeBottom, toView:background) NSLayoutConstraint.leftToLeft( view:shadeBottom, toView:thumbBottomLeft, constant:thumbSize_2) NSLayoutConstraint.rightToRight( view:shadeBottom, toView:thumbBottomRight, constant:-thumbSize_2) NSLayoutConstraint.topToTop( view:shadeLeft, toView:thumbTopLeft, constant:thumbSize_2) NSLayoutConstraint.bottomToBottom( view:shadeLeft, toView:thumbBottomLeft, constant:-thumbSize_2) NSLayoutConstraint.leftToLeft( view:shadeLeft, toView:background) NSLayoutConstraint.rightToLeft( view:shadeLeft, toView:thumbTopLeft, constant:thumbSize_2) NSLayoutConstraint.topToTop( view:shadeRight, toView:thumbTopRight, constant:thumbSize_2) NSLayoutConstraint.bottomToBottom( view:shadeRight, toView:thumbBottomRight, constant:-thumbSize_2) NSLayoutConstraint.leftToRight( view:shadeRight, toView:thumbTopRight, constant:-thumbSize_2) NSLayoutConstraint.rightToRight( view:shadeRight, toView:background) NSLayoutConstraint.topToTop( view:shadeCornerTopLeft, toView:background) NSLayoutConstraint.bottomToTop( view:shadeCornerTopLeft, toView:shadeLeft) NSLayoutConstraint.leftToLeft( view:shadeCornerTopLeft, toView:background) NSLayoutConstraint.rightToLeft( view:shadeCornerTopLeft, toView:shadeTop) NSLayoutConstraint.topToTop( view:shadeCornerTopRight, toView:background) NSLayoutConstraint.bottomToTop( view:shadeCornerTopRight, toView:shadeRight) NSLayoutConstraint.leftToRight( view:shadeCornerTopRight, toView:shadeTop) NSLayoutConstraint.rightToRight( view:shadeCornerTopRight, toView:background) NSLayoutConstraint.topToBottom( view:shadeCornerBottomLeft, toView:shadeLeft) NSLayoutConstraint.bottomToBottom( view:shadeCornerBottomLeft, toView:background) NSLayoutConstraint.leftToLeft( view:shadeCornerBottomLeft, toView:background) NSLayoutConstraint.rightToLeft( view:shadeCornerBottomLeft, toView:shadeBottom) NSLayoutConstraint.topToBottom( view:shadeCornerBottomRight, toView:shadeRight) NSLayoutConstraint.bottomToBottom( view:shadeCornerBottomRight, toView:background) NSLayoutConstraint.leftToRight( view:shadeCornerBottomRight, toView:shadeBottom) NSLayoutConstraint.rightToRight( view:shadeCornerBottomRight, toView:background) NSLayoutConstraint.topToBottom( view:viewMover, toView:shadeTop) NSLayoutConstraint.bottomToTop( view:viewMover, toView:shadeBottom) NSLayoutConstraint.leftToRight( view:viewMover, toView:shadeLeft) NSLayoutConstraint.rightToLeft( view:viewMover, toView:shadeRight) print() } } }
971a254afba127887250b62c0af798b6
31.6603
98
0.567627
false
false
false
false
ormaa/Bluetooth-LE-IOS-Swift
refs/heads/master
Central Manager/SharedCode/BLE Stack/BLE_Connection.swift
mit
1
// // BLECentralManager+Connect.swift // BlueToothCentral // // Created by Olivier Robin on 07/11/2016. // Copyright © 2016 fr.ormaa. All rights reserved. // import Foundation //import UIKit import CoreBluetooth extension BLECentralManager { // Connect to a peripheral, listed in the peripherals list // func connectToAsync(serviceUUID: String) { //centralManager?.stopScan() bleError = "" if peripherals.count > 0 { for i in 0...peripherals.count - 1 { let n = getPeripheralUUID(number: i) print(n) if n == serviceUUID { connect(peripheral: peripherals[i]) } } } } // Connect to a peripheral // func connect(peripheral: CBPeripheral?) { //stopBLEScan() log("connect to peripheral \(peripheral?.identifier)") if (peripheral != nil) { peripheralConnecting = peripheral peripheralConnected = nil let options = [CBConnectPeripheralOptionNotifyOnConnectionKey: true as AnyObject, CBConnectPeripheralOptionNotifyOnDisconnectionKey: true as AnyObject, CBConnectPeripheralOptionNotifyOnNotificationKey: true as AnyObject, CBCentralManagerRestoredStatePeripheralsKey: true as AnyObject, CBCentralManagerRestoredStateScanServicesKey : true as AnyObject] peripheral?.delegate = self centralManager?.connect(peripheral!, options: options) } } // disconnect from a connected peripheral // func disconnect() { log( "disconnect peripheral") if peripheralConnecting != nil { centralManager?.cancelPeripheralConnection(peripheralConnecting!) } } // delegate // // Connected to a peripheral // func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){ if peripheral.name != nil { log("didConnect event, peripheral: " + peripheral.name!) } else { log("didConnect event, peripheral identifier: " + peripheral.identifier.uuidString) } peripheralConnected = peripheral var name = "nil" if peripheral.name != nil { name = peripheral.name! } bleDelegate?.connected(message: name) } // delegate // Fail to connect // func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { if error != nil { bleError = ("Error didFailToConnect : \(error!.localizedDescription)") log(bleError) bleDelegate?.failConnected(message: error!.localizedDescription) } else { log("didFailToConnect") bleDelegate?.failConnected(message: "") } } // delegate // // disconnected form a peripheral // func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { if error != nil { bleError = ("Error didDisconnectPeripheral : \(error!.localizedDescription)") log(bleError) bleDelegate?.disconnected(message: error!.localizedDescription) } else { log("didDisconnectPeripheral") bleDelegate?.disconnected(message: "") } } // delegate // Called when connection is lost, or done again // func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { log("peripheral service modified. May be connection is lost !") for s in invalidatedServices { log("service: " + s.uuid.uuidString) } } // delegate // name of the device update // func peripheralDidUpdateName(_ peripheral: CBPeripheral) { log("peripheral name has change : " + peripheral.name!) } }
76701cdbbfb0f0142eac87ec550a5ab9
26.51634
119
0.578622
false
false
false
false
danpratt/Simply-Zen
refs/heads/master
Simply Zen/View Controllers/Extensions/QuotesBackupExtension.swift
apache-2.0
1
// // QuotesBackupExtension.swift // Simply Zen // // Created by Daniel Pratt on 6/26/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation struct QuotesBackupExtension { var quote: String! = "" var author: String! = "" mutating func getRandomQuote() { let quotes = [ ["Quote" : "Reduce the stress levels in your life through relaxation techniques like meditation, deep breathing, and exercise. You'll look and feel way better...", "Author":"Suzanne Somers"], ["Quote" : "Keep your best wishes, close to your heart and watch what happens", "Author" : "Tony DeLiso"], ["Quote" : "Feelings come and go like clouds in a windy sky. Conscious breathing is my anchor.", "Author" : "Thich Nhat Hanh"], ["Quote" : "If the ocean can calm itself, so can you. We are both salt water mixed with air.", "Author" : "Nayyirah Waheed"], ["Quote" : "I have lived with several Zen masters—all of them cats.", "Author" : "Eckhart Tolle"], ["Quote" : "The mind can go in a thousand directions, but on this beautiful path, I walk in peace. With each step, the wind blows. With each step, a flower blooms", "Author" : "Thich Nhat Hanh"], ["Quote" : "We can live without religion and meditation, but we cannot survive without human affection.", "Author" : "Dalai Lama"], ["Quote" : "Meditation is the tongue of the soul and the language of our spirit.", "Author" : "Jeremy Taylor"], ["Quote" : "Meditation is the soul's perspective glass.", "Author" : "Owen Feltham"], ["Quote" : "The best way to meditate is through meditation itself.", "Author" : "Ramana Maharshi"], ["Quote" : "We tend to think of meditation in only one way. But life itself is a meditation.", "Author" : "Raul Julia"] ] let quoteLocation: Int = Int(arc4random_uniform(UInt32(quotes.count))) let randomQuote = quotes[quoteLocation] self.quote = randomQuote["Quote"] self.author = randomQuote["Author"] } }
4d634aac3ab0cbf97aa2e48e396c5d71
50.853659
207
0.629351
false
false
false
false
blocktree/BitcoinSwift
refs/heads/master
BitcoinSwift/Sources/network/BTCCommand.swift
mit
1
// // BTCCommand.swift // BitcoinSwift // // Created by Chance on 2017/5/21. // // import Foundation /// 比特币网络协议指令集 /// /// - version: 一个节点收到连接请求时,它立即宣告其版本。在通信双方都得到对方版本之前,不会有其他通信 /// - verack: 版本不低于209的客户端在应答version消息时发送verack消息。这个消息仅包含一个command为"verack"的消息头 /// - addr: 提供网络上已知节点的信息。一般来说3小时不进行宣告(advertise)的节点会被网络遗忘 /// - inv: 节点通过此消息可以宣告(advertise)它又拥有的对象信息。这个消息可以主动发送,也可以用于应答getbloks消息 /// - getdata: getdata用于应答inv消息来获取指定对象,它通常在接收到inv包并滤去已知元素后发送 /// - getblocks: 发送此消息以期返回一个包含编号从hash_start到hash_stop的block列表的inv消息。若hash_start到hash_stop的block数超过500,则在500处截止。欲获取后面的block散列,需要重新发送getblocks消息。 /// - getheaders: 获取包含编号hash_star到hash_stop的至多2000个block的header包。要获取之后的block散列,需要重新发送getheaders消息。这个消息用于快速下载不包含相关交易的blockchain。 /// - tx: tx消息描述一笔比特币交易,用于应答getdata消息 /// - block: block消息用于响应请求交易信息的getdata消息 /// - headers: headers消息返回block的头部以应答getheaders /// - getaddr: getaddr消息向一个节点发送获取已知活动端的请求,以识别网络中的节点。回应这个消息的方法是发送包含已知活动端信息的addr消息。一般的,一个3小时内发送过消息的节点被认为是活动的。 /// - checkorder: 此消息用于IP Transactions,以询问对方是否接受交易并允许查看order内容。 /// - submitorder: 确认一个order已经被提交 /// - reply: IP Transactions的一般应答 /// - ping: ping消息主要用于确认TCP/IP连接的可用性。 /// - alert: alert消息用于在节点间发送通知使其传遍整个网络。如果签名验证这个alert来自Bitcoin的核心开发组,建议将这条消息显示给终端用户。交易尝试,尤其是客户端间的自动交易则建议停止。消息文字应当记入记录文件并传到每个用户。 public enum BTCCommand: String { case version = "version" case verack = "verack" case addr = "addr" case inv = "inv" case getdata = "getdata" case getblocks = "getblocks" case getheaders = "getheaders" case tx = "tx" case block = "block" case headers = "headers" case getaddr = "getaddr" case checkorder = "checkorder" case submitorder = "submitorder" case reply = "reply" case ping = "ping" case alert = "alert" /// 是否需要校验完整性 public var isChecksum: Bool { // version和verack消息不包含checksum,payload的起始位置提前4个字节 switch self { case .version, .verack: return false default: return true } } public func encode(value: [String: Any]) -> Data { var msg = Data() switch self { case .version: //一个节点收到连接请求时,它立即宣告其版本。在通信双方都得到对方版本之前,不会有其他通信 msg.appendVarInt(value: 0) // case .verack: // case .addr: // case .inv: // case .getdata: // case .getblocks: // case .getheaders: // case .tx: // case .block: // case .headers: // case .getaddr: // case .checkorder: // case .submitorder: // case .reply: // case .ping: // case .alert: default:break } return msg } public static func sendVersionMessage() { } }
b3b34c1aa62540853b539cec87f44a92
28.311828
143
0.653705
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/SuggestionLocalizationViewController.swift
gpl-2.0
1
// // SuggestionLocalizationViewController.swift // Telegram // // Created by keepcoder on 27/05/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Localization import Postbox import SwiftSignalKit private class SuggestionControllerView : View { let textView:TextView = TextView() let suggestTextView:TextView = TextView() let separatorView:View = View() let tableView:TableView = TableView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(textView) addSubview(separatorView) addSubview(tableView) addSubview(suggestTextView) textView.backgroundColor = theme.colors.background suggestTextView.backgroundColor = theme.colors.background tableView.setFrameSize(NSMakeSize(frameRect.width, frameRect.height - 50)) separatorView.setFrameSize(frameRect.width, .borderSize) separatorView.backgroundColor = theme.colors.border layout() } func updateHeaderTexts(_ suggestLocalization:String) { let headerLayout = TextViewLayout(.initialize(string: suggestLocalization, color: theme.colors.text, font: .normal(.title))) headerLayout.measure(width: frame.width - 40) textView.update(headerLayout) // let suggestHeaderLayout = TextViewLayout(.initialize(string: NativeLocalization("Suggest.Localization.Header"), color: theme.colors.grayText, font: .normal(.text))) suggestHeaderLayout.measure(width: frame.width - 40) suggestTextView.update(suggestHeaderLayout) needsLayout = true } override func layout() { super.layout() textView.centerX(y: 25 - textView.frame.height - 1) suggestTextView.centerX(y: 25 + 1) separatorView.setFrameOrigin(0, 50 - .borderSize) tableView.setFrameOrigin(0, 50) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SuggestionLocalizationViewController: ModalViewController { private let context:AccountContext private let suggestionInfo:SuggestedLocalizationInfo private var languageCode:String = "en" init(_ context: AccountContext, suggestionInfo: SuggestedLocalizationInfo) { self.context = context self.suggestionInfo = suggestionInfo super.init(frame: NSMakeRect(0, 0, 280, 198)) bar = .init(height: 0) } override func viewClass() -> AnyClass { return SuggestionControllerView.self } override var modalInteractions: ModalInteractions? { return ModalInteractions(acceptTitle: strings().modalOK, accept: { [weak self] in if let strongSelf = self { strongSelf.close() let engine = strongSelf.context.engine.localization _ = engine.markSuggestedLocalizationAsSeenInteractively(languageCode: strongSelf.suggestionInfo.languageCode).start() _ = showModalProgress(signal: engine.downloadAndApplyLocalization(accountManager: strongSelf.context.sharedContext.accountManager, languageCode: strongSelf.languageCode), for: strongSelf.context.window).start() } }, drawBorder: true, height: 40) } private var genericView:SuggestionControllerView { return self.view as! SuggestionControllerView } override var closable: Bool { return false } override func viewDidLoad() { super.viewDidLoad() genericView.updateHeaderTexts(suggestionInfo.localizedKey("Suggest.Localization.Header")) let swap = languages.index(of: self.suggestionInfo.languageCode) != nil reloadItems(swap ? 1 : 0, swap) readyOnce() } var languages:[String] { return ["nl", "es", "it", "de", "pt"] } private func reloadItems(_ selected:Int, _ swap:Bool) { genericView.tableView.removeAll() let initialSize = self.atomicSize.modify({$0}) var enInfo:LocalizationInfo? var currentInfo:LocalizationInfo? for suggestInfo in suggestionInfo.availableLocalizations { if suggestInfo.languageCode == "en" { enInfo = suggestInfo if selected == 0 { languageCode = suggestInfo.languageCode } } else if suggestInfo.languageCode == suggestionInfo.languageCode { currentInfo = suggestInfo if selected == 1 { languageCode = suggestInfo.languageCode } } } _ = genericView.tableView.addItem(item: GeneralRowItem(initialSize, height: 5)) if let info = enInfo { _ = genericView.tableView.insert(item: LanguageRowItem(initialSize: initialSize, stableId: 0, selected: selected == 0, deletable: false, value: info, action: { [weak self] in self?.reloadItems(0, swap) }, reversed: true), at: 0) } if let info = currentInfo { _ = genericView.tableView.insert(item: LanguageRowItem(initialSize: initialSize, stableId: 1, selected: selected == 1, deletable: false, value: info, action: { [weak self] in self?.reloadItems(1, swap) }, reversed: true), at: swap ? 0 : 1) } // public init(languageCode: String, baseLanguageCode: String?, customPluralizationCode: String?, title: String, localizedTitle: String, isOfficial: Bool, totalStringCount: Int32, translatedStringCount: Int32, platformUrl: String) { let otherInfo = LocalizationInfo(languageCode: "", baseLanguageCode: nil, customPluralizationCode: nil, title: NativeLocalization("Suggest.Localization.Other"), localizedTitle: suggestionInfo.localizedKey("Suggest.Localization.Other"), isOfficial: true, totalStringCount: 0, translatedStringCount: 0, platformUrl: "" ) _ = genericView.tableView.addItem(item: LanguageRowItem(initialSize: initialSize, stableId: 10, selected: false, deletable: false, value: otherInfo, action: { [weak self] in if let strongSelf = self { strongSelf.close() strongSelf.context.bindings.rootNavigation().push(LanguageViewController(strongSelf.context)) let engine = strongSelf.context.engine.localization _ = engine.markSuggestedLocalizationAsSeenInteractively(languageCode: strongSelf.suggestionInfo.languageCode).start() } }, reversed: true)) } }
05a90a7e45b43ef2b3538ae4955f4f15
40.7375
326
0.656334
false
false
false
false
samsara/samsara
refs/heads/master
clients/ios/Pod/Classes/SSDeviceInfo.swift
apache-2.0
1
// // SSDeviceInfo.swift // samsara-ios-sdk // // Created by Sathyavijayan Vittal on 14/04/2015. // Copyright © 2015-2017 Samsara's authors. // import Foundation import Locksmith import SystemConfiguration class SSDeviceInfo { private static let ssUDIDIdentifier = "samsara.io.udid" class func getDeviceInfo() -> [String:String] { var udid = getUDID() var deviceInfo = [ "device_name": UIDevice.currentDevice().name, "system_name": UIDevice.currentDevice().systemName, "system_version": UIDevice.currentDevice().systemVersion, "model": UIDevice.currentDevice().model, "localizedModel": UIDevice.currentDevice().localizedModel, ] deviceInfo["UDID"] = udid return deviceInfo } class func getUDID () -> String { var dictionary = Locksmith.loadDataForUserAccount(ssUDIDIdentifier) var s_uid = NSUUID().UUIDString dictionary = dictionary ?? [:] //Yuck !! if let uid = dictionary!["UDID"] as? String { s_uid = uid } else { do { let error = try Locksmith.saveData(["UDID": s_uid], forUserAccount: ssUDIDIdentifier) } catch _ { NSLog("SSDeviceInfo: Error: Unable to save UDID to keychain") } } return s_uid } }
eda2eeb1ca8627d5749168cd5c766905
26.46
101
0.595047
false
false
false
false
chien/CKImagePicker
refs/heads/master
CKImagePicker/Classes/CKImagePickerConfiguration.swift
mit
1
// // CKImagePickerConfiguration.swift // Pods // // Created by Cheng-chien Kuo on 6/5/16. // // extension UIImage { var uncompressedPNGData: NSData { return UIImagePNGRepresentation(self)! } var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! } var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)! } var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! } var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)! } var lowestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.0)! } } public class CKImagePickerConfiguration { public var font = UIFont.systemFontOfSize(16) public var textColor = UIColor.lightGrayColor() public var backgroundColor = UIColor.whiteColor() public var utilButtonBackgroundColor = UIColor.clearColor() public var tintColor = UIColor.orangeColor() public var menuButtonSize = CGFloat(30) public var menuButtonSpacing = CGFloat(2) public var imageFolderName = "default" public var cameraControlButtonSize = CGFloat(60) public var utilControlButtonSize = CGFloat(40) public var paddingSize = CGFloat(10) public var collectionViewImagePerRow = CGFloat(5) public var collectionViewLineSpacing = CGFloat(2) public var collectionViewCellSize: CGSize { let cellSize = (imageContainerSize-((collectionViewImagePerRow-1)*collectionViewLineSpacing))/CGFloat(collectionViewImagePerRow) return CGSize(width: cellSize, height: cellSize) } public var compressionRate = CGFloat(0.5) internal var menuSectionHeight: CGFloat { return menuButtonSize + 2*menuButtonSpacing } lazy internal var imageContainerSize: CGFloat = { return self.frame.width }() lazy internal var controllerContainerHeight: CGFloat = { return self.frame.height - self.imageContainerSize - self.menuSectionHeight }() internal let frame: CGRect! public enum MenuMode: Int { case Camera case Album } public init(frame: CGRect) { self.frame = frame } }
6c88608cd5c569e2c3c76c7f60ff9fa0
33.859375
136
0.706858
false
false
false
false
FromF/SlideDisplay
refs/heads/master
SlideDisplay/SlideDisplay/ViewController.swift
mit
1
// // ViewController.swift // SlideDisplay // // Created by Fuji on 2015/06/04. // Copyright (c) 2015年 FromF. All rights reserved. // import UIKit import CoreGraphics import AVFoundation import CoreMedia extension UIColor { class func rgb(#r: Int, g: Int, b: Int, alpha: CGFloat) -> UIColor{ return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) } } class ViewController: UIViewController , UIScrollViewDelegate { //表示する画像リスト var imageList = [ //Sample photo by http://www.ashinari.com/ "a0050_000081", "a0150_000078", "a0150_000165", "a0880_000017", "a0990_000074", "a1130_000005", "a1130_000380", "a1220_000039", "a1370_000058", "a1370_000075", ] var movieList = [ //Sample Movie by http://動画素材.com "CITY_0852", "CITY_0998", "CITY_3748", ] // スライド表示 var viewList = NSMutableArray() var circulated:Bool = true var leftImageIndex:NSInteger = 0 var leftViewIndex:NSInteger = 0 var rightViewIndex:NSInteger = 0 var imageViewHeight : CGFloat = 0 var imageViewWidth : CGFloat = 0 var displayImageNum:NSInteger = 0 let MAX_SCROLLABLE_IMAGES:NSInteger = 10000 var MAX_IMAGE_NUM:NSInteger = 0 var timer : NSTimer! // 動画再生 var playerItem : AVPlayerItem! var videoPlayer : AVPlayer! var movieIndex:NSInteger = 0 var playerLayer:AVPlayerLayer! // let imageChache : ImageCacheObject = ImageCacheObject() //UI @IBOutlet weak var _scrollView: UIScrollView! @IBOutlet weak var _subView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. _subView.backgroundColor = UIColor.rgb(r: 0xD3, g: 0xED, b: 0xFB, alpha: 1.0) view.backgroundColor = UIColor.rgb(r: 0xD3, g: 0xED, b: 0xFB, alpha: 1.0) _scrollView.delegate = self self.timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onNextAnimation:", userInfo: nil, repeats: false) //Notification Regist NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidPlayToEndTime:", name: AVPlayerItemDidPlayToEndTimeNotification , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationApplicationBackground:", name: UIApplicationDidEnterBackgroundNotification , object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationApplicationForeground:", name: UIApplicationDidBecomeActiveNotification , object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //スライド表示準備 imageViewHeight = _scrollView.frame.size.height imageViewWidth = CGFloat(NSInteger(imageViewHeight * 4 / 3)) var imageViewFrame : CGRect = CGRectMake(imageViewWidth * CGFloat(-1) , 0, imageViewWidth, imageViewHeight) displayImageNum = NSInteger(_scrollView.frame.size.width / imageViewWidth) MAX_IMAGE_NUM = displayImageNum + 2 _scrollView.contentSize = CGSizeMake(imageViewWidth * CGFloat(MAX_IMAGE_NUM), imageViewHeight) for var i = 0 ; i < MAX_IMAGE_NUM ; i++ { let imageView:UIImageView = UIImageView(frame: imageViewFrame) viewList.addObject(imageView) _scrollView.addSubview(imageView) imageViewFrame.origin.x += imageViewWidth } setImageList() //動画再生 playMovie() } func blankimage () -> UIImage { var rect : CGRect = CGRectMake(0, 0, 1, 1) UIGraphicsBeginImageContext(rect.size) var context:CGContext! = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, UIColor.grayColor().CGColor) var image:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func imageAtIndex(prmindex:NSInteger) -> UIImage { let numberOfImages : NSInteger = imageList.count var image:UIImage! var index:NSInteger = prmindex if circulated { if 0 <= index && index <= MAX_SCROLLABLE_IMAGES - 1 { index = ( index + numberOfImages) % numberOfImages } } if 0 <= index && index < numberOfImages { image = getUncachedImage(named: imageList[index]) } else { image = blankimage() } return image } func updateScrollViewSetting () { var contentSize:CGSize = CGSizeMake(0, imageViewHeight) let numberOfImages : NSInteger = imageList.count if circulated { contentSize.width = imageViewWidth * CGFloat(MAX_SCROLLABLE_IMAGES) var contentOffset:CGPoint = CGPoint.zeroPoint contentOffset.x = CGFloat((MAX_SCROLLABLE_IMAGES - numberOfImages) / 2 ) * imageViewWidth var viewFrame = CGRectMake(contentOffset.x - imageViewWidth, 0, imageViewWidth, imageViewHeight) for (var i = 0 ; i < self.viewList.count ; i++) { var view:UIImageView = self.viewList.objectAtIndex(i) as! UIImageView view.frame = viewFrame viewFrame.origin.x += imageViewWidth } leftImageIndex = NSInteger(contentOffset.x / imageViewWidth) _scrollView.contentOffset = contentOffset var leftView:UIImageView = self.viewList.objectAtIndex(leftViewIndex) as! UIImageView leftView.image = imageAtIndex(displayImageNum) } else { contentSize.width = imageViewWidth * CGFloat(numberOfImages) } _scrollView.contentSize = contentSize _scrollView.showsHorizontalScrollIndicator = !circulated } func setImageList() { // initialize indices leftImageIndex = 0 leftViewIndex = 0 rightViewIndex = MAX_IMAGE_NUM - 1 // [1]setup blank for var i = 0 ; i < MAX_IMAGE_NUM ; i++ { var view : UIImageView = viewList.objectAtIndex(i) as! UIImageView view.image = blankimage() } // [2]display area var index : NSInteger = 1; // skip 0 for (var i = 0 ; i < imageList.count ; i++) { var image : UIImage = getUncachedImage(named: imageList[i])! var view : UIImageView = viewList.objectAtIndex(index) as! UIImageView view.image = image index++ if (index > displayImageNum) { break } } // [3]outside var rightView : UIImageView = viewList.objectAtIndex(MAX_IMAGE_NUM - 1) as! UIImageView rightView.image = imageAtIndex(displayImageNum) // [4]setup scrollView updateScrollViewSetting() } // MARK: - Notification func NotificationApplicationBackground(notification : NSNotification?) { // 再生を停止 videoPlayer.pause() } func NotificationApplicationForeground(notification : NSNotification?) { // 再生時間を最初に戻して再生. videoPlayer.seekToTime(CMTimeMakeWithSeconds(0, Int32(NSEC_PER_SEC))) videoPlayer.play() } //MARK:- unchached uiimageload func getUncachedImage (named name : String) -> UIImage? { if let imgPath = NSBundle.mainBundle().pathForResource(name, ofType: "jpg") { return imageChache.getUncachedImage(imgPath) } return nil } //MARK:- Movie Play func playMovie() { // パスからassetを生成. let path = NSBundle.mainBundle().pathForResource(movieList[movieIndex] , ofType: "mov") let fileURL = NSURL(fileURLWithPath: path!) let avAsset = AVURLAsset(URL: fileURL, options: nil) // AVPlayerに再生させるアイテムを生成. playerItem = AVPlayerItem(asset: avAsset) // AVPlayerを生成. videoPlayer = AVPlayer(playerItem: playerItem) // Viewを生成. var videoPlayerFrame : CGRect = CGRectMake(0, 0, _subView.frame.size.width, _subView.frame.size.height) let videoPlayerView = AVPlayerView(frame: videoPlayerFrame) // UIViewのレイヤーをAVPlayerLayerにする. if playerLayer != nil { playerLayer.removeFromSuperlayer() } playerLayer = videoPlayerView.layer as! AVPlayerLayer playerLayer.videoGravity = AVLayerVideoGravityResizeAspect playerLayer.player = videoPlayer // レイヤーを追加する. _subView.layer.addSublayer(playerLayer) // 再生時間を最初に戻して再生. videoPlayer.seekToTime(CMTimeMakeWithSeconds(0, Int32(NSEC_PER_SEC))) videoPlayer.play() } func playerDidPlayToEndTime(notification : NSNotification?) { //再生する動画ファイル選択 movieIndex++ if (movieList.count - 1) < movieIndex { movieIndex = 0 } //動画再生 playMovie() } //MARK:- Animation func startAnimation() { _scrollView.delegate = nil var animationTime : NSTimeInterval = NSTimeInterval(imageViewWidth) / 100 UIView.animateWithDuration( animationTime, delay:0.0, options:UIViewAnimationOptions.CurveLinear, animations: {() -> Void in var offsetpoint : CGPoint = CGPointMake(self._scrollView.contentOffset.x - self.imageViewWidth, self._scrollView.contentOffset.y) self._scrollView.contentOffset = offsetpoint }, completion: {(value: Bool) in self._scrollView.delegate = self self.scrollViewDidScroll(self._scrollView) self.onNextAnimation(self.timer) } ); } func onNextAnimation(timer : NSTimer){ dispatch_async(dispatch_get_main_queue()) { self.startAnimation() } } //MARK:- enum ScrollDirection { case KScrollDirectionLeft case KScrollDirectionRight } func addViewIndex(index:NSInteger , incremental:NSInteger) -> NSInteger { return (index + incremental + MAX_IMAGE_NUM) % MAX_IMAGE_NUM } func scrollWithDirection(scrollDirection:ScrollDirection) { var incremental : NSInteger = 0 var viewIndex : NSInteger = 0 var imageIndex : NSInteger = 0 if scrollDirection == ScrollDirection.KScrollDirectionLeft { incremental = -1 viewIndex = rightViewIndex } else if scrollDirection == ScrollDirection.KScrollDirectionRight { incremental = 1 viewIndex = leftViewIndex } // change position var view : UIImageView = viewList.objectAtIndex(viewIndex) as! UIImageView var frame:CGRect = view.frame frame.origin.x += imageViewWidth * CGFloat(MAX_IMAGE_NUM * incremental) view.frame = frame // change image leftImageIndex = leftImageIndex + incremental if scrollDirection == ScrollDirection.KScrollDirectionLeft { imageIndex = leftImageIndex - 1 } else if scrollDirection == ScrollDirection.KScrollDirectionRight { imageIndex = leftImageIndex + displayImageNum } view.image = imageAtIndex(imageIndex) // adjust indicies leftViewIndex = addViewIndex(leftViewIndex, incremental: incremental) rightViewIndex = addViewIndex(rightViewIndex, incremental: incremental) } func scrollViewDidScroll(scrollView: UIScrollView) { var position : CGFloat = scrollView.contentOffset.x / imageViewWidth var delta : CGFloat = position - CGFloat(leftImageIndex) if fabs(delta) >= 1.0 { if delta > 0 { scrollWithDirection(ScrollDirection.KScrollDirectionRight) } else { scrollWithDirection(ScrollDirection.KScrollDirectionLeft) } } } }
43f33de8dd891259e8d6cc70b1798c29
34.373938
175
0.613438
false
false
false
false
MTR2D2/TIY-Assignments
refs/heads/master
HighVoltage/HighVoltage/ValuesTableViewController.swift
cc0-1.0
1
// // CalculationsTableViewController.swift // HighVoltage // // Created by Michael Reynolds on 10/23/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class ValuesTableViewController: UITableViewController { var values: [String]? var delegate: ValuesTableViewControllerDelegate? @IBOutlet weak var valuesLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return values!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("popoverCell", forIndexPath: indexPath) // Configure the cell... let aValue = values?[indexPath.row] cell.textLabel?.text = aValue return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
041be8c3da6b17c7e18c6b32f434944d
32.2
157
0.687034
false
false
false
false
roddi/UltraschallHub
refs/heads/develop
Application/UltraschallHub/GradiantView.swift
mit
1
// // GradiantView.swift // UltraschallHub // // Created by Daniel Lindenfelser on 04.10.14. // Copyright (c) 2014 Daniel Lindenfelser. All rights reserved. // import Cocoa public class GradiantView: NSView { override public func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) drawBackground(dirtyRect) } private func drawBackground(frame: NSRect) { let gradientColor1 = NSColor(calibratedRed: 0.975, green: 0.975, blue: 0.975, alpha: 1) let gradientColor2 = NSColor(calibratedRed: 0.951, green: 0.951, blue: 0.951, alpha: 1) let borderColor = NSColor(calibratedRed: 0.569, green: 0.569, blue: 0.569, alpha: 1) let gradient = NSGradient(startingColor: gradientColor1, endingColor: gradientColor2) let rectanglePath = NSBezierPath(rect: NSMakeRect(NSMinX(frame) + 0.5, NSMinY(frame) + 0.5, NSWidth(frame) - 1.0, NSHeight(frame) - 1.0)) gradient.drawInBezierPath(rectanglePath, angle: -90) borderColor.setStroke() rectanglePath.lineWidth = 1 rectanglePath.stroke() } }
60a32d809dccb31e9dca1dd49d764854
34.548387
145
0.673321
false
false
false
false
kmcgill88/KMImageLoader
refs/heads/master
KMImageLoader/KMImageLoader.swift
mit
1
// // KMImageLoader.swift // // Originally inspired by Nate Lyman - NateLyman.com // // Created by Kevin McGill on 3/19/15. // Copyright (c) 2015 McGill DevTech, LLC. All rights reserved. // import UIKit import Foundation import CoreGraphics class ImageLoader { let SECONDS_SINCE_DISK_CACHE_CLEAN = 60 //Set time in seconds until cache is cleared. let MAX_SIZE:CGFloat = 400 //Max width or height of downloaded Image. var cache = NSCache() var fileManager = NSFileManager.defaultManager() var imageDirectory = "/Documents/Images" let errorImage = UIImage(named: "error-image.png") class var sharedLoader : ImageLoader { struct Static { static let instance : ImageLoader = ImageLoader() } return Static.instance } init () { initFileManager() } func imageForUrl(urlString: String, completionHandler:(image: UIImage!, url: String) -> () ) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in //Try to get from memory cache. var img: UIImage? = self.cache.objectForKey(urlString) as? UIImage if let goodImg = img { dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: goodImg, url: urlString) }) return } //Try to get from disk, if found, stick in memory cache var data = NSKeyedUnarchiver.unarchiveObjectWithFile(self.filePathForUrl(urlString)) as? NSData if let goodData = data { img = UIImage(data: goodData) if let goodImg = img { self.cache.setObject(goodImg, forKey: urlString) dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: goodImg, url: urlString) }) return } } //Go to the web and get the image. NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if (error != nil) { completionHandler(image: self.errorImage, url: urlString) return } if (data != nil) { var image = UIImage(data: data) if var goodImg = image { var tmpImg = self.makeRoundCornerImage(goodImg) if var finalImage = tmpImg { self.cache.setObject(finalImage, forKey: urlString) var tempData = UIImagePNGRepresentation(finalImage) //var tempData = UIImageJPEGRepresentation(finalImage, 0.50) if var finalData = tempData { if !NSKeyedArchiver.archiveRootObject(finalData, toFile: self.filePathForUrl(urlString)) { println("FAILED to save good image.") } dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: finalImage, url: urlString) }) return } } dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: self.errorImage, url: urlString) }) return } dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: self.errorImage, url: urlString) }) return } dispatch_async(dispatch_get_main_queue(), {() in completionHandler(image: self.errorImage, url: urlString) }) return }).resume() }) } func makeRoundCornerImage(theImg:UIImage!) -> UIImage? { if var goodImg = theImg{ var w = goodImg.size.width var h = goodImg.size.height var aspectRatio = goodImg.size.width / goodImg.size.height while (w > MAX_SIZE || h > MAX_SIZE) { h *= 0.99 w *= 0.99 } var rect:CGRect = CGRectMake(0, 0, w, (w/aspectRatio)) var ovalWidth = CGFloat(w * 0.075) var ovalHeight = CGFloat(h * 0.075) let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) var colorSpace:CGColorSpaceRef = CGColorSpaceCreateDeviceRGB() var context:CGContextRef = CGBitmapContextCreate(nil, Int(rect.size.width), Int(rect.size.height), 8, 4 * Int(rect.size.width), colorSpace, bitmapInfo) CGContextBeginPath(context) var fw, fh :CGFloat if (ovalWidth == 0 || ovalHeight == 0) { CGContextAddRect(context, rect) } CGContextSaveGState(context) CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect)) CGContextScaleCTM (context, ovalWidth, ovalHeight) fw = CGRectGetWidth (rect) / ovalWidth fh = CGRectGetHeight (rect) / ovalHeight CGContextMoveToPoint(context, fw, fh/2) CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1) CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1) CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1) CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1) CGContextClosePath(context) CGContextRestoreGState(context) CGContextClosePath(context) CGContextClip(context) CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), goodImg.CGImage) var imageMasked:CGImageRef = CGBitmapContextCreateImage(context) return UIImage(CGImage: imageMasked) } return theImg } func cleanDiskCache(){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in var error:NSError? var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! var filePaths = self.fileManager.contentsOfDirectoryAtPath(self.imageDirectory, error: nil) if var goodPaths = filePaths as? [NSString] { for path in goodPaths { var fullPath = self.imageDirectory.stringByAppendingPathComponent(path as String) var dic:NSDictionary? = self.fileManager.attributesOfItemAtPath(fullPath, error: nil) if var goodDic = dic { var creationDate: AnyObject? = goodDic[NSFileCreationDate] if var savedDate = creationDate as? NSDate { var components = calendar.components(NSCalendarUnit.CalendarUnitSecond, fromDate: savedDate, toDate: NSDate(), options: nil) if components.second >= self.SECONDS_SINCE_DISK_CACHE_CLEAN { if !self.fileManager.removeItemAtPath(fullPath, error: &error) { println("Failed to delete \(fullPath). Because -->\(error)") } } } } } } }) } func initFileManager(){ var documentsPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String imageDirectory = documentsPath.stringByAppendingPathComponent("Images") //If the file doesn't exists, make one // if(!fileManager.fileExistsAtPath(imageDirectory)){ println("Images Directory didn't exist. Created.") fileManager.createDirectoryAtPath(imageDirectory, withIntermediateDirectories: true, attributes: nil, error: nil) } } func filePathForUrl(url:String) -> String { return imageDirectory.stringByAppendingPathComponent("\(url.hash)") } }
9a95920944396f86a5dd5b10acc70a6e
41.77451
173
0.533295
false
false
false
false
smartystreets/smartystreets-ios-sdk
refs/heads/master
Sources/SmartyStreets/USZipCode/USAlternateCounties.swift
apache-2.0
1
import Foundation public class USAlternateCounties: NSObject, Codable { // See "https://smartystreets.com/docs/cloud/us-zipcode-api#zipcodes" public var countyFips:String? public var countyName:String? public var stateAbbreviation:String? public var state:String? enum CodingKeys: String, CodingKey { case countyFips = "county_fips" case countyName = "county_name" case stateAbbreviation = "state_abbreviation" case state = "state" } public init(dictionary:NSDictionary) { self.countyFips = dictionary["county_fips"] as? String self.countyName = dictionary["county_name"] as? String self.stateAbbreviation = dictionary["state_abbreviation"] as? String self.state = dictionary["state"] as? String } }
4675059bbd8c9afa308d51ddbd768fa0
33.125
76
0.67033
false
false
false
false
xpush/lib-xpush-ios
refs/heads/master
XpushFramework/Source/MultipartFormData.swift
mit
1
// MultipartFormData.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 #if os(iOS) || os(watchOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif /** Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well and the w3 form documentation. - https://www.ietf.org/rfc/rfc2388.txt - https://www.ietf.org/rfc/rfc2045.txt - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 */ public class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let CRLF = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case Initial, Encapsulated, Final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { let boundaryText: String switch boundaryType { case .Initial: boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" case .Encapsulated: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" case .Final: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" } return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } class BodyPart { let headers: [String: String] let bodyStream: NSInputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: NSError? private let streamBufferSize: Int // MARK: - Lifecycle /** Creates a multipart form data object. - returns: The multipart form data object. */ public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /** * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more * information, please refer to the following article: * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html */ self.streamBufferSize = 1024 } // MARK: - Body Parts /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. */ public func appendBodyPart(data data: NSData, name: String) { let headers = contentHeaders(name: name) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, mimeType: String) { let headers = contentHeaders(name: name, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary The filename in the `Content-Disposition` HTTP header is generated from the last path component of the `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the system associated MIME type. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String) { if let fileName = fileURL.lastPathComponent, pathExtension = fileURL.pathExtension { let mimeType = mimeTypeForPathExtension(pathExtension) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) } } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - Content-Type: #{mimeType} (HTTP Header) - Encoded file data - Multipart form boundary - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ var isReachable = true if #available(iOS 8.0, *) { isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) } else { // Fallback on earlier versions } guard isReachable else { let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") setBodyPartError(error) return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false guard let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ var bodyContentLength: UInt64? do { if let path = fileURL.path, fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber { bodyContentLength = fileSize.unsignedLongLongValue } } catch { // No-op } guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(error) return } appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the stream and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. */ public func appendBodyPart( stream stream: NSInputStream, length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part with the headers, stream and length and appends it to the multipart form data object. The body part data will be encoded using the following format: - HTTP headers - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter headers: The HTTP headers for the body part. */ public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /** Encodes all the appended body parts into a single `NSData` object. It is important to note that this method will load all the appended body parts into memory all at the same time. This method should only be used when the encoded data will have a small memory footprint. For large data cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - throws: An `NSError` if encoding encounters an error. - returns: The encoded `NSData` if encoding is successful. */ public func encode() throws -> NSData { if let bodyPartError = bodyPartError { throw bodyPartError } let encoded = NSMutableData() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encodeBodyPart(bodyPart) encoded.appendData(encodedData) } return encoded } /** Writes the appended body parts into the given file URL. This process is facilitated by reading and writing with input and output streams, respectively. Thus, this approach is very memory efficient and should be used for large body part data. - parameter fileURL: The file URL to write the multipart form data into. - throws: An `NSError` if encoding encounters an error. */ public func writeEncodedDataToDisk(fileURL: NSURL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) } outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try writeBodyPart(bodyPart, toOutputStream: outputStream) } outputStream.close() outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { let encoded = NSMutableData() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.appendData(initialData) let headerData = encodeHeaderDataForBodyPart(bodyPart) encoded.appendData(headerData) let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) encoded.appendData(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.appendData(finalBoundaryData()) } return encoded } private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" } headerText += EncodingCharacters.CRLF return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? let encoded = NSMutableData() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if inputStream.streamError != nil { error = inputStream.streamError break } if bytesRead > 0 { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) break } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) } private func writeInitialBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try writeData(initialData, toOutputStream: outputStream) } private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let headerData = encodeHeaderDataForBodyPart(bodyPart) return try writeData(headerData, toOutputStream: outputStream) } private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw streamError } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { if bodyPart.hasFinalBoundary { return try writeData(finalBoundaryData(), toOutputStream: outputStream) } } // MARK: - Private - Writing Buffered Data to Output Stream private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws { var buffer = [UInt8](count: data.length, repeatedValue: 0) data.getBytes(&buffer, length: data.length) return try writeBuffer(&buffer, toOutputStream: outputStream) } private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws { var bytesToWrite = buffer.count while bytesToWrite > 0 { if outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let streamError = outputStream.streamError { throw streamError } if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } else if let streamError = outputStream.streamError { throw streamError } } } // MARK: - Private - Mime Type private func mimeTypeForPathExtension(pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(name name: String) -> [String: String] { return ["Content-Disposition": "form-data; name=\"\(name)\""] } private func contentHeaders(name name: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"", "Content-Type": "\(mimeType)" ] } private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", "Content-Type": "\(mimeType)" ] } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) } private func encapsulatedBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) } private func finalBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(error: NSError) { if bodyPartError == nil { bodyPartError = error } } }
5c91c485ffd328184c0583624b48b56b
39.14307
128
0.638588
false
false
false
false
antlr/antlr4
refs/heads/dev
runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift
bsd-3-clause
10
/// /// Copyright (c) 2012-2017 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. /// /// /// This is the base class for gathering detailed information about prediction /// events which occur during parsing. /// /// Note that we could record the parser call stack at the time this event /// occurred but in the presence of left recursive rules, the stack is kind of /// meaningless. It's better to look at the individual configurations for their /// individual stacks. Of course that is a _org.antlr.v4.runtime.atn.PredictionContext_ object /// not a parse tree node and so it does not have information about the extent /// (start...stop) of the various subtrees. Examining the stack tops of all /// configurations provide the return states for the rule invocations. /// From there you can get the enclosing rule. /// /// - 4.3 /// public class DecisionEventInfo { /// /// The invoked decision number which this event is related to. /// /// - seealso: org.antlr.v4.runtime.atn.ATN#decisionToState /// public let decision: Int /// /// The configuration set containing additional information relevant to the /// prediction state when the current event occurred, or `null` if no /// additional information is relevant or available. /// public let configs: ATNConfigSet? /// /// The input token stream which is being parsed. /// public let input: TokenStream /// /// The token index in the input stream at which the current prediction was /// originally invoked. /// public let startIndex: Int /// /// The token index in the input stream at which the current event occurred. /// public let stopIndex: Int /// /// `true` if the current event occurred during LL prediction; /// otherwise, `false` if the input occurred during SLL prediction. /// public let fullCtx: Bool public init(_ decision: Int, _ configs: ATNConfigSet?, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int, _ fullCtx: Bool) { self.decision = decision self.fullCtx = fullCtx self.stopIndex = stopIndex self.input = input self.startIndex = startIndex self.configs = configs } }
62f1d79171ec877082b5c3f56087c9ca
31.693333
94
0.649266
false
true
false
false
dobaduc/Swift-iTunesAPI-Demo
refs/heads/master
iTunesSearch/Backend/Models/ItunesSearchResultItem.swift
mit
1
// // ItunesSearchResultItem.swift // iTunesSearch // // Created by Duc DoBa on 1/7/16. // Copyright © 2016 Ducky Duke. All rights reserved. // import Foundation import ObjectMapper class ItunesSearchResultItem: Mappable { private(set) var id: String = "" private(set) var name: String = "" private(set) var summary: String = "" private(set) var price: Price = Price(amount: "0", currencyCode: "usd") private(set) var author = Author(id: "", name: "", itunesURL: "") private(set) var imageURL: String = "" private(set) var itunesURL: String = "" required init?(_ map: Map) { } func mapping(map: Map) { id <- map["trackId"] name <- map["trackName"] price = Price(amount: map["trackPrice"].value()!, currencyCode: map["currency"].value()!) author = Author(id: map["artistId"].value()!, name: map["artistName"].value()!, itunesURL: map["artistViewUrl"].value()!) imageURL <- map["artworkUrl100"] itunesURL <- map["trackViewUrl"] } }
972f587fe6d0127753ef02fa92153ac1
31.4375
129
0.616201
false
false
false
false
CoderAlexChan/AlexCocoa
refs/heads/master
Date/DateFormatter+date.swift
mit
1
// // DateFormatter+date.swift // Main // // Created by 陈文强 on 2017/5/17. // Copyright © 2017年 陈文强. All rights reserved. // import Foundation extension DateFormatter { public static var Custom: DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ" dateFormatter.timeZone = TimeZone.current dateFormatter.locale = Locale.current return dateFormatter } public static var ISO8601: DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" dateFormatter.timeZone = TimeZone.current dateFormatter.locale = Locale.current return dateFormatter } public static var RFC2822: DateFormatter { // "Sun, 19 Mar 2017 01:02:04 +0800" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" dateFormatter.timeZone = TimeZone.current dateFormatter.locale = Locale.current return dateFormatter } public static var CTime: DateFormatter { // "Sun Mar 19 01:04:21 2017" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE MMM d HH:mm:ss yyyy" dateFormatter.timeZone = TimeZone.current dateFormatter.locale = Locale.current return dateFormatter } }
8f433e3badd6c40dada414e4f2c7525e
29.717391
65
0.656051
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Tool/Sources/ToolKit/General/MainBundleProvider.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public enum MainBundleProvider { public static var mainBundle: Bundle = { var bundle = Bundle.main if bundle.bundleURL.pathExtension == "appex" { // If this is an App Extension (Today Extension), move up two directory levels // - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex let url = bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent() if let otherBundle = Bundle(url: url) { bundle = otherBundle } } return bundle }() } extension Bundle { /// Provides the builder number and version using this format: /// - Production builds: v1.0.0 (1) /// - Internal builds: v1.0.0 (commit hash) /// - Returns: A `String` representing the build number public static func versionAndBuildNumber() -> String { let plist: InfoPlist = MainBundleProvider.mainBundle.plist let hash = plist.COMMIT_HASH as? String ?? "" var title = "v\(plist.version)" if BuildFlag.isInternal { title = "\(title) (\(hash))" } else { title = "\(title) (\(plist.build))" } return title } }
b76cf35c9f55522a09b2848e286e9265
33.432432
94
0.601256
false
false
false
false
boxenjim/QRCode
refs/heads/master
Pods/QRCode/QRCode/QRCode.swift
mit
2
// // QRCode.swift // Example // // Created by Alexander Schuch on 25/01/15. // Copyright (c) 2015 Alexander Schuch. All rights reserved. // import UIKit public typealias 🔳 = QRCode /// QRCode generator public struct QRCode { /** The level of error correction. - Low: 7% - Medium: 15% - Quartile: 25% - High: 30% */ public enum ErrorCorrection: String { case Low = "L" case Medium = "M" case Quartile = "Q" case High = "H" } /// CIQRCodeGenerator generates 27x27px images per default private let DefaultQRCodeSize = CGSize(width: 27, height: 27) /// Data contained in the generated QRCode public let data: NSData /// Foreground color of the output /// Defaults to black public var color = CIColor(red: 0, green: 0, blue: 0) /// Background color of the output /// Defaults to white public var backgroundColor = CIColor(red: 1, green: 1, blue: 1) /// Size of the output public var size = CGSize(width: 200, height: 200) /// The error correction. The default value is `.Low`. public var errorCorrection = ErrorCorrection.Low // MARK: Init public init(_ data: NSData) { self.data = data } public init?(_ string: String) { if let data = string.dataUsingEncoding(NSISOLatin1StringEncoding) { self.data = data } else { return nil } } public init?(_ url: NSURL) { if let data = url.absoluteString.dataUsingEncoding(NSISOLatin1StringEncoding) { self.data = data } else { return nil } } // MARK: Generate QRCode /// The QRCode's UIImage representation public var image: UIImage? { guard let ciImage = ciImage else { return nil } return UIImage(CIImage: ciImage) } /// The QRCode's CIImage representation public var ciImage: CIImage? { // Generate QRCode guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil } qrFilter.setDefaults() qrFilter.setValue(data, forKey: "inputMessage") qrFilter.setValue(self.errorCorrection.rawValue, forKey: "inputCorrectionLevel") // Color code and background guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil } colorFilter.setDefaults() colorFilter.setValue(qrFilter.outputImage, forKey: "inputImage") colorFilter.setValue(color, forKey: "inputColor0") colorFilter.setValue(backgroundColor, forKey: "inputColor1") // Size let sizeRatioX = size.width / DefaultQRCodeSize.width let sizeRatioY = size.height / DefaultQRCodeSize.height let transform = CGAffineTransformMakeScale(sizeRatioX, sizeRatioY) guard let transformedImage = colorFilter.outputImage?.imageByApplyingTransform(transform) else { return nil } return transformedImage } }
686fad69b79c8e63e656c66f26b3c97c
27.803738
117
0.610318
false
false
false
false
joalbright/Relax
refs/heads/master
Sources/RelaxAPI.swift
mit
1
// // API.swift // Relax // // Created by Jo Albright on 1/11/16. // Copyright (c) 2016 Jo Albright. All rights reserved. // // import Foundation private let _s = API() open class API: Defaultable { open class func session() -> API { return _s } open var baseURL: String = "" open var authURL: String = "" open var debugPrint: Bool = false open var authBasic: [String:String] = [:] open var authHeader: String = "" open var authTokenKey: String = "Starter" open var authToken: String { get { return load(authTokenKey + "Token") ?? "" } set { save(authTokenKey + "Token",newValue) } } public enum RequestLibraries { case relax case alamoFire } open var requestLibrary: RequestLibraries = .relax public required init() { } open func url(_ endpoint: Endpoint) throws -> String { return try Relax.url(endpoint, api: self) } open func request(_ endpoint: Endpoint, response: @escaping Response) { Relax.request(endpoint, response: response, api: self) } open func start() { } open func update(_ c: (API) -> Void) -> Self { c(self); return self } open func loginDetails() -> (auth: Endpoint, authCode: Endpoint) { return (Endpoint(path: ""), Endpoint(path: "")) } public enum PrintEmotion: String { case debug = "🤔", warning = "🤢", error = "😡", deprecated = "🚧" } public func log(emotion: PrintEmotion = .debug, _ items: Any...) { if debugPrint { print(emotion.rawValue, "//////////////////////") for item in items { print(emotion.rawValue, "//////////////////////", item) } print(emotion.rawValue, "//////////////////////") } } }
e588784c715e8fce9d3ea2e6c4523f63
21.213483
103
0.505311
false
false
false
false
WilliamIzzo83/journal
refs/heads/master
journal/code/storage/EntriesDBTimelineReader.swift
bsd-3-clause
1
// // EntriesDBIterator.swift // journal // // Created by William Izzo on 21/01/2017. // Copyright © 2017 wizzo. All rights reserved. // import Foundation import RealmSwift /** * Provides a simple way to traverse the entries db as a timeline, starting from * the most recent to the oldest. */ class EntriesDBTimelineReader { let conf_ : EntriesDBConf! var entries_ : Results<DayDB> var current_index_ : Int init(conf:EntriesDBConf) { conf_ = conf // TODO: sort by date. entries_ = conf_.realm.objects(DayDB.self) current_index_ = 0 } deinit {} func count() -> Int { return entries_.count } func at(index:Int) -> DayDB { return entries_[index] } func entryAtDate(date:Date) -> DayDB? { let results = conf_.realm.objects(DayDB.self).filter({ (day_db) -> Bool in let day_date = Date(timeIntervalSince1970: day_db.timestamp) let day_date_comps = day_date.components() let input_date_comps = date.components() return input_date_comps.day! == day_date_comps.day! }) return results.first } func todayEntry() -> DayDB? { let today = Date() let results = conf_.realm.objects(DayDB.self).filter({ (day_db) -> Bool in let day_date = Date(timeIntervalSince1970: day_db.timestamp) let day_date_comps = day_date.components() let input_date_comps = today.components() return input_date_comps.day! == day_date_comps.day! }) return results.first } }
7f7cc9e4913a0b85cc45164fe4a25df4
26.393443
82
0.575703
false
false
false
false
ElvinChan/WeiXin
refs/heads/master
WeiXin/WeiXin/ChatController.swift
mit
1
// // ChatController.swift // WeiXin // // Created by chen.wenqiang on 15/7/30. // // import UIKit class ChatController: UITableViewController, MessageDelegate { @IBOutlet weak var msgTextField: UITextField! @IBOutlet weak var sendButton: UIBarButtonItem! @IBAction func composing(sender: UITextField) { // 构建XML元素message var xmlMessage = DDXMLElement.elementWithName("message") as! DDXMLElement // 增加属性 xmlMessage.addAttributeWithName("to", stringValue:toBuddyName) xmlMessage.addAttributeWithName("from", stringValue: NSUserDefaults.standardUserDefaults().stringForKey("weixinID")) // 构建正在输入元素 var composing = DDXMLElement.elementWithName("composing") as! DDXMLElement composing.addAttributeWithName("xmlns", stringValue: "http://jabber.org/protocol/chatstates") xmlMessage.addChild(composing) appDelegate().xs!.sendElement(xmlMessage) } @IBAction func send(sender: UIBarButtonItem) { // 获取聊天文本 let msgStr = msgTextField.text // 如果不为空 if (!msgStr.isEmpty) { // 构建XML元素message var xmlMessage = DDXMLElement.elementWithName("message") as! DDXMLElement // 增加属性 xmlMessage.addAttributeWithName("type", stringValue: "chat") xmlMessage.addAttributeWithName("to", stringValue:toBuddyName) xmlMessage.addAttributeWithName("from", stringValue: NSUserDefaults.standardUserDefaults().stringForKey("weixinID")) // 构建正文 var body = DDXMLElement.elementWithName("body") as! DDXMLElement body.setStringValue(msgStr) // 把正文加入到消息的子节点 xmlMessage.addChild(body) // 通过通道发送XML文本 appDelegate().xs!.sendElement(xmlMessage) // 清空聊天框 msgTextField.text = "" // 保存自己发送的消息 var msg = Message() msg.isSelf = true msg.body = msgStr // 加入到聊天记录 msgList.append(msg) self.tableView.reloadData() } } // 选择聊天的好友 var toBuddyName = "" // 聊天记录 var msgList = [Message]() // 收到消息 func newMsg(msg: Message) { // 对方正在输入 if (msg.isComposing) { self.navigationItem.title = "对方正在输入..." } else if (msg.body != "") { self.navigationItem.title = toBuddyName // 如果消息有正文,则加入到未读消息组,通知表格刷新 msgList.append(msg) // 通知表格刷新 self.tableView.reloadData() } } func appDelegate() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } override func viewDidLoad() { super.viewDidLoad() // 接管消息代理 appDelegate().messageDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return msgList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("chatCell", forIndexPath: indexPath) as! UITableViewCell // 取对应的消息 let msg = msgList[indexPath.row] // 对单元格的文本的格式做个调整 if (msg.isSelf) { cell.textLabel?.textAlignment = .Right cell.textLabel?.textColor = UIColor.grayColor() } else { cell.textLabel?.textColor = UIColor.orangeColor() } cell.textLabel?.text = msg.body return cell } }
628c447d15ed2767e95ce4cfc4f569d8
28.932331
128
0.582517
false
false
false
false
luowei/Swift-Samples
refs/heads/master
Swift-Samples/ViewController.swift
apache-2.0
1
// // ViewController.swift // Swift-Samples // // Created by luowei on 15/11/3. // Copyright © 2015年 wodedata. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { var titleLbl: UILabel? var progressVal: UILabel? var customVal: UITextField? var btn: UIButton? var progress: UIProgressView? var slide: UISlider? //KVO var text:String = ""{ willSet(newText) { print("About to set totalSteps to \(newText)") } didSet { self.textChanged(text) } } //当接收到spotlight传来的activity override func restoreUserActivityState(_ activity: NSUserActivity) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController!.navigationBar.isHidden = true self.tabBarController!.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController!.navigationBar.isHidden = false self.tabBarController!.tabBar.isHidden = false } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let selfFrame = self.view.frame let selfCenter = self.view.center; //状态标题 titleLbl = UILabel(frame: CGRect(x: selfCenter.x - 150, y: 30, width: 300, height: 60)) titleLbl?.backgroundColor = UIColor.green titleLbl?.textAlignment = .center titleLbl?.text = "Hello" self.view.addSubview(titleLbl!) //进度数值 progressVal = UILabel(frame: CGRect(x: selfCenter.x - 40, y: 120, width: 80, height: 60)) progressVal?.text = "0"; self.view.addSubview(progressVal!) //自定义数值设置框 customVal = UITextField(frame: CGRect(x: selfCenter.x - 65, y: 200, width: 60, height: 40)) customVal?.backgroundColor = UIColor.lightGray customVal?.textAlignment = .center customVal?.delegate = self self.view.addSubview(customVal!) //设置按钮 btn = UIButton(frame: CGRect(x: selfCenter.x + 5, y: 200, width: 60, height: 40)) btn?.backgroundColor = UIColor.gray btn?.layer.cornerRadius = 10 btn!.setTitle("设置", for: UIControlState()) btn!.addTarget(self, action: #selector(ViewController.setupSlideVal(_:)), for: .touchUpInside) self.view.addSubview(btn!) //进度条 progress = UIProgressView(progressViewStyle: .default) progress!.frame = CGRect(x: 20, y: 300, width: selfFrame.size.width - 40, height: 2) self.view.addSubview(progress!) //滑杆 slide = UISlider(frame: CGRect(x: 20, y: 400, width: selfFrame.size.width - 40, height: 30)) slide!.minimumValue = 0 slide!.maximumValue = 120 slide!.value = 0 self.view.addSubview(slide!); slide!.addTarget(self, action: #selector(ViewController.slideChanged(_:)), for: .valueChanged) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textChanged(_ text:String) { // UIAlertView(title: "Text改变了", message: "Text改变成了\(text)", delegate: nil, cancelButtonTitle: "OK").show() let alertController = UIAlertController(title: "Text改变了", message: "Text改变成了\(text)", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } //当输入框完成编辑 func textFieldShouldReturn(_ textField: UITextField) -> Bool{ textField.resignFirstResponder() self.textFieldDidChanged(textField) return true } func textFieldDidChanged(_ textField: UITextField) { if (textField.isEqual(customVal)) { progressVal!.text = textField.text!.isEmpty ? progressVal?.text:textField.text; slide!.value = Float((customVal?.text)!)! slide?.sendAction(#selector(ViewController.slideChanged(_:)), to: self, for: nil) } } //手动设置滑杆值 func setupSlideVal(_ btn: UIButton) { slide!.value = Float((customVal?.text)!)! slide?.sendAction(#selector(ViewController.slideChanged(_:)), to: self, for: nil) self.text = String(slide!.value) } //当滑杆值发生变化 func slideChanged(_ slide: UISlider) { progress?.progress = slide.value / 120 progressVal?.text = String(slide.value) let slideVal = CompareExpression.number(slide.value); //小于40,表示进度条在上传范围内 let val40 = CompareExpression.number(40); let uploadResult = compare(CompareExpression.compare(slideVal, val40)) switch Int(uploadResult) { //小于40 case CompareResult.Less.rawValue: //原型值的使用 self.titleLbl?.text = Status.Uploading.rawValue //等于40 case CompareResult.Equal.rawValue: self.titleLbl?.text = Status.Uploaded.rawValue //大于40 , 解压 case CompareResult.Great.rawValue: //大于40,小于80,表示进度条在上传范围内 let val80 = CompareExpression.number(80); let extractResult = compare(CompareExpression.compare(slideVal, val80)) switch Int(extractResult) { //小于80 case CompareResult.Less.rawValue: //原型值的使用 self.titleLbl?.text = Status.Extracting.rawValue //等于80 case CompareResult.Equal.rawValue: self.titleLbl?.text = Status.Extracted.rawValue //大于80 , 读取 case CompareResult.Great.rawValue: //大于80,小于100,表示在读取范围内 let val100 = CompareExpression.number(100); let readResult = compare(CompareExpression.compare(slideVal, val100)) switch Int(readResult) { //小于100 case CompareResult.Less.rawValue: //原型值的使用 self.titleLbl?.text = Status.Reading.rawValue //等于100 case CompareResult.Equal.rawValue: self.titleLbl?.text = Status.Readed.rawValue //大于100 case CompareResult.Great.rawValue: let text = Flag.read("已经读取完毕,正在执行数据操作...") self.titleLbl?.text = String(describing: text) default:break } default:break } default:break } } } //相关值 enum Flag { //上传 case upload(String) //解压 case extract(String) //读取 case read(String) //成功或失败 case isOK(Int) } //原始值(默认值) enum Status: String { case Uploading = "正在上传" case Uploaded = "上传完毕" case Extracting = "正在解压" case Extracted = "解压完毕" case Reading = "正在读取" case Readed = "读取完毕" } //递归枚举 enum CompareExpression { case number(Float) indirect case compare(CompareExpression, CompareExpression) } func compare(_ expression: CompareExpression) -> Float { switch expression { //直接返回相关值 case .number(let value): return value //比较大小 case .compare(let left, let right): if compare(left) > compare(right) { return 1 } else if compare(left) < compare(right) { return -1 } else { return 0 } } } //结构体的使用 struct CompareResult: OptionSet { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } static let Less = CompareResult(rawValue: -1) static let Equal = CompareResult(rawValue: 0) static let Great = CompareResult(rawValue: 1) static let LessOrEqual: CompareResult = [Less, Equal] static let GreatOrEqual: CompareResult = [Great, Equal] }
6370577850505cf570b2ce915e0b60a6
27.020619
139
0.597621
false
false
false
false
liuweicode/LinkimFoundation
refs/heads/master
Example/LinkimFoundation/MainView.swift
mit
1
// // MainView.swift // LinkimFoundation // // Created by 刘伟 on 16/6/30. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit class MainView: UIView { let advertView:AdvertView = { let advertView = AdvertView() return advertView }() let tableView:UITableView = { let tableView = UITableView() tableView.cellLineHidden() return tableView }() init() { super.init(frame: CGRectZero) tableView.tableHeaderView = advertView addSubview(tableView) tableView.snp_makeConstraints { (make) in make.edges.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
8367732f1a705c4bfd0b15a94c3216a1
19.25641
59
0.593671
false
false
false
false
kickerchen/CustomTransition
refs/heads/master
BoulderTransition/CustomTransition.swift
mit
1
// // CustomTransition.swift // BoulderTransition // // Created by CHENCHIAN on 5/26/15. // Copyright (c) 2015 KICKERCHEN. All rights reserved. // import Foundation import UIKit class CustomTransition: NSObject, UIViewControllerAnimatedTransitioning { let duration = 1.0 var presenting = true var originFrame = CGRect.zeroRect var selectedImageView: UIImageView? func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() // get views let destinationView = transitionContext.viewForKey(UITransitionContextToViewKey)! let climberProfileView = presenting ? destinationView : transitionContext.viewForKey(UITransitionContextFromViewKey)! // get view controllers let climberProfileViewController = presenting ? transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ClimberProfileViewController : transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ClimberProfileViewController // get frames let initialFrame = presenting ? originFrame : climberProfileView.frame let finalFrame = presenting ? climberProfileView.frame : originFrame // derive factors let xScaleFactor = originFrame.width / climberProfileView.frame.width let yScaleFactor = originFrame.height / climberProfileView.frame.height // construct transform let downScaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor) if presenting { // scale down climberProfileView.transform = downScaleTransform // move climber profile view to initial position before animation climberProfileView.center = CGPoint( x: CGRectGetMidX(initialFrame), y: CGRectGetMidY(initialFrame)) climberProfileView.clipsToBounds = true } else { // hide tapped images during transitions so it really looks like they grow to take up the full screen selectedImageView?.hidden = true } // hide climber description climberProfileViewController.setDescriptionViewAlpha(0.0) containerView.addSubview(destinationView) containerView.bringSubviewToFront(climberProfileView) // perform animation UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: nil, animations: { climberProfileView.transform = self.presenting ? CGAffineTransformIdentity : downScaleTransform climberProfileView.center = CGPoint( x: CGRectGetMidX(finalFrame), y: CGRectGetMidY(finalFrame) ) }, completion: { _ in if !self.presenting { // show tapped images self.selectedImageView?.hidden = false } // fade in climber description after pop-out animation if self.presenting { UIView.animateWithDuration(0.5, animations: { climberProfileViewController.setDescriptionViewAlpha(0.5) }) } transitionContext.completeTransition(true) }) } }
70de6bdab564da1e4df71eb7ab88dee6
37.26
283
0.620654
false
false
false
false
kazuhiro49/StringStylizer
refs/heads/master
StringStylizer/StringStylizerFontName.swift
mit
1
// // StringStylizerFontName.swift // // // Copyright (c) 2016 Kazuhiro Hayashi // // 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 /** available font names in iOS App This enum is generated from the following script ``` let name = UIFont.familyNames() .flatMap { UIFont.fontNamesForFamilyName($0) } .map { "case \($0.stringByReplacingOccurrencesOfString("-", withString: "_")) = \"\($0)\"" } .joinWithSeparator("\n") ``` */ public enum StringStylizerFontName: String { case Copperplate_Light = "Copperplate-Light" case Copperplate = "Copperplate" case Copperplate_Bold = "Copperplate-Bold" case IowanOldStyle_Italic = "IowanOldStyle-Italic" case IowanOldStyle_Roman = "IowanOldStyle-Roman" case IowanOldStyle_BoldItalic = "IowanOldStyle-BoldItalic" case IowanOldStyle_Bold = "IowanOldStyle-Bold" case KohinoorTelugu_Regular = "KohinoorTelugu-Regular" case KohinoorTelugu_Medium = "KohinoorTelugu-Medium" case KohinoorTelugu_Light = "KohinoorTelugu-Light" case Thonburi = "Thonburi" case Thonburi_Bold = "Thonburi-Bold" case Thonburi_Light = "Thonburi-Light" case CourierNewPS_BoldMT = "CourierNewPS-BoldMT" case CourierNewPS_ItalicMT = "CourierNewPS-ItalicMT" case CourierNewPSMT = "CourierNewPSMT" case CourierNewPS_BoldItalicMT = "CourierNewPS-BoldItalicMT" case GillSans_Italic = "GillSans-Italic" case GillSans_Bold = "GillSans-Bold" case GillSans_BoldItalic = "GillSans-BoldItalic" case GillSans_LightItalic = "GillSans-LightItalic" case GillSans = "GillSans" case GillSans_Light = "GillSans-Light" case GillSans_SemiBold = "GillSans-SemiBold" case GillSans_SemiBoldItalic = "GillSans-SemiBoldItalic" case GillSans_UltraBold = "GillSans-UltraBold" case AppleSDGothicNeo_Bold = "AppleSDGothicNeo-Bold" case AppleSDGothicNeo_Thin = "AppleSDGothicNeo-Thin" case AppleSDGothicNeo_UltraLight = "AppleSDGothicNeo-UltraLight" case AppleSDGothicNeo_Regular = "AppleSDGothicNeo-Regular" case AppleSDGothicNeo_Light = "AppleSDGothicNeo-Light" case AppleSDGothicNeo_Medium = "AppleSDGothicNeo-Medium" case AppleSDGothicNeo_SemiBold = "AppleSDGothicNeo-SemiBold" case MarkerFelt_Thin = "MarkerFelt-Thin" case MarkerFelt_Wide = "MarkerFelt-Wide" case AvenirNextCondensed_BoldItalic = "AvenirNextCondensed-BoldItalic" case AvenirNextCondensed_Heavy = "AvenirNextCondensed-Heavy" case AvenirNextCondensed_Medium = "AvenirNextCondensed-Medium" case AvenirNextCondensed_Regular = "AvenirNextCondensed-Regular" case AvenirNextCondensed_HeavyItalic = "AvenirNextCondensed-HeavyItalic" case AvenirNextCondensed_MediumItalic = "AvenirNextCondensed-MediumItalic" case AvenirNextCondensed_Italic = "AvenirNextCondensed-Italic" case AvenirNextCondensed_UltraLightItalic = "AvenirNextCondensed-UltraLightItalic" case AvenirNextCondensed_UltraLight = "AvenirNextCondensed-UltraLight" case AvenirNextCondensed_DemiBold = "AvenirNextCondensed-DemiBold" case AvenirNextCondensed_Bold = "AvenirNextCondensed-Bold" case AvenirNextCondensed_DemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic" case TamilSangamMN = "TamilSangamMN" case TamilSangamMN_Bold = "TamilSangamMN-Bold" case HelveticaNeue_Italic = "HelveticaNeue-Italic" case HelveticaNeue_Bold = "HelveticaNeue-Bold" case HelveticaNeue_UltraLight = "HelveticaNeue-UltraLight" case HelveticaNeue_CondensedBlack = "HelveticaNeue-CondensedBlack" case HelveticaNeue_BoldItalic = "HelveticaNeue-BoldItalic" case HelveticaNeue_CondensedBold = "HelveticaNeue-CondensedBold" case HelveticaNeue_Medium = "HelveticaNeue-Medium" case HelveticaNeue_Light = "HelveticaNeue-Light" case HelveticaNeue_Thin = "HelveticaNeue-Thin" case HelveticaNeue_ThinItalic = "HelveticaNeue-ThinItalic" case HelveticaNeue_LightItalic = "HelveticaNeue-LightItalic" case HelveticaNeue_UltraLightItalic = "HelveticaNeue-UltraLightItalic" case HelveticaNeue_MediumItalic = "HelveticaNeue-MediumItalic" case HelveticaNeue = "HelveticaNeue" case GurmukhiMN_Bold = "GurmukhiMN-Bold" case GurmukhiMN = "GurmukhiMN" case TimesNewRomanPSMT = "TimesNewRomanPSMT" case TimesNewRomanPS_BoldItalicMT = "TimesNewRomanPS-BoldItalicMT" case TimesNewRomanPS_ItalicMT = "TimesNewRomanPS-ItalicMT" case TimesNewRomanPS_BoldMT = "TimesNewRomanPS-BoldMT" case Georgia_BoldItalic = "Georgia-BoldItalic" case Georgia = "Georgia" case Georgia_Italic = "Georgia-Italic" case Georgia_Bold = "Georgia-Bold" case AppleColorEmoji = "AppleColorEmoji" case ArialRoundedMTBold = "ArialRoundedMTBold" case Kailasa_Bold = "Kailasa-Bold" case Kailasa = "Kailasa" case KohinoorDevanagari_Light = "KohinoorDevanagari-Light" case KohinoorDevanagari_Regular = "KohinoorDevanagari-Regular" case KohinoorDevanagari_Semibold = "KohinoorDevanagari-Semibold" case KohinoorBangla_Semibold = "KohinoorBangla-Semibold" case KohinoorBangla_Regular = "KohinoorBangla-Regular" case KohinoorBangla_Light = "KohinoorBangla-Light" case ChalkboardSE_Bold = "ChalkboardSE-Bold" case ChalkboardSE_Light = "ChalkboardSE-Light" case ChalkboardSE_Regular = "ChalkboardSE-Regular" case SinhalaSangamMN_Bold = "SinhalaSangamMN-Bold" case SinhalaSangamMN = "SinhalaSangamMN" case PingFangTC_Medium = "PingFangTC-Medium" case PingFangTC_Regular = "PingFangTC-Regular" case PingFangTC_Light = "PingFangTC-Light" case PingFangTC_Ultralight = "PingFangTC-Ultralight" case PingFangTC_Semibold = "PingFangTC-Semibold" case PingFangTC_Thin = "PingFangTC-Thin" case GujaratiSangamMN_Bold = "GujaratiSangamMN-Bold" case GujaratiSangamMN = "GujaratiSangamMN" case DamascusLight = "DamascusLight" case DamascusBold = "DamascusBold" case DamascusSemiBold = "DamascusSemiBold" case DamascusMedium = "DamascusMedium" case Damascus = "Damascus" case Noteworthy_Light = "Noteworthy-Light" case Noteworthy_Bold = "Noteworthy-Bold" case GeezaPro = "GeezaPro" case GeezaPro_Bold = "GeezaPro-Bold" case Avenir_Medium = "Avenir-Medium" case Avenir_HeavyOblique = "Avenir-HeavyOblique" case Avenir_Book = "Avenir-Book" case Avenir_Light = "Avenir-Light" case Avenir_Roman = "Avenir-Roman" case Avenir_BookOblique = "Avenir-BookOblique" case Avenir_Black = "Avenir-Black" case Avenir_MediumOblique = "Avenir-MediumOblique" case Avenir_BlackOblique = "Avenir-BlackOblique" case Avenir_Heavy = "Avenir-Heavy" case Avenir_LightOblique = "Avenir-LightOblique" case Avenir_Oblique = "Avenir-Oblique" case AcademyEngravedLetPlain = "AcademyEngravedLetPlain" case DiwanMishafi = "DiwanMishafi" case Futura_CondensedMedium = "Futura-CondensedMedium" case Futura_CondensedExtraBold = "Futura-CondensedExtraBold" case Futura_Medium = "Futura-Medium" case Futura_MediumItalic = "Futura-MediumItalic" case Farah = "Farah" case KannadaSangamMN = "KannadaSangamMN" case KannadaSangamMN_Bold = "KannadaSangamMN-Bold" case ArialHebrew_Bold = "ArialHebrew-Bold" case ArialHebrew_Light = "ArialHebrew-Light" case ArialHebrew = "ArialHebrew" case ArialMT = "ArialMT" case Arial_BoldItalicMT = "Arial-BoldItalicMT" case Arial_BoldMT = "Arial-BoldMT" case Arial_ItalicMT = "Arial-ItalicMT" case PartyLetPlain = "PartyLetPlain" case Chalkduster = "Chalkduster" case HoeflerText_Italic = "HoeflerText-Italic" case HoeflerText_Regular = "HoeflerText-Regular" case HoeflerText_Black = "HoeflerText-Black" case HoeflerText_BlackItalic = "HoeflerText-BlackItalic" case Optima_Regular = "Optima-Regular" case Optima_ExtraBlack = "Optima-ExtraBlack" case Optima_BoldItalic = "Optima-BoldItalic" case Optima_Italic = "Optima-Italic" case Optima_Bold = "Optima-Bold" case Palatino_Bold = "Palatino-Bold" case Palatino_Roman = "Palatino-Roman" case Palatino_BoldItalic = "Palatino-BoldItalic" case Palatino_Italic = "Palatino-Italic" case LaoSangamMN = "LaoSangamMN" case MalayalamSangamMN_Bold = "MalayalamSangamMN-Bold" case MalayalamSangamMN = "MalayalamSangamMN" case AlNile_Bold = "AlNile-Bold" case AlNile = "AlNile" case BradleyHandITCTT_Bold = "BradleyHandITCTT-Bold" case PingFangHK_Ultralight = "PingFangHK-Ultralight" case PingFangHK_Semibold = "PingFangHK-Semibold" case PingFangHK_Thin = "PingFangHK-Thin" case PingFangHK_Light = "PingFangHK-Light" case PingFangHK_Regular = "PingFangHK-Regular" case PingFangHK_Medium = "PingFangHK-Medium" case Trebuchet_BoldItalic = "Trebuchet-BoldItalic" case TrebuchetMS = "TrebuchetMS" case TrebuchetMS_Bold = "TrebuchetMS-Bold" case TrebuchetMS_Italic = "TrebuchetMS-Italic" case Helvetica_Bold = "Helvetica-Bold" case Helvetica = "Helvetica" case Helvetica_LightOblique = "Helvetica-LightOblique" case Helvetica_Oblique = "Helvetica-Oblique" case Helvetica_BoldOblique = "Helvetica-BoldOblique" case Helvetica_Light = "Helvetica-Light" case Courier_BoldOblique = "Courier-BoldOblique" case Courier = "Courier" case Courier_Bold = "Courier-Bold" case Courier_Oblique = "Courier-Oblique" case Cochin_Bold = "Cochin-Bold" case Cochin = "Cochin" case Cochin_Italic = "Cochin-Italic" case Cochin_BoldItalic = "Cochin-BoldItalic" case HiraMinProN_W6 = "HiraMinProN-W6" case HiraMinProN_W3 = "HiraMinProN-W3" case DevanagariSangamMN = "DevanagariSangamMN" case DevanagariSangamMN_Bold = "DevanagariSangamMN-Bold" case OriyaSangamMN = "OriyaSangamMN" case OriyaSangamMN_Bold = "OriyaSangamMN-Bold" case SnellRoundhand_Bold = "SnellRoundhand-Bold" case SnellRoundhand = "SnellRoundhand" case SnellRoundhand_Black = "SnellRoundhand-Black" case ZapfDingbatsITC = "ZapfDingbatsITC" case BodoniSvtyTwoITCTT_Bold = "BodoniSvtyTwoITCTT-Bold" case BodoniSvtyTwoITCTT_Book = "BodoniSvtyTwoITCTT-Book" case BodoniSvtyTwoITCTT_BookIta = "BodoniSvtyTwoITCTT-BookIta" case Verdana_Italic = "Verdana-Italic" case Verdana_BoldItalic = "Verdana-BoldItalic" case Verdana = "Verdana" case Verdana_Bold = "Verdana-Bold" case AmericanTypewriter_CondensedLight = "AmericanTypewriter-CondensedLight" case AmericanTypewriter = "AmericanTypewriter" case AmericanTypewriter_CondensedBold = "AmericanTypewriter-CondensedBold" case AmericanTypewriter_Light = "AmericanTypewriter-Light" case AmericanTypewriter_Bold = "AmericanTypewriter-Bold" case AmericanTypewriter_Condensed = "AmericanTypewriter-Condensed" case AvenirNext_UltraLight = "AvenirNext-UltraLight" case AvenirNext_UltraLightItalic = "AvenirNext-UltraLightItalic" case AvenirNext_Bold = "AvenirNext-Bold" case AvenirNext_BoldItalic = "AvenirNext-BoldItalic" case AvenirNext_DemiBold = "AvenirNext-DemiBold" case AvenirNext_DemiBoldItalic = "AvenirNext-DemiBoldItalic" case AvenirNext_Medium = "AvenirNext-Medium" case AvenirNext_HeavyItalic = "AvenirNext-HeavyItalic" case AvenirNext_Heavy = "AvenirNext-Heavy" case AvenirNext_Italic = "AvenirNext-Italic" case AvenirNext_Regular = "AvenirNext-Regular" case AvenirNext_MediumItalic = "AvenirNext-MediumItalic" case Baskerville_Italic = "Baskerville-Italic" case Baskerville_SemiBold = "Baskerville-SemiBold" case Baskerville_BoldItalic = "Baskerville-BoldItalic" case Baskerville_SemiBoldItalic = "Baskerville-SemiBoldItalic" case Baskerville_Bold = "Baskerville-Bold" case Baskerville = "Baskerville" case KhmerSangamMN = "KhmerSangamMN" case Didot_Italic = "Didot-Italic" case Didot_Bold = "Didot-Bold" case Didot = "Didot" case SavoyeLetPlain = "SavoyeLetPlain" case BodoniOrnamentsITCTT = "BodoniOrnamentsITCTT" case Symbol = "Symbol" case Menlo_Italic = "Menlo-Italic" case Menlo_Bold = "Menlo-Bold" case Menlo_Regular = "Menlo-Regular" case Menlo_BoldItalic = "Menlo-BoldItalic" case BodoniSvtyTwoSCITCTT_Book = "BodoniSvtyTwoSCITCTT-Book" case Papyrus = "Papyrus" case Papyrus_Condensed = "Papyrus-Condensed" case HiraginoSans_W3 = "HiraginoSans-W3" case HiraginoSans_W6 = "HiraginoSans-W6" case PingFangSC_Ultralight = "PingFangSC-Ultralight" case PingFangSC_Regular = "PingFangSC-Regular" case PingFangSC_Semibold = "PingFangSC-Semibold" case PingFangSC_Thin = "PingFangSC-Thin" case PingFangSC_Light = "PingFangSC-Light" case PingFangSC_Medium = "PingFangSC-Medium" case EuphemiaUCAS_Italic = "EuphemiaUCAS-Italic" case EuphemiaUCAS = "EuphemiaUCAS" case EuphemiaUCAS_Bold = "EuphemiaUCAS-Bold" case Zapfino = "Zapfino" case BodoniSvtyTwoOSITCTT_Book = "BodoniSvtyTwoOSITCTT-Book" case BodoniSvtyTwoOSITCTT_Bold = "BodoniSvtyTwoOSITCTT-Bold" case BodoniSvtyTwoOSITCTT_BookIt = "BodoniSvtyTwoOSITCTT-BookIt" // added by hand case HiraKakuProN_W6 = "HiraKakuProN-W6" case HiraKakuProN_W3 = "HiraKakuProN-W3" }
cf4f2fce0667b82bb2a7355fc36953aa
48.013746
108
0.746389
false
false
false
false
mgadda/zig
refs/heads/master
Sources/MessagePackEncoder/MessagePackEncodingStorage.swift
mit
1
// // MessagePackEncodingStorage.swift // zigPackageDescription // // Created by Matt Gadda on 9/27/17. // import Foundation import MessagePack internal struct MessagePackEncodingStorage { var containers: [BoxedValue] = [] init() {} var count: Int { return containers.count } mutating func pushKeyedContainer() -> MutableDictionaryReference<BoxedValue, BoxedValue> { let dictRef = MutableDictionaryReference<BoxedValue, BoxedValue>() let boxedDictionary = BoxedValue.map(dictRef) self.containers.append(boxedDictionary) return dictRef } mutating func pushUnkeyedContainer() -> MutableArrayReference<BoxedValue> { let arrayRef = MutableArrayReference<BoxedValue>() let boxedArray = BoxedValue.array(arrayRef) self.containers.append(boxedArray) return arrayRef } mutating func push(container: BoxedValue) { self.containers.append(container) } mutating func popContainer() -> BoxedValue { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.popLast()! } }
fe9af840e9898a26600336ca5b7d23cb
25.775
92
0.735761
false
false
false
false
Norod/Filterpedia
refs/heads/swift-3
Filterpedia/customFilters/ColorDirectedBlur.swift
gpl-3.0
1
// // ColorDirectedBlur.swift // Filterpedia // // Created by Simon Gladman on 29/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage /// **HomogeneousColorBlur** /// /// _A filter that applies a box filter with circular kernel to similar colors based /// on distance in a three dimensional RGB configuration space_ /// /// - Authors: Simon Gladman /// - Date: May 2016 class HomogeneousColorBlur: CIFilter { var inputImage: CIImage? var inputColorThreshold: CGFloat = 0.2 var inputRadius: CGFloat = 10 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Homogeneous Color Blur", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputColorThreshold": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.2, kCIAttributeDisplayName: "Color Threshold", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Radius", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 40, kCIAttributeType: kCIAttributeTypeScalar], ] } let kernel = CIKernel(string: "kernel vec4 colorDirectedBlurKernel(sampler image, float radius, float threshold)" + "{" + " int r = int(radius);" + " float n = 0.0;" + " vec2 d = destCoord();" + " vec3 thisPixel = sample(image, samplerCoord(image)).rgb;" + " vec3 accumulator = vec3(0.0, 0.0, 0.0);" + " for (int x = -r; x <= r; x++) " + " { " + " for (int y = -r; y <= r; y++) " + " { " + " vec3 offsetPixel = sample(image, samplerTransform(image, d + vec2(x ,y))).rgb; \n" + " float distanceMultiplier = step(length(vec2(x,y)), radius); \n" + " float colorMultiplier = step(distance(offsetPixel, thisPixel), threshold); \n" + " accumulator += offsetPixel * distanceMultiplier * colorMultiplier; \n" + " n += distanceMultiplier * colorMultiplier; \n" + " }" + " }" + " return vec4(accumulator / n, 1.0); " + "}") override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = kernel else { return nil } let arguments = [inputImage, inputRadius, inputColorThreshold * sqrt(3.0)] as [Any] return kernel.apply( withExtent: inputImage.extent, roiCallback: { (index, rect) in return rect }, arguments: arguments) } } /// **ColorDirectedBlur** /// /// _A filter that applies a box blur based on a surrounding quadrant of the nearest color._ /// /// Uses a similar approach to Kuwahara Filter - creates averages of squares of pixels /// in the north east, north west, south east and south west of the current pixel and /// outputs the box blur of the quadrant with the closest color distance to the current /// pixel. A threshold parameter prevents any blurring if the distances are too great. /// /// The final effect blurs within areas of a similar color while keeeping edge detail. /// /// - Authors: Simon Gladman /// - Date: April 2016 class ColorDirectedBlur: CIFilter { var inputImage: CIImage? var inputThreshold: CGFloat = 0.5 var inputIterations: CGFloat = 4 var inputRadius: CGFloat = 10 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Color Directed Blur", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputThreshold": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.5, kCIAttributeDisplayName: "Threshold", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputIterations": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 4, kCIAttributeDisplayName: "Iterations", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar], "inputRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Radius", kCIAttributeMin: 3, kCIAttributeSliderMin: 3, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], ] } let kernel = CIKernel(string: "kernel vec4 colorDirectedBlurKernel(sampler image, float radius, float threshold)" + "{" + " int r = int(radius);" + " float n = 0.0;" + " vec2 d = destCoord();" + " vec3 thisPixel = sample(image, samplerCoord(image)).rgb;" + " vec3 nwAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 neAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 swAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 seAccumulator = vec3(0.0, 0.0, 0.0);" + " for (int x = 0; x <= r; x++) " + " { " + " for (int y = 0; y <= r; y++) " + " { " + " nwAccumulator += sample(image, samplerTransform(image, d + vec2(-x ,-y))).rgb; " + " neAccumulator += sample(image, samplerTransform(image, d + vec2(x ,-y))).rgb; " + " swAccumulator += sample(image, samplerTransform(image, d + vec2(-x ,y))).rgb; " + " seAccumulator += sample(image, samplerTransform(image, d + vec2(x ,y))).rgb; " + " n = n + 1.0; " + " } " + " } " + " nwAccumulator /= n;" + " neAccumulator /= n;" + " swAccumulator /= n;" + " seAccumulator /= n;" + " float nwDiff = distance(thisPixel, nwAccumulator); " + " float neDiff = distance(thisPixel, neAccumulator); " + " float swDiff = distance(thisPixel, swAccumulator); " + " float seDiff = distance(thisPixel, seAccumulator); " + " if (nwDiff >= threshold && neDiff >= threshold && swDiff >= threshold && seDiff >= threshold)" + " {return vec4(thisPixel, 1.0);}" + " if(nwDiff < neDiff && nwDiff < swDiff && nwDiff < seDiff) " + " { return vec4 (nwAccumulator, 1.0 ); }" + " if(neDiff < nwDiff && neDiff < swDiff && neDiff < seDiff) " + " { return vec4 (neAccumulator, 1.0 ); }" + " if(swDiff < nwDiff && swDiff < neDiff && swDiff < seDiff) " + " { return vec4 (swAccumulator, 1.0 ); }" + " if(seDiff < nwDiff && seDiff < neDiff && seDiff < swDiff) " + " { return vec4 (seAccumulator, 1.0 ); }" + " return vec4(thisPixel, 1.0); " + "}" ) override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = kernel else { return nil } let accumulator = CIImageAccumulator(extent: inputImage.extent, format: kCIFormatARGB8) accumulator?.setImage(inputImage) for _ in 0 ... Int(inputIterations) { let final = kernel.apply(withExtent: inputImage.extent, roiCallback: { (index, rect) in return rect }, arguments: [(accumulator?.image())!, inputRadius, 1 - inputThreshold]) accumulator?.setImage(final!) } return accumulator?.image() } }
54e7620421961a3329c2da041b847fe2
37.8
117
0.542184
false
false
false
false
kaojohnny/CoreStore
refs/heads/master
CoreStoreDemo/CoreStoreDemo/Fetching and Querying Demo/QueryingResultsViewController.swift
mit
1
// // QueryingResultsViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/17. // Copyright © 2015 John Rommel Estropia. All rights reserved. // import UIKit class QueryingResultsViewController: UITableViewController { // MARK: Public func setValue(value: AnyObject?, title: String) { switch value { case (let array as [AnyObject])?: self.values = array.map { (item: AnyObject) -> (title: String, detail: String) in ( title: item.description, detail: String(reflecting: item.dynamicType) ) } case let item?: self.values = [ ( title: item.description, detail: String(reflecting: item.dynamicType) ) ] default: self.values = [] } self.sectionTitle = title self.tableView?.reloadData() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 60 self.tableView.rowHeight = UITableViewAutomaticDimension } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.values.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) let value = self.values[indexPath.row] cell.textLabel?.text = value.title cell.detailTextLabel?.text = value.detail return cell } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sectionTitle } // MARK: Private var values: [(title: String, detail: String)] = [] var sectionTitle: String? }
a5ab1705c3ca0666e59755dba8f7164f
24.738636
118
0.559382
false
false
false
false
ben-ng/swift
refs/heads/master
test/Constraints/casts.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift class B { init() {} } class D : B { override init() { super.init() } } var seven : Double = 7 var pair : (Int, Double) = (1, 2) var closure : (Int, Int) -> Int = { $0 + $1 } var d_as_b : B = D() var b_as_d = B() as! D var bad_b_as_d : D = B() // expected-error{{cannot convert value of type 'B' to specified type 'D'}} var d = D() var b = B() var d_as_b_2 : B = d var b_as_d_2 = b as! D var b_is_d:Bool = B() is D // FIXME: Poor diagnostic below. var bad_d_is_b:Bool = D() is B // expected-warning{{always true}} func base_class_archetype_casts<T : B>(_ t: T) { var _ : B = t _ = B() as! T var _ : T = B() // expected-error{{'B' is not convertible to 'T'; did you mean to use 'as!' to force downcast?}} let b = B() _ = b as! T var _:Bool = B() is T var _:Bool = b is T var _:Bool = t is B // expected-warning{{always true}} _ = t as! D } protocol P1 { func p1() } protocol P2 { func p2() } struct S1 : P1 { func p1() {} } class C1 : P1 { func p1() {} } class D1 : C1 {} struct S2 : P2 { func p2() {} } struct S3 {} struct S12 : P1, P2 { func p1() {} func p2() {} } func protocol_archetype_casts<T : P1>(_ t: T, p1: P1, p2: P2, p12: P1 & P2) { // Coercions. var _ : P1 = t var _ : P2 = t // expected-error{{value of type 'T' does not conform to specified type 'P2'}} // Checked unconditional casts. _ = p1 as! T _ = p2 as! T _ = p12 as! T _ = t as! S1 _ = t as! S12 _ = t as! C1 _ = t as! D1 _ = t as! S2 _ = S1() as! T _ = S12() as! T _ = C1() as! T _ = D1() as! T _ = S2() as! T // Type queries. var _:Bool = p1 is T var _:Bool = p2 is T var _:Bool = p12 is T var _:Bool = t is S1 var _:Bool = t is S12 var _:Bool = t is C1 var _:Bool = t is D1 var _:Bool = t is S2 } func protocol_concrete_casts(_ p1: P1, p2: P2, p12: P1 & P2) { // Checked unconditional casts. _ = p1 as! S1 _ = p1 as! C1 _ = p1 as! D1 _ = p1 as! S12 _ = p1 as! P1 & P2 _ = p2 as! S1 _ = p12 as! S1 _ = p12 as! S2 _ = p12 as! S12 _ = p12 as! S3 // Type queries. var _:Bool = p1 is S1 var _:Bool = p1 is C1 var _:Bool = p1 is D1 var _:Bool = p1 is S12 var _:Bool = p1 is P1 & P2 var _:Bool = p2 is S1 var _:Bool = p12 is S1 var _:Bool = p12 is S2 var _:Bool = p12 is S12 var _:Bool = p12 is S3 } func conditional_cast(_ b: B) -> D? { return b as? D } @objc protocol ObjCProto1 {} @objc protocol ObjCProto2 {} protocol NonObjCProto : class {} @objc class ObjCClass {} class NonObjCClass {} func objc_protocol_casts(_ op1: ObjCProto1, opn: NonObjCProto) { _ = ObjCClass() as! ObjCProto1 _ = ObjCClass() as! ObjCProto2 _ = ObjCClass() as! ObjCProto1 & ObjCProto2 _ = ObjCClass() as! NonObjCProto _ = ObjCClass() as! ObjCProto1 & NonObjCProto _ = op1 as! ObjCProto1 & ObjCProto2 _ = op1 as! ObjCProto2 _ = op1 as! ObjCProto1 & NonObjCProto _ = opn as! ObjCProto1 _ = NonObjCClass() as! ObjCProto1 } func dynamic_lookup_cast(_ dl: AnyObject) { _ = dl as! ObjCProto1 _ = dl as! ObjCProto2 _ = dl as! ObjCProto1 & ObjCProto2 } // Cast to subclass with generic parameter inference class C2<T> : B { } class C3<T> : C2<[T]> { func f(_ x: T) { } } var c2i : C2<[Int]> = C3() var c3iOpt = c2i as? C3 c3iOpt?.f(5) var b1 = c2i is C3 var c2f: C2<Float>? = b as? C2 var c2f2: C2<[Float]>? = b as! C3 // <rdar://problem/15633178> var f: (Float) -> Float = { $0 as Float } var f2: (B) -> Bool = { $0 is D } func metatype_casts<T, U>(_ b: B.Type, t:T.Type, u: U.Type) { _ = b is D.Type _ = T.self is U.Type _ = type(of: T.self) is U.Type.Type _ = type(of: b) is D.Type // expected-warning{{always fails}} _ = b is D.Type.Type // expected-warning{{always fails}} } // <rdar://problem/17017851> func forcedDowncastToOptional(_ b: B) { var dOpt: D? = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}} // expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{22-23=?}} // expected-note@-2{{add parentheses around the cast to silence this warning}}{{18-18=(}}{{25-25=)}} dOpt = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}} // expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{14-15=?}} // expected-note@-2{{add parentheses around the cast to silence this warning}}{{10-10=(}}{{17-17=)}} dOpt = (b as! D) _ = dOpt } _ = b1 as Int // expected-error {{cannot convert value of type 'Bool' to type 'Int' in coercion}} _ = seven as Int // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}}
30e996d192474d8b8093da95bda0620b
21.557692
118
0.576726
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/00958-swift-nominaltypedecl-getdeclaredtypeincontext.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 func q<dc>() -> (dc, dc -> dc) -> dc { t m t.w = { } { dc) { k } } protocol q { } protocol A { func b(b: X.s) { } y(m: x) { } func v<t>() -> [dc<t>] { } class b<k : dc, w : dc where k.dc == w> : v { } class b<k, w> { } protocol dc { } class A: A { } class r : C { } func ^(v: q, o) -> o { } class v<q : b, dc : b where q.t == dc> { } protocol b { } struct dc<k : b> : b
a538489c6781550e434d509e24471db1
17.756098
79
0.602081
false
false
false
false
prolificinteractive/simcoe
refs/heads/master
Simcoe/mParticle/MPCommerceEvent+Simcoe.swift
mit
1
// // MPCommerceEvent+Simcoe.swift // Simcoe // // Created by Michael Campbell on 10/25/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import mParticle_Apple_SDK extension MPCommerceEvent { /// A convenience initializer for MPCommerceEvent. /// /// - Parameters: /// - eventType: The event type. /// - products: The products. /// - eventProperties: The event properties. internal convenience init(eventType: MPCommerceEventAction, products: [MPProduct], eventProperties: Properties?) { self.init(action: eventType) self.addProducts(products) guard let eventProperties = eventProperties else { return } if let checkoutOptions = eventProperties[MPCommerceEventKeys.checkoutOptions.rawValue] as? String { self.checkoutOptions = checkoutOptions } if let checkoutStep = eventProperties[MPCommerceEventKeys.checkoutStep.rawValue] as? Int { self.checkoutStep = checkoutStep } if let currency = eventProperties[MPCommerceEventKeys.currency.rawValue] as? String { self.currency = currency } if let nonInteractive = eventProperties[MPCommerceEventKeys.nonInteractive.rawValue] as? Bool { self.nonInteractive = nonInteractive } if let promotionContainer = eventProperties[MPCommerceEventKeys.promotionContainer.rawValue] as? MPPromotionContainer { self.promotionContainer = promotionContainer } if let productListName = eventProperties[MPCommerceEventKeys.productListName.rawValue] as? String { self.productListName = productListName } if let productListSource = eventProperties[MPCommerceEventKeys.productListSource.rawValue] as? String { self.productListSource = productListSource } if let screenName = eventProperties[MPCommerceEventKeys.screenName.rawValue] as? String { self.screenName = screenName } self.transactionAttributes = MPTransactionAttributes(properties: eventProperties) var remainingAttributes = [String: String]() let remaining = MPCommerceEventKeys.remaining(properties: eventProperties) for (key, value) in remaining { if let value = value as? String { remainingAttributes[key] = value } } setCustomAttributes(remainingAttributes) } }
16b3447283df8ee00efb77bbb16e689f
32.526316
127
0.656201
false
false
false
false
adrianAlvarezFernandez/CameraResolutionHelper
refs/heads/master
CameraResolutionHelper/DeviceResolutions.swift
mit
1
// // DeviceResolutions.swift // ResolutionCamerasPreview // // Created by Adrián Álvarez Fernández on 13/05/2017. // Copyright © 2017 Electronic ID. All rights reserved. // import Foundation struct CameraResolutions { private static let iPhone4Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "480x640", "AVCaptureSessionPresetHigh" : "480x640", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : nil, "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "2448x3264", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] private static let iPhone567Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "960x1280", "AVCaptureSessionPresetHigh" : "720x1280", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "2448x3264", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] private static let iPhone8Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "960x1280", "AVCaptureSessionPresetHigh" : "720x1280", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "3024x4032", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] private static let iPad2Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "480x640", "AVCaptureSessionPresetHigh" : "480x640", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : nil, "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "720x960", "AVCaptureSessionPresetHigh" : "720x1280", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : nil ] ] private static let iPad3Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "480x640", "AVCaptureSessionPresetHigh" : "480x640", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : nil, "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "1936x2592", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] private static let iPad34iPod5Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "960x1280", "AVCaptureSessionPresetHigh" : "720x1280", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "1936x2592", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] private static let iPad5Resolution : NSDictionary = [ "front" : [ "AVCaptureSessionPresetPhoto" : "960x1280", "AVCaptureSessionPresetHigh" : "720x1280", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : nil ], "back" : [ "AVCaptureSessionPresetPhoto" : "2448x3264", "AVCaptureSessionPresetHigh" : "1080x1920", "AVCaptureSessionPresetMedium" : "360x480", "AVCaptureSessionPresetLow" : "144x192", "AVCaptureSessionPreset640x480" : "480x640", "AVCaptureSessionPreset1280x720" : "720x1280", "AVCaptureSessionPreset1920x1080" : "1080x1920" ] ] public static var resolutionsDictionary : NSDictionary = [ [ "iPhone4,1" ] : CameraResolutions.iPhone4Resolution, [ "iPhone5,1", "iPhone5,2", "iPhone5,3", "iPhone5,4", "iPhone6,1", "iPhone6,2", "iPhone7,1", "iPhone7,2", "iPod7,1" ] : CameraResolutions.iPhone567Resolution, [ "iPhone8,1", "iPhone8,2" ] : CameraResolutions.iPhone8Resolution, [ "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4" ] : CameraResolutions.iPad2Resolution, [ "iPad3,1", "iPad3,2", "iPad3,3" ] : CameraResolutions.iPad3Resolution, [ "iPad3,4", "iPad3,5", "iPad4,1", "iPad4,2", "iPad4,3", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7", "iPad4,8", "iPod5,1" ] : CameraResolutions.iPad34iPod5Resolution, [ "iPad5,3", "iPad5,4" ] : CameraResolutions.iPad5Resolution ] static func retrieveResolution(deviceModel : String) -> NSDictionary? { for(key, value) in resolutionsDictionary { for keyValue in key as! [String] { if keyValue == deviceModel { return value as? NSDictionary } } } return nil } }
6a22a2ab46ee7b76987350c1c2981506
35.983122
75
0.531432
false
false
false
false
einsteinx2/iSub
refs/heads/master
Carthage/Checkouts/swifter/Sources/WebSockets.swift
gpl-3.0
1
// // HttpHandlers+WebSockets.swift // Swifter // // Copyright © 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public func websocket( _ text: ((WebSocketSession, String) -> Void)?, _ binary: ((WebSocketSession, [UInt8]) -> Void)?, _ pong: ((WebSocketSession, [UInt8]) -> Void)?) -> ((HttpRequest) -> HttpResponse) { return { r in guard r.hasTokenForHeader("upgrade", token: "websocket") else { return .badRequest(.text("Invalid value of 'Upgrade' header: \(r.headers["upgrade"] ?? "unknown")")) } guard r.hasTokenForHeader("connection", token: "upgrade") else { return .badRequest(.text("Invalid value of 'Connection' header: \(r.headers["connection"] ?? "unknown")")) } guard let secWebSocketKey = r.headers["sec-websocket-key"] else { return .badRequest(.text("Invalid value of 'Sec-Websocket-Key' header: \(r.headers["sec-websocket-key"] ?? "unknown")")) } let protocolSessionClosure: ((Socket) -> Void) = { socket in let session = WebSocketSession(socket) var fragmentedOpCode = WebSocketSession.OpCode.close var payload = [UInt8]() // Used for fragmented frames. func handleTextPayload(_ frame: WebSocketSession.Frame) throws { if let handleText = text { if frame.fin { if payload.count > 0 { throw WebSocketSession.WsError.protocolError("Continuing fragmented frame cannot have an operation code.") } var textFramePayload = frame.payload.map { Int8(bitPattern: $0) } textFramePayload.append(0) if let text = String(validatingUTF8: textFramePayload) { handleText(session, text) } else { throw WebSocketSession.WsError.invalidUTF8("") } } else { payload.append(contentsOf: frame.payload) fragmentedOpCode = .text } } } func handleBinaryPayload(_ frame: WebSocketSession.Frame) throws { if let handleBinary = binary { if frame.fin { if payload.count > 0 { throw WebSocketSession.WsError.protocolError("Continuing fragmented frame cannot have an operation code.") } handleBinary(session, frame.payload) } else { payload.append(contentsOf: frame.payload) fragmentedOpCode = .binary } } } func handleOperationCode(_ frame: WebSocketSession.Frame) throws { switch frame.opcode { case .continue: // There is no message to continue, failed immediatelly. if fragmentedOpCode == .close { socket.close() } frame.opcode = fragmentedOpCode if frame.fin { payload.append(contentsOf: frame.payload) frame.payload = payload // Clean the buffer. payload = [] // Reset the OpCode. fragmentedOpCode = WebSocketSession.OpCode.close } try handleOperationCode(frame) case .text: try handleTextPayload(frame) case .binary: try handleBinaryPayload(frame) case .close: throw WebSocketSession.Control.close case .ping: if frame.payload.count > 125 { throw WebSocketSession.WsError.protocolError("Payload gretter than 125 octets.") } else { session.writeFrame(ArraySlice(frame.payload), .pong) } case .pong: if let handlePong = pong { handlePong(session, frame.payload) } break } } func read() throws { while true { let frame = try session.readFrame() try handleOperationCode(frame) } } do { try read() } catch let error { switch error { case WebSocketSession.Control.close: // Normal close break case WebSocketSession.WsError.unknownOpCode: print("Unknown Op Code: \(error)") case WebSocketSession.WsError.unMaskedFrame: print("Unmasked frame: \(error)") case WebSocketSession.WsError.invalidUTF8: print("Invalid UTF8 character: \(error)") case WebSocketSession.WsError.protocolError: print("Protocol error: \(error)") default: print("Unkown error \(error)") } // If an error occurs, send the close handshake. session.writeCloseFrame() } } guard let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").sha1()) else { return HttpResponse.internalServerError } let headers = ["Upgrade": "WebSocket", "Connection": "Upgrade", "Sec-WebSocket-Accept": secWebSocketAccept] return HttpResponse.switchProtocols(headers, protocolSessionClosure) } } public class WebSocketSession: Hashable, Equatable { public enum WsError: Error { case unknownOpCode(String), unMaskedFrame(String), protocolError(String), invalidUTF8(String) } public enum OpCode: UInt8 { case `continue` = 0x00, close = 0x08, ping = 0x09, pong = 0x0A, text = 0x01, binary = 0x02 } public enum Control: Error { case close } public class Frame { public var opcode = OpCode.close public var fin = false public var rsv1: UInt8 = 0 public var rsv2: UInt8 = 0 public var rsv3: UInt8 = 0 public var payload = [UInt8]() } public let socket: Socket public init(_ socket: Socket) { self.socket = socket } deinit { writeCloseFrame() socket.close() } public func writeText(_ text: String) -> Void { self.writeFrame(ArraySlice(text.utf8), OpCode.text) } public func writeBinary(_ binary: [UInt8]) -> Void { self.writeBinary(ArraySlice(binary)) } public func writeBinary(_ binary: ArraySlice<UInt8>) -> Void { self.writeFrame(binary, OpCode.binary) } public func writeFrame(_ data: ArraySlice<UInt8>, _ op: OpCode, _ fin: Bool = true) { let finAndOpCode = UInt8(fin ? 0x80 : 0x00) | op.rawValue let maskAndLngth = encodeLengthAndMaskFlag(UInt64(data.count), false) do { try self.socket.writeUInt8([finAndOpCode]) try self.socket.writeUInt8(maskAndLngth) try self.socket.writeUInt8(data) } catch { print(error) } } public func writeCloseFrame() { writeFrame(ArraySlice("".utf8), .close) } private func encodeLengthAndMaskFlag(_ len: UInt64, _ masked: Bool) -> [UInt8] { let encodedLngth = UInt8(masked ? 0x80 : 0x00) var encodedBytes = [UInt8]() switch len { case 0...125: encodedBytes.append(encodedLngth | UInt8(len)); case 126...UInt64(UINT16_MAX): encodedBytes.append(encodedLngth | 0x7E); encodedBytes.append(UInt8(len >> 8 & 0xFF)); encodedBytes.append(UInt8(len >> 0 & 0xFF)); default: encodedBytes.append(encodedLngth | 0x7F); encodedBytes.append(UInt8(len >> 56 & 0xFF)); encodedBytes.append(UInt8(len >> 48 & 0xFF)); encodedBytes.append(UInt8(len >> 40 & 0xFF)); encodedBytes.append(UInt8(len >> 32 & 0xFF)); encodedBytes.append(UInt8(len >> 24 & 0xFF)); encodedBytes.append(UInt8(len >> 16 & 0xFF)); encodedBytes.append(UInt8(len >> 08 & 0xFF)); encodedBytes.append(UInt8(len >> 00 & 0xFF)); } return encodedBytes } public func readFrame() throws -> Frame { let frm = Frame() let fst = try socket.read() frm.fin = fst & 0x80 != 0 frm.rsv1 = fst & 0x40 frm.rsv2 = fst & 0x20 frm.rsv3 = fst & 0x10 guard frm.rsv1 == 0 && frm.rsv2 == 0 && frm.rsv3 == 0 else { throw WsError.protocolError("Reserved frame bit has not been negocitated.") } let opc = fst & 0x0F guard let opcode = OpCode(rawValue: opc) else { // "If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_." // http://tools.ietf.org/html/rfc6455#section-5.2 ( Page 29 ) throw WsError.unknownOpCode("\(opc)") } if frm.fin == false { switch opcode { case .ping, .pong, .close: // Control frames must not be fragmented // https://tools.ietf.org/html/rfc6455#section-5.5 ( Page 35 ) throw WsError.protocolError("Control frames must not be fragmented.") default: break } } frm.opcode = opcode let sec = try socket.read() let msk = sec & 0x80 != 0 guard msk else { // "...a client MUST mask all frames that it sends to the server." // http://tools.ietf.org/html/rfc6455#section-5.1 throw WsError.unMaskedFrame("A client must mask all frames that it sends to the server.") } var len = UInt64(sec & 0x7F) if len == 0x7E { let b0 = UInt64(try socket.read() << 8) let b1 = UInt64(try socket.read()) len = UInt64(littleEndian: b0 | b1) } else if len == 0x7F { let b0 = UInt64(try socket.read() << 54) let b1 = UInt64(try socket.read() << 48) let b2 = UInt64(try socket.read() << 40) let b3 = UInt64(try socket.read() << 32) let b4 = UInt64(try socket.read() << 24) let b5 = UInt64(try socket.read() << 16) let b6 = UInt64(try socket.read() << 8) let b7 = UInt64(try socket.read()) len = UInt64(littleEndian: b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7) } let mask = [try socket.read(), try socket.read(), try socket.read(), try socket.read()] for i in 0..<len { frm.payload.append(try socket.read() ^ mask[Int(i % 4)]) } return frm } public var hashValue: Int { get { return socket.hashValue } } } public func ==(webSocketSession1: WebSocketSession, webSocketSession2: WebSocketSession) -> Bool { return webSocketSession1.socket == webSocketSession2.socket }
a6d63a3e391cc78f8bc28cb8c645825e
39.756184
134
0.522195
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01296-resolvetypedecl.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { } class l: f{ class func n {} func a<i>() { b b { } } class a<f : b, l : b m f.l == l> { } protocol b { } struct j<n : b> : b { } typealias d = i } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d {
29b6738d21eb95b0b15b760c7e7ae1e5
17.3
79
0.614754
false
false
false
false
hacktoberfest17/programming
refs/heads/master
halloween/isHalloween.swift
gpl-3.0
2
import Foundation let date = Date() let calendar = Calendar.current let month = calendar.component(.month, from: date) let day = calendar.component(.day, from: date) if (month == 10 && day == 31){ print("Happy Halloween!") } else if (month == 10){ print("It's October, but today is not Halloween!") } else { print("It's not October") }
13a3007a5cc39f4b50ee61a6fd194f3f
18.777778
54
0.646067
false
false
false
false
atuooo/notGIF
refs/heads/master
notGIF/Views/Base/InputAccessoryToolBar.swift
mit
1
// // CustomToolBar.swift // notGIF // // Created by Atuooo on 17/06/2017. // Copyright © 2017 xyz. All rights reserved. // import UIKit class InputAccessoryToolBar: UIToolbar { var doneButtonHandler: CommonHandler? var cancelButtonHandler: CommonHandler? fileprivate lazy var doneButton: UIButton = { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) button.setTitle(String.trans_titleDone, for: .normal) button.setTitleColor(UIColor.darkText, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16) button.addTarget(self, action: #selector(InputAccessoryToolBar.doneButtonClicked), for: .touchUpInside) return button }() fileprivate lazy var cancelButton: UIButton = { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) button.setTitle(String.trans_titleCancel, for: .normal) button.setTitleColor(UIColor.darkText, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16) button.addTarget(self, action: #selector(InputAccessoryToolBar.cancelButtonClicked), for: .touchUpInside) return button }() func doneButtonClicked() { doneButtonHandler?() } func cancelButtonClicked() { cancelButtonHandler?() } init(doneHandler: @escaping CommonHandler, cancelHandler: @escaping CommonHandler) { super.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40)) doneButtonHandler = doneHandler cancelButtonHandler = cancelHandler backgroundColor = UIColor.lightGray let doneItem = UIBarButtonItem(customView: doneButton) let cancelItem = UIBarButtonItem(customView: cancelButton) let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) items = [space, cancelItem, space, space, doneItem, space] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
72e77b19aabb4a70e5db4e59f5c0b356
34.913793
113
0.672108
false
false
false
false
daisysomus/swift-algorithm-club
refs/heads/master
Array2D/Array2D.playground/Contents.swift
mit
1
/* Two-dimensional array with a fixed number of rows and columns. This is mostly handy for games that are played on a grid, such as chess. Performance is always O(1). */ public struct Array2D<T> { public let columns: Int public let rows: Int fileprivate var array: [T] public init(columns: Int, rows: Int, initialValue: T) { self.columns = columns self.rows = rows array = .init(repeating: initialValue, count: rows*columns) } public subscript(column: Int, row: Int) -> T { get { precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))") precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))") return array[row*columns + column] } set { precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))") precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))") array[row*columns + column] = newValue } } } // initialization var matrix = Array2D(columns: 3, rows: 5, initialValue: 0) // makes an array of rows * columns elements all filled with zero print(matrix.array) // setting numbers using subscript [x, y] matrix[0, 0] = 1 matrix[1, 0] = 2 matrix[0, 1] = 3 matrix[1, 1] = 4 matrix[0, 2] = 5 matrix[1, 2] = 6 matrix[0, 3] = 7 matrix[1, 3] = 8 matrix[2, 3] = 9 // now the numbers are set in the array print(matrix.array) // print out the 2D array with a reference around the grid for i in 0..<matrix.rows { print("[", terminator: "") for j in 0..<matrix.columns { if j == matrix.columns - 1 { print("\(matrix[j, i])", terminator: "") } else { print("\(matrix[j, i]) ", terminator: "") } } print("]") }
26168377fccbcf114c20bddd2aa2626c
26.878788
123
0.632065
false
false
false
false
Derek316x/iOS8-day-by-day
refs/heads/master
39-watchkit/NightWatch/NightWatch WatchKit Extension/InterfaceController.swift
apache-2.0
22
// // Copyright 2014 Scott Logic // // 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 WatchKit import Foundation import NightWatchData class InterfaceController: WKInterfaceController { var quotes = [Quote]() var currentQuote: Int = 0 let quoteGenerator = NightWatchQuotes() var timer: NSTimer? let quoteCycleTime: NSTimeInterval = 30 @IBOutlet weak var quoteLabel: WKInterfaceLabel! @IBOutlet weak var quoteChangeTimer: WKInterfaceTimer! override func awakeWithContext(context: AnyObject!) { if quotes.count != 5 { quotes = quoteGenerator.randomQuotes(5) } quoteLabel.setText(quotes[currentQuote]) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(quoteCycleTime, target: self, selector: "fireTimer:", userInfo: nil, repeats: true) quoteChangeTimer.setDate(NSDate(timeIntervalSinceNow: quoteCycleTime)) quoteChangeTimer.start() } override func didDeactivate() { // This method is called when watch view controller is no longer visible timer?.invalidate() super.didDeactivate() } @IBAction func handleSkipButtonPressed() { timer?.fire() timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(quoteCycleTime, target: self, selector: "fireTimer:", userInfo: nil, repeats: true) } @objc func fireTimer(t: NSTimer) { currentQuote = (currentQuote + 1) % quotes.count quoteLabel.setText(quotes[currentQuote]) quoteChangeTimer.setDate(NSDate(timeIntervalSinceNow: quoteCycleTime)) quoteChangeTimer.start() } }
87e87bc0a774136bdcb11792f584670a
30.871429
134
0.731511
false
false
false
false
wj2061/ios7ptl-swift3.0
refs/heads/master
ch12-REST/iHotelApp/iHotelApp/iHotelAppMenuViewController.swift
mit
1
// // iHotelAppMenuViewController.swift // iHotelApp // // Created by WJ on 15/11/4. // Copyright © 2015年 wj. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class iHotelAppMenuViewController: UITableViewController { var token:String { get{ let userDefault = UserDefaults.standard return userDefault.string(forKey: "token") ?? "" } } var menuItems = [JSON]() override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let url = "http://restfulengine.iosptl.com/menuitem" let headers = ["Authorization": "Token token=\(token)"] Alamofire.request(url, headers: headers).responseJSON { (response ) -> Void in print(response.description) if let error = response.error{ let alert = UIAlertController(title: "error", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil )) self.present(alert, animated: true , completion: nil) return; }else if let data = response.data{ let json = JSON(data: data) self.menuItems = json["menuitems"].array! self.tableView.reloadData() } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = menuItems[indexPath.row]["name"].string return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
7aae806d203d3e15b42ac820288cc257
32.508772
157
0.638743
false
false
false
false
mariopavlovic/advent-of-code
refs/heads/master
2015/advent-of-code/day6.swift
mit
1
import CoreGraphics import Foundation let input: String = "turn on 887,9 through 959,629\n" + "turn on 454,398 through 844,448\n" + "turn off 539,243 through 559,965\n" + "turn off 370,819 through 676,868\n" + "turn off 145,40 through 370,997\n" + "turn off 301,3 through 808,453\n" + "turn on 351,678 through 951,908\n" + "toggle 720,196 through 897,994\n" + "toggle 831,394 through 904,860\n" + "toggle 753,664 through 970,926\n" + "turn off 150,300 through 213,740\n" + "turn on 141,242 through 932,871\n" + "toggle 294,259 through 474,326\n" + "toggle 678,333 through 752,957\n" + "toggle 393,804 through 510,976\n" + "turn off 6,964 through 411,976\n" + "turn off 33,572 through 978,590\n" + "turn on 579,693 through 650,978\n" + "turn on 150,20 through 652,719\n" + "turn off 782,143 through 808,802\n" + "turn off 240,377 through 761,468\n" + "turn off 899,828 through 958,967\n" + "turn on 613,565 through 952,659\n" + "turn on 295,36 through 964,978\n" + "toggle 846,296 through 969,528\n" + "turn off 211,254 through 529,491\n" + "turn off 231,594 through 406,794\n" + "turn off 169,791 through 758,942\n" + "turn on 955,440 through 980,477\n" + "toggle 944,498 through 995,928\n" + "turn on 519,391 through 605,718\n" + "toggle 521,303 through 617,366\n" + "turn off 524,349 through 694,791\n" + "toggle 391,87 through 499,792\n" + "toggle 562,527 through 668,935\n" + "turn off 68,358 through 857,453\n" + "toggle 815,811 through 889,828\n" + "turn off 666,61 through 768,87\n" + "turn on 27,501 through 921,952\n" + "turn on 953,102 through 983,471\n" + "turn on 277,552 through 451,723\n" + "turn off 64,253 through 655,960\n" + "turn on 47,485 through 734,977\n" + "turn off 59,119 through 699,734\n" + "toggle 407,898 through 493,955\n" + "toggle 912,966 through 949,991\n" + "turn on 479,990 through 895,990\n" + "toggle 390,589 through 869,766\n" + "toggle 593,903 through 926,943\n" + "toggle 358,439 through 870,528\n" + "turn off 649,410 through 652,875\n" + "turn on 629,834 through 712,895\n" + "toggle 254,555 through 770,901\n" + "toggle 641,832 through 947,850\n" + "turn on 268,448 through 743,777\n" + "turn off 512,123 through 625,874\n" + "turn off 498,262 through 930,811\n" + "turn off 835,158 through 886,242\n" + "toggle 546,310 through 607,773\n" + "turn on 501,505 through 896,909\n" + "turn off 666,796 through 817,924\n" + "toggle 987,789 through 993,809\n" + "toggle 745,8 through 860,693\n" + "toggle 181,983 through 731,988\n" + "turn on 826,174 through 924,883\n" + "turn on 239,228 through 843,993\n" + "turn on 205,613 through 891,667\n" + "toggle 867,873 through 984,896\n" + "turn on 628,251 through 677,681\n" + "toggle 276,956 through 631,964\n" + "turn on 78,358 through 974,713\n" + "turn on 521,360 through 773,597\n" + "turn off 963,52 through 979,502\n" + "turn on 117,151 through 934,622\n" + "toggle 237,91 through 528,164\n" + "turn on 944,269 through 975,453\n" + "toggle 979,460 through 988,964\n" + "turn off 440,254 through 681,507\n" + "toggle 347,100 through 896,785\n" + "turn off 329,592 through 369,985\n" + "turn on 931,960 through 979,985\n" + "toggle 703,3 through 776,36\n" + "toggle 798,120 through 908,550\n" + "turn off 186,605 through 914,709\n" + "turn off 921,725 through 979,956\n" + "toggle 167,34 through 735,249\n" + "turn on 726,781 through 987,936\n" + "toggle 720,336 through 847,756\n" + "turn on 171,630 through 656,769\n" + "turn off 417,276 through 751,500\n" + "toggle 559,485 through 584,534\n" + "turn on 568,629 through 690,873\n" + "toggle 248,712 through 277,988\n" + "toggle 345,594 through 812,723\n" + "turn off 800,108 through 834,618\n" + "turn off 967,439 through 986,869\n" + "turn on 842,209 through 955,529\n" + "turn on 132,653 through 357,696\n" + "turn on 817,38 through 973,662\n" + "turn off 569,816 through 721,861\n" + "turn on 568,429 through 945,724\n" + "turn on 77,458 through 844,685\n" + "turn off 138,78 through 498,851\n" + "turn on 136,21 through 252,986\n" + "turn off 2,460 through 863,472\n" + "turn on 172,81 through 839,332\n" + "turn on 123,216 through 703,384\n" + "turn off 879,644 through 944,887\n" + "toggle 227,491 through 504,793\n" + "toggle 580,418 through 741,479\n" + "toggle 65,276 through 414,299\n" + "toggle 482,486 through 838,931\n" + "turn off 557,768 through 950,927\n" + "turn off 615,617 through 955,864\n" + "turn on 859,886 through 923,919\n" + "turn on 391,330 through 499,971\n" + "toggle 521,835 through 613,847\n" + "turn on 822,787 through 989,847\n" + "turn on 192,142 through 357,846\n" + "turn off 564,945 through 985,945\n" + "turn off 479,361 through 703,799\n" + "toggle 56,481 through 489,978\n" + "turn off 632,991 through 774,998\n" + "toggle 723,526 through 945,792\n" + "turn on 344,149 through 441,640\n" + "toggle 568,927 through 624,952\n" + "turn on 621,784 through 970,788\n" + "toggle 665,783 through 795,981\n" + "toggle 386,610 through 817,730\n" + "toggle 440,399 through 734,417\n" + "toggle 939,201 through 978,803\n" + "turn off 395,883 through 554,929\n" + "turn on 340,309 through 637,561\n" + "turn off 875,147 through 946,481\n" + "turn off 945,837 through 957,922\n" + "turn off 429,982 through 691,991\n" + "toggle 227,137 through 439,822\n" + "toggle 4,848 through 7,932\n" + "turn off 545,146 through 756,943\n" + "turn on 763,863 through 937,994\n" + "turn on 232,94 through 404,502\n" + "turn off 742,254 through 930,512\n" + "turn on 91,931 through 101,942\n" + "toggle 585,106 through 651,425\n" + "turn on 506,700 through 567,960\n" + "turn off 548,44 through 718,352\n" + "turn off 194,827 through 673,859\n" + "turn off 6,645 through 509,764\n" + "turn off 13,230 through 821,361\n" + "turn on 734,629 through 919,631\n" + "toggle 788,552 through 957,972\n" + "toggle 244,747 through 849,773\n" + "turn off 162,553 through 276,887\n" + "turn off 569,577 through 587,604\n" + "turn off 799,482 through 854,956\n" + "turn on 744,535 through 909,802\n" + "toggle 330,641 through 396,986\n" + "turn off 927,458 through 966,564\n" + "toggle 984,486 through 986,913\n" + "toggle 519,682 through 632,708\n" + "turn on 984,977 through 989,986\n" + "toggle 766,423 through 934,495\n" + "turn on 17,509 through 947,718\n" + "turn on 413,783 through 631,903\n" + "turn on 482,370 through 493,688\n" + "turn on 433,859 through 628,938\n" + "turn off 769,549 through 945,810\n" + "turn on 178,853 through 539,941\n" + "turn off 203,251 through 692,433\n" + "turn off 525,638 through 955,794\n" + "turn on 169,70 through 764,939\n" + "toggle 59,352 through 896,404\n" + "toggle 143,245 through 707,320\n" + "turn off 103,35 through 160,949\n" + "toggle 496,24 through 669,507\n" + "turn off 581,847 through 847,903\n" + "turn on 689,153 through 733,562\n" + "turn on 821,487 through 839,699\n" + "turn on 837,627 through 978,723\n" + "toggle 96,748 through 973,753\n" + "toggle 99,818 through 609,995\n" + "turn on 731,193 through 756,509\n" + "turn off 622,55 through 813,365\n" + "turn on 456,490 through 576,548\n" + "turn on 48,421 through 163,674\n" + "turn off 853,861 through 924,964\n" + "turn off 59,963 through 556,987\n" + "turn on 458,710 through 688,847\n" + "toggle 12,484 through 878,562\n" + "turn off 241,964 through 799,983\n" + "turn off 434,299 through 845,772\n" + "toggle 896,725 through 956,847\n" + "turn on 740,289 through 784,345\n" + "turn off 395,840 through 822,845\n" + "turn on 955,224 through 996,953\n" + "turn off 710,186 through 957,722\n" + "turn off 485,949 through 869,985\n" + "turn on 848,209 through 975,376\n" + "toggle 221,241 through 906,384\n" + "turn on 588,49 through 927,496\n" + "turn on 273,332 through 735,725\n" + "turn on 505,962 through 895,962\n" + "toggle 820,112 through 923,143\n" + "turn on 919,792 through 978,982\n" + "toggle 489,461 through 910,737\n" + "turn off 202,642 through 638,940\n" + "turn off 708,953 through 970,960\n" + "toggle 437,291 through 546,381\n" + "turn on 409,358 through 837,479\n" + "turn off 756,279 through 870,943\n" + "turn off 154,657 through 375,703\n" + "turn off 524,622 through 995,779\n" + "toggle 514,221 through 651,850\n" + "toggle 808,464 through 886,646\n" + "toggle 483,537 through 739,840\n" + "toggle 654,769 through 831,825\n" + "turn off 326,37 through 631,69\n" + "turn off 590,570 through 926,656\n" + "turn off 881,913 through 911,998\n" + "turn on 996,102 through 998,616\n" + "turn off 677,503 through 828,563\n" + "turn on 860,251 through 877,441\n" + "turn off 964,100 through 982,377\n" + "toggle 888,403 through 961,597\n" + "turn off 632,240 through 938,968\n" + "toggle 731,176 through 932,413\n" + "turn on 5,498 through 203,835\n" + "turn on 819,352 through 929,855\n" + "toggle 393,813 through 832,816\n" + "toggle 725,689 through 967,888\n" + "turn on 968,950 through 969,983\n" + "turn off 152,628 through 582,896\n" + "turn off 165,844 through 459,935\n" + "turn off 882,741 through 974,786\n" + "turn off 283,179 through 731,899\n" + "toggle 197,366 through 682,445\n" + "turn on 106,309 through 120,813\n" + "toggle 950,387 through 967,782\n" + "turn off 274,603 through 383,759\n" + "turn off 155,665 through 284,787\n" + "toggle 551,871 through 860,962\n" + "turn off 30,826 through 598,892\n" + "toggle 76,552 through 977,888\n" + "turn on 938,180 through 994,997\n" + "toggle 62,381 through 993,656\n" + "toggle 625,861 through 921,941\n" + "turn on 685,311 through 872,521\n" + "turn on 124,934 through 530,962\n" + "turn on 606,379 through 961,867\n" + "turn off 792,735 through 946,783\n" + "turn on 417,480 through 860,598\n" + "toggle 178,91 through 481,887\n" + "turn off 23,935 through 833,962\n" + "toggle 317,14 through 793,425\n" + "turn on 986,89 through 999,613\n" + "turn off 359,201 through 560,554\n" + "turn off 729,494 through 942,626\n" + "turn on 204,143 through 876,610\n" + "toggle 474,97 through 636,542\n" + "turn off 902,924 through 976,973\n" + "turn off 389,442 through 824,638\n" + "turn off 622,863 through 798,863\n" + "turn on 840,622 through 978,920\n" + "toggle 567,374 through 925,439\n" + "turn off 643,319 through 935,662\n" + "toggle 185,42 through 294,810\n" + "turn on 47,124 through 598,880\n" + "toggle 828,303 through 979,770\n" + "turn off 174,272 through 280,311\n" + "turn off 540,50 through 880,212\n" + "turn on 141,994 through 221,998\n" + "turn on 476,695 through 483,901\n" + "turn on 960,216 through 972,502\n" + "toggle 752,335 through 957,733\n" + "turn off 419,713 through 537,998\n" + "toggle 772,846 through 994,888\n" + "turn on 881,159 through 902,312\n" + "turn off 537,651 through 641,816\n" + "toggle 561,947 through 638,965\n" + "turn on 368,458 through 437,612\n" + "turn on 290,149 through 705,919\n" + "turn on 711,918 through 974,945\n" + "toggle 916,242 through 926,786\n" + "toggle 522,272 through 773,314\n" + "turn on 432,897 through 440,954\n" + "turn off 132,169 through 775,380\n" + "toggle 52,205 through 693,747\n" + "toggle 926,309 through 976,669\n" + "turn off 838,342 through 938,444\n" + "turn on 144,431 through 260,951\n" + "toggle 780,318 through 975,495\n" + "turn off 185,412 through 796,541\n" + "turn on 879,548 through 892,860\n" + "turn on 294,132 through 460,338\n" + "turn on 823,500 through 899,529\n" + "turn off 225,603 through 483,920\n" + "toggle 717,493 through 930,875\n" + "toggle 534,948 through 599,968\n" + "turn on 522,730 through 968,950\n" + "turn off 102,229 through 674,529" private var lights: [Int] = Array(count: 1000*1000, repeatedValue: 0) private var brightness: [Int] = Array(count: 1000*1000, repeatedValue: 0) private enum Action { case None case TurnOn case TurnOff case Toggle } private struct Instruction { let startPoint: CGPoint let endPoint: CGPoint let action: Action init(start: CGPoint, end: CGPoint, input: String) { startPoint = start endPoint = end switch input { case "turn on": action = .TurnOn case "turn off": action = .TurnOff case "toggle": action = .Toggle default: action = .None } } } private func pointFromString(input: String) -> CGPoint { let data = input.componentsSeparatedByString(",") return CGPointMake(CGFloat((data.first! as NSString).floatValue), CGFloat((data.last! as NSString).floatValue)) } private func processInput(input: String) -> (action: String, start: CGPoint, end: CGPoint) { var words = input.componentsSeparatedByString(" ") //we know that last and last - 2 items are points let startPointIndex = words.endIndex - 3 let endPoint = pointFromString(words.last!) let startPoint = pointFromString(words[startPointIndex]) //now we know that we need to remove everything from start point till the end //this will leave only action (first one or two words) words.removeRange(startPointIndex ..< words.endIndex) let action = words.joinWithSeparator(" ") return (action, startPoint, endPoint) } private func performAction(action: Action, index: Int) { switch action { case .TurnOn: lights[index] = 1 brightness[index] += 1 case .TurnOff: lights[index] = 0 //brightness can't be less then 0 if (brightness[index]) > 0 { brightness[index] -= 1 } case .Toggle: lights[index] = (lights[index] + 1) % 2 brightness[index] += 2 case .None: print("Reached .None case") } } private func performInstructions(instructions :[Instruction]) { for instruction: Instruction in instructions { for y in Int(instruction.startPoint.y)...Int(instruction.endPoint.y) { for x in Int(instruction.startPoint.x)...Int(instruction.endPoint.x) { performAction(instruction.action, index: y * 1000 + x) } } } } private func sumElements(source: [Int]) -> Int { //"+" is short for "$0 + $1" return source.reduce(0, combine: +) } public func numberOfLitLights() -> Int { let inputArray = input.characters.split { $0 == "\n"}.map(String.init) let instructions = inputArray.map { (inputData) -> Instruction in let data = processInput(inputData) return Instruction.init(start: data.start, end: data.end, input: data.action) } performInstructions(instructions) let numLitLights = sumElements(lights) let combinedBrightness = sumElements(brightness.filter{ $0 > 0 }) print("there are \(numLitLights) lit lights, with combined brightness of \(combinedBrightness)") return numLitLights }
f6f6f96a82ad44ec22f38e0e866fa5b3
37.77887
115
0.627257
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/TableViewDataSources/StableOverviewDataSource.swift
gpl-3.0
1
// // StableOverviewDataSource.swift // Habitica // // Created by Phillip Thelen on 16.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import ReactiveSwift struct StableOverviewItem { var imageName: String var text: String var numberOwned: Int var totalNumber: Int var searchKey: String var type: String } class StableOverviewDataSource<ANIMAL: AnimalProtocol>: BaseReactiveCollectionViewDataSource<StableOverviewItem> { internal let stableRepository = StableRepository() internal let inventoryRepository = InventoryRepository() internal var fetchDisposable: Disposable? var organizeByColor = false { didSet { fetchData() } } deinit { if let disposable = fetchDisposable { disposable.dispose() } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) if let animalItem = item(at: indexPath), let overviewCell = cell as? StableOverviewCell { overviewCell.configure(item: animalItem) } return cell } internal func fetchData() { if let disposable = fetchDisposable { disposable.dispose() } } internal func mapData(owned: [String], animals: [AnimalProtocol], items: [String: String]) -> [String: [StableOverviewItem]] { var data = ["drop": [StableOverviewItem](), "quest": [StableOverviewItem](), "special": [StableOverviewItem](), "wacky": [StableOverviewItem]()] animals.forEach { (animal) in let type = (animal.type == "premium" ? "drop" : animal.type) ?? "" var item = data[type]?.last let isOwned = owned.contains(animal.key ?? "") if animal.type == "special" && !isOwned { return } var displayText = (organizeByColor ? animal.potion : animal.egg) ?? "" if let text = items[(organizeByColor ? animal.potion : animal.egg) ?? ""] { displayText = text } else if animal.type == "special" || animal.type == "wacky" { displayText = animal.key ?? "" } let searchText = ((animal.type == "special" || animal.type == "wacky") ? animal.key : (organizeByColor ? animal.potion : animal.egg)) ?? "" if item?.text == nil || item?.text != displayText { item = StableOverviewItem(imageName: getImageName(animal), text: displayText, numberOwned: 0, totalNumber: 0, searchKey: searchText, type: animal.type ?? "") if let item = item { data[type]?.append(item) } } item?.totalNumber += 1 if isOwned { item?.numberOwned += 1 } if let item = item { let lastIndex = (data[type]?.count ?? 1) - 1 data[type]?[lastIndex] = item } } return data } internal func getImageName(_ animal: AnimalProtocol) -> String { if animal.type == "special" || animal.type == "wacky" { return "stable_Pet-\(animal.key ?? "")" } else { if organizeByColor { return "Pet_HatchingPotion_\(animal.potion ?? "")" } else { return "Pet_Egg_\(animal.egg ?? "")" } } } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let reuseIdentifier = (kind == UICollectionView.elementKindSectionFooter) ? "SectionFooter" : "SectionHeader" let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifier, for: indexPath) if kind == UICollectionView.elementKindSectionHeader { let label = view.viewWithTag(1) as? UILabel label?.text = visibleSections[indexPath.section].title let countLabel = view.viewWithTag(2) as? UILabel countLabel?.textColor = ThemeService.shared.theme.ternaryTextColor view.viewWithTag(3)?.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor var ownedCount = 0 visibleSections[indexPath.section].items.forEach { ownedCount += $0.numberOwned } var totalCount = 0 visibleSections[indexPath.section].items.forEach { totalCount += $0.totalNumber } countLabel?.text = "\(ownedCount)/\(totalCount)" view.shouldGroupAccessibilityChildren = true view.isAccessibilityElement = true view.accessibilityLabel = visibleSections[indexPath.section].title ?? "" + " " + L10n.Accessibility.xofx(ownedCount, totalCount) } return view } }
1c1bd76b6f1171ca7bf24e7e5a1a9ce8
39.101563
173
0.595753
false
false
false
false
oleander/bitbar
refs/heads/master
Tests/PluginTests/RotatorTests.swift
mit
1
import Quick import Nimble import Parser import Async import Parser import SharedTests @testable import Plugin class RotHost: Rotatable { var result: [Text] = [] var rotator: Rotator! init() { rotator = Rotator(every: 1, delegate: self) } func rotator(didRotate text: Text) { result.append(text) } func stop() { rotator.stop() } func start() { rotator.start() } func set(_ items: [Text]) { try? rotator.set(text: items) } func deallocate() { rotator = nil } } class RotatorTests: QuickSpec { override func spec() { Nimble.AsyncDefaults.Timeout = 6 // Nimble.AsyncDefaults.PollInterval = 0.1 let text: [Text] = [.text1, .text2, .text3] describe("non empty list") { var host: RotHost! beforeEach { host = RotHost() } it("should handle a list of items") { host.set(text) expect(host.result).toEventually(cyclicSubset(of: text)) } it("should stop updating") { host.set(text) host.stop() expect(host.result).toEventually(equal([.text1])) } it("should be able to resume") { host.set(text) host.stop() host.start() expect(host.result).toEventually(cyclicSubset(of: text)) } it("does not rotate if deallocated") { host.set(text) host.deallocate() expect(host.result).toEventually(beEmpty()) } it("restarts when reaching the end") { host.set(text) expect(host.result).toEventually(cyclicSubset(of: text + text)) } it("does not rotate with one item") { host.set([.text1]) waitUntil(timeout: 10) { done in Async.main(after: 5) { expect(host.result).to(cyclicSubset(of: [.text1])) done() } } } } } }
a724b61a475a3401349a9df6662b3f0b
19.406593
71
0.57189
false
false
false
false
Valine/mr-inspiration
refs/heads/master
ProjectChartSwift/Mr. Inspiration/RootViewController.swift
gpl-2.0
2
// // ViewController.swift // Mr. Inspiration // // Created by Lukas Valine on 12/1/15. // Copyright © 2015 Lukas Valine. All rights reserved. // import UIKit class RootViewController: UINavigationController, SongListViewControllerDelegate, BuildSongDelegate { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.lightGrayColor() let backItem = UIBarButtonItem(title: "Custom", style: .Plain, target: nil, action: nil) navigationItem.backBarButtonItem = backItem let songListViewController = SongListViewController() songListViewController.delegate = self self.viewControllers = [songListViewController] } func deletePressed(sender: UIButton) { } func addSongTapped() { let buildSongViewController: BuildSongViewController = BuildSongViewController() self.pushViewController(buildSongViewController, animated: true) buildSongViewController.delegate = self } func songCellTapped(index: Int, model: Song) { let songViewController = SongViewController(model: model) self.pushViewController(songViewController, animated: true) } func generateTapped(song: Song) { print("hello") (viewControllers[0] as? SongListViewController)?.model.addSong(song) ((viewControllers[0] as? SongListViewController)?.view as? SongListView)?.collectionView?.reloadData() let songViewController = SongViewController(model: song) //s .dismissViewControllerAnimated(false, completion: nil) //songViewController.navigationItem.backBarButtonItem?. self.pushViewController(songViewController, animated: true) } }
ea7bfcee5eb5ad75fb1dd1a68dc84db7
25.583333
110
0.643156
false
false
false
false
yyny1789/KrMediumKit
refs/heads/master
Source/UI/PullToRefresh/RefreshView.swift
mit
1
// // RefreshView.swift // Client // // Created by aidenluo on 12/6/15. // Copyright © 2015 36Kr. All rights reserved. // import UIKit class RefreshDefaultView: RefreshView { let circleLayer = CAShapeLayer() var lineWidth: CGFloat = 1.5 { didSet { circleLayer.lineWidth = lineWidth setNeedsLayout() } } var animating: Bool = true { didSet { updateAnimation() } } var radius: CGFloat = 12.5 { didSet { setNeedsLayout() } } var strokeEnd: CGFloat = 1.5 { didSet { setNeedsLayout() } } let strokeEndAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0 animation.toValue = 1 animation.duration = 2 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let group = CAAnimationGroup() group.duration = 2.5 group.repeatCount = HUGE group.animations = [animation] return group }() let strokeStartAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "strokeStart") animation.beginTime = 0.5 animation.fromValue = 0 animation.toValue = 1 animation.duration = 2 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let group = CAAnimationGroup() group.duration = 2.5 group.repeatCount = HUGE group.animations = [animation] return group }() let rotationAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = Double.pi * 2 animation.duration = 1.0 animation.repeatCount = HUGE return animation }() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func tintColorDidChange() { super.tintColorDidChange() circleLayer.strokeColor = tintColor.cgColor } override func layoutSubviews() { super.layoutSubviews() let center = CGPoint(x: bounds.midX, y: bounds.midY) let radius = self.radius let startAngle = CGFloat(-Double.pi) let endAngle = startAngle + CGFloat(Double.pi * 2) let path = UIBezierPath(arcCenter: CGPoint.zero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) circleLayer.position = center circleLayer.path = path.cgPath circleLayer.strokeEnd = self.strokeEnd } func setup() { circleLayer.lineWidth = lineWidth circleLayer.fillColor = nil layer.addSublayer(circleLayer) tintColorDidChange() updateAnimation() self.tintColor = UIColor(hex: 0x464c56) } func updateAnimation() { if animating { circleLayer.add(strokeEndAnimation, forKey: "strokeEnd") circleLayer.add(strokeStartAnimation, forKey: "strokeStart") circleLayer.add(rotationAnimation, forKey: "rotation") } else { circleLayer.removeAnimation(forKey: "strokeEnd") circleLayer.removeAnimation(forKey: "strokeStart") circleLayer.removeAnimation(forKey: "rotation") } } override func animateState(_ state: RefresherState) { switch state { case .initial: animating = false strokeEnd = 0 case .pulling(let progress): strokeEnd = progress case .loading: animating = true case .finished: break } } }
b0b255125dfcad2551bf4f7794c5e84e
26.657343
133
0.589128
false
false
false
false
jarvisluong/ios-retro-calculator
refs/heads/master
RetroCalculator/CalculatorScreen.swift
mpl-2.0
1
// // CalculatorScreen.swift // RetroCalculator // // Created by Hai Dang Luong on 17/01/2017. // Copyright © 2017 Hai Dang Luong. All rights reserved. // import UIKit import AVFoundation class CalculatorScreen: UIViewController { // Sound effect for the buttons var btnSound : AVAudioPlayer! // Display the value to the screen @IBOutlet weak var outputLabel: UILabel! // List of operators enum Operators : String { case Divide = "/" case Multiply = "Multiply" case Subtract = "Subtract" case Add = "Add" case Empty = "Empty" } var currentOperator = Operators.Empty // Dump Memory Variable for processing the mathematics operations var leftValue = "" var rightValue = "" var result = "" var runningValue = "" override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "btn", ofType: "wav") let audioURL = URL(fileURLWithPath: path!) // Safety first, if for some reasons the sound can't be played then throw and error do { try btnSound = AVAudioPlayer(contentsOf: audioURL) btnSound.prepareToPlay() } catch let err as NSError { print(err.debugDescription) } } @IBAction func numberPressed(_ sender: UIButton) { playAudio() runningValue += String(sender.tag) outputLabel.text = runningValue } @IBAction func dividePressed(_ sender: UIButton) { processOperator(operation: .Divide) } @IBAction func multiplyPressed(_ sender: UIButton) { processOperator(operation: .Multiply) } @IBAction func subtractPressed(_ sender: UIButton) { processOperator(operation: .Subtract) } @IBAction func addPressed(_ sender: UIButton) { processOperator(operation: .Add) } @IBAction func equalPressed(_ sender: UIButton) { processOperator(operation: currentOperator) } @IBAction func ClearBtnPressed(_ sender: UIButton) { playAudio() leftValue = "" rightValue = "" runningValue = "" currentOperator = Operators.Empty outputLabel.text = "0" } func processOperator(operation: Operators) { playAudio() if currentOperator != Operators.Empty { // This happens when user press an operator but then press another operator if runningValue != "" { rightValue = runningValue runningValue = "" if currentOperator == Operators.Divide { result = "\(Double(leftValue)! / Double(rightValue)!)" } else if currentOperator == Operators.Multiply { result = "\(Double(leftValue)! * Double(rightValue)!)" } else if currentOperator == Operators.Subtract { result = "\(Double(leftValue)! - Double(rightValue)!)" } else if currentOperator == Operators.Add { result = "\(Double(leftValue)! + Double(rightValue)!)" } leftValue = result outputLabel.text = result currentOperator = Operators.Empty } } else if leftValue != "" { // This happens when user has already calculated successfully once and continue calculating currentOperator = operation } else { // This is the first time an operator being pushed leftValue = runningValue runningValue = "" currentOperator = operation } } func playAudio() { if btnSound.isPlaying { btnSound.stop() } btnSound.play() } }
9010c67afa65c982138840a165fbf586
28.664122
99
0.568708
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Common/Transitions/FromBottomTransition.swift
bsd-3-clause
1
import UIKit class FromBottomTransition: NSObject, UIViewControllerAnimatedTransitioning { let presenting : Bool init(presenting:Bool) { self.presenting = presenting } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return presenting ? 0.225 : 0.195 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let toController = transitionContext.viewController(forKey: .to)! let fromController = transitionContext.viewController(forKey: .from)! let animationDuration = transitionDuration(using: transitionContext) if presenting { transitionContext.containerView.addSubview(toController.view) let finalFrame = transitionContext.finalFrame(for: toController) toController.view.frame = finalFrame.offsetBy(dx: 0, dy: transitionContext.containerView.frame.height) toController.view.alpha = 0.5 UIView.animate( { toController.view.frame = finalFrame toController.view.alpha = 1.0 }, duration: animationDuration, delay: 0, options: [], withControlPoints: 0.175, 0.885, 0.32, 1.14, completion: { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } ) } else { let initialFrame = transitionContext.initialFrame(for: fromController) let finalFrame = initialFrame.offsetBy(dx: 0, dy: transitionContext.containerView.frame.height) if transitionContext.isInteractive { UIView.animate( withDuration: animationDuration, animations: { fromController.view.frame = finalFrame }, completion: { p in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } ) } else { UIView.animate( { fromController.view.frame = finalFrame fromController.view.alpha = 0.5 }, duration: animationDuration, delay: 0, options: [], withControlPoints: 0.4, 0.0, 0.6, 1, completion: { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } ) } } } }
a5bf91127c7333d43e2ccc6f894ccae2
34.37037
114
0.532984
false
false
false
false
cwoloszynski/XCGLogger
refs/heads/master
Sources/XCGLogger/Destinations/SyslogDestination.swift
mit
1
// // SyslogDestination.swift // GotYourBackServer // // Created by Charlie Woloszynski on 1/12/17. // // import Dispatch import Foundation import libc open class SyslogDestination: BaseDestination { open var logQueue: DispatchQueue? = nil /// Option: whether or not to output the date the log was created (Always false for this destination) open override var showDate: Bool { get { return false } set { // ignored, syslog adds the date, so we always want showDate to be false in this subclass } } var identifierPointer: UnsafeMutablePointer<Int8> public init(identifier: String) { // openlog needs access to an const char * value that lasts during the call // but the normal Swift behavior to ensure that the const char * lasts only as // long as the function call. So, we need to create that const char * equivalent // in code let utf = identifier.utf8 let length = utf.count self.identifierPointer = UnsafeMutablePointer<Int8>.allocate(capacity: length+1) let temp = UnsafePointer<Int8>(identifier) memcpy(self.identifierPointer, temp, length) self.identifierPointer[length] = 0 // zero terminate openlog(self.identifierPointer, 0, LOG_USER) } deinit { closelog() } open override func output(logDetails: LogDetails, message: String) { let outputClosure = { var logDetails = logDetails var message = message // Apply filters, if any indicate we should drop the message, we abort before doing the actual logging if self.shouldExclude(logDetails: &logDetails, message: &message) { return } self.applyFormatters(logDetails: &logDetails, message: &message) let syslogLevel = self.mappedLevel(logDetails.level) withVaList([]) { vsyslog(syslogLevel, message, $0) } } if let logQueue = logQueue { logQueue.async(execute: outputClosure) } else { outputClosure() } } func mappedLevel(_ level: XCGLogger.Level) -> Int32 { switch (level) { case .severe: return LOG_ERR case .warning: return LOG_WARNING case .info: return LOG_INFO case .debug: return LOG_DEBUG case .verbose: return LOG_DEBUG default: return LOG_DEBUG } } }
e74f0eb8d75ce1ae530475627a198bec
29.127907
114
0.594751
false
false
false
false
otto-de/OTTOPhotoBrowser
refs/heads/master
OTTOPhotoBrowser/Classes/OTTOZoomingScrollView.swift
mit
1
// // OttoZoomingScrollView.swift // OTTOPhotoBrowser // // Created by Lukas Zielinski on 22/12/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class OTTOZoomingScrollView: UIScrollView, UIScrollViewDelegate { var photo: OTTOPhoto? { didSet { displayImage() } } var padding: CGFloat = 0 weak var photoBrowserView: OTTOPhotoBrowserView? private let activityIndicatorView: UIActivityIndicatorView private let tapView: UIView private let photoImageView: UIImageView private var isPinchoutDetected = false func prepareForReuse() { photo = nil } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(photoBrowserView: OTTOPhotoBrowserView) { self.photoBrowserView = photoBrowserView activityIndicatorView = UIActivityIndicatorView() tapView = UIView(frame: CGRect.zero) photoImageView = UIImageView(frame: CGRect.zero) super.init(frame: CGRect.zero) activityIndicatorView.style = .gray activityIndicatorView.hidesWhenStopped = true addSubview(activityIndicatorView) tapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tapView.backgroundColor = UIColor.clear let tapViewSingleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(gestureRecognizer:))) let tapViewDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(gestureRecognizer:))) tapViewDoubleTapRecognizer.numberOfTapsRequired = 2 tapViewSingleTapRecognizer.require(toFail: tapViewDoubleTapRecognizer) tapView.addGestureRecognizer(tapViewSingleTapRecognizer) tapView.addGestureRecognizer(tapViewDoubleTapRecognizer) photoImageView.backgroundColor = UIColor.clear let imageViewSingleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(gestureRecognizer:))) let imageViewDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(gestureRecognizer:))) imageViewDoubleTapRecognizer.numberOfTapsRequired = 2 imageViewSingleTapRecognizer.require(toFail: imageViewDoubleTapRecognizer) photoImageView.contentMode = .scaleAspectFit photoImageView.isUserInteractionEnabled = true photoImageView.addGestureRecognizer(imageViewSingleTapRecognizer) photoImageView.addGestureRecognizer(imageViewDoubleTapRecognizer) addSubview(tapView) addSubview(photoImageView) backgroundColor = UIColor.clear delegate = self showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false decelerationRate = UIScrollView.DecelerationRate.fast autoresizingMask = [.flexibleHeight, .flexibleWidth] } func displayImage() { guard let photo = photo else { return } if let image = photoBrowserView?.imageForPhoto(photo: photo), image.size.width > 0, image.size.height > 0 { minimumZoomScale = 1 maximumZoomScale = 1 zoomScale = 1 photoImageView.image = image photoImageView.isHidden = false photoImageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) contentSize = photoImageView.frame.size setMaxMinZoomScalesForCurrentBounds() activityIndicatorView.stopAnimating() } else { photoImageView.isHidden = true activityIndicatorView.startAnimating() } setNeedsLayout() } private func setMaxMinZoomScalesForCurrentBounds() { if photoImageView.image == nil { return } var boundsSize = bounds.size boundsSize.width -= 0.1 boundsSize.height -= 0.1 let imageSize = photoImageView.frame.size let xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise let minScale = min(xScale, yScale); // use minimum of these to allow the image to become fully visible let maxScale = minScale * 2.5 maximumZoomScale = maxScale; minimumZoomScale = minScale; zoomScale = minScale; let paddingX = photoImageView.frame.size.width > padding * 4 ? padding : 0 let paddingY = photoImageView.frame.size.height > padding * 4 ? padding : 0 photoImageView.frame = CGRect(x: 0, y: 0, width: photoImageView.frame.size.width, height: photoImageView.frame.size.height).insetBy(dx: paddingX, dy: paddingY) setNeedsLayout() } override func layoutSubviews() { tapView.frame = bounds super.layoutSubviews() let boundsSize = bounds.size var frameToCenter = photoImageView.frame if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / CGFloat(2)) } else { frameToCenter.origin.x = 0; } if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / CGFloat(2)); } else { frameToCenter.origin.y = 0; } photoImageView.frame = frameToCenter activityIndicatorView.center = CGPoint(x: bounds.midX, y: bounds.midY) } // MARK: UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return photoImageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() if zoomScale < (minimumZoomScale - minimumZoomScale * 0.4) { isPinchoutDetected = true } } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { photoBrowserView?.scrollViewDidEndZooming(scrollView, with: view, atScale: scale) if isPinchoutDetected { isPinchoutDetected = false photoBrowserView?.onPinchout() } } // MARK: Tap Detection @objc func handleSingleTap(gestureRecognizer: UITapGestureRecognizer) { photoBrowserView?.onTap() } @objc func handleDoubleTap(gestureRecognizer: UITapGestureRecognizer) { let touchPoint = gestureRecognizer.location(in: photoImageView) if zoomScale == maximumZoomScale { setZoomScale(minimumZoomScale, animated: true) } else { zoom(to: CGRect(x: touchPoint.x, y: touchPoint.y, width: 1, height: 1), animated: true) } photoBrowserView?.onZoomedWithDoubleTap() } }
85243012d261a677b2c332208a5604a6
36.609375
167
0.652264
false
false
false
false
joaoSakai/torpedo-saude
refs/heads/master
GrupoFlecha/GrupoFlecha/AlertController.swift
gpl-2.0
1
// // AlertController.swift // GrupoFlecha // // Created by Davi Rodrigues on 05/03/16. // Copyright © 2016 Davi Rodrigues. All rights reserved. // import UIKit import CoreLocation import MapKit class AlertController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var map: MKMapView! var locationManager = CLLocationManager() var zoom = false override func viewDidLoad() { super.viewDidLoad() //Inicializa mapa a partir da posição do usuário self.map.showsUserLocation = true self.map.zoomEnabled = true //Configura CLLocationManager locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self locationManager.startUpdatingLocation() locationManager.requestAlwaysAuthorization() //Inicializa texto da UITextView if(AlertSource.casosDeDengue == 1) { self.textView.text = AlertSource.alertaSimples } else if(AlertSource.casosDeDengue == 0) { self.textView.text = AlertSource.alertaAreaLimpa } else { self.textView.text = AlertSource.alerta } //Configura propriedades da UITextView textView.font = UIFont(name: "Helvetica", size: 20) } override func viewWillAppear(animated: Bool) { AlertSource.getData(){ () in } } override func viewWillDisappear(animated: Bool) { AlertSource.pinCoordinates.removeAll() } override func viewDidAppear(animated: Bool) { //Zoom no mapa para posição do usuário if let coordinate = map.userLocation.location?.coordinate { let region = MKCoordinateRegionMakeWithDistance(coordinate, 1000, 1000) map.setRegion(region, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: MapKit func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { if(self.zoom == false) { let coor = self.map.userLocation.location?.coordinate let region = MKCoordinateRegionMakeWithDistance(coor!, 1000, 1000) self.map.setRegion(region, animated: true) self.zoom = true } self.updateAnnotations() self.insideRadius() } func updateAnnotations() { self.map.removeAnnotations(map.annotations) self.map.removeOverlays(map.overlays) let annotation = MKCircle(centerCoordinate: map.userLocation.coordinate, radius: 300) annotation.title = "Sua localização" annotation.subtitle = "" map.addOverlay(annotation) self.addPinCoordinates() } func addPinCoordinates() { /* for coord in AlertSource.pinCoordinates { let annotation = MKPointAnnotation() annotation.coordinate = coord annotation.title = "Caso de dengue nas proximidades" annotation.subtitle = "Localização aproximada de um caso confirmado" map.addAnnotation(annotation) }*/ let annotation = MKPointAnnotation() annotation.coordinate = map.userLocation.coordinate annotation.title = String(AlertSource.casosDeDengue) + " casos próximos a você" map.addAnnotation(annotation) } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKCircle { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.lineWidth = 1.0 //Cor do circulo if(AlertSource.casosDeDengue == 0) { circleRenderer.strokeColor = UIColor.greenColor() circleRenderer.fillColor = UIColor.greenColor().colorWithAlphaComponent(0.4) } else if(AlertSource.casosDeDengue == 1) { circleRenderer.strokeColor = UIColor.yellowColor() circleRenderer.fillColor = UIColor.yellowColor().colorWithAlphaComponent(0.4) } else { circleRenderer.strokeColor = UIColor.redColor() circleRenderer.fillColor = UIColor.redColor().colorWithAlphaComponent(0.4) } return circleRenderer } return MKOverlayRenderer() } func insideRadius() { let radius: Double = 0.0029 for coord in AlertSource.pinCoordinates { let distance: Double = (map.userLocation.coordinate.latitude - coord.latitude)*(map.userLocation.coordinate.latitude - coord.latitude) + (map.userLocation.coordinate.longitude - coord.longitude)*(map.userLocation.coordinate.longitude - coord.longitude) //print(sqrt(distance)) //print(radius) if(sqrt(distance) <= radius) { AlertSource.casosDeDengue++ } } } }
0eecd3e02d017244d4ab68827cd6805c
31.337423
264
0.615253
false
false
false
false
Ferrari-lee/firefox-ios
refs/heads/master
Sync/SyncMeta.swift
mpl-2.0
21
/* 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 // Our engine choices need to persist across server changes. // Note that EngineConfiguration is not enough to evolve an existing meta/global: // a meta/global generated from this will have different syncIDs and will // always use this device's engine versions. public class EngineConfiguration { let enabled: [String] let declined: [String] public init(enabled: [String], declined: [String]) { self.enabled = enabled self.declined = declined } public class func fromJSON(json: JSON) -> EngineConfiguration? { if let enabled = jsonsToStrings(json["enabled"].asArray) { if let declined = jsonsToStrings(json["declined"].asArray) { return EngineConfiguration(enabled: enabled, declined: declined) } } return nil } public func reconcile(meta: [String: EngineMeta]) -> EngineConfiguration { // TODO: when we get a changed meta/global, we need to be able // to reflect its changes into our configuration. // Note that sometimes we also need to make changes to the meta/global // itself -- e.g., missing declined. That should be a method on MetaGlobal. return self } } // Equivalent to Android Sync's EngineSettings, but here // we use them for meta/global itself. public struct EngineMeta: Equatable { let version: Int let syncID: String public static func fromJSON(json: JSON) -> EngineMeta? { if let syncID = json["syncID"].asString { if let version = json["version"].asInt { return EngineMeta(version: version, syncID: syncID) } } return nil } public static func mapFromJSON(map: [String: JSON]?) -> [String: EngineMeta]? { if let map = map { return optFilter(mapValues(map, f: EngineMeta.fromJSON)) } return nil } public func toJSON() -> JSON { let json: [String: AnyObject] = ["version": self.version, "syncID": self.syncID] return JSON(json) } } public func ==(lhs: EngineMeta, rhs: EngineMeta) -> Bool { return (lhs.version == rhs.version) && (lhs.syncID == rhs.syncID) } public struct MetaGlobal: Equatable { let syncID: String let storageVersion: Int let engines: [String: EngineMeta]? // Is this really optional? let declined: [String]? public static func fromPayload(string: String) -> MetaGlobal? { return fromPayload(JSON(string: string)) } // TODO: is it more useful to support partial globals? // TODO: how do we return error states here? public static func fromPayload(json: JSON) -> MetaGlobal? { if json.isError { return nil } if let syncID = json["syncID"].asString { if let storageVersion = json["storageVersion"].asInt { let engines = EngineMeta.mapFromJSON(json["engines"].asDictionary) let declined = json["declined"].asArray return MetaGlobal(syncID: syncID, storageVersion: storageVersion, engines: engines, declined: jsonsToStrings(declined)) } } return nil } public func enginesPayload() -> JSON { if let engines = engines { return JSON(mapValues(engines, f: { $0.toJSON() })) } return JSON([:]) } // TODO: make a whole record JSON for this. public func toPayload() -> JSON { return JSON([ "syncID": self.syncID, "storageVersion": self.storageVersion, "engines": enginesPayload(), "declined": JSON(self.declined ?? []) ]) } } public func ==(lhs: MetaGlobal, rhs: MetaGlobal) -> Bool { return (lhs.syncID == rhs.syncID) && (lhs.storageVersion == rhs.storageVersion) && optArrayEqual(lhs.declined, rhs: rhs.declined) && optDictionaryEqual(lhs.engines, rhs: rhs.engines) } public class GlobalEnvelope: EnvelopeJSON { public lazy var global: MetaGlobal? = { return MetaGlobal.fromPayload(self.payload) }() public func toFetched() -> Fetched<MetaGlobal>? { if let g = global { return Fetched(value: g, timestamp: self.modified) } return nil } } /** * Encapsulates a meta/global, identity-derived keys, and keys. */ public class SyncMeta { let syncKey: KeyBundle var keys: Keys? var global: MetaGlobal? public init(syncKey: KeyBundle) { self.syncKey = syncKey } }
35ae7e974a3f8d63a8c1077706348677
31.66443
88
0.608794
false
false
false
false
Athlee/ATHKit
refs/heads/master
Example/Pods/Material/Sources/iOS/MotionPulse.swift
mit
2
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(PulseAnimation) public enum PulseAnimation: Int { case none case center case centerWithBacking case centerRadialBeyondBounds case radialBeyondBounds case backing case point case pointWithBacking } public protocol Pulseable { /// A reference to the PulseAnimation. var pulseAnimation: PulseAnimation { get set } /// A UIColor. var pulseColor: UIColor { get set } /// The opcaity value for the pulse animation. var pulseOpacity: CGFloat { get set } } public struct Pulse { /// A UIView that is Pulseable. fileprivate weak var pulseView: UIView? /// The layer the pulse layers are added to. fileprivate weak var pulseLayer: CALayer? /// Pulse layers. fileprivate var layers = [CAShapeLayer]() /// A reference to the PulseAnimation. public var animation = PulseAnimation.pointWithBacking /// A UIColor. public var color = Color.grey.base /// The opcaity value for the pulse animation. public var opacity: CGFloat = 0.18 /** An initializer that takes a given view and pulse layer. - Parameter pulseView: An optional UIView. - Parameter pulseLayer: An optional CALayer. */ internal init(pulseView: UIView?, pulseLayer: CALayer?) { self.pulseView = pulseView self.pulseLayer = pulseLayer } /** Triggers the expanding animation. - Parameter point: A point to pulse from. */ public mutating func expandAnimation(point: CGPoint) { guard let view = pulseView else { return } guard let layer = pulseLayer else { return } guard .none != animation else { return } let bLayer = CAShapeLayer() let pLayer = CAShapeLayer() bLayer.addSublayer(pLayer) layer.addSublayer(bLayer) bLayer.zPosition = 0 pLayer.zPosition = 0 layers.insert(bLayer, at: 0) layer.masksToBounds = !(.centerRadialBeyondBounds == animation || .radialBeyondBounds == animation) let w = view.bounds.width let h = view.bounds.height Motion.disable(animations: { [ n = .center == animation ? w < h ? w : h : w < h ? h : w, bounds = layer.bounds, animation = animation, color = color, opacity = opacity ] in bLayer.frame = bounds pLayer.bounds = CGRect(x: 0, y: 0, width: n, height: n) switch animation { case .center, .centerWithBacking, .centerRadialBeyondBounds: pLayer.position = CGPoint(x: w / 2, y: h / 2) default: pLayer.position = point } pLayer.cornerRadius = n / 2 pLayer.backgroundColor = color.withAlphaComponent(opacity).cgColor pLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(scaleX: 0, y: 0)) }) bLayer.setValue(false, forKey: "animated") let duration: CFTimeInterval = .center == animation ? 0.16125 : 0.325 switch animation { case .centerWithBacking, .backing, .pointWithBacking: bLayer.add(Motion.backgroundColor(color: color.withAlphaComponent(opacity / 2), duration: duration), forKey: nil) default:break } switch animation { case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking: pLayer.add(Motion.scale(by: 1, duration: duration), forKey: nil) default:break } Motion.delay(time: duration) { bLayer.setValue(true, forKey: "animated") } } /// Triggers the contracting animation. public mutating func contractAnimation() { guard let bLayer = layers.popLast() else { return } guard let animated = bLayer.value(forKey: "animated") as? Bool else { return } Motion.delay(time: animated ? 0 : 0.15) { [animation = animation, color = color] in guard let pLayer = bLayer.sublayers?.first as? CAShapeLayer else { return } let duration = 0.325 switch animation { case .centerWithBacking, .backing, .pointWithBacking: bLayer.add(Motion.backgroundColor(color: color.withAlphaComponent(0), duration: duration), forKey: nil) default:break } switch animation { case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking: pLayer.add(Motion.animate(group: [ Motion.scale(by: .center == animation ? 1 : 1.325), Motion.backgroundColor(color: color.withAlphaComponent(0)) ], duration: duration), forKey: nil) default:break } Motion.delay(time: duration) { pLayer.removeFromSuperlayer() bLayer.removeFromSuperlayer() } } } }
c0f3a81123f2790b8b1755846661f122
33.98995
125
0.616114
false
false
false
false
mckaskle/FlintKit
refs/heads/master
FlintKit/UIKit/CellRegistration.swift
mit
1
// // MIT License // // CellRegistration.swift // // Copyright (c) 2016 Devin McKaskle // // 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 // Adapted from: // https://medium.com/@gonzalezreal/ios-cell-registration-reusing-with-swift-protocol-extensions-and-generics-c5ac4fb5b75e#.me93xp4ki public protocol ReusableView: class { static var reuseIdentifier: String { get } } public extension ReusableView where Self: UIView { static var reuseIdentifier: String { return String(describing: self) } } extension UICollectionReusableView: ReusableView {} extension UITableViewCell: ReusableView {} public protocol ReusableSupplementaryView: ReusableView { static var supplementaryViewKind: String { get } } public extension UICollectionView { func register<T: UICollectionViewCell>(_: T.Type) { register(T.self, forCellWithReuseIdentifier: T.reuseIdentifier) } func register<T: UICollectionReusableView>(_: T.Type) where T: ReusableSupplementaryView { register(T.self, forSupplementaryViewOfKind: T.supplementaryViewKind, withReuseIdentifier: T.reuseIdentifier) } func register<T: UICollectionViewCell>(_: T.Type) where T:NibLoadableView { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forCellWithReuseIdentifier: T.reuseIdentifier) } func register<T: UICollectionReusableView>(_: T.Type) where T: ReusableSupplementaryView, T:NibLoadableView { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forSupplementaryViewOfKind: T.supplementaryViewKind, withReuseIdentifier: T.reuseIdentifier) } func dequeueCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError() } return cell } func dequeueSupplementaryView<T: UICollectionReusableView>(for indexPath: IndexPath) -> T where T: ReusableSupplementaryView { guard let view = dequeueReusableSupplementaryView(ofKind: T.supplementaryViewKind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError() } return view } } public extension UITableView { func register<T: UITableViewCell>(_: T.Type) { self.register(T.self, forCellReuseIdentifier: T.reuseIdentifier) } func register<T: UITableViewCell>(_: T.Type) where T:NibLoadableView { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) self.register(nib, forCellReuseIdentifier: T.reuseIdentifier) } func dequeueCell<T: UITableViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError() } return cell } }
16476878d62ece4b0b74ddb7a8b1bf60
33.426087
155
0.739076
false
false
false
false
MadAppGang/SmartLog
refs/heads/master
Carthage/Checkouts/Dip/Sources/TypeForwarding.swift
mit
3
// // Dip // // Copyright (c) 2015 Olivier Halligon <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // protocol TypeForwardingDefinition: DefinitionType { var implementingTypes: [Any.Type] { get } func doesImplements(type aType: Any.Type) -> Bool } #if swift(>=3.0) extension Definition { /** Registers definition for passed type. If instance created by factory of definition on which method is called does not implement type passed in a `type` parameter, container will throw `DipError.DefinitionNotFound` error when trying to resolve that type. - parameters: - type: Type to register definition for - tag: Optional tag to associate definition with. Default is `nil`. - returns: definition on which `implements` was called */ @discardableResult public func implements<F>(_ type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition { precondition(container != nil, "Definition should be registered in the container.") container!.register(self, type: type, tag: tag) return self } /** Registers definition for passed type. If instance created by factory of definition on which method is called does not implement type passed in a `type` parameter, container will throw `DipError.DefinitionNotFound` error when trying to resolve that type. - parameters: - type: Type to register definition for - tag: Optional tag to associate definition with. Default is `nil`. - resolvingProperties: Optional block to be called to resolve instance property dependencies - returns: definition on which `implements` was called */ @discardableResult public func implements<F>(_ type: F.Type, tag: DependencyTagConvertible? = nil, resolvingProperties: @escaping (DependencyContainer, F) throws -> ()) -> Definition { precondition(container != nil, "Definition should be registered in the container.") let forwardDefinition = container!.register(self, type: type, tag: tag) forwardDefinition.resolvingProperties(resolvingProperties) return self } ///Registers definition for types passed as parameters @discardableResult public func implements<A, B>(_ a: A.Type, _ b: B.Type) -> Definition { return implements(a).implements(b) } ///Registers definition for types passed as parameters @discardableResult public func implements<A, B, C>(_ a: A.Type, _ b: B.Type, _ c: C.Type) -> Definition { return implements(a).implements(b).implements(c) } ///Registers definition for types passed as parameters @discardableResult public func implements<A, B, C, D>(_ a: A.Type, _ b: B.Type, c: C.Type, d: D.Type) -> Definition { return implements(a).implements(b).implements(c).implements(d) } } #endif extension DependencyContainer { func _register<T, U, F>(definition aDefinition: Definition<T, U>, type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition<F, U> { let definition = aDefinition precondition(definition.container === self, "Definition should be registered in the container.") let key = DefinitionKey(type: F.self, typeOfArguments: U.self) let forwardDefinition = DefinitionBuilder<F, U> { $0.scope = definition.scope let factory = definition.factory $0.factory = { [unowned self] in let resolved = try factory($0) if let resolved = resolved as? F { return resolved } else { throw DipError.invalidType(resolved: resolved, key: key.tagged(with: self.context.tag)) } } $0.numberOfArguments = definition.numberOfArguments $0.autoWiringFactory = definition.autoWiringFactory.map({ factory in { [unowned self] in let resolved = try factory($0, $1) if let resolved = resolved as? F { return resolved } else { throw DipError.invalidType(resolved: resolved, key: key.tagged(with: self.context.tag)) } } }) $0.forwardsTo = definition }.build() register(forwardDefinition, tag: tag) return forwardDefinition } /// Searches for definition that forwards requested type func typeForwardingDefinition(forKey key: DefinitionKey) -> KeyDefinitionPair? { var forwardingDefinitions = self.definitions.map({ (key: $0.0, definition: $0.1) }) forwardingDefinitions = filter(definitions: forwardingDefinitions, byKey: key, byTypeOfArguments: true) forwardingDefinitions = order(definitions: forwardingDefinitions, byTag: key.tag) //we need to carry on original tag return forwardingDefinitions.first.map({ ($0.key.tagged(with: key.tag), $0.definition) }) } }
22d4b5b7326ed8de9ae2657284405de7
38.251701
186
0.7
false
false
false
false
geetaristo/react-preso
refs/heads/master
luttrellMusic/iOS/MusicPlayer.swift
mit
1
// // PlayMusic.swift // luttrellMusic // // Created by Michael Luttrell on 5/20/15. // Copyright (c) 2015 Facebook. All rights reserved. // import Foundation import AVFoundation @objc(MusicPlayer) class MusicPlayer : NSObject, AVAudioPlayerDelegate { var audioPlayer:AVAudioPlayer? = nil var donePlaying: RCTResponseSenderBlock? = nil var title:String? = nil override init(){ } @objc func playSong(title: String, url: String, loadedCallback: RCTResponseSenderBlock, donePlaying: RCTResponseSenderBlock) -> Void { // save the callback and the title for done playing self.donePlaying = donePlaying self.title = title // var songFileName = url.lastPathComponent // we'll use this to save our file information let audioFile = NSURL(string: url)! let request = NSURLRequest(URL: audioFile) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in if error != nil { loadedCallback(["error"]) } do { try self.audioPlayer = AVAudioPlayer(data: data!, fileTypeHint: nil) } catch { print("can not create audio player, yo?") } if let player = self.audioPlayer { player.delegate = self; player.prepareToPlay() player.play() loadedCallback([title]) } else { print("Error attempting to play file: \(url). Possibly no internet connection") } } } @objc func stopPlayer() -> Void { if let player = self.audioPlayer { player.stop() } } @objc func audioPlayerDidFinishPlaying(_: AVAudioPlayer, successfully: Bool) { print("audio player finished playing") // if let donePlaying = self.donePlaying { // donePlaying([self.title!]) // } } } // func saveFile(data: NSData){ // let filemgr = NSFileManager.defaultManager() // let currentPath = filemgr.currentDirectoryPath // println("current path is \(currentPath)") // var error:NSError? = nil // let filelist = filemgr.contentsOfDirectoryAtPath("/", error: &error) // // for filename in filelist! { // println(filename) // } // } // // func loadLocalFile(fileName:String) -> NSData { // return NSData() // } //
86548aa594bbdb6b24d217e647795048
23.783505
119
0.611481
false
false
false
false
Webtrekk/webtrekk-ios-sdk
refs/heads/master
Source/Internal/Utility/ClosedInterval.swift
mit
1
internal extension ClosedRange { func clamp(_ value: Bound) -> Bound { if value < lowerBound { return lowerBound } if value > upperBound { return upperBound } return value } } internal extension ClosedRange where Bound: MinimumMaximumAware { var conditionText: String { if lowerBound.isMinimum && upperBound.isMaximum { return "any value" } if upperBound.isMaximum { return ">= \(lowerBound)" } if lowerBound.isMinimum { return "<= \(upperBound)" } return ">= \(lowerBound) and <= \(upperBound)" } } internal protocol MinimumMaximumAware { var isMaximum: Bool { get } var isMinimum: Bool { get } } extension Float: MinimumMaximumAware { internal var isMaximum: Bool { return sign == .plus && isInfinite } internal var isMinimum: Bool { return sign == .minus && isInfinite } } extension Double: MinimumMaximumAware { internal var isMaximum: Bool { return sign == .plus && isInfinite } internal var isMinimum: Bool { return sign == .minus && isInfinite } } extension Int: MinimumMaximumAware { internal var isMaximum: Bool { return self == .max } internal var isMinimum: Bool { return self == .min } }
5ef0a2bd21b01ae1ffefef396129199f
16.26087
65
0.675063
false
false
false
false
nathankot/RxSwift
refs/heads/master
Playgrounds/ObservablesOperators/Observables+Filtering.playground/Contents.swift
mit
2
import Cocoa import RxSwift /*: ## Filtering Observables Operators that selectively emit items from a source Observable. ### `where` / `filter` emit only those items from an Observable that pass a predicate test [More info in reactive.io website]( http://reactivex.io/documentation/operators/filter.html ) */ example("filter") { let onlyEvensSubscriber = returnElements(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >- filter { $0 % 2 == 0 } >- subscribeNext { value in println("\(value)") } } /*: ### `distinctUntilChanged` suppress duplicate items emitted by an Observable [More info in reactive.io website]( http://reactivex.io/documentation/operators/distinct.html ) */ example("distinctUntilChanged") { let distinctUntilChangedSubscriber = returnElements(1, 2, 3, 1, 1, 4) >- distinctUntilChanged >- subscribeNext { value in println("\(value)") } } /*: ### `take` Emit only the first n items emitted by an Observable [More info in reactive.io website]( http://reactivex.io/documentation/operators/take.html ) */ example("take") { let distinctUntilChangedSubscriber = returnElements(1, 2, 3, 4, 5, 6) >- take(3) >- subscribeNext { value in println("\(value)") } }
ce9af49160488981e2381a4a0d074444
21.719298
95
0.640927
false
false
false
false
omochi/numsw
refs/heads/master
Sources/numsw/Matrix/MatrixMultiply.swift
mit
1
#if os(iOS) || os(OSX) import Accelerate public func *(lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> { return multiplyAccelerate(lhs, rhs) } public func *(lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> { return multiplyAccelerate(lhs, rhs) } func multiplyAccelerate(_ lhs: Matrix<Float>, _ rhs: Matrix<Float>) -> Matrix<Float> { precondition(lhs.columns == rhs.rows, "Matrices can't multiply.") let count = lhs.rows * rhs.columns let cElements = UnsafeMutablePointer<Float>.allocate(capacity: count) defer { cElements.deallocate(capacity: count) } vDSP_mmul(lhs.elements, 1, rhs.elements, 1, cElements, 1, vDSP_Length(lhs.rows), vDSP_Length(rhs.columns), vDSP_Length(lhs.columns)) return Matrix(rows: lhs.rows, columns: rhs.columns, elements: Array(UnsafeBufferPointer(start: cElements, count: count))) } func multiplyAccelerate(_ lhs: Matrix<Double>, _ rhs: Matrix<Double>) -> Matrix<Double> { precondition(lhs.columns == rhs.rows, "Matrices can't multiply.") let count = lhs.rows * rhs.columns let cElements = UnsafeMutablePointer<Double>.allocate(capacity: count) defer { cElements.deallocate(capacity: count) } vDSP_mmulD(lhs.elements, 1, rhs.elements, 1, cElements, 1, vDSP_Length(lhs.rows), vDSP_Length(rhs.columns), vDSP_Length(lhs.columns)) return Matrix(rows: lhs.rows, columns: rhs.columns, elements: Array(UnsafeBufferPointer(start: cElements, count: count))) } #endif public func *<T: Arithmetic>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<T> { return multiply(lhs, rhs) } /// Multiply (m x p) matrix lhs and, (p x n) matrix rhs /// - Returns: Result of matrix multipliation of lhs and rhs func multiply<T: Arithmetic>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<T> { precondition(lhs.columns == rhs.rows, "Matrices can't multiply.") // multiply m*p matrix A and p*n matrix B, return m*n matrix C let m = lhs.rows let n = rhs.columns let p = lhs.columns let count = m * n let cElements = UnsafeMutablePointer<T>.allocate(capacity: count) defer { cElements.deallocate(capacity: count) } // init C[i,j] with A[i,0] * B[0,j] var ptr = cElements var lp = UnsafePointer(lhs.elements) var rp = UnsafePointer(rhs.elements) for i in 0..<m { for j in 0..<n { ptr.pointee = lp[i*p] * rp[j] ptr += 1 } } // add A[i,k] * B[k,j] for C[i,j] for i in 0..<m { lp = UnsafePointer(lhs.elements) + i*p + 1 for k in 1..<p { rp = UnsafePointer(rhs.elements) + k*n ptr = cElements + i*n for _ in 0..<n { ptr.pointee += lp.pointee * rp.pointee rp += 1 ptr += 1 } lp += 1 } } return Matrix(rows: m, columns: n, elements: Array(UnsafeBufferPointer(start: cElements, count: count))) }
097f1442c57300ff4ed17f70bf9400f3
32.019608
93
0.544834
false
false
false
false
coolmacmaniac/swift-ios
refs/heads/master
Stanford/FaceIt/FaceIt/Views/FaceView.swift
gpl-3.0
1
// // FaceView.swift // FaceIt // // Created by Sourabh on 08/05/17. // Copyright © 2017 Home. All rights reserved. // import UIKit @IBDesignable class FaceView: UIView { @IBInspectable public var scale: CGFloat = 0.45 { didSet { setNeedsDisplay() } } @IBInspectable public var lineWidth: CGFloat = 5.0 { didSet { setNeedsDisplay() } } @IBInspectable // -1 means sad, 1 means happy public var mouthCurvature: CGFloat = 0.0 { didSet { setNeedsDisplay() } } @IBInspectable // -1 means angry, 1 means happy public var eyebrowTilt: CGFloat = 1.0 { didSet { setNeedsDisplay() } } @IBInspectable public var pathColor: UIColor = UIColor.orange { didSet { setNeedsDisplay() } } @IBInspectable public var eyesOpen: Bool = true { didSet { setNeedsDisplay() } } private struct Ratios { static let SkullRadiusToEyeOffset: CGFloat = 3 static let SkullRadiusToEyeRadius: CGFloat = 10 static let SkullRadiusToMouthOffset: CGFloat = 3 static let SkullRadiusToMouthWidth: CGFloat = 1 static let SkullRadiusToMouthHeight: CGFloat = 3 static let SkullRadiusToEyebrowOffset: CGFloat = 5//10 } private enum Eye { case Left case Right } public dynamic var skullRadius: CGFloat { AutoreleasingUnsafeMutablePointer return min(bounds.size.width, bounds.size.height) / 2 * scale } private var skullCenter: CGPoint { return CGPoint(x: bounds.midX, y: bounds.midY) } private func pathForCircleCenteredAtPoint(_ center: CGPoint, widthRadius radius: CGFloat) -> UIBezierPath { // create the circle path points let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle: CGFloat(2 * Double.pi), clockwise: false) // set the line width path.lineWidth = lineWidth return path } private func centerForEye(_ eye: Eye) -> CGPoint { let eyeOffset = skullRadius / Ratios.SkullRadiusToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset switch eye { case .Left: eyeCenter.x -= eyeOffset case .Right: eyeCenter.x += eyeOffset } return eyeCenter } private func pathForEye(_ eye: Eye) -> UIBezierPath { let eyeRadius = skullRadius / Ratios.SkullRadiusToEyeRadius let eyeCenter = centerForEye(eye) if eyesOpen { return pathForCircleCenteredAtPoint(eyeCenter, widthRadius: eyeRadius) } let path = UIBezierPath() path.move(to: CGPoint(x: eyeCenter.x - eyeRadius, y: eyeCenter.y)) path.addLine(to: CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y)) path.lineWidth = lineWidth return path } private func pathForEyebrow(_ eye: Eye) -> UIBezierPath { let widthOffset = skullRadius / Ratios.SkullRadiusToEyeRadius let heightOffset = skullRadius / Ratios.SkullRadiusToEyebrowOffset var tilt = eyebrowTilt switch eye { case .Left: tilt *= -1 case .Right: break } var center = centerForEye(eye) center.y -= heightOffset let tiltOffset = CGFloat(max(-1, min(tilt, 1))) * widthOffset / 2 let start = CGPoint(x: center.x - widthOffset, y: center.y - tiltOffset) let end = CGPoint(x: center.x + widthOffset, y: center.y + tiltOffset) let path = UIBezierPath() path.move(to: start) path.addLine(to: end) path.lineWidth = lineWidth return path } private func pathForMouth() -> UIBezierPath { let mouthWidth = skullRadius / Ratios.SkullRadiusToMouthWidth let mouthHeight = skullRadius / Ratios.SkullRadiusToMouthHeight let mouthOffset = skullRadius / Ratios.SkullRadiusToMouthOffset let mouthRect = CGRect( x: skullCenter.x - mouthWidth / 2, y: skullCenter.y + mouthOffset, width: mouthWidth, height: mouthHeight ) let smileOffset = CGFloat(max(-1, min(mouthCurvature, 1))) * mouthRect.height let start = CGPoint(x: mouthRect.minX, y: mouthRect.minY) let end = CGPoint(x: mouthRect.maxX, y: mouthRect.minY) let cp1 = CGPoint(x: mouthRect.minX + mouthWidth / 3, y: mouthRect.minY + smileOffset) let cp2 = CGPoint(x: mouthRect.maxX - mouthWidth / 3, y: mouthRect.minY + smileOffset) let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } // override draw() as we perform custom drawing override func draw(_ rect: CGRect) { // set the stroke and fill colour pathColor.set() // draw the bezier paths with predefined properties pathForCircleCenteredAtPoint(skullCenter, widthRadius: skullRadius).stroke() pathForEyebrow(.Left).stroke() pathForEyebrow(.Right).stroke() pathForEye(.Left).stroke() pathForEye(.Right).stroke() pathForMouth().stroke() } public func changeScale(_ recognizer: UIPinchGestureRecognizer) { switch recognizer.state { case .changed, .ended: scale *= recognizer.scale scale = max(0.1, min(0.9, scale)) recognizer.scale = 1.0 default: break } } }
655c538c0962ca245208c675298e5929
28.114458
129
0.714049
false
false
false
false
daltonclaybrook/tween-controller
refs/heads/master
TweenControllerTests/KeypathListener.swift
mit
1
// // KeypathListener.swift // TweenController // // Created by Dalton Claybrook on 1/9/17. // // Copyright (c) 2017 Dalton Claybrook // // 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 TweenController class KeypathListener<T: Tweenable>: NSObject { let keyPath = "com.claybrooksoftware.tweencontroller.keyPath" private(set) var values = [T]() override func setValue(_ value: Any?, forKeyPath keyPath: String) { guard keyPath == self.keyPath, let tweenable = value as? T else { super.setValue(value, forKeyPath: keyPath) return } values.append(tweenable) } }
a37853e01b84a3f61e64fb32143a6583
38.651163
82
0.719648
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/toplevel.swift
apache-2.0
3
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func markUsed<T>(_ t: T) {} func trap() -> Never { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): // -- initialize x // CHECK: alloc_global @_Tv8toplevel1xSi // CHECK: [[X:%[0-9]+]] = global_addr @_Tv8toplevel1xSi : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_TF8toplevel7print_xFT_T_ : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_Tv8toplevel5countSi // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_Tv8toplevel5countSi : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_Tv8toplevel1ySi // CHECK: [[Y1:%[0-9]+]] = global_addr @_Tv8toplevel1ySi : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_TF8toplevel7print_yFT_T_ y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [[BOX:%.+]] : $*A // CHECK-NOT: release // CHECK: [[SINK:%.+]] = function_ref @_TF8toplevel8markUsedurFxT_ // CHECK-NOT: release // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8toplevel7print_xFT_T_ // CHECK-LABEL: sil hidden @_TF8toplevel7print_yFT_T_ // CHECK: sil hidden @_TF8toplevel13testGlobalCSEFT_Si // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_Tv8toplevel1xSi : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
10e54ec588c0807341c4e9368349f4bb
25.217742
104
0.634266
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Comments/CommentDetailViewController.swift
gpl-2.0
1
import UIKit import CoreData // Notification sent when a Comment is permanently deleted so the Notifications list (NotificationsViewController) is immediately updated. extension NSNotification.Name { static let NotificationCommentDeletedNotification = NSNotification.Name(rawValue: "NotificationCommentDeletedNotification") } let userInfoCommentIdKey = "commentID" @objc protocol CommentDetailsDelegate: AnyObject { func nextCommentSelected() } class CommentDetailViewController: UIViewController, NoResultsViewHost { // MARK: Properties private let accountService: AccountService private let containerStackView = UIStackView() private let tableView = UITableView(frame: .zero, style: .plain) // Reply properties private var replyTextView: ReplyTextView? private var suggestionsTableView: SuggestionsTableView? private var keyboardManager: KeyboardDismissHelper? private var dismissKeyboardTapGesture = UITapGestureRecognizer() @objc weak var commentDelegate: CommentDetailsDelegate? private weak var notificationDelegate: CommentDetailsNotificationDelegate? private var comment: Comment private var isLastInList = true private var managedObjectContext: NSManagedObjectContext private var sections = [SectionType] () private var rows = [RowType]() private var commentStatus: CommentStatusType? { didSet { switch commentStatus { case .pending: unapproveComment() case .approved: approveComment() case .spam: spamComment() case .unapproved: trashComment() default: break } } } private var notification: Notification? private var isNotificationComment: Bool { notification != nil } private var viewIsVisible: Bool { return navigationController?.visibleViewController == self } private var siteID: NSNumber? { return comment.blog?.dotComID ?? notification?.metaSiteID } private var replyID: Int32 { return comment.replyID } private var isCommentReplied: Bool { replyID > 0 } // MARK: Views private var headerCell = CommentHeaderTableViewCell() private lazy var replyIndicatorCell: UITableViewCell = { let cell = UITableViewCell() // display the replied icon using attributed string instead of using the default image view. // this is because the default image view is displayed beyond the separator line (within the layout margin area). let iconAttachment = NSTextAttachment() iconAttachment.image = Style.ReplyIndicator.iconImage let attributedString = NSMutableAttributedString() attributedString.append(.init(attachment: iconAttachment, attributes: Style.ReplyIndicator.textAttributes)) attributedString.append(.init(string: " " + .replyIndicatorLabelText, attributes: Style.ReplyIndicator.textAttributes)) // reverse the attributed strings in RTL direction. if view.effectiveUserInterfaceLayoutDirection == .rightToLeft { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.baseWritingDirection = .rightToLeft attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: .init(location: 0, length: attributedString.length)) } cell.textLabel?.attributedText = attributedString cell.textLabel?.numberOfLines = 0 // setup constraints for textLabel to match the spacing specified in the design. if let textLabel = cell.textLabel { textLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ textLabel.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor), textLabel.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor), textLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: Constants.replyIndicatorVerticalSpacing), textLabel.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -Constants.replyIndicatorVerticalSpacing) ]) } return cell }() private lazy var moderationCell: UITableViewCell = { return $0 }(UITableViewCell()) private lazy var deleteButtonCell: BorderedButtonTableViewCell = { let cell = BorderedButtonTableViewCell() cell.configure(buttonTitle: .deleteButtonText, titleFont: WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular), normalColor: Constants.deleteButtonNormalColor, highlightedColor: Constants.deleteButtonHighlightColor, buttonInsets: Constants.deleteButtonInsets) cell.delegate = self return cell }() private lazy var trashButtonCell: BorderedButtonTableViewCell = { let cell = BorderedButtonTableViewCell() cell.configure(buttonTitle: .trashButtonText, titleFont: WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular), normalColor: Constants.deleteButtonNormalColor, highlightedColor: Constants.trashButtonHighlightColor, borderColor: .clear, buttonInsets: Constants.deleteButtonInsets, backgroundColor: Constants.trashButtonBackgroundColor) cell.delegate = self return cell }() private lazy var commentService: CommentService = { return .init(managedObjectContext: managedObjectContext) }() /// Ideally, this property should be configurable as one of the initialization parameters (to make this testable). /// However, since this class is still initialized in Objective-C files, it cannot declare `ContentCoordinator` as the init parameter, unless the protocol /// is `@objc`-ified. Let's move this to the init parameter once the caller has been converted to Swift. private lazy var contentCoordinator: ContentCoordinator = { return DefaultContentCoordinator(controller: self, context: managedObjectContext) }() // Sometimes the parent information of a comment reply notification is in the meta block. private var notificationParentComment: Comment? { guard let parentID = notification?.metaParentID, let siteID = notification?.metaSiteID, let blog = Blog.lookup(withID: siteID, in: managedObjectContext), let parentComment = blog.comment(withID: parentID) else { return nil } return parentComment } private var parentComment: Comment? { guard comment.hasParentComment() else { return nil } if let blog = comment.blog { return blog.comment(withID: comment.parentID) } if let post = comment.post as? ReaderPost { return post.comment(withID: comment.parentID) } return nil } // transparent navigation bar style with visual blur effect. private lazy var blurredBarAppearance: UINavigationBarAppearance = { let appearance = UINavigationBarAppearance() appearance.configureWithTransparentBackground() appearance.backgroundEffect = UIBlurEffect(style: .systemThinMaterial) return appearance }() /// opaque navigation bar style. /// this is used for iOS 14 and below, since scrollEdgeAppearance only applies for large title bars, except on iOS 15 where it applies for all navbars. private lazy var opaqueBarAppearance: UINavigationBarAppearance = { let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() return appearance }() /// Convenience property that keeps track of whether the content has scrolled. private var isContentScrolled: Bool = false { didSet { if isContentScrolled == oldValue { return } // show blurred navigation bar when content is scrolled, or opaque style when the scroll position is at the top. updateNavigationBarAppearance(isBlurred: isContentScrolled) } } // MARK: Nav Bar Buttons private(set) lazy var editBarButtonItem: UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editButtonTapped)) button.accessibilityLabel = NSLocalizedString("Edit comment", comment: "Accessibility label for button to edit a comment from a notification") return button }() private(set) lazy var shareBarButtonItem: UIBarButtonItem = { let button = UIBarButtonItem( image: comment.allowsModeration() ? UIImage(systemName: Style.Content.ellipsisIconImageName) : UIImage(systemName: Style.Content.shareIconImageName), style: .plain, target: self, action: #selector(shareCommentURL) ) button.accessibilityLabel = NSLocalizedString("Share comment", comment: "Accessibility label for button to share a comment from a notification") return button }() // MARK: Initialization @objc init(comment: Comment, isLastInList: Bool, managedObjectContext: NSManagedObjectContext = ContextManager.sharedInstance().mainContext) { self.comment = comment self.commentStatus = CommentStatusType.typeForStatus(comment.status) self.isLastInList = isLastInList self.managedObjectContext = managedObjectContext self.accountService = AccountService(managedObjectContext: managedObjectContext) super.init(nibName: nil, bundle: nil) } init(comment: Comment, notification: Notification, notificationDelegate: CommentDetailsNotificationDelegate?, managedObjectContext: NSManagedObjectContext = ContextManager.sharedInstance().mainContext) { self.comment = comment self.commentStatus = CommentStatusType.typeForStatus(comment.status) self.notification = notification self.notificationDelegate = notificationDelegate self.managedObjectContext = managedObjectContext self.accountService = AccountService(managedObjectContext: managedObjectContext) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() configureView() configureReplyView() setupKeyboardManager() configureSuggestionsView() configureNavigationBar() configureTable() configureSections() refreshCommentReplyIfNeeded() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardManager?.startListeningToKeyboardNotifications() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardManager?.stopListeningToKeyboardNotifications() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // when an orientation change is triggered, recalculate the content cell's height. guard let contentRowIndex = rows.firstIndex(of: .content) else { return } tableView.reloadRows(at: [.init(row: contentRowIndex, section: .zero)], with: .fade) } // Update the Comment being displayed. @objc func displayComment(_ comment: Comment, isLastInList: Bool = true) { self.comment = comment self.isLastInList = isLastInList replyTextView?.placeholder = String(format: .replyPlaceholderFormat, comment.authorForDisplay()) refreshData() refreshCommentReplyIfNeeded() } // Update the Notification Comment being displayed. func refreshView(comment: Comment, notification: Notification) { hideNoResults() self.notification = notification displayComment(comment) } // Show an empty view with the given values. func showNoResultsView(title: String, subtitle: String? = nil, imageName: String? = nil, accessoryView: UIView? = nil) { hideNoResults() configureAndDisplayNoResults(on: tableView, title: title, subtitle: subtitle, image: imageName, accessoryView: accessoryView) } } // MARK: - Private Helpers private extension CommentDetailViewController { typealias Style = WPStyleGuide.CommentDetail enum SectionType: Equatable { case content([RowType]) case moderation([RowType]) } enum RowType: Equatable { case header case content case replyIndicator case status(status: CommentStatusType) case deleteComment } struct Constants { static let tableHorizontalInset: CGFloat = 20.0 static let tableBottomMargin: CGFloat = 40.0 static let replyIndicatorVerticalSpacing: CGFloat = 14.0 static let deleteButtonInsets = UIEdgeInsets(top: 4, left: 20, bottom: 4, right: 20) static let deleteButtonNormalColor = UIColor(light: .error, dark: .muriel(name: .red, .shade40)) static let deleteButtonHighlightColor: UIColor = .white static let trashButtonBackgroundColor = UIColor.quaternarySystemFill static let trashButtonHighlightColor: UIColor = UIColor.tertiarySystemFill static let notificationDetailSource = ["source": "notification_details"] } /// Convenience computed variable for an inset setting that hides a cell's separator by pushing it off the edge of the screen. /// This needs to be computed because the frame size changes on orientation change. /// NOTE: There's no need to flip the insets for RTL language, since it will be automatically applied. var insetsForHiddenCellSeparator: UIEdgeInsets { return .init(top: 0, left: -tableView.separatorInset.left, bottom: 0, right: tableView.frame.size.width) } /// returns the height of the navigation bar + the status bar. var topBarHeight: CGFloat { return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) + (navigationController?.navigationBar.frame.height ?? 0.0) } /// determines the threshold for the content offset on whether the content has scrolled. /// for translucent navigation bars, the content view spans behind the status bar and navigation bar so we'd have to account for that. var contentScrollThreshold: CGFloat { (navigationController?.navigationBar.isTranslucent ?? false) ? -topBarHeight : 0 } func configureView() { containerStackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(containerStackView) containerStackView.axis = .vertical containerStackView.addArrangedSubview(tableView) view.pinSubviewToAllEdges(containerStackView) } func configureNavigationBar() { if #available(iOS 15, *) { // In iOS 15, to apply visual blur only when content is scrolled, keep the scrollEdgeAppearance unchanged as it applies to ALL navigation bars. navigationItem.standardAppearance = blurredBarAppearance } else { // For iOS 14 and below, scrollEdgeAppearance only affects large title navigation bars. Therefore we need to manually detect if the content // has been scrolled and change the appearance accordingly. updateNavigationBarAppearance() } navigationController?.navigationBar.isTranslucent = true configureNavBarButton() } /// Updates the navigation bar style based on the `isBlurred` boolean parameter. The intent is to show a visual blur effect when the content is scrolled, /// but reverts to opaque style when the scroll position is at the top. This method may be called multiple times since it's triggered by the `didSet` /// property observer on the `isContentScrolled` property. func updateNavigationBarAppearance(isBlurred: Bool = false) { navigationItem.standardAppearance = isBlurred ? blurredBarAppearance : opaqueBarAppearance } func configureNavBarButton() { var barItems: [UIBarButtonItem] = [] barItems.append(shareBarButtonItem) if comment.allowsModeration() { barItems.append(editBarButtonItem) } navigationItem.setRightBarButtonItems(barItems, animated: false) } func configureTable() { tableView.delegate = self tableView.dataSource = self tableView.separatorInsetReference = .fromAutomaticInsets // get rid of the separator line for the last cell. tableView.tableFooterView = UIView(frame: .init(x: 0, y: 0, width: tableView.frame.size.width, height: Constants.tableBottomMargin)) // assign 20pt leading inset to the table view, as per the design. tableView.directionalLayoutMargins = .init(top: tableView.directionalLayoutMargins.top, leading: Constants.tableHorizontalInset, bottom: tableView.directionalLayoutMargins.bottom, trailing: Constants.tableHorizontalInset) tableView.register(CommentContentTableViewCell.defaultNib, forCellReuseIdentifier: CommentContentTableViewCell.defaultReuseID) } func configureContentRows() -> [RowType] { // Header and content cells should always be visible, regardless of user roles. var rows: [RowType] = [.header, .content] if isCommentReplied { rows.append(.replyIndicator) } return rows } func configureModeratationRows() -> [RowType] { var rows: [RowType] = [] rows.append(.status(status: .approved)) rows.append(.status(status: .pending)) rows.append(.status(status: .spam)) rows.append(.deleteComment) return rows } func configureSections() { var sections: [SectionType] = [] sections.append(.content(configureContentRows())) if comment.allowsModeration() { sections.append(.moderation(configureModeratationRows())) } self.sections = sections } /// Performs a complete refresh on the table and the row configuration, since some rows may be hidden due to changes to the Comment object. /// Use this method instead of directly calling the `reloadData` on the table view property. func refreshData() { configureNavBarButton() configureSections() tableView.reloadData() } /// Checks if the index path is positioned before the delete button cell. func shouldHideCellSeparator(for indexPath: IndexPath) -> Bool { switch sections[indexPath.section] { case .content: return false case .moderation(let rows): guard let deleteCellIndex = rows.firstIndex(of: .deleteComment) else { return false } return indexPath.row == deleteCellIndex - 1 } } // MARK: Cell configuration func configureHeaderCell() { // if the comment is a reply, show the author of the parent comment. if let parentComment = self.parentComment ?? notificationParentComment { return headerCell.configure(for: .reply(parentComment.authorForDisplay()), subtitle: parentComment.contentPreviewForDisplay().trimmingCharacters(in: .whitespacesAndNewlines)) } // otherwise, if this is a comment to a post, show the post title instead. headerCell.configure(for: .post, subtitle: comment.titleForDisplay()) } func configureContentCell(_ cell: CommentContentTableViewCell, comment: Comment) { cell.configure(with: comment) { [weak self] _ in self?.tableView.performBatchUpdates({}) } cell.contentLinkTapAction = { [weak self] url in // open all tapped links in web view. // TODO: Explore reusing URL handling logic from ReaderDetailCoordinator. self?.openWebView(for: url) } cell.accessoryButtonType = .info cell.accessoryButtonAction = { [weak self] senderView in self?.presentUserInfoSheet(senderView) } cell.likeButtonAction = { [weak self] in self?.toggleCommentLike() } cell.replyButtonAction = { [weak self] in self?.showReplyView() } } func configuredStatusCell(for status: CommentStatusType) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: .moderationCellIdentifier) ?? .init(style: .subtitle, reuseIdentifier: .moderationCellIdentifier) cell.selectionStyle = .none cell.tintColor = Style.tintColor cell.detailTextLabel?.font = Style.textFont cell.detailTextLabel?.textColor = Style.textColor cell.detailTextLabel?.numberOfLines = 0 cell.detailTextLabel?.text = status.title cell.accessoryView = status == commentStatus ? UIImageView(image: .gridicon(.checkmark)) : nil return cell } // MARK: Data Sync func refreshCommentReplyIfNeeded() { guard let siteID = siteID?.intValue else { return } commentService.getLatestReplyID(for: Int(comment.commentID), siteID: siteID) { [weak self] replyID in guard let self = self else { return } // only perform Core Data updates when the replyID differs. guard replyID != self.comment.replyID else { return } let context = self.comment.managedObjectContext ?? ContextManager.sharedInstance().mainContext self.comment.replyID = Int32(replyID) ContextManager.sharedInstance().saveContextAndWait(context) self.updateReplyIndicator() } failure: { error in DDLogError("Failed fetching latest comment reply ID: \(String(describing: error))") } } func updateReplyIndicator() { // If there is a reply, add reply indicator if it is not being shown. if replyID > 0 && !rows.contains(.replyIndicator) { // Update the rows first so replyIndicator is present in `rows`. configureSections() guard let replyIndicatorRow = rows.firstIndex(of: .replyIndicator) else { tableView.reloadData() return } tableView.insertRows(at: [IndexPath(row: replyIndicatorRow, section: .zero)], with: .fade) return } // If there is not a reply, remove reply indicator if it is being shown. if replyID == 0 && rows.contains(.replyIndicator) { // Get the reply indicator row first before it is removed via `configureRows`. guard let replyIndicatorRow = rows.firstIndex(of: .replyIndicator) else { return } configureSections() tableView.deleteRows(at: [IndexPath(row: replyIndicatorRow, section: .zero)], with: .fade) } } // MARK: Actions and navigations // Shows the comment thread with the Notification comment highlighted. func navigateToNotificationComment() { if let blog = comment.blog, !blog.supports(.wpComRESTAPI) { openWebView(for: comment.commentURL()) return } guard let siteID = siteID else { return } // Empty Back Button navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .plain, target: nil, action: nil) try? contentCoordinator.displayCommentsWithPostId(NSNumber(value: comment.postID), siteID: siteID, commentID: NSNumber(value: comment.commentID), source: .commentNotification) } // Shows the comment thread with the parent comment highlighted. func navigateToParentComment() { guard let parentComment = parentComment, let siteID = siteID, let blog = comment.blog, blog.supports(.wpComRESTAPI) else { let parentCommentURL = URL(string: parentComment?.link ?? "") openWebView(for: parentCommentURL) return } try? contentCoordinator.displayCommentsWithPostId(NSNumber(value: comment.postID), siteID: siteID, commentID: NSNumber(value: parentComment.commentID), source: .mySiteComment) } func navigateToReplyComment() { guard let siteID = siteID, isCommentReplied else { return } try? contentCoordinator.displayCommentsWithPostId(NSNumber(value: comment.postID), siteID: siteID, commentID: NSNumber(value: replyID), source: isNotificationComment ? .commentNotification : .mySiteComment) } func navigateToPost() { guard let blog = comment.blog, let siteID = siteID, blog.supports(.wpComRESTAPI) else { let postPermalinkURL = URL(string: comment.post?.permaLink ?? "") openWebView(for: postPermalinkURL) return } let readerViewController = ReaderDetailViewController.controllerWithPostID(NSNumber(value: comment.postID), siteID: siteID, isFeed: false) navigationController?.pushFullscreenViewController(readerViewController, animated: true) } func openWebView(for url: URL?) { guard let url = url else { DDLogError("\(Self.classNameWithoutNamespaces()): Attempted to open an invalid URL [\(url?.absoluteString ?? "")]") return } let viewController = WebViewControllerFactory.controllerAuthenticatedWithDefaultAccount(url: url, source: "comment_detail") let navigationControllerToPresent = UINavigationController(rootViewController: viewController) present(navigationControllerToPresent, animated: true, completion: nil) } @objc func editButtonTapped() { let editCommentTableViewController = EditCommentTableViewController(comment: comment, completion: { [weak self] comment, commentChanged in guard commentChanged else { return } self?.comment = comment self?.refreshData() self?.updateComment() }) CommentAnalytics.trackCommentEditorOpened(comment: comment) let navigationControllerToPresent = UINavigationController(rootViewController: editCommentTableViewController) navigationControllerToPresent.modalPresentationStyle = .fullScreen present(navigationControllerToPresent, animated: true) } func deleteButtonTapped() { let commentID = comment.commentID deleteComment() { [weak self] success in if success { self?.postNotificationCommentDeleted(commentID) // Dismiss the view since the Comment no longer exists. self?.navigationController?.popViewController(animated: true) } } } func updateComment() { // Regardless of success or failure track the user's intent to save a change. CommentAnalytics.trackCommentEdited(comment: comment) commentService.uploadComment(comment, success: { [weak self] in // The comment might have changed its approval status self?.refreshData() }, failure: { [weak self] error in let message = NSLocalizedString("There has been an unexpected error while editing your comment", comment: "Error displayed if a comment fails to get updated") self?.displayNotice(title: message) }) } func toggleCommentLike() { guard let siteID = siteID else { refreshData() // revert the like button state. return } if comment.isLiked { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentUnliked, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentUnLiked(comment: comment) } else { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentLiked, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentLiked(comment: comment) } commentService.toggleLikeStatus(for: comment, siteID: siteID, success: {}, failure: { _ in self.refreshData() // revert the like button state. }) } @objc func shareCommentURL(_ barButtonItem: UIBarButtonItem) { guard let commentURL = comment.commentURL() else { return } // track share intent. WPAnalytics.track(.siteCommentsCommentShared) let activityViewController = UIActivityViewController(activityItems: [commentURL as Any], applicationActivities: nil) activityViewController.popoverPresentationController?.barButtonItem = barButtonItem present(activityViewController, animated: true, completion: nil) } func presentUserInfoSheet(_ senderView: UIView) { let viewModel = CommentDetailInfoViewModel( url: comment.authorURL(), urlToDisplay: comment.authorUrlForDisplay(), email: comment.author_email, ipAddress: comment.author_ip, isAdmin: comment.allowsModeration() ) let viewController = CommentDetailInfoViewController(viewModel: viewModel) viewModel.view = viewController let bottomSheet = BottomSheetViewController(childViewController: viewController, customHeaderSpacing: 0) bottomSheet.show(from: self) } } // MARK: - Strings private extension String { // MARK: Constants static let replyIndicatorCellIdentifier = "replyIndicatorCell" static let textCellIdentifier = "textCell" static let moderationCellIdentifier = "moderationCell" // MARK: Localization static let replyPlaceholderFormat = NSLocalizedString("Reply to %1$@", comment: "Placeholder text for the reply text field." + "%1$@ is a placeholder for the comment author." + "Example: Reply to Pamela Nguyen") static let replyIndicatorLabelText = NSLocalizedString("You replied to this comment.", comment: "Informs that the user has replied to this comment.") static let deleteButtonText = NSLocalizedString("Delete Permanently", comment: "Title for button on the comment details page that deletes the comment when tapped.") static let trashButtonText = NSLocalizedString("Move to Trash", comment: "Title for button on the comment details page that moves the comment to trash when tapped.") } private extension CommentStatusType { var title: String? { switch self { case .pending: return NSLocalizedString("Pending", comment: "Button title for Pending comment state.") case .approved: return NSLocalizedString("Approved", comment: "Button title for Approved comment state.") case .spam: return NSLocalizedString("Spam", comment: "Button title for Spam comment state.") default: return nil } } } // MARK: - Comment Moderation Actions private extension CommentDetailViewController { func unapproveComment() { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentUnapproved, withProperties: Constants.notificationDetailSource, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentUnApproved(comment: comment) commentService.unapproveComment(comment, success: { [weak self] in self?.showActionableNotice(title: ModerationMessages.pendingSuccess) self?.refreshData() }, failure: { [weak self] error in self?.displayNotice(title: ModerationMessages.pendingFail) self?.commentStatus = CommentStatusType.typeForStatus(self?.comment.status) }) } func approveComment() { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentApproved, withProperties: Constants.notificationDetailSource, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentApproved(comment: comment) commentService.approve(comment, success: { [weak self] in self?.showActionableNotice(title: ModerationMessages.approveSuccess) self?.refreshData() }, failure: { [weak self] error in self?.displayNotice(title: ModerationMessages.approveFail) self?.commentStatus = CommentStatusType.typeForStatus(self?.comment.status) }) } func spamComment() { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentFlaggedAsSpam, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentSpammed(comment: comment) commentService.spamComment(comment, success: { [weak self] in self?.showActionableNotice(title: ModerationMessages.spamSuccess) self?.refreshData() }, failure: { [weak self] error in self?.displayNotice(title: ModerationMessages.spamFail) self?.commentStatus = CommentStatusType.typeForStatus(self?.comment.status) }) } func trashComment() { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentTrashed, withBlogID: notification?.metaSiteID) : CommentAnalytics.trackCommentTrashed(comment: comment) trashButtonCell.isLoading = true commentService.trashComment(comment, success: { [weak self] in self?.trashButtonCell.isLoading = false self?.showActionableNotice(title: ModerationMessages.trashSuccess) self?.refreshData() }, failure: { [weak self] error in self?.trashButtonCell.isLoading = false self?.displayNotice(title: ModerationMessages.trashFail) self?.commentStatus = CommentStatusType.typeForStatus(self?.comment.status) }) } func deleteComment(completion: ((Bool) -> Void)? = nil) { CommentAnalytics.trackCommentTrashed(comment: comment) deleteButtonCell.isLoading = true commentService.delete(comment, success: { [weak self] in self?.showActionableNotice(title: ModerationMessages.deleteSuccess) completion?(true) }, failure: { [weak self] error in self?.deleteButtonCell.isLoading = false self?.displayNotice(title: ModerationMessages.deleteFail) completion?(false) }) } func notifyDelegateCommentModerated() { notificationDelegate?.commentWasModerated(for: notification) } func postNotificationCommentDeleted(_ commentID: Int32) { NotificationCenter.default.post(name: .NotificationCommentDeletedNotification, object: nil, userInfo: [userInfoCommentIdKey: commentID]) } func showActionableNotice(title: String) { guard !isNotificationComment else { return } guard viewIsVisible, !isLastInList else { displayNotice(title: title) return } // Dismiss any old notices to avoid stacked Next notices. dismissNotice() displayActionableNotice(title: title, style: NormalNoticeStyle(showNextArrow: true), actionTitle: ModerationMessages.next, actionHandler: { [weak self] _ in self?.showNextComment() }) } func showNextComment() { guard viewIsVisible else { return } WPAnalytics.track(.commentSnackbarNext) commentDelegate?.nextCommentSelected() } struct ModerationMessages { static let pendingSuccess = NSLocalizedString("Comment set to pending.", comment: "Message displayed when pending a comment succeeds.") static let pendingFail = NSLocalizedString("Error setting comment to pending.", comment: "Message displayed when pending a comment fails.") static let approveSuccess = NSLocalizedString("Comment approved.", comment: "Message displayed when approving a comment succeeds.") static let approveFail = NSLocalizedString("Error approving comment.", comment: "Message displayed when approving a comment fails.") static let spamSuccess = NSLocalizedString("Comment marked as spam.", comment: "Message displayed when spamming a comment succeeds.") static let spamFail = NSLocalizedString("Error marking comment as spam.", comment: "Message displayed when spamming a comment fails.") static let trashSuccess = NSLocalizedString("Comment moved to trash.", comment: "Message displayed when trashing a comment succeeds.") static let trashFail = NSLocalizedString("Error moving comment to trash.", comment: "Message displayed when trashing a comment fails.") static let deleteSuccess = NSLocalizedString("Comment deleted.", comment: "Message displayed when deleting a comment succeeds.") static let deleteFail = NSLocalizedString("Error deleting comment.", comment: "Message displayed when deleting a comment fails.") static let next = NSLocalizedString("Next", comment: "Next action on comment moderation snackbar.") } } // MARK: - UITableView Methods extension CommentDetailViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch sections[section] { case .content(let rows): return rows.count case .moderation(let rows): return rows.count } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = { let rows: [RowType] switch sections[indexPath.section] { case .content(let sectionRows), .moderation(let sectionRows): rows = sectionRows } switch rows[indexPath.row] { case .header: configureHeaderCell() return headerCell case .content: guard let cell = tableView.dequeueReusableCell(withIdentifier: CommentContentTableViewCell.defaultReuseID) as? CommentContentTableViewCell else { return .init() } configureContentCell(cell, comment: comment) return cell case .replyIndicator: return replyIndicatorCell case .deleteComment: if comment.deleteWillBePermanent() { return deleteButtonCell } else { return trashButtonCell } case .status(let statusType): return configuredStatusCell(for: statusType) } }() return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch sections[section] { case .content: return nil case .moderation: return NSLocalizedString("STATUS", comment: "Section title for the moderation section of the comment details screen.") } } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.textLabel?.font = Style.tertiaryTextFont header.textLabel?.textColor = UIColor.secondaryLabel } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // Hide cell separator if it's positioned before the delete button cell. cell.separatorInset = self.shouldHideCellSeparator(for: indexPath) ? self.insetsForHiddenCellSeparator : .zero } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch sections[indexPath.section] { case .content(let rows): switch rows[indexPath.row] { case .header: if isNotificationComment { navigateToNotificationComment() } else { comment.hasParentComment() ? navigateToParentComment() : navigateToPost() } case .replyIndicator: navigateToReplyComment() default: break } case .moderation(let rows): switch rows[indexPath.row] { case .status(let statusType): if commentStatus == statusType { break } commentStatus = statusType notifyDelegateCommentModerated() guard let cell = tableView.cellForRow(at: indexPath) else { return } let activityIndicator = UIActivityIndicatorView(style: .medium) cell.accessoryView = activityIndicator activityIndicator.startAnimating() default: break } } } func scrollViewDidScroll(_ scrollView: UIScrollView) { // keep track of whether the content has scrolled or not. This is used to update the navigation bar style in iOS 14 and below. // in iOS 15, we don't need to do this since it's been handled automatically; hence the early return. if #available(iOS 15, *) { return } isContentScrolled = scrollView.contentOffset.y > contentScrollThreshold } } // MARK: - Reply Handling private extension CommentDetailViewController { func configureReplyView() { let replyView = ReplyTextView(width: view.frame.width) replyView.placeholder = String(format: .replyPlaceholderFormat, comment.authorForDisplay()) replyView.accessibilityIdentifier = NSLocalizedString("Reply Text", comment: "Notifications Reply Accessibility Identifier") replyView.delegate = self replyView.onReply = { [weak self] content in self?.createReply(content: content) } replyView.isHidden = true containerStackView.addArrangedSubview(replyView) replyTextView = replyView } func showReplyView() { guard replyTextView?.isFirstResponder == false else { return } replyTextView?.isHidden = false replyTextView?.becomeFirstResponder() addDismissKeyboardTapGesture() } func setupKeyboardManager() { guard let replyTextView = replyTextView, let bottomLayoutConstraint = view.constraints.first(where: { $0.firstAttribute == .bottom }) else { return } keyboardManager = KeyboardDismissHelper(parentView: view, scrollView: tableView, dismissableControl: replyTextView, bottomLayoutConstraint: bottomLayoutConstraint) } func addDismissKeyboardTapGesture() { dismissKeyboardTapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tableView.addGestureRecognizer(dismissKeyboardTapGesture) } @objc func dismissKeyboard() { view.endEditing(true) tableView.removeGestureRecognizer(dismissKeyboardTapGesture) } @objc func createReply(content: String) { isNotificationComment ? WPAppAnalytics.track(.notificationsCommentRepliedTo) : CommentAnalytics.trackCommentRepliedTo(comment: comment) // If there is no Blog, try with the Post. guard comment.blog != nil else { createPostCommentReply(content: content) return } guard let reply = commentService.createReply(for: comment) else { DDLogError("Failed creating comment reply.") return } reply.content = content commentService.uploadComment(reply, success: { [weak self] in self?.displayReplyNotice(success: true) self?.refreshCommentReplyIfNeeded() }, failure: { [weak self] error in DDLogError("Failed uploading comment reply: \(String(describing: error))") self?.displayReplyNotice(success: false) }) } func createPostCommentReply(content: String) { guard let post = comment.post as? ReaderPost else { return } commentService.replyToHierarchicalComment(withID: NSNumber(value: comment.commentID), post: post, content: content, success: { [weak self] in self?.displayReplyNotice(success: true) self?.refreshCommentReplyIfNeeded() }, failure: { [weak self] error in DDLogError("Failed creating post comment reply: \(String(describing: error))") self?.displayReplyNotice(success: false) }) } func displayReplyNotice(success: Bool) { let message = success ? ReplyMessages.successMessage : ReplyMessages.failureMessage displayNotice(title: message) } func configureSuggestionsView() { guard shouldShowSuggestions, let siteID = siteID, let replyTextView = replyTextView else { return } let suggestionsView = SuggestionsTableView(siteID: siteID, suggestionType: .mention, delegate: self) suggestionsView.translatesAutoresizingMaskIntoConstraints = false suggestionsView.prominentSuggestionsIds = SuggestionsTableView.prominentSuggestions( fromPostAuthorId: comment.post?.authorID, commentAuthorId: NSNumber(value: comment.authorID), defaultAccountId: try? WPAccount.lookupDefaultWordPressComAccount(in: self.managedObjectContext)?.userID ) view.addSubview(suggestionsView) NSLayoutConstraint.activate([ suggestionsView.leadingAnchor.constraint(equalTo: view.leadingAnchor), suggestionsView.trailingAnchor.constraint(equalTo: view.trailingAnchor), suggestionsView.topAnchor.constraint(equalTo: view.topAnchor), suggestionsView.bottomAnchor.constraint(equalTo: replyTextView.topAnchor) ]) suggestionsTableView = suggestionsView } var shouldShowSuggestions: Bool { guard let siteID = siteID, let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else { return false } return SuggestionService.shared.shouldShowSuggestions(for: blog) } struct ReplyMessages { static let successMessage = NSLocalizedString("Reply Sent!", comment: "The app successfully sent a comment") static let failureMessage = NSLocalizedString("There has been an unexpected error while sending your reply", comment: "Reply Failure Message") } } // MARK: - ReplyTextViewDelegate extension CommentDetailViewController: ReplyTextViewDelegate { func textView(_ textView: UITextView, didTypeWord word: String) { suggestionsTableView?.showSuggestions(forWord: word) } func replyTextView(_ replyTextView: ReplyTextView, willEnterFullScreen controller: FullScreenCommentReplyViewController) { let lastSearchText = suggestionsTableView?.viewModel.searchText suggestionsTableView?.hideSuggestions() if let siteID = siteID { controller.enableSuggestions(with: siteID, prominentSuggestionsIds: suggestionsTableView?.prominentSuggestionsIds, searchText: lastSearchText) } } func replyTextView(_ replyTextView: ReplyTextView, didExitFullScreen lastSearchText: String?) { guard let lastSearchText = lastSearchText, !lastSearchText.isEmpty else { return } suggestionsTableView?.viewModel.reloadData() suggestionsTableView?.showSuggestions(forWord: lastSearchText) } } // MARK: - SuggestionsTableViewDelegate extension CommentDetailViewController: SuggestionsTableViewDelegate { func suggestionsTableView(_ suggestionsTableView: SuggestionsTableView, didSelectSuggestion suggestion: String?, forSearchText text: String) { replyTextView?.replaceTextAtCaret(text as NSString?, withText: suggestion) suggestionsTableView.hideSuggestions() } } // MARK: - BorderedButtonTableViewCellDelegate extension CommentDetailViewController: BorderedButtonTableViewCellDelegate { func buttonTapped() { if comment.deleteWillBePermanent() { deleteButtonTapped() } else { commentStatus = .unapproved } } }
2224bdd774b1c406dba3fe7c9b7c9071
39.92749
169
0.643369
false
false
false
false
JaSpa/swift
refs/heads/master
test/Index/roles.swift
apache-2.0
2
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/imported_swift_module.swift // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s -I %t | %FileCheck %s import func imported_swift_module.importedFunc // CHECK: [[@LINE-1]]:35 | function/Swift | importedFunc() | s:F21imported_swift_module12importedFuncFT_T_ | Ref | rel: 0 import var imported_swift_module.importedGlobal // CHECK: [[@LINE-1]]:34 | variable/Swift | importedGlobal | s:v21imported_swift_module14importedGlobalSi | Ref | rel: 0 // Definition let x = 2 // CHECK: [[@LINE-1]]:5 | variable/Swift | x | s:v14swift_ide_test1xSi | Def | rel: 0 // Definition + Read of x var y = x + 1 // CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:v14swift_ide_test1ySi | Def | rel: 0 // CHECK: [[@LINE-2]]:9 | variable/Swift | x | s:v14swift_ide_test1xSi | Ref,Read | rel: 0 // CHECK: [[@LINE-3]]:11 | function/infix-operator/Swift | +(_:_:) | s:Fsoi1pFTSiSi_Si | Ref,Call | rel: 0 // Read of x + Write of y y = x + 1 // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:v14swift_ide_test1ySi | Ref,Writ | rel: 0 // CHECK: [[@LINE-2]]:5 | variable/Swift | x | s:v14swift_ide_test1xSi | Ref,Read | rel: 0 // CHECK: [[@LINE-3]]:7 | function/infix-operator/Swift | +(_:_:) | s:Fsoi1pFTSiSi_Si | Ref,Call | rel: 0 // Read of y + Write of y y += x // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:v14swift_ide_test1ySi | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-2]]:3 | function/infix-operator/Swift | +=(_:_:) | s:Fsoi2peFTRSiSi_T_ | Ref,Call | rel: 0 // CHECK: [[@LINE-3]]:6 | variable/Swift | x | s:v14swift_ide_test1xSi | Ref,Read | rel: 0 var z: Int { // CHECK: [[@LINE-1]]:5 | variable/Swift | z | s:v14swift_ide_test1zSi | Def | rel: 0 get { // CHECK: [[@LINE-1]]:3 | function/acc-get/Swift | getter:z | s:F14swift_ide_testg1zSi | Def,RelChild,RelAcc | rel: 1 return y // CHECK: [[@LINE-1]]:12 | variable/Swift | y | s:v14swift_ide_test1ySi | Ref,Read | rel: 0 } set { // CHECK: [[@LINE-1]]:3 | function/acc-set/Swift | setter:z | s:F14swift_ide_tests1zSi | Def,RelChild,RelAcc | rel: 1 y = newValue // CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:v14swift_ide_test1ySi | Ref,Writ | rel: 0 } } // Write + Read of z z = z + 1 // CHECK: [[@LINE-1]]:1 | variable/Swift | z | s:v14swift_ide_test1zSi | Ref,Writ | rel: 0 // CHECK: [[@LINE-2]]:1 | function/acc-set/Swift | setter:z | s:F14swift_ide_tests1zSi | Ref,Call,Impl | rel: 0 // CHECK: [[@LINE-3]]:5 | variable/Swift | z | s:v14swift_ide_test1zSi | Ref,Read | rel: 0 // CHECK: [[@LINE-4]]:5 | function/acc-get/Swift | getter:z | s:F14swift_ide_testg1zSi | Ref,Call,Impl | rel: 0 // Call func aCalledFunction() {} // CHECK: [[@LINE-1]]:6 | function/Swift | aCalledFunction() | s:F14swift_ide_test15aCalledFunctionFT_T_ | Def | rel: 0 aCalledFunction() // CHECK: [[@LINE-1]]:1 | function/Swift | aCalledFunction() | s:F14swift_ide_test15aCalledFunctionFT_T_ | Ref,Call | rel: 0 func aCaller() { // CHECK: [[@LINE-1]]:6 | function/Swift | aCaller() | s:F14swift_ide_test7aCallerFT_T_ | Def | rel: 0 aCalledFunction() // CHECK: [[@LINE-1]]:3 | function/Swift | aCalledFunction() | s:F14swift_ide_test15aCalledFunctionFT_T_ | Ref,Call,RelCall | rel: 1 // CHECK-NEXT: RelCall | aCaller() | s:F14swift_ide_test7aCallerFT_T_ } // RelationChildOf, Implicit struct AStruct { var x: Int // CHECK: [[@LINE-1]]:7 | instance-property/Swift | x | s:vV14swift_ide_test7AStruct1xSi | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | AStruct | s:V14swift_ide_test7AStruct mutating func aMethod() { // CHECK: [[@LINE-1]]:17 | instance-method/Swift | aMethod() | s:FV14swift_ide_test7AStruct7aMethodFT_T_ | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | AStruct | s:V14swift_ide_test7AStruct x += 1 // CHECK: [[@LINE-1]]:5 | instance-property/Swift | x | s:vV14swift_ide_test7AStruct1xSi | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-2]]:5 | function/acc-get/Swift | getter:x | s:FV14swift_ide_test7AStructg1xSi | Ref,Call,Impl,RelRec,RelCall | rel: 2 // CHECK-NEXT: RelCall | aMethod() | s:FV14swift_ide_test7AStruct7aMethodFT_T_ // CHECK-NEXT: RelRec | AStruct | s:V14swift_ide_test7AStruct // CHECK: [[@LINE-5]]:5 | function/acc-set/Swift | setter:x | s:FV14swift_ide_test7AStructs1xSi | Ref,Call,Impl,RelRec,RelCall | rel: 2 // CHECK-NEXT: RelCall | aMethod() | s:FV14swift_ide_test7AStruct7aMethodFT_T_ // CHECK-NEXT: RelRec | AStruct | s:V14swift_ide_test7AStruct // CHECK: [[@LINE-8]]:7 | function/infix-operator/Swift | +=(_:_:) | s:Fsoi2peFTRSiSi_T_ | Ref,Call,RelCall | rel: 1 // CHECK-NEXT: RelCall | aMethod() | s:FV14swift_ide_test7AStruct7aMethodFT_T_ } // RelationChildOf, RelationAccessorOf subscript(index: Int) -> Int { // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:iV14swift_ide_test7AStruct9subscriptFSiSi | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | AStruct | s:V14swift_ide_test7AStruct get { // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | s:FV14swift_ide_test7AStructg9subscriptFSiSi | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | subscript(_:) | s:iV14swift_ide_test7AStruct9subscriptFSiSi return x } set { // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | s:FV14swift_ide_test7AStructs9subscriptFSiSi | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | subscript(_:) | s:iV14swift_ide_test7AStruct9subscriptFSiSi x = newValue } } } class AClass { var y: AStruct; var z: [Int] init(x: Int) { y = AStruct(x: x) self.z = [1, 2, 3] } subscript(index: Int) -> Int { get { return z[0] } set { z[0] = newValue } } func foo() -> Int { return z[0] } } protocol AProtocol { func foo() -> Int // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | s:FP14swift_ide_test9AProtocol3fooFT_Si | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | AProtocol | s:P14swift_ide_test9AProtocol } // RelationBaseOf, RelationOverrideOf class ASubClass : AClass, AProtocol { // CHECK: [[@LINE-1]]:7 | class/Swift | ASubClass | s:C14swift_ide_test9ASubClass | Def | rel: 0 // CHECK: [[@LINE-2]]:19 | class/Swift | AClass | s:C14swift_ide_test6AClass | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | ASubClass | s:C14swift_ide_test9ASubClass // CHECK: [[@LINE-4]]:27 | protocol/Swift | AProtocol | s:P14swift_ide_test9AProtocol | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | ASubClass | s:C14swift_ide_test9ASubClass override func foo() -> Int { // CHECK: [[@LINE-1]]:17 | instance-method/Swift | foo() | s:FC14swift_ide_test9ASubClass3fooFT_Si | Def,RelChild,RelOver | rel: 3 // CHECK-NEXT: RelOver | foo() | s:FC14swift_ide_test6AClass3fooFT_Si // CHECK-NEXT: RelOver | foo() | s:FP14swift_ide_test9AProtocol3fooFT_Si // CHECK-NEXT: RelChild | ASubClass | s:C14swift_ide_test9ASubClass return 1 } } // RelationExtendedBy // FIXME give extensions their own USR like ObjC? extension AClass { // CHECK: [[@LINE-1]]:11 | extension/ext-class/Swift | AClass | s:C14swift_ide_test6AClass | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | class/Swift | AClass | s:C14swift_ide_test6AClass | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | AClass | s:C14swift_ide_test6AClass func bar() -> Int { return 2 } // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar() | s:FC14swift_ide_test6AClass3barFT_Si | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | AClass | s:C14swift_ide_test6AClass } var anInstance = AClass(x: 1) // CHECK: [[@LINE-1]]:18 | class/Swift | AClass | s:C14swift_ide_test6AClass | Ref | rel: 0 // CHECK: [[@LINE-2]]:18 | constructor/Swift | init(x:) | s:FC14swift_ide_test6AClasscFT1xSi_S0_ | Ref,Call | rel: 0 anInstance.y.x = anInstance.y.x // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | s:vC14swift_ide_test6AClass1yVS_7AStruct | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-3]]:14 | instance-property/Swift | x | s:vV14swift_ide_test7AStruct1xSi | Ref,Writ | rel: 0 // CHECK: [[@LINE-4]]:18 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-5]]:29 | instance-property/Swift | y | s:vC14swift_ide_test6AClass1yVS_7AStruct | Ref,Read | rel: 0 // CHECK: [[@LINE-6]]:31 | instance-property/Swift | x | s:vV14swift_ide_test7AStruct1xSi | Ref,Read | rel: 0 anInstance.y.aMethod() // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | s:vC14swift_ide_test6AClass1yVS_7AStruct | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-3]]:14 | instance-method/Swift | aMethod() | s:FV14swift_ide_test7AStruct7aMethodFT_T_ | Ref,Call | rel: 0 // FIXME Write role of z occurrence on the RHS? anInstance.z[1] = anInstance.z[0] // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | z | s:vC14swift_ide_test6AClass1zGSaSi_ | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-3]]:19 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-4]]:30 | instance-property/Swift | z | s:vC14swift_ide_test6AClass1zGSaSi_ | Ref,Read,Writ | rel: 0 let otherInstance = AStruct(x: 1) // CHECK: [[@LINE-1]]:21 | struct/Swift | AStruct | s:V14swift_ide_test7AStruct | Ref | rel: 0 let _ = otherInstance[0] // CHECK: [[@LINE-1]]:9 | variable/Swift | otherInstance | s:v14swift_ide_test13otherInstanceVS_7AStruct | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:22 | instance-property/subscript/Swift | subscript(_:) | s:iV14swift_ide_test7AStruct9subscriptFSiSi | Ref,Read | rel: 0 let _ = anInstance[0] // CHECK: [[@LINE-1]]:9 | variable/Swift | anInstance | s:v14swift_ide_test10anInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:19 | instance-property/subscript/Swift | subscript(_:) | s:iC14swift_ide_test6AClass9subscriptFSiSi | Ref,Read | rel: 0 let aSubInstance: AClass = ASubClass(x: 1) // CHECK: [[@LINE-1]]:5 | variable/Swift | aSubInstance | s:v14swift_ide_test12aSubInstanceCS_6AClass | Def | rel: 0 // CHECK: [[@LINE-2]]:28 | class/Swift | ASubClass | s:C14swift_ide_test9ASubClass | Ref | rel: 0 // Dynamic, RelationReceivedBy let _ = aSubInstance.foo() // CHECK: [[@LINE-1]]:9 | variable/Swift | aSubInstance | s:v14swift_ide_test12aSubInstanceCS_6AClass | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:22 | instance-method/Swift | foo() | s:FC14swift_ide_test6AClass3fooFT_Si | Ref,Call,Dyn,RelRec | rel: 1 // CHECK-NEXT: RelRec | AClass | s:C14swift_ide_test6AClass
668f4505def775874e365a454864b973
49.637209
162
0.661523
false
true
false
false
Urinx/SublimeCode
refs/heads/master
Sublime/Sublime/Utils/Github.swift
gpl-3.0
1
// // Github.swift // Sublime // // Created by Eular on 2/24/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import Foundation import SafariServices import Alamofire import SwiftyJSON class GitHubAPIManager { private let clientID = Constant.githubClientID private let clientSecret = Constant.githubClientSecret private var OAuthToken: String! private var safariVC: SFSafariViewController? static let sharedInstance = GitHubAPIManager() static let GetOAuthCodeNotifi = "GetOAuthCodeNotifi" static let GetUserInfoDoneNotifi = "GetUserInfoDoneNotifi" static var isLogin: Bool { set { Global.Database.setBool(newValue, forKey: "github-islogin") } get { return Global.Database.boolForKey("github-islogin") } } let githubFolder: Folder! var user: JSON! var delegate: UIViewController? { didSet { self.addObserver(delegate!) } } init() { githubFolder = Folder(path: Constant.SublimeRoot+"/home/sublime/github") if !githubFolder.checkFileExist("stars") { githubFolder.newFolder("stars") } if !githubFolder.checkFileExist("repositories") { githubFolder.newFolder("repositories") } if GitHubAPIManager.isLogin { OAuthToken = Global.Database.stringForKey("github-oauthtoken") if let data = Global.Database.objectForKey("github-user") as? NSData { user = JSON(data: data) } } else { OAuthToken = "" user = JSON("") } } func OAuth2() { let OAuthURL = "https://github.com/login/oauth/authorize?scope=user,repo,gist&client_id=\(clientID)" safariVC = SFSafariViewController(URL: NSURL(string: OAuthURL)!) safariVC!.modalPresentationStyle = .OverCurrentContext delegate!.presentViewController(safariVC!, animated: true, completion: nil) } func handleOAuthCode(notification: NSNotification) { safariVC!.dismissViewControllerAnimated(true, completion: nil) let info = notification.userInfo as! Dictionary<String, AnyObject> let code = info["code"] as! String getOAuthToken(code) } private func getOAuthToken(code: String) { let TokenURL = "https://github.com/login/oauth/access_token" let params = ["client_id": clientID, "client_secret": clientSecret, "code": code] Alamofire.request(.POST, TokenURL, parameters: params).responseString { response in if let str = response.result.value { self.OAuthToken = str.split("&")[0].split("=")[1] Global.Database.setValue(self.OAuthToken, forKey: "github-oauthtoken") self.getUserInfo() } } } func getUserInfo() { let url = "https://api.github.com/user" let params = ["access_token": OAuthToken] Alamofire.request(.GET, url, parameters: params).responseJSON { response in if let data = response.result.value { self.user = JSON(data) Global.Database.setObject(try! self.user.rawData(), forKey: "github-user") GitHubAPIManager.isLogin = true Global.Notifi.postNotificationName(GitHubAPIManager.GetUserInfoDoneNotifi, object: nil) } } } func listRepositories(completion: (repos: [Repo]) -> Void) { let url = "https://api.github.com/user/repos" let params = ["access_token": OAuthToken, "sort": "pushed"] Alamofire.request(.GET, url, parameters: params).responseJSON { response in if let data = response.result.value { var repos = [Repo]() for (_, r) in JSON(data) { repos.append(Repo(json: r)) } completion(repos: repos) } } } func listStarred(completion: (repos: [Repo]) -> Void) { let url = "https://api.github.com/user/starred" let params = ["access_token": OAuthToken] Alamofire.request(.GET, url, parameters: params).responseJSON { response in if let data = response.result.value { var repos = [Repo]() for (_, r) in JSON(data) { repos.append(Repo(json: r)) } completion(repos: repos) } } } func logout() { GitHubAPIManager.isLogin = false Global.Database.setValue("", forKey: "github-oauthtoken") Global.Database.setValue("", forKey: "github-user") } private func addObserver(observer: UIViewController) { // ----------------- Rewrite Code Later ----------------- Global.Notifi.addObserver(observer, selector: #selector(GithubAccountTableViewController.githubOAuthCode(_:)), name: GitHubAPIManager.GetOAuthCodeNotifi, object: nil) Global.Notifi.addObserver(observer, selector: #selector(GithubAccountTableViewController.githubGetUserInfoCompleted), name: GitHubAPIManager.GetUserInfoDoneNotifi, object: nil) } static func handleURL(url: NSURL) { if url.host == "githubLogin" { Global.Notifi.postNotificationName(GitHubAPIManager.GetOAuthCodeNotifi, object: nil, userInfo: ["code": url.query!.split("=")[1]]) } } func star(owner: String, repo: String, success: (() -> Void)? = nil, fail: (() -> Void)? = nil) { let url = "https://api.github.com/user/starred/\(owner)/\(repo)" let headers = ["Authorization": "token " + OAuthToken] Alamofire.request(.PUT, url, headers: headers).response { result in let response = result.1 if let code = response?.statusCode { if code == 204 { success?() } else { fail?() } } } } func follow(user: String, success: (() -> Void)? = nil, fail: (() -> Void)? = nil) { let url = "https://api.github.com/user/following/\(user)" let headers = ["Authorization": "token " + OAuthToken] Alamofire.request(.PUT, url, headers: headers).response { result in let response = result.1 if let code = response?.statusCode { if code == 204 { success?() } else { fail?() } } } } func listGists(completion: ((gists: [Gist]) -> Void)? = nil) { let url = "https://api.github.com/gists/public" Alamofire.request(.GET, url).responseJSON { response in if let data = response.result.value { var gists = [Gist]() for (_, r) in JSON(data) { if r["owner"] != nil && r["files"] != nil { gists.append(Gist(json: r)) } } completion?(gists: gists) } } } } protocol GithubAPIManagerDelegate { // return OAuth code func githubOAuthCode(notification: NSNotification) // get user info complete func githubGetUserInfoCompleted() }
449798460fbe785fadc90840c5a7794a
34.5
184
0.564193
false
false
false
false
RajatDhasmana/rajat_appinventiv
refs/heads/master
ProfileViewAgain/ProfileViewAgain/ProfileVC.swift
mit
1
// // ProfileVC.swift // ProfileViewAgain // // Created by Mohd Sultan on 08/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class ProfileVC: UIViewController { @IBOutlet weak var profileTableView: UITableView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! let data = [ ["titlename":"Full Name" , "titledetail":"Rajat Dhasmana"], ["titlename":"E-mail" , "titledetail":"[email protected]"], ["titlename":"Password" , "titledetail":"rajat1234"], ["titlename":"Height" , "titledetail":"5'10"], ["titlename":"Weight" , "titledetail":"68"], ["titlename":"Date Of Birth" , "titledetail":"5th june, 1995"] ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.profileTableView.dataSource = self self.profileTableView.delegate = self let cellNib1 = UINib(nibName: "ButtonCell", bundle: nil) profileTableView.register(cellNib1, forCellReuseIdentifier: "ButtonCellID") let cellNib2 = UINib(nibName: "ProfileDetailCellTableViewCell", bundle: nil) profileTableView.register(cellNib2, forCellReuseIdentifier:"ProfileDetailCellID" ) let cellNib3 = UINib(nibName: "UpperCell", bundle: nil) profileTableView.register(cellNib3, forCellReuseIdentifier: "UpperCellID") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: OperationQueue.main, using: {(Notification) -> Void in guard let userinfo = Notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else{ return } let keyboardHeight = userinfo.cgRectValue.height self.bottomConstraint.constant = keyboardHeight }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ProfileVC : UITableViewDataSource , UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count + 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let uppercell = tableView.dequeueReusableCell(withIdentifier: "UpperCellID") as! UpperCell return uppercell case 7: let buttoncell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellID") as! ButtonCell return buttoncell default : let profiledetailcell = tableView.dequeueReusableCell(withIdentifier: "ProfileDetailCellID") as! ProfileDetailCellTableViewCell profiledetailcell.configureCell( data[indexPath.row - 1]) return profiledetailcell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.row { case 0 : return 272 case 7 : return 160 default : return 100 } } }
2db94578cc4b436e155d41edf90edd70
28.984127
150
0.575966
false
false
false
false