repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
N26-OpenSource/bob
Sources/Bob/Commands/Align Version/AlignVersionCommand.swift
1
4195
/* * Copyright (c) 2017 N26 GmbH. * * This file is part of Bob. * * Bob 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. * * Bob 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 Bob. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import Vapor /// Command used to change the version and build numbers directly on GitHub public class AlignVersionCommand { enum Constants { static let defaultBuildNumber: String = "1" static let branchSpecifier: String = "-b" } fileprivate let gitHub: GitHub fileprivate let plistPaths: [String] fileprivate let messageFormat: String fileprivate let author: Author /// Initializer /// /// - Parameters: /// - config: Configuration to use to connect to github /// - plistPaths: Paths to .plist files to update. Path relative from the root of the repository /// - author: Commit author. Shows up in GitHub /// - messageFormat: Format for the commit message. `<version>` will be replaced with the version string public init(gitHub: GitHub, plistPaths: [String], author: Author, messageFormat: String = "[General] Aligns version to <version>") { self.gitHub = gitHub self.plistPaths = plistPaths self.messageFormat = messageFormat self.author = author } } extension AlignVersionCommand: Command { public var name: String { return "align" } public var usage: String { return "Change version and build number by typing `align {version} {build number}`. Build number defaults to `\(Constants.defaultBuildNumber)` if not specified. Specify a branch by typing `\(Constants.branchSpecifier) {branch}`." } public func execute(with parameters: [String], replyingTo sender: MessageSender) throws { guard plistPaths.count > 0 else { throw "Failed to align version. Misconfiguration of the `align` command. Missing Plist file paths." } var params = parameters var specifiedBranch: BranchName? if let branchSpecifierIndex = params.index(where: { $0 == Constants.branchSpecifier }) { guard params.count > branchSpecifierIndex + 1 else { throw "Branch name not specified after `\(Constants.branchSpecifier)`" } specifiedBranch = BranchName(params[branchSpecifierIndex + 1]) params.remove(at: branchSpecifierIndex + 1) params.remove(at: branchSpecifierIndex) } guard let branch = specifiedBranch else { throw "Please specify a branch" } guard params.count > 0 else { throw "Please specify a `version` parameter. See `\(self.name) usage` for instructions on how to use this command" } let versionParam = params[0] params.remove(at: 0) let buildNumber: String if params.count > 0 { buildNumber = params[0] params.remove(at: 0) } else { buildNumber = Constants.defaultBuildNumber } guard params.count == 0 else { throw "To many parameters. See `\(self.name) usage` for instructions on how to use this command" } sender.send("One sec...") let version = Version(version: versionParam, build: buildNumber) let updater = VersionUpdater(plistPaths: self.plistPaths, version: version) let message = version.commitMessage(template: messageFormat) _ = try self.gitHub.newCommit(updatingItemsWith: updater, on: branch, by: self.author, message: message).map { _ in sender.send("Done. Version aligned to *" + version.fullVersion + "* on branch *" + branch + "*") }.catch { error in sender.send("Command failed with error ```\(error)```") } } }
gpl-3.0
a6b3ceed5c65bebcc5978b2f62036203
40.534653
237
0.666508
4.559783
false
false
false
false
brentdax/swift
test/decl/class/override.swift
6
21071
// RUN: %target-typecheck-verify-swift -parse-as-library -enable-objc-interop class A { func ret_sametype() -> Int { return 0 } func ret_subclass() -> A { return self } func ret_subclass_rev() -> B { return B() } func ret_nonclass_optional() -> Int? { return .none } func ret_nonclass_optional_rev() -> Int { return 0 } func ret_class_optional() -> B? { return .none } func ret_class_optional_rev() -> A { return self } func ret_class_uoptional() -> B! { return B() } func ret_class_uoptional_rev() -> A { return self } func ret_class_optional_uoptional() -> B? { return .none } func ret_class_optional_uoptional_rev() -> A! { return self } func param_sametype(_ x : Int) {} func param_subclass(_ x : B) {} func param_subclass_rev(_ x : A) {} func param_nonclass_optional(_ x : Int) {} func param_nonclass_optional_rev(_ x : Int?) {} func param_class_optional(_ x : B) {} func param_class_optional_rev(_ x : B?) {} func param_class_uoptional(_ x : B) {} func param_class_uoptional_rev(_ x : B!) {} func param_class_optional_uoptional(_ x : B!) {} func param_class_optional_uoptional_rev(_ x : B?) {} } class B : A { override func ret_sametype() -> Int { return 1 } override func ret_subclass() -> B { return self } func ret_subclass_rev() -> A { return self } override func ret_nonclass_optional() -> Int { return 0 } func ret_nonclass_optional_rev() -> Int? { return 0 } override func ret_class_optional() -> B { return self } func ret_class_optional_rev() -> A? { return self } override func ret_class_uoptional() -> B { return self } func ret_class_uoptional_rev() -> A! { return self } override func ret_class_optional_uoptional() -> B! { return self } override func ret_class_optional_uoptional_rev() -> A? { return self } override func param_sametype(_ x : Int) {} override func param_subclass(_ x : A) {} func param_subclass_rev(_ x : B) {} override func param_nonclass_optional(_ x : Int?) {} func param_nonclass_optional_rev(_ x : Int) {} override func param_class_optional(_ x : B?) {} func param_class_optional_rev(_ x : B) {} override func param_class_uoptional(_ x : B!) {} func param_class_uoptional_rev(_ x : B) {} override func param_class_optional_uoptional(_ x : B?) {} override func param_class_optional_uoptional_rev(_ x : B!) {} } class C<T> { func ret_T() -> T {} } class D<T> : C<[T]> { override func ret_T() -> [T] {} } class E { var var_sametype: Int { get { return 0 } set {} } var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional: Int? { get { return .none } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}} var var_class_optional: F? { get { return .none } set {} } // expected-note{{attempt to override property here}} var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_optional_uoptional: F? { get { return .none } set {} } var var_class_optional_uoptional_rev: E! { get { return self } set {} } var ro_sametype: Int { return 0 } var ro_subclass: E { return self } var ro_subclass_rev: F { return F() } var ro_nonclass_optional: Int? { return 0 } var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}} var ro_class_optional: F? { return .none } var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_uoptional: F! { return F() } var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_optional_uoptional: F? { return .none } var ro_class_optional_uoptional_rev: E! { return self } } class F : E { override var var_sametype: Int { get { return 0 } set {} } override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}} override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}} override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}} override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}} override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F?' with covariant type 'F'}} override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}} override var var_class_optional_uoptional: F! { get { return .none } set {} } override var var_class_optional_uoptional_rev: E? { get { return self } set {} } override var ro_sametype: Int { return 0 } override var ro_subclass: E { return self } override var ro_subclass_rev: F { return F() } override var ro_nonclass_optional: Int { return 0 } override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var ro_class_optional: F { return self } override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var ro_class_uoptional: F { return F() } override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}} override var ro_class_optional_uoptional: F! { return .none } override var ro_class_optional_uoptional_rev: E? { return self } } class G { func f1(_: Int, int: Int) { } func f2(_: Int, int: Int) { } func f3(_: Int, int: Int) { } func f4(_: Int, int: Int) { } func f5(_: Int, int: Int) { } func f6(_: Int, int: Int) { } func f7(_: Int, int: Int) { } func g1(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g1(_:string:)' here}} {{28-28=string }} func g1(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g1(_:path:)' here}} {{28-28=path }} func g2(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g2(_:string:)' here}} {{none}} func g2(_: Int, path: String) { } func g3(_: Int, _ another: Int) { } func g3(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g3(_:path:)' here}} {{none}} func g4(_: Int, _ another: Int) { } func g4(_: Int, path: String) { } init(a: Int) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{none}} init(a: String) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{17-17=a }} expected-note {{potential overridden initializer 'init(a:)' here}} {{none}} init(b: String) {} // expected-note {{potential overridden initializer 'init(b:)' here}} {{17-17=b }} expected-note {{potential overridden initializer 'init(b:)' here}} {{none}} } class H : G { override func f1(_: Int, _: Int) { } // expected-error{{argument labels for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }} override func f2(_: Int, value: Int) { } // expected-error{{argument labels for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }} override func f3(_: Int, value int: Int) { } // expected-error{{argument labels for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}} override func f4(_: Int, _ int: Int) { } // expected-error{{argument labels for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}} override func f5(_: Int, value inValue: Int) { } // expected-error{{argument labels for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}} override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument labels for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}} override func f7(_: Int, int value: Int) { } // okay override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument labels from any potential overrides}}{{none}} override func g2(_: Int, string: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}} override func g3(_: Int, path: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}} override func g4(_: Int, string: Int) { } // expected-error{{argument labels for method 'g4(_:string:)' do not match those of overridden method 'g4'}} {{28-28=_ }} override init(x: Int) {} // expected-error{{argument labels for initializer 'init(x:)' do not match those of overridden initializer 'init(a:)'}} {{17-17=a }} override init(x: String) {} // expected-error{{declaration 'init(x:)' has different argument labels from any potential overrides}} {{none}} override init(a: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}} override init(b: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}} } @objc class IUOTestBaseClass { @objc func none() {} @objc func oneA(_: AnyObject) {} @objc func oneB(x: AnyObject) {} @objc func oneC(_ x: AnyObject) {} @objc func manyA(_: AnyObject, _: AnyObject) {} @objc func manyB(_ a: AnyObject, b: AnyObject) {} @objc func manyC(var a: AnyObject, // expected-error {{'var' as a parameter attribute is not allowed}} var b: AnyObject) {} // expected-error {{'var' as a parameter attribute is not allowed}} @objc func result() -> AnyObject? { return nil } @objc func both(_ x: AnyObject) -> AnyObject? { return x } @objc init(_: AnyObject) {} @objc init(one: AnyObject) {} @objc init(a: AnyObject, b: AnyObject) {} } class IUOTestSubclass : IUOTestBaseClass { override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneC(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func manyB(_ a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}} // expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}} override func both(_ x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{use '?' to make the result optional}} {{51-52=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 2 {{add parentheses to silence this warning}} override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}} // expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}} override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}} // expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}} override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} } class IUOTestSubclass2 : IUOTestBaseClass { override func oneA(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneC(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} } class IUOTestSubclassOkay : IUOTestBaseClass { override func oneA(_: AnyObject?) {} override func oneC(_ x: AnyObject) {} } class GenericBase<T> {} class ConcreteDerived: GenericBase<Int> {} class OverriddenWithConcreteDerived<T> { func foo() -> GenericBase<T> {} // expected-note{{potential overridden instance method 'foo()' here}} } class OverridesWithMismatchedConcreteDerived<T>: OverriddenWithConcreteDerived<T> { override func foo() -> ConcreteDerived {} //expected-error{{does not override}} } class OverridesWithConcreteDerived: OverriddenWithConcreteDerived<Int> { override func foo() -> ConcreteDerived {} } // <rdar://problem/24646184> class Ty {} class SubTy : Ty {} class Base24646184 { init(_: SubTy) { } func foo(_: SubTy) { } init(ok: Ty) { } init(ok: SubTy) { } func foo(ok: Ty) { } func foo(ok: SubTy) { } } class Derived24646184 : Base24646184 { override init(_: Ty) { } // expected-note {{'init(_:)' previously overridden here}} override init(_: SubTy) { } // expected-error {{'init(_:)' has already been overridden}} override func foo(_: Ty) { } // expected-note {{'foo' previously overridden here}} override func foo(_: SubTy) { } // expected-error {{'foo' has already been overridden}} override init(ok: Ty) { } override init(ok: SubTy) { } override func foo(ok: Ty) { } override func foo(ok: SubTy) { } } // Subscripts class SubscriptBase { subscript(a a: Int) -> Int { return a } } class SubscriptDerived : SubscriptBase { override subscript(a: Int) -> Int { return a } // expected-error@-1 {{argument labels for method 'subscript(_:)' do not match those of overridden method 'subscript(a:)'}} } // Generic subscripts class GenericSubscriptBase { var dict: [AnyHashable : Any] = [:] subscript<T : Hashable, U>(t: T) -> U { get { return dict[t] as! U } set { dict[t] = newValue } } } class GenericSubscriptDerived : GenericSubscriptBase { override subscript<K : Hashable, V>(t: K) -> V { get { return super[t] } set { super[t] = newValue } } } // @escaping class CallbackBase { func perform(handler: @escaping () -> Void) {} // expected-note * {{here}} func perform(optHandler: (() -> Void)?) {} // expected-note * {{here}} func perform(nonescapingHandler: () -> Void) {} // expected-note * {{here}} } class CallbackSubA: CallbackBase { override func perform(handler: () -> Void) {} // expected-error {{method does not override any method from its superclass}} // expected-note@-1 {{type does not match superclass instance method with type '(@escaping () -> Void) -> ()'}} override func perform(optHandler: () -> Void) {} // expected-error {{method does not override any method from its superclass}} override func perform(nonescapingHandler: () -> Void) {} } class CallbackSubB : CallbackBase { override func perform(handler: (() -> Void)?) {} override func perform(optHandler: (() -> Void)?) {} override func perform(nonescapingHandler: (() -> Void)?) {} // expected-error {{method does not override any method from its superclass}} } class CallbackSubC : CallbackBase { override func perform(handler: @escaping () -> Void) {} override func perform(optHandler: @escaping () -> Void) {} // expected-error {{cannot override instance method parameter of type '(() -> Void)?' with non-optional type '() -> Void'}} override func perform(nonescapingHandler: @escaping () -> Void) {} // expected-error {{method does not override any method from its superclass}} } // Issues with overrides of internal(set) and fileprivate(set) members public class BaseWithInternalSetter { public internal(set) var someValue: Int = 0 } public class DerivedWithInternalSetter: BaseWithInternalSetter { override public internal(set) var someValue: Int { get { return 0 } set { } } } class BaseWithFilePrivateSetter { fileprivate(set) var someValue: Int = 0 } class DerivedWithFilePrivateSetter: BaseWithFilePrivateSetter { override fileprivate(set) var someValue: Int { get { return 0 } set { } } } // Issues with final overrides of open members open class OpenBase { open func instanceMethod() {} // expected-note {{overridden declaration is here}} open class func classMethod() {} // expected-note {{overridden declaration is here}} } public class PublicDerived : OpenBase { override public func instanceMethod() {} override public class func classMethod() {} } open class OpenDerived : OpenBase { override open func instanceMethod() {} override open class func classMethod() {} } open class OpenDerivedPublic : OpenBase { override public func instanceMethod() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} override public class func classMethod() {} // expected-error {{overriding class method must be as accessible as the declaration it overrides}} } open class OpenDerivedFinal : OpenBase { override public final func instanceMethod() {} override public class final func classMethod() {} } open class OpenDerivedStatic : OpenBase { override public static func classMethod() {} }
apache-2.0
4898297828623a3938ae9560703cb1a4
52.615776
333
0.674909
3.91218
false
false
false
false
ryet231ere/DouYuSwift
douyu/douyu/Classes/Home/ViewModel/RecommendViewModel.swift
1
4872
// // RecommendViewModel.swift // douyu // // Created by 练锦波 on 2017/2/15. // Copyright © 2017年 练锦波. All rights reserved. // import UIKit class RecommendViewModel : BaseViewModel { lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() } // MARK:- 发送网络请求 extension RecommendViewModel { // 请求推荐数据 func requestData(finishCallback : @escaping () -> ()) { //1.定义参数 let parameters = ["limit": "4","offset":"0","time":Date.getCurrentTime()] //2.创建Group let dGroup = DispatchGroup() //3.请求第一部分推荐数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time": Date.getCurrentTime()]) { (result) in //1.将result转成字典类型 guard let resultDict = result as? [String:NSObject] else {return} //2.根据date该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3.遍历字典,并且转成模型对象 //3.1 设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" //3.2 获取主播数据 for dict in dataArray { let anchor = ANchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } //3.3 离开组 dGroup.leave() } //4.请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in //1.将result转成字典类型 guard let resultDict = result as? [String:NSObject] else {return} //2.根据date该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //3.遍历字典,并且转成模型对象 //3.1 设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" //3.2 获取主播数据 for dict in dataArray { let anchor = ANchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } //3.3 离开组 dGroup.leave() } //5.请求2-12部分的游戏数据 dGroup.enter() loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { dGroup.leave() } // NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters ) { (result) in // // //1.将result转成字典类型 // guard let resultDict = result as? [String:NSObject] else {return} // // //2.根据date该key,获取数据 // guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} // // //3.遍历数组,获取字典,并且将字典转成模型对象 // for dict in dataArray { // let group = AnchorGroup(dict:dict) // self.anchorGroups.append(group) // } // // //4.离开组 // dGroup.leave() // } //6.所有的数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } // 请求无限轮播的数据 // http://www.douyutv.com/api/v1/slide/6 func requestCycleData(finishCallback : @escaping () -> ()){ NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in // 1.获取整体字典数据 guard let resultDict = result as? [String:NSObject] else {return} // 2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} // 3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } finishCallback() } } }
mit
bfd11f2c94783a7112725ec7482faf14
32.416667
157
0.527998
4.393426
false
false
false
false
chenkaige/EasyIOS-Swift
Pod/Classes/Easy/Core/EZNavigationController.swift
1
2100
// // EZNavigationController.swift // medical // // Created by zhuchao on 15/4/24. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit public class EZNavigationController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate{ public var popGestureRecognizerEnabled = true override public func viewDidLoad() { super.viewDidLoad() self.configGestureRecognizer() // Do any additional setup after loading the view. } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func configGestureRecognizer() { if let target = self.interactivePopGestureRecognizer?.delegate { let pan = UIPanGestureRecognizer(target: target, action: Selector("handleNavigationTransition:")) pan.delegate = self self.view.addGestureRecognizer(pan) } //禁掉系统的侧滑手势 weak var weekSelf = self self.interactivePopGestureRecognizer?.enabled = false; self.interactivePopGestureRecognizer?.delegate = weekSelf; } public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer != self.interactivePopGestureRecognizer && self.viewControllers.count > 1 && self.popGestureRecognizerEnabled{ return true }else{ return false } } override public func pushViewController(viewController: UIViewController, animated: Bool) { self.interactivePopGestureRecognizer?.enabled = false super.pushViewController(viewController, animated: animated) } //UINavigationControllerDelegate public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { if self.popGestureRecognizerEnabled { self.interactivePopGestureRecognizer?.enabled = true } } }
mit
dd6c77dc24fcd1a82e56c599546e97f1
33.666667
156
0.698077
6.011561
false
false
false
false
craftsmanship-toledo/katangapp-ios
Katanga/BusStopRepository.swift
1
1761
/** * Copyright 2016-today Software Craftmanship Toledo * * 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. */ /*! @author Víctor Galán */ import Foundation import RealmSwift class BusStopRepository { func save(_ input: BusStop) { let stopRealm = map(input) let realm = try! Realm() try! realm.write { realm.add(stopRealm, update: true) } } func remove(_ input: BusStop) { let realm = try! Realm() if let stop = realm.object(ofType: BusStopRealm.self, forPrimaryKey: input.id) { try! realm.write { realm.delete(stop) } } } func exists(_ input: BusStop) -> Bool { let realm = try! Realm() if realm.object(ofType: BusStopRealm.self, forPrimaryKey: input.id) != nil { return true } return false } func getAll() -> [BusStop] { let realm = try! Realm() return realm.objects(BusStopRealm.self).map(reverseMap) } private func map(_ input: BusStop) -> BusStopRealm { return BusStopRealm(address: input.address, id: input.id, latitude: input.latitude, longitude: input.longitude, routeId: input.routeId) } private func reverseMap(_ input: BusStopRealm) -> BusStop { return BusStop(address: input.address, id: input.id, latitude: input.latitude, longitude: input.longitude, routeId: input.routeId) } }
apache-2.0
8e1cb1bac2ba799146fd844629efb8cc
25.651515
85
0.711768
3.490079
false
false
false
false
marcopompei/Gloss
Sources/Gloss.swift
4
3348
// // Gloss.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // 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 // MARK: - Types public typealias JSON = [String : AnyObject] // MARK: - Protocols /** Convenience protocol for objects that can be translated from and to JSON. */ public protocol Glossy: Decodable, Encodable { } /** Enables an object to be decoded from JSON. */ public protocol Decodable { /** Returns new instance created from provided JSON. - parameter: json: JSON representation of object. */ init?(json: JSON) } /** Enables an object to be encoded to JSON. */ public protocol Encodable { /** Encodes and object as JSON. - returns: JSON when encoding was successful, nil otherwise. */ func toJSON() -> JSON? } // MARK: - Global /** Date formatter used for ISO8601 dates. - returns: Date formatter. */ public private(set) var GlossDateFormatterISO8601: NSDateFormatter = { let dateFormatterISO8601 = NSDateFormatter() // WORKAROUND to ignore device configuration regarding AM/PM http://openradar.appspot.com/radar?id=1110403 dateFormatterISO8601.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatterISO8601.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // translate to Gregorian calendar if other calendar is selected in system settings let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! gregorian.timeZone = NSTimeZone(abbreviation: "GMT")! dateFormatterISO8601.calendar = gregorian return dateFormatterISO8601 }() /** Default delimiter used for nested key paths. - returns: Default key path delimiter. */ public private(set) var GlossKeyPathDelimiter: String = { return "." }() /** Transforms an array of JSON optionals to a single optional JSON dictionary. - parameter array: Array of JSON to transform. - parameter keyPathDelimiter: Delimiter used for nested key paths. - returns: JSON when successful, nil otherwise. */ public func jsonify(array: [JSON?], keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON? { var json: JSON = [:] for j in array { if(j != nil) { json.add(j!, delimiter: keyPathDelimiter) } } return json }
mit
4a1147615ab420503774b6d30346f639
27.615385
110
0.710872
4.530447
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/RSEnhancedInstructionStepViewController.swift
1
2352
// // RSEnhancedInstructionStepViewController.swift // Pods // // Created by James Kizer on 7/30/17. // // import UIKit import SwiftyGif open class RSEnhancedInstructionStepViewController: RSQuestionViewController { var stackView: UIStackView! override open func viewDidLoad() { super.viewDidLoad() guard let step = self.step as? RSEnhancedInstructionStep else { return } var stackedViews: [UIView] = [] if let image = step.image { let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFit stackedViews.append(imageView) } else if let gifURL = step.gifURL { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.setGifFromURL(gifURL) stackedViews.append(imageView) } if let audioTitle = step.audioTitle, let path = Bundle.main.path(forResource: audioTitle, ofType: nil) { let url = URL(fileURLWithPath: path) if let audioPlayer = RSAudioPlayer(fileURL: url) { stackedViews.append(audioPlayer) } } let stackView = UIStackView(arrangedSubviews: stackedViews) stackView.distribution = .equalCentering stackView.frame = self.contentView.bounds self.stackView = stackView if step.moveForwardOnTap { let tapHandler = UITapGestureRecognizer(target: self, action: #selector(stackViewTapped(_:))) stackView.addGestureRecognizer(tapHandler) } self.contentView.addSubview(stackView) if let skipButtonText = step.skipButtonText { self.skipButton.isHidden = false self.setSkipButtonTitle(title: skipButtonText) } } @objc public func stackViewTapped(_ gestureRecognizer: UIGestureRecognizer) { self.goForward() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.stackView.frame = self.contentView.bounds } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.stackView.frame = self.contentView.bounds } }
apache-2.0
ed0cb4b8175e55a16da113c77c4d8e48
28.772152
105
0.614371
5.369863
false
false
false
false
aolan/Cattle
CattleKit/UIView+CAFrame.swift
1
1790
// // UIView+CAFrame.swift // cattle // // Created by lawn on 15/11/5. // Copyright © 2015年 zodiac. All rights reserved. // import UIKit extension UIView{ func ca_minX() -> CGFloat{ return frame.origin.x } func ca_minX(x: CGFloat) -> Void{ frame.origin.x = x } func ca_minY() -> CGFloat{ return frame.origin.y } func ca_minY(y: CGFloat) -> Void{ frame.origin.y = y } func ca_maxX() -> CGFloat{ return frame.origin.x + frame.size.width } func ca_maxX(x:CGFloat) -> Void{ frame.origin.x = x - frame.size.width } func ca_maxY() -> CGFloat{ return frame.origin.y + frame.size.height } func ca_maxY(y:CGFloat) -> Void{ frame.origin.y = y - frame.size.height } func ca_width() -> CGFloat{ return frame.size.width } func ca_width(w:CGFloat) -> Void{ frame.size.width = w } func ca_heigth() -> CGFloat{ return frame.size.height } func ca_height(h:CGFloat) -> Void{ frame.size.height = h } func ca_centerX() -> CGFloat{ return frame.origin.x + frame.size.width/2.0 } func ca_centerX(x:CGFloat) -> Void{ frame.origin.x = x - frame.size.width/2.0 } func ca_centerY() -> CGFloat{ return frame.origin.y + frame.size.height/2.0 } func ca_centerY(y:CGFloat) -> Void{ frame.origin.y = y - frame.size.height/2.0 } func ca_center() -> CGPoint{ return CGPoint(x: ca_centerX(), y: ca_centerY()) } func ca_center(p:CGPoint) ->Void{ frame.origin.x = p.x - frame.size.width/2.0 frame.origin.y = p.y - frame.size.height/2.0 } func ca_size() -> CGSize{ return frame.size } func ca_size(size:CGSize) -> Void{ frame.size = size } func ca_addX(increment:CGFloat) -> Void{ frame.origin.x += increment } func ca_addY(increment:CGFloat) -> Void{ frame.origin.y += increment } }
mit
199df8b7f0cc9a378482677d9b8a016c
16.693069
50
0.630106
2.608759
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/VerticalParameterAlignmentRule.swift
1
4487
import Foundation import SourceKittenFramework public struct VerticalParameterAlignmentRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "vertical_parameter_alignment", name: "Vertical Parameter Alignment", description: "Function parameters should be aligned vertically if they're in multiple lines in a declaration.", kind: .style, nonTriggeringExamples: [ "func validateFunction(_ file: File, kind: SwiftDeclarationKind,\n" + " dictionary: [String: SourceKitRepresentable]) { }\n", "func validateFunction(_ file: File, kind: SwiftDeclarationKind,\n" + " dictionary: [String: SourceKitRepresentable]) -> [StyleViolation]\n", "func foo(bar: Int)\n", "func foo(bar: Int) -> String \n", "func validateFunction(_ file: File, kind: SwiftDeclarationKind,\n" + " dictionary: [String: SourceKitRepresentable])\n" + " -> [StyleViolation]\n", "func validateFunction(\n" + " _ file: File, kind: SwiftDeclarationKind,\n" + " dictionary: [String: SourceKitRepresentable]) -> [StyleViolation]\n", "func validateFunction(\n" + " _ file: File, kind: SwiftDeclarationKind,\n" + " dictionary: [String: SourceKitRepresentable]\n" + ") -> [StyleViolation]\n", "func regex(_ pattern: String,\n" + " options: NSRegularExpression.Options = [.anchorsMatchLines,\n" + " .dotMatchesLineSeparators]) -> NSRegularExpression\n", "func foo(a: Void,\n b: [String: String] =\n [:]) {\n}\n", "func foo(data: (size: CGSize,\n" + " identifier: String)) {}" ], triggeringExamples: [ "func validateFunction(_ file: File, kind: SwiftDeclarationKind,\n" + " ↓dictionary: [String: SourceKitRepresentable]) { }\n", "func validateFunction(_ file: File, kind: SwiftDeclarationKind,\n" + " ↓dictionary: [String: SourceKitRepresentable]) { }\n", "func validateFunction(_ file: File,\n" + " ↓kind: SwiftDeclarationKind,\n" + " ↓dictionary: [String: SourceKitRepresentable]) { }\n" ] ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard SwiftDeclarationKind.functionKinds.contains(kind), let startOffset = dictionary.nameOffset, let length = dictionary.nameLength, case let endOffset = startOffset + length else { return [] } let params = dictionary.substructure.filter { subDict in return subDict.kind.flatMap(SwiftDeclarationKind.init) == .varParameter && (subDict.offset ?? .max) < endOffset } guard params.count > 1 else { return [] } let contents = file.contents.bridge() let paramLocations = params.compactMap { paramDict -> Location? in guard let byteOffset = paramDict.offset, let lineAndChar = contents.lineAndCharacter(forByteOffset: byteOffset) else { return nil } return Location(file: file.path, line: lineAndChar.line, character: lineAndChar.character) } var violationLocations = [Location]() let firstParamLoc = paramLocations[0] for (index, paramLoc) in paramLocations.enumerated() where index > 0 && paramLoc.line! > firstParamLoc.line! { let previousParamLoc = paramLocations[index - 1] if previousParamLoc.line! < paramLoc.line! && firstParamLoc.character! != paramLoc.character! { violationLocations.append(paramLoc) } } return violationLocations.map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: $0) } } }
mit
dee34170df09d114676660539ec7a9ea
47.16129
119
0.562179
5.300592
false
false
false
false
benlangmuir/swift
benchmark/single-source/ArrayInClass.swift
10
1921
//===--- ArrayInClass.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 TestsUtils public let benchmarks = [ BenchmarkInfo( name: "ArrayInClass", runFunction: run_ArrayInClass, tags: [.validation, .api, .Array], setUpFunction: { ac = ArrayContainer() }, tearDownFunction: { ac = nil }, legacyFactor: 5), BenchmarkInfo(name: "DistinctClassFieldAccesses", runFunction: run_DistinctClassFieldAccesses, tags: [.validation, .api, .Array], setUpFunction: { workload = ClassWithArrs(n: 10_000) }, tearDownFunction: { workload = nil }), ] var ac: ArrayContainer! class ArrayContainer { final var arr : [Int] init() { arr = [Int] (repeating: 0, count: 20_000) } func runLoop(_ n: Int) { for _ in 0 ..< n { for i in 0 ..< arr.count { arr[i] = arr[i] + 1 } } } } @inline(never) public func run_ArrayInClass(_ n: Int) { let a = ac! a.runLoop(n) } class ClassWithArrs { var n: Int = 0 var a: [Int] var b: [Int] init(n: Int) { self.n = n a = [Int](repeating: 0, count: n) b = [Int](repeating: 0, count: n) } func readArr() { for i in 0..<self.n { guard a[i] == b[i] else { fatalError("") } } } func writeArr() { for i in 0..<self.n { a[i] = i b[i] = i } } } var workload: ClassWithArrs! public func run_DistinctClassFieldAccesses(_ n: Int) { for _ in 1...n { workload.writeArr() workload.readArr() } }
apache-2.0
aab1f7ef0f24b31df2a4a06e854ab8b8
21.337209
80
0.566372
3.557407
false
false
false
false
benlangmuir/swift
stdlib/public/core/Print.swift
9
8616
//===--- Print.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if !SWIFT_STDLIB_STATIC_PRINT /// Writes the textual representations of the given items into the standard /// output. /// /// You can pass zero or more items to the `print(_:separator:terminator:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a string, /// a closed range of integers, and a group of floating-point values to /// standard output: /// /// print("One two three four five") /// // Prints "One two three four five" /// /// print(1...5) /// // Prints "1...5" /// /// print(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `print(_:separator:terminator:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// for n in 1...5 { /// print(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). public func print( _ items: Any..., separator: String = " ", terminator: String = "\n" ) { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _print(items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _print(items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items most suitable for /// debugging into the standard output. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:)` function. The textual representation /// for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints the debugging /// representation of a string, a closed range of integers, and a group of /// floating-point values to standard output: /// /// debugPrint("One two three four five") /// // Prints "One two three four five" /// /// debugPrint(1...5) /// // Prints "ClosedRange(1...5)" /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `debugPrint(_:separator:terminator:)` includes /// a newline by default. To print the items without a trailing newline, pass /// an empty string as `terminator`. /// /// for n in 1...5 { /// debugPrint(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). public func debugPrint( _ items: Any..., separator: String = " ", terminator: String = "\n" ) { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _debugPrint(items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _debugPrint(items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items into the given output /// stream. /// /// You can pass zero or more items to the `print(_:separator:terminator:to:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a closed /// range of integers to a string: /// /// var range = "My range: " /// print(1...5, to: &range) /// // range == "My range: 1...5\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `print(_:separator:terminator:to:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// print(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. public func print<Target: TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _print(items, separator: separator, terminator: terminator, to: &output) } /// Writes the textual representations of the given items most suitable for /// debugging into the given output stream. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:to:)` function. The textual /// representation for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints a closed range of /// integers to a string: /// /// var range = "My range: " /// debugPrint(1...5, to: &range) /// // range == "My range: ClosedRange(1...5)\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `debugPrint(_:separator:terminator:to:)` /// includes a newline by default. To print the items without a trailing /// newline, pass an empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// debugPrint(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. public func debugPrint<Target: TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _debugPrint(items, separator: separator, terminator: terminator, to: &output) } internal func _print<Target: TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _print_unlocked(item, &output) prefix = separator } output.write(terminator) } internal func _debugPrint<Target: TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _debugPrint_unlocked(item, &output) prefix = separator } output.write(terminator) } #endif
apache-2.0
7a26b6ddff7d1365b2613ba3dcbf621c
33.055336
81
0.612117
3.675768
false
false
false
false
ikesyo/swift-corelibs-foundation
Foundation/Progress.swift
9
32798
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import Dispatch /** `Progress` is used to report the amount of work done, and provides a way to allow the user to cancel that work. Since work is often split up into several parts, progress objects can form a tree where children represent part of the overall total work. Each parent may have as many children as required, but each child only has one parent. The top level progress object in this tree is typically the one that you would display to a user. The leaf objects are updated as work completes, and the updates propagate up the tree. The work that a `Progress` does is tracked via a "unit count." There are two unit count values: total and completed. In its leaf form, a `Progress` is created with a total unit count and its completed unit count is updated by setting `completedUnitCount` until it matches the `totalUnitCount`. The progress is then considered finished. When progress objects form nodes in trees, they are still created with a total unit count. Portions of the total are then handed out to children as a "pending unit count." The total amount handed out to children should add up to the parent's `totalUnitCount`. When those children become finished, the pending unit count assigned to that child is added to the parent's `completedUnitCount`. Therefore, when all children are finished, the parent's `completedUnitCount` is equal to its `totalUnitCount` and it becomes finished itself. Children `Progress` objects can be added implicitly or by calling `addChild(withPendingUnitCount)` on the parent. Implicitly added children are attached to a parent progress between a call to `becomeCurrent(withPendingUnitCount)` and a call to `resignCurrent`. The implicit child is created with the `Progress(totalUnitCount:)` initializer, or by passing the result of `Progress.currentProgress` to the `Progress(parent:userInfo:)` initializer. Both kinds of children can be attached to the same parent progress object. If you have an idea in advance that some portions of the work will take more or less time than the others, you can use different values of pending unit count for each child. If you are designing an interface of an object that reports progress, then the recommended approach is to vend a `Progress` property and adopt the `ProgressReporting` protocol. The progress should be created with the `Progress.discreteProgress(withTotalUnitCount:)` class function. You can then either update the progress object directly or set it up to have children of its own. Users of your object can compose your progress into their tree by using the `addChild(withPendingUnitCount)` function. If you want to provide progress reporting for a single method, then the recommended approach is to implicitly attach to a current `Progress` by creating an `Progress` object at the very beginning of your method using `Progress(withTotalUnitCount)`. This progress object will consume the pending unit count, and then you can set up the progress object with children of its own. The `localizedDescription` and `localizedAdditionalDescription` properties are meant to be observed as well as set. So are the `cancellable` and `pausable` properties. `totalUnitCount` and `completedUnitCount`, on the other hand, are often not the best properties to observe when presenting progress to the user. You should observe `fractionCompleted` instead of observing `totalUnitCount` and `completedUnitCount` and doing your own calculation. `Progress`' default implementation of `fractionCompleted` does fairly sophisticated things like taking child `Progress` into account. - note: In swift-corelibs-foundation, Key Value Observing is not yet available. */ open class Progress : NSObject { private weak var _parent : Progress? private var _children : Set<Progress> private var _selfFraction : _ProgressFraction private var _childFraction : _ProgressFraction private var _userInfo : [ProgressUserInfoKey : Any] // This is set once, but after initialization private var _portionOfParent : Int64 static private var _tsdKey = "_Foundation_CurrentProgressKey" /// The instance of `Progress` associated with the current thread by a previous invocation of `becomeCurrent(withPendingUnitCount:)`, if any. /// /// The purpose of this per-thread value is to allow code that does work to usefully report progress even when it is widely separated from the code that actually presents progress to the user, without requiring layers of intervening code to pass the instance of `Progress` through. Using the result of invoking this directly will often not be the right thing to do, because the invoking code will often not even know what units of work the current progress object deals in. Using `Progress(withTotalUnitCount:)` to create a child `Progress` object and then using that to report progress makes more sense in that situation. open class func current() -> Progress? { return (Thread.current.threadDictionary[Progress._tsdKey] as? _ProgressTSD)?.currentProgress } /// Initializes an instance of `Progress` with a parent of `Progress.current()`. /// /// The value of the `totalUnitCount` property is also set. In many cases you can simply precede code that does a substantial amount of work with an invocation of this method, with repeated setting of the `completedUnitCount` property and synchronous checking of `isCancelled` in the loop that does the work. public convenience init(totalUnitCount unitCount: Int64) { self.init(parent: Progress.current()) totalUnitCount = unitCount } /// Initializes an instance of `Progress` with a `nil` parent. /// /// The value of the `totalUnitCount` property is also set. The resulting progress object is not part of an existing progress tree. open class func discreteProgress(totalUnitCount unitCount: Int64) -> Progress { let progress = Progress(parent: nil) progress.totalUnitCount = unitCount return progress } /// Initializes an instance of `Progress` with the specified total unit count, parent, and pending unit count. public convenience init(totalUnitCount unitCount: Int64, parent: Progress, pendingUnitCount portionOfParentTotalUnitCount: Int64) { self.init(parent: nil) totalUnitCount = unitCount parent.addChild(self, withPendingUnitCount: portionOfParentTotalUnitCount) } /// Initializes an instance of `Progress` with the specified parent and user info dictionary. public init(parent parentProgress: Progress?, userInfo userInfoOrNil: [ProgressUserInfoKey : Any]? = nil) { _children = Set() isCancellable = false isPausable = false isCancelled = false isPaused = false _selfFraction = _ProgressFraction() _childFraction = _ProgressFraction() // It doesn't matter what the units are here as long as the total is non-zero _childFraction.total = 1 // This is reset later, if this progress becomes a child of some other progress _portionOfParent = 0 _userInfo = userInfoOrNil ?? [:] super.init() if let p = parentProgress { precondition(p === Progress.current(), "The Parent must be the current progress") p._addImplicitChild(self) } } /// MARK: - /// This is called when some other progress becomes an implicit child of this progress. private func _addImplicitChild(_ child : Progress) { guard let tsd = Thread.current.threadDictionary[Progress._tsdKey] as? _ProgressTSD else { preconditionFailure("A child was added without a current progress being set") } // We only allow one implicit child. More than that and things get confusing (and wrong) real quick. if !tsd.childAttached { addChild(child, withPendingUnitCount: tsd.pendingUnitCount) tsd.childAttached = true } } /// Make this `Progress` the current thread's current progress object, returned by `Progress.currentProgress()`. /// /// At the same time, record how large a portion of the work represented by the progress will be represented by the next progress object initialized with `Progress(parent:userInfo:)` in the current thread with this `Progress` as the parent. The portion of work will be used when the `completedUnitCount` of the child is set. /// /// With this mechanism, code that doesn't know anything about its callers can report progress accurately by using `Progress(withTotalUnitCount:)` and `completedUnitCount`. The calling code will account for the fact that the work done is only a portion of the work to be done as part of a larger operation. /// /// The unit of work in a call to `becomeCurrent(withPendingUnitCount:)` has to be the same unit of work as that used for the value of the `totalUnitCount` property, but the unit of work used by the child can be a completely different one, and often will be. /// /// You must always balance invocations of this method with invocations of `resignCurrent`. open func becomeCurrent(withPendingUnitCount unitCount: Int64) { let oldTSD = Thread.current.threadDictionary[Progress._tsdKey] as? _ProgressTSD if let checkedTSD = oldTSD { precondition(checkedTSD.currentProgress !== self, "This Progress is already current on this thread.") } let newTSD = _ProgressTSD(currentProgress: self, nextTSD: oldTSD, pendingUnitCount: unitCount) Thread.current.threadDictionary[Progress._tsdKey] = newTSD } /// Balance the most recent previous invocation of `becomeCurrent(withPendingUnitCount:)` on the same thread. /// /// This restores the current progress object to what it was before `becomeCurrent(withPendingUnitCount:)` was invoked. open func resignCurrent() { guard let oldTSD = Thread.current.threadDictionary[Progress._tsdKey] as? _ProgressTSD else { preconditionFailure("This Progress was not the current progress on this thread.") } if !oldTSD.childAttached { // No children attached. Account for the completed unit count now. _addCompletedUnitCount(oldTSD.pendingUnitCount) } // Ok if the following is nil - then we clear the dictionary entry let newTSD = oldTSD.nextTSD Thread.current.threadDictionary[Progress._tsdKey] = newTSD } /// Directly add a child progress to the receiver, assigning it a portion of the receiver's total unit count. open func addChild(_ child: Progress, withPendingUnitCount inUnitCount: Int64) { precondition(child._parent == nil, "The Progress was already the child of another Progress") _children.insert(child) child._setParent(self, portion: inUnitCount) if isCancelled { child.cancel() } if isPaused { child.pause() } } private func _setParent(_ parent: Progress, portion: Int64) { _parent = parent _portionOfParent = portion // We need to tell the new parent what our fraction completed is // The previous fraction is the same as if it didn't exist (0/0), but the new one represents our current state. _parent?._updateChild(self, from: _ProgressFraction(completed: 0, total: 0), to: _overallFraction, portion: portion) } /// How much of the job has been completed so far. /// /// For a `Progress` with a kind of `.file`, the unit of these properties is bytes while the `fileTotalCountKey` and `fileCompletedCountKey` keys in the `userInfo` dictionary are used for the overall count of files. For any other kind of `Progress`, the unit of measurement you use does not matter as long as you are consistent. The values may be reported to the user in the `localizedDescription` and `localizedAdditionalDescription`. /// /// If the `Progress` object is a "leaf progress" (no children), then the `fractionCompleted` is generally `completedUnitCount / totalUnitCount`. If the receiver `Progress` has children, the `fractionCompleted` will reflect progress made in child objects in addition to its own `completedUnitCount`. As children finish, the `completedUnitCount` of the parent will be updated. open var totalUnitCount: Int64 { get { return _selfFraction.total } set { let previous = _overallFraction if _selfFraction.total != newValue && _selfFraction.total > 0 { _childFraction = _childFraction * _ProgressFraction(completed: _selfFraction.total, total: newValue) } _selfFraction.total = newValue _updateFractionCompleted(from: previous, to: _overallFraction) } } /// The size of the job whose progress is being reported. /// /// For a `Progress` with a kind of `.file`, the unit of these properties is bytes while the `fileTotalCountKey` and `fileCompletedCountKey` keys in the `userInfo` dictionary are used for the overall count of files. For any other kind of `Progress`, the unit of measurement you use does not matter as long as you are consistent. The values may be reported to the user in the `localizedDescription` and `localizedAdditionalDescription`. /// /// If the `Progress` object is a "leaf progress" (no children), then the `fractionCompleted` is generally `completedUnitCount / totalUnitCount`. If the receiver `Progress` has children, the `fractionCompleted` will reflect progress made in child objects in addition to its own `completedUnitCount`. As children finish, the `completedUnitCount` of the parent will be updated. open var completedUnitCount: Int64 { get { return _selfFraction.completed } set { let previous = _overallFraction _selfFraction.completed = newValue _updateFractionCompleted(from: previous, to: _overallFraction) } } /// A description of what progress is being made, fit to present to the user. /// /// `Progress` is by default KVO-compliant for this property, with the notifications always being sent on thread which updates the property. The default implementation of the getter for this property does not always return the most recently set value of the property. If the most recently set value of this property is nil then `Progress` uses the value of the `kind` property to determine how to use the values of other properties, as well as values in the user info dictionary, to return a computed string. If it fails to do that then it returns an empty string. /// /// For example, depending on the kind of progress, the completed and total unit counts, and other parameters, these kinds of strings may be generated: /// Copying 10 files… /// 30% completed /// Copying “TextEdit”… /// - note: In swift-corelibs-foundation, Key Value Observing is not yet available. open var localizedDescription: String! { // Unimplemented return "" } /// A more specific description of what progress is being made, fit to present to the user. /// /// `Progress` is by default KVO-compliant for this property, with the notifications always being sent on thread which updates the property. The default implementation of the getter for this property does not always return the most recently set value of the property. If the most recently set value of this property is nil then `Progress` uses the value of the `kind` property to determine how to use the values of other properties, as well as values in the user info dictionary, to return a computed string. If it fails to do that then it returns an empty string. The difference between this and `localizedDescription` is that this text is meant to be more specific about what work is being done at any particular moment. /// /// For example, depending on the kind of progress, the completed and total unit counts, and other parameters, these kinds of strings may be generated: /// 3 of 10 files /// 123 KB of 789.1 MB /// 3.3 MB of 103.92 GB — 2 minutes remaining /// 1.61 GB of 3.22 GB (2 KB/sec) — 2 minutes remaining /// 1 minute remaining (1 KB/sec) /// - note: In swift-corelibs-foundation, Key Value Observing is not yet available. open var localizedAdditionalDescription: String! { // Unimplemented return "" } /// Whether the work being done can be cancelled. /// /// By default `Progress` is cancellable. /// /// This property is for communicating whether controls for cancelling should appear in a progress reporting user interface. `Progress` itself does not do anything with these properties other than help pass their values from progress reporters to progress observers. It is valid for the values of these properties to change in virtually any way during the lifetime of a `Progress`. Of course, if a `Progress` is cancellable you should actually implement cancellability by setting a cancellation handler or by making your code poll the result of invoking `isCancelled`. open var isCancellable: Bool /// Whether the work being done can be paused. /// /// By default `Progress` not pausable. /// /// This property is for communicating whether controls for pausing should appear in a progress reporting user interface. `Progress` itself does not do anything with these properties other than help pass their values from progress reporters to progress observers. It is valid for the values of these properties to change in virtually any way during the lifetime of a `Progress`. Of course, if a `Progress` is pausable you should actually implement pausibility by setting a pausing handler or by making your code poll the result of invoking `isPaused`. open var isPausable: Bool /// Whether the work being done has been cancelled. /// /// Instances of `Progress` that have parents are at least as cancelled as their parents. open var isCancelled: Bool /// Whether the work being done has been paused. /// /// Instances of `Progress` that have parents are at least as paused as their parents. open var isPaused: Bool /// A closure to be called when `cancel` is called. /// /// The closure will be called even when the function is called on an ancestor of the receiver. Your closure won't be called on any particular queue. If it must do work on a specific queue then it should schedule that work on that queue. open var cancellationHandler: (() -> Void)? { didSet { guard let handler = cancellationHandler else { return } // If we're already cancelled, then invoke it - asynchronously if isCancelled { DispatchQueue.global().async { handler() } } } } /// A closure to be called when pause is called. /// /// The closure will be called even when the function is called on an ancestor of the receiver. Your closure won't be called on any particular queue. If it must do work on a specific queue then it should schedule that work on that queue. open var pausingHandler: (() -> Void)? { didSet { guard let handler = pausingHandler else { return } // If we're already paused, then invoke it - asynchronously if isPaused { DispatchQueue.global().async { handler() } } } } /// A closure to be called when resume is called. /// /// The closure will be called even when the function is called on an ancestor of the receiver. Your closure won't be called on any particular queue. If it must do work on a specific queue then it should schedule that work on that queue. open var resumingHandler: (() -> Void)? /// Returns `true` if the progress is indeterminate. /// /// This returns `true` when the value of the `totalUnitCount` or `completedUnitCount` property is less than zero. Zero values for both of those properties indicates that there turned out to not be any work to do after all; `isIndeterminate` returns `false` and `fractionCompleted` returns `1.0` in that case. open var isIndeterminate: Bool { return _selfFraction.isIndeterminate } /// Returns `true` if the progress is finished. /// /// Checking the result of this function is preferred to comparing `fractionCompleted`, as rounding errors can cause that value to appear less than `1.0` in some circumstances. /// - Experiment: This is a draft API currently under consideration for official import into Foundation open var isFinished: Bool { return _selfFraction.isFinished } /// The fraction of the overall work completed by this progress object, including work done by any children it may have. public var fractionCompleted: Double { // We have to special case one thing to maintain consistency; if _selfFraction.total == 0 then we do not add any children guard _selfFraction.total > 0 else { return _selfFraction.fractionCompleted } return (_selfFraction + _childFraction).fractionCompleted } /// Calls the closure registered with the `cancellationHandler` property, if there is one, and set the `isCancelled` property to `true`. /// /// Do this for this `Progress` and any descendants of this `Progress`. open func cancel() { isCancelled = true if let handler = cancellationHandler { DispatchQueue.global().async { handler() } } for child in _children { child.cancel() } } /// Calls the closure registered with the `pausingHandler` property, if there is one, and set the `isPaused` property to `true`. /// /// Do this for this `Progress` and any descendants of this `Progress`. open func pause() { isPaused = true if let handler = pausingHandler { DispatchQueue.global().async { handler() } } for child in _children { child.pause() } } /// Calls the closure registered with the `resumingHandler` property, if there is one, and set the `isPaused` property to `false`. /// /// Do this for this `Progress` and any descendants of this `Progress`. open func resume() { isPaused = false if let handler = resumingHandler { DispatchQueue.global().async { handler() } } for child in _children { child.resume() } } /// Set a value in the dictionary returned by `userInfo`, with appropriate KVO notification for properties whose values can depend on values in the user info dictionary, like `localizedDescription`. If a nil value is passed then the dictionary entry is removed. /// - note: In swift-corelibs-foundation, Key Value Observing is not yet available. open func setUserInfoObject(_ objectOrNil: Any?, forKey key: ProgressUserInfoKey) { _userInfo[key] = objectOrNil } /// A collection of arbitrary values associated with this `Progress`. /// /// Returns a KVO-compliant dictionary that changes as `setUserInfoObject(forKey:)` is sent to this `Progress`. The dictionary will send all of its KVO notifications on the thread which updates the property. The result will never be nil, but may be an empty dictionary. /// /// Some entries have meanings that are recognized by the `Progress` class itself. See also `ProgressUserInfoKey`. /// - note: In swift-corelibs-foundation, Key Value Observing is not yet available. open var userInfo: [ProgressUserInfoKey : Any] { return _userInfo } /// Optionally specifies more information about what kind of progress is being reported. /// /// If the value of the `localizedDescription` property has not been set, then the default implementation of `localizedDescription` uses the progress kind to determine how to use the values of other properties, as well as values in the user info dictionary, to create a string that is presentable to the user. open var kind: ProgressKind? public struct FileOperationKind : RawRepresentable, Equatable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: FileOperationKind, _ rhs: FileOperationKind) -> Bool { return lhs.rawValue == rhs.rawValue } /// Use for indicating the progress represents a download. public static let downloading = FileOperationKind(rawValue: "NSProgressFileOperationKindDownloading") /// Use for indicating the progress represents decompressing after downloading. public static let decompressingAfterDownloading = FileOperationKind(rawValue: "NSProgressFileOperationKindDecompressingAfterDownloading") /// Use for indicating the progress represents receiving a file in some way. public static let receiving = FileOperationKind(rawValue: "NSProgressFileOperationKindReceiving") /// Use for indicating the progress represents copying a file. public static let copying = FileOperationKind(rawValue: "NSProgressFileOperationKindCopying") } // MARK: - // MARK: Implementation of unit counts private var _overallFraction : _ProgressFraction { return _selfFraction + _childFraction } private func _addCompletedUnitCount(_ unitCount : Int64) { let old = _overallFraction _selfFraction.completed += unitCount let new = _overallFraction _updateFractionCompleted(from: old, to: new) } private func _updateFractionCompleted(from: _ProgressFraction, to: _ProgressFraction) { if from != to { _parent?._updateChild(self, from: from, to: to, portion: _portionOfParent) } } /// A child progress has been updated, which changes our own fraction completed. private func _updateChild(_ child: Progress, from previous: _ProgressFraction, to next: _ProgressFraction, portion: Int64) { let previousOverallFraction = _overallFraction let multiple = _ProgressFraction(completed: portion, total: _selfFraction.total) let oldFractionOfParent = previous * multiple // Subtract the previous fraction (multiplied by portion), add new fraction (multiplied by portion). If either is indeterminate, treat as zero. if !previous.isIndeterminate { _childFraction = _childFraction - oldFractionOfParent } if !next.isIndeterminate { _childFraction = _childFraction + (next * multiple) } if next.isFinished { _children.remove(child) if portion != 0 { // Update our self completed units _selfFraction.completed += portion // Subtract the (child's fraction completed * multiple) from our child fraction _childFraction = _childFraction - (multiple * next) } } _updateFractionCompleted(from: previousOverallFraction, to: _overallFraction) } } /// If your class supports reporting progress, then you can adopt the ProgressReporting protocol. /// /// Objects that adopt this protocol should typically be "one-shot" -- that is, the progress is setup at initialization of the object and is updated when work is done. The value of the property should not be set to another progress object. Instead, the user of the `ProgressReporting` class should create a new instance to represent a new set of work. public protocol ProgressReporting : NSObjectProtocol { var progress: Progress { get } } public struct ProgressKind : RawRepresentable, Equatable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: ProgressKind, _ rhs: ProgressKind) -> Bool { return lhs.rawValue == rhs.rawValue } /// Indicates that the progress being performed is related to files. /// /// Progress of this kind is assumed to use bytes as the unit of work being done and the default implementation of `localizedDescription` takes advantage of that to return more specific text than it could otherwise. public static let file = ProgressKind(rawValue: "NSProgressKindFile") } public struct ProgressUserInfoKey : RawRepresentable, Equatable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: ProgressUserInfoKey, _ rhs: ProgressUserInfoKey) -> Bool { return lhs.rawValue == rhs.rawValue } /// How much time is probably left in the operation, as an NSNumber containing a number of seconds. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is an `NSNumber`. public static let estimatedTimeRemainingKey = ProgressUserInfoKey(rawValue: "NSProgressEstimatedTimeRemainingKey") /// How fast data is being processed, as an NSNumber containing bytes per second. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is an `NSNumber`. public static let throughputKey = ProgressUserInfoKey(rawValue: "NSProgressThroughputKey") /// A description of what "kind" of progress is being made on a file. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is a `Progress.FileOperationKind`. public static let fileOperationKindKey = ProgressUserInfoKey(rawValue: "NSProgressFileOperationKindKey") /// A URL for the item on which progress is being made. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is a `URL`. public static let fileURLKey = ProgressUserInfoKey(rawValue: "NSProgressFileURLKey") /// The total number of files. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is an `NSNumber`. public static let fileTotalCountKey = ProgressUserInfoKey(rawValue: "NSProgressFileTotalCountKey") /// The completed number of files. /// /// If this value is present, then `Progress` can present a more detailed `localizedAdditionalDescription`. /// Value is an `NSNumber`. public static let fileCompletedCountKey = ProgressUserInfoKey(rawValue: "NSProgressFileCompletedCountKey") } fileprivate class _ProgressTSD { /// The thread's default progress. fileprivate var currentProgress : Progress /// The instances of this thing that will become current the next time resignCurrent is called fileprivate var nextTSD : _ProgressTSD? /// Pending unit count var pendingUnitCount : Int64 /// True if any children are implicitly attached var childAttached : Bool init(currentProgress: Progress, nextTSD: _ProgressTSD?, pendingUnitCount: Int64) { self.currentProgress = currentProgress self.pendingUnitCount = pendingUnitCount self.nextTSD = nextTSD childAttached = false } }
apache-2.0
b9fc236104649782292aa0bd60a4ee90
57.651163
726
0.699018
5.143709
false
false
false
false
zirinisp/SlackKit
SlackKit/Sources/Client+Utilities.swift
1
2547
// // Client+Utilities.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public enum ClientError: Error { case channelDoesNotExist case userDoesNotExist } public extension Client { //MARK: - User & Channel public func getChannelIDWith(name: String) throws -> String { guard let id = channels.filter({$0.1.name == strip(string:name)}).first?.0 else { throw ClientError.channelDoesNotExist } return id } public func getUserIDWith(name: String) throws -> String { guard let id = users.filter({$0.1.name == strip(string:name)}).first?.0 else { throw ClientError.userDoesNotExist } return id } public func getImIDForUserWith(id: String, success: @escaping (_ imID: String?)->Void, failure: @escaping (SlackError)->Void) { let ims = channels.filter{$0.1.isIM == true} let channel = ims.filter{$0.1.user == id}.first if let channel = channel { success(channel.0) } else { webAPI.openIM(id, success: success, failure: failure) } } //MARK: - Utilities internal func strip(string: String) -> String { var strippedString = string if string[string.startIndex] == "@" || string[string.startIndex] == "#" { strippedString = string.substring(from: string.characters.index(string.startIndex, offsetBy: 1)) } return strippedString } }
mit
5ee70f4a7bb616b2dbe0f9bb0debd35c
38.78125
131
0.678712
4.397237
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/Services/MediaSettings.swift
1
3187
import Foundation protocol MediaSettingsStorage { func valueForKey(key: String) -> AnyObject? func setValue(value: AnyObject, forKey key: String) } class MediaSettings: NSObject { // MARK: - Constants private let maxImageSizeKey = "SavedMaxImageSizeSetting" private let minImageDimension = 150 private let maxImageDimension = 3000 // MARK: - Internal variables private let storage: MediaSettingsStorage // MARK: - Initialization init(storage: MediaSettingsStorage) { self.storage = storage super.init() } convenience override init() { self.init(storage: DefaultsStorage()) } // MARK: Public accessors /// The minimum and maximum allowed sizes for `maxImageSizeSetting`. /// The UI to configure this setting should not allow values outside this limits. /// - seealso: maxImageSizeSetting var allowedImageSizeRange: (min: Int, max: Int) { return (minImageDimension, maxImageDimension) } /// The size that an image needs to be resized to before uploading. /// - note: if the image doesn't need to be resized, it returns `Int.max` var imageSizeForUpload: Int { if maxImageSizeSetting >= maxImageDimension { return Int.max } else { return maxImageSizeSetting } } /// The stored value for the maximum size images can have before uploading. /// If you set this to `maxImageDimension` or higher, it means images won't /// be resized on upload. /// If you set this to `minImageDimension` or lower, it will be set to `minImageDimension`. /// - important: don't access this propery directly to check what size to resize an image, use `imageSizeForUpload` instead. var maxImageSizeSetting: Int { get { if let savedSize = storage.valueForKey(maxImageSizeKey) as? Int { return savedSize } else if let savedSize = storage.valueForKey(maxImageSizeKey) as? String { let newSize = CGSizeFromString(savedSize).width storage.setValue(newSize, forKey: maxImageSizeKey) return Int(newSize) } else { return maxImageDimension } } set { let size = newValue.clamp(min: minImageDimension, max: maxImageDimension) storage.setValue(size, forKey: maxImageSizeKey) } } // MARK: - Storage implementations struct DefaultsStorage: MediaSettingsStorage { func setValue(value: AnyObject, forKey key: String) { NSUserDefaults.standardUserDefaults().setObject(value, forKey: key) NSUserDefaults.resetStandardUserDefaults() } func valueForKey(key: String) -> AnyObject? { return NSUserDefaults.standardUserDefaults().objectForKey(key) } } class EphemeralStorage: MediaSettingsStorage { private var memory = [String: AnyObject]() func setValue(value: AnyObject, forKey key: String) { memory[key] = value } func valueForKey(key: String) -> AnyObject? { return memory[key] } } }
gpl-2.0
905df10467e623a5538e3866ede665b6
33.641304
128
0.641042
5.107372
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/AbstractPost+TitleForVisibility.swift
2
898
import Foundation extension AbstractPost { static let passwordProtectedLabel = NSLocalizedString("Password protected", comment: "Privacy setting for posts set to 'Password protected'. Should be the same as in core WP.") static let privateLabel = NSLocalizedString("Private", comment: "Privacy setting for posts set to 'Private'. Should be the same as in core WP.") static let publicLabel = NSLocalizedString("Public", comment: "Privacy setting for posts set to 'Public' (default). Should be the same as in core WP.") /// A title describing the status. Ie.: "Public" or "Private" or "Password protected" @objc var titleForVisibility: String { if password != nil { return AbstractPost.passwordProtectedLabel } else if status == .publishPrivate { return AbstractPost.privateLabel } return AbstractPost.publicLabel } }
gpl-2.0
0882d748792b432929972d458347d61d
48.888889
180
0.706013
5.01676
false
false
false
false
fastred/SingleFetchedResultController
Framework/SingleFetchedResultController.swift
1
2969
// // SingleFetchedResultController.swift // SingleFetchedResultController // // Created by Arkadiusz Holko on 07/06/16. // Copyright © 2016 Arkadiusz Holko. All rights reserved. // import Foundation import CoreData public protocol EntityNameProviding { static func entityName() -> String } public enum ChangeType { case firstFetch case insert case update case delete } open class SingleFetchedResultController<T: NSManagedObject> where T: EntityNameProviding { public typealias OnChange = ((T, ChangeType) -> Void) open let predicate: NSPredicate open let managedObjectContext: NSManagedObjectContext open let onChange: OnChange open fileprivate(set) var object: T? = nil public init(predicate: NSPredicate, managedObjectContext: NSManagedObjectContext, onChange: @escaping OnChange) { self.predicate = predicate self.managedObjectContext = managedObjectContext self.onChange = onChange NotificationCenter.default.addObserver(self, selector: #selector(objectsDidChange(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } open func performFetch() throws { let fetchRequest = NSFetchRequest<T>(entityName: T.entityName()) fetchRequest.predicate = predicate let results = try managedObjectContext.fetch(fetchRequest) assert(results.count < 2) // we shouldn't have any duplicates if let result = results.first { object = result onChange(result, .firstFetch) } } @objc func objectsDidChange(_ notification: Notification) { updateCurrentObject(notification: notification, key: NSInsertedObjectsKey) updateCurrentObject(notification: notification, key: NSUpdatedObjectsKey) updateCurrentObject(notification: notification, key: NSDeletedObjectsKey) } fileprivate func updateCurrentObject(notification: Notification, key: String) { guard let allModifiedObjects = (notification as NSNotification).userInfo?[key] as? Set<NSManagedObject> else { return } let objectsWithCorrectType = Set(allModifiedObjects.filter { return $0 as? T != nil }) let matchingObjects = NSSet(set: objectsWithCorrectType) .filtered(using: self.predicate) as? Set<NSManagedObject> ?? [] assert(matchingObjects.count < 2) guard let matchingObject = matchingObjects.first as? T else { return } object = matchingObject onChange(matchingObject, changeType(fromKey: key)) } fileprivate func changeType(fromKey key: String) -> ChangeType { let map: [String : ChangeType] = [ NSInsertedObjectsKey : .insert, NSUpdatedObjectsKey : .update, NSDeletedObjectsKey : .delete, ] return map[key]! } }
mit
90ce5dc33985b0bc998da70f814b2753
31.977778
174
0.688005
5.126079
false
false
false
false
publickanai/PLMSideMenu
Example/PLMSideMenu/MenuViewController.swift
1
3334
// // MenuViewController.swift // PLMSideMenu // // Created by Tatsuhiro Kanai on 2016/04/21. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit class MenuViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) // 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 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... 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. } */ }
mit
de6e8831c900396515e70375d6132997
33.340206
157
0.684179
5.469622
false
false
false
false
tgu/HAP
Sources/HAP/Utils/WeakObjectSet.swift
1
1763
//adapted from: http://stackoverflow.com/a/36184182 class WeakObject<T: AnyObject>: Equatable, Hashable { weak var object: T? init(_ object: T) { self.object = object } var hashValue: Int { if let object = self.object { return ObjectIdentifier(object).hashValue } else { return 0 } } static func == <T> (lhs: WeakObject<T>, rhs: WeakObject<T>) -> Bool { return lhs.object === rhs.object } } struct WeakObjectSet<T: AnyObject>: Sequence, ExpressibleByArrayLiteral where T: Hashable { var objects: Set<WeakObject<T>> init() { self.objects = Set() } init(objects: [T]) { self.objects = Set(objects.map { WeakObject($0) }) } var allObjects: [T] { return objects.compactMap { $0.object } } func contains(object: T) -> Bool { return self.objects.contains(WeakObject(object)) } mutating func addObject(object: T) { cleanup() self.objects.formUnion([WeakObject(object)]) } mutating func addObjects(objects: [T]) { cleanup() self.objects.formUnion(objects.map { WeakObject($0) }) } mutating func remove(_ member: T) -> T? { cleanup() return self.objects.remove(WeakObject(member))?.object } mutating func cleanup() { objects = objects.filter { $0.object != nil } } /// Complexity: O(n) var isEmpty: Bool { return allObjects.isEmpty } // Sequence func makeIterator() -> IndexingIterator<[T]> { return allObjects.makeIterator() } // ExpressibleByArrayLiteral init(arrayLiteral elements: T...) { self.objects = Set(elements.map { WeakObject($0) }) } }
mit
d3bcc25dfa1eaaaaddfd8177b1172004
22.824324
91
0.58253
4.187648
false
false
false
false
ahoppen/swift
test/Generics/opaque_archetype_concrete_requirement.swift
1
1591
// RUN: %target-swift-frontend -typecheck -verify %s -disable-availability-checking -debug-generic-signatures -enable-requirement-machine-opaque-archetypes 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-silgen %s -disable-availability-checking -enable-requirement-machine-opaque-archetypes protocol P1 { associatedtype T : P2 associatedtype U } struct S_P1 : P1 { typealias T = S_P2 typealias U = Int } protocol P2 {} struct S_P2 : P2 {} protocol P { associatedtype T var t: T { get } } struct DefinesOpaqueP1 : P { var t: some P1 { return S_P1() } } struct ConcreteHasP<T : P1, TT : P2, TU> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=ConcreteHasP // CHECK-NEXT: Generic signature: <T, TT, TU where T == some P1, TT == (some P1).T, TU == (some P1).U> extension ConcreteHasP where T == DefinesOpaqueP1.T, TT == T.T, TU == T.U { func checkSameType1(_ t: TT) -> DefinesOpaqueP1.T.T { return t } func checkSameType2(_ u: TU) -> DefinesOpaqueP1.T.U { return u } func checkSameType3(_ t: T.T) -> DefinesOpaqueP1.T.T { return t } func checkSameType4(_ u: T.U) -> DefinesOpaqueP1.T.U { return u } } struct G<T> {} protocol HasP { associatedtype T : P1 associatedtype U } // CHECK-LABEL: ExtensionDecl line={{.*}} base=HasP // CHECK-NEXT: Generic signature: <Self where Self : HasP, Self.[HasP]T == some P1, Self.[HasP]U == G<(some P1).T>> extension HasP where T == DefinesOpaqueP1.T, U == G<T.T> { func checkSameType1(_ t: T.T) -> DefinesOpaqueP1.T.T { return t } func checkSameType2(_ u: T.U) -> DefinesOpaqueP1.T.U { return u } }
apache-2.0
4d36e4c5884d43dc3689b82777df44d8
28.462963
176
0.668133
3.125737
false
false
false
false
cuappdev/tcat-ios
TCAT/Controllers/RouteDetail+DrawerViewController.swift
1
10541
// // RouteDetailViewController.swift // TCAT // // Created by Matthew Barker on 2/11/17. // Copyright © 2017 cuappdev. All rights reserved. // import FutureNova import Pulley import SwiftyJSON import UIKit struct RouteDetailCellSize { static let indentedWidth: CGFloat = 140 static let largeHeight: CGFloat = 80 static let regularWidth: CGFloat = 120 static let smallHeight: CGFloat = 60 } class RouteDetailDrawerViewController: UIViewController { struct Section { let type: SectionType var items: [RouteDetailItem] } enum SectionType { case notification case routeDetail } enum RouteDetailItem { case busStop(LocationObject) case direction(Direction) case notificationType(NotificationType) func getDirection() -> Direction? { switch self { case .direction(let direction): return direction default: return nil } } } let safeAreaCover = UIView() var summaryView: SummaryView! let tableView = UITableView(frame: .zero, style: .grouped) var currentPulleyPosition: PulleyPosition? var directionsAndVisibleStops: [RouteDetailItem] = [] var expandedDirections: Set<Direction> = [] var sections: [Section] = [] var selectedDirection: Direction? /// Number of seconds to wait before auto-refreshing bus delay network call. private var busDelayNetworkRefreshRate: Double = 10 private var busDelayNetworkTimer: Timer? private let chevronFlipDurationTime = 0.25 private let networking: Networking = URLSession.shared.request private let route: Route // MARK: - Initalization init(route: Route) { self.route = route super.init(nibName: nil, bundle: nil) summaryView = SummaryView(route: route) directionsAndVisibleStops = route.directions.map({ RouteDetailItem.direction($0) }) } required convenience init(coder aDecoder: NSCoder) { guard let route = aDecoder.decodeObject(forKey: "route") as? Route else { fatalError("init(coder:) has not been implemented") } self.init(route: route) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Colors.white setupSummaryView() setupTableView() setupSafeAreaCoverView() setupSections() if let drawer = self.parent as? RouteDetailViewController { drawer.initialDrawerPosition = .partiallyRevealed } setupConstraints() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Bus Delay Network Timer busDelayNetworkTimer?.invalidate() busDelayNetworkTimer = Timer.scheduledTimer( timeInterval: busDelayNetworkRefreshRate, target: self, selector: #selector(getDelays), userInfo: nil, repeats: true ) busDelayNetworkTimer?.fire() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) busDelayNetworkTimer?.invalidate() } private func setupSummaryView() { let summaryTapGesture = UITapGestureRecognizer(target: self, action: #selector(summaryTapped)) summaryTapGesture.delegate = self summaryView.addGestureRecognizer(summaryTapGesture) view.addSubview(summaryView) } private func setupTableView() { tableView.bounces = false tableView.estimatedRowHeight = RouteDetailCellSize.smallHeight tableView.rowHeight = UITableView.automaticDimension tableView.register(SmallDetailTableViewCell.self, forCellReuseIdentifier: Constants.Cells.smallDetailCellIdentifier) tableView.register(LargeDetailTableViewCell.self, forCellReuseIdentifier: Constants.Cells.largeDetailCellIdentifier) tableView.register(BusStopTableViewCell.self, forCellReuseIdentifier: Constants.Cells.busStopDetailCellIdentifier) tableView.register(NotificationToggleTableViewCell.self, forCellReuseIdentifier: Constants.Cells.notificationToggleCellIdentifier) tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: Constants.Footers.emptyFooterView) tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.contentInset = UIEdgeInsets(top: -34, left: 0.0, bottom: 34, right: 0.0) tableView.backgroundColor = Colors.white tableView.sectionHeaderHeight = 0 view.addSubview(tableView) } /// Creates a temporary view to cover the drawer contents when collapsed. Hidden by default. private func setupSafeAreaCoverView() { safeAreaCover.backgroundColor = Colors.backgroundWash safeAreaCover.alpha = 0 view.addSubview(safeAreaCover) } private func setupSections() { let notificationTypes = [ RouteDetailItem.notificationType(.delay), RouteDetailItem.notificationType(.beforeBoarding) ] let notificationSection = Section(type: .notification, items: notificationTypes) let routeDetailSection = Section(type: .routeDetail, items: directionsAndVisibleStops) sections = [routeDetailSection] // TODO: Uncomment when notifications are implemented on backend // if !route.isRawWalkingRoute() { // sections.append(notificationSection) // } } private func setupConstraints() { summaryView.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview() } tableView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() make.top.equalTo(summaryView.snp.bottom) } safeAreaCover.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() make.top.equalTo(summaryView.snp.bottom) } } /// Fetch delay information and update table view cells. @objc private func getDelays() { // First depart direction(s) guard let delayDirection = route.getFirstDepartRawDirection() else { return // Use rawDirection (preserves first stop metadata) } let directions = directionsAndVisibleStops.compactMap { $0.getDirection() } let firstDepartDirection = directions.first(where: { $0.type == .depart })! directions.forEach { $0.delay = nil } if let tripId = delayDirection.tripIdentifiers?.first, let stopId = delayDirection.stops.first?.id { getDelay(tripId: tripId, stopId: stopId).observe(with: { [weak self] result in guard let self = self else { return } DispatchQueue.main.async { switch result { case .value(let response): if response.success { delayDirection.delay = response.data firstDepartDirection.delay = response.data // Update delay variable of other ensuing directions directions.filter { let isAfter = directions.firstIndex(of: firstDepartDirection)! < directions.firstIndex(of: $0)! return isAfter && $0.type != .depart }.forEach { direction in if direction.delay != nil { direction.delay! += delayDirection.delay ?? 0 } else { direction.delay = delayDirection.delay } } self.tableView.reloadData() self.summaryView.updateTimes(for: self.route) } else { self.printClass(context: "\(#function) success", message: "false") let payload = NetworkErrorPayload( location: "\(self) Get Delay", type: "Response Failure", description: "Response Failure") Analytics.shared.log(payload) } case .error(let error): self.printClass(context: "\(#function) error", message: error.localizedDescription) let payload = NetworkErrorPayload( location: "\(self) Get Delay", type: "\((error as NSError).domain)", description: error.localizedDescription) Analytics.shared.log(payload) } } }) } } private func getDelay(tripId: String, stopId: String) -> Future<Response<Int?>> { return networking(Endpoint.getDelay(tripID: tripId, stopID: stopId)).decode() } func getFirstDirection() -> Direction? { return route.directions.first(where: { $0.type == .depart }) } /// Toggle the cell expansion at the indexPath func toggleCellExpansion(for cell: LargeDetailTableViewCell) { guard let indexPath = tableView.indexPath(for: cell), let direction = sections[indexPath.section].items[indexPath.row].getDirection() else { return } // Prepare bus stop data to be inserted / deleted into Directions array let busStops = direction.stops.map { return RouteDetailItem.busStop($0) } let busStopRange = (indexPath.row + 1)..<((indexPath.row + 1) + busStops.count) let indexPathArray = busStopRange.map { return IndexPath(row: $0, section: 0) } tableView.beginUpdates() // Insert or remove bus stop data based on selection if expandedDirections.contains(direction) { expandedDirections.remove(direction) sections[indexPath.section].items.removeSubrange(busStopRange) tableView.deleteRows(at: indexPathArray, with: .middle) } else { expandedDirections.insert(direction) sections[indexPath.section].items.insert(contentsOf: busStops, at: indexPath.row + 1) tableView.insertRows(at: indexPathArray, with: .middle) } tableView.endUpdates() } }
mit
8ff734a2ce07dcf51a5535d3252677be
36.913669
138
0.618216
5.383044
false
false
false
false
howardhsien/EasyTaipei-iOS
EasyTaipei/EasyTaipei/controller/MRTViewController.swift
1
4342
// // MRTViewController.swift // EasyTaipei // // Created by howard hsien on 2016/7/5. // Copyright © 2016年 AppWorks School Hsien. All rights reserved. // import UIKit class MRTViewController: UIViewController,UIScrollViewDelegate { //ScrollView image viewer lazy var scrollView:UIScrollView = { let sv = UIScrollView(frame: self.view.bounds) sv.delegate = self return sv }() lazy var imageView:UIImageView = { if let image = UIImage(named: "mrtMap"){ let imgView = UIImageView(image: image) let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height if let tabHeight = self.tabBarController?.tabBar.frame.height, navHeight = self.navigationController?.navigationBar.frame.height { imgView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height - tabHeight - navHeight - statusBarHeight) } else{ imgView.frame = self.view.frame } imgView.contentMode = .ScaleToFill return imgView } else{ return UIImageView() } }() //MARK: LifeCycle override func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) setupScrollView() setZoomScale() setupGestureRecognizer() } //MARK: ScrollView private func setupScrollView(){ scrollView.addSubview(imageView) scrollView.maximumZoomScale = 4.0 scrollView.minimumZoomScale = 1.0 scrollView.contentSize = imageView.frame.size } //handle the zooming private func setZoomScale() { let imageViewSize = imageView.bounds.size let scrollViewSize = scrollView.bounds.size let widthScale = scrollViewSize.width / imageViewSize.width let heightScale = scrollViewSize.height / imageViewSize.height scrollView.minimumZoomScale = min(widthScale, heightScale) scrollView.zoomScale = 1.0 } private func setupGestureRecognizer() { let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)) doubleTap.numberOfTapsRequired = 2 scrollView.addGestureRecognizer(doubleTap) } @objc private func handleDoubleTap(recognizer: UITapGestureRecognizer) { let tapPoint = recognizer.locationInView(view) let preferedTapZoomScale:CGFloat = 3.0 if (scrollView.zoomScale > scrollView.minimumZoomScale) { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true) } else { scrollView.zoomToPoint(tapPoint, withScale: preferedTapZoomScale, animated: true) // scrollView.setZoomScale(preferedTapZoomScale, animated: true) } } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } } extension UIScrollView { func zoomToPoint( zoomPoint: CGPoint, withScale scale:CGFloat, animated :Bool) { //Normalize current content size back to content scale of 1.0f var contentSize = CGSize() contentSize.width = (self.contentSize.width / self.zoomScale); contentSize.height = (self.contentSize.height / self.zoomScale); var zoomToPoint = CGPoint() //translate the zoom point to relative to the content rect zoomToPoint.x = (zoomPoint.x / self.bounds.size.width) * contentSize.width; zoomToPoint.y = (zoomPoint.y / self.bounds.size.height) * contentSize.height; //derive the size of the region to zoom to var zoomSize = CGSize(); zoomSize.width = self.bounds.size.width / scale; zoomSize.height = self.bounds.size.height / scale; //offset the zoom rect so the actual zoom point is in the middle of the rectangle var zoomRect = CGRect(); zoomRect.origin.x = zoomPoint.x - zoomSize.width / 2.0; zoomRect.origin.y = zoomPoint.y - zoomSize.height / 2.0; zoomRect.size.width = zoomSize.width; zoomRect.size.height = zoomSize.height; //apply the resize zoomToRect(zoomRect, animated: animated) } }
mit
f7df2ff6dc24ea10308ad4a4fd4272b2
33.436508
138
0.636322
5.063011
false
false
false
false
darkerk/v2ex
V2EX/ViewControllers/LoginViewController.swift
1
10225
// // LoginViewController.swift // V2EX // // Created by darker on 2017/3/3. // Copyright © 2017年 darker. All rights reserved. // import UIKit import RxSwift import RxCocoa import PKHUD import OnePasswordExtension class LoginViewController: UIViewController { @IBOutlet weak var loginButton: LoginButton! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var googleButton: LoginButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var sublitLabel: UILabel! @IBOutlet weak var line1View: UIImageView! @IBOutlet weak var line2View: UIImageView! @IBOutlet weak var line3View: UIImageView! @IBOutlet weak var captchaView: UIImageView! @IBOutlet weak var verifcodeTextField: UITextField! var viewModel: LoginViewModel = LoginViewModel() private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() if AppStyle.shared.theme == .night { view.backgroundColor = AppStyle.shared.theme.cellBackgroundColor cancelButton.setImage(#imageLiteral(resourceName: "cancel_X").imageWithTintColor(#colorLiteral(red: 0.1137254902, green: 0.631372549, blue: 0.9490196078, alpha: 1)), for: .normal) titleLabel.textColor = UIColor.white sublitLabel.textColor = UIColor.white let lineImage = #imageLiteral(resourceName: "line").imageWithTintColor(UIColor.black) line1View.image = lineImage line2View.image = lineImage line3View.image = lineImage let attributes = [NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.4196078431, green: 0.4901960784, blue: 0.5490196078, alpha: 1)] usernameTextField.attributedPlaceholder = NSAttributedString(string: "用户名或邮箱", attributes: attributes) passwordTextField.attributedPlaceholder = NSAttributedString(string: "密码", attributes: attributes) verifcodeTextField.attributedPlaceholder = NSAttributedString(string: "请输入下图中的验证码", attributes: attributes) usernameTextField.textColor = #colorLiteral(red: 0.6078431373, green: 0.6862745098, blue: 0.8, alpha: 1) passwordTextField.textColor = #colorLiteral(red: 0.6078431373, green: 0.6862745098, blue: 0.8, alpha: 1) verifcodeTextField.textColor = #colorLiteral(red: 0.6078431373, green: 0.6862745098, blue: 0.8, alpha: 1) loginButton.backgroundColor = #colorLiteral(red: 0.1411764706, green: 0.2039215686, blue: 0.2784313725, alpha: 1) loginButton.layer.borderColor = #colorLiteral(red: 0.1411764706, green: 0.2039215686, blue: 0.2784313725, alpha: 1).cgColor loginButton.setTitleColor(UIColor.white, for: .normal) loginButton.setTitleColor(#colorLiteral(red: 0.6078431373, green: 0.6862745098, blue: 0.8, alpha: 1), for: .disabled) usernameTextField.keyboardAppearance = .dark passwordTextField.keyboardAppearance = .dark verifcodeTextField.keyboardAppearance = .dark } if OnePasswordExtension.shared().isAppExtensionAvailable() { let bundlePath = Bundle(for: OnePasswordExtension.self).path(forResource: "OnePasswordExtensionResources", ofType: "bundle") let image = UIImage(named: AppStyle.shared.theme == .night ? "onepassword-button-light" : "onepassword-button", in: Bundle(path: bundlePath!), compatibleWith: nil) let button = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) button.setImage(image, for: .normal) button.addTarget(self, action: #selector(findLoginFrom1Password(_:)), for: .touchUpInside) passwordTextField.rightViewMode = .always passwordTextField.rightView = button } let usernameValid = usernameTextField.rx.text.orEmpty.map({$0.isEmpty == false}).share(replay: 1) let passwordValid = passwordTextField.rx.text.orEmpty.map({$0.isEmpty == false}).share(replay: 1) // let codeValid = verifcodeTextField.rx.text.orEmpty.map({$0.isEmpty == false}).shareReplay(1) let allValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }.share(replay: 1) allValid.bind(to: loginButton.rx.isEnabled).disposed(by: disposeBag) usernameTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: {[weak self] in self?.passwordTextField.becomeFirstResponder() }).disposed(by: disposeBag) passwordTextField.rx.controlEvent(.editingDidEndOnExit).subscribe().disposed(by: disposeBag) verifcodeTextField.rx.controlEvent(.editingDidEndOnExit).subscribe().disposed(by: disposeBag) viewModel.activityIndicator.asObservable().bind(to: PKHUD.sharedHUD.rx.isAnimating).disposed(by: disposeBag) viewModel.fetchCaptchaImage().asObservable().bind(to: captchaView.rx.image).disposed(by: disposeBag) } @objc func findLoginFrom1Password(_ sender: Any) { view.endEditing(true) OnePasswordExtension.shared().findLogin(forURLString: "www.v2ex.com", for: self, sender: sender) { (result, error) in if let result = result as? [String: String], let username = result[AppExtensionUsernameKey], let password = result[AppExtensionPasswordKey] { self.usernameTextField.text = username self.passwordTextField.text = password self.loginButton.isEnabled = true self.loginButton.sendActions(for: .touchUpInside) } } } func showTwoStepVerify() { let alert = UIAlertController(title: "两步验证登录", message: "你的 V2EX 账号已经开启了两步验证,请输入验证码继续", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) let action = UIAlertAction(title: "登录", style: .default, handler: {_ in let code = alert.textFields?.first?.text ?? "" self.viewModel.twoStepVerifyLogin(code: code).asObservable().subscribe(onNext: {[weak self] resp in let result = HTMLParser.shared.twoStepVerifyResult(html: resp.data) if let user = result.user { Account.shared.user.value = user Account.shared.isLoggedIn.value = true self?.dismiss(animated: true, completion: nil) }else { self?.showTwoStepVerify() DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { let errorMsg = result.problem ?? "验证失败,请重新输入验证码" HUD.showText(errorMsg) }) } }, onError: {[weak self] error in HUD.showText(error.message) self?.showTwoStepVerify() }).disposed(by: self.disposeBag) }) alert.addTextField { textField in textField.keyboardType = .numberPad textField.placeholder = "验证码" textField.rx.text.orEmpty.map({$0.isEmpty == false}).share(replay: 1).bind(to: action.rx.isEnabled).disposed(by: self.disposeBag) } alert.addAction(action) present(alert, animated: true, completion: nil) } @IBAction func loginButtonAction(_ sender: Any) { guard let username = usernameTextField.text, let password = passwordTextField.text, let code = verifcodeTextField.text else { return } viewModel.loginRequest(username: username, password: password, code: code).subscribe(onNext: {[weak self] response in let result = HTMLParser.shared.loginResult(html: response.data) if result.isTwoStepVerification { self?.showTwoStepVerify() return } if let user = result.user { Account.shared.user.value = user Account.shared.isLoggedIn.value = true self?.dismiss(animated: true, completion: nil) }else { DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { let errorMsg = result.problem ?? "登录失败,请稍后再试" HUD.showText(errorMsg) }) } }, onError: {error in HUD.showText(error.message) }).disposed(by: disposeBag) } @IBAction func googleLoginAction(_ sender: Any) { view.endEditing(true) } @IBAction func cancelButtonAction(_ sender: Any) { view.endEditing(true) dismiss(animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) view.endEditing(true) } override var preferredStatusBarStyle: UIStatusBarStyle { switch AppStyle.shared.theme { case .normal: return .default case .night: return .lightContent } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /** extension LoginViewController: GIDSignInUIDelegate { func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) { } func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) { present(viewController, animated: true, completion: nil) } func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) { dismiss(animated: true, completion: nil) } } **/
mit
053ef7e50250e73596cd6c8a81bba81f
44.36036
191
0.631877
4.876513
false
false
false
false
barijaona/vienna-rss
Vienna/Sources/Main window/OverlayStatusBar.swift
1
14194
// // OverlayStatusBar.swift // Vienna // // Copyright 2017-2018 // // 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 // // https://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 Cocoa /// An overlay status bar can show context-specific information above a view. /// It is supposed to be a subview of another view. Once added, it will set its /// own frame and constraints. Removing the status bar from its superview will /// unwind the constraints. /// /// Setting or unsetting the `label` property will show or hide the status bar /// accordingly. It will not hide by itself. final class OverlayStatusBar: NSView { // MARK: Subviews private var backgroundView: NSVisualEffectView = { let backgroundView = NSVisualEffectView(frame: .zero) backgroundView.wantsLayer = true backgroundView.blendingMode = .withinWindow backgroundView.material = .menu backgroundView.alphaValue = 0 backgroundView.layer?.cornerRadius = 3 return backgroundView }() private var addressField: NSTextField = { let addressField = NSTextField(labelWithString: "") addressField.font = .systemFont(ofSize: 12, weight: .medium) addressField.textColor = .overlayStatusBarPrimaryLabelColor addressField.lineBreakMode = .byTruncatingMiddle addressField.allowsDefaultTighteningForTruncation = true return addressField }() // MARK: Initialization init() { super.init(frame: NSRect(x: 0, y: 0, width: 4_800, height: 26)) // Make sure that no other constraints are created. translatesAutoresizingMaskIntoConstraints = false backgroundView.translatesAutoresizingMaskIntoConstraints = false addressField.translatesAutoresizingMaskIntoConstraints = false // The text field should always be among the first views to shrink. addressField.setContentHuggingPriority(.defaultHigh, for: .horizontal) addressField.setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal) addSubview(backgroundView) backgroundView.addSubview(addressField) // Set the constraints. var backgroundViewConstraints: [NSLayoutConstraint] = [] backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-3-[view]-3-|", metrics: nil, views: ["view": backgroundView]) backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-3-[view]-3-|", metrics: nil, views: ["view": backgroundView]) var addressFieldConstraints: [NSLayoutConstraint] = [] addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-1@250-[label]-3@250-|", options: .alignAllCenterY, metrics: nil, views: ["label": addressField]) addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-6-[label]-6-|", metrics: nil, views: ["label": addressField]) NSLayoutConstraint.activate(backgroundViewConstraints) NSLayoutConstraint.activate(addressFieldConstraints) } // Make this initialiser unavailable. override private convenience init(frame frameRect: NSRect) { self.init() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: Setting the view hierarchy // When the status bar is added to the view hierarchy of another view, // perform additional setup, such as setting the constraints and creating // a tracking area for mouse movements. override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() guard let superview = superview else { return } // Layer-backing will make sure that the visual-effect view redraws. superview.wantsLayer = true var baseContraints: [NSLayoutConstraint] = [] baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|->=0-[view]-0-|", options: [], metrics: nil, views: ["view": self]) baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|->=0-[view]->=0-|", options: [], metrics: nil, views: ["view": self]) NSLayoutConstraint.activate(baseContraints) // Pin the view to the left side. pin(to: .leadingEdge, of: superview) startTrackingMouse(on: superview) } // If the status bar is removed from the view hierarchy, then the tracking // area must be removed too. override func viewWillMove(toSuperview newSuperview: NSView?) { if let superview = superview { stopTrackingMouse(on: superview) isShown = false position = nil } } // MARK: Pinning the status bar private enum Position { case leadingEdge, trailingEdge } private var position: Position? private lazy var leadingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options: [], metrics: nil, views: ["view": self]) private lazy var trailingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-0-|", options: [], metrics: nil, views: ["view": self]) // The status bar is pinned simply by setting and unsetting constraints. private func pin(to position: Position, of positioningView: NSView) { guard position != self.position else { return } let oldConstraints: [NSLayoutConstraint] let newConstraints: [NSLayoutConstraint] switch position { case .leadingEdge: oldConstraints = trailingConstraints newConstraints = leadingConstraints case .trailingEdge: oldConstraints = leadingConstraints newConstraints = trailingConstraints } // Remove existing constraints. NSLayoutConstraint.deactivate(oldConstraints) // Add new constraints. NSLayoutConstraint.activate(newConstraints) self.position = position } // MARK: Handling status updates private lazy var formatter: URLFormatter = { let urlFormatter = URLFormatter() // Set the default attributes. This should match addressField. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byTruncatingMiddle paragraphStyle.allowsDefaultTighteningForTruncation = true urlFormatter.defaultAttributes = [ .font: NSFont.systemFont(ofSize: 12, weight: .medium), .paragraphStyle: paragraphStyle, .foregroundColor: NSColor.overlayStatusBarPrimaryLabelColor ] urlFormatter.primaryAttributes = [ .font: NSFont.systemFont(ofSize: 12, weight: .medium), .foregroundColor: NSColor.overlayStatusBarPrimaryLabelColor ] urlFormatter.secondaryAttributes = [ .font: NSFont.systemFont(ofSize: 12, weight: .regular), .foregroundColor: NSColor.overlayStatusBarSecondaryLabelColor ] return urlFormatter }() /// The label to show. Setting this property will show or hide the status /// bar. It will remain visible until the label is set to `nil`. @objc var label: String? { didSet { // This closure is meant to be called very often. It should not // cause any expensive computations. if let label = label, !label.isEmpty { // URLs can have special formatting with an attributed string. if let url = URL(string: label) { let attrString = formatter.attributedString(from: url) if attrString != addressField.attributedStringValue { addressField.attributedStringValue = attrString } } else if label != addressField.stringValue { addressField.stringValue = label } isShown = true } else { isShown = false } } } private var isShown = false { didSet { guard isShown != oldValue else { return } NSAnimationContext.runAnimationGroup({ context in context.duration = 0.4 backgroundView.animator().alphaValue = isShown ? 1 : 0 }, completionHandler: nil) } } // MARK: Setting up mouse tracking private var trackingArea: NSTrackingArea? private func startTrackingMouse(on trackingView: NSView) { if let trackingArea = self.trackingArea, trackingView.trackingAreas.contains(trackingArea) { return } let rect = trackingView.bounds let size = CGSize(width: rect.maxX, height: frame.height + 15) let origin = CGPoint(x: rect.minX, y: rect.minY) let trackingArea = NSTrackingArea(rect: NSRect(origin: origin, size: size), options: [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow], owner: self, userInfo: nil) self.trackingArea = trackingArea trackingView.addTrackingArea(trackingArea) } // Remove the tracking area and unset the reference. private func stopTrackingMouse(on trackingView: NSView) { if let trackingArea = trackingArea { trackingView.removeTrackingArea(trackingArea) self.trackingArea = nil } } // This method is called often, thus only change the tracking area when // the superview's bounds width and the tracking area's width do not match. override func updateTrackingAreas() { super.updateTrackingAreas() guard let superview = superview, let trackingArea = trackingArea else { return } if superview.trackingAreas.contains(trackingArea), trackingArea.rect.width != superview.bounds.width { stopTrackingMouse(on: superview) startTrackingMouse(on: superview) } } // MARK: Responding to mouse movement private var widthConstraint: NSLayoutConstraint? // Once the mouse enters the tracking area, the width of the status bar // should shrink. This is done by adding a width constraint. override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) guard let superview = superview, event.trackingArea == trackingArea else { return } // Add the width constraint, if not already added. if widthConstraint == nil { let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: superview.bounds.midX - 8) self.widthConstraint = widthConstraint widthConstraint.isActive = true } } // Pin the status bar to the side, opposite of the mouse's position. override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) guard let superview = superview else { return } // Map the mouse location to the superview's bounds. let point = superview.convert(event.locationInWindow, from: nil) if point.x <= superview.bounds.midX { pin(to: .trailingEdge, of: superview) } else { pin(to: .leadingEdge, of: superview) } } // Once the mouse exits the tracking area, the status bar's intrinsic width // should be restored, by removing the width constraint and pinning the view // back to the left side. override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) guard let superview = superview, event.trackingArea == trackingArea else { return } pin(to: .leadingEdge, of: superview) if let constraint = widthConstraint { removeConstraint(constraint) // Delete the constraint to make sure that a new one is created, // appropriate for the superview size (which may change). widthConstraint = nil } } } private extension NSColor { class var overlayStatusBarPrimaryLabelColor: NSColor { if #available(macOS 10.13, *) { return NSColor(named: "OverlayStatusBarPrimaryTextColor")! } else { if NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast { return .black.withAlphaComponent(0.85) } else { return .black.withAlphaComponent(0.70) } } } class var overlayStatusBarSecondaryLabelColor: NSColor { if #available(macOS 10.13, *) { return NSColor(named: "OverlayStatusBarSecondaryTextColor")! } else { if NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast { return .black.withAlphaComponent(0.70) } else { return .black.withAlphaComponent(0.55) } } } }
apache-2.0
3410f4b5d827a7335f15c333434107f4
36.951872
157
0.62146
5.605845
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/PalaciosArlette/Ejercicio15.swift
1
1847
/* Palacios Lee Arlette 12211431 Programa para resolver el siguiente problema: 15. Leer las logitudes de los catetos de un triángulo rectángulo. Calcular e imprimir los valores de las seis funciones trigonométricas de cualquiera de los ángulos agudos del triángulo. */ //Librería para utilizar funciones trigonométricas import Foundation //Declaración de variables var hipotenusa: Float = 15 //Tamaño de uno de los lados var catetoAd: Float = 12 //Mitad del tamaño del lado más largo de triángulo var catetoOp: Float = 9 //Operaciones para calcular las fuciones trigonométricas var seno = catetoOp/hipotenusa //Cálculo de seno del ángulo var coseno = catetoAd/hipotenusa //Cálculo de seno del ángulo var tangente = catetoOp/catetoAd //Cálculo de seno del ángulo var cotangente = catetoAd/catetoOp //Cálculo de seno del ángulo var cosecante = hipotenusa/catetoOp //Cálculo de seno del ángulo var secante = hipotenusa/catetoAd //Cálculo de seno del ángulo //En una variable se guarda el problema y datos para imprimirlos posteriormente var Problema = "\n" + "Problema:" + "\n" + "15. Leer las logitudes de los catetos de un triángulo rectángulo. Calcular e imprimir los valores de las seis funciones trigonométricas de cualquiera de los ángulos agudos del triángulo." var Datos = "\n \n" + "Datos:" + "\n" + "Hipotenusa: \(String(format:"%.0f", hipotenusa))cm " + "\n" + "Cateto Adyacente: \(String(format:"%.0f", catetoAd))cm" + "\n" + "Cateto Opuesto: \(String(format:"%.0f", catetoOp))cm" var Resultado = "\n \n" + "Resultado:" + "\n" + "Seno: \(seno)" + "\n" + "Coseno: \(coseno)" + "\n" + "Tangente: \(tangente)" + "\n" + "Cotangente: \(cotangente)" + "\n" + "Secante: \(secante)" + "\n" + "Cosecante: \(cosecante)" //Despliegue de resultados print(Problema, Datos, Resultado);
gpl-3.0
53c11c0bd980d74e54c8fd1e2a7c88d7
54.060606
229
0.717116
3.127367
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/AnchorViewController/View/AnchorSignerCell.swift
1
5257
// // AnchorSignerCellCell.swift // XMLYDemo // // Created by xiudou on 2016/12/28. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit private let iconImageHW : CGFloat = 50 class AnchorSignerCell: UICollectionViewCell { /// 头像 fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() // iconImageView.layer.borderWidth = 1 // iconImageView.layer.borderColor = UIColor.gray.cgColor iconImageView.layer.cornerRadius = iconImageHW * 0.5 iconImageView.clipsToBounds = true return iconImageView }() fileprivate lazy var nameLabel : UILabel = { let nameLabel = UILabel() nameLabel.textAlignment = .center nameLabel.font = UIFont.systemFont(ofSize: 12) nameLabel.textColor = UIColor.orange.withAlphaComponent(0.7) return nameLabel }() fileprivate lazy var musicLabel : UILabel = { let musicLabel = UILabel() musicLabel.font = UIFont.systemFont(ofSize: 12) return musicLabel }() // 足迹 fileprivate lazy var tracksCountsButton : UIButton = { let tracksCountsButton = UIButton() tracksCountsButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) tracksCountsButton.setTitleColor(UIColor.gray, for: .normal) return tracksCountsButton }() /// 粉丝数 fileprivate lazy var followersCountsButton : UIButton = { let followersCountsButton = UIButton() followersCountsButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) followersCountsButton.setTitleColor(UIColor.gray, for: .normal) return followersCountsButton }() /// 关注 fileprivate lazy var attentionButton : UIButton = { let attentionButton = UIButton() attentionButton.backgroundColor = UIColor.red attentionButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) attentionButton.setTitleColor(UIColor.orange, for: .normal) return attentionButton }() fileprivate lazy var lineView : UIView = { let lineView = UIView() lineView.backgroundColor = UIColor(r: 230, g: 230, b: 230, alpha: 0.8) return lineView }() var singerModel : AnchorSectionList?{ didSet{ guard let singerModel = singerModel else { return } iconImageView.sd_setImage(with: URL(string: singerModel.largeLogo ), placeholderImage: UIImage(named: "find_radio_default")) nameLabel.text = singerModel.nickname musicLabel.text = singerModel.verifyTitle tracksCountsButton.setTitle("\(singerModel.tracksCounts)", for: .normal) followersCountsButton.setTitle(setupfollowNumber(singerModel.followersCounts), for: .normal) } } override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = .white contentView.addSubview(iconImageView) contentView.addSubview(nameLabel) contentView.addSubview(musicLabel) contentView.addSubview(tracksCountsButton) contentView.addSubview(followersCountsButton) contentView.addSubview(attentionButton) contentView.addSubview(lineView) setupFrame() } fileprivate func setupFrame() { iconImageView.snp.makeConstraints { (make) in make.width.height.equalTo(iconImageHW) make.centerY.equalTo(contentView) make.left.equalTo(contentView).offset(10) } nameLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView.snp.right).offset(10) make.top.equalTo(iconImageView).offset(-5) } musicLabel.snp.makeConstraints { (make) in make.left.equalTo(nameLabel) make.centerY.equalTo(contentView) } tracksCountsButton.snp.makeConstraints { (make) in make.left.equalTo(nameLabel) make.bottom.equalTo(iconImageView.snp.bottom).offset(5) } followersCountsButton.snp.makeConstraints { (make) in make.left.equalTo(tracksCountsButton.snp.right).offset(10) make.top.equalTo(tracksCountsButton) } attentionButton.snp.makeConstraints { (make) in make.centerY.equalTo(contentView) make.right.equalTo(contentView).offset(-10) } lineView.snp.makeConstraints { (make) in make.left.equalTo(nameLabel) make.right.equalTo(contentView) make.height.equalTo(0.5) make.bottom.equalTo(contentView) } } fileprivate func setupfollowNumber(_ count : Int64) ->String{ if count > 10000{ let countString = String(format:"%.2f万",count / 10000) return countString }else{ return "\(count)" } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ece8bb2d1096dbb27e5b35def4f86a90
31.7125
136
0.61559
5.202783
false
false
false
false
skela/SwiftyDropbox
Source/SwiftyDropbox/Platform/SwiftyDropbox_macOS/OAuthDesktop.swift
1
3150
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Foundation import AppKit import WebKit extension DropboxClientsManager { public static func authorizeFromController(sharedWorkspace: NSWorkspace, controller: NSViewController?, openURL: @escaping ((URL) -> Void)) { precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` before calling this method") DropboxOAuthManager.sharedOAuthManager.authorizeFromSharedApplication(DesktopSharedApplication(sharedWorkspace: sharedWorkspace, controller: controller, openURL: openURL)) } public static func setupWithAppKeyDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManager(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithAppKeyMultiUserDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUser(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } public static func setupWithTeamAppKeyDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManagerTeam(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithTeamAppKeyMultiUserDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUserTeam(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } } public class DesktopSharedApplication: SharedApplication { let sharedWorkspace: NSWorkspace let controller: NSViewController? let openURL: ((URL) -> Void) public init(sharedWorkspace: NSWorkspace, controller: NSViewController?, openURL: @escaping ((URL) -> Void)) { self.sharedWorkspace = sharedWorkspace self.controller = controller self.openURL = openURL } public func presentErrorMessage(_ message: String, title: String) { let error = NSError(domain: "", code: 123, userInfo: [NSLocalizedDescriptionKey:message]) if let controller = self.controller { controller.presentError(error) } } public func presentErrorMessageWithHandlers(_ message: String, title: String, buttonHandlers: Dictionary<String, () -> Void>) { presentErrorMessage(message, title: title) } // no platform-specific auth methods for OS X public func presentPlatformSpecificAuth(_ authURL: URL) -> Bool { return false } public func presentAuthChannel(_ authURL: URL, tryIntercept: @escaping ((URL) -> Bool), cancelHandler: @escaping (() -> Void)) { self.presentExternalApp(authURL) } public func presentExternalApp(_ url: URL) { self.openURL(url) } public func canPresentExternalApp(_ url: URL) -> Bool { return true } }
mit
9fab57b814f30a1faf56359db60b95c9
43.366197
189
0.737143
5.241265
false
false
false
false
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/conversion/video/LGVideoController.swift
1
4418
// // LGVideoController.swift // LGWeChatKit // // Created by jamy on 11/4/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import AVFoundation class LGVideoController: UIViewController { var totalTimer: String! var playItem: AVPlayerItem! var playView: LGAVPlayView! var timerObserver: AnyObject? init() { super.init(nibName: nil, bundle: nil) playView = LGAVPlayView(frame: view.bounds) view.addSubview(playView) playView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapView:")) } func tapView(gesture: UITapGestureRecognizer) { removeConfigure() dismissViewControllerAnimated(true) { () -> Void in } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { removeConfigure() } func removeConfigure() { NSNotificationCenter.defaultCenter().removeObserver(self) playItem.removeObserver(self, forKeyPath: "status", context: nil) if let observer = timerObserver { let layer = playView.layer as! AVPlayerLayer layer.player?.removeTimeObserver(observer) } playView.removeFromSuperview() playView = nil } // MARK: - 初始化配置 func setPlayUrl(url: NSURL) { playItem = AVPlayerItem(URL: url) configurationItem() } func setPlayAsset(asset: AVAsset) { playItem = AVPlayerItem(asset: asset) configurationItem() } func configurationItem() { let play = AVPlayer(playerItem: playItem) let layer = playView.layer as! AVPlayerLayer layer.player = play playItem.addObserver(self, forKeyPath: "status", options: .New, context: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoPlayDidEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "status" { if playItem.status == .ReadyToPlay { let dutation = playItem.duration let totalSecond = CGFloat(playItem.duration.value) / CGFloat(playItem.duration.timescale) totalTimer = converTimer(totalSecond) configureSlider(dutation) monitoringPlayback(self.playItem) let layer = playView.layer as! AVPlayerLayer layer.player?.play() } } } func videoPlayDidEnd(notifation: NSNotification) { playItem.seekToTime(CMTimeMake(0, 1)) let layer = playView.layer as! AVPlayerLayer layer.player?.play() } // MARK: operation func converTimer(time: CGFloat) -> String { let date = NSDate(timeIntervalSince1970: Double(time)) let dateFormat = NSDateFormatter() if time / 3600 >= 1 { dateFormat.dateFormat = "HH:mm:ss" } else { dateFormat.dateFormat = "mm:ss" } let formatTime = dateFormat.stringFromDate(date) return formatTime } func configureSlider(duration: CMTime) { playView.slider.maximumValue = Float(CMTimeGetSeconds(duration)) } func monitoringPlayback(item: AVPlayerItem) { let layer = playView.layer as! AVPlayerLayer timerObserver = layer.player!.addPeriodicTimeObserverForInterval(CMTimeMake(1, 1), queue: nil, usingBlock: { (time) -> Void in let currentSecond = item.currentTime().value / Int64(item.currentTime().timescale) self.playView.slider.setValue(Float(currentSecond), animated: true) let timeStr = self.converTimer(CGFloat(currentSecond)) self.playView.timerIndicator.text = "\(timeStr)/\(self.totalTimer)" }) } }
mit
4d9edf4c9f8a83f4c83335db511d697a
31.404412
157
0.626503
5.00227
false
true
false
false
austinzheng/swift
validation-test/compiler_crashers_fixed/01534-bool.swift
65
849
// 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 class a<U) { b: b: a { init <f = Swift.Element == true } protocol C = g<D>() { let x } return { x { } } self.endIndex - range.Iterator.init() { struct c = Swift.c : Any) -> { func g(a<T.B>(T)) { func i: A, U) { func b() { class a { } func a<1 { } e where B : T>() { class a { } } } } } struct c { } class a<d: b: k) { } var b<T> { } func f<T : U : X<d = i<T { } class B { typealias d>, d>() { } } } deinit { struct A : NSObject { } } var b(c() -> Int
apache-2.0
3e79c718c9b02182ab0252525a990c5b
15.98
79
0.617197
2.686709
false
false
false
false
ArthurXHK/AXRegex
Example/AXRegex/ViewController.swift
1
3212
// // ViewController.swift // AXRegex // // Created by Arthur XU on 10/15/2015. // Copyright (c) 2015 Arthur XU. All rights reserved. // import UIKit import AXRegex class ViewController: UIViewController, UITextViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDataSource { // MARK: - Variable - @IBOutlet weak var textView: UITextView! @IBOutlet weak var regexPicker: UIPickerView! @IBOutlet weak var resultTable: UITableView! var regexResult: RegexResult? var regexPattern: String = RegexPattern.HtmlTag // MARK: - Life Cycle - override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.refreshResult() } // MARK: - Private Methods - func refreshResult() { self.regexResult = textView.text =~ regexPattern resultTable.reloadData() if let row = self.regexResult?.matches.count where row>0 { resultTable.scrollToRowAtIndexPath(NSIndexPath(forRow: row-1, inSection: 0), atScrollPosition: .None, animated: true) } } // MARK: - Delegate - // MARK: UITextViewDelegate func textViewDidChange(textView: UITextView) { self.refreshResult() } // MARK: UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 6 } // MARK: UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { var title: String switch row { case 0: title = "Html Tag" case 1: title = "Email" case 2: title = "IP Address" case 3: title = "WebSite" case 4: title = "Number" case 5: title = "Chinese" default: title = "" } return title } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch row { case 0: regexPattern = RegexPattern.HtmlTag case 1: regexPattern = RegexPattern.Email case 2: regexPattern = RegexPattern.IPAddress case 3: regexPattern = RegexPattern.WebSite case 4: regexPattern = RegexPattern.Number case 5: regexPattern = RegexPattern.Chinese default: regexPattern = "" } self.refreshResult() } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let result = regexResult else {return 0} return result.matches.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") if let match=regexResult?.matches[indexPath.row], label=cell.textLabel { label.text = match.content } return cell } }
apache-2.0
929e849f2d8c5edd8d60701139e575ca
29.884615
129
0.617061
5.058268
false
false
false
false
lelandjansen/fatigue
ios/fatigue/NameSettingController.swift
1
2171
import UIKit class NameSettingController: UITableViewController, UITextFieldDelegate { weak var delegate: SettingsDelegate? enum CellId: String { case nameCell } init() { super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NameSetting.settingName view.backgroundColor = .light nameTextField.delegate = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() nameTextField.becomeFirstResponder() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } let nameTextField: UITextField = { let textField = UITextField() textField.font = .systemFont(ofSize: 17) textField.backgroundColor = .clear textField.textColor = .dark textField.autocapitalizationType = .words textField.clearButtonMode = .whileEditing textField.returnKeyType = .done textField.placeholder = "Your name" textField.text = UserDefaults.standard.name return textField }() override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: CellId.nameCell.rawValue) cell.selectionStyle = .none cell.contentView.addSubview(nameTextField) cell.backgroundColor = .clear nameTextField.anchor(toCell: cell) return cell } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let name = nameTextField.text?.trimmingCharacters(in: .whitespaces) UserDefaults.standard.name = name delegate?.setSelectedCellDetails(toValue: name!) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { navigationController?.popViewController(animated: true) return false } }
apache-2.0
d757e3db20073d17e7306e1255c9b255
29.152778
109
0.650392
5.624352
false
false
false
false
anisimovsergey/lumino-ios
Lumino/DevicesTableViewController.swift
1
6491
// // DevicesTableViewController.swift // Lumino // // Created by Sergey Anisimov on 19/12/2016. // Copyright © 2016 Sergey Anisimov. All rights reserved. // import UIKit import MulticastDelegateSwift class DevicesTableViewController: UITableViewController, NetServiceBrowserDelegate, WebSocketConnectionDelegate, WebSocketCommunicationDelegate { private var nsb: NetServiceBrowser! private var nsbSearchTimer: Timer! private var serializer: SerializationService! private var clients: Dictionary<String, DeviceListItem> = [:] private var devices = [DeviceListItem]() override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 75 self.title = "Lumino" serializer = SerializationService() serializer.addSerializer(Color.self, ColorSerializer()) serializer.addSerializer(Settings.self, SettingsSerializer()) serializer.addSerializer(Request.self, RequestSerializer()) serializer.addSerializer(Response.self, ResponseSerializer()) serializer.addSerializer(Event.self, EventSerializer()) serializer.addSerializer(Status.self, StatusSerializer()) self.nsb = NetServiceBrowser() self.nsb.delegate = self self.start() self.nsbSearchTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.restartSerach), userInfo: nil, repeats: true) } func start() { print("listening for services...") self.clients.removeAll() self.devices.removeAll() restartSerach() } func restartSerach() { self.nsb.stop() self.nsb.searchForServices(ofType:"_lumino-ws._tcp", inDomain: "") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCell", for: indexPath) as? DeviceCell { let device = devices[indexPath.row] cell.label?.text = device.name cell.isOn.isOn = device.isOn! cell.colorView.backgroundColor = device.color?.toUIColor(min: 0.5, range: 0.5) cell.isOn.tag = indexPath.row cell.isOn.addTarget(self, action: #selector(self.switchIsChanged(_:)), for: UIControlEvents.valueChanged) return cell } else { fatalError("Expecting DeviceCell") } } func switchIsChanged(_ isOn: UISwitch) { let device = devices[isOn.tag] let settings = Settings(isOn: isOn.isOn, deviceName: device.name!) _ = device.client.updateSettings(settings) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.devices.count } func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) { print("discovered service \(service.name)") var deviceListItem = self.clients[service.name] if deviceListItem == nil { let client = WebSocketClient(serializer, service) client.connectionDelegate += self client.communicationDelegate += self deviceListItem = DeviceListItem(client) self.clients[client.name] = deviceListItem } if !((deviceListItem?.client.isConnected)!) { deviceListItem?.client.connect() } } func updateInterface() { self.tableView.reloadData() } func websocketDidConnect(client: WebSocketClient) { self.presentedViewController?.performSegue(withIdentifier: "unwindToDevices", sender: self) _ = client.requestColor() _ = client.requestSettings() } func websocketDidDisconnect(client: WebSocketClient) { if self.isViewLoaded && (self.view.window != nil) { if let device = self.clients[client.name] { if let i = self.devices.index(where: {$0 === device}) { self.devices.remove(at: i) } self.clients.removeValue(forKey: client.name) } self.updateInterface() } } func tryToAdd(_ device: DeviceListItem) { if device.name != nil && device.color != nil { if (self.devices.index {$0 === device}) == nil { self.devices.append(device) } self.updateInterface() } } func websocketOnColorRead(client: WebSocketClient, color: Color) { let device = self.clients[client.name]! device.color = color tryToAdd(device) } func websocketOnColorUpdated(client: WebSocketClient, color: Color) { let device = self.clients[client.name]! device.color = color self.updateInterface() } func websocketOnSettingsRead(client: WebSocketClient, settings: Settings) { let device = self.clients[client.name]! device.name = settings.deviceName device.isOn = settings.isOn tryToAdd(device) } func websocketOnSettingsUpdated(client: WebSocketClient, settings: Settings) { let device = self.clients[client.name]! device.name = settings.deviceName device.isOn = settings.isOn self.updateInterface() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Removing the diconnected clients for (name, client) in self.clients { if !client.client.isConnected { if let i = self.devices.index(where: {$0 === client}) { self.devices.remove(at: i) } self.clients.removeValue(forKey: name) } } if self.clients.count == 0 { self.performSegue(withIdentifier: "disconnected", sender:self) } self.updateInterface() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetails" { if let nextViewController = segue.destination as? DeviceDetailsUIViewController { let row = self.tableView.indexPathForSelectedRow!.row nextViewController.device = self.devices[row] } } } @IBAction func unwindToDevices(_ segue:UIStoryboardSegue) { print("unwind to devices") } }
mit
2e6ad8ce87aaffa2feef8faa073de92b
34.271739
155
0.632974
4.876033
false
false
false
false
tardieu/swift
test/Constraints/if_expr.swift
26
2196
// RUN: %target-typecheck-verify-swift func useInt(_ x: Int) {} func useDouble(_ x: Double) {} class B { init() {} } class D1 : B { override init() { super.init() } } class D2 : B { override init() { super.init() } } func useB(_ x: B) {} func useD1(_ x: D1) {} func useD2(_ x: D2) {} var a = true ? 1 : 0 // should infer Int var b : Double = true ? 1 : 0 // should infer Double var c = true ? 1 : 0.0 // should infer Double var d = true ? 1.0 : 0 // should infer Double useInt(a) useDouble(b) useDouble(c) useDouble(d) var z = true ? a : b // expected-error{{result values in '? :' expression have mismatching types 'Int' and 'Double'}} var _ = a ? b : b // expected-error{{'Int' is not convertible to 'Bool'}} var e = true ? B() : B() // should infer B var f = true ? B() : D1() // should infer B var g = true ? D1() : B() // should infer B var h = true ? D1() : D1() // should infer D1 var i = true ? D1() : D2() // should infer B useB(e) useD1(e) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(f) useD1(f) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(g) useD1(g) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(h) useD1(h) useB(i) useD1(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useD2(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D2'}} var x = true ? 1 : 0 var y = 22 ? 1 : 0 // expected-error{{'Int' is not convertible to 'Bool'}} _ = x ? x : x // expected-error {{'Int' is not convertible to 'Bool'}} _ = true ? x : 1.2 // expected-error {{result values in '? :' expression have mismatching types 'Int' and 'Double'}} _ = (x: true) ? true : false // expected-error {{'(x: Bool)' is not convertible to 'Bool'}} _ = (x: 1) ? true : false // expected-error {{'(x: Int)' is not convertible to 'Bool'}} let ib: Bool! = false let eb: Bool? = .some(false) let conditional = ib ? "Broken" : "Heart" // should infer Bool! let conditional = eb ? "Broken" : "Heart" // expected-error {{value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '?'?}}
apache-2.0
e96b8c868ecf878bf512baea73787a10
32.784615
141
0.623406
3.037344
false
false
false
false
milseman/swift
test/Driver/Dependencies/independent.swift
36
2754
// main | other // RUN: rm -rf %t && cp -r %S/Inputs/independent/ %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: ls %t/main~buildrecord.swiftdeps // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND-NOT: Handled // RUN: touch -t 201401240006 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240007 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: rm -rf %t && cp -r %S/Inputs/independent/ %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s // CHECK-FIRST-MULTI: Handled main.swift // CHECK-FIRST-MULTI: Handled other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // RUN: touch -t 201401240006 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s // RUN: rm -rf %t && cp -r %S/Inputs/independent/ %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SINGLE %s // CHECK-SINGLE: Handled main.swift // RUN: ls %t/main~buildrecord.swiftdeps
apache-2.0
1664bec7c302de48f5c5399f0841c06f
61.590909
277
0.713145
3.023052
false
false
true
false
abertelrud/swift-package-manager
Sources/PackagePlugin/Utilities.swift
2
3233
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Package { /// The list of targets matching the given names. Throws an error if any of /// the targets cannot be found. public func targets(named targetNames: [String]) throws -> [Target] { return try targetNames.map { name in guard let target = self.targets.first(where: { $0.name == name }) else { throw PluginContextError.targetNotFound(name: name, package: self) } return target } } /// The list of products matching the given names. Throws an error if any of /// the products cannot be found. public func products(named productNames: [String]) throws -> [Product] { return try productNames.map { name in guard let product = self.products.first(where: { $0.name == name }) else { throw PluginContextError.productNotFound(name: name, package: self) } return product } } } extension Target { /// The transitive closure of all the targets on which the reciver depends, /// ordered such that every dependency appears before any other target that /// depends on it (i.e. in "topological sort order"). public var recursiveTargetDependencies: [Target] { // FIXME: We can rewrite this to use a stack instead of recursion. var visited = Set<Target.ID>() func dependencyClosure(for target: Target) -> [Target] { guard visited.insert(target.id).inserted else { return [] } return target.dependencies.flatMap{ dependencyClosure(for: $0) } + [target] } func dependencyClosure(for dependency: TargetDependency) -> [Target] { switch dependency { case .target(let target): return dependencyClosure(for: target) case .product(let product): return product.targets.flatMap{ dependencyClosure(for: $0) } } } return self.dependencies.flatMap{ dependencyClosure(for: $0) } } } extension Package { /// The products in this package that conform to a specific type. public func products<T: Product>(ofType: T.Type) -> [T] { return self.products.compactMap { $0 as? T } } /// The targets in this package that conform to a specific type. public func targets<T: Target>(ofType: T.Type) -> [T] { return self.targets.compactMap { $0 as? T } } } extension SourceModuleTarget { /// A possibly empty list of source files in the target that have the given /// filename suffix. public func sourceFiles(withSuffix suffix: String) -> FileList { return FileList(self.sourceFiles.filter{ $0.path.lastComponent.hasSuffix(suffix) }) } }
apache-2.0
ecc4b3318a00b6299b4feddb0ebeb80f
40.448718
91
0.610578
4.692308
false
false
false
false
juliantejera/JTDataStructures
Pods/Nimble/Sources/Nimble/Utils/Stringers.swift
15
6865
import Foundation internal func identityAsString(_ value: Any?) -> String { let anyObject: AnyObject? #if os(Linux) anyObject = value as? AnyObject #else anyObject = value as AnyObject? #endif if let value = anyObject { return NSString(format: "<%p>", unsafeBitCast(value, to: Int.self)).description } else { return "nil" } } internal func arrayAsString<T>(_ items: [T], joiner: String = ", ") -> String { return items.reduce("") { accum, item in let prefix = (accum.isEmpty ? "" : joiner) return accum + prefix + "\(stringify(item))" } } /// A type with a customized test output text representation. /// /// This textual representation is produced when values will be /// printed in test runs, and may be useful when producing /// error messages in custom matchers. /// /// - SeeAlso: `CustomDebugStringConvertible` public protocol TestOutputStringConvertible { var testDescription: String { get } } extension Double: TestOutputStringConvertible { public var testDescription: String { return NSNumber(value: self).testDescription } } extension Float: TestOutputStringConvertible { public var testDescription: String { return NSNumber(value: self).testDescription } } extension NSNumber: TestOutputStringConvertible { // This is using `NSString(format:)` instead of // `String(format:)` because the latter somehow breaks // the travis CI build on linux. public var testDescription: String { let description = self.description if description.contains(".") { // Travis linux swiftpm build doesn't like casting String to NSString, // which is why this annoying nested initializer thing is here. // Maybe this will change in a future snapshot. let decimalPlaces = NSString(string: NSString(string: description) .components(separatedBy: ".")[1]) // SeeAlso: https://bugs.swift.org/browse/SR-1464 switch decimalPlaces.length { case 1: return NSString(format: "%0.1f", self.doubleValue).description case 2: return NSString(format: "%0.2f", self.doubleValue).description case 3: return NSString(format: "%0.3f", self.doubleValue).description default: return NSString(format: "%0.4f", self.doubleValue).description } } return self.description } } extension Array: TestOutputStringConvertible { public var testDescription: String { let list = self.map(Nimble.stringify).joined(separator: ", ") return "[\(list)]" } } extension AnySequence: TestOutputStringConvertible { public var testDescription: String { let generator = self.makeIterator() var strings = [String]() var value: AnySequence.Iterator.Element? repeat { value = generator.next() if let value = value { strings.append(stringify(value)) } } while value != nil let list = strings.joined(separator: ", ") return "[\(list)]" } } extension NSArray: TestOutputStringConvertible { public var testDescription: String { let list = Array(self).map(Nimble.stringify).joined(separator: ", ") return "(\(list))" } } extension NSIndexSet: TestOutputStringConvertible { public var testDescription: String { let list = Array(self).map(Nimble.stringify).joined(separator: ", ") return "(\(list))" } } extension String: TestOutputStringConvertible { public var testDescription: String { return self } } extension Data: TestOutputStringConvertible { public var testDescription: String { #if os(Linux) // FIXME: Swift on Linux triggers a segfault when calling NSData's hash() (last checked on 03-11-16) return "Data<length=\(count)>" #else return "Data<hash=\((self as NSData).hash),length=\(count)>" #endif } } /// /// Returns a string appropriate for displaying in test output /// from the provided value. /// /// - parameter value: A value that will show up in a test's output. /// /// - returns: The string that is returned can be /// customized per type by conforming a type to the `TestOutputStringConvertible` /// protocol. When stringifying a non-`TestOutputStringConvertible` type, this /// function will return the value's debug description and then its /// normal description if available and in that order. Otherwise it /// will return the result of constructing a string from the value. /// /// - SeeAlso: `TestOutputStringConvertible` public func stringify<T>(_ value: T?) -> String { guard let value = value else { return "nil" } if let value = value as? TestOutputStringConvertible { return value.testDescription } if let value = value as? CustomDebugStringConvertible { return value.debugDescription } return String(describing: value) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @objc public class NMBStringer: NSObject { @objc public class func stringify(_ obj: Any?) -> String { return Nimble.stringify(obj) } } #endif // MARK: Collection Type Stringers /// Attempts to generate a pretty type string for a given value. If the value is of a Objective-C /// collection type, or a subclass thereof, (e.g. `NSArray`, `NSDictionary`, etc.). /// This function will return the type name of the root class of the class cluster for better /// readability (e.g. `NSArray` instead of `__NSArrayI`). /// /// For values that don't have a type of an Objective-C collection, this function returns the /// default type description. /// /// - parameter value: A value that will be used to determine a type name. /// /// - returns: The name of the class cluster root class for Objective-C collection types, or the /// the `dynamicType` of the value for values of any other type. public func prettyCollectionType<T>(_ value: T) -> String { switch value { case is NSArray: return String(describing: NSArray.self) case is NSDictionary: return String(describing: NSDictionary.self) case is NSSet: return String(describing: NSSet.self) case is NSIndexSet: return String(describing: NSIndexSet.self) default: return String(describing: value) } } /// Returns the type name for a given collection type. This overload is used by Swift /// collection types. /// /// - parameter collection: A Swift `CollectionType` value. /// /// - returns: A string representing the `dynamicType` of the value. public func prettyCollectionType<T: Collection>(_ collection: T) -> String { return String(describing: type(of: collection)) }
mit
1d68e00c485cdf125fed02b5af7996df
32.325243
112
0.656664
4.604292
false
true
false
false
HotCocoaTouch/DeclarativeLayout
Example/DeclarativeLayout/WithoutFramework/RegistrationExampleWithoutFrameworkViewController.swift
1
8216
import UIKit class RegistrationWithoutFrameworkViewController: UIViewController { private let registerOrSignInSegmentedControl = UISegmentedControl() private let headerLabel = UILabel() private let stackView = UIStackView() private let emailContainerView = UIView() private let emailLabel = UILabel() private let emailTextField = UITextField() private let passwordContainerView = UIView() private let passwordLabel = UILabel() private let passwordTextField = UITextField() private let submitButton = UIButton() private let forgotMyPasswordButton = UIButton() override func viewDidLoad() { super.viewDidLoad() title = "No Framework" layoutAllViews() configureAllViews() } private func layoutAllViews () { layoutViewHierarchy() layoutHeaderLabel() layoutStackView() layoutEmailContainerView() layoutPasswordContainerView() layoutSubmitButton() layoutForgotMyPasswordButton() } private func layoutViewHierarchy() { registerOrSignInSegmentedControl.translatesAutoresizingMaskIntoConstraints = false headerLabel.translatesAutoresizingMaskIntoConstraints = false emailLabel.translatesAutoresizingMaskIntoConstraints = false emailTextField.translatesAutoresizingMaskIntoConstraints = false emailContainerView.translatesAutoresizingMaskIntoConstraints = false passwordLabel.translatesAutoresizingMaskIntoConstraints = false passwordTextField.translatesAutoresizingMaskIntoConstraints = false passwordContainerView.translatesAutoresizingMaskIntoConstraints = false stackView.translatesAutoresizingMaskIntoConstraints = false submitButton.translatesAutoresizingMaskIntoConstraints = false forgotMyPasswordButton.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(registerOrSignInSegmentedControl) stackView.addArrangedSubview(headerLabel) emailContainerView.addSubview(emailLabel) emailContainerView.addSubview(emailTextField) stackView.addArrangedSubview(emailContainerView) passwordContainerView.addSubview(passwordLabel) passwordContainerView.addSubview(passwordTextField) stackView.addArrangedSubview(passwordContainerView) stackView.addArrangedSubview(submitButton) view.addSubview(stackView) view.addSubview(forgotMyPasswordButton) } private func layoutStackView() { stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 35).isActive = true stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true } private func layoutHeaderLabel() { stackView.setCustomSpacing(30, after: registerOrSignInSegmentedControl) } private func layoutEmailContainerView() { stackView.setCustomSpacing(20, after: headerLabel) layoutEmailLabel() layoutEmailTextField() } private func layoutEmailLabel() { emailLabel.topAnchor.constraint(greaterThanOrEqualTo: emailContainerView.topAnchor).isActive = true emailLabel.leadingAnchor.constraint(equalTo: emailContainerView.leadingAnchor).isActive = true emailLabel.trailingAnchor.constraint(equalTo: emailTextField.leadingAnchor, constant: -20).isActive = true emailLabel.bottomAnchor.constraint(lessThanOrEqualTo: emailContainerView.bottomAnchor).isActive = true emailLabel.centerYAnchor.constraint(equalTo: emailContainerView.centerYAnchor) } private func layoutEmailTextField() { emailTextField.topAnchor.constraint(greaterThanOrEqualTo: emailContainerView.topAnchor).isActive = true emailTextField.trailingAnchor.constraint(equalTo: emailContainerView.trailingAnchor).isActive = true emailTextField.bottomAnchor.constraint(greaterThanOrEqualTo: emailContainerView.bottomAnchor).isActive = true emailTextField.centerYAnchor.constraint(equalTo: emailContainerView.centerYAnchor).isActive = true } private func layoutPasswordContainerView() { stackView.setCustomSpacing(40, after: emailContainerView) layoutPasswordLabel() layoutPasswordTextField() } private func layoutPasswordLabel() { passwordLabel.topAnchor.constraint(greaterThanOrEqualTo: passwordContainerView.topAnchor).isActive = true passwordLabel.leadingAnchor.constraint(equalTo: passwordContainerView.leadingAnchor).isActive = true passwordLabel.trailingAnchor.constraint(equalTo: passwordTextField.leadingAnchor, constant: -20).isActive = true passwordLabel.bottomAnchor.constraint(lessThanOrEqualTo: passwordContainerView.bottomAnchor).isActive = true passwordLabel.centerYAnchor.constraint(equalTo: passwordContainerView.centerYAnchor).isActive = true } private func layoutPasswordTextField() { passwordTextField.topAnchor.constraint(greaterThanOrEqualTo: passwordContainerView.topAnchor).isActive = true passwordTextField.trailingAnchor.constraint(equalTo: passwordContainerView.trailingAnchor).isActive = true passwordTextField.bottomAnchor.constraint(greaterThanOrEqualTo: passwordContainerView.bottomAnchor).isActive = true passwordTextField.centerYAnchor.constraint(equalTo: passwordContainerView.centerYAnchor).isActive = true passwordTextField.leadingAnchor.constraint(equalTo: emailTextField.leadingAnchor).isActive = true } private func layoutSubmitButton() { stackView.setCustomSpacing(40, after: passwordContainerView) } private func layoutForgotMyPasswordButton() { forgotMyPasswordButton.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 20).isActive = true forgotMyPasswordButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } // Don't worry about this below here private func configureAllViews() { view.backgroundColor = .white registerOrSignInSegmentedControl.insertSegment(withTitle: "Register", at: 0, animated: false) registerOrSignInSegmentedControl.insertSegment(withTitle: "Sign In", at: 1, animated: false) if registerOrSignInSegmentedControl.selectedSegmentIndex == -1 { registerOrSignInSegmentedControl.selectedSegmentIndex = 0 } headerLabel.font = UIFont.boldSystemFont(ofSize: 18) if registerOrSignInSegmentedControl.selectedSegmentIndex == 0 { headerLabel.text = "Register" } else { headerLabel.text = "Sign In" } stackView.axis = .vertical emailLabel.text = "Email" emailTextField.placeholder = "[email protected]" if #available(iOS 10.0, *) { emailTextField.textContentType = .emailAddress } emailTextField.layer.borderColor = UIColor.blue.cgColor emailTextField.layer.borderWidth = 1 emailTextField.textAlignment = .center emailTextField.isUserInteractionEnabled = false passwordLabel.text = "Password" passwordTextField.placeholder = "secure password here" passwordTextField.isSecureTextEntry = true passwordTextField.layer.borderColor = UIColor.blue.cgColor passwordTextField.layer.borderWidth = 1 passwordTextField.textAlignment = .center passwordTextField.isUserInteractionEnabled = false submitButton.setTitle("Submit", for: .normal) submitButton.backgroundColor = UIColor.blue submitButton.setTitleColor(.white, for: .normal) submitButton.layer.cornerRadius = 10 submitButton.clipsToBounds = true submitButton.titleLabel?.textAlignment = .center forgotMyPasswordButton.setTitle("forgot your password?", for: .normal) forgotMyPasswordButton.setTitleColor(.blue, for: .normal) } }
mit
cddfb8bcb187488d1d90e2ce65da208a
46.218391
123
0.733569
6.723404
false
false
false
false
Ilhasoft/ISParseBind
ISParseBind/Classes/Components/ISParseBindLabel.swift
1
661
// // ISParseBindLabel.swift // ISParseBind // // Created by Daniel Amaral on 11/03/17. // Copyright © 2017 Ilhasoft. All rights reserved. // import UIKit open class ISParseBindLabel: UILabel, ISParseBindable { override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public var required: Bool = false public var requiredError: String = "" public var fieldType: String = "Text" public var fieldTypeError: String = "" @IBInspectable open var fieldPath: String = "" public var persist: Bool = false }
mit
6744e82245dd8b10fa47a411b2f6c55a
22.571429
55
0.660606
3.882353
false
false
false
false
madbat/SwiftMath
SwiftMath/Surge/Arithmetic.swift
1
7968
// Arithmetic.swift // // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // 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 Accelerate // MARK: Sum func sum(x: [Float]) -> Float { var result: Float = 0.0 vDSP_sve(x, 1, &result, vDSP_Length(x.count)) return result } func sum(x: [Double]) -> Double { var result: Double = 0.0 vDSP_sveD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Sum of Absolute Values func asum(x: [Float]) -> Float { return cblas_sasum(Int32(x.count), x, 1) } func asum(x: [Double]) -> Double { return cblas_dasum(Int32(x.count), x, 1) } // MARK: Maximum func max(x: [Float]) -> Float { var result: Float = 0.0 vDSP_maxv(x, 1, &result, vDSP_Length(x.count)) return result } func max(x: [Double]) -> Double { var result: Double = 0.0 vDSP_maxvD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Minimum func min(x: [Float]) -> Float { var result: Float = 0.0 vDSP_minv(x, 1, &result, vDSP_Length(x.count)) return result } func min(x: [Double]) -> Double { var result: Double = 0.0 vDSP_minvD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Mean func mean(x: [Float]) -> Float { var result: Float = 0.0 vDSP_meanv(x, 1, &result, vDSP_Length(x.count)) return result } func mean(x: [Double]) -> Double { var result: Double = 0.0 vDSP_meanvD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Mean Magnitude func meamg(x: [Float]) -> Float { var result: Float = 0.0 vDSP_meamgv(x, 1, &result, vDSP_Length(x.count)) return result } func meamg(x: [Double]) -> Double { var result: Double = 0.0 vDSP_meamgvD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Mean Square Value func measq(x: [Float]) -> Float { var result: Float = 0.0 vDSP_measqv(x, 1, &result, vDSP_Length(x.count)) return result } func measq(x: [Double]) -> Double { var result: Double = 0.0 vDSP_measqvD(x, 1, &result, vDSP_Length(x.count)) return result } // MARK: Square Root func sqrt(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvsqrtf(&results, x, [Int32(x.count)]) return results } func sqrt(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvsqrt(&results, x, [Int32(x.count)]) return results } // MARK: Add public func add<Real: RealType>(x: [Real], _ y: [Real]) -> [Real] { return analysis(x, y, ifFloat: add, ifDouble: add) } func add(x: [Float], _ y: [Float]) -> [Float] { var results = [Float](y) cblas_saxpy(Int32(x.count), 1.0, x, 1, &results, 1) return results } func add(x: [Double], _ y: [Double]) -> [Double] { var results = [Double](y) cblas_daxpy(Int32(x.count), 1.0, x, 1, &results, 1) return results } // MARK: Multiply public func multiply<Real: RealType>(x: [Real], _ y: [Real]) -> [Real] { return analysis(x, y, ifFloat: mul, ifDouble: mul) } func mul(x: [Float], _ y: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vDSP_vmul(x, 1, y, 1, &results, 1, vDSP_Length(x.count)) return results } func mul(x: [Double], _ y: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vDSP_vmulD(x, 1, y, 1, &results, 1, vDSP_Length(x.count)) return results } // MARK: Divide public func divide<Real: RealType>(x: [Real], _ y: [Real]) -> [Real] { return analysis(x, y, ifFloat: div, ifDouble: div) } func div(x: [Float], _ y: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvdivf(&results, x, y, [Int32(x.count)]) return results } func div(x: [Double], _ y: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvdiv(&results, x, y, [Int32(x.count)]) return results } // MARK: Modulo public func modulo<Real: RealType>(x: [Real], _ y: [Real]) -> [Real] { return analysis(x, y, ifFloat: mod, ifDouble: mod) } func mod(x: [Float], _ y: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvfmodf(&results, x, y, [Int32(x.count)]) return results } func mod(x: [Double], _ y: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvfmod(&results, x, y, [Int32(x.count)]) return results } // MARK: Remainder public func remainder<Real: RealType>(x: [Real], _ y: [Real]) -> [Real] { return analysis(x, y, ifFloat: remainder, ifDouble: remainder) } func remainder(x: [Float], _ y: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvremainderf(&results, x, y, [Int32(x.count)]) return results } func remainder(x: [Double], _ y: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvremainder(&results, x, y, [Int32(x.count)]) return results } // MARK: Dot Product public func dotProduct<Real: RealType>(x: [Real], _ y: [Real]) -> Real { precondition(x.count == y.count, "Vectors must have equal count") return analysis(x, y, ifFloat: dot, ifDouble: dot) } func dot(x: [Float], _ y: [Float]) -> Float { precondition(x.count == y.count, "Vectors must have equal count") var result: Float = 0.0 vDSP_dotpr(x, 1, y, 1, &result, vDSP_Length(x.count)) return result } func dot(x: [Double], _ y: [Double]) -> Double { precondition(x.count == y.count, "Vectors must have equal count") var result: Double = 0.0 vDSP_dotprD(x, 1, y, 1, &result, vDSP_Length(x.count)) return result } // MARK: - Operators public func + <Real: RealType>(lhs: [Real], rhs: [Real]) -> [Real] { return add(lhs, rhs) } public func + <Real: RealType>(lhs: [Real], rhs: Real) -> [Real] { return add(lhs, [Real](count: lhs.count, repeatedValue: rhs)) } public func / <Real: RealType>(lhs: [Real], rhs: [Real]) -> [Real] { return divide(lhs, rhs) } public func / <Real: RealType>(lhs: [Real], rhs: Real) -> [Real] { return divide(lhs, [Real](count: lhs.count, repeatedValue: rhs)) } public func * <Real: RealType>(lhs: [Real], rhs: [Real]) -> [Real] { return multiply(lhs, rhs) } public func * <Real: RealType>(lhs: [Real], rhs: Real) -> [Real] { return multiply(lhs, [Real](count: lhs.count, repeatedValue: rhs)) } public func % <Real: RealType>(lhs: [Real], rhs: [Real]) -> [Real] { return modulo(lhs, rhs) } public func % <Real: RealType>(lhs: [Real], rhs: Real) -> [Real] { return modulo(lhs, [Real](count: lhs.count, repeatedValue: rhs)) } infix operator • { associativity left precedence 150 } public func • <Real: RealType>(lhs: [Real], rhs: [Real]) -> Real { return dotProduct(lhs, rhs) }
mit
80029d0b5ad022ce1d446c6316131d80
24.683871
80
0.62007
3.122353
false
false
false
false
adis300/Swift-Learn
SwiftLearn/Source/Random.swift
1
1963
// // Random.swift // Swift-Learn // // Created by Innovation on 11/12/16. // Copyright © 2016 Votebin. All rights reserved. // import Foundation class Random{ static func randMinus1To1(length: Int) -> [Double]{ return (0..<length).map{_ in Double(arc4random())/Double(INT32_MAX) - 1} } static func randMinus1To1() -> Double{ return Double(arc4random())/Double(INT32_MAX) - 1 } static func randN(n:Int) -> Int{ return Int(arc4random_uniform(UInt32(n))) } static func rand0To1() -> Double{ return Double(arc4random()) / Double(UINT32_MAX) } static var y2 = 0.0 static var use_last = false /// static Function to get a random value for a given distribution // static func gaussianRandom(_ mean : Double, standardDeviation : Double) -> Double static func normalRandom() -> Double { var y1 : Double if (use_last) /* use value from previous call */ { y1 = y2 use_last = false } else { var w = 1.0 var x1 = 0.0 var x2 = 0.0 repeat { x1 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 x2 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 w = x1 * x1 + x2 * x2 } while ( w >= 1.0 ) w = sqrt( (-2.0 * log( w ) ) / w ) y1 = x1 * w y2 = x2 * w use_last = true } return( y1 * 1 ) } /* static func normalDistribution(μ:Double, σ:Double, x:Double) -> Double { let a = exp( -1 * pow(x-μ, 2) / ( 2 * pow(σ,2) ) ) let b = σ * sqrt( 2 * M_PI ) return a / b } static func standardNormalDistribution(_ x:Double) -> Double { return exp( -1 * pow(x, 2) / 2 ) / sqrt( 2 * M_PI ) }*/ }
apache-2.0
b139ccb535fb0d6730359d80ac5f3c15
25.093333
88
0.485437
3.482206
false
false
false
false
JacquesCarette/literate-scientific-software
code/stable/glassbr/src/swift/main.swift
1
9467
/** main.swift Controls the flow of the program - Authors: Nikitha Krithnan and W. Spencer Smith */ import Foundation extension String: Error {} var outfile: FileHandle var filename: String = CommandLine.arguments[0] do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'filename' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(filename.utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var inParams: InputParameters = InputParameters() try get_input(filename, inParams) try derived_values(inParams) try input_constraints(&inParams) var J_tol: Double = try func_J_tol(&inParams) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'J_tol' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(J_tol).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var q: Double = try func_q(&inParams) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'q' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(q).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var q_hat: Double = try func_q_hat(&inParams, q) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'q_hat' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(q_hat).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var q_hat_tol: Double = try func_q_hat_tol(&inParams, J_tol) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'q_hat_tol' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(q_hat_tol).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var J: Double = try func_J(&inParams, q_hat) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'J' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(J).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var NFL: Double = try func_NFL(&inParams, q_hat_tol) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'NFL' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(NFL).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var B: Double = try func_B(&inParams, J) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'B' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(B).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var LR: Double = try func_LR(&inParams, NFL) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'LR' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(LR).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var isSafeLR: Bool = try func_isSafeLR(LR, q) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'isSafeLR' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(isSafeLR).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var P_b: Double = try func_P_b(B) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'P_b' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(P_b).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } var isSafePb: Bool = try func_isSafePb(&inParams, P_b) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'isSafePb' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(isSafePb).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module Control".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } try write_output(isSafePb, isSafeLR, P_b, J)
bsd-2-clause
8f0e1364beae16296af3746c69cb39cb
26.048571
155
0.677723
3.543039
false
false
false
false
panyam/SwiftHTTP
Sources/WebSocket/WSHandler.swift
2
5743
// // WSHandler.swift // SwiftHTTP // // Created by Sriram Panyam on 12/27/15. // Copyright © 2015 Sriram Panyam. All rights reserved. // import SwiftIO public let WS_HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" public typealias WSHandler = (connection : WSConnection) -> Void public class WSRequestServer : HttpRequestServer, WSConnectionDelegate { public var extensionRegistry = WSExtensionRegistry() var handler : WSHandler public init(_ handler: WSHandler) { self.handler = handler } convenience public init (_ handler: WSConnectionHandler) { self.init(handler.handle) } public func handleRequest(request: HttpRequest, response: HttpResponse) { if let _ = validateRequest(request) { let connection = request.connection! response.setStatus(HttpStatusCode.SwitchingProtocols) response.headers.setValueFor("Connection", value: "Upgrade") response.headers.setValueFor("Upgrade", value: "websocket") let websocketKey = request.headers.firstValueFor("Sec-WebSocket-Key")! let websocketAcceptString = websocketKey + WS_HANDSHAKE_GUID let sha1Bytes = websocketAcceptString.SHA1Bytes() if let base64Encoded = BaseXEncoding.Base64Encode(sha1Bytes) { response.headers.setValueFor("Sec-WebSocket-Accept", value: base64Encoded) // process WS extensions to see what we can handle var extensions : [WSExtension] = [] if let extensionHeader = request.headers.forKey("Sec-WebSocket-Extensions") { extensions = parseWSExtensions(extensionHeader) let extensionHeader = response.headers.forKey("Sec-WebSocket-Extensions", create: true) for extn in extensions { extensionHeader?.addValue(extn.negotiationResponseString) } } response.writeHeaders() let connection = WSConnection(connection.reader, writer: connection.writer, extensions) connections.append(ConnectionWrapper(connection: connection, request: request, response: response)) connection.delegate = self handler(connection: connection) return } } response.setStatus(HttpStatusCode.BadRequest) response.close() } private func validateRequest(request: HttpRequest) -> NSData? { // check that the request is indeed a websocket request // Must have Host if request.hostHeader != nil && request.connectionHeader?.lowercaseString == "upgrade" && request.headers.firstValueFor("Upgrade")?.lowercaseString == "websocket" && request.headers.firstValueFor("Sec-WebSocket-Version")?.lowercaseString == "13" { if let websocketKey = BaseXEncoding.Base64DecodeData(request.headers.firstValueFor("Sec-WebSocket-Key")) { if websocketKey.length == 16 { return websocketKey } } } return nil } private func parseWSExtensions(values: Header) -> [WSExtension] { var extensions = [WSExtension]() var acceptedNames = [String: Bool]() for value in values.allValues() { for var extensionString in value.componentsSeparatedByString(",") { extensionString = extensionString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var extensionName = "" var arguments = [(String, String)]() for (index, extensionParam) in extensionString.componentsSeparatedByString(";").enumerate() { let extParam = extensionParam.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if index == 0 { extensionName = extParam if acceptedNames[extensionName] != nil { continue } } else { let argparts = extParam.componentsSeparatedByString("=") var argname = "" var argvalue = "" if argparts.count > 0 { argname = argparts[0] if argparts.count > 1 { argvalue = argparts[1] } } arguments.append((argname, argvalue)) } } if let extn = self.extensionRegistry.createExtension(extensionName, arguments: arguments) { acceptedNames[extensionName] = true extensions.append(extn) } } } return extensions } private struct ConnectionWrapper { var connection: WSConnection var request: HttpRequest var response: HttpResponse } private var connections = [ConnectionWrapper]() public func connectionClosed(connection: WSConnection) { for i in 0 ..< connections.count { if connections[i].connection === connection { let wrapper = connections.removeAtIndex(i) let httpConnection = wrapper.request.connection! httpConnection.delegate?.connectionFinished(httpConnection) return } } } }
apache-2.0
95d2c63aa2f4d8ea87f514630b65a23d
38.328767
122
0.564786
5.596491
false
false
false
false
glyuck/GlyuckDataGrid
Example/Tests/DataGridViewSpec.swift
1
10338
// // DataGridViewSpec.swift // // Created by Vladimir Lyukov on 30/07/15. // import Quick import Nimble import GlyuckDataGrid class DataGridViewSpec: QuickSpec { override func spec() { var sut: DataGridView! var stubDataSource: StubDataGridViewDataSource! beforeEach { stubDataSource = StubDataGridViewDataSource() sut = DataGridView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) sut.dataSource = stubDataSource sut.collectionView.layoutIfNeeded() } describe("Registering/dequeuing cells") { context("zebra-striped tables") { it("should return transparent cells when row1BackgroundColor and row2BackgroundColor are nil") { let cell1 = sut.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: IndexPath(forColumn: 1, row: 0)) let cell2 = sut.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: IndexPath(forColumn: 1, row: 1)) expect(cell1.backgroundColor).to(beNil()) expect(cell2.backgroundColor).to(beNil()) } it("should return row1BackgroundColor for odd rows and row2BackgroundColor for even rows") { sut.row1BackgroundColor = UIColor.red sut.row2BackgroundColor = UIColor.green let cell1 = sut.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: IndexPath(forColumn: 1, row: 0)) let cell2 = sut.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: IndexPath(forColumn: 1, row: 1)) expect(cell1.backgroundColor) == sut.row1BackgroundColor expect(cell2.backgroundColor) == sut.row2BackgroundColor } } it("should register and dequeue cells") { sut.registerClass(DataGridViewContentCell.self, forCellWithReuseIdentifier: "MyIdentifier") let cell = sut.dequeueReusableCellWithReuseIdentifier("MyIdentifier", forIndexPath: IndexPath(forColumn: 0, row: 0)) expect(cell).notTo(beNil()) } it("should register and dequeue column headers") { sut.registerClass(DataGridViewColumnHeaderCell.self, forHeaderOfKind: .ColumnHeader, withReuseIdentifier: "MyIdentifier") let cell = sut.dequeueReusableHeaderViewWithReuseIdentifier("MyIdentifier", forColumn: 1) expect(cell).notTo(beNil()) expect(cell.dataGridView) == sut expect(cell.indexPath) == IndexPath(index: 1) } it("should register and dequeue row headers") { sut.registerClass(DataGridViewRowHeaderCell.self, forHeaderOfKind: .RowHeader, withReuseIdentifier: "MyIdentifier") let cell = sut.dequeueReusableHeaderViewWithReuseIdentifier("MyIdentifier", forRow: 1) expect(cell).notTo(beNil()) expect(cell.dataGridView) == sut expect(cell.indexPath) == IndexPath(index: 1) } it("should register and dequeue corner headers") { sut.registerClass(DataGridViewCornerHeaderCell.self, forHeaderOfKind: .CornerHeader, withReuseIdentifier: "MyIdentifier") let cell = sut.dequeueReusableCornerHeaderViewWithReuseIdentifier("MyIdentifier") expect(cell).notTo(beNil()) expect(cell.dataGridView) == sut expect(cell.indexPath) == IndexPath(index: 0) } } describe("collectionView") { it("should not be nil") { expect(sut.collectionView).notTo(beNil()) } it("should be subview of dataGridView") { expect(sut.collectionView.superview) === sut } it("should resize along with dataGridView") { sut.collectionView.layoutIfNeeded() // Ensure text label is initialized when tests are started sut.frame = CGRect(x: 0, y: 0, width: sut.frame.width * 2, height: sut.frame.height / 2) sut.layoutIfNeeded() expect(sut.collectionView.frame) == sut.frame } it("should register DataGridViewContentCell as default cell") { let cell = sut.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: IndexPath(forColumn: 0, row: 0)) as? DataGridViewContentCell expect(cell).notTo(beNil()) } it("should register DataGridViewColumnHeaderCell as default column header") { let header = sut.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultColumnHeader, forColumn: 0) expect(header).notTo(beNil()) } it("should set isSorted and iSortedAsc for column headers") { let header1 = sut.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultColumnHeader, forColumn: 0) expect(header1.isSorted).to(beFalse()) sut.setSortColumn(0, ascending: false) let header2 = sut.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultColumnHeader, forColumn: 0) expect(header2.isSorted).to(beTrue()) expect(header2.isSortedAsc).to(beFalse()) } it("should register DataGridViewRowHeaderCell as default row header") { let header = sut.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultRowHeader, forRow: 0) expect(header).notTo(beNil()) } it("should register DataGridViewCornerHeaderCell as default row header") { let header = sut.dequeueReusableCornerHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCornerHeader) expect(header).notTo(beNil()) } it("should have CollectionViewDataSource as dataSource") { let dataSource = sut.collectionView.dataSource as? CollectionViewDataSource expect(dataSource).notTo(beNil()) expect(dataSource) == sut.collectionViewDataSource expect(dataSource?.dataGridView) == sut } it("should have CollectionViewDelegate as delegate") { let delegate = sut.collectionView.delegate as? CollectionViewDelegate expect(delegate).notTo(beNil()) expect(delegate) == sut.collectionViewDelegate expect(delegate?.dataGridView) == sut } it("should have transparent background") { expect(sut.collectionView.backgroundColor) == UIColor.clear } describe("layout") { it("should be instance of DataGridViewLayout") { expect(sut.collectionView.collectionViewLayout).to(beAKindOf(DataGridViewLayout.self)) } it("should have dataGridView set") { let layout = sut.collectionView.collectionViewLayout as? DataGridViewLayout expect(layout?.dataGridView) === sut } it("should have collectionView and dataGridView properties set") { let layout = sut.collectionView.collectionViewLayout as? DataGridViewLayout expect(layout).notTo(beNil()) if let layout = layout { expect(layout.dataGridView) === sut expect(layout.collectionView) === sut.collectionView } } } } describe("numberOfColumns") { it("should return value provided by dataSource") { stubDataSource.numberOfColumns = 7 sut.dataSource = stubDataSource expect(sut.numberOfColumns()) == stubDataSource.numberOfColumns } it("should return 0 if dataSource is nil") { sut.dataSource = nil expect(sut.numberOfColumns()) == 0 } } describe("numberOfRows") { it("should return value provided by dataSource") { stubDataSource.numberOfRows = 7 sut.dataSource = stubDataSource expect(sut.numberOfRows()) == stubDataSource.numberOfRows } it("should return 0 if dataSource is nil") { sut.dataSource = nil expect(sut.numberOfRows()) == 0 } } describe("selectRow:animated:") { it("should select all items in corresponding section") { let row = 1 sut.selectRow(row, animated: false) expect(sut.collectionView.indexPathsForSelectedItems?.count) == sut.numberOfColumns() for i in 0..<sut.numberOfColumns() { let indexPath = IndexPath(item: i, section: row) expect(sut.collectionView.indexPathsForSelectedItems).to(contain(indexPath)) } } it("should deselect previously selected row") { let row = 1 sut.selectRow(0, animated: false) sut.selectRow(row, animated: false) expect(sut.collectionView.indexPathsForSelectedItems?.count) == sut.numberOfColumns() for i in 0..<sut.numberOfColumns() { let indexPath = IndexPath(item: i, section: row) expect(sut.collectionView.indexPathsForSelectedItems).to(contain(indexPath)) } } } describe("deselectRow:animated:") { it("should deselect all items in corresponding section") { let row = 1 sut.selectRow(row, animated: false) sut.deselectRow(row, animated: false) expect(sut.collectionView.indexPathsForSelectedItems?.count) == 0 } } } }
mit
5581de7a5f61a4382361c1d84b171022
44.946667
187
0.600019
5.801347
false
false
false
false
Colrying/DouYuZB
DouYuZB/DouYuZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
1
713
// // UIBarButtonItem-Extension.swift // DouYuZB // // Created by 皇坤鹏 on 17/4/11. // Copyright © 2017年 皇坤鹏. All rights reserved. // import UIKit extension UIBarButtonItem { // 构造方法 convenience init(imageName:String, hightImageName:String = "", size:CGSize = .zero) { let btn = UIButton(); btn.setImage(UIImage(named:imageName), for: .normal); if hightImageName != "" { btn.setImage(UIImage(named:hightImageName), for: .highlighted); } if size == .zero { btn.sizeToFit(); } else { btn.frame = CGRect(origin: .zero, size: size); } self.init(customView : btn); } }
mit
c2b9f30ce39d4c1ea5b98f8f77dd5864
23.642857
89
0.569565
3.876404
false
false
false
false
nathawes/swift
test/Interop/Cxx/static/static-var-irgen.swift
9
5975
// RUN: %target-swift-emit-ir -I %S/Inputs -enable-cxx-interop %s | %FileCheck %s import StaticVar public func initStaticVars() -> CInt { return staticVar + staticVarInit + staticVarInlineInit + staticConst + staticConstInit + staticConstInlineInit + staticConstexpr + staticNonTrivial.val + staticConstNonTrivial.val + staticConstexprNonTrivial.val } // CHECK: @{{_ZL9staticVar|staticVar}} = internal global i32 2, align 4 // CHECK: @{{_ZL13staticVarInit|staticVarInit}} = internal global i32 0, align 4 // CHECK: @{{_ZL19staticVarInlineInit|staticVarInlineInit}} = internal global i32 0, align 4 // CHECK: @{{_ZL11staticConst|staticConst}} = internal constant i32 4, align 4 // CHECK: @{{_ZL15staticConstInit|staticConstInit}} = internal global i32 0, align 4 // CHECK: @{{_ZL21staticConstInlineInit|staticConstInlineInit}} = internal global i32 0, align 4 // CHECK: @{{_ZL15staticConstexpr|staticConstexpr}} = internal constant i32 32, align 4 // CHECK: @{{_ZL16staticNonTrivial|staticNonTrivial}} = internal global %class.NonTrivial zeroinitializer, align 4 // CHECK: @{{_ZL21staticConstNonTrivial|staticConstNonTrivial}} = internal global %class.NonTrivial zeroinitializer, align 4 // CHECK: @{{_ZL25staticConstexprNonTrivial|staticConstexprNonTrivial}} = internal constant %class.NonTrivial { i32 8192 }, align 4 // CHECK: define internal void @{{__cxx_global_var_init|"\?\?__EstaticVarInit@@YAXXZ"}}() // CHECK: %call = call i32 @{{_Z13makeStaticVarv|"\?makeStaticVar@@YAHXZ"}}() // CHECK: store i32 %call, i32* @{{_ZL13staticVarInit|staticVarInit}}, align 4 // CHECK: declare{{( dso_local)?}} i32 @{{_Z13makeStaticVarv|"\?makeStaticVar@@YAHXZ"}}() // CHECK: define internal void @{{__cxx_global_var_init.1|"\?\?__EstaticVarInlineInit@@YAXXZ"}}() // CHECK: %call = call i32 @{{_Z19inlineMakeStaticVarv|"\?inlineMakeStaticVar@@YAHXZ"}}() // CHECK: store i32 %call, i32* @{{_ZL19staticVarInlineInit|staticVarInlineInit}}, align 4 // CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_Z19inlineMakeStaticVarv|"\?inlineMakeStaticVar@@YAHXZ"}}() // CHECK: ret i32 8 // CHECK: define internal void @{{__cxx_global_var_init.2|"\?\?__EstaticConstInit@@YAXXZ"}}() // CHECK: %call = call i32 @{{_Z15makeStaticConstv|"\?makeStaticConst@@YAHXZ"}}() // CHECK: store i32 %call, i32* @{{_ZL15staticConstInit|staticConstInit}}, align 4 // CHECK: declare{{( dso_local)?}} i32 @{{_Z15makeStaticConstv|"\?makeStaticConst@@YAHXZ"}}() // CHECK: define internal void @{{__cxx_global_var_init.3|"\?\?__EstaticConstInlineInit@@YAXXZ"}}() // CHECK: %call = call i32 @{{_Z21inlineMakeStaticConstv|"\?inlineMakeStaticConst@@YAHXZ"}}() // CHECK: store i32 %call, i32* @{{_ZL21staticConstInlineInit|staticConstInlineInit}}, align 4 // CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_Z21inlineMakeStaticConstv|"\?inlineMakeStaticConst@@YAHXZ"}}() // CHECK: ret i32 16 // CHECK: define internal void @{{__cxx_global_var_init.4|"\?\?__EstaticNonTrivial@@YAXXZ"}}() // CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* @_ZL16staticNonTrivial, i32 1024\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* @staticNonTrivial, i32 1024\)}} // CHECK: define internal void @{{__cxx_global_var_init.5|"\?\?__EstaticConstNonTrivial@@YAXXZ"}}() // CHECK: call {{void|%class.NonTrivial\*}} {{@_ZN10NonTrivialC[12]Ei\(%class.NonTrivial\* @_ZL21staticConstNonTrivial, i32 2048\)|@"\?\?0NonTrivial@@QEAA@H@Z"\(%class.NonTrivial\* @staticConstNonTrivial, i32 2048\)}} public func readStaticVar() -> CInt { return staticVar } // CHECK: define {{(protected |dllexport )?}}swiftcc i32 @"$s4main13readStaticVars5Int32VyF"() // CHECK: [[VALUE:%.*]] = load i32, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{_ZL9staticVar|staticVar}} to %Ts5Int32V*), i32 0, i32 0), align 4 // CHECK: ret i32 [[VALUE]] public func writeStaticVar(_ v: CInt) { staticVar = v } // CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main14writeStaticVaryys5Int32VF"(i32 %0) // CHECK: store i32 %0, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{_ZL9staticVar|staticVar}} to %Ts5Int32V*), i32 0, i32 0), align 4 public func readStaticNonTrivial() -> NonTrivial { return staticNonTrivial } // CHECK: define {{(protected |dllexport )?}}swiftcc i32 @"$s4main20readStaticNonTrivialSo0dE0VyF"() // CHECK: [[VALUE:%.*]] = load i32, i32* getelementptr inbounds (%TSo10NonTrivialV, %TSo10NonTrivialV* bitcast (%class.NonTrivial* @{{_ZL16staticNonTrivial|staticNonTrivial}} to %TSo10NonTrivialV*), i32 0, i32 0, i32 0), align 4 // CHECK: ret i32 [[VALUE]] public func writeStaticNonTrivial(_ i: NonTrivial) { staticNonTrivial = i } // CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main21writeStaticNonTrivialyySo0dE0VF"(i32 %0) // CHECK: store i32 %0, i32* getelementptr inbounds (%TSo10NonTrivialV, %TSo10NonTrivialV* bitcast (%class.NonTrivial* @{{_ZL16staticNonTrivial|staticNonTrivial}} to %TSo10NonTrivialV*), i32 0, i32 0, i32 0), align 4 func modifyInout(_ c: inout CInt) { c = 42 } public func passingVarAsInout() { modifyInout(&staticVar) } // CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main17passingVarAsInoutyyF"() // CHECK: call swiftcc void @"$s4main11modifyInoutyys5Int32VzF"(%Ts5Int32V* nocapture dereferenceable(4) bitcast (i32* @{{_ZL9staticVar|staticVar}} to %Ts5Int32V*)) // CHECK: define internal void @_GLOBAL__sub_I__swift_imported_modules_() // CHECK: call void @{{__cxx_global_var_init|"\?\?__EstaticVarInit@@YAXXZ"}}() // CHECK: call void @{{__cxx_global_var_init.1|"\?\?__EstaticVarInlineInit@@YAXXZ"}}() // CHECK: call void @{{__cxx_global_var_init.2|"\?\?__EstaticConstInit@@YAXXZ"}}() // CHECK: call void @{{__cxx_global_var_init.3|"\?\?__EstaticConstInlineInit@@YAXXZ"}}() // CHECK: call void @{{__cxx_global_var_init.4|"\?\?__EstaticNonTrivial@@YAXXZ"}}() // CHECK: call void @{{__cxx_global_var_init.5|"\?\?__EstaticConstNonTrivial@@YAXXZ"}}()
apache-2.0
4a284c9bbedea309dbcccf57d429302e
58.75
228
0.708619
3.779254
false
false
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/BindingMessage.swift
5
2494
// // BindingMessage // Mixpanel // // Created by Yarden Eitan on 8/26/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation class BindingRequest: BaseWebSocketMessage { init?(payload: [String: AnyObject]?) { guard let payload = payload else { return nil } super.init(type: MessageType.bindingRequest.rawValue, payload: payload) } override func responseCommand(connection: WebSocketWrapper) -> Operation? { let operation = BlockOperation { [weak connection] in guard let connection = connection else { return } DispatchQueue.main.sync { var bindingCollection = connection.getSessionObjectSynchronized(for: "event_bindings") as? CodelessBindingCollection if bindingCollection == nil { bindingCollection = CodelessBindingCollection() connection.setSessionObjectSynchronized(with: bindingCollection!, for: "event_bindings") } if let payload = self.payload["events"] as? [[String: Any]] { Logger.debug(message: "Loading event bindings: \(payload)") bindingCollection?.updateBindings(payload) } } let response = BindingResponse() response.status = "OK" connection.send(message: response) } return operation } } class BindingResponse: BaseWebSocketMessage { var status: String { get { return payload["status"] as! String } set { payload["status"] = newValue as AnyObject } } init() { super.init(type: MessageType.bindingResponse.rawValue) } } class CodelessBindingCollection { var bindings: [CodelessBinding] = [CodelessBinding]() func updateBindings(_ payload: [[String: Any]]) { var newBindings = [CodelessBinding]() for bindingInfo in payload { if let binding = Codeless.createBinding(object: bindingInfo) { newBindings.append(binding) } } for oldBinding in bindings { oldBinding.stop() } bindings = newBindings for newBinding in bindings { newBinding.execute() } } func cleanup() { for oldBinding in bindings { oldBinding.stop() } bindings.removeAll() } }
mit
c6d971cb1aab15166a6f336425d6ee6f
27.329545
132
0.576815
5.182952
false
false
false
false
wenjunos/DYZB
斗鱼/斗鱼/Classes/Tools/NetTool/DYHttpTool.swift
1
853
// // DYHttpTool.swift // 斗鱼 // // Created by pba on 2017/1/19. // Copyright © 2017年 wenjun. All rights reserved. // import UIKit import Alamofire //请求方式 enum MethodType { case POST case GET } class DYHttpTool: NSObject { class func request(type : MethodType, url : String, parames : [String : Any]? = nil, callBack : @escaping (_ response : Any) -> ()) { //请求类型 let methodType = type == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(url, method: methodType, parameters: parames).responseJSON { (response) in guard let result = response.result.value else { //请求失败 print(response.result.error as Any) return } //请求成功 callBack(result) } } }
mit
196fd0b05247ea475c06ff6036a69eb2
22.941176
137
0.566339
3.990196
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Trivial - 不需要看的题目/119_Pascal's Triangle II.swift
1
1153
// 119_Pascal's Triangle II // https://leetcode.com/problems/pascals-triangle-ii/ // // Created by Honghao Zhang on 10/16/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. // //Note that the row index starts from 0. // // //In Pascal's triangle, each number is the sum of the two numbers directly above it. // //Example: // //Input: 3 //Output: [1,3,3,1] //Follow up: // //Could you optimize your algorithm to use only O(k) extra space? // // 返回第N行的数字 import Foundation class Num119 { // O(n) space // Can just keep one row and update it many times func getRow(_ rowIndex: Int) -> [Int] { var triangle: [[Int]] = [[1]] if rowIndex == 0 { return triangle[0] } for i in 1...rowIndex { // i = 0 -> row1 let lastRow = triangle[i - 1] var row = Array(repeating: 0, count: i + 1) for j in 0..<(i + 1) { row[j] = ((j - 1) < 0 ? 0 : lastRow[j - 1]) + (j >= lastRow.count ? 0 : lastRow[j]) } triangle.append(row) } return triangle[rowIndex] } }
mit
5ccecd6868643e26fe92ceaf57b3e466
23.695652
96
0.603873
3.173184
false
false
false
false
swift-lang/swift-k
tests/apps/050-stomp-skel-2.swift
2
2202
type file; app (file output) stomp(file input) { stomp @input @output; } // Creates the output and a few files named directory/pg-*.out app (file output, file index) pg(file input, string directory) { pg @input directory @output @index; } app (file output) sph(file tarfile, string entry) { sph @tarfile @entry @output; } app (file output) gpg(file input[]) { // Put output first for easier command-line processing gpg @output @input; } (file output) model(file input, int iter) { tracef("model input: %M\n", input); string directory = @strcat("run-", iter); tracef("directory: %s\n", directory); string stomp_out_name = @strcat(directory, "/stomp.out"); tracef("stomp_out_name: %s\n", stomp_out_name); file stomp_out<single_file_mapper;file=stomp_out_name>; stomp_out = stomp(input); tracef("stomp_out: %M\n", stomp_out); string pg_tar_name = @strcat(directory, "/pg.tar"); file pg_tar<single_file_mapper;file=pg_tar_name>; string pg_index_name = @strcat(directory, "/pg.index"); file pg_index<single_file_mapper;file=pg_index_name>; (pg_tar, pg_index) = pg(stomp_out, directory); tracef("pg output: %M %M\n", pg_tar, pg_index); string pg_entry_names[] = readData(pg_index); file pg_entries[]<array_mapper;files=pg_entry_names>; string sph_transform = @strcat(directory, "/sph-\\1"); file sph_outputs[]<structured_regexp_mapper; source=pg_entries, match=".*/pg-(.*)", transform=sph_transform>; foreach pg_entry, i in pg_entries { tracef("sph: %M:%s -> %M\n", pg_tar, pg_entry_names[i], sph_outputs[i]); sph_outputs[i] = sph(pg_tar, pg_entry_names[i]); } output = gpg(sph_outputs); tracef("model output: %M\n", output); } int iterations = @toint(@arg("iters")); file inputs[]; file input0<"data-0.txt">; tracef("starting with: %M\n", input0); inputs[0] = input0; iterate iter { tracef("iter: %i\n", iter); string output_name = @strcat("data-", iter+1, ".txt"); tracef("output_name: %s\n", output_name); file output<single_file_mapper;file=output_name>; output = model(inputs[iter], iter); inputs[iter+1] = output; } until (iter > iterations);
apache-2.0
b99eb6d23ffd210ad4a9b0caa1092dd7
29.164384
62
0.641689
3.054092
false
false
false
false
tyleryouk11/space-hero
Stick-Hero/StickHeroGameScene.swift
1
21603
// // StickHeroGameScene.swift // Stick-Hero // // Created by 顾枫 on 15/6/19. // Copyright © 2015年 koofrank. All rights reserved. // import SpriteKit import GoogleMobileAds import UIKit class StickHeroGameScene: SKScene, SKPhysicsContactDelegate { var gameOver = false { willSet { if (newValue) { checkHighScoreAndStore() let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? gameOverLayer?.runAction(SKAction.moveDistance(CGVectorMake(0, 100), fadeInWithDuration: 0.2)) } } } var interstitial: GADInterstitial? let StackHeight:CGFloat = 650.0 let StackMaxWidth:CGFloat = 300.0 let StackMinWidth:CGFloat = 100.0 let gravity:CGFloat = -100.0 let StackGapMinWidth:Int = 80 let HeroSpeed:CGFloat = 760 let StoreScoreName = "com.stickHero.score" var isBegin = false var isEnd = false var leftStack:SKShapeNode? var rightStack:SKShapeNode? var nextLeftStartX:CGFloat = 0 var stickHeight:CGFloat = 0 var score:Int = 0 { willSet { let scoreBand = childNodeWithName(StickHeroGameSceneChildName.ScoreName.rawValue) as? SKLabelNode scoreBand?.text = "\(newValue)" scoreBand?.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration: 0.1), SKAction.scaleTo(1, duration: 0.1)])) if (newValue == 1) { let tip = childNodeWithName(StickHeroGameSceneChildName.TipName.rawValue) as? SKLabelNode tip?.runAction(SKAction.fadeAlphaTo(0, duration: 0.4)) } } } lazy var playAbleRect:CGRect = { let maxAspectRatio:CGFloat = 16.0/9.0 // iPhone 5" let maxAspectRatioWidth = self.size.height / maxAspectRatio let playableMargin = (self.size.width - maxAspectRatioWidth) / 2.0 return CGRectMake(playableMargin, 0, maxAspectRatioWidth, self.size.height) }() lazy var walkAction:SKAction = { var textures:[SKTexture] = [] for i in 0...1 { let texture = SKTexture(imageNamed: "human\(i + 1).png") textures.append(texture) } let action = SKAction.animateWithTextures(textures, timePerFrame: 0.15, resize: true, restore: true) return SKAction.repeatActionForever(action) }() //MARK: - override override init(size: CGSize) { super.init(size: size) anchorPoint = CGPointMake(0.5, 0.5) physicsWorld.contactDelegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { start() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { guard !gameOver else { let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let location = touches.first?.locationInNode(gameOverLayer!) let retry = gameOverLayer!.nodeAtPoint(location!) if (retry.name == StickHeroGameSceneChildName.RetryButtonName.rawValue) { retry.runAction(SKAction.sequence([SKAction.setTexture(SKTexture(imageNamed: "button_retry_down"), resize: false), SKAction.waitForDuration(0.3)]), completion: {[unowned self] () -> Void in self.restart() }) } return } if !isBegin && !isEnd { isBegin = true let stick = loadStick() let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let action = SKAction.resizeToHeight(CGFloat(DefinedScreenHeight - StackHeight), duration: 1.5) stick.runAction(action, withKey:StickHeroGameSceneActionKey.StickGrowAction.rawValue) let scaleAction = SKAction.sequence([SKAction.scaleYTo(0.9, duration: 0.05), SKAction.scaleYTo(1, duration: 0.05)]) let loopAction = SKAction.group([SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowAudioName.rawValue, waitForCompletion: true)]) stick.runAction(SKAction.repeatActionForever(loopAction), withKey: StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) hero.runAction(SKAction.repeatActionForever(scaleAction), withKey: StickHeroGameSceneActionKey.HeroScaleAction.rawValue) return } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if isBegin && !isEnd { isEnd = true let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode hero.removeActionForKey(StickHeroGameSceneActionKey.HeroScaleAction.rawValue) hero.runAction(SKAction.scaleYTo(1, duration: 0.04)) let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAction.rawValue) stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) stick.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowOverAudioName.rawValue, waitForCompletion: false)) stickHeight = stick.size.height; let action = SKAction.rotateToAngle(CGFloat(-M_PI / 2), duration: 0.4, shortestUnitArc: true) let playFall = SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickFallAudioName.rawValue, waitForCompletion: false) stick.runAction(SKAction.sequence([SKAction.waitForDuration(0.2), action, playFall]), completion: {[unowned self] () -> Void in self.heroGo(self.checkPass()) }) } } func start() { loadBackground() loadScoreBackground() loadScore() //loadTip() /* if (interstitial!.isReady) { interstitial!.presentFromRootViewController(GameViewController) }*/ loadGameOverLayer() leftStack = loadStacks(false, startLeftPoint: playAbleRect.origin.x) self.removeMidTouch(false, left:true) loadHero() let maxGap = Int(playAbleRect.width - StackMaxWidth - (leftStack?.frame.size.width)!) let gap = CGFloat(randomInRange(StackGapMinWidth...maxGap)) rightStack = loadStacks(false, startLeftPoint: nextLeftStartX + gap) gameOver = false } func restart() { isBegin = false isEnd = false score = 0 nextLeftStartX = 0 removeAllChildren() start() } private func checkPass() -> Bool { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let rightPoint = DefinedScreenWidth / 2 + stick.position.x + self.stickHeight guard rightPoint < self.nextLeftStartX else { return false } guard (CGRectIntersectsRect((leftStack?.frame)!, stick.frame) && CGRectIntersectsRect((rightStack?.frame)!, stick.frame)) else { return false } self.checkTouchMidStack() return true } private func checkTouchMidStack() { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let stackMid = rightStack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode let newPoint = stackMid.convertPoint(CGPointMake(-10, 10), toNode: self) if ((stick.position.x + self.stickHeight) >= newPoint.x && (stick.position.x + self.stickHeight) <= newPoint.x + 20) { loadPerfect() self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickTouchMidAudioName.rawValue, waitForCompletion: false)) score++ } } private func removeMidTouch(animate:Bool, left:Bool) { let stack = left ? leftStack : rightStack let mid = stack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode if (animate) { mid.runAction(SKAction.fadeAlphaTo(0, duration: 0.3)) } else { mid.removeFromParent() } } private func heroGo(pass:Bool) { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode guard pass else { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let dis:CGFloat = stick.position.x + self.stickHeight let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move, completion: {[unowned self] () -> Void in stick.runAction(SKAction.rotateToAngle(CGFloat(-M_PI), duration: 0.4)) hero.physicsBody!.affectedByGravity = true hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.DeadAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.runAction(SKAction.waitForDuration(0.5), completion: {[unowned self] () -> Void in self.gameOver = true }) }) return } let dis:CGFloat = -DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20 let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move) { [unowned self]() -> Void in self.score++ hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.VictoryAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.moveStackAndCreateNew() } } private func checkHighScoreAndStore() { let highScore = NSUserDefaults.standardUserDefaults().integerForKey(StoreScoreName) if (score > Int(highScore)) { showHighScore() NSUserDefaults.standardUserDefaults().setInteger(score, forKey: StoreScoreName) NSUserDefaults.standardUserDefaults().synchronize() } } private func showHighScore() { self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.HighScoreAudioName.rawValue, waitForCompletion: false)) let wait = SKAction.waitForDuration(0.4) let grow = SKAction.scaleTo(1.5, duration: 0.4) grow.timingMode = .EaseInEaseOut let explosion = starEmitterActionAtPosition(CGPointMake(0, 300)) let shrink = SKAction.scaleTo(1, duration: 0.2) let idleGrow = SKAction.scaleTo(1.2, duration: 0.4) idleGrow.timingMode = .EaseInEaseOut let idleShrink = SKAction.scaleTo(1, duration: 0.4) let pulsate = SKAction.repeatActionForever(SKAction.sequence([idleGrow, idleShrink])) let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let highScoreLabel = gameOverLayer?.childNodeWithName(StickHeroGameSceneChildName.HighScoreName.rawValue) as SKNode? highScoreLabel?.runAction(SKAction.sequence([wait, explosion, grow, shrink]), completion: { () -> Void in highScoreLabel?.runAction(pulsate) }) } private func moveStackAndCreateNew() { let action = SKAction.moveBy(CGVectorMake(-nextLeftStartX + (rightStack?.frame.size.width)! + playAbleRect.origin.x - 2, 0), duration: 0.3) rightStack?.runAction(action) self.removeMidTouch(true, left:false) let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode hero.runAction(action) stick.runAction(SKAction.group([SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), SKAction.fadeAlphaTo(0, duration: 0.3)])) { () -> Void in stick.removeFromParent() } leftStack?.runAction(SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), completion: {[unowned self] () -> Void in self.leftStack?.removeFromParent() let maxGap = Int(self.playAbleRect.width - (self.rightStack?.frame.size.width)! - self.StackMaxWidth) let gap = CGFloat(randomInRange(self.StackGapMinWidth...maxGap)) self.leftStack = self.rightStack self.rightStack = self.loadStacks(true, startLeftPoint:self.playAbleRect.origin.x + (self.rightStack?.frame.size.width)! + gap) }) } } //MARK: - load node private extension StickHeroGameScene { func loadBackground() { guard let _ = childNodeWithName("background") as! SKSpriteNode? else { let texture = SKTexture(image: UIImage(named: "stick_background.jpg")!) let node = SKSpriteNode(texture: texture) node.size = texture.size() node.zPosition = StickHeroGameSceneZposition.BackgroundZposition.rawValue self.physicsWorld.gravity = CGVectorMake(0, gravity) addChild(node) return } } func loadScore() { let scoreBand = SKLabelNode(fontNamed: "Arial") scoreBand.name = StickHeroGameSceneChildName.ScoreName.rawValue scoreBand.text = "0" scoreBand.position = CGPointMake(0, DefinedScreenHeight / 2 - 200) scoreBand.fontColor = SKColor.whiteColor() scoreBand.fontSize = 100 scoreBand.zPosition = StickHeroGameSceneZposition.ScoreZposition.rawValue scoreBand.horizontalAlignmentMode = .Center addChild(scoreBand) } func loadScoreBackground() { let back = SKShapeNode(rect: CGRectMake(0-120, 1024-200-30, 240, 140), cornerRadius: 20) back.zPosition = StickHeroGameSceneZposition.ScoreBackgroundZposition.rawValue back.fillColor = SKColor.blackColor().colorWithAlphaComponent(0.3) back.strokeColor = SKColor.blackColor().colorWithAlphaComponent(0.3) addChild(back) } func loadHero() { let hero = SKSpriteNode(imageNamed: "human1") hero.name = StickHeroGameSceneChildName.HeroName.rawValue hero.position = CGPointMake(-DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20, -DefinedScreenHeight / 2 + StackHeight + hero.size.height / 2 - 4) hero.zPosition = StickHeroGameSceneZposition.HeroZposition.rawValue hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(16, 18)) hero.physicsBody?.affectedByGravity = false hero.physicsBody?.allowsRotation = false addChild(hero) } /*func loadTip() { let tip = SKLabelNode(fontNamed: "HelveticaNeue-Bold") tip.name = StickHeroGameSceneChildName.TipName.rawValue tip.text = "将手放在屏幕使竿变长" tip.position = CGPointMake(0, DefinedScreenHeight / 2 - 350) tip.fontColor = SKColor.blackColor() tip.fontSize = 52 tip.zPosition = StickHeroGameSceneZposition.TipZposition.rawValue tip.horizontalAlignmentMode = .Center addChild(tip) }*/ func loadPerfect() { defer { let perfect = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? let sequence = SKAction.sequence([SKAction.fadeAlphaTo(1, duration: 0.3), SKAction.fadeAlphaTo(0, duration: 0.3)]) let scale = SKAction.sequence([SKAction.scaleTo(1.4, duration: 0.3), SKAction.scaleTo(1, duration: 0.3)]) perfect!.runAction(SKAction.group([sequence, scale])) } guard let _ = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? else { let perfect = SKLabelNode(fontNamed: "Arial") perfect.text = "Perfect +1" perfect.name = StickHeroGameSceneChildName.PerfectName.rawValue perfect.position = CGPointMake(0, -100) perfect.fontColor = SKColor.whiteColor() perfect.fontSize = 75 perfect.zPosition = StickHeroGameSceneZposition.PerfectZposition.rawValue perfect.horizontalAlignmentMode = .Center perfect.alpha = 0 addChild(perfect) return } } func loadStick() -> SKSpriteNode { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = SKSpriteNode(color: SKColor.whiteColor(), size: CGSizeMake(12, 1)) stick.zPosition = StickHeroGameSceneZposition.StickZposition.rawValue stick.name = StickHeroGameSceneChildName.StickName.rawValue stick.anchorPoint = CGPointMake(0.5, 0); stick.position = CGPointMake(hero.position.x + hero.size.width / 2 + 18, hero.position.y - hero.size.height / 2) addChild(stick) return stick } func loadStacks(animate: Bool, startLeftPoint: CGFloat) -> SKShapeNode { let max:Int = Int(StackMaxWidth / 10) let min:Int = Int(StackMinWidth / 10) let width:CGFloat = CGFloat(randomInRange(min...max) * 10) let height:CGFloat = StackHeight let stack = SKShapeNode(rectOfSize: CGSizeMake(width, height)) stack.fillColor = SKColor.whiteColor() stack.strokeColor = SKColor.whiteColor() stack.zPosition = StickHeroGameSceneZposition.StackZposition.rawValue stack.name = StickHeroGameSceneChildName.StackName.rawValue if (animate) { stack.position = CGPointMake(DefinedScreenWidth / 2, -DefinedScreenHeight / 2 + height / 2) stack.runAction(SKAction.moveToX(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, duration: 0.3), completion: {[unowned self] () -> Void in self.isBegin = false self.isEnd = false }) } else { stack.position = CGPointMake(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, -DefinedScreenHeight / 2 + height / 2) } addChild(stack) let mid = SKShapeNode(rectOfSize: CGSizeMake(20, 20)) mid.fillColor = SKColor.redColor() mid.strokeColor = SKColor.redColor() mid.zPosition = StickHeroGameSceneZposition.StackMidZposition.rawValue mid.name = StickHeroGameSceneChildName.StackMidName.rawValue mid.position = CGPointMake(0, height / 2 - 20 / 2) stack.addChild(mid) nextLeftStartX = width + startLeftPoint return stack } func loadGameOverLayer() { let node = SKNode() node.alpha = 0 node.name = StickHeroGameSceneChildName.GameOverLayerName.rawValue node.zPosition = StickHeroGameSceneZposition.GameOverZposition.rawValue addChild(node) let label = SKLabelNode(fontNamed: "HelveticaNeue-Bold") label.text = "Game Over" label.fontColor = SKColor.redColor() label.fontSize = 150 label.position = CGPointMake(0, 100) label.horizontalAlignmentMode = .Center node.addChild(label) let retry = SKSpriteNode(imageNamed: "button_retry_up") retry.name = StickHeroGameSceneChildName.RetryButtonName.rawValue retry.position = CGPointMake(0, -200) node.addChild(retry) let highScore = SKLabelNode(fontNamed: "AmericanTypewriter") highScore.text = "Highscore!" highScore.fontColor = UIColor.whiteColor() highScore.fontSize = 50 highScore.name = StickHeroGameSceneChildName.HighScoreName.rawValue highScore.position = CGPointMake(0, 300) highScore.horizontalAlignmentMode = .Center highScore.setScale(0) node.addChild(highScore) } //MARK: - Action func starEmitterActionAtPosition(position: CGPoint) -> SKAction { let emitter = SKEmitterNode(fileNamed: "StarExplosion") emitter?.position = position emitter?.zPosition = StickHeroGameSceneZposition.EmitterZposition.rawValue emitter?.alpha = 0.6 addChild((emitter)!) let wait = SKAction.waitForDuration(0.15) return SKAction.runBlock({ () -> Void in emitter?.runAction(wait) }) } }
mit
b70fc21fda01c7cd66303ac2315cfcb0
41.140625
205
0.645393
5.279178
false
false
false
false
MrZoidberg/metapp
metapp/Pods/RealmSwift/RealmSwift/ObjectSchema.swift
26
4638
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 Realm #if swift(>=3.0) /** This class represents Realm model object schemas. When using Realm, `ObjectSchema` instances allow performing migrations and introspecting the database's schema. Object schemas map to tables in the core database. */ public final class ObjectSchema: CustomStringConvertible { // MARK: Properties internal let rlmObjectSchema: RLMObjectSchema /** An array of `Property` instances representing the managed properties of a class described by the schema. - see: `Property` */ public var properties: [Property] { return rlmObjectSchema.properties.map { Property($0) } } /// The name of the class the schema describes. public var className: String { return rlmObjectSchema.className } /// The property which serves as the primary key for the class the schema describes, if any. public var primaryKeyProperty: Property? { if let rlmProperty = rlmObjectSchema.primaryKeyProperty { return Property(rlmProperty) } return nil } /// A human-readable description of the properties contained in the object schema. public var description: String { return rlmObjectSchema.description } // MARK: Initializers internal init(_ rlmObjectSchema: RLMObjectSchema) { self.rlmObjectSchema = rlmObjectSchema } // MARK: Property Retrieval /// Returns the property with the given name, if it exists. public subscript(propertyName: String) -> Property? { if let rlmProperty = rlmObjectSchema[propertyName] { return Property(rlmProperty) } return nil } } // MARK: Equatable extension ObjectSchema: Equatable {} /// Returns whether the two object schemas are equal. public func == (lhs: ObjectSchema, rhs: ObjectSchema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmObjectSchema.isEqual(to: rhs.rlmObjectSchema) } #else /** This class represents Realm model object schemas. When using Realm, `ObjectSchema` instances allow performing migrations and introspecting the database's schema. Object schemas map to tables in the core database. */ public final class ObjectSchema: CustomStringConvertible { // MARK: Properties internal let rlmObjectSchema: RLMObjectSchema /** An array of `Property` instances representing the managed properties of a class described by the schema. - see: `Property` */ public var properties: [Property] { return rlmObjectSchema.properties.map { Property($0) } } /// The name of the class the schema describes. public var className: String { return rlmObjectSchema.className } /// The property which serves as the primary key for the class the schema describes, if any. public var primaryKeyProperty: Property? { if let rlmProperty = rlmObjectSchema.primaryKeyProperty { return Property(rlmProperty) } return nil } /// Returns a human-readable description of the properties contained in the object schema. public var description: String { return rlmObjectSchema.description } // MARK: Initializers internal init(_ rlmObjectSchema: RLMObjectSchema) { self.rlmObjectSchema = rlmObjectSchema } // MARK: Property Retrieval /// Returns the property with the given name, if it exists. public subscript(propertyName: String) -> Property? { if let rlmProperty = rlmObjectSchema[propertyName] { return Property(rlmProperty) } return nil } } // MARK: Equatable extension ObjectSchema: Equatable {} /// Returns whether the two object schemas are equal. public func == (lhs: ObjectSchema, rhs: ObjectSchema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmObjectSchema.isEqualToObjectSchema(rhs.rlmObjectSchema) } #endif
mpl-2.0
dac5971024f967b894fb337011af4dd9
29.715232
112
0.6837
5.147614
false
false
false
false
ikesyo/Swiftz
SwiftzTests/ProxySpec.swift
2
3906
// // ProxySpec.swift // Swiftz // // Created by Robert Widmann on 7/20/15. // Copyright © 2015 TypeLift. All rights reserved. // This file may be a carefully crafted joke. // import XCTest import Swiftz import SwiftCheck extension Proxy : Arbitrary { public static var arbitrary : Gen<Proxy<T>> { return Gen.pure(Proxy()) } } extension Proxy : CoArbitrary { public static func coarbitrary<C>(_ : Proxy<T>) -> (Gen<C> -> Gen<C>) { return identity } } class ProxySpec : XCTestCase { func testProperties() { property("Proxies obey reflexivity") <- forAll { (l : Proxy<Int>) in return l == l } property("Proxies obey symmetry") <- forAll { (x : Proxy<Int>, y : Proxy<Int>) in return (x == y) == (y == x) } property("Proxies obey transitivity") <- forAll { (x : Proxy<Int>, y : Proxy<Int>, z : Proxy<Int>) in return (x == y) && (y == z) ==> (x == z) } property("Proxies obey negation") <- forAll { (x : Proxy<Int>, y : Proxy<Int>) in return (x != y) == !(x == y) } property("Proxy's bounds are unique") <- forAll { (x : Proxy<Int>) in return (Proxy.minBound() == x) == (Proxy.maxBound() == x) } property("Proxy obeys the Functor identity law") <- forAll { (x : Proxy<Int>) in return (x.fmap(identity)) == identity(x) } property("Proxy obeys the Functor composition law") <- forAll { (f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>, x : Proxy<Int>) in return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow)) } property("Proxy obeys the Applicative identity law") <- forAll { (x : Proxy<Int>) in return (Proxy.pure(identity) <*> x) == x } property("Proxy obeys the Applicative homomorphism law") <- forAll { (f : ArrowOf<Int, Int>, x : Int) in return (Proxy.pure(f.getArrow) <*> Proxy.pure(x)) == Proxy.pure(f.getArrow(x)) } property("Proxy obeys the Applicative interchange law") <- forAll { (u : Proxy<Int -> Int>, y : Int) in return (u <*> Proxy.pure(y)) == (Proxy.pure({ f in f(y) }) <*> u) } property("Proxy obeys the first Applicative composition law") <- forAll { (f : Proxy<Int -> Int>, g : Proxy<Int -> Int>, x : Proxy<Int>) in return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x)) } property("Proxy obeys the second Applicative composition law") <- forAll { (f : Proxy<Int -> Int>, g : Proxy<Int -> Int>, x : Proxy<Int>) in return (Proxy<(Int -> Int) -> (Int -> Int) -> Int -> Int>.pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x)) } property("Proxy obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Proxy<Int>>) in let f = { $0 } • fa.getArrow return (Proxy.pure(a) >>- f) == f(a) } property("Proxy obeys the Monad right identity law") <- forAll { (m : Proxy<Int>) in return (m >>- Proxy.pure) == m } property("Proxy obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, ArrayOf<Int>>, ga : ArrowOf<Int, ArrayOf<Int>>, m : ArrayOf<Int>) in let f = { $0.getArray } • fa.getArrow let g = { $0.getArray } • ga.getArrow return ((m.getArray >>- f) >>- g) == (m.getArray >>- { x in f(x) >>- g }) } property("Proxy obeys the Comonad identity law") <- forAll { (x : Proxy<Int>) in return x.extend({ $0.extract() }) == x } // Can't test ⊥ == ⊥ in this language. // property("Proxy obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>) in // return forAll { (x : Proxy<Int>) in // let f : Proxy<Int> -> Int = ff.getArrow • const(0) // return x.extend(f).extract() == f(x) // } // } property("Proxy obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>, gg : ArrowOf<Int, Int>) in return forAll { (x : Proxy<Int>) in let f : Proxy<Int> -> Int = ff.getArrow • const(0) let g : Proxy<Int> -> Int = gg.getArrow • const(0) return x.extend(f).extend(g) == x.extend({ f($0.extend(g)) }) } } } }
bsd-3-clause
f33cc1d6993db023738916d67bb98927
33.669643
153
0.589493
3.05989
false
false
false
false
AlwaysRightInstitute/SwiftySecurity
SwiftySecurity/SecTrust.swift
1
2805
// // SecTrust.swift // TestSwiftyDocker // // Created by Helge Hess on 08/05/15. // Copyright (c) 2015 Helge Hess. All rights reserved. // import Foundation // Note: a trust seems to be more like an evaluation context public extension SecTrust { public var count : Int { return SecTrustGetCertificateCount(self) } public subscript(index: Int) -> SecCertificate? { // Swift.Unmanaged<ObjectiveC.SecCertificate> // TBD: is unretained OK? (Get = Retained or not? :-) return SecTrustGetCertificateAtIndex(self, index) } /* anchor certs */ public var anchorCertificates : [ SecCertificate ] { set { setAnchorCertificates(newValue) } get { var valueCopy : CFArray? let _ = SecTrustCopyCustomAnchorCertificates(self, &valueCopy) if valueCopy == nil { return [] } return valueCopy! as! [ SecCertificate ] } } public var trustOwnCertificatesOnly : Bool? { set { let _ = SecTrustSetAnchorCertificatesOnly(self, newValue ?? false) } get { return nil // there is no getter for this? } } public func setAnchorCertificates(certificates: SecCertificate...) -> OSStatus { return setAnchorCertificates(certificates) } public func setAnchorCertificates(certificates: [ SecCertificate ]) -> OSStatus { return SecTrustSetAnchorCertificates(self, certificates) } public static var anchorCertificates : [ SecCertificate ] { // those are the system certificates var valueCopy : CFArray? let _ = SecTrustCopyAnchorCertificates(&valueCopy) if valueCopy == nil { return [] } return valueCopy! as! [ SecCertificate ] } /* evaluation */ public func evaluate() -> ( OSStatus, SecTrustResultType ) { var result : SecTrustResultType = 0 let status = SecTrustEvaluate(self, &result) return ( status, result ) } public func evaluate(queue: dispatch_queue_t, cb: SecTrustCallback) -> OSStatus { return SecTrustEvaluateAsync(self, queue, cb) } public var lastResult : ( OSStatus, SecTrustResultType ) { var result : SecTrustResultType = 0 let status = SecTrustGetTrustResult(self, &result) return ( status, result ) } /* keys */ public var publicKey : SecKey? { return SecTrustCopyPublicKey(self) } /* times */ public var verifyTimestamp : CFAbsoluteTime { set { let newTime = CFDateCreate(nil, newValue) let _ = SecTrustSetVerifyDate(self, newTime) } get { return SecTrustGetVerifyTime(self) } } public var verifyDate : CFDate { set { verifyTimestamp = CFDateGetAbsoluteTime(newValue) } get { return CFDateCreate(nil, verifyTimestamp) } } }
mit
8762ee340a0fc539035a60ec9234c651
23.181034
76
0.647415
4.698492
false
false
false
false
longitachi/ZLPhotoBrowser
Example/Example/Extension/UIColor+Hex.swift
1
533
// // UIColor+Hex.swift // Example // // Created by long on 2022/7/1. // import UIKit extension UIColor { class func color(hexRGB: Int64, alpha: CGFloat = 1.0) -> UIColor { let r: Int64 = (hexRGB & 0xFF0000) >> 16 let g: Int64 = (hexRGB & 0xFF00) >> 8 let b: Int64 = (hexRGB & 0xFF) let color = UIColor( red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha ) return color } }
mit
b19dda4d2a22d70438530e92b3bd95d7
20.32
70
0.499062
3.230303
false
false
false
false
russbishop/swift
test/SILGen/arguments.swift
1
2689
// RUN: %target-swift-frontend -module-name Swift -parse-stdlib -emit-silgen %s | FileCheck %s struct Int {} struct Float {} struct UnicodeScalar {} // Minimal implementation to support varargs. struct Array<T> { } func _allocateUninitializedArray<T>(_: Builtin.Word) -> (Array<T>, Builtin.RawPointer) { Builtin.int_trap() } func _deallocateUninitializedArray<T>(_: Array<T>) {} var i:Int, f:Float, c:UnicodeScalar func arg_tuple(x x: Int, y: Float) {} // CHECK-LABEL: sil hidden @_TFs9arg_tupleFT1xSi1ySf_T_ // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Float): arg_tuple(x: i, y: f) func arg_deep_tuples(x x: Int, y: (Float, UnicodeScalar)) {} // CHECK-LABEL: sil hidden @_TFs15arg_deep_tuplesFT1xSi1yTSfSc__T_ // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y_0:%[0-9]+]] : $Float, [[Y_1:%[0-9]+]] : $UnicodeScalar): arg_deep_tuples(x:i, y:(f, c)) var unnamed_subtuple = (f, c) arg_deep_tuples(x: i, y: unnamed_subtuple) // FIXME rdar://problem/12985801 -- tuple conversion confuses named fields // of a subtuple with those of outer tuple //var named_subtuple = (x:f, y:c) //arg_deep_tuples(i, named_subtuple) func arg_deep_tuples_2(x x: Int, _: (y: Float, z: UnicodeScalar)) {} // CHECK-LABEL: sil hidden @_TFs17arg_deep_tuples_2FT1xSiT1ySf1zSc__T_ // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Float, [[Z:%[0-9]+]] : $UnicodeScalar): arg_deep_tuples_2(x: i, (f, c)) arg_deep_tuples_2(x: i, unnamed_subtuple) // FIXME rdar://problem/12985103 -- tuples don't convert recursively, so // #var x = (1, (2.0, '3')); arg_deep_tuples_2(x)# doesn't type check //arg_deep_tuples_2(deep_named_tuple) func arg_default_tuple(x x: Int = i, y: Float = f) {} // CHECK-LABEL: sil hidden @_TFs17arg_default_tupleFT1xSi1ySf_T_ // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Float): arg_default_tuple() arg_default_tuple(x:i) arg_default_tuple(y:f) arg_default_tuple(x:i, y:f) func variadic_arg_1(_ x: Int...) {} // CHECK-LABEL: sil hidden @_TFs14variadic_arg_1 // CHECK: bb0([[X:%[0-9]+]] : $Array<Int>): variadic_arg_1() variadic_arg_1(i) variadic_arg_1(i, i, i) func variadic_arg_2(_ x: Int, _ y: Float...) {} // CHECK-LABEL: sil hidden @_TFs14variadic_arg_2 // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Array<Float>): variadic_arg_2(i) variadic_arg_2(i, f) variadic_arg_2(i, f, f, f) func variadic_arg_3(_ y: Float..., x: Int) {} // CHECK-LABEL: sil hidden @_TFs14variadic_arg_3 // CHECK: bb0([[Y:%[0-9]+]] : $Array<Float>, [[X:%[0-9]+]] : $Int): variadic_arg_3(x: i) variadic_arg_3(f, x: i) variadic_arg_3(f, f, f, x: i) protocol Runcible {} extension Int : Runcible {} func variadic_address_only_arg(_ x: Runcible...) {} variadic_address_only_arg(i)
apache-2.0
7b4bdc183477aeed2b9644a1d7b860cb
29.213483
96
0.628858
2.57814
false
false
false
false
jtbandes/swift
test/APINotes/versioned-objc.swift
2
7796
// RUN: rm -rf %t && mkdir -p %t // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s // RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s // REQUIRES: objc_interop import APINotesFrameworkTest // CHECK-DIAGS-4-NOT: versioned-objc.swift:[[@LINE-1]]: class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember { // CHECK-DIAGS-3: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied func requirement() -> Any? { return nil } } func testNonGeneric() { // CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int' let _: Int = NewlyGenericSub.defaultElement() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: generic parameter 'Element' could not be inferred // CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub' let _: Int = NewlyGenericSub<Base>.defaultElement() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int' } func testRenamedGeneric() { // CHECK-DIAGS-3-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: OldRenamedGeneric<Base> = RenamedGeneric<Base>() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' // CHECK-DIAGS-3-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric' let _: RenamedGeneric<Base> = OldRenamedGeneric<Base>() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric' class SwiftClass {} // CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: OldRenamedGeneric<SwiftClass> = RenamedGeneric<SwiftClass>() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' // CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' let _: RenamedGeneric<SwiftClass> = OldRenamedGeneric<SwiftClass>() // CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base' } func testRenamedClassMembers(obj: ClassWithManyRenames) { // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(swift3Factory:)' _ = ClassWithManyRenames.classWithManyRenamesForInt(0) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(for:)' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(forInt:)' has been replaced by 'init(swift3Factory:)' _ = ClassWithManyRenames(forInt: 0) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(forInt:)' has been replaced by 'init(for:)' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift3Factory: 0) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Factory:)' has been replaced by 'init(for:)' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(for:)' has been replaced by 'init(swift3Factory:)' _ = ClassWithManyRenames(for: 0) // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift3Boolean:)' _ = ClassWithManyRenames(boolean: false) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames(swift3Boolean: false) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift3Boolean:)' _ = ClassWithManyRenames(finalBoolean: false) // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift3DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift3DoImportantThings() // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift3DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift3ClassProperty' _ = ClassWithManyRenames.importantClassProperty // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = ClassWithManyRenames.swift3ClassProperty // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift3ClassProperty' _ = ClassWithManyRenames.finalClassProperty // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: } func testRenamedProtocolMembers(obj: ProtoWithManyRenames) { // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift3Boolean:)' _ = type(of: obj).init(boolean: false) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).init(swift3Boolean: false) // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Boolean:)' has been renamed to 'init(finalBoolean:)' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift3Boolean:)' _ = type(of: obj).init(finalBoolean: false) // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift3DoImportantThings()' obj.doImportantThings() // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: obj.swift3DoImportantThings() // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3DoImportantThings()' has been renamed to 'finalDoImportantThings()' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift3DoImportantThings()' obj.finalDoImportantThings() // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift3ClassProperty' _ = type(of: obj).importantClassProperty // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}: _ = type(of: obj).swift3ClassProperty // CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3ClassProperty' has been renamed to 'finalClassProperty' // CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift3ClassProperty' _ = type(of: obj).finalClassProperty // CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}: } let unrelatedDiagnostic: Int = nil
apache-2.0
f9dde76ceb54846b3734fbb266429b6c
53.517483
227
0.657132
3.675625
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/SMSValidPasscodeLogin/Login/LoginViewController.swift
2
7121
// // LoginViewController.swift // Yona // // Created by Chandan on 05/04/16. // Copyright © 2016 Yona. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet var codeView:UIView! @IBOutlet var infoLabel: UILabel! @IBOutlet var scrollView: UIScrollView! @IBOutlet var pinResetButton: UIButton! @IBOutlet var errorLabel: UILabel! private var colorX : UIColor = UIColor.yiWhiteColor() var posi:CGFloat = 0.0 var loginAttempts:Int = 1 private var codeInputView: CodeInputView? private var totalAttempts : Int = 5 @IBOutlet var gradientView: GradientView! override func viewDidLoad() { super.viewDidLoad() //Nav bar Back button. self.navigationItem.hidesBackButton = true self.navigationController?.setNavigationBarHidden(true, animated: false) dispatch_async(dispatch_get_main_queue(), { if NSUserDefaults.standardUserDefaults().boolForKey(YonaConstants.nsUserDefaultsKeys.isBlocked) { self.pinResetButton.hidden = false } else { self.pinResetButton.hidden = true } self.gradientView.colors = [UIColor.yiGrapeTwoColor(), UIColor.yiGrapeTwoColor()] }) UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) codeInputView = CodeInputView(frame: CGRect(x: 0, y: 0, width: 260, height: 55)) if codeInputView != nil { codeInputView!.delegate = self codeInputView?.secure = true codeView.addSubview(codeInputView!) codeInputView!.becomeFirstResponder() } if NSUserDefaults.standardUserDefaults().boolForKey(YonaConstants.nsUserDefaultsKeys.isBlocked) { self.pinResetButton.hidden = false self.displayAlertMessage("Login", alertDescription: NSLocalizedString("login.user.errorinfoText", comment: "")) errorLabel.hidden = false errorLabel.text = NSLocalizedString("login.user.errorinfoText", comment: "") return; } //keyboard functions let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector.keyboardWasShown, name: UIKeyboardDidShowNotification, object: nil) notificationCenter.addObserver(self, selector: Selector.keyboardWillBeHidden, name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } } extension LoginViewController: KeyboardProtocol { func keyboardWasShown (notification: NSNotification) { let viewHeight = self.view.frame.size.height let info : NSDictionary = notification.userInfo! let keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size let keyboardInset = keyboardSize.height - viewHeight/3 let pos = (pinResetButton?.frame.origin.y)! + (pinResetButton?.frame.size.height)! if (pos > (viewHeight-keyboardSize.height)) { scrollView.setContentOffset(CGPointMake(0, pos-(viewHeight-keyboardSize.height)), animated: true) } else { scrollView.setContentOffset(CGPointMake(0, keyboardInset), animated: true) } } func keyboardWillBeHidden(notification: NSNotification) { if let position = resetTheView(posi, scrollView: scrollView, view: view) { posi = position } } } extension LoginViewController: CodeInputViewDelegate { func codeInputView(codeInputView: CodeInputView, didFinishWithCode code: String) { let passcode = KeychainManager.sharedInstance.getPINCode() if code == passcode { codeInputView.resignFirstResponder() let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(false, forKey: YonaConstants.nsUserDefaultsKeys.isBlocked) if let dashboardStoryboard = R.storyboard.dashboard.dashboardStoryboard { navigationController?.pushViewController(dashboardStoryboard, animated: true) } } else { errorLabel.hidden = false codeInputView.clear() if loginAttempts == totalAttempts { self.pinResetButton.hidden = false let defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(true, forKey: YonaConstants.nsUserDefaultsKeys.isBlocked) defaults.synchronize() self.displayAlertMessage("Login", alertDescription: NSLocalizedString("login.user.errorinfoText", comment: "")) errorLabel.hidden = false errorLabel.text = NSLocalizedString("login.user.errorinfoText", comment: "") } else { loginAttempts += 1 } } } @IBAction func pinResetTapped(sender: UIButton) { if NSUserDefaults.standardUserDefaults().boolForKey(YonaConstants.nsUserDefaultsKeys.isBlocked) { APIServiceManager.sharedInstance.pinResetRequest({ (success, pincode, message, code) in dispatch_async(dispatch_get_main_queue(), { if success { print(pincode!) if pincode != nil { let timeToDisplay = pincode!.convertFromISO8601Duration() setViewControllerToDisplay("SMSValidation", key: YonaConstants.nsUserDefaultsKeys.screenToDisplay) let localizedString = NSLocalizedString("login.user.pinResetReuestAlert", comment: "") let alert = NSString(format: localizedString, timeToDisplay!) self.displayAlertMessage("", alertDescription: String(alert)) if let sMSValidation = R.storyboard.sMSValidation.sMSValidationViewController { self.navigationController?.pushViewController(sMSValidation, animated: false) } } } else { //TODO: Will change this after this build self.displayAlertMessage("Error", alertDescription: "User not found") } }) }) } } } private extension Selector { static let keyboardWasShown = #selector(LoginViewController.keyboardWasShown(_:)) static let keyboardWillBeHidden = #selector(LoginViewController.keyboardWillBeHidden(_:)) static let pinResetTapped = #selector(LoginViewController.pinResetTapped(_:)) }
mpl-2.0
41d19b2d589efd60ee13dc58e96ac97e
41.634731
136
0.627388
5.968148
false
false
false
false
MTR2D2/TIY-Assignments
Forecaster/Forecaster/City.swift
1
3025
// // City.swift // Forecaster // // Created by Michael Reynolds on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation //NSCoding Constants let kNameKey = "name" let kZipCodeKey = "zipCode" let kLatitudeKey = "latitude" let kLongitudeKey = "longitude" class City { let cityName: String let zipCode: String let latitude: String let longitude: String var weather: WeatherConditions? init(cityName: String, zip: String, latitude: String, longitude: String, weather: WeatherConditions?) { self.cityName = cityName self.zipCode = zip self.latitude = latitude self.longitude = longitude if weather != nil { self.weather = weather! } else { self.weather = nil } } static func locationWithJSON(results: NSArray) -> City { var city: City var cityName = "" var latStr = "" var lngStr = "" if results.count > 0 { for result in results { let formatted_address = result["formatted_address"] as? String if formatted_address != nil { let addressComponents = formatted_address!.componentsSeparatedByString(",") cityName = String(addressComponents[0]) } let geometry = result["geometry"] as? NSDictionary if geometry != nil { let latlong = geometry?["location"] as? NSDictionary if latlong != nil { let lat = latlong?["lat"] as! Double let lng = latlong?["lng"] as! Double latStr = String(lat) lngStr = String(lng) } } } } city = City(cityName: cityName, zip: "", latitude: latStr, longitude: lngStr, weather: nil) return city } // MARK: - NSCoding required convenience init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObjectForKey(kNameKey) as? String, let zipCode = aDecoder.decodeObjectForKey(kZipCodeKey) as? String, let lat = aDecoder.decodeObjectForKey(kLatitudeKey) as? String, let lng = aDecoder.decodeObjectForKey(kLongitudeKey) as? String else { return nil} self.init(cityName: name, zip: zipCode, latitude: lat , longitude: lng, weather: nil) } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.cityName, forKey: kNameKey) aCoder.encodeObject(self.zipCode, forKey: kZipCodeKey) aCoder.encodeObject(self.latitude, forKey: kLatitudeKey) aCoder.encodeObject(self.longitude, forKey: kLongitudeKey) } }
cc0-1.0
2931bae1fa9136c0759eb52a403e5365
28.359223
105
0.536376
5.065327
false
false
false
false
KYawn/myiOS
FinalPhotoPicker/FinalPhotoPicker/ViewController.swift
1
2271
// // ViewController.swift // FinalPhotoPicker // // Created by K.Yawn Xoan on 3/25/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit class ViewController: UIViewController,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ var photoImageView = UIImageView(frame: CGRectMake(40, 120, 150, 150)) override func viewDidLoad() { super.viewDidLoad() self.photoImageView.layer.masksToBounds = true self.photoImageView.layer.cornerRadius = self.photoImageView.bounds.size.width * 0.5 self.view.addSubview(photoImageView) } @IBAction func photoPicker(sender: UIButton) { var myActionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancle", destructiveButtonTitle: nil, otherButtonTitles: "Choose photo from library", "take photos") myActionSheet.showInView(self.view) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { // buttonIndex == 1 choose photo from library if (buttonIndex == 1){ choosePhoto() }else if(buttonIndex == 2){ takePhoto() } } func choosePhoto(){ var photoPicker = UIImagePickerController() photoPicker.delegate = self photoPicker.sourceType = .PhotoLibrary photoPicker.allowsEditing = true self.presentViewController(photoPicker, animated: true, completion: nil) } func takePhoto(){ var photoPicker = UIImagePickerController() photoPicker.delegate = self photoPicker.sourceType = .Camera photoPicker.allowsEditing = true self.presentViewController(photoPicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { photoImageView.image = info[UIImagePickerControllerEditedImage] as? UIImage self.dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
154ce87fea6e839eb62d989ee207ff2f
34.484375
190
0.679877
5.539024
false
false
false
false
mozilla-mobile/firefox-ios
Client/Application/AppDelegate+SyncSentTabs.swift
2
3098
// 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 Shared import Storage import Sync import UserNotifications import Account private let log = Logger.browserLogger extension UIApplication { var syncDelegate: SyncDelegate { return AppSyncDelegate(app: self) } } /** Sent tabs can be displayed not only by receiving push notifications, but by sync. Sync will get the list of sent tabs, and try to display any in that list. Thus, push notifications are not needed to receive sent tabs, they can be handled when the app performs a sync. */ class AppSyncDelegate: SyncDelegate { private let app: UIApplication init(app: UIApplication) { self.app = app } func displaySentTab(for url: URL, title: String, from deviceName: String?) { DispatchQueue.main.sync { if app.applicationState == .active { BrowserViewController.foregroundBVC().switchToTabForURLOrOpen(url) return } // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.alertSetting != .enabled { return } if Logger.logPII { log.info("Displaying notification for URL \(url.absoluteString)") } let notificationContent = UNMutableNotificationContent() let title: String if let deviceName = deviceName { title = String(format: .SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = .SentTab_TabArrivingNotification_NoDevice_title } notificationContent.title = title notificationContent.body = url.absoluteDisplayExternalString notificationContent.userInfo = [SentTabAction.TabSendURLKey: url.absoluteString, SentTabAction.TabSendTitleKey: title] notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder" // `timeInterval` must be greater than zero let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) // The identifier for each notification request must be unique in order to be created let requestIdentifier = "\(SentTabAction.TabSendCategory).\(url.absoluteString)" let request = UNNotificationRequest(identifier: requestIdentifier, content: notificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { log.error(error.localizedDescription) } } } } } }
mpl-2.0
c3baa8fc4ebe2b4f2e3f52d54160eac5
39.763158
134
0.632666
5.673993
false
false
false
false
DanielMandea/coredatahelper
CoreDataStackHelper/Classes/Persistence.swift
1
3174
// // CoreDataManager.swift // Pods // // Created by DanielMandea on 3/14/17. // // import Foundation import CoreData @available(iOS 10.0, *) public typealias LoadPersistentStoreCompletion = (NSPersistentStoreDescription, Error?) -> Swift.Void /** Use this protocol in order to manage light weight core data stack */ public protocol PersistentStore: class { /// Holds persistent coordinator continer name !!!!! var persistentContainerName: String! {get set} /// Holds the configuration for the persistent store @available(iOS 10.0, *) var persistentStoreDescriptions: Array<NSPersistentStoreDescription>? {get set} /// Holds a refference to the a saving context (bg context) var savingContext: NSManagedObjectContext { get } // Holds a refference to the main context (bg context) var mainContext: NSManagedObjectContext { get } /// Holds the persistent coordinator @available(iOS 10.0, *) var persistentContainer: NSPersistentContainer { get set } } public let kDefatultContainerName = "Model" /** This is a singletone that enhances work with core data stack */ @available(iOS 10.0, *) private let sharedManager = Persistence() @available(iOS 10.0, *) open class Persistence: PersistentStore { // MARK: - Singletone open class var store: Persistence { return sharedManager } // MARK: - Initialization init() { persistentContainerName = kDefatultContainerName } // MARK: - PersistentStore open var persistentContainerName: String! open var persistentStoreDescriptions: Array<NSPersistentStoreDescription>? open var savingContext: NSManagedObjectContext { get { let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) context.persistentStoreCoordinator = self.persistentContainer.persistentStoreCoordinator context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return context } } open var mainContext: NSManagedObjectContext { get { let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = self.persistentContainer.persistentStoreCoordinator context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return context } } /** The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ @available(iOS 10.0, *) lazy public var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: self.persistentContainerName) if let descriptions = self.persistentStoreDescriptions { container.persistentStoreDescriptions = descriptions } container.loadPersistentStores(completionHandler: { (description, error) in if let error = error { print(error) } }) return container }() }
mit
ef400751de8e58b52cd01b468c2558a4
29.228571
101
0.741966
5.246281
false
false
false
false
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwift/Tool/YBWeiBoModel.swift
1
9022
// // YBWeiBoModel.swift // weiBoSwift // // Created by MAC on 15/12/1. // Copyright © 2015年 MAC. All rights reserved. // import UIKit import SDWebImage class YBWeiBoModel: NSObject { // MARK: - 属性 // 微薄id var Id = 0 /// MARK: 微博创建时间 var created_at: String? { didSet{ created_at = weiBoDataSwitch(created_at ?? "") } } /// MARK: 微博信息内容 var text: String? { didSet{ let pattern = "\\[.*?\\]" let regularExpression = try? NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0)) let textCheckingResults = regularExpression?.matchesInString(text!, options: NSMatchingOptions.ReportCompletion, range: NSRange(location: 0, length: text!.characters.count)) let attStr = NSMutableAttributedString(string: text!) // 表情数组 let emotionGroups = YBEmotionGroupModel.emotionGroupModels() for var i = (textCheckingResults!.count ?? 0) - 1; i >= 0; i -= 1 { // 替换指定位置字符 串 let range = textCheckingResults![i].rangeAtIndex(0) attStr.replaceCharactersInRange(range, withString: "") let subText = (text! as NSString).substringWithRange(textCheckingResults![i].rangeAtIndex(0)) // 遍历表情模型组 for emotionGroup in emotionGroups! { // 遍历表情模型 for emotion in emotionGroup.emotions! { if subText == emotion.chs { // 替换数据 let textAttachment = NSTextAttachment() textAttachment.image = UIImage(contentsOfFile: emotion.png!) textAttachment.bounds = CGRect(x: 0, y: -3, width: 18, height: 18) let atts = NSAttributedString(attachment: textAttachment) attStr.insertAttributedString(atts, atIndex: range.location) } } } } attStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18), range: NSRange(location: 0, length: attStr.length)) attText = attStr; } } // MARK: - attText var attText: NSAttributedString? // MARK: 微博来源 var source: String? { didSet { source = weiBoSourceSwitch(source ?? "") } } /// MARK: 微博作者的用户信息字段 详细 var user: AnyObject? { didSet{ user = YBWeIBoUserModel(dic: user as! [String: AnyObject]) } } /// MARK: 转发微博 var retweeted_status: AnyObject? { didSet { let weiBoModel = YBWeiBoModel(dic: retweeted_status as! [String: AnyObject]) retweeted_status = weiBoModel pic_urls = weiBoModel.pic_urls } } /// MARK: 图片 @objc private var pic_urls: [[String: String]]? { didSet { for picDic in pic_urls! { imageURLs.append(NSURL(string: picDic["thumbnail_pic"]!)!) // 设置大图的url // 获取图片地址 bigPictureUrls.append(NSURL(string: picDic["thumbnail_pic"]!.stringByReplacingOccurrencesOfString("thumbnail", withString: "large"))!) } } } // ----------------------------------------- /// 当为一张图片的时候图片的大小 var imageSize: CGSize = CGSizeMake(0, 0) /// MARK: 图片数组的Url var imageURLs = [NSURL]() /// 大图的url var bigPictureUrls = [NSURL]() /// MARK: 行高 var rowHeight: CGFloat? /// 当前点击的图片索引 var index: Int = 0; /// 当前点击所有的位置 var imageViewFrames: [CGRect]? // MARK: - 构造方法 init(dic: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dic) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} // MARK: - 微薄数据加载 class func loadWeiBoData(newData: Int, max_id: Int,finish: (dataArr: [YBWeiBoModel]?, isError: Bool) -> ()){ // 加载数据 YBNetworking.sharedInstance.loadWeiBoData(newData, max_id: max_id) { (result, error) -> () in // 判断是否有错误 if error == nil { // 加载成功 var weiBoArr = [YBWeiBoModel]() // 遍历数组 for data in result! { weiBoArr.append(YBWeiBoModel(dic: data)) } loadImages(weiBoArr, finish: finish) }else{ // 数据加载出错 finish(dataArr: nil, isError: true) } } } /// 加载所有单张图片 private class func loadImages(dataArr: [YBWeiBoModel], finish: (dataArr: [YBWeiBoModel]?, isError: Bool) -> ()){ // 设置GCD group let group = dispatch_group_create() // 遍历数组 for data in dataArr { if data.imageURLs.count == 1 { // 队列进组 dispatch_group_enter(group) // 下载图片 SDWebImageManager.sharedManager().downloadImageWithURL(data.imageURLs[0], options: SDWebImageOptions(rawValue: 0), progress: { (_, _) -> Void in }, completed: {[unowned data] (image, error, _, _, _) -> Void in // 队列出租 dispatch_group_leave(group) // 判断图片是否加载成功 if error == nil && image != nil { // 加载到图片 // 如果图片太窄就设置默认大小 if image.size.width < 40 { data.imageSize = CGSizeMake(80, 90) }else if image.size.width > UIScreen.width() - 20 { data.imageSize = CGSizeMake(UIScreen.width() - 20, image.size.height * (UIScreen.width() / image.size.height)) } else { data.imageSize = CGSizeMake(image.size.width, image.size.height) } }else{ // 加载错误 data.imageSize = CGSizeMake(80, 90) } }) } } // 组全部执行完执行 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in finish(dataArr: dataArr, isError: false) } } // 刚刚(一分钟内) // X分钟前(一小时内) // X小时前(当天) // 昨天 HH:mm(昨天) // MM-dd HH:mm(一年内) // yyyy-MM-dd HH:mm(更早期) /// 时间转换 private func weiBoDataSwitch(str: String) -> String { let dateF = NSDateFormatter() dateF.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy" let date = dateF.dateFromString(str) ?? NSDate() let calendar = NSCalendar.currentCalendar() // 判断时间 if calendar.compareDate(date, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame { // 今年 if calendar.isDateInToday(date) {// 今天 let timeInterval = date.timeIntervalSinceDate(NSDate()) if timeInterval < 60 { // 一分钟内 return "刚刚" } else if timeInterval < 3600 { // 一小时内 return "\(Int(timeInterval / 60))分钟前" } else { // 当天 return "\(Int(timeInterval / 3600))小时前" } }else if calendar.isDateInYesterday(date) { // 昨天 dateF.dateFormat = "HH:mm" return "昨天\(dateF.stringFromDate(date))" }else{ // 一年内 dateF.dateFormat = "MM-dd HH:mm" } }else{ // 更早期 dateF.dateFormat = "yyyy-MM-dd HH:mm" } return dateF.stringFromDate(date) } /// 微薄来源 private func weiBoSourceSwitch(str: String) -> String { if str == "" {return ""} let regularExpression = try? NSRegularExpression(pattern: ">(.*?)</a>", options: NSRegularExpressionOptions(rawValue: 0)) if regularExpression == nil {return ""} let result = regularExpression?.firstMatchInString(str, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: str.characters.count)) if result == nil {return ""} if result!.numberOfRanges > 0 { return (str as NSString).substringWithRange(result!.rangeAtIndex(1)) } return "" } }
apache-2.0
96e2027e38555f7b67813def8bb5008c
34.868085
185
0.511449
4.695822
false
false
false
false
CikeQiu/CKMnemonic
CKMnemonic/CKMnemonic/CKMnemonic/CKMnemonic.swift
1
3059
// // CKMnemonic.swift // Pods // // Created by 仇弘扬 on 2017/7/24. // // import UIKit import CryptoSwift import Security public enum CKMnemonicLanguageType { case english case chinese func words() -> [String] { switch self { case .english: return String.englishMnemonics case .chinese: return String.chineseMnemonics } } } enum CKMnemonicError: Error { case invalidStrength case unableToGetRandomData case unableToCreateSeedData } public class CKMnemonic: NSObject { public static func mnemonicString(from hexString: String, language: CKMnemonicLanguageType) throws -> String { let seedData = hexString.ck_mnemonicData() // print("\(hexString.characters.count)\t\(seedData.count)") let hashData = seedData.sha256() // print(hashData.toHexString()) let checkSum = hashData.ck_toBitArray() // print(checkSum) var seedBits = seedData.ck_toBitArray() for i in 0..<seedBits.count / 32 { seedBits.append(checkSum[i]) } let words = language.words() let mnemonicCount = seedBits.count / 11 var mnemonic = [String]() for i in 0..<mnemonicCount { let length = 11 let startIndex = i * length let subArray = seedBits[startIndex..<startIndex + length] let subString = subArray.joined(separator: "") // print(subString) let index = Int(strtoul(subString, nil, 2)) mnemonic.append(words[index]) } return mnemonic.joined(separator: " ") } public static func deterministicSeedString(from mnemonic: String, passphrase: String = "", language: CKMnemonicLanguageType) throws -> String { func normalized(string: String) -> Data? { guard let data = string.data(using: .utf8, allowLossyConversion: true) else { return nil } guard let dataString = String(data: data, encoding: .utf8) else { return nil } guard let normalizedData = dataString.data(using: .utf8, allowLossyConversion: false) else { return nil } return normalizedData } guard let normalizedData = normalized(string: mnemonic) else { return "" } guard let saltData = normalized(string: "mnemonic" + passphrase) else { return "" } let password = normalizedData.bytes let salt = saltData.bytes do { let bytes = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 2048, variant: .sha512).calculate() return bytes.toHexString() } catch { // print(error) throw error } } public static func generateMnemonic(strength: Int, language: CKMnemonicLanguageType) throws -> String { guard strength % 32 == 0 else { throw CKMnemonicError.invalidStrength } let count = strength / 8 let bytes = Array<UInt8>(repeating: 0, count: count) let status = SecRandomCopyBytes(kSecRandomDefault, count, UnsafeMutablePointer<UInt8>(mutating: bytes)) // print(status) if status != -1 { let data = Data(bytes: bytes) let hexString = data.toHexString() // print(hexString) return try mnemonicString(from: hexString, language: language) } throw CKMnemonicError.unableToGetRandomData } }
mit
ecdd3834ba10d0959ae500a4ad65bb22
24.02459
144
0.695709
3.617299
false
false
false
false
lanjing99/iOSByTutorials
iOS 9 by tutorials/05-multitasking/starter/Travelog/Travelog/Custom Views/BorderedImageView.swift
1
2074
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit @IBDesignable class BorderedImageView: UIImageView { var maskLayer: CAShapeLayer? var maskLayerRect = CGRect() override func layoutSubviews() { super.layoutSubviews() if !CGRectEqualToRect(maskLayerRect, bounds) { maskLayer?.removeFromSuperlayer() maskLayer = nil } if maskLayer == nil { let outterPath = UIBezierPath(roundedRect: bounds, cornerRadius: 0) let innerRect = CGRectInset(bounds, 4, 4) let innerPath = UIBezierPath(roundedRect: innerRect, cornerRadius: 10) outterPath.appendPath(innerPath) outterPath.usesEvenOddFillRule = true maskLayer = CAShapeLayer() maskLayer!.path = outterPath.CGPath maskLayer!.fillRule = kCAFillRuleEvenOdd; maskLayer!.fillColor = UIColor.whiteColor().CGColor maskLayer!.opacity = 1.0 layer.masksToBounds = true layer.addSublayer(maskLayer!) maskLayerRect = bounds } } }
mit
f92111fb61fb23aab30e11d43c0ebbee
34.775862
79
0.727097
4.845794
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Source/Rows/ButtonRowWithPresent.swift
7
3746
// Rows.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class _ButtonRowWithPresent<VCType: TypedRowControllerType>: Row<ButtonCellOf<VCType.RowValue>>, PresenterRowType where VCType: UIViewController { open var presentationMode: PresentationMode<VCType>? open var onPresentCallback : ((FormViewController, VCType)->())? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellStyle = .default } open override func customUpdateCell() { super.customUpdateCell() let leftAligmnment = presentationMode != nil cell.textLabel?.textAlignment = leftAligmnment ? .left : .center cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator cell.editingAccessoryType = cell.accessoryType if (!leftAligmnment){ var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0) } else{ cell.textLabel?.textColor = nil } } open override func customDidSelect() { super.customDidSelect() if let presentationMode = presentationMode, !isDisabled { if let controller = presentationMode.makeController(){ controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.present(controller, row: self, presentingController: cell.formViewController()!) } else{ presentationMode.present(nil, row: self, presentingController: cell.formViewController()!) } } } open override func prepare(for segue: UIStoryboardSegue) { super.prepare(for: segue) guard let rowVC = segue.destination as? VCType else { return } if let callback = presentationMode?.onDismissCallback{ rowVC.onDismissCallback = callback } rowVC.row = self onPresentCallback?(cell.formViewController()!, rowVC) } } //MARK: Rows /// A generic row with a button that presents a view controller when tapped public final class ButtonRowWithPresent<VCType: TypedRowControllerType> : _ButtonRowWithPresent<VCType>, RowType where VCType: UIViewController { public required init(tag: String?) { super.init(tag: tag) } }
mit
9a4261be581d628433ead1e31b0a6d36
39.27957
151
0.676989
5.028188
false
false
false
false
shafiullakhan/Swift-Paper
Swift-Paper/Swift-Paper/Transition/TransitionLayout.swift
1
1881
// // TransitionLayout.swift // Swift-Paper // // Created by Shaf on 8/5/15. // Copyright (c) 2015 Shaffiulla. All rights reserved. // import UIKit class TransitionLayout: UICollectionViewTransitionLayout { var itemSize: CGSize override init() { itemSize = CGSizeZero super.init() } required init(coder aDecoder: NSCoder) { itemSize = CGSizeZero super.init(coder: aDecoder) } init(currentLayout: UICollectionViewLayout, nextLayout newLayout: UICollectionViewLayout, itemSize newSize: CGSize){ itemSize = newSize super.init(currentLayout: currentLayout, nextLayout: newLayout); } override var transitionProgress:CGFloat { didSet { super.transitionProgress = transitionProgress; } } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let attributes = super.layoutAttributesForElementsInRect(rect); for currentAttribute in (attributes! as NSArray) { let currentCenter = currentAttribute.center; let updatedCenter = CGPointMake(currentCenter.x, currentCenter.y); var layoutArr = currentAttribute as! UICollectionViewLayoutAttributes; layoutArr.center = updatedCenter; } return attributes; } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { // returns the layout attributes for the item at the specified index path let attributes = super.layoutAttributesForItemAtIndexPath(indexPath) as UICollectionViewLayoutAttributes; let currentCenter = attributes.center; let updatedCenter = CGPointMake(currentCenter.x , currentCenter.y); attributes.center = updatedCenter; return attributes; } }
mit
5b2f2a6b092e701e842f0076228cb6cd
31.431034
120
0.679426
5.581602
false
false
false
false
idapgroup/IDPDesign
Tests/iOS/Pods/Nimble/Sources/Nimble/Matchers/Match.swift
19
984
import Foundation /// A Nimble matcher that succeeds when the actual string satisfies the regular expression /// described by the expected string. public func match(_ expectedValue: String?) -> Predicate<String> { return Predicate.simple("match <\(stringify(expectedValue))>") { actualExpression in if let actual = try actualExpression.evaluate() { if let regexp = expectedValue { let bool = actual.range(of: regexp, options: .regularExpression) != nil return PredicateStatus(bool: bool) } } return .fail } } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func matchMatcher(_ expected: NSString) -> NMBMatcher { return NMBPredicate { actualExpression in let actual = actualExpression.cast { $0 as? String } return try match(expected.description).satisfies(actual).toObjectiveC() } } } #endif
bsd-3-clause
e4cc42386d9f30a619294d0db67e1cec
32.931034
90
0.645325
4.823529
false
false
false
false
parkera/swift
test/Concurrency/async_task_groups.swift
1
5853
// RUN: %target-typecheck-verify-swift -disable-availability-checking // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch @available(SwiftStdlib 5.5, *) func asyncFunc() async -> Int { 42 } @available(SwiftStdlib 5.5, *) func asyncThrowsFunc() async throws -> Int { 42 } @available(SwiftStdlib 5.5, *) func asyncThrowsOnCancel() async throws -> Int { // terrible suspend-spin-loop -- do not do this // only for purposes of demonstration while Task.isCancelled { await Task.sleep(1_000_000_000) } throw CancellationError() } @available(SwiftStdlib 5.5, *) func test_taskGroup_add() async throws -> Int { try await withThrowingTaskGroup(of: Int.self) { group in group.addTask { await asyncFunc() } group.addTask { await asyncFunc() } var sum = 0 while let v = try await group.next() { sum += v } return sum } // implicitly awaits } // ==== ------------------------------------------------------------------------ // MARK: Example group Usages struct Boom: Error {} @available(SwiftStdlib 5.5, *) func work() async -> Int { 42 } @available(SwiftStdlib 5.5, *) func boom() async throws -> Int { throw Boom() } @available(SwiftStdlib 5.5, *) func first_allMustSucceed() async throws { let first: Int = try await withThrowingTaskGroup(of: Int.self) { group in group.addTask { await work() } group.addTask { await work() } group.addTask { try await boom() } if let first = try await group.next() { return first } else { fatalError("Should never happen, we either throw, or get a result from any of the tasks") } // implicitly await: boom } _ = first // Expected: re-thrown Boom } @available(SwiftStdlib 5.5, *) func first_ignoreFailures() async throws { @Sendable func work() async -> Int { 42 } @Sendable func boom() async throws -> Int { throw Boom() } let first: Int = try await withThrowingTaskGroup(of: Int.self) { group in group.addTask { await work() } group.addTask { await work() } group.addTask { do { return try await boom() } catch { return 0 // TODO: until try? await works properly } } var result: Int = 0 while let v = try await group.next() { result = v if result != 0 { break } } return result } _ = first // Expected: re-thrown Boom } // ==== ------------------------------------------------------------------------ // MARK: Advanced Custom Task Group Usage @available(SwiftStdlib 5.5, *) func test_taskGroup_quorum_thenCancel() async { // imitates a typical "gather quorum" routine that is typical in distributed systems programming enum Vote { case yay case nay } struct Follower: Sendable { init(_ name: String) {} func vote() async throws -> Vote { // "randomly" vote yes or no return .yay } } /// Performs a simple quorum vote among the followers. /// /// - Returns: `true` iff `N/2 + 1` followers return `.yay`, `false` otherwise. func gatherQuorum(followers: [Follower]) async -> Bool { try! await withThrowingTaskGroup(of: Vote.self) { group in for follower in followers { group.addTask { try await follower.vote() } } defer { group.cancelAll() } var yays: Int = 0 var nays: Int = 0 let quorum = Int(followers.count / 2) + 1 while let vote = try await group.next() { switch vote { case .yay: yays += 1 if yays >= quorum { // cancel all remaining voters, we already reached quorum return true } case .nay: nays += 1 if nays >= quorum { return false } } } return false } } _ = await gatherQuorum(followers: [Follower("A"), Follower("B"), Follower("C")]) } // FIXME: this is a workaround since (A, B) today isn't inferred to be Sendable // and causes an error, but should be a warning (this year at least) @available(SwiftStdlib 5.5, *) struct SendableTuple2<A: Sendable, B: Sendable>: Sendable { let first: A let second: B init(_ first: A, _ second: B) { self.first = first self.second = second } } @available(SwiftStdlib 5.5, *) extension Collection where Self: Sendable, Element: Sendable, Self.Index: Sendable { /// Just another example of how one might use task groups. func map<T: Sendable>( parallelism requestedParallelism: Int? = nil/*system default*/, // ordered: Bool = true, / _ transform: @Sendable (Element) async throws -> T ) async throws -> [T] { // TODO: can't use rethrows here, maybe that's just life though; rdar://71479187 (rethrows is a bit limiting with async functions that use task groups) let defaultParallelism = 2 let parallelism = requestedParallelism ?? defaultParallelism let n = self.count if n == 0 { return [] } return try await withThrowingTaskGroup(of: SendableTuple2<Int, T>.self) { group in var result = ContiguousArray<T>() result.reserveCapacity(n) var i = self.startIndex var submitted = 0 func submitNext() async throws { group.addTask { [submitted,i] in let value = try await transform(self[i]) return SendableTuple2(submitted, value) } submitted += 1 formIndex(after: &i) } // submit first initial tasks for _ in 0..<parallelism { try await submitNext() } while let tuple = try await group.next() { let index = tuple.first let taskResult = tuple.second result[index] = taskResult try Task.checkCancellation() try await submitNext() } assert(result.count == n) return Array(result) } } }
apache-2.0
edf5be7f4e3051623018000811e1cf3a
25.364865
177
0.598496
4.090147
false
false
false
false
rnystrom/GitHawk
Classes/Repository/GitHubClient+Repository.swift
1
2424
// // GitHubClient+Repository.swift // Freetime // // Created by Ryan Nystrom on 10/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation extension GithubClient { func fetchFiles( owner: String, repo: String, branch: String, path: String, completion: @escaping (Result<[RepositoryFile]>) -> Void ) { let query = RepoFilesQuery(owner: owner, name: repo, branchAndPath: "\(branch):\(path)") client.query(query, result: { $0.repository?.object?.asTree?.entries }, completion: { result in switch result { case .failure(let error): completion(.error(error)) case .success(let models): // trees A-Z first, then blobs A-Z var trees = [RepositoryFile]() var blobs = [RepositoryFile]() for model in models { let isTree = model.type == "tree" let file = RepositoryFile( name: model.name, isDirectory: model.type == "tree" ) if isTree { trees.append(file) } else { blobs.append(file) } } trees.sort { $0.name < $1.name } blobs.sort { $0.name < $1.name } completion(.success(trees + blobs)) } }) } // different result type so handling non-text is treated differently enum FileResult { case success(String) case nonUTF8 case error(Error?) } func fetchFile( owner: String, repo: String, branch: String, path: String, completion: @escaping (FileResult) -> Void ) { let query = RepoFileQuery(owner: owner, name: repo, branchAndPath: "\(branch):\(path)") client.query(query, result: { $0.repository?.object?.asBlob }, completion: { result in switch result { case .failure(let error): completion(.error(error)) case .success(let blob): if let text = blob.text, !text.isEmpty { completion(.success(text)) } else { completion(.nonUTF8) } } }) } }
mit
590a59dd0cff53035755511e4c7a7d22
30.064103
103
0.486174
4.714008
false
false
false
false
iOS-mamu/SS
P/Library/ICSMainFramework/ICSMainFramework/AppEnvironment.swift
1
1825
// // AppConfig.swift // ICSMainFramework // // Created by LEI on 5/14/15. // Copyright (c) 2015 TouchingApp. All rights reserved. // import Foundation public struct AppEnv { // App Name // App Version // App Build public static var version: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } public static var fullVersion: String { return "\(AppEnv.version) Build \(AppEnv.build)" } public static var build: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String } public static var countryCode: String { return (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String ?? "US" } public static var languageCode: String { return (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode) as? String ?? "en" } public static var appName: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String } public static var isTestFlight: Bool { return isAppStoreReceiptSandbox && !hasEmbeddedMobileProvision } public static var isAppStore: Bool { if isAppStoreReceiptSandbox || hasEmbeddedMobileProvision { return false } return true } fileprivate static var isAppStoreReceiptSandbox: Bool { let b = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" NSLog("isAppStoreReceiptSandbox: \(b)") return b } fileprivate static var hasEmbeddedMobileProvision: Bool { let b = Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil NSLog("hasEmbeddedMobileProvision: \(b)") return b } }
mit
65fcfac6f5bb15bb5fbb38545dc09af3
28.435484
104
0.661918
4.63198
false
false
false
false
steve228uk/PeachKit
FriendRequest.swift
1
3180
// // Request.swift // Peach // // Created by Stephen Radford on 14/01/2016. // Copyright © 2016 Cocoon Development Ltd. All rights reserved. // import Foundation import Alamofire import SwiftyJSON public struct FriendRequest { /// ID of the friend request public var id: String? /// Stream releated to the friend request public var stream: Stream? /** Accept the friend request - parameter callback: Optional callback */ public func accept(callback: ((NSError?) -> Void)?) { if let requestID = id { Alamofire.request(API.AcceptFriendRequest(requestID)) .responseJSON { response in callback?(response.result.error) } } } /** Accept the friend request */ public func accept() { accept(nil) } /** Decline the friend request - parameter callback: Optional callback */ public func decline(callback: ((NSError?) -> Void)?) { if let requestID = id { Alamofire.request(API.DeclineFriendRequest(requestID)) .responseJSON { response in callback?(response.result.error) } } } /** Decline the friend request */ public func decline() { decline(nil) } /** Ignore the friend request - parameter callback: Optional callback */ public func ignore(callback: ((NSError?) -> Void)?) { if let requestID = id { Alamofire.request(API.IgnoreFriendRequest(requestID)) .responseJSON { response in callback?(response.result.error) } } } /** Ignore the friend request */ public func ignore() { ignore(nil) } } extension Peach { /** Fetch a list of friend requests - parameter callback: Callback with array of requests and optional NSError */ public class func getFriendRequests(callback: ([FriendRequest], NSError?) -> Void) { Alamofire.request(API.FriendRequests) .responseJSON { response in if response.result.isSuccess { if let value = response.result.value { let json = JSON(value) if let data = json["data"].dictionary { if let rawRequests = data["inboundFriendRequests"]?.array { let requests: [FriendRequest] = rawRequests.map { var request = FriendRequest() request.id = $0["id"].string request.stream = self.parseStream($0["stream"]) return request } callback(requests, response.result.error) } } } } callback([], response.result.error) } } }
mit
104394387cb12e47837c35f75b74f81c
25.722689
88
0.493237
5.577193
false
false
false
false
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Data/BubbleChartDataSet.swift
35
2840
// // BubbleChartDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class BubbleChartDataSet: BarLineScatterCandleBubbleChartDataSet { internal var _xMax = Double(0.0) internal var _xMin = Double(0.0) internal var _maxSize = CGFloat(0.0) public var xMin: Double { return _xMin } public var xMax: Double { return _xMax } public var maxSize: CGFloat { return _maxSize } public func setColor(color: UIColor, alpha: CGFloat) { super.setColor(color.colorWithAlphaComponent(alpha)) } internal override func calcMinMax(start start: Int, end: Int) { if (yVals.count == 0) { return } let entries = yVals as! [BubbleChartDataEntry] // need chart width to guess this properly var endValue : Int if end == 0 { endValue = entries.count - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = yMin(entries[start]) _yMax = yMax(entries[start]) for (var i = start; i <= endValue; i++) { let entry = entries[i] let ymin = yMin(entry) let ymax = yMax(entry) if (ymin < _yMin) { _yMin = ymin } if (ymax > _yMax) { _yMax = ymax } let xmin = xMin(entry) let xmax = xMax(entry) if (xmin < _xMin) { _xMin = xmin } if (xmax > _xMax) { _xMax = xmax } let size = largestSize(entry) if (size > _maxSize) { _maxSize = size } } } /// Sets/gets the width of the circle that surrounds the bubble when highlighted public var highlightCircleWidth: CGFloat = 2.5 private func yMin(entry: BubbleChartDataEntry) -> Double { return entry.value } private func yMax(entry: BubbleChartDataEntry) -> Double { return entry.value } private func xMin(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func xMax(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func largestSize(entry: BubbleChartDataEntry) -> CGFloat { return entry.size } }
apache-2.0
ba9522e26a55d96a0324a36d36c30222
21.72
84
0.501761
4.905009
false
false
false
false
tomasharkema/HoelangTotTrein2.iOS
Packages/Core/Sources/Core/Extensions/DisposeBagContainer+Variable.swift
1
1816
// // DisposeBagContainer+Variable.swift // HoelangTotTreinCore // // Created by Tomas Harkema on 30-07-18. // Copyright © 2018 Tomas Harkema. All rights reserved. // import Bindable import Foundation // public protocol Bindable: class { // var disposeBag: DisposeBag { get } // var subscriptions: [AnyKeyPath: Subscription] { get set } // } // // extension Bindable { // public func bind<T>(_ keyPath: ReferenceWritableKeyPath<Self, T>, to variable: Variable<T>) { // subscriptions[keyPath]?.unsubscribe() // subscriptions[keyPath] = nil // // self[keyPath: keyPath] = variable.value // let subscription = variable.subscribe { [weak self] event in // self?[keyPath: keyPath] = event.value // } // // disposeBag.insert(subscription) // subscriptions[keyPath] = subscription // } // // public func bind<T>(_ keyPath: ReferenceWritableKeyPath<Self, T?>, to variable: Variable<T>?) { // subscriptions[keyPath]?.unsubscribe() // subscriptions[keyPath] = nil // // if let variable = variable { // self[keyPath: keyPath] = variable.value // let subscription = variable.subscribe { [weak self] event in // self?[keyPath: keyPath] = event.value // } // disposeBag.insert(subscription) // subscriptions[keyPath] = subscription // } else { // self[keyPath: keyPath] = nil // } // } // // public func unbind<T>(_ keyPath: ReferenceWritableKeyPath<Self, T>, resetTo value: T) { // subscriptions[keyPath]?.unsubscribe() // subscriptions[keyPath] = nil // // self[keyPath: keyPath] = value // } // // public func unbind<T>(_ keyPath: ReferenceWritableKeyPath<Self, T?>, resetTo value: T? = nil) { // subscriptions[keyPath]?.unsubscribe() // subscriptions[keyPath] = nil // // self[keyPath: keyPath] = value // } // }
mit
eab3f9f8ad323a249d1943c2098f22bc
29.25
99
0.650689
3.711656
false
false
false
false
khizkhiz/swift
validation-test/stdlib/ErrorProtocol.swift
2
1666
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import SwiftPrivate import StdlibUnittest import Foundation // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivatePthreadExtras #if _runtime(_ObjC) import ObjectiveC #endif enum SomeError : ErrorProtocol { case GoneToFail } struct ErrorProtocolAsNSErrorRaceTest : RaceTestWithPerTrialData { class RaceData { let error: ErrorProtocol init(error: ErrorProtocol) { self.error = error } } func makeRaceData() -> RaceData { return RaceData(error: SomeError.GoneToFail) } func makeThreadLocalData() {} func thread1(raceData: RaceData, _: inout Void) -> Observation3Int { let ns = raceData.error as NSError // Use valueForKey to bypass bridging, so we can verify that the identity // of the unbridged NSString object is stable. let domainInt: Int = unsafeBitCast(ns.value(forKey: "domain"), to: Int.self) let code: Int = ns.code let userInfoInt: Int = unsafeBitCast(ns.value(forKey: "userInfo"), to: Int.self) return Observation3Int(domainInt, code, userInfoInt) } func evaluateObservations( observations: [Observation3Int], _ sink: (RaceTestObservationEvaluation) -> Void ) { sink(evaluateObservationsAllEqual(observations)) } } var ErrorProtocolRaceTestSuite = TestSuite("ErrorProtocol races") ErrorProtocolRaceTestSuite.test("NSError bridging") { runRaceTest(ErrorProtocolAsNSErrorRaceTest.self, operations: 1000) } runAllTests()
apache-2.0
4cbb541ff7a317e0951395062c85ed02
27.237288
84
0.744898
4.466488
false
true
false
false
TheBrewery/Hikes
WorldHeritage/Controllers/TBMapViewController.swift
1
7901
// // TBMapViewController.swift // World Heritage // // Created by James Hildensperger on 2/18/16. // Copyright © 2016 The Brewery. All rights reserved. // import Foundation import UIKit import MapKit import RealmSwift import FBAnnotationClusteringSwift class TBMapViewController: TBBaseViewController { let clusteringManager = FBClusteringManager() var dataSource = SitesRealmDataSource() @IBOutlet var mapView: MKMapView! lazy var recenterButton: TBCircularIconButton = { let buttonSize = CGSize(width: 50, height: 50) let buttonFrame = CGRect(origin: CGPointZero, size: buttonSize) let button = TBCircularIconButton(icon: Ionic.Pinpoint, frame: buttonFrame, target: self, action: #selector(TBMapViewController.recenterMap)) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(TBMapViewController.zoomToLocation)) tapGesture.numberOfTapsRequired = 2 button.addGestureRecognizer(tapGesture) button.translatesAutoresizingMaskIntoConstraints = false let heightConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: buttonSize.height) let widthConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: buttonSize.width) button.addConstraints([heightConstraint, widthConstraint]) self.view.addSubview(button) let horizontalConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: -20) let bottomConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -69) self.view.addConstraints([horizontalConstraint, bottomConstraint]) return button }() var showsRecenterButton = true { didSet { recenterButton.alpha = CGFloat(showsRecenterButton) } } override func viewDidLoad() { super.viewDidLoad() mapView.showsScale = true mapView.showsCompass = true preferredBlurredStatusBarStyleBarStyle = .LightDefault recenterButton.alpha = 1 dataSource.fetch { [weak self] (objects) -> () in guard let _self = self else { return } var annotations = [MKAnnotation]() for site in _self.dataSource.fetchedResults { annotations.append(WHSiteAnnotation(site: site)) } _self.clusteringManager.addAnnotations(annotations) } } // MARK: - Private @objc private func search() { } @objc private func zoomToLocation() { guard let coordinate = mapView.userLocation.location?.coordinate else { return } let region = MKCoordinateRegionMakeWithDistance(coordinate, 3000, 3000) mapView.setRegion(region, animated: true) } @objc private func recenterMap() { guard let coordinate = mapView.userLocation.location?.coordinate else { return } mapView.setCenterCoordinate(coordinate, animated: true) } } class WHSiteAnnotation: NSObject, MKAnnotation { var site: Site! init(site: Site) { self.site = site } var coordinate: CLLocationCoordinate2D { return site.coordinate } var title: String? { return site.name } var subtitle: String? { return site.location.isEmpty ? site.countries.map({ $0.name }).joinWithSeparator(", "): site.location } } class WHSiteAnnotationView: MKAnnotationView { var icon = Ionic.IosLocation { didSet { self.image = UIImage.imageWithIcon(icon, fontSize: fontSize, color: iconTintColor) } } var fontSize: CGFloat = 40.0 { didSet { self.image = UIImage.imageWithIcon(icon, fontSize: fontSize, color: iconTintColor) } } var iconTintColor: UIColor { guard let annotation = annotation as? WHSiteAnnotation else { return UIColor.redColor() } return annotation.site.category.lowercaseString == "natural" ? UIColor.greenColor() : UIColor.whDarkBlueColor() } override init(frame: CGRect) { super.init(frame: frame) self.image = UIImage.imageWithIcon(icon, fontSize: fontSize, color: iconTintColor) self.rightCalloutAccessoryView = UIView() } override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) self.image = UIImage.imageWithIcon(icon, fontSize: fontSize, color: iconTintColor) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private extension MKAnnotationView { } extension TBMapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { NSOperationQueue().addOperationWithBlock({ let mapBoundsWidth = Double(self.mapView.bounds.size.width) let mapRectWidth:Double = self.mapView.visibleMapRect.size.width let scale:Double = mapBoundsWidth / mapRectWidth executeOn(.Main, block: { let annotationArray = self.clusteringManager.clusteredAnnotationsWithinMapRect(self.mapView.visibleMapRect, withZoomScale:scale) self.clusteringManager.displayAnnotations(annotationArray, onMapView:self.mapView) }) }) } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard let site = (view.annotation as? WHSiteAnnotation)?.site else { return } let viewController = WHSiteViewController.createWith(site) self.showViewController(viewController, sender: nil) } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard !(annotation is MKUserLocation) else { return nil } var reuseId = "" if annotation.isKindOfClass(FBAnnotationCluster) { reuseId = "Cluster" var clusterView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) if clusterView == nil { clusterView = FBAnnotationClusterView(annotation: annotation, reuseIdentifier: reuseId) } else { clusterView?.annotation = annotation } return clusterView } else { reuseId = "Pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) } else { pinView?.annotation = annotation } pinView?.canShowCallout = true let color = (annotation as? WHSiteAnnotation)?.site.category == "Cultural" ? UIColor.whDarkBlueColor() : UIColor.whDarkGreenColor() let image = UIImage.imageWithIcon(Ionic.IosArrowRight, fontSize: 30.0, color: color) let button = UIButton(frame: CGRect(origin: CGPointZero, size: image.size)) button.setImage(image, forState: .Normal) pinView?.rightCalloutAccessoryView = button pinView?.pinTintColor = color return pinView } } }
mit
289b363d6f724830c8f133e7f8819b86
35.40553
239
0.672785
5.221414
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Services/Base/RealmStorable.swift
1
2964
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import RealmSwift enum Changes<PlainType: RealmMappable> { case initial(objects: [PlainType]) case update(objects: [PlainType], deleteons: [Int], insertions: [Int], modifications: [Int]) } class RealmStorable<PlainType: RealmMappable> { var notificationToken: NotificationToken? deinit { notificationToken?.invalidate() notificationToken = nil } func observe(updateHandler: @escaping ([PlainType]) -> Void) { let realm = try! Realm() let objects = realm.objects(PlainType.RealmType.self) notificationToken?.invalidate() notificationToken = objects.observe { changes in updateHandler(objects.map { PlainType.mapFromRealmObject($0) } ) } } func observe(predicate: String, updateHandler: @escaping ([PlainType]) -> Void) { let realm = try! Realm() let objects = realm.objects(PlainType.RealmType.self).filter(predicate) notificationToken?.invalidate() notificationToken = objects.observe { changes in updateHandler(objects.map { PlainType.mapFromRealmObject($0) } ) } } func observeChanges(updateHandler: @escaping (Changes<PlainType>) -> Void) { let realm = try! Realm() let objects = realm.objects(PlainType.RealmType.self) notificationToken?.invalidate() notificationToken = objects.observe { changes in switch changes { case let .initial(objects): let plainObjects: [PlainType] = objects.map { PlainType.mapFromRealmObject($0) } updateHandler(Changes.initial(objects: plainObjects)) case let .update(objects, deletions, insertions, modifications): let plainObjects: [PlainType] = objects.map { PlainType.mapFromRealmObject($0) } updateHandler(Changes.update(objects: plainObjects, deleteons: deletions, insertions: insertions, modifications: modifications)) case .error(let error): print(error.localizedDescription) } } } func find() -> [PlainType] { let realm = try! Realm() return realm.objects(PlainType.RealmType.self).compactMap() { PlainType.mapFromRealmObject($0) } } func find(_ predicateString: String) -> [PlainType] { let realm = try! Realm() return realm.objects(PlainType.RealmType.self) .filter(predicateString) .compactMap() { PlainType.mapFromRealmObject($0) } } func findOne(_ predicateString: String) -> PlainType? { let realm = try! Realm() return realm.objects(PlainType.RealmType.self).filter(predicateString).compactMap() { PlainType.mapFromRealmObject($0) }.first } func save(_ model: PlainType) { let realm = try! Realm() try! realm.write { realm.add(model.mapToRealmObject(), update: true) } } func save(_ models: [PlainType]) { let realm = try! Realm() try! realm.write { realm.add(models.map({ $0.mapToRealmObject() }), update: true) } } }
gpl-3.0
268ff00a883cfdc6c10364afdf73a93d
31.922222
136
0.682079
4.448949
false
false
false
false
testpress/ios-app
ios-app/UI/VideoPlayerResourceLoaderDelegate.swift
1
3144
// // VideoPlayerResourceLoaderDelegate.swift // ios-app // // Created by Karthik on 05/06/20. // Copyright © 2020 Testpress. All rights reserved. // import Foundation import AVKit class VideoPlayerResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate { var contentKeySession: AVContentKeySession? func setContentKeySession(contentKeySession: AVContentKeySession) { self.contentKeySession = contentKeySession } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { guard let url = loadingRequest.request.url else { return false } if url.scheme == "fakehttps" { M3U8Handler().fetch(url: url) { data, response in self.setM3U8Response(loadingRequest: loadingRequest, data: data, response: response) } return true } else if url.scheme == "skd" { if #available(iOS 11, *) { contentKeySession?.processContentKeyRequest(withIdentifier: url, initializationData: nil, options: nil) } } else if isEncryptionKeyUrl(url: url) { EncryptionKeyRepository().load(url: url) { data in self.setEncryptionKeyResponse(loadingRequest: loadingRequest, data: data) } return true } return false } func isEncryptionKeyUrl(url: URL) -> Bool { return url.scheme == "fakekeyhttps" || url.path.contains("encryption_key") } func setM3U8Response(loadingRequest: AVAssetResourceLoadingRequest, data: Data, response:URLResponse?) { loadingRequest.contentInformationRequest?.contentType = response?.mimeType loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true loadingRequest.contentInformationRequest?.contentLength = response!.expectedContentLength loadingRequest.dataRequest?.respond(with: data) loadingRequest.finishLoading() } func setEncryptionKeyResponse(loadingRequest: AVAssetResourceLoadingRequest, data: Data) { loadingRequest.contentInformationRequest?.contentType = getContentType(contentInformationRequest: loadingRequest.contentInformationRequest) loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true loadingRequest.contentInformationRequest?.contentLength = Int64(data.count) loadingRequest.dataRequest?.respond(with: data) loadingRequest.finishLoading() } func getContentType(contentInformationRequest: AVAssetResourceLoadingContentInformationRequest?) -> String{ var contentType = AVStreamingKeyDeliveryPersistentContentKeyType if #available(iOS 11.2, *) { if let allowedContentType = contentInformationRequest?.allowedContentTypes?.first{ if allowedContentType == AVStreamingKeyDeliveryContentKeyType{ contentType = AVStreamingKeyDeliveryContentKeyType } } } return contentType } }
mit
304e6cbcae1ab084d15eb8da9c837cbf
41.472973
161
0.694241
5.592527
false
false
false
false
marty-suzuki/FluxCapacitor
Examples/Flux+MVVM/FluxCapacitorSample/Sources/UI/UserRepository/UserRepositoryViewModel.swift
1
4081
// // UserRepositoryViewModel.swift // FluxCapacitorSample // // Created by marty-suzuki on 2017/08/21. // Copyright © 2017年 marty-suzuki. All rights reserved. // import Foundation import GithubKit import RxSwift import FluxCapacitor final class UserRepositoryViewModel { private let userAction: UserAction private let userStore: UserStore private let repositoryAction: RepositoryAction private let repositoryStore: RepositoryStore private let disposeBag = DisposeBag() private let dustBuster = DustBuster() let showRepository: Observable<Void> private let _showRepository = PublishSubject<Void>() let reloadData: Observable<Void> private let _reloadData = PublishSubject<Void>() let counterText: Observable<String> private let _counterText = PublishSubject<String>() let isRepositoryFetching: Constant<Bool> let repositories: Constant<[Repository]> var usernameValue: String { return userStore.value.selectedUser?.login ?? "" } init(userAction: UserAction = .init(), userStore: UserStore = .instantiate(), repositoryAction: RepositoryAction = .init(), repositoryStore: RepositoryStore = .instantiate(), fetchMoreRepositories: Observable<Void>, selectRepositoryRowAt: Observable<IndexPath>) { self.userAction = userAction self.userStore = userStore self.repositoryAction = repositoryAction self.repositoryStore = repositoryStore self.showRepository = _showRepository self.reloadData = _reloadData self.counterText = _counterText self.isRepositoryFetching = repositoryStore.isRepositoryFetching self.repositories = repositoryStore.repositories Observable.merge(repositoryStore.repositories.asObservable().map { _ in }, repositoryStore.isRepositoryFetching.asObservable().map { _ in }) .bind(to: _reloadData) .disposed(by: disposeBag) repositoryStore.selectedRepository .observe { [weak self] in if $0 == nil { return } self?._showRepository.onNext(()) } .cleaned(by: dustBuster) Observable.combineLatest(repositoryStore.repositories.asObservable(), repositoryStore.repositoryTotalCount.asObservable()) { "\($0.count) / \($1)" } .bind(to: _counterText) .disposed(by: disposeBag) let selectedUser = userStore.selectedUser .filter { $0 != nil } .map { $0! } let lastPageInfo = Observable<PageInfo?>.create { [weak self] observer in let dust = self?.repositoryStore.lastPageInfo .observe { pageInfo in observer.onNext(pageInfo) } return Disposables.create { dust?.clean() } } .filter { $0 != nil } .map { $0! } fetchMoreRepositories .withLatestFrom(Observable.combineLatest(selectedUser, lastPageInfo)) .subscribe(onNext: { [weak self] user, pageInfo in guard pageInfo.hasNextPage, let after = pageInfo.endCursor else { return } self?.repositoryAction.fetchRepositories(withUserId: user.id, after: after) }) .disposed(by: disposeBag) selectRepositoryRowAt .withLatestFrom(repositoryStore.repositories.asObservable()) { $1[$0.row] } .subscribe(onNext: { [weak self] in self?.repositoryAction.invoke(.selectedRepository($0)) }) .disposed(by: disposeBag) if let userId = userStore.value.selectedUser?.id { repositoryAction.fetchRepositories(withUserId: userId, after: nil) } } deinit { userAction.invoke(.selectedUser(nil)) repositoryAction.invoke(.removeAllRepositories) repositoryAction.invoke(.lastPageInfo(nil)) } }
mit
3a71c3305a0919bc29b07db0811fae11
36.412844
91
0.622364
5.358739
false
false
false
false
jkolb/Shkadov
Sources/PlatformXCB/XCBCreateWindow.swift
1
2589
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 ShkadovXCB public struct XCBCreateWindow : OptionSet { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } public static var backPixmap = XCBCreateWindow(rawValue: XCB_CW_BACK_PIXMAP.rawValue) public static var backPixel = XCBCreateWindow(rawValue: XCB_CW_BACK_PIXEL.rawValue) public static var borderPixmap = XCBCreateWindow(rawValue: XCB_CW_BORDER_PIXMAP.rawValue) public static var borderPixel = XCBCreateWindow(rawValue: XCB_CW_BORDER_PIXEL.rawValue) public static var bitGravity = XCBCreateWindow(rawValue: XCB_CW_BIT_GRAVITY.rawValue) public static var winGravity = XCBCreateWindow(rawValue: XCB_CW_WIN_GRAVITY.rawValue) public static var backingStore = XCBCreateWindow(rawValue: XCB_CW_BACKING_STORE.rawValue) public static var backingPlanes = XCBCreateWindow(rawValue: XCB_CW_BACKING_PLANES.rawValue) public static var backingPixel = XCBCreateWindow(rawValue: XCB_CW_BACKING_PIXEL.rawValue) public static var overrideRedirect = XCBCreateWindow(rawValue: XCB_CW_OVERRIDE_REDIRECT.rawValue) public static var saveUnder = XCBCreateWindow(rawValue: XCB_CW_SAVE_UNDER.rawValue) public static var eventMask = XCBCreateWindow(rawValue: XCB_CW_EVENT_MASK.rawValue) public static var dontPropagate = XCBCreateWindow(rawValue: XCB_CW_DONT_PROPAGATE.rawValue) public static var colormap = XCBCreateWindow(rawValue: XCB_CW_COLORMAP.rawValue) public static var cursor = XCBCreateWindow(rawValue: XCB_CW_CURSOR.rawValue) }
mit
14a1163f5a6315d1b6daf250a3180586
51.836735
98
0.799537
4.162379
false
false
false
false
xoyip/AzureStorageApiClient
Pod/Classes/AzureStorage/Client.swift
1
6883
// // Client.swift // AzureStorageApiClient // // Created by Hiromasa Ohno on 2015/07/30. // Copyright (c) 2015 Hiromasa Ohno. All rights reserved. // import Foundation import AFNetworking import CryptoSwift import BrightFutures extension AzureStorage { public class Client { let scheme : String! let key : String! let name : String! let hostName : String? let defaultHost = "core.windows.net" public init(accoutName: String, accessKey: String, useHTTPS: Bool, hostName: String?) { scheme = useHTTPS ? "https" : "http" key = accessKey name = accoutName self.hostName = hostName } public func future<T: Request>(request: T) -> Future<T.Response, NSError> { let promise = Promise<T.Response, NSError>() let handleError = { () -> Void in let userInfo = [NSLocalizedDescriptionKey: "unresolved error occurred."] let error = NSError(domain: "WebAPIErrorDomain", code: 0, userInfo: userInfo) promise.failure(error) } let success = { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in let statusCode = (task.response as? NSHTTPURLResponse)?.statusCode switch (statusCode, request.convertResponseObject(responseObject)) { case (.Some(200..<300), .Some(let response)): promise.success(response) default: handleError() } } let headSuccess = { (task: NSURLSessionDataTask!) -> Void in let response = task.response as? NSHTTPURLResponse switch (response?.statusCode, request.convertResponseObject(response?.allHeaderFields)) { case (.Some(200..<300), .Some(let response)): promise.success(response) default: handleError() } } let failure = { (task: NSURLSessionDataTask!, error: NSError!) -> Void in promise.failure(error) } callImpl(request, success: success, headSuccess: headSuccess, failure: failure) return promise.future } public func call<T: Request>(request: T, handler: (Response<T.Response>) -> Void) { let handleError = { () -> Void in let userInfo = [NSLocalizedDescriptionKey: "unresolved error occurred."] let error = NSError(domain: "WebAPIErrorDomain", code: 0, userInfo: userInfo) handler(Response(error)) } let success = { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in let statusCode = (task.response as? NSHTTPURLResponse)?.statusCode switch (statusCode, request.convertResponseObject(responseObject)) { case (.Some(200..<300), .Some(let response)): handler(Response(response)) default: handleError() } } let headSuccess = { (task: NSURLSessionDataTask!) -> Void in let response = task.response as? NSHTTPURLResponse switch (response?.statusCode, request.convertResponseObject(response?.allHeaderFields)) { case (.Some(200..<300), .Some(let response)): handler(Response(response)) default: handleError() } } let failure = { (task: NSURLSessionDataTask!, error: NSError!) -> Void in handler(Response(error)) } callImpl(request, success: success, headSuccess: headSuccess, failure: failure) } internal func service() -> String { return "" } private func host() -> String { if let hostname = hostName { return hostname } else { return "\(name).\(service()).\(defaultHost)" } } private func callImpl<T: Request>(request: T, success: (NSURLSessionDataTask!, AnyObject!) -> Void, headSuccess: (NSURLSessionDataTask!) -> Void, failure: (NSURLSessionDataTask!, NSError!) -> Void) { let url = scheme + "://" + host() + request.path() let manager = configuredManager(request) switch request.method { case "HEAD": manager.HEAD(url, parameters: nil, success: headSuccess, failure: failure) case "GET": manager.GET(url, parameters: nil, success: success, failure: failure) case "POST": manager.POST(url, parameters: request.body(), success: success, failure: failure) case "PUT": manager.PUT(url, parameters: request.body(), success: success, failure: failure) case "DELETE": manager.DELETE(url, parameters: nil, success: success, failure: failure) default: break } } private func configuredManager<T: Request>(request: T) -> AFHTTPSessionManager { let url = scheme + "://" + host() + request.path() var headers = Dictionary<String, String>() headers["x-ms-date"] = dateString() headers["x-ms-version"] = "2014-02-14" headers.merge(request.additionalHeaders()) var signer = Signer(name: name, key: key) var sign = signer.signature(request.method, uri: url, headers: headers) headers["Authorization"] = "SharedKey \(name):\(sign)" var manager = AFHTTPSessionManager() if let data = request.body() { manager.requestSerializer = AzureStorageRequetSerializer() } for (key, value) in headers { manager.requestSerializer.setValue(value, forHTTPHeaderField: key) } manager.responseSerializer = AFHTTPResponseSerializer() manager.responseSerializer.acceptableContentTypes = request.responseTypes() return manager } private func dateString() -> String { let date = NSDate() let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US") formatter.timeZone = NSTimeZone(name: "UTC") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" return formatter.stringFromDate(date) } } }
mit
5fe3cafb928d85b0def89d40b9550150
39.494118
105
0.535522
5.493216
false
false
false
false
jwzhuang/TimeTrackBarKit
TimeTrackBarKit/ObjectRect.swift
1
1787
// // FileRect.swift // TimeBar // // Created by JingWen on 2015/10/13. // Copyright © 2015年 JingWen. All rights reserved. // import UIKit class ObjectRect { var posX:CGFloat var posY:CGFloat = 10.0 var width:CGFloat var height:CGFloat = 10.0 var type:ObjectType = .normal var startDate:Date var endDate:Date init(posX:CGFloat, posY:CGFloat, width:CGFloat, height:CGFloat, type:ObjectType, startDate:Date, endDate:Date){ self.posX = posX self.posY = posY self.width = width self.height = height self.type = type self.startDate = startDate self.endDate = endDate } //MARK: Public Method func draw(_ context:CGContext, barX:CGFloat = 0, barWidth:CGFloat) ->(){ switch type{ case .normal: context.setFillColor(UIColor.blue.cgColor) case .important: context.setFillColor(UIColor.red.cgColor) case .nothing: return } if isInRange(barX, width: barWidth){ if self.posX < barX && self.posX + self.width > barX{ //cut at left context.fill(CGRect(x: barX, y: posY, width: posX + self.width, height: height)) }else if self.posX < barWidth && self.posX + self.width > barWidth{ //cut at right context.fill(CGRect(x: posX, y: posY, width: barWidth, height: height)) }else{ context.fill(CGRect(x: posX, y: posY, width: width, height: height)) } } } //MARK: Public Method func isInRange(_ barX:CGFloat, width barWidth:CGFloat) -> Bool{ if (self.posX + self.width < barX) || self.posX > barWidth{ return false } return true } }
mit
baf0a1ddee5bae33cb52bc9c821a210a
28.245902
115
0.576233
4.018018
false
false
false
false
algolia/algoliasearch-client-swift
Tests/AlgoliaSearchClientTests/Integration/DictionairesIntegrationTests.swift
1
7449
// // DictionairesIntegrationTests.swift // // // Created by Vladislav Fitc on 21/01/2021. // import Foundation import XCTest @testable import AlgoliaSearchClient class DictionairesIntegrationTests: IntegrationTestCase { override var allowFailure: Bool { return true } override var retryableTests: [() throws -> Void] { [ stopwordsDictionary, compoundsDictionary, pluralsDictionary ] } override func setUpWithError() throws { let fetchedCredentials = Result(catching: { try TestCredentials(environment: .secondary) }).mapError { XCTSkip("\($0)") } let credentials = try fetchedCredentials.get() client = SearchClient(appID: credentials.applicationID, apiKey: credentials.apiKey) } func stopwordsDictionary() throws { // Create one `entry_id` with a random string let entryID = ObjectID(rawValue: .random(length: 10)) // Search in the `stopwords` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 var response = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) // Add the following entry in the `stopwords` dictionary with **save_dictionary_entries** and wait for the task to finish let stopwordEntry = StopwordsDictionary.Entry(objectID: entryID, language: .english, word: "down", state: .enabled) try client.saveDictionaryEntries(to: StopwordsDictionary.self, dictionaryEntries: [stopwordEntry]).wait() // Search in the `stopwords` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 1 response = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "\(entryID)") XCTAssertEqual(response.nbHits, 1) // Assert that the retrieved entry matches the saved one XCTAssertEqual(response.hits.first!, stopwordEntry) // Delete the entry with **delete_dictionary_entries** and wait for the task to finish try client.deleteDictionaryEntries(from: StopwordsDictionary.self, withObjectIDs: [entryID]).wait() // Search in the `stopwords` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 response = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) // Retrieve the current dictionary entries and store them in a variable let previousEntries = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "").hits // Add the following entry in the `stopwords` dictionary with **save_dictionary_entries** and wait for the task to finish try client.saveDictionaryEntries(to: StopwordsDictionary.self, dictionaryEntries: [stopwordEntry]).wait() // Search in the `stopwords` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 1 response = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "\(entryID)") XCTAssertEqual(response.nbHits, 1) // Replace all the entries in the `stopwords` dictionary with the previously stored entries try client.replaceDictionaryEntries(in: StopwordsDictionary.self, with: previousEntries) .wait() // Search in the `stopwords` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 response = try client.searchDictionaryEntries(in: StopwordsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) // Set dictionaries settings with **set_dictionary_settings** the following settings and wait for the task to finish let settings = DictionarySettings(disableStandardEntries: .init(stopwords: [.english: true, .french: true])) try client.setDictionarySettings(settings).wait() // Retrieve the dictionary settings with **get_dictionary_settings** and assert the settings match the one saved let fetchedSettings = try client.getDictionarySettings() XCTAssertEqual(settings, fetchedSettings) } func compoundsDictionary() throws { // Create one `entry_id` with a random string let entryID = ObjectID(rawValue: .random(length: 10)) // Search in the `compounds` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 var response = try client.searchDictionaryEntries(in: CompoundsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) // Add the following entry in the `compounds` dictionary with **save_dictionary_entries** and wait for the task to finish let compoundEntry = CompoundsDictionary.Entry(objectID: entryID, language: .german, word: "kopfschmerztablette", decomposition: ["kopf", "schmerz", "tablette"]) try client.saveDictionaryEntries(to: CompoundsDictionary.self, dictionaryEntries: [compoundEntry]).wait() // Search in the `compounds` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 1 response = try client.searchDictionaryEntries(in: CompoundsDictionary.self, query: "\(entryID)") XCTAssertEqual(response.nbHits, 1) // Assert that the retrieved entry matches the saved one XCTAssertEqual(response.hits.first!, compoundEntry) // Delete the entry with **delete_dictionary_entries** and wait for the task to finish try client.deleteDictionaryEntries(from: CompoundsDictionary.self, withObjectIDs: [entryID]).wait() // Search in the `compounds` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 response = try client.searchDictionaryEntries(in: CompoundsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) } func pluralsDictionary() throws { // Create one `entry_id` with a random string let entryID = ObjectID(rawValue: .random(length: 10)) // Search in the `plurals` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 var response = try client.searchDictionaryEntries(in: PluralsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) // Add the following entry in the `plurals` dictionary with **save_dictionary_entries** and wait for the task to finish let pluralEntry = PluralsDictionary.Entry(objectID: entryID, language: .french, words: ["cheval", "chevaux"]) try client.saveDictionaryEntries(to: PluralsDictionary.self, dictionaryEntries: [pluralEntry]).wait() // Search in the `plurals` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 1 response = try client.searchDictionaryEntries(in: PluralsDictionary.self, query: "\(entryID)") XCTAssertEqual(response.nbHits, 1) // Assert that the retrieved entry matches the saved one XCTAssertEqual(response.hits.first!, pluralEntry) // Delete the entry with **delete_dictionary_entries** and wait for the task to finish try client.deleteDictionaryEntries(from: PluralsDictionary.self, withObjectIDs: [entryID]).wait() // Search in the `plurals` dictionary with **search_dictionary_entries** for the entry_id and assert that the result count is 0 response = try client.searchDictionaryEntries(in: PluralsDictionary.self, query: "\(entryID)") XCTAssert(response.hits.isEmpty) } }
mit
b2de7f6d88c1a3ad2a7e9f552d8d3612
52.978261
164
0.740905
4.687854
false
true
false
false
kickstarter/ios-oss
Library/Tracking/KSRAnalyticsIdentityDataTests.swift
1
3327
@testable import KsApi @testable import Library import Prelude import XCTest final class KSRAnalyticsIdentityDataTests: XCTestCase { func testInitialization() { let user = User.template |> User.lens.name .~ "Test User" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true let data = KSRAnalyticsIdentityData(user) XCTAssertEqual(data.userId, 1) XCTAssertEqual(data.uniqueTraits(comparedTo: nil)["name"] as? String, "Test User") XCTAssertEqual(data.uniqueTraits(comparedTo: nil)["notify_mobile_of_backings"] as? Bool, false) XCTAssertEqual(data.uniqueTraits(comparedTo: nil)["notify_of_messages"] as? Bool, true) } func testUniqueTraits() { let user1 = User.template |> User.lens.name .~ "Test User 1" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true let user2 = User.template |> User.lens.name .~ "Test User 2" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true |> User.lens.notifications.friendActivity .~ true let data1 = KSRAnalyticsIdentityData(user1) let data2 = KSRAnalyticsIdentityData(user2) let uniqueTraits = data2.uniqueTraits(comparedTo: data1) XCTAssertEqual(uniqueTraits.keys.count, 2) XCTAssertEqual(uniqueTraits["name"] as? String, "Test User 2") XCTAssertEqual(uniqueTraits["notify_of_friend_activity"] as? Bool, true) } func testEquality() { let user1 = User.template |> User.lens.name .~ "Test User 1" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true let user2 = User.template |> User.lens.name .~ "Test User 1" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true XCTAssertEqual(KSRAnalyticsIdentityData(user1), KSRAnalyticsIdentityData(user2)) let user3 = User.template |> User.lens.name .~ "Test User 2" |> User.lens.notifications.mobileBackings .~ false |> User.lens.notifications.messages .~ true let user4 = User.template |> User.lens.name .~ "Test User 3" |> User.lens.notifications.mobileBackings .~ true |> User.lens.notifications.messages .~ true XCTAssertNotEqual(KSRAnalyticsIdentityData(user3), KSRAnalyticsIdentityData(user4)) let user5 = User.template |> User.lens.id .~ 1 let user6 = User.template |> User.lens.id .~ 2 XCTAssertNotEqual(KSRAnalyticsIdentityData(user5), KSRAnalyticsIdentityData(user6)) } func testAllTraits() { let user = User.template let data = KSRAnalyticsIdentityData(user) let traits = data.allTraits XCTAssertEqual(traits["name"] as? String, user.name) let notifications = user.notifications.encode() for (key, _) in notifications { XCTAssertEqual(notifications[key] as? Bool, traits[key] as? Bool) } } func testEncodingDecoding() { let data1 = KSRAnalyticsIdentityData(.template) guard let encoded = try? JSONEncoder().encode(data1) else { XCTFail("Failed to encode") return } let decoded = try? JSONDecoder().decode(KSRAnalyticsIdentityData.self, from: encoded) XCTAssertEqual(decoded, data1) } }
apache-2.0
2cfb36062175c704b0833955e5dfe6eb
30.386792
99
0.68951
4.371879
false
true
false
false
samodom/TestSwagger
SampleTypes/Spyables/SwiftSpyables.swift
1
3241
// // SwiftSpyables.swift // SampleTypes // // Created by Sam Odom on 12/17/16. // Copyright © 2016 Swagger Soft. All rights reserved. // // Well-known return values @objc public enum WellKnownMethodReturnValues: Int { case definedAtRoot = 14 case overriddenAtLevel1 = 42 case overriddenAtLevel2 = 99 case commonSpyValue = -18 } // Root sample class public class SwiftRootSpyable { public dynamic class func sampleClassMethod(_ input: String) -> Int { return WellKnownMethodReturnValues.definedAtRoot.rawValue } public dynamic func sampleInstanceMethod(_ input: String) -> Int { return WellKnownMethodReturnValues.definedAtRoot.rawValue } public init() {} } // Inheriting subclasses public class SwiftInheritor: SwiftRootSpyable {} public class SwiftInheritorOfInheritor: SwiftInheritor {} // Overriding subclasses public class SwiftOverrider: SwiftRootSpyable { public static var swiftOverriderCallsSuperclass = false public override class func sampleClassMethod(_ input: String) -> Int { if SwiftOverrider.swiftOverriderCallsSuperclass { return super.sampleClassMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel1.rawValue } } public override func sampleInstanceMethod(_ input: String) -> Int { if SwiftOverrider.swiftOverriderCallsSuperclass { return super.sampleInstanceMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel1.rawValue } } } public class SwiftOverriderOfOverrider: SwiftOverrider { public static var swiftOverriderOfOverriderCallsSuperclass = false public override class func sampleClassMethod(_ input: String) -> Int { if SwiftOverriderOfOverrider.swiftOverriderOfOverriderCallsSuperclass { return super.sampleClassMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel2.rawValue } } public override func sampleInstanceMethod(_ input: String) -> Int { if SwiftOverriderOfOverrider.swiftOverriderOfOverriderCallsSuperclass { return super.sampleInstanceMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel2.rawValue } } } // Hybrid subclasses public class SwiftOverriderOfInheritor: SwiftInheritor { public static var swiftOverriderOfInheritorCallsSuperclass = false public override class func sampleClassMethod(_ input: String) -> Int { if SwiftOverriderOfInheritor.swiftOverriderOfInheritorCallsSuperclass { return super.sampleClassMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel2.rawValue } } public override func sampleInstanceMethod(_ input: String) -> Int { if SwiftOverriderOfInheritor.swiftOverriderOfInheritorCallsSuperclass { return super.sampleInstanceMethod(input) } else { return WellKnownMethodReturnValues.overriddenAtLevel2.rawValue } } } public class SwiftInheritorOfOverrider: SwiftOverrider {}
mit
60f20485781bb88a2f07eed8a19a51ec
25.557377
79
0.703086
5.858951
false
false
false
false
ancode-cn/Meizhi
Meizhi/Classes/sdk/ui/WebViewController.swift
1
4476
// // WebViewController.swift // Meizhi // // Created by snowleft on 15/9/24. // Copyright (c) 2015年 ancode. All rights reserved. // import UIKit // 公共WebViewController class WebViewController: UIViewController { private var url:String? private let webView = UIWebView() private lazy var progressbar:NJKWebViewProgressView = { let progressbar:NJKWebViewProgressView = NJKWebViewProgressView() let progressBarHeight:CGFloat = 2.0 let navigaitonBarBounds = self.navigationController?.navigationBar.bounds var barFrame = CGRectMake(0, (navigaitonBarBounds?.size.height)! - progressBarHeight , (navigaitonBarBounds?.size.width)!, progressBarHeight); progressbar.frame = barFrame // progressbar.autoresizingMask = UIViewAutoresizing.FlexibleWidth // UIViewAutoresizing.FlexibleTopMargin return progressbar }() private let cancelActionSheetJS = "document.documentElement.style.webkitTouchCallout = 'none';" func setUrl(url:String?){ self.url = url } override func viewDidLoad() { super.viewDidLoad() print("WebViewController===\(url)") initWebView() configWebView(webView) configLoadingProgress() if url != nil{ webView.loadRequest(NSURLRequest(URL: NSURL(string: url!)!)) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.addSubview(progressbar) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) progressbar.removeFromSuperview() } // 清除指定domain的cookies private func clearCookie(domain:String){ if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies{ for cookie in cookies{ if cookie.domain == domain{ NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie) } } } } private func initWebView() -> UIWebView{ webView.backgroundColor = UIColor.whiteColor() self.view.addSubview(webView) webView.mas_makeConstraints { (make) -> Void in make.edges.equalTo()(self.view) } return webView } private func configWebView(webView:UIWebView){ webView.scalesPageToFit = true webView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber } private func configLoadingProgress(){ // let _progressProxy = NJKWebViewProgress() // webView.delegate = _progressProxy // _progressProxy.webViewProxyDelegate = self // _progressProxy.progressDelegate = self webView.delegate = self } deinit{ webView.stopLoading() SVProgressHUD.dismiss() } } // MARK: - NJKWebViewProgressDelegate extension WebViewController: NJKWebViewProgressDelegate{ func webViewProgress(webViewProgress: NJKWebViewProgress!, updateProgress progress: Float) { // progressbar.progress = progress print(progress) } } // MARK: - UIWebViewDelegate extension WebViewController: UIWebViewDelegate{ // 使用flashScrollIndicators方法显示滚动标识然后消失,告知用户此页面可以滚动,后面还有更多内容 func handleFlashScrollIndicators(){ for view in webView.subviews{ if view.respondsToSelector("flashScrollIndicators"){ view.performSelector("flashScrollIndicators") } } } // 取消长按webView上的链接弹出actionSheet的问题 func cancelActionSheetWhenLinkClick(){ webView.stringByEvaluatingJavaScriptFromString(cancelActionSheetJS) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{ return true } func webViewDidStartLoad(webView: UIWebView){ SVProgressHUD.show() } func webViewDidFinishLoad(webView: UIWebView){ cancelActionSheetWhenLinkClick() handleFlashScrollIndicators() SVProgressHUD.dismiss() } func webView(webView: UIWebView, didFailLoadWithError error: NSError?){ SVProgressHUD.dismiss() SVProgressHUD.showErrorWithStatus("加载出错,请重试!") } }
mit
cc723d7b5022e20d6fc9a44b11ea2b22
29.605634
136
0.661528
5.425718
false
false
false
false
txstate-etc/mobile-tracs-ios
mobile-tracs-ios/WebViewController.swift
1
11553
// // WebViewController.swift // mobile-tracs-ios // // Created by Nick Wing on 3/17/17. // Copyright © 2017 Texas State University. All rights reserved. // import UIKit import MessageUI import WebKit class WebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, MFMailComposeViewControllerDelegate, UIDocumentInteractionControllerDelegate { @IBOutlet weak var wvContainer: UIView! @IBOutlet var toolBar: UIToolbar! @IBOutlet var back: UIBarButtonItem! @IBOutlet var forward: UIBarButtonItem! @IBOutlet var refresh: UIBarButtonItem! @IBOutlet var interaction: UIBarButtonItem! var webview:WKWebView! var documentInteractionController: UIDocumentInteractionController? let documentsPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] let stop = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(pressedRefresh(sender:))) let loginUrl = Secrets.shared.loginbaseurl ?? "https://login.its.txstate.edu" var urlToLoad: String? var bellnumber: Int? var wasLogout = false var urltoload:String? override func viewDidLoad() { super.viewDidLoad() Utils.showActivity(view) webview = Utils.getWebView() wvContainer.addSubview(webview) Utils.constrainToContainer(view: webview, container: wvContainer) webview.navigationDelegate = self webview.uiDelegate = self toolBar.isHidden = true let iconSize: CGSize = CGSize(width: 28, height: 28) let backImage = UIImage.fontAwesomeIcon(name: .chevronLeft, textColor: UIColor.blue, size: iconSize) let forwardImage = UIImage.fontAwesomeIcon(name: .chevronRight, textColor: UIColor.blue, size: iconSize) back = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(pressedBack(sender:))) forward = UIBarButtonItem(image: forwardImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(pressedForward(sender:))) var tb = toolBar.items! tb[1] = back; tb[3] = forward; toolBar.setItems(tb, animated: false) refresh.action = #selector(pressedRefresh(sender:)) interaction.action = #selector(pressedInteraction(sender:)) back.accessibilityLabel = "back" forward.accessibilityLabel = "forward" self.load() Analytics.viewWillAppear("WebView") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidAppear(_ animated: Bool) { loginIfNecessary { (loggedin) in if !loggedin { let lvc = LoginViewController() DispatchQueue.main.async { self.present(lvc, animated: true) { self.navigationController?.popToRootViewController(animated: true) Utils.hideActivity() } } } else { DispatchQueue.main.async { Utils.hideActivity() } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } // MARK: - Helper functions func load() { loginIfNecessary { (loggedin) in if loggedin { let urlString = self.urlToLoad ?? TRACSClient.portalurl if let url = URL(string: urlString) { let req = URLRequest(url: url) self.webview.load(req) } } } } func loginIfNecessary(completion:@escaping(Bool)->Void) { TRACSClient.loginIfNecessary { (loggedin) in DispatchQueue.main.async { completion(loggedin) } } } // MARK: - Button Presses func pressedBack(sender: UIBarButtonItem!) { webview.goBack() } func pressedForward(sender: UIBarButtonItem!) { webview.goForward() } func pressedRefresh(sender: UIBarButtonItem!) { if webview.isLoading { webview.stopLoading() } else { webview.reload() } } func pressedInteraction(sender: UIBarButtonItem!) { let fileUrl = webview.url if fileUrl == nil { return } let filename = fileUrl?.lastPathComponent; let downloadpath = documentsPath+"/"+filename! let downloadurl = URL(fileURLWithPath: downloadpath) interaction.isEnabled = false URLSession.shared.dataTask(with: fileUrl!) { (tmp, response, error) in if (error != nil) { NSLog("Unable to download file. %@", error!.localizedDescription) return } // Save the loaded data if loaded successfully do { try tmp!.write(to: downloadurl, options: [Data.WritingOptions.atomicWrite]) } catch { NSLog("Failed to save the file to disk. %@", error.localizedDescription) return } NSLog("Saved file to location: %@", downloadpath) // Initialize Document Interaction Controller in main thread DispatchQueue.main.async { self.documentInteractionController = UIDocumentInteractionController(url: downloadurl) self.documentInteractionController?.delegate = self self.documentInteractionController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true) } }.resume() } func pressedBell() { let nvStoryBoard = UIStoryboard(name: "MainStory", bundle: nil) let nvController = nvStoryBoard.instantiateViewController(withIdentifier: "Dashboard") navigationController?.pushViewController(nvController, animated: true) } func pressedMenu() { let mvStoryBoard = UIStoryboard(name: "MainStory", bundle: nil) let mvController = mvStoryBoard.instantiateViewController(withIdentifier: "MenuView") navigationController?.pushViewController(mvController, animated: true) } func updateButtons() { forward.isEnabled = webview.canGoForward back.isEnabled = webview.canGoBack var tb = toolBar.items! tb[5] = (webview.isLoading ? stop : refresh); toolBar.setItems(tb, animated: false) interaction.isEnabled = false let shouldDisplayNavigation = forward.isEnabled || back.isEnabled || interaction.isEnabled if shouldDisplayNavigation { toolBar.isHidden = false } if let ext = webview.url?.pathExtension.lowercased() { if !ext.isEmpty && ext != "html" { interaction.isEnabled = true } } } // MARK: - UIWebViewDelegate func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { updateButtons() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { updateButtons() Utils.hideActivity() if let urlstring = webView.url?.absoluteString { if urlstring.hasPrefix(TRACSClient.tracsurl) && TRACSClient.userid.isEmpty { loginIfNecessary(completion: { (loggedin) in }) } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { NSLog("webView didFail navigation %@", error.localizedDescription) updateButtons() } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if var urlstring = navigationAction.request.url?.absoluteString { if navigationAction.request.url?.scheme == "mailto" { Analytics.event(category: "E-mail", action: "compose", label: urlstring, value: nil) let mvc = MFMailComposeViewController() mvc.mailComposeDelegate = self let rawcomponents = urlstring.characters.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false).map(String.init) let mailtocomponents = rawcomponents[1].characters.split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false).map(String.init) let recipients = mailtocomponents[0].components(separatedBy: ";") var params = [String:String]() if mailtocomponents.count == 2 { let pairs = mailtocomponents[1].components(separatedBy: "&") for pair in pairs { let p = pair.components(separatedBy: "=") let key = p[0].removingPercentEncoding?.lowercased() let value = p[1].removingPercentEncoding if p.count == 2 { params[key!] = value } } } mvc.setToRecipients(recipients) if !(params["subject"] ?? "").isEmpty { mvc.setSubject(params["subject"]!) } if !(params["body"] ?? "").isEmpty { mvc.setMessageBody(params["body"]!, isHTML: false) } if !(params["cc"] ?? "").isEmpty { mvc.setCcRecipients(params["cc"]?.components(separatedBy: ";")) } if !(params["bcc"] ?? "").isEmpty { mvc.setBccRecipients(params["bcc"]?.components(separatedBy: ";")) } self.present(mvc, animated: true, completion: nil) return decisionHandler(.cancel) } Analytics.linkClick(urlstring) if urlstring == "about:blank" { return decisionHandler(.cancel) } if urlstring.contains(TRACSClient.logouturl) || urlstring.contains(TRACSClient.altlogouturl) { TRACSClient.userid = "" Utils.removeCredentials() IntegrationClient.unregister() UIApplication.shared.applicationIconBadgeNumber = 0 wasLogout = true } } decisionHandler(.allow) } // this handles target=_blank links by opening them in the same view func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { webView.load(navigationAction.request) } return nil } // MARK: - UIDocumentInteractionControllerDelegate func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) { interaction.isEnabled = true do { try FileManager.default.removeItem(at: controller.url!) NSLog("deleted temporary file at %@", controller.url?.absoluteString ?? "nil") } catch { NSLog("documentInteractionController was unable to clean up after itself") } } // MARK: - MFMailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { self.dismiss(animated: true, completion: nil) } }
mit
803b959d128d2d1ffdd6db6162cd514b
40.257143
187
0.610197
5.482677
false
false
false
false
alexeyxo/swift-apns
Source/APNS-Protobuf.swift
1
2833
// // APNS-Protobuf.swift // APNS // // Created by Alexey Khokhlov on 30.01.16. // Copyright © 2016 Alexey Khokhlov. All rights reserved. // import Foundation //extension extension APNSNetwork { public func sendPush(pushService:Apple.Apns.ProviderData, responseBlock:((_ response:Apple.Apns.Response) -> Void)?, networkError:((Error?) -> ())?) throws -> URLSessionDataTask? { let payload = try getPayload(push: pushService) var sandbox = true if pushService.serviceIdentity == .production { sandbox = false } let task = try sendPushWith(topic:pushService.bundle, priority: Int(pushService.priority), payload: payload, deviceToken: pushService.token, certificatePath: pushService.certificatePath, passphrase: pushService.certificatePassphrase, sandbox: sandbox, responseBlock: { (response) -> Void in let responseObject = APNServiceStatus.getResponseObject(response: response) responseBlock?(responseObject) }, networkError: networkError) return task } private func getIdentityWith(providerData:Apple.Apns.ProviderData) -> SecIdentity? { return getIdentityWith(certificatePath:providerData.certificatePath, passphrase: providerData.certificatePassphrase) } private func getPayload(push:Apple.Apns.ProviderData) throws -> Dictionary<String,Any> { var payload = try push.payload.encode() if var aps = payload["aps"] as? Dictionary<String,Any> { if let contentAvailable = aps["contentAvailable"] { aps["content-available"] = contentAvailable aps.removeValue(forKey:"contentAvailable") } if let mutableContent = aps["mutableContent"] { aps["mutable-content"] = mutableContent aps.removeValue(forKey: "mutableContent") } payload["aps"] = aps } return payload } } extension APNServiceStatus { public static func getResponseObject(response:APNServiceResponse) -> Apple.Apns.Response { let builder = Apple.Apns.Response.Builder() builder.statusCode = Int32(response.serviceStatus.0) if let reason = response.serviceErrorReason { builder.reason = reason.rawValue builder.reasonDescription = reason.getReasonDescription() } if let apnsId = response.apnsId { builder.apnsId = apnsId } return try! builder.build() } }
apache-2.0
5a57a9505f4c86b717ab909d0446bac5
38.333333
184
0.58404
5.509728
false
false
false
false
annarev/tensorflow
tensorflow/lite/swift/Sources/Tensor.swift
11
4323
// Copyright 2018 Google Inc. 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 TensorFlowLiteC /// An input or output tensor in a TensorFlow Lite graph. public struct Tensor: Equatable, Hashable { /// The name of the `Tensor`. public let name: String /// The data type of the `Tensor`. public let dataType: DataType /// The shape of the `Tensor`. public let shape: Shape /// The data in the input or output `Tensor`. public let data: Data /// The quantization parameters for the `Tensor` if using a quantized model. public let quantizationParameters: QuantizationParameters? /// Creates a new input or output `Tensor` instance. /// /// - Parameters: /// - name: The name of the `Tensor`. /// - dataType: The data type of the `Tensor`. /// - shape: The shape of the `Tensor`. /// - data: The data in the input `Tensor`. /// - quantizationParameters Parameters for the `Tensor` if using a quantized model. The default /// is `nil`. init( name: String, dataType: DataType, shape: Shape, data: Data, quantizationParameters: QuantizationParameters? = nil ) { self.name = name self.dataType = dataType self.shape = shape self.data = data self.quantizationParameters = quantizationParameters } } extension Tensor { /// The supported `Tensor` data types. public enum DataType: Equatable, Hashable { /// A boolean. case bool /// An 8-bit unsigned integer. case uInt8 /// A 16-bit signed integer. case int16 /// A 32-bit signed integer. case int32 /// A 64-bit signed integer. case int64 /// A 16-bit half precision floating point. case float16 /// A 32-bit single precision floating point. case float32 /// A 64-bit double precision floating point. case float64 /// Creates a new instance from the given `TfLiteType` or `nil` if the data type is unsupported /// or could not be determined because there was an error. /// /// - Parameter type: A data type for a tensor. init?(type: TfLiteType) { switch type { case kTfLiteBool: self = .bool case kTfLiteUInt8: self = .uInt8 case kTfLiteInt16: self = .int16 case kTfLiteInt32: self = .int32 case kTfLiteInt64: self = .int64 case kTfLiteFloat16: self = .float16 case kTfLiteFloat32: self = .float32 case kTfLiteFloat64: self = .float64 case kTfLiteNoType: fallthrough default: return nil } } } } extension Tensor { /// The shape of a `Tensor`. public struct Shape: Equatable, Hashable { /// The number of dimensions of the `Tensor`. public let rank: Int /// An array of dimensions for the `Tensor`. public let dimensions: [Int] /// An array of `Int32` dimensions for the `Tensor`. var int32Dimensions: [Int32] { return dimensions.map(Int32.init) } /// Creates a new instance with the given array of dimensions. /// /// - Parameters: /// - dimensions: Dimensions for the `Tensor`. public init(_ dimensions: [Int]) { self.rank = dimensions.count self.dimensions = dimensions } /// Creates a new instance with the given elements representing the dimensions. /// /// - Parameters: /// - elements: Dimensions for the `Tensor`. public init(_ elements: Int...) { self.init(elements) } } } extension Tensor.Shape: ExpressibleByArrayLiteral { /// Creates a new instance with the given array literal representing the dimensions. /// /// - Parameters: /// - arrayLiteral: Dimensions for the `Tensor`. public init(arrayLiteral: Int...) { self.init(arrayLiteral) } }
apache-2.0
d79aec428e0f1de1178f7511d46439a3
28.013423
100
0.650474
4.234084
false
false
false
false
sashohadz/swift
examPrep/examPrep/examPrep/ApplicationContainer.swift
1
1092
// // ViewController.swift // examPrep // // Created by Sasho Hadzhiev on 2/15/17. // Copyright © 2017 Sasho Hadzhiev. All rights reserved. // import UIKit class ApplicationContainer: UIViewController { var userLoggedIn:Bool! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { if let autoUserLoginEnabled = UserDefaults.standard.object(forKey: UserDefaultKeys.autoLoginEnabled.rawValue) { self.userLoggedIn = autoUserLoginEnabled as? Bool } else { self.userLoggedIn = false } } override func viewDidAppear(_ animated: Bool) { if userLoggedIn == true { self.performSegue(withIdentifier: "ToMainScreenSegue", sender: nil) } else { self.performSegue(withIdentifier: "ToLoginSegue", sender: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
59c83f90dcbad8450b99c2d09400660d
22.717391
119
0.621448
4.806167
false
false
false
false
dusek/firefox-ios
Providers/Favicons.swift
1
2953
/* 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 UIKit import CoreData /* * Types of Favicons that pages might provide. Allows callers to differentiate between an article image * favicons, and other types of images provided by the site. */ enum FaviconType { case Favicon; } /* * Useful constants */ struct FaviconConsts { static let DefaultFaviconName : String = "leaf.png" static let DefaultFavicon : String = "resource:" + DefaultFaviconName static let DefaultFaviconUrl : NSURL = NSURL(string: DefaultFavicon)! } /* * Options opbject to allow specifying a preferred size or type of favicon to request */ struct FaviconOptions { let type: FaviconType let desiredSize: Int } protocol Favicons { func clearFavicons(siteUrl: String, success: () -> Void, failure: (Any) -> Void) func saveFavicon(siteUrl: String, iconUrl: String, image: UIImage?, success: (Favicon) -> Void, failure: (Any) -> Void) func getForUrls(urls: [String], options: FaviconOptions?, success: ([String: [Favicon]]) -> Void) func getForUrl(url: String, options: FaviconOptions?, success: (Favicon) -> Void) } /* * A Base favicon implementation, Always returns a default for now. */ class BasicFavicons : Favicons { lazy var DEFAULT_IMAGE : UIImage = { var img = UIImage(named: FaviconConsts.DefaultFaviconName)! return img; }(); init() { } func clearFavicons(siteUrl: String, success: () -> Void, failure: (Any) -> Void) { failure("Not implemented") } func saveFavicon(siteUrl: String, iconUrl: String, image: UIImage? = nil, success: (Favicon) -> Void, failure: (Any) -> Void) { failure("Not implemented") } func getForUrls(urls: [String], options: FaviconOptions?, success: ([String: [Favicon]]) -> Void) { let result = [String:[Favicon]]() success(result) } func getForUrl(url: String, options: FaviconOptions?, success: (Favicon) -> Void) { let urls = [url]; getForUrls(urls, options: options, success: { data in var icons = data[url] success(icons![0]) }) } } public func createSizedFavicon(icon: UIImage) -> UIImage { let size = CGSize(width: 30, height: 30) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) var context = UIGraphicsGetCurrentContext() icon.drawInRect(CGRectInset(CGRect(origin: CGPointZero, size: size), 1.0, 1.0)) CGContextSetStrokeColorWithColor(context, UIColor.grayColor().CGColor) CGContextSetLineWidth(context, 0.5); CGContextStrokeEllipseInRect(context, CGRectInset(CGRect(origin: CGPointZero, size: size), 1.0, 1.0)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image }
mpl-2.0
aa574073cb6813afae9f74ca4dc6ba84
32.942529
131
0.681341
4.176803
false
false
false
false
mileswd/mac2imgur
mac2imgur/StatusItemController.swift
1
3912
/* This file is part of mac2imgur. * * mac2imgur 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. * mac2imgur 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 mac2imgur. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa import AFNetworking class StatusItemController: NSObject, NSWindowDelegate, NSDraggingDestination { let statusItem: NSStatusItem let statusItemMenuController: StatusItemMenuController var currentOperationCount = 0 override init() { statusItem = NSStatusBar.system().statusItem( withLength: NSVariableStatusItemLength) statusItemMenuController = StatusItemMenuController() super.init() statusItem.menu = statusItemMenuController.menu updateStatusItemImage() // Enable drag and drop upload if OS X >= 10.10 if #available(macOS 10.10, *) { statusItem.button?.window?.delegate = self statusItem.button?.window? .registerForDraggedTypes([NSFilenamesPboardType, NSTIFFPboardType]) } NotificationCenter.default.addObserver(forName: .AFNetworkingTaskDidResume, object: nil, queue: nil, using: notificationHandler) NotificationCenter.default.addObserver(forName: .AFNetworkingTaskDidComplete, object: nil, queue: nil, using: notificationHandler) } func notificationHandler(notification: Notification) { if notification.name == .AFNetworkingTaskDidResume { currentOperationCount += 1 } else if notification.name == .AFNetworkingTaskDidComplete { currentOperationCount -= 1 } updateStatusItemImage() } func updateStatusItemImage() { statusItem.image = currentOperationCount > 0 ? #imageLiteral(resourceName: "StatusActive") : #imageLiteral(resourceName: "StatusInactive") } deinit { NSStatusBar.system().removeStatusItem(statusItem) } // MARK: NSDraggingDestination func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { if let paths = sender.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? [String] { for path in paths { var isDirectory: ObjCBool = false if !FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) || isDirectory.boolValue { return [] } } } return .copy } func performDragOperation(_ sender: NSDraggingInfo) -> Bool { if let data = sender.draggingPasteboard().data(forType: NSTIFFPboardType) { ImgurClient.shared.uploadImage(withData: data) return true } else if let paths = sender.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? [String] { for path in paths { ImgurClient.shared.uploadImage(withURL: URL(fileURLWithPath: path), isScreenshot: false) } return true } return false } }
gpl-3.0
322b53f5b2082636512db3ad6a025544
36.980583
117
0.59816
5.812779
false
false
false
false
domenicosolazzo/practice-swift
iCloud/Tinypix/Tinypix/TinyPixView.swift
1
4138
// // TinyPixView.swift // Tinypix // // Created by Domenico on 28/04/15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit struct GridIndex { var row: Int var column: Int } class TinyPixView: UIView { var document: TinyPixDocument! var lastSize: CGSize = CGSize.zero var gridRect: CGRect! var blockSize: CGSize! var gap: CGFloat = 0 var selectedBlockIndex: GridIndex = GridIndex(row: NSNotFound, column: NSNotFound) //- MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { calculateGridForSize(bounds.size) } fileprivate func calculateGridForSize(_ size: CGSize) { let space = min(size.width, size.height) gap = space/57 let cellSide = gap * 6 blockSize = CGSize(width: cellSide, height: cellSide) gridRect = CGRect(x: (size.width - space)/2, y: (size.height - space)/2, width: space, height: space) } //- MARK: Draw // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { if (document != nil) { let size = bounds.size if !size.equalTo(lastSize) { lastSize = size calculateGridForSize(size) } for row in 0 ..< 8 { for column in 0 ..< 8 { drawBlockAt(row: row, column: column) } } } } fileprivate func drawBlockAt(#row: Int, _ column: Int) { let startX = gridRect.origin.x + gap + (blockSize.width + gap) * (7 - CGFloat(column)) + 1 let startY = gridRect.origin.y + gap + (blockSize.height + gap) * CGFloat(row) + 1 let blockFrame = CGRect(x: startX, y: startY, width: blockSize.width, height: blockSize.height) let color = document.stateAt(row: row, column: column) ? UIColor.blackColor() : UIColor.whiteColor() color.setFill() tintColor.setStroke() let path = UIBezierPath(rect:blockFrame) path.fill() path.stroke() } //- MARK: Touch events fileprivate func touchedGridIndexFromTouches(_ touches: NSSet) -> GridIndex { var result = GridIndex(row: -1, column: -1) let touch = touches.anyObject() as! UITouch var location = touch.location(in: self) if gridRect.contains(location) { location.x -= gridRect.origin.x location.y -= gridRect.origin.y result.column = Int(8 - (location.x * 8.0 / gridRect.size.width)) result.row = Int(location.y * 8.0 / gridRect.size.height) } return result } fileprivate func toggleSelectedBlock() { if selectedBlockIndex.row != -1 && selectedBlockIndex.column != -1 { document.toggleStateAt(row: selectedBlockIndex.row, column: selectedBlockIndex.column) (document.undoManager.prepare(withInvocationTarget: document) as AnyObject) .toggleStateAt(row: selectedBlockIndex.row, column: selectedBlockIndex.column) setNeedsDisplay() } } override func touchesBegan(_ touches: Set<NSObject>, with event: UIEvent) { selectedBlockIndex = touchedGridIndexFromTouches(touches as NSSet) toggleSelectedBlock() } override func touchesMoved(_ touches: Set<NSObject>, with event: UIEvent) { let touched = touchedGridIndexFromTouches(touches as NSSet) if touched.row != selectedBlockIndex.row && touched.column != selectedBlockIndex.column { selectedBlockIndex = touched toggleSelectedBlock() } } }
mit
78344006473a40db8d7ed2e41dc06cc7
31.328125
91
0.580715
4.582503
false
false
false
false
mozhenhau/D3Notice
D3Notice/ViewController.swift
1
2000
// // ViewController.swift // D3Notice // // Created by mozhenhau on 15/6/11. // Copyright (c) 2015年 mozhenhau. All rights reserved. // import UIKit class ViewController: UIViewController { @IBAction func clickClearNotcie(sender: AnyObject) { clearAll() timer?.invalidate() timer = nil } @IBAction func clickShowSuc(sender: AnyObject) { showNoticeSuc("suc") } @IBAction func clickShowSucNotDisapear(sender: AnyObject) { showNoticeSuc("suc", time: D3NoticeManager.longTime, autoClear: false) } @IBAction func clickShowErr(sender: AnyObject) { showNoticeErr("err") } @IBAction func clickSowInfo(sender: AnyObject) { showNoticeInfo("info") } @IBAction func clickShowWait(sender: AnyObject) { showNoticeWait() } @IBAction func clickShowText(sender: AnyObject) { showNoticeText("text") } @IBAction func clickShowSuc2(sender: AnyObject) { D3NoticeManager.sharedInstance.showNoticeWithText(NoticeType.Success, text: "suc",time: D3NoticeManager.longTime, autoClear: true) } var progress:Double = 0 var timer:NSTimer? var type:NoticeType = NoticeType.CircleProgress @IBAction func clickProgressCircle(sender: AnyObject) { progress = 0 timer?.invalidate() type = NoticeType.CircleProgress timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateProgress:"), userInfo: nil, repeats: true) } @IBAction func clickProgressLine(sender: AnyObject) { progress = 0 timer?.invalidate() type = NoticeType.LineProgress timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateProgress:"), userInfo: nil, repeats: true) } func updateProgress(timer:NSTimer){ progress += 0.01 self.showProgressView(progress, type: type) } }
mit
b668e98cd3691e1d3139b8d941572805
26.369863
142
0.653153
4.520362
false
false
false
false
TonnyTao/Acornote
Acornote_iOS/Acornote/CoreData/Folder+CoreDataClass.swift
1
3375
// // Folder+CoreDataClass.swift // Acornote // // Created by Tonny on 27/10/2016. // Copyright © 2016 Tonny&Sunm. All rights reserved. // import Foundation import CoreData import UIKit import SugarRecord enum FolderOrderBy : Int16 { case createdAscend, createdDescent } public class Folder: NSManagedObject { } //MARK: Color extension Folder { //1 is folder.color Coredata default value enum Color: Int16, Comparable { case sky = 1, red, green, yellow, purple, blue public static func <(lhs: Folder.Color, rhs: Folder.Color) -> Bool { return lhs.rawValue < rhs.rawValue } } struct ColorConfig { static let `defalut`: Int16 = Color.sky.rawValue var name: Color var rgb: (Int, Int, Int) static func all() -> [ColorConfig] { return [ ColorConfig(name: .sky, rgb: (25, 210, 185)), ColorConfig(name: .red, rgb: (233, 78, 78)), ColorConfig(name: .green, rgb: (141, 219, 55)), ColorConfig(name: .yellow, rgb: (245, 166, 35)), ColorConfig(name: .purple, rgb: (186, 108, 255)), ColorConfig(name: .blue, rgb: (74, 144, 226))] } var uiColor: UIColor { return UIColor.rgb(rgb.0, rgb.1, rgb.2) } static func color(withId id: Int16) -> ColorConfig? { return all().first { $0.name.rawValue == id } } } class func existColors() -> [ColorConfig] { //TODO by group let folders = try! cdStore.mainContext.request(Folder.self).fetch() var colors:Set = Set<Int16>() folders.forEach { (item) in let color = item.color as Int16 if !colors.contains(color) { colors.insert(color) } } let all = ColorConfig.all() let maps = colors.map { (item) -> ColorConfig? in return all.first(where: { (c) -> Bool in return c.name.rawValue == item }) } let arr = maps.compactMap { $0 } return arr.sorted { $0.name < $1.name } } var highlightColor: UIColor { return Folder.ColorConfig.color(withId: self.color)?.uiColor ?? UIColor.appGreen } } extension Folder { class func audio(title: String, url: String, completion: @escaping ((Data?)->Void)) -> URLSessionTask? { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let file = (path as NSString).appendingPathComponent("\(title)_audio") if let data = try? Data(contentsOf: URL(fileURLWithPath: file)) { completion(data) return nil } let url = URL(string:url)! let request = URLRequest(url: url) return URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in if let d = data { try? d.write(to: URL(fileURLWithPath: file)) DispatchQueue.main.async { completion(d) } }else { DispatchQueue.main.async { completion(nil) } } } } }
apache-2.0
cf120453b1bcdc88e3f4727475ca695c
28.596491
108
0.529638
4.364812
false
true
false
false
synchromation/Buildasaur
Buildasaur/ConfigEditViewController.swift
2
3653
// // ConfigEditViewController.swift // Buildasaur // // Created by Honza Dvorsky on 08/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Cocoa import BuildaUtils import XcodeServerSDK import BuildaKit import ReactiveCocoa class ConfigEditViewController: EditableViewController { let availabilityCheckState = MutableProperty<AvailabilityCheckState>(.Unchecked) @IBOutlet weak var trashButton: NSButton! @IBOutlet weak var lastConnectionView: NSTextField? @IBOutlet weak var progressIndicator: NSProgressIndicator? @IBOutlet weak var serverStatusImageView: NSImageView! var valid: SignalProducer<Bool, NoError>! override func viewDidLoad() { super.viewDidLoad() self.setupUI() self.setupAvailability() } private func setupUI() { if self.serverStatusImageView != nil { //status image let statusImage = self .availabilityCheckState .producer .map { ConfigEditViewController.imageNameForStatus($0) } .map { NSImage(named: $0) } self.serverStatusImageView.rac_image <~ statusImage } if self.trashButton != nil { //only enable the delete button in editing mode self.trashButton.rac_enabled <~ self.editing } } //do not call directly! just override func checkAvailability(statusChanged: ((status: AvailabilityCheckState) -> ())) { assertionFailure("Must be overriden by subclasses") } @IBAction final func trashButtonClicked(sender: AnyObject) { self.delete() } func edit() { self.editing.value = true } func delete() { assertionFailure("Must be overriden by subclasses") } final func recheckForAvailability(completion: ((state: AvailabilityCheckState) -> ())?) { self.editingAllowed.value = false self.checkAvailability { [weak self] (status) -> () in self?.availabilityCheckState.value = status if status.isDone() { completion?(state: status) self?.editingAllowed.value = true } } } private func setupAvailability() { let state = self.availabilityCheckState.producer if let progress = self.progressIndicator { progress.rac_animating <~ state.map { $0 == .Checking } } if let lastConnection = self.lastConnectionView { lastConnection.rac_stringValue <~ state.map { ConfigEditViewController.stringForState($0) } } } private static func stringForState(state: AvailabilityCheckState) -> String { //TODO: add some emoji! switch state { case .Checking: return "Checking access to server..." case .Failed(let error): let desc = (error as? NSError)?.localizedDescription ?? "\(error)" return "Failed to access server, error: \n\(desc)" case .Succeeded: return "Verified access, all is well!" case .Unchecked: return "-" } } private static func imageNameForStatus(status: AvailabilityCheckState) -> String { switch status { case .Unchecked: return NSImageNameStatusNone case .Checking: return NSImageNameStatusPartiallyAvailable case .Succeeded: return NSImageNameStatusAvailable case .Failed(_): return NSImageNameStatusUnavailable } } }
mit
e5005a6709617556b30feec34100ba1f
29.697479
103
0.608541
5.419881
false
false
false
false
SergeMaslyakov/audio-player
app/src/dip/CompositionRoot.swift
1
6126
// // CompositionRoot.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import MediaPlayer import Dip import DipUI import SwiftyBeaver import Reusable extension DependencyContainer { static func configure() -> DependencyContainer { return DependencyContainer { container in unowned let container = container DependencyContainer.uiContainers = [container] container.register(.singleton) { SwiftyBeaver.self } .resolvingProperties { container, logger in logger.addDestination(ConsoleDestination()) } container.register(.singleton) { MPlayerPlaybackWorker() as MPlayerPlaybackWorker } .resolvingProperties { container, worker in let isSystemMusicPlayer = UserDefaults.standard.isSystemAudioPlayer() if isSystemMusicPlayer { worker.player = MPMusicPlayerController.systemMusicPlayer() } else { worker.player = MPMusicPlayerController.applicationMusicPlayer() } } container.register(.singleton) { MusicControllersCoordinator() as MusicControllersCoordinator } container.register(.unique) { RootPresenter() as RootPresenter } container.register(.unique) { AudioSourceDataServiceRealm() as AudioSourceDataService } container.register(.unique) { AppleMusicTracksDataService() as AppleMusicTracksDataService } container.register(.unique) { AppleMusicArtistsDataService() as AppleMusicArtistsDataService } container.register(.unique) { AppleMusicAlbumsDataService() as AppleMusicAlbumsDataService } container.register(.unique) { AppleMusicGenresDataService() as AppleMusicGenresDataService } container.register(.unique) { AppleMusicPlaylistsDataService() as AppleMusicPlaylistsDataService } container.register(tag: OnboardingPage2ViewController.tag) { OnboardingPage2ViewController() } .resolvingProperties { container, controller in controller.presenter = try container.resolve() as RootPresenter } container.register(tag: AudioSourcesViewController.tag) { AudioSourcesViewController() } .resolvingProperties { container, controller in controller.audioSourceService = try! container.resolve() as AudioSourceDataService } container.register(tag: MusicPickerViewController.tag) { MusicPickerViewController() } .resolvingProperties { container, controller in controller.currentMusicState = UserDefaults.standard.getMusicLibraryState() } container.register(tag: ArtistsViewController.tag) { ArtistsViewController() } .resolvingProperties { container, controller in controller.dataService = try! container.resolve() as AppleMusicArtistsDataService } container.register(tag: AlbumsViewController.tag) { AlbumsViewController() } .resolvingProperties { container, controller in controller.dataService = try! container.resolve() as AppleMusicAlbumsDataService } container.register(tag: PlayListsViewController.tag) { PlayListsViewController() } .resolvingProperties { container, controller in controller.dataService = try! container.resolve() as AppleMusicPlaylistsDataService } container.register(tag: SongsViewController.tag) { SongsViewController() } .resolvingProperties { container, controller in controller.dataService = try! container.resolve() as AppleMusicTracksDataService controller.playerWorker = try! container.resolve() as MPlayerPlaybackWorker } container.register(tag: GenresViewController.tag) { GenresViewController() } .resolvingProperties { container, controller in controller.dataService = try! container.resolve() as AppleMusicGenresDataService } } } } extension OnboardingContainerViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension OnboardingPage1ViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension OnboardingPage2ViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension AudioSourcesViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension MusicPickerViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension ArtistsViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension PlayListsViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension AlbumsViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension SongsViewController: StoryboardInstantiatable, UIViewControllerTaggable { } extension GenresViewController: StoryboardInstantiatable, UIViewControllerTaggable { }
apache-2.0
eeda11e6ab0fc7286e722bc83ed29666
34.404624
107
0.59902
7.163743
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Utils/FaviconFetcher+Non-Bundled.swift
1
7116
/* 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 Storage import Shared import XCGLogger import SDWebImage import Fuzi import SwiftyJSON // Extension of FaviconFetcher that handles fetching non-bundled, non-letter favicons extension FaviconFetcher { class func getForURL(_ url: URL, profile: Profile) -> Deferred<Maybe<[Favicon]>> { let favicon = FaviconFetcher() return favicon.loadFavicons(url, profile: profile) } fileprivate func loadFavicons(_ url: URL, profile: Profile, oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> { if isIgnoredURL(url) { return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons.")) } let deferred = Deferred<Maybe<[Favicon]>>() var oldIcons: [Favicon] = oldIcons queue.async { self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in var deferreds = [Deferred<Maybe<Favicon>>]() if let icons = result.successValue { deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) } } return all(deferreds) }).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in for result in results { if let icon = result.successValue { oldIcons.append(icon) } } oldIcons = oldIcons.sorted { return $0.width! > $1.width! } return deferMaybe(oldIcons) }).upon({ (result: Maybe<[Favicon]>) in deferred.fill(result) return }) } return deferred } // Loads and parses an html document and tries to find any known favicon-type tags for the page fileprivate func parseHTMLForFavicons(_ url: URL) -> Deferred<Maybe<[Favicon]>> { return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in var icons = [Favicon]() guard let data = result.successValue, result.isSuccess, let root = try? HTMLDocument(data: data as Data) else { return deferMaybe([]) } var reloadUrl: URL? for meta in root.xpath("//head/meta") { if let refresh = meta["http-equiv"], refresh == "Refresh", let content = meta["content"], let index = content.range(of: "URL="), let url = NSURL(string: String(content[index.upperBound...])) { reloadUrl = url as URL } } if let url = reloadUrl { return self.parseHTMLForFavicons(url) } for link in root.xpath("//head//link[contains(@rel, 'icon')]") { guard let href = link["href"] else { continue //Skip the rest of the loop. But don't stop the loop } if let iconUrl = NSURL(string: href, relativeTo: url as URL), let absoluteString = iconUrl.absoluteString { let icon = Favicon(url: absoluteString) icons = [icon] } // If we haven't got any options icons, then use the default at the root of the domain. if let url = NSURL(string: "/favicon.ico", relativeTo: url as URL), icons.isEmpty, let absoluteString = url.absoluteString { let icon = Favicon(url: absoluteString) icons = [icon] } } return deferMaybe(icons) }) } fileprivate func fetchDataForURL(_ url: URL) -> Deferred<Maybe<Data>> { let deferred = Deferred<Maybe<Data>>() urlSession.dataTask(with: url) { (data, _, error) in if let data = data { deferred.fill(Maybe(success: data)) return } let errorDescription = (error as NSError?)?.description ?? "No content." deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: errorDescription))) }.resume() return deferred } func getFavicon(_ siteUrl: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let url = icon.url let manager = SDWebImageManager.shared let site = Site(url: siteUrl.absoluteString, title: "") var fav = Favicon(url: url) if let url = url.asURL { var fetch: SDWebImageOperation? fetch = manager.loadImage(with: url, options: .lowPriority, progress: { (receivedSize, expectedSize, _) in if receivedSize > FaviconFetcher.MaximumFaviconSize || expectedSize > FaviconFetcher.MaximumFaviconSize { fetch?.cancel() } }, completed: { (img, _, _, _, _, url) in guard let url = url else { deferred.fill(Maybe(failure: FaviconError())) return } fav = Favicon(url: url.absoluteString) if let img = img { fav.width = Int(img.size.width) fav.height = Int(img.size.height) profile.favicons.addFavicon(fav, forSite: site) } else { fav.width = 0 fav.height = 0 } deferred.fill(Maybe(success: fav)) }) } else { return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)")) } return deferred } // Returns the largest Favicon UIImage for a given URL class func fetchFavImageForURL(forURL url: URL, profile: Profile) -> Deferred<Maybe<UIImage>> { let deferred = Deferred<Maybe<UIImage>>() FaviconFetcher.getForURL(url.domainURL, profile: profile).uponQueue(.main) { result in var iconURL: URL? if let favicons = result.successValue, favicons.count > 0, let faviconImageURL = favicons.first?.url.asURL { iconURL = faviconImageURL } else { return deferred.fill(Maybe(failure: FaviconError())) } SDWebImageManager.shared.loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in if let image = image { deferred.fill(Maybe(success: image)) } else { deferred.fill(Maybe(failure: FaviconError())) } } } return deferred } }
mpl-2.0
2cd36cb3048b57a411ea546aab78523b
38.977528
140
0.531619
5.156522
false
false
false
false
huonw/swift
benchmark/single-source/SortLargeExistentials.swift
12
3392
//===--- SortLargeExistentials.swift --------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is a variant of the SortLettersInPlace. import TestsUtils public let SortLargeExistentials = BenchmarkInfo( name: "SortLargeExistentials", runFunction: run_SortLargeExistentials, tags: [.validation, .api, .algorithm]) protocol LetterKind { var value: String { get } func lessthan(_ rhs: LetterKind) -> Bool } // A struct which exceeds the size of the existential inline buffer. struct Letter : LetterKind { let value: String // Make this struct a large struct which does not fit into the 3-word // existential inline buffer. Also provide an answer to ... var a: Int = 42 var b: Int = 42 var c: Int = 42 var d: Int = 42 init(_ value: String) { self.value = value } func lessthan(_ rhs: LetterKind) -> Bool { return value < rhs.value } } let lettersTemplate : [LetterKind] = [ Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"), Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"), Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"), Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"), Letter("z"), Letter("g"), Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"), Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"), Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"), Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"), Letter("z"), Letter("g"), Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"), Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"), Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"), Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"), Letter("z"), Letter("g"), Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"), Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"), Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"), Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"), Letter("z"), Letter("g"), Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"), Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"), Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"), Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"), Letter("z"), Letter("g") ] @inline(never) public func run_SortLargeExistentials(_ N: Int) { for _ in 1...100*N { var letters = lettersTemplate letters.sort { return $0.lessthan($1) } // Check whether letters are sorted. CheckResults(letters[0].value <= letters[letters.count/2].value) } }
apache-2.0
2cfb38a5d64a93fdf4a9c59c247b57a9
37.988506
80
0.580483
3.600849
false
false
false
false
crass45/PoGoApiAppleWatchExample
PoGoApiAppleWatchExample/PGoApi/SnipeController.swift
1
5060
// // PGOApiController.swift // PGoApi // // Created by Jose Luis on 19/8/16. // Copyright © 2016 CocoaPods. All rights reserved. // import PGoApi class SnipeController: AnyObject, PGoApiDelegate { var pokemonName:String var latitude:Double var longitude:Double var antiqueLatitude:Double var antiqueLongitude:Double var wPokem:Pogoprotos.Map.Pokemon.WildPokemon! init(pokeName:String, lat:Double, lon:Double, latAntique:Double, lonAntique:Double) { pokemonName = pokeName latitude = lat longitude = lon antiqueLatitude = latAntique antiqueLongitude = lonAntique } let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate func didReceiveApiResponse(intent: PGoApiIntent, response: PGoApiResponse) { print("Got that API response: \(intent)") if (intent == .EncounterPokemon){ print("ENCOUNTER POKEMON!") // print(response.response) // print(response.subresponses) if response.subresponses.count > 0 { if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.EncounterResponse { if r.status == .EncounterSuccess { updateLocation(antiqueLatitude, lon: antiqueLongitude) appDelegate.manager.startUpdatingLocation() wPokem = r.wildPokemon cazaPokemonConPokeBall(wPokem.encounterId, spawnPointId: wPokem.spawnPointId) } } } } if (intent == .CatchPokemon){ print("CAZANDO POKEMON!") if response.subresponses.count > 0 { if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.CatchPokemonResponse { let status = r.status.toString() print(status) if r.status == .CatchSuccess { //TODO se ha capturado correctamente al pokemon print("CATCH SUCCESS") UIAlertView(title: "POKEMON SNIPEADO", message: "", delegate: self, cancelButtonTitle: "OK").show() } if r.status == .CatchFlee { // print("CATCHFLEE") } if r.status == .CatchError { print("CATCH ERROR") } if r.status == .CatchMissed { print("CATCH MISSED") cazaPokemonConPokeBall(wPokem.encounterId, spawnPointId: wPokem.spawnPointId) } if r.status == .CatchEscape { print("CATCH ESCAPE") cazaPokemonConPokeBall(wPokem.encounterId, spawnPointId: wPokem.spawnPointId) } } } } if (intent == .GetMapObjects) { // print(response) // print(response.subresponses) if response.subresponses.count > 0 { if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.GetMapObjectsResponse { for cell in r.mapCells { for poke in cell.catchablePokemons { //agarramos el pokemon if poke.pokemonId.toString() == pokemonName { request.encounterPokemon(poke.encounterId, spawnPointId: poke.spawnPointId) request.makeRequest(.EncounterPokemon, delegate: self) } } } } } } } func didReceiveApiError(intent: PGoApiIntent, statusCode: Int?) { print("API Error: \(statusCode)") UIAlertView(title: "API ERROR", message: "\(statusCode)", delegate: self, cancelButtonTitle: "OK").show() } func snipe(){ appDelegate.manager.stopUpdatingLocation() updateLocation(latitude, lon: longitude) request.getMapObjects() request.makeRequest(.GetMapObjects, delegate: self) } func cazaPokemonConPokeBall(encounterId:UInt64, spawnPointId:String){ request.catchPokemon(encounterId, spawnPointId: spawnPointId, pokeball: Pogoprotos.Inventory.Item.ItemId.ItemPokeBall, hitPokemon: true, normalizedReticleSize: 1, normalizedHitPosition: 1, spinModifier: 1) request.makeRequest(.CatchPokemon, delegate: self) } }
mit
a21dc1d2119816fb166b7f71955c087c
36.205882
213
0.505831
5.703495
false
false
false
false
keyOfVv/Cusp
Cusp/Sources/Subscription.swift
1
669
// // Subscription.swift // Pods // // Created by Ke Yang on 3/16/16. // // import Foundation class Subscription: NSObject { fileprivate(set) var characteristic: Characteristic! fileprivate(set) var update: ((Data?) -> Void)? fileprivate override init() { super.init() } convenience init(characteristic: Characteristic, update: ((Data?) -> Void)?) { self.init() self.characteristic = characteristic self.update = update } override var hash: Int { return characteristic.hashValue } override func isEqual(_ object: Any?) -> Bool { if let other = object as? Subscription { return self.hashValue == other.hashValue } return false } }
mit
9881a7fd738b67c95d55cba59f70230f
17.583333
79
0.684604
3.539683
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/ViewControllers/LoginViewReactor.swift
1
1479
// // LoginViewReactor.swift // Drrrible // // Created by Suyeol Jeon on 07/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import ReactorKit import RxCocoa import RxSwift final class LoginViewReactor: Reactor { enum Action { case login } enum Mutation { case setLoading(Bool) case setLoggedIn(Bool) } struct State { var isLoading: Bool = false var isLoggedIn: Bool = false } let initialState: State = State() fileprivate let authService: AuthServiceType fileprivate let userService: UserServiceType init(authService: AuthServiceType, userService: UserServiceType) { self.authService = authService self.userService = userService } func mutate(action: Action) -> Observable<Mutation> { switch action { case .login: let setLoading: Observable<Mutation> = .just(Mutation.setLoading(true)) let setLoggedIn: Observable<Mutation> = self.authService.authorize() .asObservable() .flatMap { self.userService.fetchMe() } .map { true } .catchErrorJustReturn(false) .map(Mutation.setLoggedIn) return setLoading.concat(setLoggedIn) } } func reduce(state: State, mutation: Mutation) -> State { var state = state switch mutation { case let .setLoading(isLoading): state.isLoading = isLoading return state case let .setLoggedIn(isLoggedIn): state.isLoggedIn = isLoggedIn return state } } }
mit
a4c3fd2dc364f97ac615a90eb868c8b3
22.09375
77
0.677943
4.334311
false
false
false
false