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
linbin00303/Dotadog
DotaDog/DotaDog/Classes/News/Renovate/DDogRenovateViewController.swift
1
3368
// // DDogRenovateViewController.swift // DotaDog // // Created by 林彬 on 16/5/31. // Copyright © 2016年 linbin. All rights reserved. // import UIKit import MJRefresh import SVProgressHUD class DDogRenovateViewController: UITableViewController { let ID = "Renovate" let header = MJRefreshNormalHeader() let footer = MJRefreshAutoNormalFooter() var page = 1 private lazy var newsModelArr : NSMutableArray = { let newsModelArr = NSMutableArray() return newsModelArr }() override func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = UITableViewCellSeparatorStyle.None DDogNewsHttp.getRenovateData(1) { [weak self](resultMs) in if resultMs == [] { SVProgressHUD.setMinimumDismissTimeInterval(2) SVProgressHUD.showErrorWithStatus("Json数据出错") return } self?.newsModelArr = resultMs self?.tableView.reloadData() } header.setRefreshingTarget(self, refreshingAction:#selector(DDogNewViewController.getNetData)) tableView.mj_header = header footer.setRefreshingTarget(self, refreshingAction: #selector(DDogNewViewController.getMoreData)) footer.automaticallyHidden = true tableView.mj_footer = footer tableView.registerNib(UINib(nibName: "DDogNewsCell", bundle: nil), forCellReuseIdentifier: ID) } func getNetData() { DDogNewsHttp.getRenovateData(1) { [weak self](resultMs) in self?.newsModelArr = resultMs self?.tableView.reloadData() self?.tableView.mj_header.endRefreshing() } } func getMoreData() { page = page + 1 DDogNewsHttp.getRenovateData(page) { [weak self](resultMs) in if resultMs == [] { self?.tableView.mj_footer.state = .NoMoreData self?.tableView.mj_footer.endRefreshing() return } for i in 0..<resultMs.count { self?.newsModelArr.addObject(resultMs[i]) } self?.tableView.reloadData() self?.tableView.mj_footer.endRefreshing() } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return newsModelArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! DDogNewsCell cell.newsModel = newsModelArr[indexPath.row] as? DDogNewsModel return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ let contentVC = DDogDetailsViewController() contentVC.model = newsModelArr[indexPath.row] as? DDogNewsModel self.navigationController?.pushViewController(contentVC, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } }
mit
d0099c9eba1f2a915196a5284e5b7233
30.632075
118
0.630182
5.460912
false
false
false
false
mamaz/gym-timer
GymTimer/GTTimerView.swift
1
1127
// // GTTimerView.swift // GymTimer // // Created by Hisma Mulya S on 11/14/16. // Copyright © 2016 mamaz. All rights reserved. // import UIKit import SnapKit class GTTimerView: UIView { public var text: String? { set { self.timerLabel.text = text } get { return self.text } } private lazy var padding: CGFloat = 15.0 private lazy var timerLabelHeight: CGFloat = 30 private lazy var timerLabel = UILabel() convenience init() { self.init() setTimerLabel() } private func setTimerLabel() -> Void{ self.addSubview(timerLabel) self.timerLabel.snp.makeConstraints { make in make.center.equalToSuperview() make.width.equalTo(self.currentSize().width - (2 * padding)) make.height.equalTo(timerLabelHeight) } } private func currentSize() -> CGSize { return self.frame.size == CGSize.zero ? CGSize(width: 70, height: 30) : self.frame.size } }
mit
92a42c3abb3bd5c6c49679052439645e
22.957447
72
0.546181
4.433071
false
false
false
false
psoamusic/PourOver
PourOver/POUserDocumentsTableViewController.swift
1
1415
// // PieceTableViewController.swift // PourOver // // Created by labuser on 11/5/14. // Copyright (c) 2014 labuser. All rights reserved. // import UIKit class POUserDocumentsTableViewController: POPieceTableViewController { //=================================================================================== //MARK: Private Properties //=================================================================================== override var reminderTextViewText: String { get { return "No user documents present\n\nCopy your files into iTunes > \(UIDevice.currentDevice().name) > Apps > PourOver > File Sharing\n\n Supported file types: .pd, .aif, .wav, .txt" } } //=================================================================================== //MARK: Refresh //=================================================================================== override func refreshPieces() { cellDictionaries.removeAll(keepCapacity: false) if let availablePatches = POPdFileLoader.sharedPdFileLoader.availablePatchesInDocuments() { cellDictionaries = availablePatches } //add spacer cells to the top and bottom for correct scrolling behavior cellDictionaries.insert(Dictionary(), atIndex: 0) cellDictionaries.append(Dictionary()) checkForNoDocuments() } }
gpl-3.0
5b263029856af69753410d975a06ae54
36.236842
193
0.49894
5.728745
false
false
false
false
stephentyrone/swift
test/Driver/PrivateDependencies/fail-chained-fine.swift
5
7632
/// a ==> bad ==> c ==> d | b --> bad --> e ==> f // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-chained-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled a.swift // CHECK-FIRST: Handled b.swift // CHECK-FIRST: Handled c.swift // CHECK-FIRST: Handled d.swift // CHECK-FIRST: Handled e.swift // CHECK-FIRST: Handled f.swift // CHECK-FIRST: Handled bad.swift // CHECK-RECORD-CLEAN-DAG: "./a.swift": [ // CHECK-RECORD-CLEAN-DAG: "./b.swift": [ // CHECK-RECORD-CLEAN-DAG: "./c.swift": [ // CHECK-RECORD-CLEAN-DAG: "./d.swift": [ // CHECK-RECORD-CLEAN-DAG: "./e.swift": [ // CHECK-RECORD-CLEAN-DAG: "./f.swift": [ // CHECK-RECORD-CLEAN-DAG: "./bad.swift": [ // RUN: touch -t 201401240006 %t/a.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./bad.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift -module-name main -j1 -v > %t/a.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=NEGATIVE-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-A %s < %t/main~buildrecord.swiftdeps // CHECK-A: Handled a.swift // CHECK-A: Handled bad.swift // NEGATIVE-A-NOT: Handled b.swift // NEGATIVE-A-NOT: Handled c.swift // NEGATIVE-A-NOT: Handled d.swift // NEGATIVE-A-NOT: Handled e.swift // NEGATIVE-A-NOT: Handled f.swift // CHECK-RECORD-A-DAG: "./a.swift": [ // CHECK-RECORD-A-DAG: "./b.swift": [ // CHECK-RECORD-A-DAG: "./c.swift": !private [ // CHECK-RECORD-A-DAG: "./d.swift": !private [ // CHECK-RECORD-A-DAG: "./e.swift": !private [ // CHECK-RECORD-A-DAG: "./f.swift": [ // CHECK-RECORD-A-DAG: "./bad.swift": !private [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v > %t/a2.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A2 %s < %t/a2.txt // RUN: %FileCheck -check-prefix=NEGATIVE-A2 %s < %t/a2.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps // CHECK-A2-DAG: Handled c.swift // CHECK-A2-DAG: Handled d.swift // CHECK-A2-DAG: Handled e.swift // CHECK-A2-DAG: Handled bad.swift // NEGATIVE-A2-NOT: Handled a.swift // NEGATIVE-A2-NOT: Handled b.swift // NEGATIVE-A2-NOT: Handled f.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-chained-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240006 %t/b.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v > %t/b.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-B %s < %t/b.txt // RUN: %FileCheck -check-prefix=NEGATIVE-B %s < %t/b.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-B %s < %t/main~buildrecord.swiftdeps // CHECK-B: Handled b.swift // CHECK-B: Handled bad.swift // NEGATIVE-B-NOT: Handled a.swift // NEGATIVE-B-NOT: Handled c.swift // NEGATIVE-B-NOT: Handled d.swift // NEGATIVE-B-NOT: Handled e.swift // NEGATIVE-B-NOT: Handled f.swift // CHECK-RECORD-B-DAG: "./a.swift": [ // CHECK-RECORD-B-DAG: "./b.swift": [ // CHECK-RECORD-B-DAG: "./c.swift": [ // CHECK-RECORD-B-DAG: "./d.swift": [ // CHECK-RECORD-B-DAG: "./e.swift": [ // CHECK-RECORD-B-DAG: "./f.swift": [ // CHECK-RECORD-B-DAG: "./bad.swift": !private [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v > %t/b2.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-B2 %s < %t/b2.txt // RUN: %FileCheck -check-prefix=NEGATIVE-B2 %s < %t/b2.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps // CHECK-B2-DAG: Handled bad.swift // NEGATIVE-B2-NOT: Handled a.swift // NEGATIVE-B2-NOT: Handled b.swift // NEGATIVE-B2-NOT: Handled c.swift // NEGATIVE-B2-NOT: Handled d.swift // NEGATIVE-B2-NOT: Handled e.swift // NEGATIVE-B2-NOT: Handled f.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-chained-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240006 %t/bad.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./bad.swift ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift -module-name main -j1 -v > %t/bad.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-BAD %s < %t/bad.txt // RUN: %FileCheck -check-prefix=NEGATIVE-BAD %s < %t/bad.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-A %s < %t/main~buildrecord.swiftdeps // CHECK-BAD: Handled bad.swift // NEGATIVE-BAD-NOT: Handled a.swift // NEGATIVE-BAD-NOT: Handled b.swift // NEGATIVE-BAD-NOT: Handled c.swift // NEGATIVE-BAD-NOT: Handled d.swift // NEGATIVE-BAD-NOT: Handled e.swift // NEGATIVE-BAD-NOT: Handled f.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./bad.swift -module-name main -j1 -v > %t/bad2.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A2 %s < %t/bad2.txt // RUN: %FileCheck -check-prefix=NEGATIVE-A2 %s < %t/bad2.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps
apache-2.0
691d9fc4a01ef3ebc003fc8c704492d5
58.162791
401
0.691431
2.876743
false
false
false
false
alblue/swift
test/SILGen/opaque_ownership.swift
1
11337
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s // RUN: %target-swift-emit-silgen -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s public typealias AnyObject = Builtin.AnyObject precedencegroup AssignmentPrecedence {} precedencegroup CastingPrecedence {} precedencegroup ComparisonPrecedence {} public protocol _ObjectiveCBridgeable {} public protocol UnkeyedDecodingContainer { var isAtEnd: Builtin.Int1 { get } } public protocol Decoder { func unkeyedContainer() throws -> UnkeyedDecodingContainer } // Test open_existential_value ownership // --- // CHECK-LABEL: sil @$ss11takeDecoder4fromBi1_s0B0_p_tKF : $@convention(thin) (@in_guaranteed Decoder) -> (Builtin.Int1, @error Error) { // CHECK: bb0(%0 : @guaranteed $Decoder): // CHECK: [[OPENED:%.*]] = open_existential_value %0 : $Decoder to $@opened("{{.*}}") Decoder // CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") Decoder, #Decoder.unkeyedContainer!1 : <Self where Self : Decoder> (Self) -> () throws -> UnkeyedDecodingContainer, %3 : $@opened("{{.*}}") Decoder : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error) // CHECK: try_apply [[WT]]<@opened("{{.*}}") Decoder>([[OPENED]]) : $@convention(witness_method: Decoder) <τ_0_0 where τ_0_0 : Decoder> (@in_guaranteed τ_0_0) -> (@out UnkeyedDecodingContainer, @error Error), normal bb2, error bb1 // // CHECK:bb{{.*}}([[RET1:%.*]] : @owned $UnkeyedDecodingContainer): // CHECK: [[BORROW2:%.*]] = begin_borrow [[RET1]] : $UnkeyedDecodingContainer // CHECK: [[OPENED2:%.*]] = open_existential_value [[BORROW2]] : $UnkeyedDecodingContainer to $@opened("{{.*}}") UnkeyedDecodingContainer // CHECK: [[WT2:%.*]] = witness_method $@opened("{{.*}}") UnkeyedDecodingContainer, #UnkeyedDecodingContainer.isAtEnd!getter.1 : <Self where Self : UnkeyedDecodingContainer> (Self) -> () -> Builtin.Int1, [[OPENED2]] : $@opened("{{.*}}") UnkeyedDecodingContainer : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: [[RET2:%.*]] = apply [[WT2]]<@opened("{{.*}}") UnkeyedDecodingContainer>([[OPENED2]]) : $@convention(witness_method: UnkeyedDecodingContainer) <τ_0_0 where τ_0_0 : UnkeyedDecodingContainer> (@in_guaranteed τ_0_0) -> Builtin.Int1 // CHECK: end_borrow [[BORROW2]] : $UnkeyedDecodingContainer // CHECK: destroy_value [[RET1]] : $UnkeyedDecodingContainer // CHECK-NOT: destroy_value %0 : $Decoder // CHECK: return [[RET2]] : $Builtin.Int1 // CHECK-LABEL: } // end sil function '$ss11takeDecoder4fromBi1_s0B0_p_tKF' public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 { let container = try decoder.unkeyedContainer() return container.isAtEnd } // Test unsafe_bitwise_cast nontrivial ownership. // --- // CHECK-LABEL: sil @$ss13unsafeBitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $T, [[ARG1:%.*]] : @trivial $@thick U.Type): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG0]] : $T // CHECK: [[RESULT:%.*]] = unchecked_bitwise_cast [[ARG_COPY]] : $T to $U // CHECK: [[RESULT_COPY:%.*]] = copy_value [[RESULT]] : $U // CHECK: destroy_value [[ARG_COPY]] : $T // CHECK: return [[RESULT_COPY]] : $U // CHECK-LABEL: } // end sil function '$ss13unsafeBitCast_2toq_x_q_mtr0_lF' public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // A lot of standard library support is necessary to support raw enums. // -------------------------------------------------------------------- infix operator == : ComparisonPrecedence infix operator ~= : ComparisonPrecedence public struct Bool { var _value: Builtin.Int1 public init() { let zero: Int64 = 0 self._value = Builtin.trunc_Int64_Int1(zero._value) } internal init(_ v: Builtin.Int1) { self._value = v } public init(_ value: Bool) { self = value } } extension Bool { public func _getBuiltinLogicValue() -> Builtin.Int1 { return _value } } public protocol Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func == (lhs: Self, rhs: Self) -> Bool } public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } public protocol RawRepresentable { associatedtype RawValue init?(rawValue: RawValue) var rawValue: RawValue { get } } public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue == rhs.rawValue } public typealias _MaxBuiltinIntegerType = Builtin.IntLiteral public protocol _ExpressibleByBuiltinIntegerLiteral { init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) } public protocol ExpressibleByIntegerLiteral { associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral init(integerLiteral value: IntegerLiteralType) } extension ExpressibleByIntegerLiteral where Self : _ExpressibleByBuiltinIntegerLiteral { @_transparent public init(integerLiteral value: Self) { self = value } } public protocol ExpressibleByStringLiteral {} public protocol ExpressibleByFloatLiteral {} public protocol ExpressibleByUnicodeScalarLiteral {} public protocol ExpressibleByExtendedGraphemeClusterLiteral {} public struct Int64 : ExpressibleByIntegerLiteral, _ExpressibleByBuiltinIntegerLiteral, Equatable { public var _value: Builtin.Int64 public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) { _value = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(x).0 } public typealias IntegerLiteralType = Int64 public init(integerLiteral value: Int64) { self = value } public static func ==(_ lhs: Int64, rhs: Int64) -> Bool { return Bool(Builtin.cmp_eq_Int64(lhs._value, rhs._value)) } } // Test ownership of multi-case Enum values in the context of @trivial to @in thunks. // --- // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW : $@convention(witness_method: Equatable) (@in_guaranteed FloatingPointSign, @in_guaranteed FloatingPointSign, @thick FloatingPointSign.Type) -> Bool { // CHECK: bb0(%0 : @trivial $FloatingPointSign, %1 : @trivial $FloatingPointSign, %2 : @trivial $@thick FloatingPointSign.Type): // CHECK: %3 = function_ref @$ss2eeoiySbx_xtSYRzSQ8RawValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: %4 = apply %3<FloatingPointSign>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK: return %4 : $Bool // CHECK-LABEL: } // end sil function '$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW' public enum FloatingPointSign: Int64 { /// The sign for a positive value. case plus /// The sign for a negative value. case minus } #if os(macOS) // Test open_existential_value used in a conversion context. // (the actual bridging call is dropped because we don't import Swift). // --- // CHECK-OSX-LABEL: sil @$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF : $@convention(thin) (@in_guaranteed Any) -> @owned AnyObject { // CHECK-OSX: bb0(%0 : @guaranteed $Any): // CHECK-OSX: [[COPY:%.*]] = copy_value %0 : $Any // CHECK-OSX: [[BORROW2:%.*]] = begin_borrow [[COPY]] : $Any // CHECK-OSX: [[VAL:%.*]] = open_existential_value [[BORROW2]] : $Any to $@opened // CHECK-OSX: [[COPY2:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: end_borrow [[BORROW2]] : $Any // CHECK-OSX: destroy_value [[COPY2]] : $@opened // CHECK-OSX: destroy_value [[COPY]] : $Any // CHECK-OSX-NOT: destroy_value %0 : $Any // CHECK-OSX: return undef : $AnyObject // CHECK-OSX-LABEL: } // end sil function '$ss26_unsafeDowncastToAnyObject04fromD0yXlyp_tF' public func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject { return any as AnyObject } #endif public protocol Error {} #if os(macOS) // Test open_existential_box_value in a conversion context. // --- // CHECK-OSX-LABEL: sil @$ss3foo1eys5Error_pSg_tF : $@convention(thin) (@guaranteed Optional<Error>) -> () { // CHECK-OSX: [[BORROW:%.*]] = begin_borrow %{{.*}} : $Error // CHECK-OSX: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened // CHECK-OSX: [[COPY:%.*]] = copy_value [[VAL]] : $@opened // CHECK-OSX: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened // CHECK-OSX: end_borrow [[BORROW]] : $Error // CHECK-OSX-LABEL: } // end sil function '$ss3foo1eys5Error_pSg_tF' public func foo(e: Error?) { if let u = e { let a: Any = u _ = a } } #endif public enum Optional<Wrapped> { case none case some(Wrapped) } public protocol IP {} public protocol Seq { associatedtype Iterator : IP func makeIterator() -> Iterator } extension Seq where Self.Iterator == Self { public func makeIterator() -> Self { return self } } public struct EnumIter<Base : IP> : IP, Seq { internal var _base: Base public typealias Iterator = EnumIter<Base> } // Test passing a +1 RValue to @in_guaranteed. // --- // CHECK-LABEL: sil @$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF : $@convention(method) <Base where Base : Seq> (@in_guaranteed EnumSeq<Base>) -> @out EnumIter<Base.Iterator> { // CHECK: bb0(%0 : @guaranteed $EnumSeq<Base>): // CHECK: [[MT:%.*]] = metatype $@thin EnumIter<Base.Iterator>.Type // CHECK: [[FIELD:%.*]] = struct_extract %0 : $EnumSeq<Base>, #EnumSeq._base // CHECK: [[COPY:%.*]] = copy_value [[FIELD]] : $Base // CHECK: [[WT:%.*]] = witness_method $Base, #Seq.makeIterator!1 : <Self where Self : Seq> (Self) -> () -> Self.Iterator : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: [[ITER:%.*]] = apply [[WT]]<Base>([[COPY]]) : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator // CHECK: destroy_value [[COPY]] : $Base // CHECK: [[FN:%.*]] = function_ref @$ss8EnumIterV5_baseAByxGx_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0> // CHECK: return [[RET]] : $EnumIter<Base.Iterator> // CHECK-LABEL: } // end sil function '$ss7EnumSeqV12makeIterators0A4IterVy0D0QzGyF' public struct EnumSeq<Base : Seq> : Seq { public typealias Iterator = EnumIter<Base.Iterator> internal var _base: Base public func makeIterator() -> Iterator { return EnumIter(_base: _base.makeIterator()) } }
apache-2.0
487e841e3ab5171092f5ff9a29402c8e
42.957198
405
0.674958
3.571609
false
false
false
false
scottrhoyt/Jolt
Jolt.playground/Contents.swift
1
2162
import Jolt import XCPlayground import JoltOperators //// MARK: - Arithmetic // //let n = [-1.0, 2.0, 3.0, 4.0, 5.0] //let sum = Jolt.sum(n) // //let a = [1.0, 3.0, 5.0, 7.0] //let b = [2.0, 4.0, 6.0, 8.0] //let product = Jolt.mul(a, b) // //// MARK: - Matrix // //// ⎛ 1 1 ⎞ ⎛ 3 ⎞ //// ⎢ ⎟ * B = ⎢ ⎟ C = ? //// ⎝ 1 -1 ⎠ ⎝ 1 ⎠ // //let A = Matrix([[1, 1], [1, -1]]) //let C = Matrix([[3], [1]]) //let B = inv(A) * C // //// MARK: - FFT // //func plot<T>(values: [T], title: String) { // for value in values { // XCPCaptureValue(title, value: value) // } //} // //let count = 64 //let frequency = 4.0 //let amplitude = 3.0 // //let x = (0..<count).map { 2.0 * M_PI / Double(count) * Double($0) * frequency } // //plot(sin(x), title: "Sine Wave") //plot(fft(sin(x)), title: "FFT") struct Temp : VectorOperationsConvertible { enum Unit { case Kelvin, Farenheight, Celsius } static var defaultUnit = Unit.Kelvin var kelvin: Double var celsius: Double { get { return kelvin - 273.15 } set { kelvin = newValue + 273.15 } } var farenheight: Double { get { return celsius * 9 / 5 + 32 } set { celsius = (newValue - 32) * 5 / 9 } } func defaultValue() -> Double { switch Temp.defaultUnit { case .Kelvin: return kelvin case .Celsius: return celsius case .Farenheight: return farenheight } } // MARK: DoubleConvertible Stuff var floatingPointValue: Double { return kelvin } init(floatingPointValue: Double) { kelvin = floatingPointValue } } var a = Temp(floatingPointValue: 3) var b = Temp(floatingPointValue: 2) let c = [a,b] Temp.sqrt(c) c / c b.farenheight = 32 a.celsius = 100 a.defaultValue() b.defaultValue() Temp.defaultUnit = .Celsius a.defaultValue() b.defaultValue() Temp.defaultUnit = .Farenheight a.defaultValue() let aa: [Double] = [1, 2, 3, 4] Double.clip(aa, 2.1, 2.9) Double.threshold(aa, 2.5)
mit
7a1275668ba8df22db00d6b8d6102edb
19.361905
81
0.525257
3.067432
false
false
false
false
skela/FileProvider
Sources/FTPFileProvider.swift
2
43920
// // FTPFileProvider.swift // FileProvider // // Created by Amir Abbas Mousavian. // Copyright © 2017 Mousavian. Distributed under MIT license. // import Foundation /** Allows accessing to FTP files and directories. This provider doesn't cache or save files internally. It's a complete reimplementation and doesn't use CFNetwork deprecated API. */ open class FTPFileProvider: NSObject, FileProviderBasicRemote, FileProviderOperations, FileProviderReadWrite, FileProviderReadWriteProgressive { /// FTP data connection mode. public enum Mode: String { /// Passive mode for FTP and Extended Passive mode for FTP over TLS. case `default` /// Data connection would establish by client to determined server host/port. case passive /// Data connection would establish by server to determined client's port. case active /// Data connection would establish by client to determined server host/port, with IPv6 support. (RFC 2428) case extendedPassive } open class var type: String { return "FTP" } public let baseURL: URL? open var dispatch_queue: DispatchQueue open var operation_queue: OperationQueue { willSet { assert(_session == nil, "It's not effective to change dispatch_queue property after session is initialized.") } } open weak var delegate: FileProviderDelegate? open var credential: URLCredential? { didSet { sessionDelegate?.credential = self.credential } } open private(set) var cache: URLCache? public var useCache: Bool public var validatingCache: Bool /// Determine either FTP session is in passive or active mode. public let mode: Mode fileprivate var _session: URLSession! internal var sessionDelegate: SessionDelegate? public var session: URLSession { get { if _session == nil { self.sessionDelegate = SessionDelegate(fileProvider: self) let config = URLSessionConfiguration.default _session = URLSession(configuration: config, delegate: sessionDelegate as URLSessionDelegate?, delegateQueue: self.operation_queue) _session.sessionDescription = UUID().uuidString initEmptySessionHandler(_session.sessionDescription!) } return _session } set { assert(newValue.delegate is SessionDelegate, "session instances should have a SessionDelegate instance as delegate.") _session = newValue if _session.sessionDescription?.isEmpty ?? true { _session.sessionDescription = UUID().uuidString } self.sessionDelegate = newValue.delegate as? SessionDelegate initEmptySessionHandler(_session.sessionDescription!) } } #if os(macOS) || os(iOS) || os(tvOS) open var undoManager: UndoManager? = nil #endif /** Initializer for FTP provider with given username and password. - Note: `passive` value should be set according to server settings and firewall presence. - Parameter baseURL: a url with `ftp://hostaddress/` format. - Parameter mode: FTP server data connection type. - Parameter credential: a `URLCredential` object contains user and password. - Parameter cache: A URLCache to cache downloaded files and contents. (unimplemented for FTP and should be nil) - Important: Extended Passive or Active modes will fallback to normal Passive or Active modes if your server does not support extended modes. */ public init? (baseURL: URL, mode: Mode = .default, credential: URLCredential? = nil, cache: URLCache? = nil) { guard ["ftp", "ftps", "ftpes"].contains(baseURL.uw_scheme.lowercased()) else { return nil } guard baseURL.host != nil else { return nil } var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)! let defaultPort: Int = baseURL.scheme?.lowercased() == "ftps" ? 990 : 21 urlComponents.port = urlComponents.port ?? defaultPort urlComponents.scheme = urlComponents.scheme ?? "ftp" urlComponents.path = urlComponents.path.hasSuffix("/") ? urlComponents.path : urlComponents.path + "/" self.baseURL = urlComponents.url!.absoluteURL self.mode = mode self.useCache = false self.validatingCache = true self.cache = cache self.credential = credential self.supportsRFC3659 = true let queueLabel = "FileProvider.\(Swift.type(of: self).type)" dispatch_queue = DispatchQueue(label: queueLabel, attributes: .concurrent) operation_queue = OperationQueue() operation_queue.name = "\(queueLabel).Operation" super.init() } /** **DEPRECATED** Initializer for FTP provider with given username and password. - Note: `passive` value should be set according to server settings and firewall presence. - Parameter baseURL: a url with `ftp://hostaddress/` format. - Parameter passive: FTP server data connection, `true` means passive connection (data connection created by client) and `false` means active connection (data connection created by server). Default is `true` (passive mode). - Parameter credential: a `URLCredential` object contains user and password. - Parameter cache: A URLCache to cache downloaded files and contents. (unimplemented for FTP and should be nil) */ @available(*, deprecated, renamed: "init(baseURL:mode:credential:cache:)") public convenience init? (baseURL: URL, passive: Bool, credential: URLCredential? = nil, cache: URLCache? = nil) { self.init(baseURL: baseURL, mode: passive ? .passive : .active, credential: credential, cache: cache) } public required convenience init?(coder aDecoder: NSCoder) { guard let baseURL = aDecoder.decodeObject(of: NSURL.self, forKey: "baseURL") as URL? else { if #available(macOS 10.11, iOS 9.0, tvOS 9.0, *) { aDecoder.failWithError(CocoaError(.coderValueNotFound, userInfo: [NSLocalizedDescriptionKey: "Base URL is not set."])) } return nil } let mode: Mode if let modeStr = aDecoder.decodeObject(of: NSString.self, forKey: "mode") as String?, let mode_v = Mode(rawValue: modeStr) { mode = mode_v } else { let passiveMode = aDecoder.decodeBool(forKey: "passiveMode") mode = passiveMode ? .passive : .active } self.init(baseURL: baseURL, mode: mode, credential: aDecoder.decodeObject(of: URLCredential.self, forKey: "credential")) self.useCache = aDecoder.decodeBool(forKey: "useCache") self.validatingCache = aDecoder.decodeBool(forKey: "validatingCache") self.supportsRFC3659 = aDecoder.decodeBool(forKey: "supportsRFC3659") self.securedDataConnection = aDecoder.decodeBool(forKey: "securedDataConnection") } public func encode(with aCoder: NSCoder) { aCoder.encode(self.baseURL, forKey: "baseURL") aCoder.encode(self.credential, forKey: "credential") aCoder.encode(self.useCache, forKey: "useCache") aCoder.encode(self.validatingCache, forKey: "validatingCache") aCoder.encode(self.mode.rawValue, forKey: "mode") aCoder.encode(self.supportsRFC3659, forKey: "supportsRFC3659") aCoder.encode(self.securedDataConnection, forKey: "securedDataConnection") } public static var supportsSecureCoding: Bool { return true } open func copy(with zone: NSZone? = nil) -> Any { let copy = FTPFileProvider(baseURL: self.baseURL!, mode: self.mode, credential: self.credential, cache: self.cache)! copy.delegate = self.delegate copy.fileOperationDelegate = self.fileOperationDelegate copy.useCache = self.useCache copy.validatingCache = self.validatingCache copy.securedDataConnection = self.securedDataConnection copy.supportsRFC3659 = self.supportsRFC3659 return copy } deinit { if let sessionuuid = _session?.sessionDescription { removeSessionHandler(for: sessionuuid) } if fileProviderCancelTasksOnInvalidating { _session?.invalidateAndCancel() } else { _session?.finishTasksAndInvalidate() } } internal var supportsRFC3659: Bool /** Uploads files in chunk if `true`, Otherwise It will uploads entire file/data as single stream. - Note: Due to an internal bug in `NSURLSessionStreamTask`, it must be `true` when using Apple's stream task, otherwise it will occasionally throw `Assertion failed: (_writeBufferAlreadyWrittenForNextWrite == 0)` fatal error. My implementation of `FileProviderStreamTask` doesn't have this bug. - Note: Disabling this option will increase upload speed. */ public var uploadByREST: Bool = false /** Determines data connection must TLS or not. `false` value indicates to use `PROT C` and `true` value indicates to use `PROT P`. Default is `true`. */ public var securedDataConnection: Bool = true /** Trust all certificates if `disableEvaluation`, Otherwise validate certificate chain. Default is `performDefaultEvaluation`. */ public var serverTrustPolicy: ServerTrustPolicy = .performDefaultEvaluation(validateHost: true) open func contentsOfDirectory(path: String, completionHandler: @escaping ([FileObject], Error?) -> Void) { self.contentsOfDirectory(path: path, rfc3659enabled: supportsRFC3659, completionHandler: completionHandler) } /** Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty array. - Parameter path: path to target directory. If empty, root will be iterated. - Parameter rfc3659enabled: uses MLST command instead of old LIST to get files attributes, default is `true`. - Parameter completionHandler: a closure with result of directory entries or error. - Parameter contents: An array of `FileObject` identifying the the directory entries. - Parameter error: Error returned by system. */ open func contentsOfDirectory(path apath: String, rfc3659enabled: Bool , completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) { let path = ftpPath(apath) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = FileOperationType.fetch(path: path).json self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler([], error) } return } self.ftpList(task, of: self.ftpPath(path), useMLST: rfc3659enabled, completionHandler: { (contents, error) in defer { self.ftpQuit(task) } if let error = error { if let uerror = error as? URLError, uerror.code == .unsupportedURL { self.contentsOfDirectory(path: path, rfc3659enabled: false, completionHandler: completionHandler) return } self.dispatch_queue.async { completionHandler([], error) } return } let files: [FileObject] = contents.compactMap { rfc3659enabled ? self.parseMLST($0, in: path) : (self.parseUnixList($0, in: path) ?? self.parseDOSList($0, in: path)) } self.dispatch_queue.async { completionHandler(files, nil) } }) } } open func attributesOfItem(path: String, completionHandler: @escaping (FileObject?, Error?) -> Void) { self.attributesOfItem(path: path, rfc3659enabled: supportsRFC3659, completionHandler: completionHandler) } /** Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty `FileObject`. - Parameter path: path to target directory. If empty, attributes of root will be returned. - Parameter rfc3659enabled: uses MLST command instead of old LIST to get files attributes, default is true. - Parameter completionHandler: a closure with result of directory entries or error. `attributes`: A `FileObject` containing the attributes of the item. `error`: Error returned by system. */ open func attributesOfItem(path apath: String, rfc3659enabled: Bool, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) { let path = ftpPath(apath) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = FileOperationType.fetch(path: path).json self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler(nil, error) } return } let command = rfc3659enabled ? "MLST \(path)" : "LIST \(path)" self.execute(command: command, on: task, completionHandler: { (response, error) in defer { self.ftpQuit(task) } do { if let error = error { throw error } guard let response = response, response.hasPrefix("250") || (response.hasPrefix("50") && rfc3659enabled) else { throw URLError(.badServerResponse, url: self.url(of: path)) } if response.hasPrefix("500") { self.supportsRFC3659 = false self.attributesOfItem(path: path, rfc3659enabled: false, completionHandler: completionHandler) } let lines = response.components(separatedBy: "\n").compactMap { $0.isEmpty ? nil : $0.trimmingCharacters(in: .whitespacesAndNewlines) } guard lines.count > 2 else { throw URLError(.badServerResponse, url: self.url(of: path)) } let dirPath = path.deletingLastPathComponent let file: FileObject? = rfc3659enabled ? self.parseMLST(lines[1], in: dirPath) : (self.parseUnixList(lines[1], in: dirPath) ?? self.parseDOSList(lines[1], in: dirPath)) self.dispatch_queue.async { completionHandler(file, nil) } } catch { self.dispatch_queue.async { completionHandler(nil, error) } } }) } } open func storageProperties(completionHandler: @escaping (_ volume: VolumeObject?) -> Void) { dispatch_queue.async { completionHandler(nil) } } @discardableResult open func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { let progress = Progress(totalUnitCount: -1) if recursive { return self.recursiveList(path: path, useMLST: true, foundItemsHandler: { items in if let foundItemHandler = foundItemHandler { for item in items where query.evaluate(with: item.mapPredicate()) { foundItemHandler(item) } progress.totalUnitCount = Int64(items.count) } }, completionHandler: {files, error in if let error = error { completionHandler([], error) return } let foundFiles = files.filter { query.evaluate(with: $0.mapPredicate()) } completionHandler(foundFiles, nil) }) } else { self.contentsOfDirectory(path: path, completionHandler: { (items, error) in if let error = error { completionHandler([], error) return } var result = [FileObject]() for item in items where query.evaluate(with: item.mapPredicate()) { foundItemHandler?(item) result.append(item) } completionHandler(result, nil) }) } return progress } open func url(of path: String?) -> URL { let path = path?.trimmingCharacters(in: CharacterSet(charactersIn: "/ ")).addingPercentEncoding(withAllowedCharacters: .filePathAllowed) ?? (path ?? "") var baseUrlComponent = URLComponents(url: self.baseURL!, resolvingAgainstBaseURL: true) baseUrlComponent?.user = credential?.user baseUrlComponent?.password = credential?.password return URL(string: path, relativeTo: baseUrlComponent?.url ?? baseURL) ?? baseUrlComponent?.url ?? baseURL! } open func relativePathOf(url: URL) -> String { // check if url derieved from current base url let relativePath = url.relativePath if !relativePath.isEmpty, url.baseURL == self.baseURL { return (relativePath.removingPercentEncoding ?? relativePath).replacingOccurrences(of: "/", with: "", options: .anchored) } if !relativePath.isEmpty, self.baseURL == self.url(of: "/") { return (relativePath.removingPercentEncoding ?? relativePath).replacingOccurrences(of: "/", with: "", options: .anchored) } return relativePath.replacingOccurrences(of: "/", with: "", options: .anchored) } open func isReachable(completionHandler: @escaping (_ success: Bool, _ error: Error?) -> Void) { self.attributesOfItem(path: "/") { (file, error) in completionHandler(file != nil, error) } } open weak var fileOperationDelegate: FileOperationDelegate? @discardableResult open func create(folder folderName: String, at atPath: String, completionHandler: SimpleCompletionHandler) -> Progress? { let path = atPath.appendingPathComponent(folderName) + "/" return doOperation(.create(path: path), completionHandler: completionHandler) } @discardableResult open func moveItem(path: String, to toPath: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return doOperation(.move(source: path, destination: toPath), completionHandler: completionHandler) } @discardableResult open func copyItem(path: String, to toPath: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return doOperation(.copy(source: path, destination: toPath), completionHandler: completionHandler) } @discardableResult open func removeItem(path: String, completionHandler: SimpleCompletionHandler) -> Progress? { return doOperation(.remove(path: path), completionHandler: completionHandler) } @discardableResult open func copyItem(localFile: URL, to toPath: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { guard (try? localFile.checkResourceIsReachable()) ?? false else { dispatch_queue.async { completionHandler?(URLError(.fileDoesNotExist, url: localFile)) } return nil } // check file is not a folder guard (try? localFile.resourceValues(forKeys: [.fileResourceTypeKey]))?.fileResourceType ?? .unknown == .regular else { dispatch_queue.async { completionHandler?(URLError(.fileIsDirectory, url: localFile)) } return nil } let operation = FileOperationType.copy(source: localFile.absoluteString, destination: toPath) guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } let progress = Progress(totalUnitCount: -1) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } return } guard let stream = InputStream(url: localFile) else { return } let size = localFile.fileSize self.ftpStore(task, filePath: self.ftpPath(toPath), from: stream, size: size, onTask: { task in weak var weakTask = task progress.cancellationHandler = { weakTask?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) }, onProgress: { bytesSent, totalSent, expectedBytes in progress.totalUnitCount = expectedBytes progress.completedUnitCount = totalSent self.delegateNotify(operation, progress: progress.fractionCompleted) }, completionHandler: { (error) in if error != nil { progress.cancel() } self.ftpQuit(task) self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } }) } return progress } @discardableResult open func copyItem(path: String, toLocalURL destURL: URL, completionHandler: SimpleCompletionHandler) -> Progress? { let operation = FileOperationType.copy(source: path, destination: destURL.absoluteString) guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } let progress = Progress(totalUnitCount: -1) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) } return } let tempURL = URL(fileURLWithPath: NSTemporaryDirectory().appendingPathComponent(UUID().uuidString)) guard let stream = OutputStream(url: tempURL, append: false) else { completionHandler?(CocoaError(.fileWriteUnknown, path: destURL.path)) return } self.ftpDownload(task, filePath: self.ftpPath(path), to: stream, onTask: { task in weak var weakTask = task progress.cancellationHandler = { weakTask?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) }, onProgress: { recevied, totalReceived, totalSize in progress.totalUnitCount = totalSize progress.completedUnitCount = totalReceived self.delegateNotify(operation, progress: progress.fractionCompleted) }) { (error) in if error != nil { progress.cancel() } do { try FileManager.default.moveItem(at: tempURL, to: destURL) } catch { self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } try? FileManager.default.removeItem(at: tempURL) return } self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } } } return progress } @discardableResult open func contents(path: String, offset: Int64, length: Int, completionHandler: @escaping ((_ contents: Data?, _ error: Error?) -> Void)) -> Progress? { let operation = FileOperationType.fetch(path: path) if length == 0 || offset < 0 { dispatch_queue.async { completionHandler(Data(), nil) self.delegateNotify(operation) } return nil } let progress = Progress(totalUnitCount: -1) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler(nil, error) } return } let stream = OutputStream.toMemory() self.ftpDownload(task, filePath: self.ftpPath(path), from: offset, length: length, to: stream, onTask: { task in weak var weakTask = task progress.cancellationHandler = { weakTask?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) }, onProgress: { recevied, totalReceived, totalSize in progress.totalUnitCount = totalSize progress.completedUnitCount = totalReceived self.delegateNotify(operation, progress: progress.fractionCompleted) }) { (error) in if let error = error { progress.cancel() self.dispatch_queue.async { completionHandler(nil, error) self.delegateNotify(operation, error: error) } return } if let data = stream.property(forKey: .dataWrittenToMemoryStreamKey) as? Data { self.dispatch_queue.async { completionHandler(data, nil) self.delegateNotify(operation) } } } } return progress } @discardableResult open func writeContents(path: String, contents data: Data?, atomically: Bool, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { let operation = FileOperationType.modify(path: path) guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } let progress = Progress(totalUnitCount: Int64(data?.count ?? -1)) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } return } let storeHandler = { let data = data ?? Data() let stream = InputStream(data: data) self.ftpStore(task, filePath: self.ftpPath(path), from: stream, size: Int64(data.count), onTask: { task in weak var weakTask = task progress.cancellationHandler = { weakTask?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) }, onProgress: { bytesSent, totalSent, expectedBytes in progress.completedUnitCount = totalSent self.delegateNotify(operation, progress: progress.fractionCompleted) }, completionHandler: { (error) in if error != nil { progress.cancel() } self.ftpQuit(task) self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } }) } if overwrite { storeHandler() } else { self.attributesOfItem(path: path, completionHandler: { (file, erroe) in if file == nil { storeHandler() } }) } } return progress } public func contents(path: String, offset: Int64, length: Int, responseHandler: ((URLResponse) -> Void)?, progressHandler: @escaping (Int64, Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? { let operation = FileOperationType.fetch(path: path) if length == 0 || offset < 0 { dispatch_queue.async { completionHandler?(nil) self.delegateNotify(operation) } return nil } let progress = Progress(totalUnitCount: -1) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) } return } self.ftpDownloadData(task, filePath: self.ftpPath(path), from: offset, length: length, onTask: { task in weak var weakTask = task progress.cancellationHandler = { weakTask?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) }, onProgress: { data, recevied, totalReceived, totalSize in progressHandler(totalReceived - recevied, data) progress.totalUnitCount = totalSize progress.completedUnitCount = totalReceived self.delegateNotify(operation, progress: progress.fractionCompleted) }) { (data, error) in if let error = error { progress.cancel() self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } return } self.dispatch_queue.async { completionHandler?(nil) self.delegateNotify(operation) } } } return progress } /** Creates a symbolic link at the specified path that points to an item at the given path. This method does not traverse symbolic links contained in destination path, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component is a symbolic link, that link is not followed. - Note: Many servers does't support this functionality. - Parameters: - symbolicLink: The file path at which to create the new symbolic link. The last component of the path issued as the name of the link. - withDestinationPath: The path that contains the item to be pointed to by the link. In other words, this is the destination of the link. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. */ open func create(symbolicLink path: String, withDestinationPath destPath: String, completionHandler: SimpleCompletionHandler) { let operation = FileOperationType.link(link: path, target: destPath) _=self.doOperation(operation, completionHandler: completionHandler) } } extension FTPFileProvider { fileprivate func doOperation(_ operation: FileOperationType, completionHandler: SimpleCompletionHandler) -> Progress? { guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } let sourcePath = operation.source let destPath = operation.destination let command: String switch operation { case .create: command = "MKD \(ftpPath(sourcePath))" case .copy: command = "SITE CPFR \(ftpPath(sourcePath))\r\nSITE CPTO \(ftpPath(destPath!))" case .move: command = "RNFR \(ftpPath(sourcePath))\r\nRNTO \(ftpPath(destPath!))" case .remove: command = "DELE \(ftpPath(sourcePath))" case .link: command = "SITE SYMLINK \(ftpPath(sourcePath)) \(ftpPath(destPath!))" default: return nil // modify, fetch } let progress = Progress(totalUnitCount: 1) progress.setUserInfoObject(operation, forKey: .fileProvderOperationTypeKey) progress.kind = .file progress.setUserInfoObject(Progress.FileOperationKind.downloading, forKey: .fileOperationKindKey) let task = session.fpstreamTask(withHostName: baseURL!.host!, port: baseURL!.port!) task.serverTrustPolicy = serverTrustPolicy task.taskDescription = operation.json progress.cancellationHandler = { [weak task] in task?.cancel() } self.ftpLogin(task) { (error) in if let error = error { completionHandler?(error) self.delegateNotify(operation, error: error) return } self.execute(command: command, on: task, completionHandler: { (response, error) in if let error = error { completionHandler?(error) self.delegateNotify(operation, error: error) return } guard let response = response else { completionHandler?(error) self.delegateNotify(operation, error: URLError(.badServerResponse, url: self.url(of: sourcePath))) return } let codes: [Int] = response.components(separatedBy: .newlines).compactMap({ $0.isEmpty ? nil : $0}) .compactMap { let code = $0.components(separatedBy: .whitespaces).compactMap({ $0.isEmpty ? nil : $0}).first return code != nil ? Int(code!) : nil } if codes.filter({ (450..<560).contains($0) }).count > 0 { let errorCode: URLError.Code switch operation { case .create: errorCode = .cannotCreateFile case .modify: errorCode = .cannotWriteToFile case .copy: self.fallbackCopy(operation, progress: progress, completionHandler: completionHandler) return case .move: errorCode = .cannotMoveFile case .remove: self.fallbackRemove(operation, progress: progress, on: task, completionHandler: completionHandler) return case .link: errorCode = .cannotWriteToFile default: errorCode = .cannotOpenFile } let error = URLError(errorCode, url: self.url(of: sourcePath)) progress.cancel() completionHandler?(error) self.delegateNotify(operation, error: error) return } #if os(macOS) || os(iOS) || os(tvOS) self._registerUndo(operation) #endif progress.completedUnitCount = progress.totalUnitCount completionHandler?(nil) self.delegateNotify(operation) }) } progress.cancellationHandler = { [weak task] in task?.cancel() } progress.setUserInfoObject(Date(), forKey: .startingTimeKey) return progress } private func fallbackCopy(_ operation: FileOperationType, progress: Progress, completionHandler: SimpleCompletionHandler) { let sourcePath = operation.source guard let destPath = operation.destination else { return } let localURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("tmp") progress.becomeCurrent(withPendingUnitCount: 1) _ = self.copyItem(path: sourcePath, toLocalURL: localURL) { (error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } return } progress.becomeCurrent(withPendingUnitCount: 1) _ = self.copyItem(localFile: localURL, to: destPath) { error in completionHandler?(nil) self.delegateNotify(operation) } progress.resignCurrent() } progress.resignCurrent() return } private func fallbackRemove(_ operation: FileOperationType, progress: Progress, on task: FileProviderStreamTask, completionHandler: SimpleCompletionHandler) { let sourcePath = operation.source self.execute(command: "SITE RMDIR \(ftpPath(sourcePath))", on: task) { (response, error) in do { if let error = error { throw error } guard let response = response else { throw URLError(.badServerResponse, url: self.url(of: sourcePath)) } if response.hasPrefix("50") { self.fallbackRecursiveRemove(operation, progress: progress, on: task, completionHandler: completionHandler) return } if !response.hasPrefix("2") { throw URLError(.cannotRemoveFile, url: self.url(of: sourcePath)) } self.dispatch_queue.async { completionHandler?(nil) } self.delegateNotify(operation) } catch { progress.cancel() self.dispatch_queue.async { completionHandler?(error) } self.delegateNotify(operation, error: error) } } } private func fallbackRecursiveRemove(_ operation: FileOperationType, progress: Progress, on task: FileProviderStreamTask, completionHandler: SimpleCompletionHandler) { let sourcePath = operation.source _ = self.recursiveList(path: sourcePath, useMLST: true, completionHandler: { (contents, error) in if let error = error { self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } return } progress.becomeCurrent(withPendingUnitCount: 1) let recursiveProgress = Progress(totalUnitCount: Int64(contents.count)) let sortedContents = contents.sorted(by: { $0.path.localizedStandardCompare($1.path) == .orderedDescending }) progress.resignCurrent() var command = "" for file in sortedContents { command += (file.isDirectory ? "RMD \(self.ftpPath(file.path))" : "DELE \(self.ftpPath(file.path))") + "\r\n" } command += "RMD \(self.ftpPath(sourcePath))" self.execute(command: command, on: task, completionHandler: { (response, error) in recursiveProgress.completedUnitCount += 1 self.dispatch_queue.async { completionHandler?(error) self.delegateNotify(operation, error: error) } // TODO: Digest response }) }) } } extension FTPFileProvider: FileProvider { } #if os(macOS) || os(iOS) || os(tvOS) extension FTPFileProvider: FileProvideUndoable { } #endif
mit
53cecce146555c62afbed9c4ac1c8e46
43.952917
218
0.582664
5.5756
false
false
false
false
pmlbrito/cookiecutter-ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Presentation/Splash/Injection/SplashModuleInjector.swift
1
1537
// // SplashModuleInjector.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on 01/06/2017. // Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved. // import Foundation import Swinject class SplashModuleInjector: ModuleInjectionProtocol { static let container = Container() func setup() { resolver.register(SplashViewController.self) { r in let controller = SplashViewController() let defaultsManager = UserDefaultsManagerInjector().resolver.resolve(UserDefaultsManager.self) let process = r.resolve(SplashProcessProtocol.self, argument: defaultsManager) let interactor = r.resolve(SplashInteractorProtocol.self, argument: process) controller.presenter = r.resolve(SplashPresenterProtocol.self, argument: interactor) as? BasePresenter return controller } resolver.register(SplashPresenterProtocol.self) { (_, interactor: SplashInteractorProtocol?) in SplashPresenter(interactor: interactor) } resolver.register(SplashInteractorProtocol.self) { (_, process: SplashProcessProtocol?) in SplashInteractor(process: process) } resolver.register(SplashProcessProtocol.self) { (_, userDefaults: UserDefaultsManager?) in SplashProcess(userDefaults: userDefaults) } } } extension SplashModuleInjector { var resolver: Container { return SplashModuleInjector.container } }
mit
ae5a5b59f55b30b4ffc4a2bec0455144
33.909091
114
0.693359
5.10299
false
false
false
false
Ramotion/animated-tab-bar
RAMAnimatedTabBarController/Animations/TransitionAniamtions/RAMTransitionItemAnimations.swift
1
4415
// RAMTransitionItemAnimations.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /// Transition animtion open class RAMTransitionItemAnimations: RAMItemAnimation { /// Options for animating. Default TransitionNone open var transitionOptions: UIView.AnimationOptions! override init() { super.init() transitionOptions = UIView.AnimationOptions() } /** Start animation, method call when UITabBarItem is selected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open override func playAnimation(_ icon: UIImageView, textLabel: UILabel) { selectedColor(icon, textLabel: textLabel) UIView.transition(with: icon, duration: TimeInterval(duration), options: transitionOptions, animations: { }, completion: { _ in }) } /** Start animation, method call when UITabBarItem is unselected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel - parameter defaultTextColor: default UITabBarItem text color - parameter defaultIconColor: default UITabBarItem icon color */ open override func deselectAnimation(_ icon: UIImageView, textLabel: UILabel, defaultTextColor: UIColor, defaultIconColor: UIColor) { if let iconImage = icon.image { let renderMode = defaultIconColor.cgColor.alpha == 0 ? UIImage.RenderingMode.alwaysOriginal : UIImage.RenderingMode.alwaysTemplate let renderImage = iconImage.withRenderingMode(renderMode) icon.image = renderImage icon.tintColor = defaultIconColor } textLabel.textColor = defaultTextColor } /** Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open override func selectedState(_ icon: UIImageView, textLabel: UILabel) { selectedColor(icon, textLabel: textLabel) } func selectedColor(_ icon: UIImageView, textLabel: UILabel) { if let iconImage = icon.image, iconSelectedColor != nil { let renderImage = iconImage.withRenderingMode(.alwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } textLabel.textColor = textSelectedColor } } open class RAMFlipLeftTransitionItemAnimations: RAMTransitionItemAnimations { public override init() { super.init() transitionOptions = UIView.AnimationOptions.transitionFlipFromLeft } } open class RAMFlipRightTransitionItemAnimations: RAMTransitionItemAnimations { public override init() { super.init() transitionOptions = UIView.AnimationOptions.transitionFlipFromRight } } open class RAMFlipTopTransitionItemAnimations: RAMTransitionItemAnimations { public override init() { super.init() transitionOptions = UIView.AnimationOptions.transitionFlipFromTop } } open class RAMFlipBottomTransitionItemAnimations: RAMTransitionItemAnimations { public override init() { super.init() transitionOptions = UIView.AnimationOptions.transitionFlipFromBottom } }
mit
fe9414db7bffd6dea2f9a2dbb2fc31cb
33.224806
137
0.716648
5.588608
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/CS193p/iOS11/EmojiArtForDocument/EmojiArt.swift
1
891
// // EmojiArt.swift // EmojiArt // // Created by 朱双泉 on 2018/5/16. // Copyright © 2018 Castie!. All rights reserved. // import Foundation struct EmojiArt: Codable { var url: URL? var imageData: Data? var emojis = [EmojiInfo]() struct EmojiInfo: Codable { let x: Int let y: Int let text: String let size: Int } init?(json: Data) { if let newValue = try? JSONDecoder().decode(EmojiArt.self, from: json) { self = newValue } else { return nil } } var json: Data? { return try? JSONEncoder().encode(self) } init(url: URL, emojis: [EmojiInfo]) { self.url = url self.emojis = emojis } init(imageData: Data, emojis: [EmojiInfo]) { self.imageData = imageData self.emojis = emojis } }
mit
da44b88b5986b7bac84cbb1bb2978360
18.644444
80
0.530543
4.03653
false
false
false
false
khizkhiz/swift
benchmark/single-source/TypeFlood.swift
2
3834
//===--- TypeFlood.swift --------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // We use this test to benchmark the runtime memory that Swift programs use. // // The Swift compiler caches the metadata that it needs to generate to support // code that checks for protocol conformance and other operations that require // use of metadata. // This mechanism has the potential to allocate a lot of memory. This benchmark // program generates 2^15 calls to swift_conformsToProtocol and fills the // metadata/conformance caches with data that we never free. We use this // program to track the runtime memory usage of swift programs. The test is // optimized away in Release builds but kept in Debug mode. import TestsUtils protocol Pingable {} struct Some1<T> { init() {} func foo(x: T) {} } struct Some0<T> { init() {} func foo(x: T) {} } @inline(never) func flood<T>(x : T) { Some1<Some1<Some1<Some1<T>>>>() is Pingable Some1<Some1<Some1<Some0<T>>>>() is Pingable Some1<Some1<Some0<Some1<T>>>>() is Pingable Some1<Some1<Some0<Some0<T>>>>() is Pingable Some1<Some0<Some1<Some1<T>>>>() is Pingable Some1<Some0<Some1<Some0<T>>>>() is Pingable Some1<Some0<Some0<Some1<T>>>>() is Pingable Some1<Some0<Some0<Some0<T>>>>() is Pingable Some0<Some1<Some1<Some1<T>>>>() is Pingable Some0<Some1<Some1<Some0<T>>>>() is Pingable Some0<Some1<Some0<Some1<T>>>>() is Pingable Some0<Some1<Some0<Some0<T>>>>() is Pingable Some0<Some0<Some1<Some1<T>>>>() is Pingable Some0<Some0<Some1<Some0<T>>>>() is Pingable Some0<Some0<Some0<Some1<T>>>>() is Pingable Some0<Some0<Some0<Some0<T>>>>() is Pingable } @inline(never) func flood3<T>(x : T) { flood(Some1<Some1<Some1<Some1<T>>>>()) flood(Some1<Some1<Some1<Some0<T>>>>()) flood(Some1<Some1<Some0<Some1<T>>>>()) flood(Some1<Some1<Some0<Some0<T>>>>()) flood(Some1<Some0<Some1<Some1<T>>>>()) flood(Some1<Some0<Some1<Some0<T>>>>()) flood(Some1<Some0<Some0<Some1<T>>>>()) flood(Some1<Some0<Some0<Some0<T>>>>()) flood(Some0<Some1<Some1<Some1<T>>>>()) flood(Some0<Some1<Some1<Some0<T>>>>()) flood(Some0<Some1<Some0<Some1<T>>>>()) flood(Some0<Some1<Some0<Some0<T>>>>()) flood(Some0<Some0<Some1<Some1<T>>>>()) flood(Some0<Some0<Some1<Some0<T>>>>()) flood(Some0<Some0<Some0<Some1<T>>>>()) flood(Some0<Some0<Some0<Some0<T>>>>()) } @inline(never) func flood2<T>(x : T) { flood3(Some1<Some1<Some1<Some1<T>>>>()) flood3(Some1<Some1<Some1<Some0<T>>>>()) flood3(Some1<Some1<Some0<Some1<T>>>>()) flood3(Some1<Some1<Some0<Some0<T>>>>()) flood3(Some1<Some0<Some1<Some1<T>>>>()) flood3(Some1<Some0<Some1<Some0<T>>>>()) flood3(Some1<Some0<Some0<Some1<T>>>>()) flood3(Some1<Some0<Some0<Some0<T>>>>()) flood3(Some0<Some1<Some1<Some1<T>>>>()) flood3(Some0<Some1<Some1<Some0<T>>>>()) flood3(Some0<Some1<Some0<Some1<T>>>>()) flood3(Some0<Some1<Some0<Some0<T>>>>()) flood3(Some0<Some0<Some1<Some1<T>>>>()) flood3(Some0<Some0<Some1<Some0<T>>>>()) flood3(Some0<Some0<Some0<Some1<T>>>>()) flood3(Some0<Some0<Some0<Some0<T>>>>()) } @inline(never) public func run_TypeFlood(N: Int) { for _ in 1...N { flood3(Some1<Some1<Some1<Int>>>()) flood3(Some1<Some1<Some0<Int>>>()) flood3(Some1<Some0<Some1<Int>>>()) flood3(Some1<Some0<Some0<Int>>>()) flood3(Some0<Some1<Some1<Int>>>()) flood3(Some0<Some1<Some0<Int>>>()) flood3(Some0<Some0<Some1<Int>>>()) flood3(Some0<Some0<Some0<Int>>>()) } }
apache-2.0
07b234db790a50a2895e8a188078eb8f
33.854545
80
0.651278
2.889224
false
false
false
false
hayleyqinn/windWeather
风生/Pods/Alamofire/Source/ResponseSerialization.swift
170
29450
// // ResponseSerialization.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The type in which all data response serializers must conform to in order to serialize a response. public protocol DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, data and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, data and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - /// The type in which all download response serializers must conform to in order to serialize a response. public protocol DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, url and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, url and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - Default extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var dataResponse = DefaultDataResponse( request: self.request, response: self.response, data: self.delegate.data, error: self.delegate.error ) dataResponse.add(self.delegate.metrics) completionHandler(dataResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DataResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime let timeline = Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) var dataResponse = DataResponse<T.SerializedObject>( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: timeline ) dataResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } } return self } } extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDownloadResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var downloadResponse = DefaultDownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, error: self.downloadDelegate.error ) downloadResponse.add(self.delegate.metrics) completionHandler(downloadResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data contained in the destination url. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DownloadResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.downloadDelegate.fileURL, self.downloadDelegate.error ) let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime let timeline = Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) var downloadResponse = DownloadResponse<T.SerializedObject>( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, result: result, timeline: timeline ) downloadResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self } } // MARK: - Data extension Request { /// Returns a result data type that contains the response data as-is. /// /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return .success(validData) } } extension DataRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DataResponseSerializer<Data> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseData(response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseData(response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } // MARK: - String extension Request { /// Returns a result string type initialized from the response data with the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<String> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } } extension DataRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DataResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DownloadResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(json) } catch { return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /// Returns a plist object contained in a result type constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponsePropertyList( options: PropertyListSerialization.ReadOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) return .success(plist) } catch { return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set<Int> = [204, 205]
mit
9c37f72bafb6ed85b2b9d2cf10e261dd
40.131285
126
0.650017
5.602054
false
false
false
false
softermii/ASSwiftContactBook
Pods/CustomViews/ContactHeader.swift
2
5989
// // ContactHeader.swift // ASContactBook // // Created by Anton Stremovskiy on 7/12/17. // Copyright © 2017 áSoft. All rights reserved. // import UIKit import MessageUI open class ContactHeader: UIView { @IBOutlet weak var profileLabel: UILabel! @IBOutlet weak var profileName: UILabel! @IBOutlet weak var profileDescription: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var contactImage: UIImageView! @IBOutlet weak var callButton: ActionButton! @IBOutlet weak var chatButton: ActionButton! @IBOutlet weak var mailButton: ActionButton! var contact: Contact! func setupHeader(_ contact: Contact) { profileLabel.layer.cornerRadius = profileLabel.frame.size.height / 2 profileLabel.layer.masksToBounds = true contactImage.layer.cornerRadius = contactImage.frame.size.height / 2 contactImage.layer.masksToBounds = true self.contact = contact self.profileName.text = contact.firstName + " " + contact.lastName self.profileDescription.text = contact.jobTitle + " " + contact.organization let firstName = contact.firstName.first ?? Character.init("N") let lastName = contact.lastName.first ?? Character.init("A") self.profileLabel.text = "\(firstName)\(lastName)".uppercased() self.profileLabel.backgroundColor = ASContactPicker.barColor self.updateUI(contact) self.setupButtons() } func updateUI(_ contact: Contact) { if contact.thumb != nil { stackView.insertArrangedSubview(contactImage, at: 0) contactImage.image = contact.thumb contactImage.isHidden = false profileLabel.isHidden = true } else { contactImage.isHidden = true profileLabel.isHidden = false } } func setupButtons() { callButton.subtitleType = .phone; callButton.isEnabled = contact.phones.count > 0 chatButton.subtitleType = .message; chatButton.isEnabled = contact.phones.count > 0 || contact.emails.count > 0 mailButton.subtitleType = .email; mailButton.isEnabled = contact.emails.count > 0 } @IBAction func actionTap(_ button: ActionButton) { switch button.subtitleType { case .phone: showAlertController(contact.phones, subtype: button.subtitleType) case .message: var allData = [String]() allData.append(contentsOf: contact.phones) allData.append(contentsOf: contact.emails) showAlertController(allData, subtype: button.subtitleType) case .email: showAlertController(contact.emails, subtype: button.subtitleType) default: break } } fileprivate func sendMessage(_ contact: String) { if MFMessageComposeViewController.canSendText() { let messageVC = MFMessageComposeViewController() messageVC.recipients = [contact] messageVC.messageComposeDelegate = self presentController(messageVC) } } fileprivate func sendEmail(_ contact: String) { if MFMailComposeViewController.canSendMail() { let mailVC = MFMailComposeViewController() mailVC.setToRecipients([contact]) mailVC.mailComposeDelegate = self presentController(mailVC) } } fileprivate func openCallUrl(_ contact: String) { let num = contact.digits.hasPrefix("+") ? contact.digits : "+" + contact.digits if let url = URL(string: "tel://\(num)"), UIApplication.shared.canOpenURL(url) { openURL(url) } } fileprivate func presentController(_ controller: UIViewController) { if let vc = UIApplication.shared.delegate?.window??.rootViewController?.presentedViewController { vc.present(controller, animated: true, completion: nil) } } private func openURL(_ url: URL) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } func showAlertController(_ data: [String], subtype: SubtitleType) { let actionSheet = UIAlertController(title: "Make your choose", message: nil, preferredStyle: .actionSheet) for contact in data { let action = UIAlertAction(title: contact, style: .default, handler: { _ in switch subtype { case .phone: self.openCallUrl(contact.digits) case .email: self.sendEmail(contact) case .message: self.sendMessage(contact) default: break } }) actionSheet.addAction(action) } let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) actionSheet.addAction(cancel) if let vc = UIApplication.shared.delegate?.window??.rootViewController?.presentedViewController { vc.present(actionSheet, animated: true, completion: nil) } } } extension ContactHeader: MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate { public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { controller.dismiss(animated: true, completion: nil) } }
mit
627466842062b04206f29fb445e3fb97
33.408046
119
0.610489
5.487626
false
false
false
false
devyu/DownloadFont
DownloadFont/ViewController.swift
1
6697
// // ViewController.swift // DownloadFont // // Created by mac on 11/21/15. // Copyright © 2015 JY. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var textView: UITextView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var progress: UIProgressView! @IBOutlet weak var activityIndeicator: UIActivityIndicatorView! var fontNames = [String]() var fontSamples = [String]() var errorMessage: String = "" override func viewDidLoad() { super.viewDidLoad() fontNames = [ "STXingkai-SC-Light", "DFWaWaSC-W5", "FZLTXHK--GBK1-0", "STLibian-SC-Regular", "LiHeiPro", "HiraginoSansGB-W3", ] fontSamples = [ "没错,我就是行楷字体", "我是娃娃字体,是不是很可爱?😄😄😄", "支援服务升级资讯专业制", "作创意空间快速无线上网", "兙兛兞兝兡兣嗧瓩糎", "㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩", ] textView.editable = false tableView.dataSource = self tableView.delegate = self } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fontNames.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID = "cellID" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellID) } cell!.textLabel?.text = fontNames[indexPath.row] return cell! } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { asynchronousSetFontsName(fontNames[indexPath.row]) } private func asynchronousSetFontsName(fontName: String) { let aFont = UIFont(name: fontName, size: 12.0) // If the font is already download if let font = aFont { if (font.fontName.compare(fontName) == .OrderedSame || font.familyName.compare(fontName) == .OrderedSame) { if let sampleIndex = fontNames.indexOf(fontName) { textView.text = fontSamples[sampleIndex] textView.font = UIFont(name: fontName, size: 24.0) } return } } // Creat a dictionary with the font's PostScript name. let attrs = NSDictionary(object: fontName, forKey: kCTFontNameAttribute as String) // Creat a new font descriptor reference from the attributtes dictionary let desc = CTFontDescriptorCreateWithAttributes(attrs as CFDictionaryRef) var descs = NSMutableArray() descs = NSMutableArray(capacity: 0) descs.addObject(desc) CTFontDescriptorMatchFontDescriptorsWithProgressHandler(descs, nil) { (state: CTFontDescriptorMatchingState, progressParameter: CFDictionary) -> Bool in // print(" state == \(state), progress = \(progressParameter)") let parameter = progressParameter as NSDictionary let progressValue = parameter.objectForKey(kCTFontDescriptorMatchingPercentage)?.doubleValue switch state { case .DidBegin: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.activityIndeicator.startAnimating() self.textView.text = "Downloading \(fontName)" self.textView.font = UIFont.systemFontOfSize(12.0) print("Begin Matching") }) case .DidFinish: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.activityIndeicator.stopAnimating() self.activityIndeicator.hidden = true // display the sample text for the newly downloaded font if let index = self.fontNames.indexOf(fontName) { self.textView.text = self.fontSamples[index] self.textView.font = UIFont(name: fontName, size: 24.0) // Log the font URL in the console let font = CTFontCreateWithName(fontName, 0.0, nil) let fontURL = CTFontCopyAttribute(font, kCTFontURLAttribute) as! NSURL print("FontURL: \(fontURL)") } }) case .WillBeginDownloading: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.progress.progress = 0.0 self.progress.hidden = false print("Begin Downloading") }) case .DidFinishDownloading: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.progress.hidden = true self.activityIndeicator.hidden = true print("Finish Downloading") }) case .Downloading: dispatch_async(dispatch_get_main_queue(), { () -> Void in self.progress.setProgress(Float(progressValue! / 100.0), animated: true) print("Downliading \(progressValue!) complete") }) case .DidFailWithError: if let error = parameter.objectForKey(kCTFontDescriptorMatchingError) { self.errorMessage = error.description! } else { self.errorMessage = "Error message is not avilable!" } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.progress.hidden = true print("Download Error, msg: \(self.errorMessage)") }) default: break } return true } } }
mit
5ba94b474138150dd80173675183963c
35.232044
109
0.522495
5.378999
false
false
false
false
davidear/PasswordMenu
PasswordMenu/Module/PMLeftController.swift
1
8342
// // PMLeftController.swift // PasswordMenu // // Created by DaiFengyi on 15/11/17. // Copyright © 2015年 DaiFengyi. All rights reserved. // import UIKit import SnapKit import MagicalRecord class PMLeftController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var catList : NSMutableArray? override func viewDidLoad() { super.viewDidLoad() setupData() // 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() tableView.snp_updateConstraints { (make) -> Void in make.width.equalTo(self.view.snp_width).multipliedBy(0.75) } } func setupData() { catList = NSMutableArray(array: Category.MR_findAll()) } // MARK: - Button Action @IBAction func addNewCategory(sender: UIButton) { let ac = UIAlertController(title: "新建分类名", message: nil, preferredStyle: UIAlertControllerStyle.Alert) ac.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in } ac.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { [unowned self](alertAction: UIAlertAction) -> Void in guard var name = ac.textFields?.first?.text else { return } name = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) guard let list = self.catList else { return } for cat in list { if cat.name == name { return } } MagicalRecord.saveWithBlock({ (localContext: NSManagedObjectContext!) -> Void in let cat = Category.MR_createEntityInContext(localContext) if let textField = ac.textFields?.first { cat.name = textField.text } }, completion: { [unowned self](success: Bool, error: NSError!) -> Void in self.setupData() self.tableView.reloadData() }) })) ac.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: { (alertAction:UIAlertAction) -> Void in })) self.presentViewController(ac, animated: true, completion:nil) } @IBAction func settingButtonAction(sender: UIButton) { if let settingNavigationController = self.storyboard?.instantiateViewControllerWithIdentifier("SettingNavigationController") as? PMNavigationController { self.showViewController(settingNavigationController, sender: sender) } } @IBAction func EditButtonAction(sender: UIButton) { sender.selected = !sender.selected tableView.editing = sender.selected } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return catList!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LeftControllerCell", forIndexPath: indexPath) // Configure the cell... if let cat = catList![indexPath.row] as? Category { cell.textLabel?.text = cat.name cell.detailTextLabel?.text = "\(cat.itemList!.count)" } return cell } // func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // tableView.deselectRowAtIndexPath(indexPath, animated: true) // if let nc = self.sideMenuViewController.contentViewController as? UINavigationController { // if let itemListController = nc.viewControllers[0] as? PMItemListController { // if let cat = catList![indexPath.row] as? Category { // itemListController.cat = cat // } // } // } // } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 44 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return NSBundle.mainBundle().loadNibNamed("LeftControllerSecitonFooter", owner: self, options: nil).last as? UIButton } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 80 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return NSBundle.mainBundle().loadNibNamed("LeftControllerSectionHeader", owner: self, options: nil).last as? UIView } // MARK: Edition // Override to support conditional editing of the table view. 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. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source let alertController = UIAlertController(title: "请输入“Delete”确认删除", message: "该分类及其所属的密码将被删除", preferredStyle: UIAlertControllerStyle.Alert) alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField) -> Void in }) alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Destructive, handler: { (alertAction: UIAlertAction) -> Void in if alertController.textFields?.first?.text != "Delete" { return } guard let cat = self.catList![indexPath.row] as? Category else{ return } MagicalRecord.saveWithBlock({ (localContext: NSManagedObjectContext!) -> Void in cat.MR_deleteEntityInContext(localContext) }, completion: { (success: Bool, error: NSError!) -> Void in self.setupData() self.tableView.reloadData() // todo better animation,if use code below, the section footer will misplace // self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }) })) alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: { (alertAction:UIAlertAction) -> Void in })) self.showViewController(alertController, sender: nil) } 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. func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return false } */ /* // 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
ac50c8f86c42bef8282381f8984690b1
42.057292
161
0.633362
5.563257
false
false
false
false
aclissold/the-oakland-post
The Oakland Post/Constants.swift
5
1300
// // Constants.swift // The Oakland Post // // Global constants. // // Created by Andrew Clissold on 6/13/14. // Copyright (c) 2014 Andrew Clissold. All rights reserved. // import UIKit // Theming let serifName = "Palatino-Roman" let sansSerifName = "AvenirNext-Medium" let boldSansSerifName = "AvenirNext-DemiBold" let oaklandPostBlue = UIColor( red: 115.0/255.0, green: 148.0/255.0, blue: 175.0/255.0, alpha: 1.0 ) let translucentToolbarWhite: CGFloat = 0.96 let tableViewHeaderHeight: CGFloat = 80 let tableViewRowHeight: CGFloat = 120 let topToolbarHeight: CGFloat = 64, bottomToolbarHeight: CGFloat = 44 // NSNotificationCenter let foundStarredPostsNotification = "foundStarredPosts" // For ShowAlertForErrorCode.swift let feedParserDidFailErrorCode = 0 // UITableViewCell identifiers let cellID = "cell", sectionsCellID = "sectionsCell" let photoCellID = "photoCell", favoritesHeaderViewID = "favoritesHeaderView" // Segue identifiers let readPostID = "readPost", showSectionID = "showSection", signUpID = "signUp" let logInID = "logIn", favoritesID = "favoritesViewController", searchResultsID = "searchResultsViewController" let biosID1 = "bios1", biosID2 = "bios2", biosID3 = "bios3" // Restoration identifiers let infoContentViewControllerID = "infoContentViewController"
bsd-3-clause
ea7a8b7c42b3e26cc5ec8afda5e6359f
29.952381
111
0.763846
3.724928
false
false
false
false
kstaring/swift
stdlib/public/SDK/Foundation/Hashing.swift
5
832
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import CoreFoundation @_silgen_name("__CFHashInt") internal func __CFHashInt(_ i: Int) -> CFHashCode @_silgen_name("__CFHashDouble") internal func __CFHashDouble(_ d: Double) -> CFHashCode @_silgen_name("CFHashBytes") internal func CFHashBytes(_ bytes: UnsafeMutablePointer<UInt8>, _ length: Int) -> CFHashCode
apache-2.0
7a4df815fcb384717217c2660d66e0e2
36.818182
92
0.59375
4.923077
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/Services/AccountSettingsService.swift
2
7583
import Foundation import CocoaLumberjack import Reachability import WordPressKit let AccountSettingsServiceChangeSaveFailedNotification = "AccountSettingsServiceChangeSaveFailed" protocol AccountSettingsRemoteInterface { func getSettings(success: @escaping (AccountSettings) -> Void, failure: @escaping (Error) -> Void) func updateSetting(_ change: AccountSettingsChange, success: @escaping () -> Void, failure: @escaping (Error) -> Void) } extension AccountSettingsRemote: AccountSettingsRemoteInterface {} class AccountSettingsService { struct Defaults { static let stallTimeout = 4.0 static let maxRetries = 3 static let pollingInterval = 60.0 } enum Notifications { static let accountSettingsChanged = "AccountSettingsServiceSettingsChanged" static let refreshStatusChanged = "AccountSettingsServiceRefreshStatusChanged" } let remote: AccountSettingsRemoteInterface let userID: Int var status: RefreshStatus = .idle { didSet { stallTimer?.invalidate() stallTimer = nil NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: Notifications.refreshStatusChanged), object: nil) } } var settings: AccountSettings? = nil { didSet { NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: Notifications.accountSettingsChanged), object: nil) } } var stallTimer: Timer? fileprivate let context = ContextManager.sharedInstance().mainContext convenience init(userID: Int, api: WordPressComRestApi) { let remote = AccountSettingsRemote.remoteWithApi(api) self.init(userID: userID, remote: remote) } init(userID: Int, remote: AccountSettingsRemoteInterface) { self.userID = userID self.remote = remote loadSettings() } func getSettingsAttempt(count: Int = 0) { self.remote.getSettings( success: { settings in self.updateSettings(settings) self.status = .idle }, failure: { error in let error = error as NSError if error.domain == NSURLErrorDomain { DDLogError("Error refreshing settings (attempt \(count)): \(error)") } else { DDLogError("Error refreshing settings (unrecoverable): \(error)") } if error.domain == NSURLErrorDomain && count < Defaults.maxRetries { self.getSettingsAttempt(count: count + 1) } else { self.status = .failed } } ) } func refreshSettings() { guard status == .idle || status == .failed else { return } status = .refreshing getSettingsAttempt() stallTimer = Timer.scheduledTimer(timeInterval: Defaults.stallTimeout, target: self, selector: #selector(AccountSettingsService.stallTimerFired), userInfo: nil, repeats: false) } @objc func stallTimerFired() { guard status == .refreshing else { return } status = .stalled } func saveChange(_ change: AccountSettingsChange) { guard let reverse = try? applyChange(change) else { return } remote.updateSetting(change, success: { }) { (error) -> Void in do { // revert change try self.applyChange(reverse) } catch { DDLogError("Error reverting change \(error)") } DDLogError("Error saving account settings change \(error)") // TODO: show/return error to the user (@koke 2015-11-24) // What should be showing the error? Let's post a notification for now so something else can handle it NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: AccountSettingsServiceChangeSaveFailedNotification), object: error as NSError) } } func primarySiteNameForSettings(_ settings: AccountSettings) -> String? { let service = BlogService(managedObjectContext: context) let blog = service.blog(byBlogId: NSNumber(value: settings.primarySiteID)) return blog?.settings?.name } fileprivate func loadSettings() { settings = accountSettingsWithID(self.userID) } @discardableResult fileprivate func applyChange(_ change: AccountSettingsChange) throws -> AccountSettingsChange { guard let settings = managedAccountSettingsWithID(userID) else { DDLogError("Tried to apply a change to nonexistent settings (ID: \(userID)") throw Errors.notFound } let reverse = settings.applyChange(change) settings.account.applyChange(change) ContextManager.sharedInstance().save(context) loadSettings() return reverse } fileprivate func updateSettings(_ settings: AccountSettings) { if let managedSettings = managedAccountSettingsWithID(userID) { managedSettings.updateWith(settings) } else { createAccountSettings(userID, settings: settings) } ContextManager.sharedInstance().save(context) loadSettings() } fileprivate func accountSettingsWithID(_ userID: Int) -> AccountSettings? { return managedAccountSettingsWithID(userID).map(AccountSettings.init) } fileprivate func managedAccountSettingsWithID(_ userID: Int) -> ManagedAccountSettings? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: ManagedAccountSettings.entityName) request.predicate = NSPredicate(format: "account.userID = %d", userID) request.fetchLimit = 1 guard let results = (try? context.fetch(request)) as? [ManagedAccountSettings] else { return nil } return results.first } fileprivate func createAccountSettings(_ userID: Int, settings: AccountSettings) { let accountService = AccountService(managedObjectContext: context) guard let account = accountService.findAccount(withUserID: NSNumber(value: userID)) else { DDLogError("Tried to create settings for a missing account (ID: \(userID)): \(settings)") return } if let managedSettings = NSEntityDescription.insertNewObject(forEntityName: ManagedAccountSettings.entityName, into: context) as? ManagedAccountSettings { managedSettings.updateWith(settings) managedSettings.account = account } } enum Errors: Error { case notFound } enum RefreshStatus { case idle case refreshing case stalled case failed var errorMessage: String? { switch self { case .stalled: return NSLocalizedString("We are having trouble loading data", comment: "Error message displayed when a refresh is taking longer than usual. The refresh hasn't failed and it might still succeed") case .failed: return NSLocalizedString("We had trouble loading data", comment: "Error message displayed when a refresh failed") case .idle, .refreshing: return nil } } } }
gpl-2.0
021ca69420e7e8d70d8440dd5a82b7e4
36.171569
211
0.624159
5.646314
false
false
false
false
PureSwift/DBus
Sources/DBus/Error.swift
1
4966
// // Error.swift // DBus // // Created by Alsey Coleman Miller on 2/25/16. // Copyright © 2016 PureSwift. All rights reserved. // import Foundation import CDBus /// DBus type representing an exception. public struct DBusError: Error, Equatable, Hashable { /// Error name field public let name: DBusError.Name /// Error message field public let message: String internal init(name: DBusError.Name, message: String) { self.name = name self.message = message } } // MARK: - Internal Reference internal extension DBusError { /// Internal class for working with the C DBus error API internal final class Reference { // MARK: - Internal Properties internal var internalValue: CDBus.DBusError // MARK: - Initialization deinit { dbus_error_free(&internalValue) } /// Creates New DBus Error instance. init() { var internalValue = CDBus.DBusError() dbus_error_init(&internalValue) self.internalValue = internalValue } // MARK: - Properties /// Checks whether an error occurred (the error is set). /// /// - Returns: `true` if the error is empty or `false` if the error is set. var isEmpty: Bool { return Bool(dbus_error_is_set(&internalValue)) == false } var name: String { return String(cString: internalValue.name) } var message: String { return String(cString: internalValue.message) } func hasName(_ name: String) -> Bool { return Bool(dbus_error_has_name(&internalValue, name)) } } } internal extension DBusError { init?(_ reference: DBusError.Reference) { guard reference.isEmpty == false else { return nil } guard let name = DBusError.Name(rawValue: reference.name) else { fatalError("Invalid error \(reference.name)") } self.init(name: name, message: reference.message) } } // MARK: CustomNSError extension DBusError: CustomNSError { public enum UserInfoKey: String { /// DBus error name case name } /// The domain of the error. public static let errorDomain = "org.freedesktop.DBus.Error" /// The error code within the given domain. public var errorCode: Int { return hashValue } /// The user-info dictionary. public var errorUserInfo: [String: Any] { return [ UserInfoKey.name.rawValue: self.name.rawValue, NSLocalizedDescriptionKey: self.message ] } } // MARK: Error Name public extension DBusError { public struct Name: Equatable, Hashable { public let rawValue: String public init?(rawValue: String) { // validate from C, no parsing do { try DBusInterface.validate(rawValue) } catch { return nil } self.rawValue = rawValue } } } public extension DBusError.Name { public init(_ interface: DBusInterface) { // should be valid self.rawValue = interface.rawValue } } public extension DBusInterface { init(_ error: DBusError.Name) { self.init(rawValue: error.rawValue)! } } public extension DBusError.Name { /// A generic error; "something went wrong" - see the error message for more. /// /// `org.freedesktop.DBus.Error.Failed` public static let failed = DBusError.Name(rawValue: DBUS_ERROR_FAILED)! /// No Memory /// /// `org.freedesktop.DBus.Error.NoMemory` public static let noMemory = DBusError.Name(rawValue: DBUS_ERROR_NO_MEMORY)! /// Existing file and the operation you're using does not silently overwrite. /// /// `org.freedesktop.DBus.Error.FileExists` public static let fileExists = DBusError.Name(rawValue: DBUS_ERROR_FILE_EXISTS)! /// Missing file. /// /// `org.freedesktop.DBus.Error.FileNotFound` public static let fileNotFound = DBusError.Name(rawValue: DBUS_ERROR_FILE_NOT_FOUND)! /// Invalid arguments /// /// `org.freedesktop.DBus.Error.InvalidArgs` public static let invalidArguments = DBusError.Name(rawValue: DBUS_ERROR_INVALID_ARGS)! /// Invalid signature /// /// `org.freedesktop.DBus.Error.InvalidSignature` public static let invalidSignature = DBusError.Name(rawValue: DBUS_ERROR_INVALID_SIGNATURE)! } extension DBusError.Name: CustomStringConvertible { public var description: String { return rawValue } }
mit
e9eaaa23a3b81873bd74b6dc09f451e0
23.825
96
0.578449
4.87721
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Controllers/AwesomeMediaVideoViewController.swift
1
4911
// // AwesomeMediaVideoViewController.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 4/4/18. // import UIKit public class AwesomeMediaVideoViewController: UIViewController { public static var presentingVideoInFullscreen = false @IBOutlet public weak var playerView: AwesomeMediaView! // Public variables public var mediaParams = AwesomeMediaParams() var controls: AwesomeMediaVideoControls = .all var titleViewVisible: Bool = true public override func viewDidLoad() { super.viewDidLoad() playerView.configure(withMediaParams: mediaParams, controls: controls, states: .standard, trackingSource: .videoFullscreen, titleViewVisible: titleViewVisible) playerView.controlView?.fullscreenCallback = { [weak self] in self?.close() // track event track(event: .toggleFullscreen, source: .videoFullscreen) } playerView.controlView?.jumpToCallback = { [weak self] in guard let self = self else { return } self.showMarkers(self.mediaParams.markers) { (mediaMarker) in if let mediaMarker = mediaMarker { sharedAVPlayer.seek(toTime: mediaMarker.time) sharedAVPlayer.play() } } } playerView.titleView?.closeCallback = { [weak self] in sharedAVPlayer.stop() self?.close() // track event track(event: .closeFullscreen, source: .videoFullscreen) track(event: .stoppedPlaying, source: .videoFullscreen) } playerView.finishedPlayingCallback = { [weak self] in self?.close() } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // adds player layer in case it's not visible playerView.addPlayerLayer() } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) AwesomeMediaVideoViewController.presentingVideoInFullscreen = false // remove observers when leaving playerView.removeObservers() } public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // track event track(event: .changedOrientation, source: .audioFullscreen, value: UIApplication.shared.statusBarOrientation) } // MARK: Events @IBAction func toggleControlsButtonPressed(_ sender: Any) { playerView.controlView?.toggleViewIfPossible() } // MARK: - Marker Selected public func markerSelected(marker: AwesomeMediaMarker) { } //to hide the bottom bar on iPhone X+ after a few seconds override public var prefersHomeIndicatorAutoHidden: Bool { return true } } extension AwesomeMediaVideoViewController { fileprivate func close() { dismiss(animated: true) { if AwesomeMedia.shouldStopVideoWhenCloseFullScreen { sharedAVPlayer.stop() AwesomeMedia.shouldStopVideoWhenCloseFullScreen = false } AwesomeMediaVideoViewController.presentingVideoInFullscreen = false } } } // MARK: - ViewController Initialization extension AwesomeMediaVideoViewController { public static var newInstance: AwesomeMediaVideoViewController { let storyboard = UIStoryboard(name: "AwesomeMedia", bundle: AwesomeMedia.bundle) return storyboard.instantiateViewController(withIdentifier: "AwesomeMediaVideoViewController") as! AwesomeMediaVideoViewController } } extension UIViewController { public func presentVideoFullscreen(withMediaParams mediaParams: AwesomeMediaParams, withControls controls: AwesomeMediaVideoControls = .all, titleViewVisible: Bool = true) { guard !AwesomeMediaVideoViewController.presentingVideoInFullscreen else { return } AwesomeMediaPlayerType.type = .video AwesomeMediaVideoViewController.presentingVideoInFullscreen = true let viewController = AwesomeMediaVideoViewController.newInstance viewController.mediaParams = mediaParams viewController.controls = controls viewController.titleViewVisible = titleViewVisible interactor = AwesomeMediaInteractor() viewController.modalPresentationStyle = .fullScreen viewController.transitioningDelegate = self viewController.interactor = interactor self.present(viewController, animated: true, completion: nil) } }
mit
5e73db34cf6bb429d9f6c295d5498012
34.330935
138
0.643861
6.280051
false
false
false
false
iankunneke/TIY-Assignmnts
22-SwiftBriefing/22-SwiftBriefing/MyViewController.swift
1
2463
// // MyViewController.swift // 22-SwiftBriefing // // Created by ian kunneke on 7/15/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // import UIKit class MyViewController: UIViewController { @IBOutlet weak var agentNameTextField: UITextField! @IBOutlet weak var agentPasswordTextField: UITextField! @IBOutlet weak var greetingLabel: UILabel! @IBOutlet weak var missionBriefingTextView: UITextView! @IBAction func authenticateAgent (sender: AnyObject) { if agentNameTextField .isFirstResponder() { agentNameTextField .resignFirstResponder() } if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty && agentNameTextField.text.componentsSeparatedByString(" ").count == 2 { let agentName = agentNameTextField.text let nameComponents = agentName.componentsSeparatedByString(" ") greetingLabel.text = "Good Evening, Agent \(nameComponents[1])" missionBriefingTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(nameComponents[1]), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds." self.view.backgroundColor = UIColor.greenColor() } else { self.view.backgroundColor = UIColor.redColor() } } override func viewDidLoad() { super.viewDidLoad() self.agentNameTextField.text = "" self.agentPasswordTextField.text = "" self.missionBriefingTextView.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty { resignFirstResponder() } /* // 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. } */ } }
cc0-1.0
a4b1e4e5915934cf17637a47e56caeb2
30.987013
356
0.662201
5.17437
false
false
false
false
exchangegroup/FitLoader
Demo/ViewControllers/ViewController.swift
2
1603
import UIKit import MprHttp import FitLoader import Dodo class ViewController: UIViewController, UINavigationControllerDelegate, TegReachableViewController { weak var failedLoader: TegReachabilityLoader? @IBOutlet weak var label: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var loader: TegReachabilityLoader? override func viewDidLoad() { super.viewDidLoad() view.dodo.style.rightButton.hideOnTap = true DodoBarDefaultStyles.locationTop = false navigationController?.delegate = self label.text = nil activityIndicator.hidden = true load() } private func load() { if loader != nil { return } // already loading let requestIdentity = TegRequestType.Text.identity() let newLoadder = TegReachabilityLoader(httpText: TegHttpText(), requestIdentity: requestIdentity, viewController: self, authentication: nil) { [weak self] text in self?.label.text = text return true } newLoadder.onStarted = { [weak self] in self?.activityIndicator.hidden = false } newLoadder.onFinishedWithSuccessOrError = { [weak self] in self?.activityIndicator.hidden = true } newLoadder.startLoading() loader = newLoadder } // UINavigationControllerDelegate // ------------------------- func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { TegReachability.shared.reloadOldFailedRequest(viewController) } }
mit
0a74b649313c2740ad850561bdf3c1c9
25.278689
148
0.700561
5.325581
false
false
false
false
pepibumur/SoundCloudSwift
SoundCloudSwift/Source/Core/Entities/Filters/TrackFilter.swift
2
1683
import Foundation /// Track filter /// Reference: https://developers.soundcloud.com/docs/api/reference#tracks public enum TrackFilter: Filter { /// Track visibility public enum Visibility: String { case All, Public, Private } case Query(String) case Tags([String]) case Filter(Visibility) case License(String) case BpmFrom(Int) case BpmTo(Int) case DurationTo(Int) case From(NSDate) case To(NSDate) case Ids([Int]) case Genres([String]) case Types([String]) // MARK: - Filter func toDict() -> [String: AnyObject] { var dict = [String: AnyObject]() switch self { case .Query(let query): dict["q"] = query case .Tags(let tags): dict["tags"] = tags.joinWithSeparator(",") case .Filter(let visibility): dict["filter"] = visibility.rawValue.lowercaseString case .License(let license): dict["license"] = license case .BpmFrom(let from): dict["bpm[from]"] = from case .BpmTo(let from): dict["bpm[to]"] = from case .DurationTo(let from): dict["duration[to]"] = from case .From(let from): dict["created_at[from]"] = date(from) case .To(let to): dict["created_at[to]"] = date(to) case .Ids(let ids): dict["ids"] = ids.map({"\($0)"}).joinWithSeparator(",") case .Genres(let genres): dict["genres"] = genres.joinWithSeparator(",") case .Types(let types): dict["types"] = types.joinWithSeparator(",") } return dict } }
mit
0634009784dc088f7d027fe22711ac84
28.034483
74
0.546643
4.271574
false
false
false
false
RLovelett/langserver-swift
Sources/SourceKitter/Types/library_wrapper.swift
1
8664
// // library_wrapper.swift // sourcekitten // // Created by Norio Nomura on 2/20/16. // Copyright © 2016 SourceKitten. All rights reserved. // // This code originates from the SourceKitten tool which carries the following license: // The MIT License (MIT) // // Copyright (c) 2014 JP Simard. // // 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 struct DynamicLinkLibrary { let path: String let handle: UnsafeMutableRawPointer func load<T>(symbol: String) -> T { if let sym = dlsym(handle, symbol) { return unsafeBitCast(sym, to: T.self) } let errorString = String(validatingUTF8: dlerror()) fatalError("Finding symbol \(symbol) failed: \(errorString ?? "unknown error")") } } #if os(Linux) let toolchainLoader = Loader(searchPaths: [ linuxSourceKitLibPath, linuxFindSwiftenvActiveLibPath, linuxFindSwiftInstallationLibPath, linuxDefaultLibPath ].compactMap({ $0 })) #else let toolchainLoader = Loader(searchPaths: [ xcodeDefaultToolchainOverride, toolchainDir, xcrunFindPath, /* These search paths are used when `xcode-select -p` points to "Command Line Tools OS X for Xcode", but Xcode.app exists. */ applicationsDir?.xcodeDeveloperDir.toolchainDir, applicationsDir?.xcodeBetaDeveloperDir.toolchainDir, userApplicationsDir?.xcodeDeveloperDir.toolchainDir, userApplicationsDir?.xcodeBetaDeveloperDir.toolchainDir ].compactMap { path in if let fullPath = path?.usrLibDir, fullPath.isFile { return fullPath } return nil }) #endif struct Loader { let searchPaths: [String] func load(path: String) -> DynamicLinkLibrary { let fullPaths = searchPaths.map { $0.appending(pathComponent: path) }.filter { $0.isFile } // try all fullPaths that contains target file, // then try loading with simple path that depends resolving to DYLD for fullPath in fullPaths + [path] { if let handle = dlopen(fullPath, RTLD_LAZY) { return DynamicLinkLibrary(path: path, handle: handle) } } fatalError("Loading \(path) failed") } } private func env(_ name: String) -> String? { return ProcessInfo.processInfo.environment[name] } /// Run a process at the given (absolute) path, capture output, return outupt. private func runCommand(_ path: String, _ args: String...) -> String? { let process = Process() process.launchPath = path process.arguments = args let pipe = Pipe() process.standardOutput = pipe process.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard let encoded = String(data: data, encoding: String.Encoding.utf8) else { return nil } let trimmed = encoded.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if trimmed.isEmpty { return nil } return trimmed } /// Returns "LINUX_SOURCEKIT_LIB_PATH" environment variable. internal let linuxSourceKitLibPath = env("LINUX_SOURCEKIT_LIB_PATH") /// If available, uses `swiftenv` to determine the user's active Swift root. internal let linuxFindSwiftenvActiveLibPath: String? = { guard let swiftenvPath = runCommand("/usr/bin/which", "swiftenv") else { return nil } guard let swiftenvRoot = runCommand(swiftenvPath, "prefix") else { return nil } return swiftenvRoot + "/usr/lib" }() /// Attempts to discover the location of libsourcekitdInProc.so by looking at /// the `swift` binary on the path. internal let linuxFindSwiftInstallationLibPath: String? = { guard let swiftPath = runCommand("/usr/bin/which", "swift") else { return nil } if linuxSourceKitLibPath == nil && linuxFindSwiftenvActiveLibPath == nil && swiftPath.hasSuffix("/shims/swift") { /// If we hit this path, the user is invoking Swift via swiftenv shims and has not set the /// environment variable; this means we're going to end up trying to load from `/usr/lib` /// which will fail - and instead, we can give a more useful error message. fatalError("Swift is installed via swiftenv but swiftenv is not initialized.") } if !swiftPath.hasSuffix("/bin/swift") { return nil } /// .../bin/swift -> .../lib return swiftPath.deleting(lastPathComponents: 2) + "lib" }() /// Fallback path on Linux if no better option is available. internal let linuxDefaultLibPath = "/usr/lib" /// Returns "XCODE_DEFAULT_TOOLCHAIN_OVERRIDE" environment variable /// /// `launch-with-toolchain` sets the toolchain path to the /// "XCODE_DEFAULT_TOOLCHAIN_OVERRIDE" environment variable. private let xcodeDefaultToolchainOverride = env("XCODE_DEFAULT_TOOLCHAIN_OVERRIDE") /// Returns "TOOLCHAIN_DIR" environment variable /// /// `Xcode`/`xcodebuild` sets the toolchain path to the /// "TOOLCHAIN_DIR" environment variable. private let toolchainDir = env("TOOLCHAIN_DIR") /// Returns toolchain directory that parsed from result of `xcrun -find swift` /// /// This is affected by "DEVELOPER_DIR", "TOOLCHAINS" environment variables. private let xcrunFindPath: String? = { let pathOfXcrun = "/usr/bin/xcrun" if !FileManager.default.isExecutableFile(atPath: pathOfXcrun) { return nil } let task = Process() task.launchPath = pathOfXcrun task.arguments = ["-find", "swift"] let pipe = Pipe() task.standardOutput = pipe task.launch() // if xcode-select does not exist, crash with `NSInvalidArgumentException`. let data = pipe.fileHandleForReading.readDataToEndOfFile() guard let output = String(data: data, encoding: .utf8) else { return nil } var start = output.startIndex var end = output.startIndex var contentsEnd = output.startIndex output.getLineStart(&start, end: &end, contentsEnd: &contentsEnd, for: start..<start) #if swift(>=4.0) let xcrunFindSwiftPath = String(output[start..<contentsEnd]) #else let xcrunFindSwiftPath = output[start..<contentsEnd] #endif guard xcrunFindSwiftPath.hasSuffix("/usr/bin/swift") else { return nil } let xcrunFindPath = xcrunFindSwiftPath.deleting(lastPathComponents: 3) // Return nil if xcrunFindPath points to "Command Line Tools OS X for Xcode" // because it doesn't contain `sourcekitd.framework`. if xcrunFindPath == "/Library/Developer/CommandLineTools" { return nil } return xcrunFindPath }() private let applicationsDir: String? = NSSearchPathForDirectoriesInDomains(.applicationDirectory, .systemDomainMask, true).first private let userApplicationsDir: String? = NSSearchPathForDirectoriesInDomains(.applicationDirectory, .userDomainMask, true).first private extension String { var toolchainDir: String { return appending(pathComponent: "Toolchains/XcodeDefault.xctoolchain") } var xcodeDeveloperDir: String { return appending(pathComponent: "Xcode.app/Contents/Developer") } var xcodeBetaDeveloperDir: String { return appending(pathComponent: "Xcode-beta.app/Contents/Developer") } var usrLibDir: String { return appending(pathComponent: "/usr/lib") } func appending(pathComponent: String) -> String { return URL(fileURLWithPath: self).appendingPathComponent(pathComponent).path } func deleting(lastPathComponents numberOfPathComponents: Int) -> String { var url = URL(fileURLWithPath: self) for _ in 0..<numberOfPathComponents { url = url.deletingLastPathComponent() } return url.path } }
apache-2.0
4478bb612eaeeb548267a3343c3ac6d4
33.376984
98
0.702066
4.465464
false
false
false
false
2RKowski/two-blobs
TwoBlobs/AmbientLightCell.swift
1
826
// // DecoderCell.swift // TwoBlobs // // Created by Lësha Turkowski on 14/01/2017. // Copyright © 2017 Amblyofetus. All rights reserved. // import UIKit import RxSwift import RxCocoa final class AmbientLightCell: UICollectionViewCell { private var viewModel: AmbientLightCellModelType? private var disposeBag = DisposeBag() func configure(viewModel: AmbientLightCellModelType) { self.viewModel = viewModel disposeBag = DisposeBag() viewModel .backgroundColor .asDriver(onErrorJustReturn: nil) .drive(onNext: setBackgroundColor) .addDisposableTo(disposeBag) } private func setBackgroundColor(_ color: UIColor?) { if let color = color { contentView.backgroundColor = color } } }
mit
ae42b3dbc55537ee9af066d0b4ad2f21
23.235294
58
0.651699
4.847059
false
false
false
false
tardieu/swift
validation-test/compiler_crashers_fixed/00170-swift-parser-skipsingle.swift
65
10392
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func i(f: g) -> <j>(() -> j) -> g { func g k, l { typealias l = m<k<m>, f> } func ^(a: Boolean, Bool) -> Bool { return !(a) } func b(c) -> <d>(() -> d) { } func q(v: h) -> <r>(() -> r) -> h { n { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } protocol p { } protocol m : p { } protocol v : p { } protocol m { v = m } func s<s : m, v : m u v.v == s> (m: v) { } func s<v : m u v.v == v> (m: v) { } s( { ({}) } t func f<e>() -> (e, e -> e) -> e { e b e.c = {} { e) { f } } protocol f { class func c() } class e: f { class func c } } protocol A { func c()l k { func l() -> g { m "" } } class C: k, A { j func l()q c() -> g { m "" } } func e<r where r: A, r: k>(n: r) { n.c() } protocol A { typealias h } c k<r : A> { p f: r p p: r.h } protocol C l.e() } } class o { typealias l = l protocol a { } protocol h : a { } protocol k : a { } protocol g { j n = a } struct n : g { j n = h } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } let k = a k() h protocol k : h { func h k func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c k) func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { class func i() } class k: c{ class func i { } class i { func d((h: (Any, AnyObject)) { d(h) } } d h) func d<i>() -> (i, i -> i) -> i { i j i.f = { } protocol d { class func f() } class i: d{ class func f {} protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e()) class l { func f((k, l() -> f } class d } class i: d, g { l func d() -> f { m "" } } } func m<j n j: g, j: d let l = h l() f protocol l : f { func f protocol g func g<h>() -> (h, h -> h) -> h { f f: ((h, h -> h) -> h)! j f } protocol f { class func j() } struct i { f d: f.i func j() { d.j() } } class g { typealias f = f } func g(f: Int = k) { } let i = g class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j struct c<d : Sequence> { var b: [c<d>] { return [] } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func f<T : Boolean>(b: T) { } f(true as Boolean) func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type func e() { d.e() } } b protocol c : b { func b otocol A { E == F>(f: B<T>) } struct } } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f func g() f e: d { f func g() { } } (e() h d).i() e protocol g : e { func e func a(b: Int = 0) { } let c = a c() var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func m<u>() -> (u, u -> u) -> u { p o p.s = { } { u) { o } } s m { class func s() } class p: m{ class func s {} s p { func m() -> String } class n { func p() -> String { q "" } } class e: n, p { v func> String { q "" } { r m = m } func s<o : m, o : p o o.m == o> (m: o) { } func s<v : p o v.m == m> (u: String) -> <t>(() -> t) - func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n struct c<d: Sequence, b where Optional<b> == d.Iterator.Element> d = i } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { typealias i } protocol e { class func i() } i (d() as e).j.i() d protocol i : d { func d class k<g>: d { var f: g init(f: g) { self.f = f l. d { typealias i = l typealias j = j<i<l>, i> } class j { typealias d = d struct A<T> { let a: [(T, () -> ())] = [] } func b<d-> d { class d:b class b class A<T : A> { } func c<d { enum c { func e var _ = e } } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicl A { { typealias b = b d.i = { } { g) { h } } protocol f { class func i() }} func f<m>() -> (m, m -> m) -> m { e c e.i = { } { m) { n } } protocol f { class func i() } class e: f{ class func i {} func n<j>() -> (j, j -> j) -> j { var m: ((j> j)! f m } protocol k { typealias m } struct e<j : k> {n: j let i: j.m } l func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m - import Foundation class Foo<T>: NSObject { var foo: T init(foo: T) { B>(t: T) { t.c() } x x) { } class a { var _ = i() { } } a=1 as a=1 func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> func k<q { enum k { func j var _ = j } } class x { s m func j(m) } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v let u: v.l } protocol y { o= p>(r: m<v>) } struct D : y { s p = Int func y<v k r { s m } class y<D> { w <r: func j<v x: v) { x.k() } func x(j: Int = a) { } let k = x func b((Any, e))(e: (Any) -> <d>(()-> d) -> f func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) protocol f : f { } func h<d { enum h { func e var _ = e } } protocol e { e func e() } struct h { var d: e.h func e() { d.e() } } protocol f { i [] } func f<g>() -> (g, g -> g) -> g class A<T : A> n = { return $u } l o: n = { (d: n, o: n -> n) -> n q return o(d) } import Foundation class m<j>: NSObject { var h: j g -> k = l $n } b f: _ = j() { } } func k<g { enum k { func l var _ = l func o() as o).m.k() func p(k: b) -> <i>(() -> i) -> b { n { o f "\(k): \(o())" } } struct d<d : n, o:j n { l p } protocol o : o { } func o< class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> struct l<e : Sequence> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k struct c<e> { let d: [( h } func b(g: f) -> <e>(()-> e) -> i h } func e<l { enum e { func e j { class func n() } class l: j{ k() -> ()) } ({}) func j<o : Boolean>(l: o) { } j(j q Boolean) func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) { return { (p: (Any, Any) -> Any) -> Any in func n<n : l,) { } n(e()) e func a<T>() { enum b { case c } } o class w<r>: c { init(g: r) { n.g = g s.init() (t: o struct t : o { p v = t } q t<where n.v == t<v : o u m : v { } struct h<t, j: v where t.h == j f> { c(d ()) } func b(e)-> <d>(() -> d) func f<T : Boolean>(b: T) { } f(true as Boolean) class A: A { } class B : C { } typealias C = B protocol A { typealias E } struct B<T : As a { typealias b = b } func a<T>() {f { class func i() } class d: f{ class func i {} func f() { ({}) } func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } protocol a : a { } class j { func y((Any, j))(v: (Any, AnyObject)) { y(v) } } func w(j: () -> ()) { } class v { l _ = w() { } } ({}) func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { u n } y q<x> { s w(x, () -> ()) } o n { func j() p } class r { func s() -> p { t "" } } class w: r, n { k v: ))] = [] } class n<x : n> w class x<u>: d { l i: u init(i: u) { o.i = j { r { w s "\(f): \(w())" } } protoc protocol f : b { func b () { g g h g } } func e(i: d) -> <f>(() -> f)> import Foundation class k<f>: NSObject { d e: f g(e: f) { j h.g() } } d protocol i : d { func d i b protocol d : b { func b func d(e: = { (g: h, f: h -> h) -> h in return f(g) } } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } struct j<l : o> { k b: l } func a<l>() -> [j<l>] { return [] } f k) func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typealias l typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } a=1 as a=1 enum S<T> { case C(T, () -> ()) } n) func f<o>() -> (o, o -> o) -> o { o m o.j = { } { o) { r } } p q) { } o m = j m() class m { func r((Any, m))(j: (Any, AnyObject)) { r(j) } } func m<o { r m { func n n _ = n } } class k<l : k <c b: func b<c { enum b { func b var _ = b func n<p>() -> (p, p -> p) -> p { b, l] g(o(q)) h e { j class func r() } class k: h{ class func r {} var k = 1 var s: r -> r t -> r) -> r m u h>] { u [] } func r(e: () -> ()) { } class n { var _ = r()
apache-2.0
5f20009e5a72cfc9a41cf5f5070e2f16
12.272031
79
0.410701
2.29759
false
false
false
false
sora0077/libevent
OSX Projects/libeventDemo/libeventDemo/main.swift
1
1573
// // main.swift // libeventDemo // // Created by 林達也 on 2016/01/04. // Copyright © 2016年 jp.sora0077. All rights reserved. // import Foundation import libevent print("Hello, World!") func http_request_done(req: UnsafeMutablePointer<evhttp_request>, arg: UnsafeMutablePointer<Void>) { var buf = Array<CChar>(count: 256, repeatedValue: 0) var nread: Int32 = 0 repeat { let input = evhttp_request_get_input_buffer(req) nread = evbuffer_remove(input, &buf, 255) if nread == 0 { break } print(String.fromCString(buf)) } while(nread > 0) event_base_loopbreak(COpaquePointer(arg)) } var uri_path: String = "" let uri = evhttp_uri_parse("http://qiita.com/tattsun58/items/50e606696f1daa607a5f") let host = evhttp_uri_get_host(uri) let port = evhttp_uri_get_port(uri) == -1 ? 80 : evhttp_uri_get_port(uri) let path = evhttp_uri_get_path(uri) if let path = String.fromCString(path) where path.characters.count != 0 { uri_path = path } else { uri_path = "/" } let base = event_base_new() let dns_base = evdns_base_new(base, 1) let conn = evhttp_connection_base_new(base, dns_base, host, UInt16(port)) let req = evhttp_request_new(http_request_done, UnsafeMutablePointer(base)) evhttp_add_header(req.memory.output_headers, "Host", host) evhttp_add_header(req.memory.output_headers, "Connection", "close") evhttp_make_request(conn, req, EVHTTP_REQ_GET, uri_path) evhttp_connection_set_timeout(req.memory.evcon, 600) event_base_dispatch(base) evhttp_connection_free(conn) event_base_free(base)
mit
bcb4d93aa08ff13253301f9a50d8c20c
27.962963
100
0.695013
3.054688
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/General/GeneralInformationClient.swift
1
1228
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import Errors import NetworkKit public protocol GeneralInformationClientAPI: AnyObject { var countries: AnyPublisher<[CountryData], NabuNetworkError> { get } } final class GeneralInformationClient: GeneralInformationClientAPI { // MARK: - Types private enum Path { static let countries = ["countries"] } // MARK: - Properties /// Requests a session token for the wallet, if not available already var countries: AnyPublisher<[CountryData], NabuNetworkError> { let request = requestBuilder.get( path: Path.countries )! return networkAdapter.perform( request: request, responseType: [CountryData].self ) } // MARK: - Properties private let requestBuilder: RequestBuilder private let networkAdapter: NetworkAdapterAPI // MARK: - Setup init( networkAdapter: NetworkAdapterAPI = resolve(tag: DIKitContext.retail), requestBuilder: RequestBuilder = resolve(tag: DIKitContext.retail) ) { self.networkAdapter = networkAdapter self.requestBuilder = requestBuilder } }
lgpl-3.0
f5d9dfa4181be5bc081ba4d01d601588
25.106383
78
0.678077
5.334783
false
false
false
false
finder39/resumod
Resumod/ResumeModel.swift
1
1416
// // ResumeModel.swift // Resumod // // Created by Joseph Neuman on 7/16/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation class ResumeModel { let version:String = "" var bio:BioModel = BioModel() var work:[WorkModel] = [] var education:[EducationModel] = [] var awards:[AnyObject] = [] var publications:[AnyObject] = [] var skills:[SkillModel] = [] var hobbies:[AnyObject] = [] var references:[AnyObject] = [] init() { } init(fromJSONData json:Dictionary<String, AnyObject>) { if let version = (json["version"] as AnyObject?) as? String { self.version = version } if let bio = (json["bio"] as AnyObject?) as? Dictionary<String, AnyObject> { self.bio = BioModel(fromJSONData: json["bio"]! as Dictionary) } if let work = (json["work"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for workItem in work { self.work.append(WorkModel(fromJSONData: workItem)) } } if let education = (json["education"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for educationItem in education { self.education.append(EducationModel(fromJSONData: educationItem)) } } if let skills = (json["skills"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for skill in skills { self.skills.append(SkillModel(fromJSONData: skill)) } } } }
mit
342e1a2c8e7ba38a93e5def641b424ae
27.918367
94
0.634887
3.847826
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/FormattableContent/Ranges/FormattableNoticonRange.swift
2
1115
/// This class is used as part of the Notification Formattable Content system. /// It inserts the given icon into an attributed string at the given range. /// public class FormattableNoticonRange: FormattableContentRange { public var kind: FormattableRangeKind = .noticon public var range: NSRange public let value: String private var noticon: String { return value + " " } public init(value: String, range: NSRange) { self.value = value self.range = range } public func apply(_ styles: FormattableContentStyles, to string: NSMutableAttributedString, withShift shift: Int) -> FormattableContentRange.Shift { let shiftedRange = rangeShifted(by: shift) insertIcon(to: string, at: shiftedRange) let longerRange = NSMakeRange(shiftedRange.location, shiftedRange.length + noticon.count) apply(styles, to: string, at: longerRange) return noticon.count } func insertIcon(to string: NSMutableAttributedString, at shiftedRange: NSRange) { string.replaceCharacters(in: shiftedRange, with: noticon) } }
gpl-2.0
ba3abd29eca69f3184b5885979d97ff7
33.84375
152
0.702242
4.607438
false
false
false
false
grayunicorn/Quiz
Quiz/Core Data/QuizCollection+CoreDataProperties.swift
1
6656
// // QuizCollection+CoreDataProperties.swift // Quiz // // Created by Adam Eberbach on 11/9/17. // Copyright © 2017 Adam Eberbach. All rights reserved. // // import Foundation import CoreData extension QuizCollection { @nonobjc public class func fetchRequest() -> NSFetchRequest<QuizCollection> { return NSFetchRequest<QuizCollection>(entityName: "QuizCollection") } @NSManaged public var text: String? @NSManaged public var questions: NSOrderedSet? @NSManaged public var students: Student? @NSManaged public var teachers: Teacher? } // MARK: Generated accessors for questions extension QuizCollection { @objc(insertObject:inQuestionsAtIndex:) @NSManaged public func insertIntoQuestions(_ value: QuizQuestion, at idx: Int) @objc(removeObjectFromQuestionsAtIndex:) @NSManaged public func removeFromQuestions(at idx: Int) @objc(insertQuestions:atIndexes:) @NSManaged public func insertIntoQuestions(_ values: [QuizQuestion], at indexes: NSIndexSet) @objc(removeQuestionsAtIndexes:) @NSManaged public func removeFromQuestions(at indexes: NSIndexSet) @objc(replaceObjectInQuestionsAtIndex:withObject:) @NSManaged public func replaceQuestions(at idx: Int, with value: QuizQuestion) @objc(replaceQuestionsAtIndexes:withQuestions:) @NSManaged public func replaceQuestions(at indexes: NSIndexSet, with values: [QuizQuestion]) @objc(addQuestionsObject:) @NSManaged public func addToQuestions(_ value: QuizQuestion) @objc(removeQuestionsObject:) @NSManaged public func removeFromQuestions(_ value: QuizQuestion) @objc(addQuestions:) @NSManaged public func addToQuestions(_ values: NSOrderedSet) @objc(removeQuestions:) @NSManaged public func removeFromQuestions(_ values: NSOrderedSet) } // MARK: convenience functions extension QuizCollection { // create a new QuizCollection with its title, add it to the Teacher's collection class func createWithTitle(_ text: String, inContext: NSManagedObjectContext) -> QuizCollection { let collection = NSEntityDescription.insertNewObject(forEntityName: kManagedObjectIdentifier, into: inContext) as! QuizCollection collection.text = text return collection } func questionNumber(_ number: Int) -> QuizQuestion? { var foundQuestion: QuizQuestion? if let questions = questions { if number < questions.count { let question = questions[number] as! QuizQuestion foundQuestion = question } } return foundQuestion } // duplicate this quiz collection, but make every answer false/empty // this method uses some unsafe ! unwraps - but if there were any chance a collection was not valid things would have broken long before this point func duplicateWithoutAnswers(moc: NSManagedObjectContext) throws -> QuizCollection? { let newCollection = QuizCollection.createWithTitle(text!, inContext: moc) for question in questions! { // duplicate every question let thisQuestion = question as! QuizQuestion let newQuestion = QuizQuestion.createWithText(text: thisQuestion.text!, inContext: moc) newCollection.addToQuestions(newQuestion) for answer in thisQuestion.answers! { // duplicate every answer let thisAnswer = answer as! QuizAnswer let newAnswer = QuizAnswer.createWithText(text: thisAnswer.text!, isCorrect: "F", inContext: moc) newQuestion.addToAnswers(newAnswer) } } // write the new QuizCollection to the managed object context moc.insert(newCollection) try moc.save() // return the copy return newCollection } // a quiz is graded if every question has answers that can produce a grade - that is, if it has multiple choice // questions that can be automatically checked, and if any text answer has a grade recorded. The actual grade is // not recorded only the fact that a grade is possible. (Because a teacher could revise the correct answer and then // grades should be recalculated) func isGradeable() -> Bool { var gradeable = true; for question in questions! { let thisQuestion = question as! QuizQuestion // for now it is just assumed that since student quizzes come directly from teacher quizzes they always have // multiple choice answers that can be checked against teacher answers. Only text answers matter here. if thisQuestion.answers!.count == 0 { // default value is -1, so if a grade has not been assigned it is < 0 if thisQuestion.assignedPercentage < 0 { // not assigned a grade - can't be graded gradeable = false break } } } return gradeable } // attempt to grade this quiz against a supplied quiz. // for each multiple choice question, if the supplied quiz has answers that match that question is correct. // for each textual answer (no multiple choice answers) check for a teacher grade. // If all answers can be checked in this way add the marks and calculate a percentage which can be returned. // If a question is unanswered (i.e. teacher has not graded the text answer) return nil. // // one big assumption here is that every question is worth the same, proportionally. // value returned is grade out of 100. func gradeAgainst(teacherQuiz: QuizCollection) throws -> Int? { var cumulativeScore: Int = 0 var questionCount: Int = 0 if isGradeable() == false { return nil } let numberOfQuestions = questions!.count for questionIndex in 0..<numberOfQuestions { let question = questions![questionIndex] as! QuizQuestion let teacherQuestion = teacherQuiz.questions![questionIndex] as! QuizQuestion let numberOfAnswers = question.answers!.count if numberOfAnswers == 0 { // award points assigned by teacher for this text question cumulativeScore += Int(question.assignedPercentage) } else { var thisQuestionScore = 100 for answerIndex in 0..<numberOfAnswers { let answer = question.answers![answerIndex] as! QuizAnswer let teacherAnswer = teacherQuestion.answers![answerIndex] as! QuizAnswer if answer.isCorrect != teacherAnswer.isCorrect { thisQuestionScore = 0 } } cumulativeScore += thisQuestionScore } questionCount += 1 } // then the final grade is the average - rounding here (dividing using Int) is intentional let grade = cumulativeScore / questionCount return grade } }
bsd-3-clause
e8bdf524b6e7569c2de263d3ab8d5b8d
34.77957
149
0.704583
4.959016
false
false
false
false
ImperialCollegeDocWebappGroup/webappProject
webapp/LoginVCViewController.swift
1
6081
// // LoginVCViewController.swift // webapp // // Created by Shan, Jinyi on 25/05/2015. // Copyright (c) 2015 Shan, Jinyi. All rights reserved. // import UIKit class LoginVCViewController: UIViewController { @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signinTapped(sender: UIButton) { // Authentication Code var username:NSString = txtUsername.text var password:NSString = txtPassword.text if ( username.isEqualToString("") || password.isEqualToString("") ) { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Please enter Username and Password" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } else { var post:NSString = "username=\(username)&password=\(password)" NSLog("PostData: %@",post); var url:NSURL = NSURL(string: "https://dipinkrishna.com/jsonlogin2.php")! var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! var postLength:NSString = String( postData.length ) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError) if ( urlData != nil ) { let res = response as! NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary let success:NSInteger = jsonData.valueForKey("success") as! NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Login SUCCESS"); var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() prefs.setObject(username, forKey: "USERNAME") prefs.setInteger(1, forKey: "ISLOGGEDIN") prefs.synchronize() self.performSegueWithIdentifier("goto_home", sender: self) //self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" } var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = error_msg as String alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.view.endEditing(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. } */ }
gpl-3.0
65006198e19b0ad9e75b11fb5f001602
38.487013
177
0.515869
6.230533
false
false
false
false
plenprojectcompany/plen-Scenography_iOS
PLENConnect/Connect/Entities/PlenProgram.swift
1
387
// // PlenProgram.swift // Scenography // // Created by PLEN Project on 2016/03/09. // Copyright © 2016年 PLEN Project. All rights reserved. // import Foundation struct PlenProgram: Equatable { var sequence: [PlenFunction] static let Empty = PlenProgram(sequence: []) } func ==(lhs: PlenProgram, rhs: PlenProgram) -> Bool { return lhs.sequence == rhs.sequence }
mit
c5bbee6fd0ac083665791f588fddc50c
19.263158
56
0.679688
3.490909
false
false
false
false
wjk930726/Nexus
Nexus/Application/Controller/MainViewController.swift
1
5709
// // MainViewController.swift // Nexus // // Created by 王靖凯 on 2017/3/18. // Copyright © 2017年 王靖凯. All rights reserved. // import Cocoa class MainViewController: NSViewController { @IBOutlet var parserButton: NSButton! @IBOutlet var parserView: DragDropView! @IBOutlet var importView: DropDragView! fileprivate var isParsing: Bool = false fileprivate var isImporting: Bool = false fileprivate var xmls: [String] = [] fileprivate var txts: [String] = [] fileprivate var flag: Int = 0 fileprivate var mark: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do view setup here. setup() } } extension MainViewController { fileprivate func setup() { parserView.getDraggingFilePath = { (files: [String]) in self.displayFileName(files: files, isParser: true) } importView.getDraggingFilePath = { (files: [String]) in self.displayFileName(files: files, isParser: false) } } } extension MainViewController { fileprivate func importTXT() { mark = 0 DispatchQueue.global().async { if self.txts.count > 0, self.xmls.count > 0 { for txt in self.txts { let name = (txt as NSString).lastPathComponent let range: Range = name.range(of: ".txt")! let tf = name.substring(to: range.lowerBound) for xml in self.xmls { let name = (xml as NSString).lastPathComponent let range: Range = name.range(of: ".xml")! let xf = name.substring(to: range.lowerBound) if tf == xf { OperationQueue().addOperation { let editor = TXTEditor() editor.importIsFinished = { self.mark += 1 if self.mark == self.txts.count { self.isImporting = false } } editor.importTXT(filePath: txt, xmlPath: xml) } } } } } else { NSAlert.alertModal(messageText: "need xml and txt!", informativeText: "both are indispensable", firstButtonTitle: "ok", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil) } } } fileprivate func parseXML() { flag = 0 DispatchQueue.global().async { if self.xmls.count > 0 { for xml in self.xmls { OperationQueue().addOperation { let parser = XMLParserTool() parser.parseIsFinished = { self.flag += 1 if self.flag == self.xmls.count { self.isParsing = false DispatchQueue.main.async { NSAlert.alertModal(messageText: "parser", informativeText: "parser is finished", firstButtonTitle: "done", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil) } } } parser.parse(filePath: xml) } } } } } fileprivate func displayFileName(files: [String], isParser: Bool) { if isParser { xmls = [] for file in files { if file.hasSuffix(".xml") { xmls.append(file) } if xmls.count > 0 { var names: String = "" for name in xmls { let nsString: NSString = name as NSString names.append(nsString.lastPathComponent) names.append("\n") } parserView.fileNamesField.stringValue = names parserView.fileNamesField.isHidden = false } else { importView.fileNamesField.isHidden = false parserView.fileNamesField.stringValue = "仅支持xml文档" } } } else { txts = [] for file in files { if file.hasSuffix(".txt") { txts.append(file) } if txts.count > 0 { var names: String = "" for name in txts { let nsString: NSString = name as NSString names.append(nsString.lastPathComponent) names.append("\n") } importView.fileNamesField.stringValue = names importView.fileNamesField.isHidden = false } else { importView.fileNamesField.isHidden = false importView.fileNamesField.stringValue = "仅支持txt文档" } } } } } // MARK: - parserButtonAction extension MainViewController { @IBAction func startParser(_: NSButton) { if isParsing == false { parseXML() isParsing = true } } @IBAction func improtAction(_: NSButton) { importTXT() } }
mit
a21c096101f1b5db904c0826385368e1
35.371795
262
0.471977
5.562745
false
false
false
false
supertommy/yahoo-weather-ios-watchkit-swift
weather/WeatherData.swift
1
3230
// // WeatherData.swift // weather // // Created by Tommy Leung on 3/14/15. // Copyright (c) 2015 Tommy Leung. All rights reserved. // import Foundation public class WeatherData { public enum State { case UNINITIALIZED, LOADING, READY } public typealias OnUpdatedCallback = (data: WeatherData) -> Void private var _state: State public var state: State { return _state } public var name: String { if let s = _name { return s } return "" } public var temperature: Int { if let t = _temperature { return t } return -1 } public var unit: String { if let u = _unit { return u } return "F" } public var city: String { if let c = _city { return c } return "" } public var region: String { if let r = _region { return r } return "" } private var _location: String private var _name: String? private var _temperature: Int? private var _unit: String? private var _city: String? private var _region: String? private var onUpdatedCallbacks: [OnUpdatedCallback] init(location: String) { _state = State.UNINITIALIZED _location = location self.onUpdatedCallbacks = [] update() } public func update() -> WeatherData { if (self.state == State.LOADING) { return self } self._state = State.LOADING let query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"\(_location)\")" Craft.promise { (resolve: (value: Value) -> (), reject: (value: Value) -> ()) -> () in let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue, { let result = JSON(YQL.query(query)) dispatch_sync(dispatch_get_main_queue(), { let response = result["query"]["results"]["channel"] self._name = response["title"].string self._temperature = response["item"]["condition"]["temp"].intValue self._unit = response["unit"]["temperature"].string self._city = response["location"]["city"].string self._region = response["location"]["region"].string self._state = State.READY for cb in self.onUpdatedCallbacks { cb(data: self) } self.onUpdatedCallbacks.removeAll(keepCapacity: true) }) }) } return self } public func then(resolve: OnUpdatedCallback) { self.onUpdatedCallbacks.append(resolve); } }
mit
53d4a4ac443e80cbeb77f9785a245325
22.933333
129
0.469969
5.070644
false
false
false
false
danwood/Resolutionary
Sources/ResolutionController.swift
1
13618
/* Board → Board Current Version ID Author → Person CoAuthors (free form text; author responsible for crediting; allows non users to chime in and get credit) Notes (free-form, introduction to resolution, why written, requests for improvement, etc.) CreationTimeStamp */ import StORM import PostgresStORM import Foundation import PerfectHTTP import PerfectMustache import PerfectHTTPServer import PerfectWebSockets import PerfectMarkdown /// server port to start with let PORT = 7777 /// web socket protocol let PROTOCOL = "editor" /// WebSocket Event Handler public class EditorHandler: WebSocketSessionHandler { public let socketProtocol : String? = PROTOCOL let resolution : Resolution let resolutionVersion : ResolutionVersion init(_ resolution: Resolution, version: ResolutionVersion) { self.resolution = resolution self.resolutionVersion = version } // This function is called by the WebSocketHandler once the connection has been established. public func handleSession(request: HTTPRequest, socket: WebSocket) { socket.readStringMessage { input, _, _ in guard let nameAndMarkdown = input else { socket.close() return }//end guard let scanner = Scanner(string: nameAndMarkdown) var inputName: NSString? = "" let ignore = scanner.scanString("#", into:nil) if scanner.scanUpToCharacters(from:NSCharacterSet.newlines, into:&inputName), let inputName = inputName as String? { scanner.scanCharacters(from:NSCharacterSet.newlines, into:nil) let index = scanner.string.index(scanner.string.startIndex, offsetBy: scanner.scanLocation+1) let inputValue = scanner.string.substring(from: index) var toSave : PostgresStORM = self.resolution; // Is there some way to dynamically set setValue forKey ? For now just do brute force switch(inputName) { case "publicNotesMarkdown": self.resolution.publicNotesMarkdown = inputValue case "privateNotesMarkdown": self.resolution.privateNotesMarkdown = inputValue case "title": self.resolutionVersion.title = inputValue toSave = self.resolutionVersion; case "textMarkdown": self.resolutionVersion.textMarkdown = inputValue toSave = self.resolutionVersion; case "coauthors": self.resolutionVersion.coauthors = inputValue toSave = self.resolutionVersion; case "resolution_status": switch(inputValue) { case "unlisted":self.resolution.status = ResolutionStatus.unlisted case "listed": self.resolution.status = ResolutionStatus.listed case "finished":self.resolution.status = ResolutionStatus.finished case "hidden": self.resolution.status = ResolutionStatus.hidden default: self.resolution.status = ResolutionStatus.hidden // in case of a weird input } default: print("NOT HANDLED: ##### Set \(inputName) of \(self.resolution) to \(inputValue)") } if (!ignore) { do { try toSave.save() // HACK -- SPECIAL CASE OF TWO THINGS BEING SAVED. if inputName == "title" { self.resolution.currentTitle = inputValue try self.resolution.save() } } catch { print("Unable to save resolution") } } if inputName.hasSuffix("Markdown") { // convert the input from markdown to HTML let output = inputName + "Rendered" + "\n" + (inputValue.markdownToHTML ?? "") // sent it back to the request socket.sendStringMessage(string: output, final: true) { self.handleSession(request: request, socket: socket) }//end send } } }//end readStringMessage }//end handleSession }//end handler public class ResolutionController { // Defines and returns the Web Authentication routes public static func makeRoutes() -> Routes { // Add old-fashioned? route style var routes = Routes() routes.add(method: .post, uri: "/newresolution", handler: ResolutionController.newResolutionHandlerPOST) routes.add(method: .post, uri: "/newversion/{c}", handler: ResolutionController.newResolutionVersionHandlerPOST) routes.add(method: .get, uri: "/resolutions", handler: ResolutionController.resolutionsHandlerGET) routes.add(method: .get, uri: "/resolution/{c}", handler: ResolutionController.viewResolutionHandlerGET) routes.add(method: .get, uri: "/editresolution/{c}", handler: ResolutionController.editResolutionHandlerGET) routes.add(method: .get, uri: "/editresolution/{c}/{version}", handler: ResolutionController.editResolutionHandlerGET) // Add the endpoint for the WebSocket example system routes.add(method: .get, uri: "/editor/{c}", handler: { request, response in // To add a WebSocket service, set the handler to WebSocketHandler. // Provide your closure which will return your service handler. WebSocketHandler(handlerProducer: { (request: HTTPRequest, protocols: [String]) -> WebSocketSessionHandler? in // Check to make sure the client is requesting our service. guard protocols.contains("editor") else { return nil } guard let codedIdString = request.urlVariables["c"], let id = Resolution.encodedIdToId(codedIdString) else { return nil } do { let resolution = try Resolution.getResolution(matchingId: id) let resolutionVersion = try ResolutionVersion.getLastResolutionVersion(matchingResolutionId: id) guard resolutionVersion.id > 0 else { return nil } // Return our service handler. return EditorHandler(resolution, version:resolutionVersion) } catch { return nil } }).handleRequest(request: request, response: response) }) return routes } /// Handles the POST request for a "newresolution" route. Creates a new empty record. We will be saving to the record in real time, no submit button. Websockets. open static func newResolutionHandlerPOST(request: HTTPRequest, _ response: HTTPResponse) { do { // Create empty resolution let resolution = Resolution() resolution.creationTimeStamp = Date() try resolution.save { id in resolution.id = id as! Int } // Create empty resolution version that corresponds to this resolution let resolutionVersion = ResolutionVersion() resolutionVersion.creationTimeStamp = Date() resolutionVersion.resolutionID = resolution.id resolutionVersion.version = 1; // always start with version 1 try resolutionVersion.save { id in resolutionVersion.id = id as! Int } response.redirect(path: "/editresolution/" + resolution.encodedId() ) } catch { response.render(template: "/editresolution", context: ["flash": "An unknown error occurred."]) } } /// Handles the POST request for a "newversion" route. open static func newResolutionVersionHandlerPOST(request: HTTPRequest, _ response: HTTPResponse) { do { // Find the last version, which we will be cloning. guard let codedIdString = request.urlVariables["c"], let id = Resolution.encodedIdToId(codedIdString) else { response.completed(status: .badRequest) return } let lastVersion = try ResolutionVersion.getLastResolutionVersion(matchingResolutionId: id) guard lastVersion.id > 0 else { throw StORMError.noRecordFound } if !(try ResolutionVersion.canLastVersionBePublished(matchingResolutionId: id)) { response.render(template: "/editresolution", context: ["flash": "The resolution has not been changed, so it can't be published."]) } // Create new resolution version that is a copy of the last one. let newVersion = ResolutionVersion() newVersion.creationTimeStamp = Date() newVersion.resolutionID = id newVersion.isPublished = false; newVersion.version = lastVersion.version + 1; newVersion.title = lastVersion.title newVersion.coauthors = lastVersion.coauthors newVersion.textMarkdown = lastVersion.textMarkdown try newVersion.save { id in newVersion.id = id as! Int } // "Freeze" the current version lastVersion.isPublished = true; try lastVersion.save() response.redirect(path: "/editresolution/" + codedIdString ) // use same id string passed in } catch { response.render(template: "/editresolution", context: ["flash": "An unknown error occurred."]) } } open static func viewResolutionHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { do { guard let codedIdString = request.urlVariables["c"], let id = Resolution.encodedIdToId(codedIdString) else { response.completed(status: .badRequest) return } let resolution = try Resolution.getResolution(matchingId: id) var values = MustacheEvaluationContext.MapType() values["resolution"] = Resolution.resolutionsToDictionary( resolutions:[ resolution ], sanitizedExceptAuthorID:0 ) // Get all resolution versions too let resolutionVersions = try ResolutionVersion.getResolutionVersions(matchingResolutionId: id) values["resolution_versions"] = ResolutionVersion.resolutionVersionsToDictionary( resolutionVersions ) // Get latest version, or specified version if let versionString = request.urlVariables["version"] { if let version = Int(versionString) { // Get the current resolution version in context. let resolutionVersion = try ResolutionVersion.getResolutionVersion(matchingResolutionId:id, matchingVersion: version) guard resolutionVersion.id > 0 else { throw StORMError.noRecordFound } values["resolution_version"] = ResolutionVersion.resolutionVersionsToDictionary( [ resolutionVersion ] ) } else { response.completed(status: .badRequest) return } } // If we couldn't parse, or find given ID, get the lastest version. if (values["resolution_version"] == nil) { // Get the current resolution version in context let resolutionVersion = try ResolutionVersion.getLastResolutionVersion(matchingResolutionId: id) guard resolutionVersion.id > 0 else { throw StORMError.noRecordFound } values["resolution_version"] = ResolutionVersion.resolutionVersionsToDictionary( [ resolutionVersion ] ) } response.render(template: "resolution", context: values) } catch { response.render(template: "resolution", context: ["flash": "An unknown error occurred."]) } } open static func resolutionsHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { do { /* Maybe want to separate lists: Resolutions I can SEE, and resolutions I authored. Maybe I can store the latest title in the Resolution database for easy access, but keep the versioned title as well so we can see the evolution of it! */ var values = MustacheEvaluationContext.MapType() let myResolutions = try Resolution.getResolutions(matchingAuthorId:0) values["my_resolutions"] = Resolution.resolutionsToDictionary( myResolutions ) let publicResolutions = try Resolution.getPublicResolutions() values["public_resolutions"] = Resolution.resolutionsToDictionary( resolutions:publicResolutions, sanitizedExceptAuthorID:0 ) response.render(template: "resolutions", context: values) } catch { response.render(template: "resolutions", context: ["flash": "An unknown error occurred."]) } } /// Handles the POST request for a "newresolution" route. Creates a new empty record. We will be saving to the record in real time, no submit button. Websockets. open static func editResolutionHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { do { guard let codedIdString = request.urlVariables["c"], let id = Resolution.encodedIdToId(codedIdString) else { response.completed(status: .badRequest) return } let resolution = try Resolution.getResolution(matchingId: id) var values = MustacheEvaluationContext.MapType() values["resolution"] = Resolution.resolutionsToDictionary( [ resolution ] ) // Get all resolution versions too let resolutionVersions = try ResolutionVersion.getResolutionVersions(matchingResolutionId: id) values["resolution_versions"] = ResolutionVersion.resolutionVersionsToDictionary( resolutionVersions ) // Get latest version, or specified version if let versionString = request.urlVariables["version"] { if let version = Int(versionString) { // Get the current resolution version in context. let resolutionVersion = try ResolutionVersion.getResolutionVersion(matchingResolutionId:id, matchingVersion: version) guard resolutionVersion.id > 0 else { throw StORMError.noRecordFound } values["resolution_version"] = ResolutionVersion.resolutionVersionsToDictionary( [ resolutionVersion ] ) } else { response.completed(status: .badRequest) return } } // If we couldn't parse, or find given ID, get the lastest version. if (values["resolution_version"] == nil) { // Get the current resolution version in context let resolutionVersion = try ResolutionVersion.getLastResolutionVersion(matchingResolutionId: id) guard resolutionVersion.id > 0 else { throw StORMError.noRecordFound } values["resolution_version"] = ResolutionVersion.resolutionVersionsToDictionary( [ resolutionVersion ] ) } response.render(template: "editresolution", context: values) } catch { response.render(template: "editresolution", context: ["flash": "An unknown error occurred."]) } } }
apache-2.0
6483bcedc9ff4cd96f52dc1b807ad869
30.153318
165
0.711547
4.397287
false
false
false
false
ovyhlidal/Billingo
Billingo/StatisticGroupViewController.swift
1
2664
// // StatisticGroupViewController.swift // Billingo // // Created by Matej Minarik on 07/06/16. // Copyright © 2016 MU. All rights reserved. // import Foundation class StatisticGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //@IBOutlet weak var groupName: UILabel! //moze byt nemusi byt, mohlo by byt pekne niekde hore vidiet v akej som skupine @IBOutlet weak var groupName: UINavigationItem! var expense: Expense? var name: String? var members: Member? var group: Group? let reuseIdentifier = "statisticCell" @IBOutlet weak var tableView: UITableView! func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (group?.members.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StatisticGroupTableViewCell // Configure the cell cell.memberName.text = group?.members[indexPath.item].memberName var numPayments = 0 var balanceOfPayments = 0.0 for expense in (group?.expenses)! { if expense.expenseCreatorID == group?.members[indexPath.item].memberID { numPayments += 1 for payment in expense.payments { if payment.userID != group?.members[indexPath.item].memberID{ balanceOfPayments += payment.cost } } }else{ for payment in expense.payments { if payment.userID == group?.members[indexPath.item].memberID{ balanceOfPayments -= payment.cost } } } } let balanceOfPaymentsAdapted = String(format: "%.2f", balanceOfPayments) cell.memberCredit.text = "Amount: \(balanceOfPaymentsAdapted)Kč" if balanceOfPayments < 0 { cell.memberCredit.textColor = UIColor.redColor() }else{ cell.memberCredit.textColor = UIColor.blackColor() } cell.memberCreatedPayments.text = "Payed for: \(numPayments)" return cell } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self groupName.title = group?.name self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None } }
mit
151212d2b979175c3072f3311322e024
34.986486
136
0.627348
5.119231
false
false
false
false
RemarkableIO/Deferred
Deferred/Deferred.swift
1
5048
// // Deferred.swift // Deferred // // Created by Giles Van Gruisen on 3/2/15. // Copyright (c) 2015 Remarkable.io. All rights reserved. // import Foundation internal struct Then<T> { let onFulfilled: T -> () let onRejected: NSError -> () } public final class Deferred<T> { typealias ThenBlock = Then<T> private typealias WrappedFulfilledBlock = T -> () public typealias RejectedBlock = NSError -> () /** If `value` is filled then the promise was resolved. */ private var value: T? /** If `error` is filled then the promise was rejected. */ private var error: NSError? /** `ThenBlock` objects whose onFulfilled or onRejected will be called upon `resolve(value: T)` or `reject(error: NSError)`, respectively. */ internal var pending: [ThenBlock] = [ThenBlock]() /** Returns an empty (unresolved, unrejected) promise. */ public required init() { } // Shouldn't be necessary? /** Returns a promise resolved with the given `value`. */ public convenience init(value: T) { self.init() self.resolve(value) } /** Returns a promise rejected with the given `error`. */ public convenience init(error: NSError) { self.init() self.reject(error) } /** Returns a collective promise that resolves with a collection of T when all resolve */ public class func combine(promises: [Deferred<T>]) -> Deferred<[T]> { let combined = Deferred<[T]>() var collection = [T]() for deferred in promises { deferred.then({ value -> Void in collection += [value] if collection.count == promises.count { combined.resolve(collection) } }) } return combined } /** Appends to `pending` a `Then<T>` object containing the given `onFulfilled` and (optional) `onRejected` blocks, or calls onFulfilled/onRejected if the promise is already fulfilled or rejected, respectively. */ public func then<U>(onFulfilled: (T) -> U, _ onRejected: RejectedBlock = { error in }) -> Deferred<U> { // Chained promise to be returned let deferred = Deferred<U>() // Curry onFulfilled and onRejected before appending ThenBlock to `pending` let _onFulfilled = wrapFulfilledBlock(deferred, onFulfilled: onFulfilled) let _onRejected = wrapRejectedBlock(deferred, onRejected: onRejected) // Check promise status if let value = value { // Fulfilled, call onFulfilled immediately _onFulfilled(value) } else if let error = error { // Rejected, call onRejected immediately _onRejected(error) } else { // Pending, add ThenBlock pending.append(ThenBlock(onFulfilled: _onFulfilled, onRejected: _onRejected)) } return deferred } public func then<U>(onFulfilled: (T) -> Deferred<U>, _ onRejected: RejectedBlock = { error in }) -> Deferred<U> { // Proxy since we won't have a Deferred<U> until self resolves let proxy = Deferred<U>() // When self resolves, add then block to resulting Deferred<U> let _onFulfilled: T -> () = { value in let next = onFulfilled(value) next.then({ value in proxy.resolve(value) }, { error in proxy.reject(error) }) } // When self rejects, reject proxy with error let _onRejected: NSError -> () = { error in proxy.reject(error) } then(_onFulfilled, _onRejected) return proxy } /** Resolve the promise, clearing `pending` after calling each `onFulfilled` block with the given `value`. */ public func resolve(value: T) { // Promise fulfilled, set value self.value = value // Loop through ThenBlocks, calling each onFulfilled with value for thenBlock in pending { thenBlock.onFulfilled(value) } // Clear pending now that promise has been fulfilled self.pending = [ThenBlock]() } /** Rejects the promise, clearing `pending` after calling each `onRejected` block with the given `error`. */ public func reject(error: NSError) { // Promise rejected, set error self.error = error // Loop through ThenBlocks, calling each onRejected with error for thenBlock in pending { thenBlock.onRejected(error) } // Clear pending now that promise has been rejected self.pending = [ThenBlock]() } private func wrapFulfilledBlock<U>(deferred: Deferred<U>, onFulfilled: T -> U) -> WrappedFulfilledBlock { return { val in deferred.resolve(onFulfilled(val)) } } private func wrapRejectedBlock<U>(deferred: Deferred<U>, onRejected: NSError -> ()) -> RejectedBlock { return { err in onRejected(err) deferred.reject(err) } } }
mit
34d7278b851bb5b446467100e761c266
29.780488
216
0.602615
4.704567
false
false
false
false
rabbitmq/rabbitmq-tutorials
swift/tutorial1/tutorial1/ViewController.swift
1
1152
// // ViewController.swift // tutorial1 // // Copyright © 2016 RabbitMQ. All rights reserved. // import UIKit import RMQClient class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.send() self.receive() } func send() { print("Attempting to connect to local RabbitMQ broker") let conn = RMQConnection(delegate: RMQConnectionDelegateLogger()) conn.start() let ch = conn.createChannel() let q = ch.queue("hello") ch.defaultExchange().publish("Hello World!".data(using: .utf8), routingKey: q.name) print("Sent 'Hello World!'") conn.close() } func receive() { print("Attempting to connect to local RabbitMQ broker") let conn = RMQConnection(delegate: RMQConnectionDelegateLogger()) conn.start() let ch = conn.createChannel() let q = ch.queue("hello") print("Waiting for messages.") q.subscribe({(_ message: RMQMessage) -> Void in print("Received \(String(data: message.body, encoding: String.Encoding.utf8)!)") }) } }
apache-2.0
8820c8acadb9dbb6fba0119b233066fa
27.073171
92
0.611642
4.359848
false
false
false
false
AnneBlair/YYGRegular
YYGRegular/YYGText.swift
1
4505
// // YYGText.swift // 24demo // // Created by 区块国际-yin on 17/2/10. // Copyright © 2017年 区块国际-yin. All rights reserved. // import UIKit /// Seting AttributedString /// /// - Parameters: /// - color: 颜色 Arry [[RGB,RGB,RGB],[RGB,RGB,RGB]] /// - content: 内容 Arry ["第一个","第二个"] /// - size: 字体 Arry [size1,size2] /// - Returns: 富文本 public func setAttribute(color: [[Int]],content:[String],size: [CGFloat])-> NSMutableAttributedString { let str = NSMutableAttributedString() for i in 0..<color.count { str.append(NSAttributedString(string: content[i], attributes: [NSForegroundColorAttributeName: UIColor(hex: color[i][0]), NSFontAttributeName:UIFont.systemFont(ofSize: size[i])])) } return str } /// scientific Notation Transition Normal String /// 9.0006e+07 Transition 90,006,000 /// - Parameter f_loat: Input /// - Returns: Output public func inputFOutputS(f_loat: Double) -> String { let numFormat = NumberFormatter() numFormat.numberStyle = NumberFormatter.Style.decimal let num = NSNumber.init(value: f_loat) return numFormat.string(from: num)! } // MARK: - 数字转换成字符串金额 11121.01 -> "11,121.01" 三位一个逗号 extension NSNumber { var dollars: String { let formatter: NumberFormatter = NumberFormatter() var result: String? formatter.numberStyle = NumberFormatter.Style.decimal result = formatter.string(from: self) if result == nil { return "error" } return result! } } extension String { /// 截取第一个到第任意位置 /// /// - Parameter end: 结束的位值 /// - Returns: 截取后的字符串 func stringCut(end: Int) ->String{ printLogDebug(self.characters.count) if !(end < characters.count) { return "截取超出范围" } let sInde = index(startIndex, offsetBy: end) return substring(to: sInde) } /// 截取人任意位置到结束 /// /// - Parameter end: /// - Returns: 截取后的字符串 func stringCutToEnd(star: Int) -> String { if !(star < characters.count) { return "截取超出范围" } let sRang = index(startIndex, offsetBy: star)..<endIndex return substring(with: sRang) } /// 字符串任意位置插入 /// /// - Parameters: /// - content: 插入内容 /// - locat: 插入的位置 /// - Returns: 添加后的字符串 func stringInsert(content: String,locat: Int) -> String { if !(locat < characters.count) { return "截取超出范围" } let str1 = stringCut(end: locat) let str2 = stringCutToEnd(star: locat) return str1 + content + str2 } /// 计算字符串宽高 /// /// - Parameter size: size /// - Returns: CGSize func getStringSzie(size: CGFloat = 10) -> CGSize { let baseFont = UIFont.systemFont(ofSize: size) let size = self.size(attributes: [NSFontAttributeName: baseFont]) let width = ceil(size.width) + 5 let height = ceil(size.height) return CGSize(width: width, height: height) } /// 输入字符串 输出数组 /// e.g "qwert" -> ["q","w","e","r","t"] /// - Returns: ["q","w","e","r","t"] func stringToArr() -> [String] { let num = characters.count if !(num > 0) { return [""] } var arr: [String] = [] for i in 0..<num { let tempStr: String = self[self.index(self.startIndex, offsetBy: i)].description arr.append(tempStr) } return arr } /// 字符串截取 3 6 /// e.g let aaa = "abcdefghijklmnopqrstuvwxyz" -> "cdef" /// - Parameters: /// - start: 开始位置 3 /// - end: 结束位置 6 /// - Returns: 截取后的字符串 "cdef" func startToEnd(start: Int,end: Int) -> String { if !(end < characters.count) || start > end { return "取值范围错误" } var tempStr: String = "" for i in start...end { let temp: String = self[self.index(self.startIndex, offsetBy: i - 1)].description tempStr += temp } return tempStr } /// 字符URL格式化 /// /// - Returns: 格式化的 url func stringEncoding() -> String { let url = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) return url! } }
mit
efc136c313594f727aa82131b4ef5a06
29.072464
187
0.580482
3.735374
false
false
false
false
mleiv/UIHeaderTabs
UIHeaderTabsExample/UIHeaderTabsExample/List Groups/ListGroupsController.swift
1
2701
// // ListGroupsController.swift // // Created by Emily Ivie on 9/22/15. // Copyright © 2015 urdnot. // Licensed under The MIT License // For full copyright and license information, please see http://opensource.org/licenses/MIT // Redistributions of files must retain the above copyright notice. import UIKit class ListGroupsController: UIViewController, TabGroupsControllable { var pageLoaded = false override func viewDidLoad() { super.viewDidLoad() setupTabs() pageLoaded = true } // MARK: TabGroupsControllable protocol @IBOutlet weak var tabs: UIHeaderTabs! @IBOutlet weak var tabsContentWrapper: UIView! var tabNames: [String] = ["Friends", "Enemies"] func tabControllersInitializer(tabName: String) -> UIViewController? { let bundle = NSBundle(forClass: self.dynamicType) switch tabName { case "Friends": let controller = UIStoryboard(name: "List", bundle: bundle).instantiateInitialViewController() as? ListController // set some custom values here (mine happen to be trivial): controller?.group = "Friends" return controller case "Enemies": // can use any controller/storyboard here (mine happen to be the same): let controller = UIStoryboard(name: "List", bundle: bundle).instantiateInitialViewController() as? ListController controller?.group = "Enemies" return controller default: return nil } } // only used internally: var tabsPageViewController: UIPageViewController? var tabControllers: [String: UIViewController] = [:] var tabCurrentIndex: Int = 0 func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { return handleTabsPageViewController(pageViewController, viewControllerBeforeViewController: viewController) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { return handleTabsPageViewController(pageViewController, viewControllerAfterViewController: viewController) } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { handleTabsPageViewController(pageViewController, didFinishAnimating: finished, previousViewControllers: previousViewControllers, transitionCompleted: completed) } }
mit
1fc5eb5fc135d1ade6f97c1008d1c1d0
44
188
0.714444
5.960265
false
false
false
false
CodaFi/PersistentStructure.swift
Persistent/QueueSeq.swift
1
875
// // QueueSeq.swift // Persistent // // Created by Robert Widmann on 12/22/15. // Copyright © 2015 TypeLift. All rights reserved. // class QueueSeq: AbstractSeq { private var _f: ISeq private var _rseq: ISeq init(f: ISeq, rev rseq: ISeq) { _f = f _rseq = rseq super.init() } init(meta: IPersistentMap?, first f: ISeq, rev rseq: ISeq) { _f = f _rseq = rseq super.init(meta: meta) } override var first : AnyObject? { return _f.first } override var next : ISeq { var f1: ISeq = _f.next var r1: ISeq = _rseq if f1.count == 0 { if _rseq.count == 0 { return EmptySeq() } f1 = _rseq r1 = EmptySeq() } return QueueSeq(f: f1, rev: r1) } override var count : Int { return Utils.count(_f) + Utils.count(_rseq) } func withMeta(meta: IPersistentMap?) -> ISeq? { return QueueSeq(meta: meta, first: _f, rev: _rseq) } }
mit
1dccf140b13b376c7c4fb972ae72a8fb
16.836735
61
0.60984
2.616766
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Objects/BuildPhase/PBXBuildPhase.swift
1
6378
import Foundation /// An absctract class for all the build phase objects public class PBXBuildPhase: PBXContainerItem { /// Default build action mask. public static let defaultBuildActionMask: UInt = 2_147_483_647 /// Element build action mask. public var buildActionMask: UInt /// References to build files. var fileReferences: [PBXObjectReference]? /// Build files. public var files: [PBXBuildFile]? { get { fileReferences?.objects() } set { newValue?.forEach { $0.buildPhase = self } fileReferences = newValue?.references() } } /// Paths to the input file lists. /// Note: Introduced in Xcode 10 public var inputFileListPaths: [String]? /// Paths to the output file lists. /// Note: Introduced in Xcode 10 public var outputFileListPaths: [String]? /// Element run only for deployment post processing value. public var runOnlyForDeploymentPostprocessing: Bool /// The build phase type of the build phase public var buildPhase: BuildPhase { fatalError("This property must be overriden") } /// Initializes the build phase. /// /// - Parameters: /// - files: Build files. /// - inputFileListPaths: Input file lists paths. /// - outputFileListPaths: Input file list paths. /// - buildActionMask: Build action mask. /// - runOnlyForDeploymentPostprocessing: When true, it runs the build phase only for deployment post processing. public init(files: [PBXBuildFile] = [], inputFileListPaths: [String]? = nil, outputFileListPaths: [String]? = nil, buildActionMask: UInt = defaultBuildActionMask, runOnlyForDeploymentPostprocessing: Bool = false) { fileReferences = files.references() self.inputFileListPaths = inputFileListPaths self.outputFileListPaths = outputFileListPaths self.buildActionMask = buildActionMask self.runOnlyForDeploymentPostprocessing = runOnlyForDeploymentPostprocessing super.init() files.forEach { $0.buildPhase = self } } // MARK: - Decodable fileprivate enum CodingKeys: String, CodingKey { case buildActionMask case files case runOnlyForDeploymentPostprocessing case inputFileListPaths case outputFileListPaths } public required init(from decoder: Decoder) throws { let objects = decoder.context.objects let objectReferenceRepository = decoder.context.objectReferenceRepository let container = try decoder.container(keyedBy: CodingKeys.self) buildActionMask = try container.decodeIntIfPresent(.buildActionMask) ?? PBXBuildPhase.defaultBuildActionMask let fileReferences: [String]? = try container.decodeIfPresent(.files) self.fileReferences = fileReferences?.map { objectReferenceRepository.getOrCreate(reference: $0, objects: objects) } inputFileListPaths = try container.decodeIfPresent(.inputFileListPaths) outputFileListPaths = try container.decodeIfPresent(.outputFileListPaths) runOnlyForDeploymentPostprocessing = try container.decodeIntBool(.runOnlyForDeploymentPostprocessing) try super.init(from: decoder) } override func plistValues(proj: PBXProj, reference: String) throws -> [CommentedString: PlistValue] { var dictionary = try super.plistValues(proj: proj, reference: reference) dictionary["buildActionMask"] = .string(CommentedString("\(buildActionMask)")) if let fileReferences = fileReferences { let files: PlistValue = .array(fileReferences.map { fileReference in let buildFile: PBXBuildFile? = fileReference.getObject() let name = buildFile.flatMap { try? $0.fileName() } ?? nil let fileName: String = name ?? "(null)" let type = self.name() let comment = (type.flatMap { "\(fileName) in \($0)" }) ?? name return .string(CommentedString(fileReference.value, comment: comment)) }) dictionary["files"] = files } if let inputFileListPaths = inputFileListPaths { dictionary["inputFileListPaths"] = .array(inputFileListPaths.map { .string(CommentedString($0)) }) } if let outputFileListPaths = outputFileListPaths { dictionary["outputFileListPaths"] = .array(outputFileListPaths.map { .string(CommentedString($0)) }) } dictionary["runOnlyForDeploymentPostprocessing"] = .string(CommentedString("\(runOnlyForDeploymentPostprocessing.int)")) return dictionary } } // MARK: - Helpers public extension PBXBuildPhase { /// Adds a file to a build phase, creating a proxy build file that points to the given file element. /// /// - Parameter file: file element to be added to the build phase. /// - Returns: proxy build file. /// - Throws: an error if the file cannot be added. func add(file: PBXFileElement) throws -> PBXBuildFile { if let existing = files?.first(where: { $0.fileReference == file.reference }) { return existing } let projectObjects = try objects() let buildFile = PBXBuildFile(file: file) projectObjects.add(object: buildFile) files?.append(buildFile) return buildFile } } // MARK: - Utils public extension PBXBuildPhase { /// Returns the build phase type. /// /// - Returns: build phase type. func type() -> BuildPhase? { buildPhase } /// Build phase name. /// /// - Returns: build phase name. func name() -> String? { if self is PBXSourcesBuildPhase { return "Sources" } else if self is PBXFrameworksBuildPhase { return "Frameworks" } else if self is PBXResourcesBuildPhase { return "Resources" } else if let phase = self as? PBXCopyFilesBuildPhase { return phase.name ?? "CopyFiles" } else if let phase = self as? PBXShellScriptBuildPhase { return phase.name ?? "ShellScript" } else if self is PBXHeadersBuildPhase { return "Headers" } else if self is PBXRezBuildPhase { return "Rez" } return nil } }
mit
5055191d2da13d21cb810727d0fa67eb
38.37037
128
0.647695
5.368687
false
false
false
false
actorapp/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/CocoaNetworkRuntime.swift
2
4118
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation class CocoaNetworkRuntime : ARManagedNetworkProvider { override init() { super.init(factory: CocoaTcpConnectionFactory()) } } class CocoaTcpConnectionFactory: NSObject, ARAsyncConnectionFactory { func createConnection(withConnectionId connectionId: jint, with endpoint: ARConnectionEndpoint!, with connectionInterface: ARAsyncConnectionInterface!) -> ARAsyncConnection! { return CocoaTcpConnection(connectionId: Int(connectionId), endpoint: endpoint, connection: connectionInterface) } } class CocoaTcpConnection: ARAsyncConnection, GCDAsyncSocketDelegate { static let queue = DispatchQueue(label: "im.actor.network", attributes: []) let READ_HEADER = 1 let READ_BODY = 2 var TAG: String! var gcdSocket:GCDAsyncSocket? = nil var header: Data? init(connectionId: Int, endpoint: ARConnectionEndpoint!, connection: ARAsyncConnectionInterface!) { super.init(endpoint: endpoint, with: connection) TAG = "🎍ConnectionTcp#\(connectionId)" } override func doConnect() { let endpoint = getEndpoint() gcdSocket = GCDAsyncSocket(delegate: self, delegateQueue: CocoaTcpConnection.queue) gcdSocket?.isIPv4PreferredOverIPv6 = false do { try self.gcdSocket!.connect(toHost: (endpoint?.host!)!, onPort: UInt16((endpoint?.port)!), withTimeout: Double(ARManagedConnection_CONNECTION_TIMEOUT) / 1000.0) } catch _ { } } // Affer successful connection func socket(_ sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) { if (self.getEndpoint().type == ARConnectionEndpoint.type_TCP_TLS()) { // NSLog("\(TAG) Starring TLS Session...") sock.startTLS(nil) } else { startConnection() } } // After TLS successful func socketDidSecure(_ sock: GCDAsyncSocket!) { // NSLog("\(TAG) TLS Session started...") startConnection() } func startConnection() { gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER) onConnected() } // On connection closed func socketDidDisconnect(_ sock: GCDAsyncSocket!, withError err: Error?) { // NSLog("\(TAG) Connection closed...") onClosed() } func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { if (tag == READ_HEADER) { // NSLog("\(TAG) Header received") self.header = data data.readUInt32(0) // IGNORE: package id let size = data.readUInt32(5) gcdSocket?.readData(toLength: UInt(size + 4), withTimeout: -1, tag: READ_BODY) } else if (tag == READ_BODY) { // NSLog("\(TAG) Body received") var package = Data() package.append(self.header!) package.append(data) package.readUInt32(0) // IGNORE: package id self.header = nil onReceived(package.toJavaBytes()) gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER) } else { fatalError("Unknown tag in read data") } } override func doClose() { if (gcdSocket != nil) { // NSLog("\(TAG) Closing...") gcdSocket?.disconnect() gcdSocket = nil } } override func doSend(_ data: IOSByteArray!) { gcdSocket?.write(data.toNSData(), withTimeout: -1, tag: 0) } } private extension Data { func readUInt32() -> UInt32 { var raw: UInt32 = 0; (self as NSData).getBytes(&raw, length: 4) return raw.bigEndian } func readUInt32(_ offset: Int) -> UInt32 { var raw: UInt32 = 0; (self as NSData).getBytes(&raw, range: NSMakeRange(offset, 4)) return raw.bigEndian } }
agpl-3.0
d26ec9c58dc18213f108fd0835e3bfa3
31.148438
172
0.586148
4.818501
false
false
false
false
RahulKatariya/RKParallaxEffect
Sources/RKParallaxEffect.swift
1
7515
// // RKParallaxEffect.swift // RKParallaxEffect // // Created by Rahul Katariya on 02/02/15. // Copyright (c) 2015 Rahul Katariya. All rights reserved. // import UIKit open class RKParallaxEffect: NSObject { var tableView: UITableView! var tableHeaderView: UIView? var tableViewTopInset: CGFloat = 0 open var isParallaxEffectEnabled: Bool = false { didSet { if isParallaxEffectEnabled { self.setupTableHeaderView() self.addObservers() } } } //FullScreen Tap var tableHeaderViewIntitalFrame:CGRect! var isFullScreenModeEnabled = false var isAnimating = false var isFullScreen = false var initialContentSize: CGSize! open var isFullScreenTapGestureRecognizerEnabled: Bool = false { didSet { if isFullScreenTapGestureRecognizerEnabled { if !isFullScreenModeEnabled { isFullScreenModeEnabled = true } tableHeaderView?.isUserInteractionEnabled = true tableHeaderView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(RKParallaxEffect.handleTap(_:)))) } } } deinit { removeObservers() } var newFrame: CGRect { get { if isFullScreen { return tableHeaderViewIntitalFrame } else { return CGRect(x: tableView.frame.origin.x, y: -(tableView.frame.size.height-tableViewTopInset), width: tableView.frame.size.width, height: tableView.frame.size.height-tableViewTopInset) } } } //FullScreen Pan open var thresholdValue: CGFloat = 100.0 open var isFullScreenPanGestureRecognizerEnabled: Bool = false { didSet { if isFullScreenPanGestureRecognizerEnabled { if !isFullScreenModeEnabled { isFullScreenModeEnabled = true } if !isParallaxEffectEnabled { isParallaxEffectEnabled = true } tableHeaderView?.isUserInteractionEnabled = true } } } public init(tableView:UITableView) { self.tableView = tableView self.tableHeaderView = tableView.tableHeaderView super.init() } func setupTableHeaderView() { if let thv = tableHeaderView { tableView.tableHeaderView = tableView.tableHeaderView tableView.tableHeaderView = nil tableView.addSubview(thv) thv.clipsToBounds = true var frame = thv.frame frame.origin.y = -(thv.frame.size.height) thv.frame = frame tableHeaderViewIntitalFrame = frame setupTableView() } } func setupTableView() { tableViewTopInset = tableView.contentInset.top var contentInset = tableView.contentInset contentInset.top = tableViewTopInset + tableHeaderViewIntitalFrame.size.height tableView.contentInset = contentInset tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: -(tableHeaderViewIntitalFrame.size.height+tableViewTopInset)), animated:false) } func addObservers() { tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) tableHeaderView?.addObserver(self, forKeyPath: "frame", options: .new, context: nil) } func removeObservers() { tableView.removeObserver(self, forKeyPath: "contentOffset") tableHeaderView?.removeObserver(self, forKeyPath: "frame") } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentOffset" { adjustParallaxEffectOnTableHeaderViewWithContentOffset((change![NSKeyValueChangeKey.newKey]! as AnyObject).cgPointValue) } else if keyPath == "frame" { tableView.layoutIfNeeded() } } func adjustParallaxEffectOnTableHeaderViewWithContentOffset(_ contentOffset:CGPoint) { if let thv = tableHeaderView { let yOffset = -1*(contentOffset.y+tableViewTopInset) if yOffset > 0 { if isParallaxEffectEnabled { thv.frame = CGRect(x: 0, y: -yOffset, width: thv.frame.width, height: yOffset) } if isFullScreenModeEnabled && !isAnimating { if isFullScreenPanGestureRecognizerEnabled { if !isFullScreen && yOffset > tableHeaderViewIntitalFrame.size.height + thresholdValue { tableView.isScrollEnabled = false var frame = tableHeaderViewIntitalFrame frame?.size.height = yOffset thv.frame = frame! tableView.layoutIfNeeded() enterFullScreen() } else if isFullScreen && yOffset < tableView.frame.size.height-tableViewTopInset-thresholdValue { tableView.isScrollEnabled = false var frame = CGRect(x: tableView.frame.origin.x, y: -(tableView.frame.size.height-tableViewTopInset), width: tableView.frame.size.width, height: tableView.frame.size.height-tableViewTopInset) frame.size.height -= thresholdValue thv.frame = frame tableView.layoutIfNeeded() exitFullScreen() } } } } } } func enterFullScreen() { if !isFullScreen { handleTap(nil) } } func exitFullScreen() { if isFullScreen { handleTap(nil) } } @objc func handleTap(_ sender:AnyObject?) { self.willChangeFullScreenMode() UIView.animate(withDuration: 0.3, delay: 0, options: [.beginFromCurrentState, .beginFromCurrentState], animations: { () -> Void in self.adjustTableViewContentInset() self.tableHeaderView!.frame = self.newFrame }) { (completed: Bool) -> Void in self.didChangeFullScreenMode() } } func adjustTableViewContentInset() { //Adjust ContentOffset tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x,y: -(self.newFrame.size.height+self.tableViewTopInset)), animated: false) //Adjust ContentInset var contentInset = tableView.contentInset contentInset.top = newFrame.size.height+tableViewTopInset tableView.contentInset = contentInset } func willChangeFullScreenMode() { isAnimating = true if isFullScreen { } else { initialContentSize = tableView.contentSize } } func didChangeFullScreenMode() { isFullScreen = !isFullScreen isAnimating = false tableView.isScrollEnabled = true if isFullScreen { tableView.contentSize = CGSize(width: initialContentSize.width, height: 0) } else { tableView.contentSize = initialContentSize } } }
mit
aa3b5eea23b2d4c0aaaf4bf29febcdaa
34.448113
218
0.586427
5.997606
false
false
false
false
phanviet/AppState
Example/Pods/AppState/Pod/Classes/AppState.swift
1
5778
// // AppState.swift // AppState // // Created by Phan Hong Viet on 11/30/15. // Copyright (c) 2015 Viet Phan. All rights reserved. // import Foundation import UIKit public struct AppStateEvent { let name: String let from: [String] let to: String init(name: String, from: [String], to: String) { self.name = name self.from = from self.to = to } init(name: String, from: String, to: String) { self.init(name: name, from: [from], to: to) } } public typealias AppEvents = [AppStateEvent] public typealias StateContext = [String: AnyObject] @objc protocol AppStateDelegate { optional func onLeaveState(eventName: String, currentState: String, from: String, to: String, context: StateContext?) optional func onEnterState(eventName: String, currentState: String, from: String, to: String, context: StateContext?) } public class AppState { //--------------------------------------------------------------------------- enum Result { // the event transitioned successfully from one state to another case Succeeded // the event was successfull but no state transition was necessary case NoTransition } //--------------------------------------------------------------------------- let initialState: String let events: AppEvents var delegateDict = [String: AppStateDelegate]() private var _currentState: String private var eventNotFound = "" // { event: { from: to } } var map = [String: [String: String]]() // { state: [ event ] } var transition = [String: [String]]() init(initialState: String, events: AppEvents) { self.initialState = initialState self.events = events _currentState = initialState // Init Events self.addEvents(events) } // MARK: - Instance // Add a delegate func addDelegate(delegate: AppStateDelegate, forState state: String) { delegateDict[state] = delegate } // Remove all delegates func removeAllDelegates() { delegateDict.removeAll(keepCapacity: false) } // Remove a delegate func removeDelegateForState(state: String) { delegateDict.removeValueForKey(state) } // Get current state func getCurrentState() -> String { return _currentState } // Return true if state is the current state func isCurrentState(stateName: String) -> Bool { return stateName == getCurrentState() } // Return list of events that are allowed from the current state func getTransitions() -> [String] { var transitions = [String]() if let eventNames = transition[getCurrentState()] { transitions = eventNames } return transitions } // Transit to other state from current state by event name func transitTo(eventName: String, context: StateContext? = nil) -> Result { if canTransitTo(eventName) { return _transitTo(eventName, context: context) } return Result.NoTransition } // Return true if event can be fired in the current state func canTransitTo(eventName: String) -> Bool { if let eventNames = transition[getCurrentState()] { return eventNames.contains(eventName) } return false } // Adding Events to State Machine func addEvents(events: AppEvents) { for event in events { addEvent(event) } } // Adding an Event to State Machine func addEvent(event: AppStateEvent) { if map[event.name] == nil { map[event.name] = [:] } for from in event.from { if transition[from] == nil { transition[from] = [] } if transition[from] != nil { transition[from]!.append(event.name) } if map[event.name] != nil { map[event.name]![from] = event.to } } } // Update destination step if have func updateState(state: String, context: StateContext? = nil) -> Result { let eventName = eventNameForState(state) if eventName != eventNotFound { return _transitTo(eventName, context: context) } return Result.NoTransition } // Register View Controller for state func registerViewController(viewController: UIViewController, forState state: String) { if let viewControllerDelegate = viewController as? AppStateDelegate { self.addDelegate(viewControllerDelegate, forState: state) } } // MARK: - private // Return true if it's state delegate private func _isStateHasDelegate(state: String) -> Bool { if let _ = delegateDict[state] { return true } return false } // Return true if the current state could change to next state private func eventNameForState(state: String) -> String { let currentState = getCurrentState() for (eventName, states) in map { for (from, to) in states { if from == currentState && to == state { return eventName } } } return eventNotFound } // Transit to other state from current state by event name private func _transitTo(eventName: String, context: StateContext? = nil) -> Result { if let state = map[eventName], to = state[getCurrentState()] { let from = getCurrentState() let isStateHasDelegate = _isStateHasDelegate(to) // Call delegate on leave state if isStateHasDelegate { delegateDict[to]?.onLeaveState?(eventName, currentState: getCurrentState(), from: from, to: to, context: context) } _currentState = to // Call delegate on enter state if isStateHasDelegate { delegateDict[to]?.onEnterState?(eventName, currentState: getCurrentState(), from: from, to: to, context: context) } return Result.Succeeded } return Result.NoTransition } }
mit
491fd494d4f9d87335475f23e42554ab
25.031532
121
0.632918
4.567589
false
false
false
false
MLSDev/TRON
Source/TRON/TRON.swift
1
11528
// // TRON.swift // TRON // // Created by Denys Telezhkin on 28.01.16. // Copyright © 2015 - present MLSDev. 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. import Foundation import Alamofire /** `TRON` is a root object, that serves as a provider for single API endpoint. It is used to create and configure instances of `APIRequest` and `MultipartAPIRequest`. You need to hold strong reference to `TRON` instance while your network requests are running. */ open class TRON: TronDelegate { /// URL builder to be used by default in all requests. Can be overridden for specific requests. open var urlBuilder: URLBuilder /// Global property, that defines whether stubbing is enabled. It is simply set on each `APIRequest` instance and can be reset. open var stubbingEnabled = false /// Global plugins, that will receive events from all requests, created from current TRON instance. open var plugins: [Plugin] = [] /// Default parameter encoding, that will be set on all APIRequests. Can be overrided by setting new value on APIRequest.parameterEncoding property. /// Default value - URLEncoding.default open var parameterEncoding: Alamofire.ParameterEncoding = URLEncoding.default /// Queue, used to deliver result completion blocks. Defaults to dispatch_get_main_queue(). open var resultDeliveryQueue = DispatchQueue.main /// `CodableSerializer` for current `TRON` instance. open lazy var codable: CodableSerializer = { CodableSerializer(self) }() /// Alamofire.Session instance used to send network requests public let session: Alamofire.Session /** Initializes `TRON` with given base URL, Alamofire.Session instance, and array of global plugins. - parameter baseURL: Base URL to be used - parameter buildingURL: Behavior to use while building URLs. Defaults to .appendingPathComponent. - parameter session: Alamofire.Session instance that will send requests created by current `TRON` - parameter plugins: Array of plugins, that will receive events from requests, created and managed by current `TRON` instance. */ public init(baseURL: String, buildingURL: URLBuilder.Behavior = .appendingPathComponent, session: Alamofire.Session = .default, plugins: [Plugin] = []) { self.urlBuilder = URLBuilder(baseURL: baseURL, behavior: buildingURL) self.plugins = plugins self.session = session } /** Creates APIRequest with specified relative path and type RequestType.Default. - parameter path: Path, that will be appended to current `baseURL`. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. */ open func request<Model, ErrorModel: ErrorSerializable, Serializer: DataResponseSerializerProtocol> (_ path: String, responseSerializer: Serializer) -> APIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return APIRequest(path: path, tron: self, responseSerializer: responseSerializer) } /** Creates APIRequest with specified relative path and type RequestType.UploadFromFile. - parameter path: Path, that will be appended to current `baseURL`. - parameter fileURL: File url to upload from. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. */ open func upload<Model, ErrorModel: ErrorSerializable, Serializer: DataResponseSerializerProtocol> (_ path: String, fromFileAt fileURL: URL, responseSerializer: Serializer) -> UploadAPIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return UploadAPIRequest(type: .uploadFromFile(fileURL), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates APIRequest with specified relative path and type RequestType.UploadData. - parameter path: Path, that will be appended to current `baseURL`. - parameter data: Data to upload. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. */ open func upload<Model, ErrorModel: ErrorSerializable, Serializer: DataResponseSerializerProtocol> (_ path: String, data: Data, responseSerializer: Serializer) -> UploadAPIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return UploadAPIRequest(type: .uploadData(data), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates APIRequest with specified relative path and type RequestType.UploadStream. - parameter path: Path, that will be appended to current `baseURL`. - parameter stream: Stream to upload from. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. */ open func upload<Model, ErrorModel: ErrorSerializable, Serializer: DataResponseSerializerProtocol> (_ path: String, from stream: InputStream, responseSerializer: Serializer) -> UploadAPIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return UploadAPIRequest(type: .uploadStream(stream), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates MultipartAPIRequest with specified relative path. - parameter path: Path, that will be appended to current `baseURL`. - parameter responseSerializer: object used to serialize response. - parameter formData: Multipart form data creation block. - returns: MultipartAPIRequest instance. */ open func uploadMultipart<Model, ErrorModel, Serializer> (_ path: String, responseSerializer: Serializer, encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, fileManager: FileManager = .default, formData: @escaping (MultipartFormData) -> Void) -> UploadAPIRequest<Model, ErrorModel> where ErrorModel: ErrorSerializable, Serializer: DataResponseSerializerProtocol, Serializer.SerializedObject == Model { return UploadAPIRequest(type: UploadRequestType.multipartFormData(formData: formData, memoryThreshold: encodingMemoryThreshold, fileManager: fileManager), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates DownloadAPIRequest with specified relative path and type RequestType.Download. - parameter path: Path, that will be appended to current `baseURL`. - parameter destination: Destination for downloading. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. - seealso: `Alamofire.Request.suggestedDownloadDestination(directory:domain:)` method. */ open func download<Model, ErrorModel: DownloadErrorSerializable, Serializer: DownloadResponseSerializerProtocol> (_ path: String, to destination: @escaping DownloadRequest.Destination, responseSerializer: Serializer) -> DownloadAPIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return DownloadAPIRequest(type: .download(destination), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates DownloadAPIRequest with specified relative path and type RequestType.DownloadResuming. - parameter path: Path, that will be appended to current `baseURL`. - parameter destination: Destination to download to. - parameter resumingFrom: Resume data for current request. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. - seealso: `Alamofire.Request.suggestedDownloadDestination(directory:domain:)` method. */ open func download<Model, ErrorModel: DownloadErrorSerializable, Serializer: DownloadResponseSerializerProtocol> (_ path: String, to destination: @escaping DownloadRequest.Destination, resumingFrom: Data, responseSerializer: Serializer) -> DownloadAPIRequest<Model, ErrorModel> where Serializer.SerializedObject == Model { return DownloadAPIRequest(type: .downloadResuming(data: resumingFrom, destination: destination), path: path, tron: self, responseSerializer: responseSerializer) } /** Creates DownloadAPIRequest with specified relative path and type RequestType.Download. - parameter path: Path, that will be appended to current `baseURL`. - parameter destination: Destination for downloading. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. - seealso: `Alamofire.Request.suggestedDownloadDestination(directory:domain:)` method. */ open func download<ErrorModel: DownloadErrorSerializable> (_ path: String, to destination: @escaping DownloadRequest.Destination) -> DownloadAPIRequest<URL, ErrorModel> { DownloadAPIRequest(type: .download(destination), path: path, tron: self, responseSerializer: FileURLPassthroughResponseSerializer()) } /** Creates DownloadAPIRequest with specified relative path and type RequestType.DownloadResuming. - parameter path: Path, that will be appended to current `baseURL`. - parameter destination: Destination to download to. - parameter resumingFrom: Resume data for current request. - parameter responseSerializer: object used to serialize response. - returns: APIRequest instance. - seealso: `Alamofire.Request.suggestedDownloadDestination(directory:domain:)` method. */ open func download<ErrorModel: DownloadErrorSerializable> (_ path: String, to destination: @escaping DownloadRequest.Destination, resumingFrom: Data) -> DownloadAPIRequest<URL, ErrorModel> { DownloadAPIRequest(type: .downloadResuming(data: resumingFrom, destination: destination), path: path, tron: self, responseSerializer: FileURLPassthroughResponseSerializer()) } }
mit
be60b8247e7f62d6b747eb4ee6ef5105
43.678295
168
0.707469
5.606518
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/Connect View Controllers/CustomRaceViewController/CustomRaceOtherController.swift
2
2954
// // CustomRaceOtherController.swift // WikiRaces // // Created by Andrew Finke on 5/3/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import UIKit import WKRKit final class CustomRaceOtherController: CustomRaceController { // MARK: - Types - private class Cell: UITableViewCell { // MARK: - Properties - let toggle = UISwitch() static let reuseIdentifier = "reuseIdentifier" // MARK: - Initalization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(toggle) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - override func layoutSubviews() { super.layoutSubviews() toggle.onTintColor = .wkrTextColor(for: traitCollection) toggle.center = CGPoint( x: contentView.frame.width - contentView.layoutMargins.right - toggle.frame.width / 2, y: contentView.frame.height / 2) } } // MARK: - Properties - var other: WKRGameSettings.Other { didSet { didUpdate?(other) } } var didUpdate: ((WKRGameSettings.Other) -> Void)? // MARK: - Initalization - init(other: WKRGameSettings.Other) { self.other = other super.init(style: .grouped) title = "Other".uppercased() tableView.allowsSelection = false tableView.register(Cell.self, forCellReuseIdentifier: Cell.reuseIdentifier) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else { fatalError() } cell.toggle.tag = indexPath.row cell.toggle.addTarget(self, action: #selector(switchChanged(updatedSwitch:)), for: .valueChanged) switch indexPath.row { case 0: cell.textLabel?.text = "Help Enabled" cell.toggle.isOn = other.isHelpEnabled default: fatalError() } return cell } // MARK: - Helpers - @objc func switchChanged(updatedSwitch: UISwitch) { other = WKRGameSettings.Other(isHelpEnabled: updatedSwitch.tag == 0 ? updatedSwitch.isOn : other.isHelpEnabled) } }
mit
95b1f85d921f8159cea307a5b8ca2721
27.394231
119
0.611243
4.848933
false
false
false
false
dduan/swift
stdlib/public/core/CString.swift
1
4085
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Create a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `cString`. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, replaces them /// with replacement characters (U+FFFD). /// /// - Precondition: `cString != nil` public init(cString: UnsafePointer<CChar>) { _precondition(cString != nil, "cString must not be nil") self = String.decodeCString(UnsafePointer(cString), as: UTF8.self, repairingInvalidCodeUnits: true)!.result } /// Create a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `cString`. /// /// Does not try to repair ill-formed UTF-8 code unit sequences, fails if any /// such sequences are found. /// /// - Precondition: `cString != nil` public init?(validatingUTF8 cString: UnsafePointer<CChar>) { _precondition(cString != nil, "cString must not be nil") guard let (result, _) = String.decodeCString( UnsafePointer(cString), as: UTF8.self, repairingInvalidCodeUnits: false) else { return nil } self = result } /// Create a new `String` by copying the nul-terminated data /// referenced by a `cString` using `encoding`. /// /// Returns `nil` if the `cString` is `NULL` or if it contains ill-formed code /// units and no repairing has been requested. Otherwise replaces /// ill-formed code units with replacement characters (U+FFFD). @warn_unused_result public static func decodeCString<Encoding : UnicodeCodec>( cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { if cString._isNull { return nil } let len = Int(_swift_stdlib_strlen(UnsafePointer(cString))) let buffer = UnsafeBufferPointer<Encoding.CodeUnit>( start: cString, count: len) let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits( buffer, encoding: encoding, repairIllFormedSequences: isRepairing) return stringBuffer.map { (result: String(_storage: $0), repairsMade: hadError) } } } /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. @warn_unused_result public func _persistCString(s: UnsafePointer<CChar>) -> [CChar]? { if s == nil { return nil } let count = Int(_swift_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result } extension String { @available(*, unavailable, message: "Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.") @warn_unused_result public static func fromCString(cs: UnsafePointer<CChar>) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.") @warn_unused_result public static func fromCStringRepairingIllFormedUTF8( cs: UnsafePointer<CChar> ) -> (String?, hadError: Bool) { fatalError("unavailable function can't be called") } }
apache-2.0
0ef3d1880b5b5a19eed8ca4aceb027f3
36.477064
233
0.653856
4.430586
false
false
false
false
superk589/DereGuide
DereGuide/Toolbox/Colleague/Composing/View/FreeCardGroupView.swift
2
1683
// // FreeCardGroupView.swift // DereGuide // // Created by zzk on 2019/4/19. // Copyright © 2019 zzk. All rights reserved. // import UIKit class FreeCardGroupView: UIView { let descLabel = UILabel() var stackView: UIStackView! var editableItemViews = [FreeCardItemView]() override init(frame: CGRect) { super.init(frame: frame) for _ in 0..<5 { let view = FreeCardItemView() editableItemViews.append(view) } stackView = UIStackView(arrangedSubviews: editableItemViews) stackView.spacing = 6 stackView.distribution = .fillEqually stackView.alignment = .center addSubview(stackView) stackView.snp.remakeConstraints { (make) in make.top.equalToSuperview() make.left.greaterThanOrEqualTo(10) make.right.lessThanOrEqualTo(-10) // make the view as wide as possible make.right.equalTo(-10).priority(900) make.left.equalTo(10).priority(900) // make.bottom.equalToSuperview() make.width.lessThanOrEqualTo(96 * 5 + 6 * 5) make.centerX.equalToSuperview() } } func setupWith(cardID: Int, at index: Int, hidesIfNeeded: Bool = false) { editableItemViews[index].setupWith(cardID: cardID) if cardID == 0 && hidesIfNeeded { editableItemViews[index].isHidden = true } else { editableItemViews[index].isHidden = false } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ccb66556f255f800555b5d4681ff0a03
27.033333
77
0.590963
4.764873
false
false
false
false
mpullman/ios-charts
Charts/Classes/Renderers/D3HorizontalBarChartRenderer.swift
1
19720
// // D3HorizontalBarChartRenderer.swift // Charts // // Created by Malcolm Pullman on 16/07/15. // Copyright (c) 2015 dcg. All rights reserved. // import Foundation import CoreGraphics import UIKit public class D3HorizontalBarChartRenderer: D3BarChartRenderer { internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context) var barData = delegate!.barChartRendererData(self) var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self) var dataSetOffset = (barData.dataSetCount - 1) var groupSpace = barData.groupSpace var groupSpaceHalf = groupSpace / 2.0 var barSpace = dataSet.barSpace var barSpaceHalf = barSpace / 2.0 var containsStacks = dataSet.isStacked var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var barWidth: CGFloat = 0.5 var phaseY = _animator.phaseY var barRect = CGRect() var barShadow = CGRect() var y: Double // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextFillRect(context, barRect) } else { var allPos = e.positiveSum var allNeg = e.negativeSum // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // fill the stack for (var k = 0; k < vals!.count; k++) { let value = vals![k] if value >= 0.0 { allPos -= value y = value + allPos } else { allNeg -= abs(value) y = value + allNeg } var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = y >= 0.0 ? CGFloat(y) : 0.0 var left = y <= 0.0 ? CGFloat(y) : 0.0 // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextFillRect(context, barRect) } } } CGContextRestoreGState(context) } internal override func prepareBarHighlight(#x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 var top = x - barWidth + barspacehalf var bottom = x + barWidth - barspacehalf var left = CGFloat(y1) var right = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY) } public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY) } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self) var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self) var dataSets = barData.dataSets var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self) var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValueAboveBarEnabled(self) let textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right let valueOffsetPlus: CGFloat = 5.0 var posOffset: CGFloat var negOffset: CGFloat for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i] if (!dataSet.isDrawValuesEnabled) { continue } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var yOffset = -valueFont.lineHeight / 2.0 var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i) // if only single values are drawn (sum) if (!drawValuesForWholeStackEnabled) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = entries[j].value var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } else { // if each value of a potential stack should be drawn for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j] var vals = e.values // we still draw stacked bars, but there is one non-stacked in between if (vals == nil) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = e.value var valueText: String! if let barData = barData as? D3BarChartData { valueText = barData.drawLabelInBar ? barData.xVals[j]! : formatter!.stringFromNumber(val)! } else { valueText = formatter!.stringFromNumber(val)! } // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } else { var transformed = [CGPoint]() var allPos = e.positiveSum var allNeg = e.negativeSum for (var k = 0; k < vals!.count; k++) { let value = vals![k] var y: Double if value >= 0.0 { allPos -= value y = value + allPos } else { allNeg -= abs(value) y = value + allNeg } transformed.append(CGPoint(x: CGFloat(y) * _animator.phaseY, y: 0.0)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { var val = vals![k] var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } var x = transformed[k].x + (val >= 0 ? posOffset : negOffset) var y = valuePoints[j].y if (!viewPortHandler.isInBoundsX(x)) { continue } if (!viewPortHandler.isInBoundsTop(y)) { break } if (!viewPortHandler.isInBoundsBottom(y)) { continue } drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } } } } } } internal override func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return false } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY } }
apache-2.0
dc744636d760f5e334645b11b28c144c
42.058952
170
0.410953
7.101188
false
false
false
false
maxbritto/cours-ios11-swift4
Niveau_avance/Objectif 2/Safety First/Safety First/Model/VaultManager.swift
1
1960
// // VaultManager.swift // Safety First // // Created by Maxime Britto on 27/09/2017. // Copyright © 2017 Maxime Britto. All rights reserved. // import Foundation import RealmSwift import KeychainAccess class VaultManager { private static let REALM_ENCRYPTION_KEY = "REALM_ENCRYPTION_KEY" private static let MASTER_PASSWORD = "SAFETY_FIRST_MASTER_PASSWORD" private var _vault:Vault? private var _keychain:Keychain init() { _keychain = Keychain(service: Bundle.main.bundleIdentifier ?? "fr.purplegiraffe.ios.Safety-First") } func getMainVault() -> Vault? { var possibleKey:Data? //charger la clée possibleKey = loadRealmEncryptionKey() //si pas de clée générer une nouvelle clée if possibleKey == nil { possibleKey = generateRealmEncryptionKey() } //config realm avec cette clée if let realmEncyptionKey = possibleKey { let realmConf = Realm.Configuration(encryptionKey: realmEncyptionKey) let realm = try! Realm(configuration: realmConf) _vault = Vault(withRealm: realm) } return _vault } private func loadRealmEncryptionKey() -> Data? { return _keychain[data: VaultManager.REALM_ENCRYPTION_KEY] } private func generateRealmEncryptionKey() -> Data? { guard let generatedData = Data(countOfRandomData: 64) else { return nil } try! _keychain.set(generatedData, key: VaultManager.REALM_ENCRYPTION_KEY) return generatedData } func saveMasterPassword(_ password:String) { _keychain[VaultManager.MASTER_PASSWORD] = password } func getMasterPassword() -> String? { return _keychain[VaultManager.MASTER_PASSWORD] } func hasMasterPassword() -> Bool { return getMasterPassword() != nil } }
apache-2.0
681bb13a7620292e94bc97f3db3926e6
24.038462
106
0.626728
4.378924
false
false
false
false
siberianisaev/NeutronBarrel
NeutronBarrel/chi.playground/Contents.swift
1
2606
import Foundation extension Int { func factorial() -> Double { if self <= 1 { return 1 } return (1...self).map(Double.init).reduce(1.0, *) } } //let m = NeutronsMultiplicity.init(info: [0:3, 1:15, 2:20, 3:15, 4:4, 5:5, 6:1], efficiency: 43.0, efficiencyError: 1.0) //print(m.stringValue()) let t = NeutronsMultiplicity.averageNumberOf(neutrons: 45+97, events: 25+65, efficiency: 45.0, efficiencyError: 1.0) print(t) //let a1 = [ //"AR208PB002.001_303889", "AR208PB23.138_375743"] //let a2 = ["AR208PB002.001_303889", "AR208PB002.001_303889", "AR208PB002.001_303889"] //let set1 = Set(a1) //let set2 = Set(a2) //let sub = set1.symmetricDifference(set2) //print(sub) let events = 1419612 let neutrons = 2435546 let average = 1.715642020495741 //± 0.001811610238618803 let efficiency = 54.7 let efficiencyError = 0.1 let averageErrorWithEfficiency = (Double(neutrons)/(Double(events) * (efficiency/100)))*(1/Double(neutrons) + 1/Double(events) + pow(efficiencyError/efficiency, 2)).squareRoot() print("\n*Average: \(average * 100.0/efficiency) ± \(averageErrorWithEfficiency)") var measured = [96135, 257551, 269196, 141210, 40847, 7083, 801, 58, 3, 1] let PkExpected = [0.0061, 0.0608, 0.2272, 0.3460, 0.2476, 0.0906, 0.0190, 0.0024, 0.0002, 0.0001] let minN = 0 let maxN = measured.count-1 let Nd = measured.reduce(.zero, +) print("Efficiency,Chi^2") for step in 0...99999 { let e: Double = Double(step) / 100000.0 var expected = [Int]() for _ in 0...maxN { expected.append(0) } var chi2: Double = 0 for index in minN...maxN { let i = index var Nit: Double = 0 for index2 in index...maxN { let k = index2 let Pk: Double = PkExpected[k] Nit += (k.factorial() / (i.factorial() * (k - i).factorial())) * pow(e, Double(i)) * pow(1 - e, Double(k - i)) * Pk } Nit *= Double(Nd) expected[index] = Int(Nit) } for index in minN...maxN { let measuredN = Double(measured[index]) let expectedN = Double(expected[index]) if measured[index] > 5 && expected[index] > 5 { chi2 += pow(measuredN - expectedN, 2)/expectedN } } print(String(format: "%f,%.5f", e, chi2)) } let recoil: CUnsignedShort = 0b1000_0000_0000_0000 let beam: CUnsignedShort = 0b1100_0000_0000_0000 let overflow: CUnsignedShort = 0b1010_0000_0000_0000 print(String(recoil >> 15, radix: 2)) // 1st bit print(String((beam << 1) >> 15, radix: 2)) // 2nd bit print(String((overflow << 2) >> 15, radix: 2)) // 3rd bit
mit
a61b125db5eb03812b569dc616ce8400
31.962025
177
0.619816
2.955732
false
false
false
false
aronse/Hero
Sources/HeroPlugin.swift
1
5937
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit open class HeroPlugin: NSObject, HeroPreprocessor, HeroAnimator { weak public var hero: HeroTransition! public var context: HeroContext! { return hero.context } /** Determines whether or not to receive `seekTo` callback on every frame. Default is false. When **requirePerFrameCallback** is **false**, the plugin needs to start its own animations inside `animate` & `resume` The `seekTo` method is only being called during an interactive transition. When **requirePerFrameCallback** is **true**, the plugin will receive `seekTo` callback on every animation frame. Hence it is possible for the plugin to do per-frame animations without implementing `animate` & `resume` */ open var requirePerFrameCallback = false public override required init() {} /** Called before any animation. Override this method when you want to preprocess modifiers for views - Parameters: - context: object holding all parsed and changed modifiers, - fromViews: A flattened list of all views from source ViewController - toViews: A flattened list of all views from destination ViewController To check a view's modifiers: context[view] context[view, "modifierName"] To set a view's modifiers: context[view] = [("modifier1", ["parameter1"]), ("modifier2", [])] context[view, "modifier1"] = ["parameter1", "parameter2"] */ open func process(fromViews: [UIView], toViews: [UIView]) {} /** - Returns: return true if the plugin can handle animating the view. - Parameters: - context: object holding all parsed and changed modifiers, - view: the view to check whether or not the plugin can handle the animation - appearing: true if the view is appearing(i.e. a view in destination ViewController) If return true, Hero won't animate and won't let any other plugins animate this view. The view will also be hidden automatically during the animation. */ open func canAnimate(view: UIView, appearing: Bool) -> Bool { return false } /** Perform the animation. Note: views in `fromViews` & `toViews` are hidden already. Unhide then if you need to take snapshots. - Parameters: - context: object holding all parsed and changed modifiers, - fromViews: A flattened list of all views from source ViewController (filtered by `canAnimate`) - toViews: A flattened list of all views from destination ViewController (filtered by `canAnimate`) - Returns: The duration needed to complete the animation */ open func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval { return 0 } /** Called when all animations are completed. Should perform cleanup and release any reference */ open func clean() {} /** For supporting interactive animation only. This method is called when an interactive animation is in place The plugin should pause the animation, and seek to the given progress - Parameters: - timePassed: time of the animation to seek to. */ open func seekTo(timePassed: TimeInterval) {} /** For supporting interactive animation only. This method is called when an interactive animation is ended The plugin should resume the animation. - Parameters: - timePassed: will be the same value since last `seekTo` - reverse: a boolean value indicating whether or not the animation should reverse */ open func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval { return 0 } /** For supporting interactive animation only. This method is called when user wants to override animation modifiers during an interactive animation - Parameters: - state: the target state to override - view: the view to override */ open func apply(state: HeroTargetState, to view: UIView) {} } // methods for enable/disable the current plugin extension HeroPlugin { public static var isEnabled: Bool { get { return HeroTransition.isEnabled(plugin: self) } set { if newValue { enable() } else { disable() } } } public static func enable() { HeroTransition.enable(plugin: self) } public static func disable() { HeroTransition.disable(plugin: self) } } // MARK: Plugin Support internal extension HeroTransition { static func isEnabled(plugin: HeroPlugin.Type) -> Bool { return enabledPlugins.index(where: { return $0 == plugin}) != nil } static func enable(plugin: HeroPlugin.Type) { disable(plugin: plugin) enabledPlugins.append(plugin) } static func disable(plugin: HeroPlugin.Type) { if let index = enabledPlugins.index(where: { return $0 == plugin}) { enabledPlugins.remove(at: index) } } }
mit
114ad8306e3b963aef771d4657aa3304
33.923529
222
0.708607
4.64554
false
false
false
false
malaonline/iOS
mala-ios/Model/Payment/PaymentChannel.swift
1
885
// // PaymentChannel.swift // mala-ios // // Created by 王新宇 on 2/29/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit class PaymentChannel: NSObject { // MARK: - Property var imageName: String? var title: String? var subTitle: String? var channel: MalaPaymentChannel? // MARK: - Constructed override init() { super.init() } convenience init(imageName: String, title: String, subTitle: String, channel: MalaPaymentChannel) { self.init() self.imageName = imageName self.title = title self.subTitle = subTitle self.channel = channel } // MARK: - Description override var description: String { let keys = ["imageName", "title", "subTitle", "channel"] return dictionaryWithValues(forKeys: keys).description } }
mit
6c4219bfcd63aacb5b9244cd7dce8a2b
21.512821
103
0.611617
4.325123
false
false
false
false
hassanabidpk/umapit_ios
uMAPit/controllers/LandingPageViewController.swift
1
4220
// // LandingPageViewController.swift // uMAPit // // Created by Hassan Abid on 11/02/2017. // Copyright © 2017 uMAPit. All rights reserved. // import UIKit class LandingPageViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { @IBOutlet weak var pageControl: UIPageControl! // The UIPageViewController var pageContainer: UIPageViewController! // The pages it contains var pages = [UIViewController]() // Track the current index var currentIndex: Int? private var pendingIndex: Int? // let google_api_key = "AIzaSyB-zYAhnW0bDmH2g1uBJ1Ps558Sp25j1EE" // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupPageViewControllers() } // MARK: - UI func setupPageViewControllers() { // Setup the pages let storyboard = UIStoryboard(name: "Main", bundle: nil) let landingViewController: UIViewController! = storyboard.instantiateViewController(withIdentifier: "landing") let loginViewController: UIViewController! = storyboard.instantiateViewController(withIdentifier: "login") landingViewController.view.backgroundColor = UIColor(red: 77/255, green: 195/255, blue: 58/255, alpha: 1.0) loginViewController.view.backgroundColor = UIColor(red: 77/255, green: 195/255, blue: 58/255, alpha: 1.0) pages.append(landingViewController) pages.append(loginViewController) // Create the page container pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) pageContainer.delegate = self pageContainer.dataSource = self pageContainer.setViewControllers([landingViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil) // Add it to the view view.addSubview(pageContainer.view) // Configure our custom pageControl view.bringSubview(toFront: pageControl) pageControl.numberOfPages = pages.count pageControl.currentPage = 0 } // MARK: UIPageViewController delegates func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let currentIndex = pages.index(of: viewController)! if currentIndex == 0 { return nil } let previousIndex = abs((currentIndex - 1) % pages.count) return pages[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let currentIndex = pages.index(of: viewController)! if currentIndex == pages.count-1 { return nil } let nextIndex = abs((currentIndex + 1) % pages.count) return pages[nextIndex] } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { pendingIndex = pages.index(of: pendingViewControllers.first!) } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { currentIndex = pendingIndex if let index = currentIndex { print("Current Index : \(index)") pageControl.currentPage = index } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK - helpers }
mit
896d8c9937f276031b15074443ba67b2
30.962121
190
0.653709
5.701351
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Axis/ChartAxisLabel.swift
1
1839
// // ChartAxisLabel.swift // swift_charts // // Created by ischuetz on 01/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// A model of an axis label open class ChartAxisLabel { /// Displayed text. Can be truncated. public let text: String public let settings: ChartLabelSettings open fileprivate(set) var originalText: String var hidden: Bool = false open lazy private(set) var textSizeNonRotated: CGSize = { return self.text.size(self.settings.font) }() /// The size of the bounding rectangle for the axis label, taking into account the font and rotation it will be drawn with open lazy private(set) var textSize: CGSize = { let size = self.textSizeNonRotated if self.settings.rotation =~ 0 { return size } else { return CGRect(x: 0, y: 0, width: size.width, height: size.height).boundingRectAfterRotating(radians: self.settings.rotation * CGFloat.pi / 180.0).size } }() public init(text: String, settings: ChartLabelSettings) { self.text = text self.settings = settings self.originalText = text } func copy(_ text: String? = nil, settings: ChartLabelSettings? = nil, originalText: String? = nil, hidden: Bool? = nil) -> ChartAxisLabel { let label = ChartAxisLabel( text: text ?? self.text, settings: settings ?? self.settings ) label.originalText = originalText ?? self.originalText label.hidden = hidden ?? self.hidden return label } } extension ChartAxisLabel: CustomDebugStringConvertible { public var debugDescription: String { return [ "text": text, "settings": settings ] .debugDescription } }
apache-2.0
3a9efe6dfe0ee3585b98b0444bad8b16
28.66129
162
0.626427
4.574627
false
false
false
false
dustintownsend/ApiModel
Source/NSDateTransform.swift
2
1118
import Foundation public class NSDateTransform: Transform { public init() {} public func perform(value: AnyObject?) -> AnyObject { if let dateValue = value as? NSDate { return dateValue } // Rails dates with time and zone if let stringValue = value as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" if let date = dateFormatter.dateFromString("\(stringValue)") { return toLocalTimezone(date) } // Standard short dates let simpleDateFormatter = NSDateFormatter() simpleDateFormatter.dateFormat = "yyyy-MM-dd" if let date = simpleDateFormatter.dateFromString("\(stringValue)") { return toLocalTimezone(date) } } return NSDate() } func toLocalTimezone(date: NSDate) -> NSDate { let seconds = NSTimeInterval(NSTimeZone.localTimeZone().secondsFromGMTForDate(date)) return NSDate(timeInterval: seconds, sinceDate: date) } }
mit
468580f502b5055c2cd430cb8fd977a4
31.882353
92
0.603757
5.248826
false
false
false
false
GiorgioNatili/pokedev
Pokedev/Pokedev/PokemonDetails/WireFrame/PokemonDetailsWireFrame.swift
1
1542
// // Created by Benjamin Soung // Copyright (c) 2016 Benjamin Soung. All rights reserved. // import Foundation import UIKit class PokemonDetailsWireFrame: PokemonDetailsWireFrameProtocol { func presentPokemonDetailsModule(fromView uiview: AnyObject) { let viewController = uiview as! UIViewController let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // Generating module components let view = mainStoryboard.instantiateViewControllerWithIdentifier("PokemonDetails") as! PokemonDetailsView let presenter: protocol<PokemonDetailsPresenterProtocol, PokemonDetailsInteractorOutputProtocol> = PokemonDetailsPresenter() let interactor: PokemonDetailsInteractorInputProtocol = PokemonDetailsInteractor() let APIDataManager: PokemonDetailsAPIDataManagerInputProtocol = PokemonDetailsAPIDataManager() let localDataManager: PokemonDetailsLocalDataManagerInputProtocol = PokemonDetailsLocalDataManager() let wireFrame: PokemonDetailsWireFrameProtocol = PokemonDetailsWireFrame() // Connecting view.presenter = presenter presenter.view = view presenter.wireFrame = wireFrame presenter.interactor = interactor interactor.presenter = presenter interactor.APIDataManager = APIDataManager interactor.localDatamanager = localDataManager // Presenting (viewController as! UINavigationController).pushViewController(view, animated: true) } }
unlicense
e41a99cc9f9efa34e23ad38274bed5df
41.861111
132
0.745785
6.763158
false
false
false
false
cmyers78/TIY-Assignments
19/SpotifIron Swift Myers/SpotifIron Swift Myers/ViewController.swift
1
5099
// // ViewController.swift // SpotifIron Swift Myers // // Created by Christopher Myers on 6/16/16. // Copyright © 2016 Dragoman Developers, LLC. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet weak var textFieldOutlet: UITextField! @IBOutlet weak var tableView: UITableView! let session = NSURLSession.sharedSession() var artistArray = [Artist]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } // MARK : Grab text and implement parsing method func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() if let query = textField.text { print("The textfield value is \(query)") self.fetchArtist(query) } return true } // MARK : Table View Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.artistArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let currentArtist = self.artistArray[indexPath.row] cell.textLabel?.text = currentArtist.name return cell } // MARK: Parsing Method func fetchArtist(query : String) { print("fetchArtist query value is \(query)") self.artistArray.removeAll() let artistURLString = "https://api.spotify.com/v1/search?q=\(query)&type=artist" if let url = NSURL(string: artistURLString) { let task = self.session.dataTaskWithURL(url, completionHandler: { (data, response, error) in if error != nil { print("An error occured") return } do { if let data = data { if let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? JSONDictionary { if let artistDict = dict["artists"] as? JSONDictionary { if let itemsArray = artistDict["items"] as? JSONArray { for itemsDict in itemsArray { print("The item dict == \(itemsDict)") let theArtist = Artist() if let name = itemsDict["name"] as? String { theArtist.name = name } else { print("I could not parse the name") } if let artistID = itemsDict["id"] as? String { theArtist.artistID = artistID } else { print("I could not parse the artistID") } self.artistArray.append(theArtist) } print(self.artistArray.count) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } else { print("I could not parse the items") } } else { print ("I could not parse the artists") } } else { print ("I could not parse the json dictionary") } } } catch { // error happened } }) task.resume() } } }
mit
3272da4434570da8415d4c45c44ee6bf
31.890323
120
0.397607
7.241477
false
false
false
false
ztyjr888/WeChat
WeChat/Contact/Person/AddCommentViewController.swift
1
2000
// // AddCommentViewController.swift // WeChat // // Created by Smile on 16/1/26. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit //添加评论页面 class AddCommentViewController: UIViewController,WeChatCustomNavigationHeaderDelegate{ var textView:UITextView! var navigation:WeChatCustomNavigationHeaderView! var navigationHeight:CGFloat = 44 override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() initNavigationBar() } func initNavigationBar(){ //获取状态栏 let statusBarFrame = UIApplication.sharedApplication().statusBarFrame self.navigationHeight += statusBarFrame.height self.navigation = WeChatCustomNavigationHeaderView(frame: CGRectMake(0, 0,UIScreen.mainScreen().bounds.width, navigationHeight), backImage: nil, backTitle: "取消", centerLabel: "评论", rightButtonText: "发送", rightButtonImage: nil, backgroundColor: nil, leftLabelColor: nil, rightLabelColor: UIColor.greenColor()) self.view.addSubview(self.navigation) self.view.bringSubviewToFront(self.navigation) self.navigation.delegate = self createTextField(self.navigation.frame.height) } func createTextField(topPadding:CGFloat){ textView = UITextView() textView.frame = CGRectMake(10, topPadding, UIScreen.mainScreen().bounds.width - 10, UIScreen.mainScreen().bounds.height - topPadding) textView.returnKeyType = .Done textView.becomeFirstResponder() textView.font = UIFont(name: "Arial", size: 16) self.view.addSubview(textView) } func leftBarClick() { self.textView.resignFirstResponder() self.dismissViewControllerAnimated(true) { () -> Void in UtilTools().weChatTabBarController.selectedIndex = 1 } } func rightBarClick() { leftBarClick() } }
apache-2.0
e4a11eb48dd539dcd03d5a4d7d7f14f0
33.438596
316
0.685176
4.823096
false
false
false
false
bravelocation/yeltzland-ios
yeltzland/Models/NavigationActivity.swift
1
1596
// // NavigationActivity.swift // Yeltzland // // Created by John Pollard on 08/11/2020. // Copyright © 2020 John Pollard. All rights reserved. // import Foundation public struct NavigationActivity: Hashable { init(main: Bool, navElementId: String, url: URL? = nil, title: String) { self.main = main self.navElementId = navElementId self.url = url self.title = title } init(userInfo: [AnyHashable: Any]) { if let navType = userInfo["navType"] as? String { self.main = navType == "main" } else { self.main = false } self.navElementId = userInfo["navElementId"] as? String ?? "" if let savedUrl = userInfo["url"] as? NSURL { self.url = savedUrl.absoluteURL } self.title = userInfo["title"] as? String ?? "" } var main: Bool var navElementId: String var title: String var url: URL? var userInfo: [AnyHashable: Any] { get { if let url = self.url { return [ "navType": self.main ? NSString("main") :NSString( "more"), "navElementId": self.navElementId, "url": url.absoluteURL, "title": title ] } else { return [ "navType": self.main ? NSString("main") :NSString( "more"), "navElementId": self.navElementId, "title": title ] } } } }
mit
503f48a59eb2b8299cfad741b03bb57d
26.5
79
0.491536
4.518414
false
false
false
false
AlexMcArdle/LooseFoot
LooseFoot/Views/AMHeaderCellNode.swift
1
14781
// // AMHeaderCellNode.swift // LooseFoot // // Created by Alexander McArdle on 2/12/17. // Copyright © 2017 Alexander McArdle. All rights reserved. // import AsyncDisplayKit import ChameleonFramework import FontAwesome_swift import UIColor_Hex_Swift import Toaster class AMHeaderCellNode: ASCellNode { let header: AMSubreddit fileprivate let titleNode = ASTextNode() // fileprivate let authorNode = ASTextNode() fileprivate let imageBannerNode = ASNetworkImageNode() fileprivate let imageIconNode = ASNetworkImageNode() // fileprivate let pointsNode = ASTextNode() // fileprivate let commentsNode = ASTextNode() // fileprivate let subredditNode = ASTextNode() // fileprivate let authorFlairNode = ASTextNode() // fileprivate let linkFlairNode = ASTextNode() // fileprivate let goldNode = ASTextNode() // fileprivate let nsfwNode = ASTextNode() // fileprivate let spoilerNode = ASTextNode() // fileprivate let voteNode = ASTextNode() let middleStackSpec = ASStackLayoutSpec.vertical() let horizontalStackSpec = ASStackLayoutSpec.horizontal() let centerStackSpec = ASCenterLayoutSpec() var overlayStackSpec: ASOverlayLayoutSpec? // let rightSideStackSpec = ASStackLayoutSpec.vertical() // let leftSideStackSpec = ASStackLayoutSpec.vertical() // let topRowStackSpec = ASStackLayoutSpec.horizontal() // let bottomRowStackSpec = ASStackLayoutSpec.horizontal() // // let linkFlairBackground = ASDisplayNode() // let authorFlairBackground = ASDisplayNode() // // var linkFlairOverlay: ASBackgroundLayoutSpec? // var authorFlairOverlay: ASBackgroundLayoutSpec? // // var topRowChildren: [ASLayoutElement]? // var bottomRowChildren: [ASLayoutElement]? // var leftSideChildren: [ASLayoutElement]? var centerStackChildren: [ASLayoutElement]? var horizontalStackChildren: [ASLayoutElement]? func cellSwipedLeft() { Toast(text: "swipe left: \(header)").show() } func cellSwipedRight() { Toast(text: "swipe right: \(header)").show() } init(_ header: AMSubreddit) { self.header = header // init the super super.init() let leftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(cellSwipedLeft)) leftRecognizer.direction = .left let rightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(cellSwipedRight)) rightRecognizer.direction = .right self.view.isUserInteractionEnabled = true self.view.addGestureRecognizer(leftRecognizer) self.view.addGestureRecognizer(rightRecognizer) // topRowChildren = [subredditNode] // bottomRowChildren = [authorNode] // leftSideChildren = [imageNode] horizontalStackChildren = [] centerStackChildren = [titleNode] self.automaticallyManagesSubnodes = true backgroundColor = .flatBlack // // Check for vote // switch link.l.likes { // case .down: // let text = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .arrowDown), attributes: // [NSFontAttributeName: UIFont.fontAwesome(ofSize: 15), // NSForegroundColorAttributeName: UIColor.flatSkyBlue]) // voteNode.attributedText = text // case .up: // let text = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .arrowUp), attributes: // [NSFontAttributeName: UIFont.fontAwesome(ofSize: 15), // NSForegroundColorAttributeName: UIColor.orange]) // voteNode.attributedText = text // case .none: // break // } // Check for Image imageBannerNode.shouldRenderProgressImages = true imageIconNode.shouldRenderProgressImages = true if(self.header.s.bannerImg.hasPrefix("http")) { //imageNode.clipsToBounds = true imageBannerNode.url = URL(string: self.header.s.bannerImg) } if(self.header.s.iconImg.hasPrefix("http")) { imageIconNode.url = URL(string: self.header.s.iconImg) centerStackChildren?.insert(imageIconNode, at: 0) } // titleNode.attributedText = NSAttributedString.attributedString(string: "/r/\(self.header.s.displayName)", fontSize: 20, color: .flatWhite) titleNode.attributedText = NSAttributedString(string: "/r/\(self.header.s.displayName)", attributes: [NSFontAttributeName: AppFont(size: 20, bold: true), NSForegroundColorAttributeName: UIColor.flatWhite, NSStrokeColorAttributeName: UIColor.black, NSStrokeWidthAttributeName: -4.0]) // subredditNode.attributedText = NSAttributedString.attributedString(string: link.l.subreddit, fontSize: 12, color: UIColor.flatSkyBlue) // authorNode.attributedText = NSAttributedString.attributedString(string: link.l.author, fontSize: 12, color: .flatSand) // // var scoreString = String(link.l.score) // if(link.l.score >= 1000) { // scoreString = link.l.score.getFancyNumber()! // } // pointsNode.attributedText = NSAttributedString.attributedString(string: scoreString, fontSize: 12, color: .orange) // // commentsNode.attributedText = NSAttributedString.attributedString(string: String(link.l.numComments), fontSize: 12, color: .flatGray) // // // Check for Link Flair // if(link.l.linkFlairText != "") { // let flairString = link.l.linkFlairText.checkForBrackets() // linkFlairNode.attributedText = NSAttributedString.attributedString(string: flairString, fontSize: 8, color: .flatWhite) // linkFlairNode.textContainerInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) // //linkFlairNode.borderWidth = 1.0 // //linkFlairNode.borderColor = UIColor.flatWhiteDark.cgColor // //linkFlairNode.cornerRadius = 10.0 // linkFlairNode.truncationMode = .byTruncatingTail // linkFlairNode.maximumNumberOfLines = 1 // // linkFlairBackground.clipsToBounds = true // linkFlairBackground.borderColor = UIColor.flatGrayDark.cgColor // linkFlairBackground.borderWidth = 5.0 // linkFlairBackground.cornerRadius = 5 // linkFlairBackground.backgroundColor = .flatGrayDark // // linkFlairOverlay = ASBackgroundLayoutSpec(child: linkFlairNode, background: linkFlairBackground) // // topRowChildren?.append(linkFlairOverlay!) // } // // // Check for Author Flair // if(link.l.authorFlairText != "") { // let flairString = link.l.authorFlairText.checkForBrackets() // authorFlairNode.attributedText = NSAttributedString.attributedString(string: flairString, fontSize: 8, color: .flatWhite) // authorFlairNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 1, right: 2) // // authorFlairNode.borderWidth = 1.0 // // authorFlairNode.borderColor = UIColor.flatGrayDark.cgColor // // authorFlairNode.cornerRadius = 3.0 // authorFlairNode.truncationMode = .byTruncatingTail // authorFlairNode.maximumNumberOfLines = 1 // // authorFlairBackground.clipsToBounds = true // authorFlairBackground.borderColor = UIColor.flatGrayDark.cgColor // authorFlairBackground.borderWidth = 5.0 // authorFlairBackground.cornerRadius = 5 // authorFlairBackground.backgroundColor = .flatGrayDark // // authorFlairOverlay = ASBackgroundLayoutSpec(child: authorFlairNode, background: authorFlairBackground) // // bottomRowChildren?.append(authorFlairOverlay!) // } // // // Check for NSFW // if(link.l.over18) { // nsfwNode.attributedText = NSAttributedString.attributedString(string: "NSFW", fontSize: 10, color: .flatRedDark) // nsfwNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2) // nsfwNode.borderWidth = 1.0 // nsfwNode.borderColor = UIColor.flatRedDark.cgColor // nsfwNode.cornerRadius = 3.0 // // topRowChildren?.insert(nsfwNode, at: 0) // } // // Check for Spoiler // if(link.l.spoiler != 0) { // spoilerNode.attributedText = NSAttributedString.attributedString(string: "SPOILER", fontSize: 10, color: .flatRedDark) // spoilerNode.textContainerInset = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2) // spoilerNode.borderWidth = 1.0 // spoilerNode.borderColor = UIColor.flatRedDark.cgColor // spoilerNode.cornerRadius = 3.0 // // topRowChildren?.insert(spoilerNode, at: 0) // } // // // Check for Gold // if(link.l.gilded > 0) { // //goldNode.attributedText = NSAttributedString.attributedString(string: String(link.l.gilded), fontSize: 12, color: UIColor("#ffd700")) // let goldSymbol = NSMutableAttributedString(string: String.fontAwesomeIcon(name: .star), attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 12)]) // // let text: NSMutableAttributedString = goldSymbol // // // Add count if more than one (disabled) // //if(link.l.gilded > 1) { // let count = NSMutableAttributedString(string: "x\(link.l.gilded)", attributes: [NSFontAttributeName: AppFont(size: 12, bold: false)]) // text.append(count) // //} // // text.addAttribute(NSForegroundColorAttributeName, value: UIColor(hexString: "FFD700")!, range: NSRange(location: 0, length: text.length)) // goldNode.attributedText = text as NSAttributedString // // topRowChildren?.append(goldNode) // } } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { //debugPrint(constrainedSize) // Make the images pretty // if(link.l.thumbnail.hasPrefix("http")) { // let imageSize = CGSize(width: 60, height: 60) // imageNode.style.preferredSize = imageSize // imageNode.imageModificationBlock = { image in // let width: CGFloat // var color: UIColor? = nil // if(self.link.l.over18) { // width = 5 // color = UIColor.flatRed // } else { // width = 0 // } // return image.makeRoundedImage(size: imageSize, borderWidth: width, color: color) // } // } else { // imageNode.style.preferredSize = CGSize(width: 0, height: 0) // } // // let voteNodeSpec = ASRelativeLayoutSpec() // let pointsNodeSpec = ASRelativeLayoutSpec() // let commentsNodeSpec = ASRelativeLayoutSpec() // // linkFlairNode.style.flexGrow = 1.0 // linkFlairNode.style.flexShrink = 1.0 // authorFlairNode.style.flexGrow = 1.0 // authorFlairNode.style.flexShrink = 1.0 // // topRowStackSpec.alignItems = .center // topRowStackSpec.spacing = 5.0 // topRowStackSpec.children = topRowChildren // topRowStackSpec.style.flexShrink = 1.0 // topRowStackSpec.style.flexGrow = 1.0 // Make the images pretty if(header.s.iconImg.hasPrefix("http")) { let imageSize = CGSize(width: 64, height: 64) imageIconNode.style.preferredSize = imageSize imageIconNode.imageModificationBlock = { image in let width: CGFloat = 2 let color: UIColor = .black return image.makeRoundedImage(size: imageSize, borderWidth: width, color: color) } } else { imageIconNode.style.preferredSize = CGSize(width: 0, height: 0) } imageBannerNode.style.preferredSize = CGSize(width: constrainedSize.max.width, height: 100) imageIconNode.style.preferredSize = CGSize(width: 60, height: 60) let centerStack = ASStackLayoutSpec.vertical() centerStack.alignItems = .center centerStack.spacing = 5.0 centerStack.children = centerStackChildren centerStack.style.flexGrow = 1.0 centerStack.style.flexShrink = 1.0 let insetStack = ASInsetLayoutSpec(insets: UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0), child: centerStack) overlayStackSpec = ASOverlayLayoutSpec(child: imageBannerNode, overlay: insetStack) middleStackSpec.alignItems = .start middleStackSpec.spacing = 5.0 middleStackSpec.children = [overlayStackSpec!] middleStackSpec.style.flexShrink = 1.0 middleStackSpec.style.flexGrow = 1.0 horizontalStackSpec.alignItems = .start horizontalStackSpec.spacing = 5.0 horizontalStackSpec.children = [middleStackSpec] horizontalStackSpec.style.flexShrink = 1.0 horizontalStackSpec.style.flexGrow = 1.0 // // bottomRowStackSpec.alignItems = .center // bottomRowStackSpec.spacing = 5.0 // bottomRowStackSpec.children = bottomRowChildren // bottomRowStackSpec.style.flexShrink = 1.0 // bottomRowStackSpec.style.flexGrow = 1.0 // // leftSideStackSpec.alignItems = .center // leftSideStackSpec.spacing = 5.0 // leftSideStackSpec.children = [imageNode] // // pointsNodeSpec.verticalPosition = .start // pointsNodeSpec.children = [pointsNode] // pointsNodeSpec.horizontalPosition = .start // // commentsNodeSpec.verticalPosition = .start // commentsNodeSpec.children = [commentsNode] // commentsNodeSpec.horizontalPosition = .start // // voteNodeSpec.verticalPosition = .end // voteNodeSpec.children = [voteNode] // voteNodeSpec.horizontalPosition = .end // // rightSideStackSpec.alignItems = .center // rightSideStackSpec.spacing = 5.0 // rightSideStackSpec.children = [pointsNodeSpec, commentsNodeSpec, voteNodeSpec] centerStackSpec.centeringOptions = .XY centerStackSpec.children = [horizontalStackSpec] return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5), child: centerStackSpec) } }
gpl-3.0
8fd3b3813a0e829836742cfcd1e37c8a
44.060976
168
0.631664
4.792477
false
false
false
false
SASAbus/SASAbus-ios
SASAbus Watch Extension/Controller/Nearby/NearbyInterfaceController.swift
1
2287
import WatchKit import Foundation import CoreLocation class NearbyInterfaceController: WKInterfaceController { @IBOutlet var tableView: WKInterfaceTable! @IBOutlet var loadingText: WKInterfaceLabel! @IBOutlet var noNearbyText: WKInterfaceLabel! var nearbyBusStops = [BusStopDistance]() override func awake(withContext context: Any?) { super.awake(withContext: context) parseData() } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } func parseData() { let locationManager = CLLocationManager() locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers locationManager.requestAlwaysAuthorization() let lastLocation = locationManager.location guard let location = lastLocation else { Log.error("Cannot get last location") noNearbyText.setHidden(false) loadingText.setHidden(true) return } Log.info("Location: \(location)") let busStops = BusStopRealmHelper.nearestBusStops(location: location, count: 10) self.nearbyBusStops.removeAll() self.nearbyBusStops.append(contentsOf: busStops) DispatchQueue.main.async { self.loadingText.setHidden(true) if busStops.isEmpty { self.noNearbyText.setHidden(false) } else { self.noNearbyText.setHidden(true) } self.tableView.setNumberOfRows(self.nearbyBusStops.count, withRowType: "NearbyRowController") for (index, item) in busStops.enumerated() { let row = self.tableView.rowController(at: index) as! NearbyRowController row.name.setText(item.busStop.name()) row.city.setText(item.busStop.munic()) } } } override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { pushController(withName: "DeparturesInterfaceController", context: nearbyBusStops[rowIndex].busStop) } }
gpl-3.0
bc0dd66b54264402117aa0e587bd8967
27.949367
108
0.604285
5.834184
false
false
false
false
SSiming/ClipImage
ClipImage/ClipImage/ClipImageVC.swift
1
7731
// // ClipImageVC.swift // ClipImage // // Created by hujunhua on 13/05/2017. // Copyright © 2017 hujunhua. All rights reserved. // import UIKit protocol ClipImageVCDelegate { func clipImageVC(_ clipImageVC: ClipImageVC, didFinishClipingImage image: UIImage) } class ClipImageVC: UIViewController { let ScreenWidth = UIScreen.main.bounds.size.width let ScreenHeight = UIScreen.main.bounds.size.height let clipRectWidth = UIScreen.main.bounds.size.width * 0.8 let TimesThanMin: CGFloat = 5.0 var delegate: ClipImageVCDelegate? var image: UIImage! var scrollView: UIScrollView! var imageView: UIImageView! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black automaticallyAdjustsScrollViewInsets = false initUI() settingScrollViewZoomScale() } func initUI() { let maskView = UIView.init(frame: view.bounds) maskView.backgroundColor = UIColor.clear maskView.isUserInteractionEnabled = false let clipRectX = (ScreenWidth - clipRectWidth) / 2.0 let clipRectY = (ScreenHeight - clipRectWidth) / 2.0 let path = UIBezierPath.init(rect: view.bounds) let ovalPath = UIBezierPath.init(ovalIn: CGRect.init(x: clipRectX, y: clipRectY, width: clipRectWidth, height: clipRectWidth)) path.append(ovalPath) let shaperLayer = CAShapeLayer.init() shaperLayer.fillRule = .evenOdd shaperLayer.path = path.cgPath shaperLayer.fillColor = UIColor.black.withAlphaComponent(0.5).cgColor let whiteCircleLayer = CAShapeLayer.init() whiteCircleLayer.lineWidth = 2; whiteCircleLayer.path = ovalPath.cgPath whiteCircleLayer.fillColor = UIColor.clear.cgColor whiteCircleLayer.strokeColor = UIColor.white.cgColor shaperLayer.addSublayer(whiteCircleLayer) maskView.layer.addSublayer(shaperLayer) let bottomView = UIView.init(frame: CGRect.init(x: 0, y: ScreenHeight - 60, width: ScreenWidth, height: 60)) bottomView.backgroundColor = UIColor.white let confirmButton = UIButton.init(frame: CGRect.init(x: 20, y: 10, width: ScreenWidth - 40, height: 40)) confirmButton.backgroundColor = UIColor.black confirmButton.setTitle("Confirm", for: .normal) confirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) confirmButton.addTarget(self, action: #selector(ClipImageVC.confirmButtonAction(_:)), for: .touchUpInside) bottomView.addSubview(confirmButton) scrollView = UIScrollView.init(frame: view.bounds) scrollView.delegate = self scrollView.backgroundColor = UIColor.clear scrollView.contentInset = UIEdgeInsets.init(top: clipRectY, left: clipRectX, bottom: clipRectY, right: clipRectX) view.addSubview(scrollView) let imageViewH = image.size.height / image.size.width * ScreenWidth imageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: imageViewH)) imageView.image = image scrollView.addSubview(imageView) let offsetY = (scrollView.bounds.height - imageViewH) / 2.0 scrollView.setContentOffset(CGPoint.init(x: 0, y: -offsetY), animated: false) view.addSubview(maskView) view.addSubview(bottomView) } func settingScrollViewZoomScale() { let imageWidth = image.size.width let imageHeight = image.size.height if imageWidth > imageHeight { scrollView.minimumZoomScale = clipRectWidth / (imageHeight / imageWidth * ScreenWidth); } else { scrollView.minimumZoomScale = clipRectWidth / ScreenWidth; } scrollView.maximumZoomScale = (scrollView.minimumZoomScale) * TimesThanMin scrollView.zoomScale = scrollView.minimumZoomScale > 1 ? scrollView.minimumZoomScale : 1 } // MARK: - Action @objc func confirmButtonAction(_ button: UIButton) { let image = clipImage() delegate?.clipImageVC(self, didFinishClipingImage: image!) navigationController?.popViewController(animated: true) } // MARK: - Private func clipImage() -> UIImage? { let offset = scrollView.contentOffset let imageSize = imageView.image?.size let scale = (imageView.frame.size.width) / (imageSize?.width)! / image.scale let clipRectX = (ScreenWidth - clipRectWidth) / 2.0 let clipRectY = (ScreenHeight - clipRectWidth) / 2.0 let rectX = (offset.x + clipRectX) / scale let rectY = (offset.y + clipRectY) / scale let rectWidth = clipRectWidth / scale let rectHeight = rectWidth let rect = CGRect.init(x: rectX, y: rectY, width: rectWidth, height: rectHeight) let fixedImage = fixedImageOrientation(image) let resultImage = fixedImage?.cgImage?.cropping(to: rect) let clipImage = UIImage.init(cgImage: resultImage!) return clipImage; } func fixedImageOrientation(_ image: UIImage) -> UIImage? { if image.imageOrientation == .up { return image } let imageWidth = image.size.width let imageHeight = image.size.height let π = Double.pi var transform = CGAffineTransform.identity switch image.imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: imageWidth, y: imageHeight) transform = transform.rotated(by: CGFloat(π)) case .left, .leftMirrored: transform = transform.translatedBy(x: imageWidth, y: 0) transform = transform.rotated(by: CGFloat(π / 2)) case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: imageHeight) transform = transform.rotated(by: CGFloat(-π / 2)) default: break } switch image.imageOrientation { case .up, .upMirrored: transform = transform.translatedBy(x: imageWidth, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: imageHeight, y: 0) transform = transform.scaledBy(x: -1, y: 1) default: break } let context = CGContext.init(data: nil, width: Int(imageWidth), height: Int(imageHeight), bitsPerComponent: Int(image.cgImage!.bitsPerComponent), bytesPerRow: Int((image.cgImage?.bytesPerRow)!), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: (image.cgImage?.bitmapInfo.rawValue)!) context!.concatenate(transform) switch image.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context?.draw(image.cgImage!, in: CGRect.init(x: 0, y: 0, width: imageHeight, height: imageWidth)) default: context?.draw(image.cgImage!, in: CGRect.init(x: 0, y: 0, width: imageWidth, height: imageHeight)) } let fixedImage = UIImage.init(cgImage: context!.makeImage()!) return fixedImage } } extension ClipImageVC: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } }
mit
5dd1f789d194c15fe6af0bf8380ddd99
38.020202
134
0.624644
4.997413
false
false
false
false
manuelbl/WirekiteMac
WirekiteMacTest/Controllers/Ammeter.swift
1
1998
// // Wirekite for MacOS // // Copyright (c) 2017 Manuel Bleichenbacher // Licensed under MIT License // https://opensource.org/licenses/MIT // import Foundation class Ammeter { private static let InvalidValue = 0x7fffffff private let device: WirekiteDevice? private let i2cPort: PortID private let releasePort: Bool var ammeterAddress: Int = 0x40 init(device: WirekiteDevice, i2cPins: I2CPins) { self.device = device i2cPort = device.configureI2CMaster(i2cPins, frequency: 100000) releasePort = true initSensor() } init(device: WirekiteDevice, i2cPort: PortID) { self.device = device self.i2cPort = i2cPort releasePort = false initSensor() } deinit { if releasePort { device?.releaseI2CPort(i2cPort) } } func readAmps() -> Double { let value = read(register: 4, length: 2) if value == Ammeter.InvalidValue { return Double.nan } return Double(value) / 10 } private func initSensor() { write(register: 5, value: 4096) write(register: 0, value: 0x2000 | 0x1800 | 0x04000 | 0x0018 | 0x0007) } private func write(register: Int, value: Int) { var bytes: [UInt8] = [ UInt8(register), 0, 0 ] bytes[1] = UInt8((value >> 8) & 0xff) bytes[2] = UInt8(value & 0xff) let data = Data(bytes: bytes) device?.send(onI2CPort: i2cPort, data: data, toSlave: ammeterAddress) } private func read(register: Int, length: Int) -> Int { let bytes: [UInt8] = [ UInt8(register) ] let txData = Data(bytes: bytes) if let data = device!.sendAndRequest(onI2CPort: i2cPort, data: txData, toSlave: ammeterAddress, receiveLength: 2) { let bytes = [UInt8](data) return Int((Int16(bytes[0]) << 8) | Int16(bytes[1])) } return Ammeter.InvalidValue } }
mit
5ff628eb778dffb760389fa577c3d021
26.75
123
0.588589
3.672794
false
false
false
false
zvonicek/SpriteKit-Pong
TDT4240-pong/SKTUtils/Vector3.swift
12
6171
/* * Copyright (c) 2013-2014 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 CoreGraphics public struct Vector3: Equatable { public var x: CGFloat public var y: CGFloat public var z: CGFloat public init(x: CGFloat, y: CGFloat, z: CGFloat) { self.x = x self.y = y self.z = z } } /** * Returns true if two vectors have the same element values. */ public func == (lhs: Vector3, rhs: Vector3) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } /** * Returns true if all the vector elements are equal to the provided scalar. */ public func == (lhs: Vector3, rhs: CGFloat) -> Bool { return lhs.x == rhs && lhs.y == rhs && lhs.z == rhs } extension Vector3 { /** * A vector constant with value (0, 0, 0). */ static var zeroVector: Vector3 { return Vector3(x: 0, y: 0, z: 0) } /** * Returns true if all the vector elements are equal to the provided value. * * DEPRECATED: Use the == operator instead. */ public func equalToScalar(value: CGFloat) -> Bool { return x == value && y == value && z == value } /** * Returns the magnitude of the vector. */ public func length() -> CGFloat { return sqrt(x*x + y*y + z*z) } /** * Normalizes the vector and returns the result as a new vector. */ public func normalized() -> Vector3 { let scale = 1.0/length() return Vector3(x: x * scale, y: y * scale, z: z * scale) } /** * Normalizes the vector described by this Vector3 object. */ public mutating func normalize() { let scale = 1.0/length() x *= scale y *= scale z *= scale } /** * Calculates the dot product with another Vector3. */ public func dot(vector: Vector3) -> CGFloat { return Vector3.dotProduct(self, right: vector) } /** * Calculates the cross product with another Vector3. */ public func cross(vector: Vector3) -> Vector3 { return Vector3.crossProduct(self, right: vector) } /** * Calculates the dot product of two vectors. * * DEPRECATED: Use dot() instead. */ public static func dotProduct(left: Vector3, right: Vector3) -> CGFloat { return left.x * right.x + left.y * right.y + left.z * right.z } /** * Calculates the cross product of two vectors. * * DEPRECATED: Use cross() instead. */ public static func crossProduct(left: Vector3, right: Vector3) -> Vector3 { let crossProduct = Vector3(x: left.y * right.z - left.z * right.y, y: left.z * right.x - left.x * right.z, z: left.x * right.y - left.y * right.x) return crossProduct } } /** * Adds two Vector3 values and returns the result as a new Vector3. */ public func + (left: Vector3, right: Vector3) -> Vector3 { return Vector3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z) } /** * Increments a Vector3 with the value of another. */ public func += (inout left: Vector3, right: Vector3) { left = left + right } /** * Subtracts two Vector3 values and returns the result as a new Vector3. */ public func - (left: Vector3, right: Vector3) -> Vector3 { return Vector3(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z) } /** * Decrements a Vector3 with the value of another. */ public func -= (inout left: Vector3, right: Vector3) { left = left - right } /** * Multiplies two Vector3 values and returns the result as a new Vector3. */ public func * (left: Vector3, right: Vector3) -> Vector3 { return Vector3(x: left.x * right.x, y: left.y * right.y, z: left.z * right.z) } /** * Multiplies a Vector3 with another. */ public func *= (inout left: Vector3, right: Vector3) { left = left * right } /** * Multiplies the x,y,z fields of a Vector3 with the same scalar value and * returns the result as a new Vector3. */ public func * (vector: Vector3, scalar: CGFloat) -> Vector3 { return Vector3(x: vector.x * scalar, y: vector.y * scalar, z: vector.z * scalar) } /** * Multiplies the x,y,z fields of a Vector3 with the same scalar value. */ public func *= (inout vector: Vector3, scalar: CGFloat) { vector = vector * scalar } /** * Divides two Vector3 values and returns the result as a new Vector3. */ public func / (left: Vector3, right: Vector3) -> Vector3 { return Vector3(x: left.x / right.x, y: left.y / right.y, z: left.z / right.z) } /** * Divides a Vector3 by another. */ public func /= (inout left: Vector3, right: Vector3) { left = left / right } /** * Divides the x,y,z fields of a Vector3 by the same scalar value and * returns the result as a new Vector3. */ public func / (vector: Vector3, scalar: CGFloat) -> Vector3 { return Vector3(x: vector.x / scalar, y: vector.y / scalar, z: vector.z / scalar) } /** * Divides the x,y,z fields of a Vector3 by the same scalar value. */ public func /= (inout vector: Vector3, scalar: CGFloat) { vector = vector / scalar } /** * Performs a linear interpolation between two Vector3 values. */ public func lerp(#start: Vector3, #end: Vector3, #t: CGFloat) -> Vector3 { return start + (end - start) * t }
mit
b947b046d3b61806a73bd194980323db
27.05
82
0.650138
3.490385
false
false
false
false
ahoppen/swift
test/Inputs/conditional_conformance_basic_conformances_future.swift
6
25003
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public struct IsP3: P3 {} public struct Single<A> {} extension Single: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Single.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself %0, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE6normalyyF"(%swift.type* [[A]], i8** [[A_P2]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Single.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself %1, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func single_generic<T: P2>(_: T.Type) { takes_p1(Single<T>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF"(%swift.type* %0, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func single_concrete() { takes_p1(Single<IsP2>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances15single_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"( // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: i8** [[Single_P1]] // CHECK-SAME: ) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Single<IsP2> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable( // CHECK-SAME: %swift.protocol_conformance_descriptor* bitcast ( // CHECK-SAME: { i32, i32, i32, i32, i32, i32, i32, i16, i16, i32, i32 }* // CHECK-SAME: @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlMc" // CHECK-SAME: to %swift.protocol_conformance_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: i8*** [[CONDITIONAL_REQUIREMENTS]] // CHECK-SAME: ) // CHECK-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // TYPEBYNAME-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // TYPEBYNAME-NEXT: entry: // TYPEBYNAME-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // TYPEBYNAME-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8 // TYPEBYNAME-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // TYPEBYNAME-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // TYPEBYNAME: cacheIsNull: // TYPEBYNAME-NEXT: [[T0:%.*]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledNameAbstract({ i32, i32 }* @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMD") // TYPEBYNAME-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // TYPEBYNAME-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // TYPEBYNAME-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // TYPEBYNAME-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable // TYPEBYNAME-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8 // TYPEBYNAME-NEXT: br label %cont // TYPEBYNAME: cont: // TYPEBYNAME-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ] // TYPEBYNAME-NEXT: ret i8** [[T0]] // TYPEBYNAME-NEXT: } // TYPEBYNAME_PRESPECIALIZED-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // TYPEBYNAME_PRESPECIALIZED-NEXT: entry: // TYPEBYNAME_PRESPECIALIZED-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // TYPEBYNAME_PRESPECIALIZED-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8 // TYPEBYNAME_PRESPECIALIZED-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // TYPEBYNAME_PRESPECIALIZED-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // TYPEBYNAME_PRESPECIALIZED: cacheIsNull: // TYPEBYNAME_PRESPECIALIZED-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // TYPEBYNAME_PRESPECIALIZED-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // TYPEBYNAME_PRESPECIALIZED-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // TYPEBYNAME_PRESPECIALIZED-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable // TYPEBYNAME_PRESPECIALIZED-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8 // TYPEBYNAME_PRESPECIALIZED-NEXT: br label %cont // TYPEBYNAME_PRESPECIALIZED: cont: // TYPEBYNAME_PRESPECIALIZED-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ] // TYPEBYNAME_PRESPECIALIZED-NEXT: ret i8** [[T0]] // TYPEBYNAME_PRESPECIALIZED-NEXT: } public struct Double<B, C> {} extension Double: P1 where B: P2, C: P3 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Double.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself %0, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE6normalyyF"(%swift.type* [[B]], %swift.type* [[C]], i8** [[B_P2]], i8** [[C_P3]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Double.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself %1, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) { takes_p1(Double<U, V>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF"(%swift.type* %0, %swift.type* %1, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %U, %swift.type* %V) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %U.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** %V.P3, i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_generic_concrete<X: P2>(_: X.Type) { takes_p1(Double<X, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF"(%swift.type* %0, %swift.type* %X, i8** %X.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[Double_TYPE_Response:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"( // CHECK-SAME: i64 0, // CHECK-SAME: %swift.type* // CHECK-SAME: %X, // CHECK-SAME: %swift.type* bitcast ( // CHECK-SAME: i64* getelementptr inbounds ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: i64, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i32, i32 }>*, // CHECK-SAME: i64 // CHECK-SAME: }>, // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: i64, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i32, i32 }>*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances4IsP3VMf", // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) to %swift.type* // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: [[Double_TYPE:%[0-9]+]] = extractvalue %swift.metadata_response [[Double_TYPE_Response]], 0 // CHECK: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %X.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable( // CHECK-SAME: %swift.protocol_conformance_descriptor* bitcast ( // CHECK-SAME: { i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32, i32 }* // CHECK-SAME: @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlMc" // CHECK-SAME: to %swift.protocol_conformance_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* %3, // CHECK-SAME: i8*** [[CONDITIONAL_REQUIREMENTS]] // CHECK-SAME: ) // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"( // CHECK-SAME: %swift.type* [[Double_TYPE]], // CHECK-SAME: %swift.type* [[Double_TYPE]], // CHECK-SAME: i8** [[Double_P1]] // CHECK-SAME: ) // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_concrete_concrete() { takes_p1(Double<IsP2, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances016double_concrete_F0yyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"( // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: i8** [[Double_P1]] // CHECK-SAME: ) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Double<IsP2, IsP3> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable( // CHECK-SAME: %swift.protocol_conformance_descriptor* bitcast ( // CHECK-SAME: { i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32, i32 }* // CHECK-SAME: @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlMc" // CHECK-SAME: to %swift.protocol_conformance_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: i64, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: i8*** [[CONDITIONAL_REQUIREMENTS]] // CHECK-SAME: ) // CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } func dynamicCastToP1(_ value: Any) -> P1? { return value as? P1 } protocol P4 {} typealias P4Typealias = P4 protocol P5 {} struct SR7101<T> {} extension SR7101 : P5 where T == P4Typealias {}
apache-2.0
8bd8d6892e23b65841d489619757e5d3
57.418224
389
0.631364
3.049518
false
false
false
false
mikelbrownus/SwiftMythTVBackend
Sources/mythserver/model/Recorded.swift
1
1768
import MySQL import Foundation import SwiftyJSON import DotEnv public struct Recorded { public let recordid: Int public let title: String public let description: String public let filesize: Int public let chanid: Int public let programstart: Date public let programend: Date public let channelName: String public let channelNumber: String } extension Recorded { func toMySQLRow() -> ([String: Any]) { var data = [String: Any]() data["recordid"] = recordid data["title"] = title data["description"] = description data["channelName"] = channelName data["channelNumber"] = channelNumber data["filesize"] = filesize data["chanid"] = chanid data["programstart"] = programstart data["programend"] = programend return data } } extension Recorded { func toJSON() -> JSON { let formatter = DateFormatter() formatter.dateFormat = "MMM d, h:mm a" formatter.timeZone = TimeZone(abbreviation: env.get("DB_TZ") ?? "GMT") return JSON([ "title": title, "description": description, "channelName": channelName, "channelNumber": channelNumber, "filesize": Int(round((Double(filesize)/Double(1024))/Double(1024))), "chanid": Int(chanid), "startTimeInSecs": Int(programstart.timeIntervalSince1970), "programstart": formatter.string(from: programstart), "length": minutesBetweenDates( programstart, programend ) ]) } func minutesBetweenDates(_ startDate: Date, _ endDate: Date) -> Int { return Int(round((endDate.timeIntervalSinceNow - startDate.timeIntervalSinceNow) / 60)) } }
mit
fe263e94dc53f0806b2ceedda333396e
29.5
94
0.623303
4.64042
false
false
false
false
haskellswift/swift-package-manager
Sources/Basic/OptionParser.swift
2
4443
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ #if os(Linux) import Foundation // String.hasPrefix #endif public enum OptionParserError: Swift.Error { case unknownArgument(String) case multipleModesSpecified([String]) case expectedAssociatedValue(String) case unexpectedAssociatedValue(String, String) case invalidUsage(String) case noCommandProvided(String) } extension OptionParserError: CustomStringConvertible { public var description: String { switch self { case .expectedAssociatedValue(let arg): return "expected associated value for argument: \(arg)" case .unexpectedAssociatedValue(let arg, let value): return "unexpected associated value for argument: \(arg)=\(value)" case .multipleModesSpecified(let modes): return "multiple modes specified: \(modes)" case .unknownArgument(let cmd): return "unknown command: \(cmd)" case .invalidUsage(let hint): return "invalid usage: \(hint)" case .noCommandProvided(let hint): return "no command provided: \(hint)" } } } public protocol Argument { /** Attempt to convert the provided argument. If you need an associated value, call `pop()`, if there is no associated value we will throw. If the argument was passed `--foo=bar` and you don’t `pop` we also `throw` */ init?(argument: String, pop: @escaping () -> String?) throws } public func parseOptions<Mode: Argument, Flag: Argument>(arguments: [String]) throws -> (Mode?, [Flag]) where Mode: Equatable { var mode: Mode! var it = arguments.makeIterator() var kept = [String]() while let rawArg = it.next() { var popped = false let (arg, value) = split(rawArg) if let mkmode = try Mode(argument: arg, pop: { popped = true; return value ?? it.next() }) { guard mode == nil || mode == mkmode else { let modes = [mode!, mkmode].map{"\($0)"} throw OptionParserError.multipleModesSpecified(modes) } mode = mkmode if let value = value, !popped { throw OptionParserError.unexpectedAssociatedValue(arg, value) } } else { kept.append(rawArg) } } var flags = [Flag]() it = kept.makeIterator() while let arg = it.next() { var popped = false let (arg, value) = split(arg) if let flag = try Flag(argument: arg, pop: { popped = true; return value ?? it.next() }) { flags.append(flag) } else if arg.hasPrefix("-") { // attempt to split eg. `-xyz` to `-x -y -z` guard !arg.hasPrefix("--") else { throw OptionParserError.unknownArgument(arg) } guard arg != "-" else { throw OptionParserError.unknownArgument(arg) } var characters = arg.characters.dropFirst() func pop() -> String? { if characters.isEmpty { return nil } else { // thus we support eg. `-mwip` as `-m=wip` let str = String(characters) characters.removeAll() return str } } while !characters.isEmpty { let c = characters.removeFirst() guard let flag = try Flag(argument: "-\(c)", pop: pop) else { throw OptionParserError.unknownArgument(arg) } flags.append(flag) } } else { throw OptionParserError.unknownArgument(arg) } if let value = value, !popped { throw OptionParserError.unexpectedAssociatedValue(arg, value) } } return (mode, flags) } private func split(_ arg: String) -> (String, String?) { let chars = arg.characters if let ii = chars.index(of: "=") { let flag = chars.prefix(upTo: ii) let value = chars.suffix(from: chars.index(after: ii)) return (String(flag), String(value)) } else { return (arg, nil) } }
apache-2.0
3b94d78dd7ac64752ff5f5cfcf30a2e8
31.896296
127
0.582526
4.573635
false
false
false
false
attaswift/Attabench
BenchmarkRunner/BenchmarkProcess.swift
2
7715
// Copyright © 2017 Károly Lőrentey. // This file is part of Attabench: https://github.com/attaswift/Attabench // For licensing information, see the file LICENSE.md in the Git repository above. import Foundation import Darwin import BenchmarkIPC import BenchmarkModel public protocol BenchmarkDelegate { func benchmark(_ benchmark: BenchmarkProcess, didReceiveListOfTasks tasks: [String]) func benchmark(_ benchmark: BenchmarkProcess, willMeasureTask task: String, atSize size: Int) func benchmark(_ benchmark: BenchmarkProcess, didMeasureTask task: String, atSize size: Int, withResult time: Time) func benchmark(_ benchmark: BenchmarkProcess, didPrintToStandardOutput line: String) func benchmark(_ benchmark: BenchmarkProcess, didPrintToStandardError line: String) func benchmark(_ benchmark: BenchmarkProcess, didFailWithError error: String) func benchmarkDidStop(_ benchmark: BenchmarkProcess) } extension BenchmarkDelegate { public func benchmark(_ benchmark: BenchmarkProcess, didSendListOfTasks tasks: [String]) {} public func benchmark(_ benchmark: BenchmarkProcess, didFailWithError error: String) {} } public class BenchmarkProcess { private struct Delegate: CommandLineDelegate { unowned let benchmark: BenchmarkProcess init(_ benchmark: BenchmarkProcess) { self.benchmark = benchmark } func commandLineProcess(_ process: CommandLineProcess, didPrintToStandardOutput line: String) { precondition(process === benchmark.process) var line = line if line.last == "\n" { line.removeLast() } benchmark.delegate.benchmark(benchmark, didPrintToStandardOutput: line) } func commandLineProcess(_ process: CommandLineProcess, didPrintToStandardError line: String) { precondition(process === benchmark.process) var line = line if line.last == "\n" { line.removeLast() } benchmark.delegate.benchmark(benchmark, didPrintToStandardError: line) } func commandLineProcess(_ process: CommandLineProcess, channel: CommandLineProcess.Channel, didFailWithError error: Int32) { precondition(process === benchmark.process) guard error != 0 else { return } // EOF guard process.isRunning else { return } benchmark.fail(String(posixError: error)) } func commandLineProcess(_ process: CommandLineProcess, didExitWithState state: CommandLineProcess.ExitState) { precondition(process === benchmark.process) benchmark.cleanup() guard !benchmark.hasFailed else { return } switch state { case .exit(0): benchmark.delegate.benchmarkDidStop(benchmark) case .exit(let code): benchmark.fail("Process exited with code \(code)") case .uncaughtSignal(SIGTERM): benchmark.fail("Process terminated") case .uncaughtSignal(SIGKILL): benchmark.fail("Process killed") case .uncaughtSignal(let signal): benchmark.fail(String(signal: signal)) } } } public let url: URL public let delegate: BenchmarkDelegate public let delegateQueue: DispatchQueue public let command: BenchmarkIPC.Command let fm = FileManager() let temporaryFolder: URL let reportQueue = DispatchQueue(label: "org.attaswift.Attabench.report") var reportChannel: DispatchIO var process: CommandLineProcess! = nil var killTimer: DispatchSourceTimer? = nil var hasFailed = false public init(url: URL, command: Command, delegate: BenchmarkDelegate, on delegateQueue: DispatchQueue) throws { let input = try JSONEncoder().encode(command) self.url = url self.delegate = delegate self.delegateQueue = delegateQueue self.command = command self.temporaryFolder = try fm.createTemporaryFolder("Attabench.XXXXXXX") let reportPipe = temporaryFolder.appendingPathComponent("report.fifo") do { // Create report channel. try fm.createFIFO(at: reportPipe) let reportFD = open(reportPipe.path, O_RDWR) // We won't write, but having it prevents early EOF in DispatchIO guard reportFD != -1 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [NSURLErrorKey: reportPipe]) } reportChannel = DispatchIO(type: .stream, fileDescriptor: reportFD, queue: reportQueue, cleanupHandler: { result in close(reportFD) }) reportChannel.setLimit(lowWater: 1) reportChannel.setInterval(interval: .milliseconds(100)) reportChannel.readRecords(on: delegateQueue, delimitedBy: 0x0A) { chunk in switch chunk { case .endOfFile: self.fail("Report file closed") case .error(ECANCELED): break // Ignore case .error(let error): self.fail(String(posixError: error)) case .record(let data): self.processReport(data) } } } catch { try? fm.removeItem(at: temporaryFolder) throw error } // Create process self.process = CommandLineProcess(launchPath: "/bin/sh", workingDirectory: url.path, arguments: ["run.sh", "attabench", reportPipe.path], delegate: Delegate(self), on: delegateQueue) self.process.launch() if !input.isEmpty { self.process.sendToStandardInput(input) } self.process.closeStandardInput() } public func stop() { guard process.isRunning else { return } guard killTimer == nil else { return } process.terminate() let timer = DispatchSource.makeTimerSource(flags: [], queue: reportQueue) timer.setEventHandler { self.process.kill() } timer.resume() timer.schedule(deadline: .now() + 2.0, leeway: .milliseconds(250)) killTimer = timer } private func cleanup() { reportChannel.close(flags: []) if let timer = killTimer { timer.cancel() self.killTimer = nil } try? fm.removeItem(at: self.temporaryFolder) } private func fail(_ error: String) { guard !hasFailed else { return } hasFailed = true stop() delegate.benchmark(self, didFailWithError: error) } private func processReport(_ data: Data) { do { let report = try JSONDecoder().decode(BenchmarkIPC.Report.self, from: data) switch report { case let .list(tasks: tasks): delegate.benchmark(self, didReceiveListOfTasks: tasks) case let .begin(task: task, size: size): delegate.benchmark(self, willMeasureTask: task, atSize: size) case let .finish(task: task, size: size, time: time): delegate.benchmark(self, didMeasureTask: task, atSize: size, withResult: Time(time)) } } catch { if let string = String(data: data, encoding: .utf8) { fail("Corrupt report received: \(string)") } else { fail("Corrupt report received: \(data)") } } } }
mit
c75e5fc49a47d0adce61323ccde3ca65
40.021277
132
0.608921
5.189771
false
false
false
false
notjosh/OkayButHowDoYouFeel
OkayButHowDoYouFeel/ViewController.swift
1
3610
// // ViewController.swift // OkayButHowDoYouFeel // // Created by joshua may on 22/2/17. // Copyright © 2017 joshua may. All rights reserved. // import Cocoa import SpriteKit let FontSize: CGFloat = 96 class ViewController: NSViewController { @IBOutlet var skView: SKView! override func viewDidLoad() { super.viewDidLoad() let word = "FUCKFUCKFUCKFUCKFUCKFUCKFUCK" let whatever = whtaever(word: word) let slices = whatever.slices let size16x9 = CGSize(width: whatever.size.height * 16/9 * 2, height: whatever.size.height * 1.5) let scene = AnotherFeelingScene(size: size16x9, sliceImages: slices) scene.scaleMode = .aspectFit scene.backgroundColor = .white skView.presentScene(scene) skView.ignoresSiblingOrder = true skView.showsFPS = true skView.showsNodeCount = true } func whtaever(word: String) -> NSImage { let nsWord = word as NSString let attributes = [ NSFontAttributeName: NSFont.boldSystemFont(ofSize: FontSize), NSForegroundColorAttributeName: NSColor.black, ] let size = nsWord.size(withAttributes: attributes) let image = NSImage(size: size) image.lockFocus() nsWord.draw(at: NSPoint.zero, withAttributes: attributes) image.unlockFocus() return image } } extension NSColor { var isEmpty: Bool { if redComponent > 0.99 && greenComponent > 0.99 && blueComponent > 0.99 { return true } if alphaComponent < 0.01 { return true } return false } } extension NSImage { var yeahBut: NSBitmapImageRep { let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)! bitmap.size = size NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrent(NSGraphicsContext.init(bitmapImageRep: bitmap)) draw(at: NSPoint(x: 0, y: 0), from: NSRect.zero, operation: .sourceOver, fraction: 1) NSGraphicsContext.restoreGraphicsState() return bitmap } var slices: [NSImage] { var _slices: [NSImage] = [] for x in 0..<Int(self.size.width) { let slice = self.slice(from: NSRect(x: CGFloat(x), y: 0, width: 1, height: self.size.height)) _slices.append(slice) } return _slices } func slice(from fromRect: NSRect) -> NSImage { let targetRect = NSRect(x: 0, y: 0, width: fromRect.width, height: fromRect.height) let result = NSImage(size: targetRect.size) result.lockFocus() self.draw(in: targetRect, from: fromRect, operation: .copy, fraction: 1) result.unlockFocus() return result } }
mit
605c6b704f9d53022d91644aa337b0bb
26.135338
91
0.522305
5.148359
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00551-swift-nominaltypedecl-getdeclaredtypeincontext.swift
1
545
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f: P { typealias F = { } struct B<T where A.B : P { let g = { } let h == b.init(f: Array<T.c = e, V, AnyObject) { var b: (v: A>(e)" var f = 0
apache-2.0
8ca5599c6013a86c0ee155e040fe7618
31.058824
79
0.691743
3.224852
false
false
false
false
adrfer/swift
validation-test/stdlib/StringSlicesConcurrentAppend.swift
3
3145
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import SwiftPrivatePthreadExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif // 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. #if _runtime(_ObjC) import ObjectiveC #endif var StringTestSuite = TestSuite("String") extension String { var bufferID: UInt { return unsafeBitCast(_core._owner, UInt.self) } var capacityInBytes: Int { return _core.nativeBuffer!.capacity } } // Swift.String has an optimization that allows us to append to a shared string // buffer. Make sure that it works correctly when two threads try to append to // different non-shared strings that point to the same shared buffer. enum ThreadID { case Primary case Secondary } var barrierVar: UnsafeMutablePointer<_stdlib_pthread_barrier_t> = nil var sharedString: String = "" var secondaryString: String = "" func barrier() { var ret = _stdlib_pthread_barrier_wait(barrierVar) expectTrue(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) } func sliceConcurrentAppendThread(tid: ThreadID) { for i in 0..<100 { barrier() if tid == .Primary { // Get a fresh buffer. sharedString = "" sharedString.appendContentsOf("abc") sharedString.reserveCapacity(16) expectLE(16, sharedString.capacityInBytes) } barrier() // Get a private string. var privateString = sharedString barrier() // Append to the private string. if tid == .Primary { privateString.appendContentsOf("def") } else { privateString.appendContentsOf("ghi") } barrier() // Verify that contents look good. if tid == .Primary { expectEqual("abcdef", privateString) } else { expectEqual("abcghi", privateString) } expectEqual("abc", sharedString) // Verify that only one thread took ownership of the buffer. if tid == .Secondary { secondaryString = privateString } barrier() if tid == .Primary { expectTrue( (privateString.bufferID == sharedString.bufferID) != (secondaryString.bufferID == sharedString.bufferID)) } } } StringTestSuite.test("SliceConcurrentAppend") { barrierVar = UnsafeMutablePointer.alloc(1) barrierVar.initialize(_stdlib_pthread_barrier_t()) var ret = _stdlib_pthread_barrier_init(barrierVar, nil, 2) expectEqual(0, ret) let (createRet1, tid1) = _stdlib_pthread_create_block( nil, sliceConcurrentAppendThread, .Primary) let (createRet2, tid2) = _stdlib_pthread_create_block( nil, sliceConcurrentAppendThread, .Secondary) expectEqual(0, createRet1) expectEqual(0, createRet2) let (joinRet1, _) = _stdlib_pthread_join(tid1!, Void.self) let (joinRet2, _) = _stdlib_pthread_join(tid2!, Void.self) expectEqual(0, joinRet1) expectEqual(0, joinRet2) ret = _stdlib_pthread_barrier_destroy(barrierVar) expectEqual(0, ret) barrierVar.destroy() barrierVar.dealloc(1) } runAllTests()
apache-2.0
16015b2968080dbce15331b5b84eb8ab
24.362903
79
0.697933
3.97598
false
true
false
false
Woooop/WPPrintBoard
WPPrintBoardDemo/WPPrintBoardDemo/ViewController.swift
1
7574
// // ViewController.swift // WPPrintBoardDemo // // Created by Wupeng on 8/11/16. // Copyright © 2016 Wooop. All rights reserved. // import UIKit class ViewController: UIViewController { let screenWidth = UIScreen.mainScreen().bounds.width let screenHeight = UIScreen.mainScreen().bounds.height var printBoard : WPPrintBoard? var bottomView : UIView? var colorToolBoard : UIView? var fontToolBoard : UIView? var imageView : UIImageView? override func viewDidLoad() { super.viewDidLoad() let bgImageView = UIImageView(image: UIImage(named: "apple")) bgImageView.frame = UIScreen.mainScreen().bounds self.view.addSubview(bgImageView) self.imageView = UIImageView(frame: CGRectMake(0, 0, screenWidth, screenHeight - 44)) self.view.addSubview(self.imageView!) let board = WPPrintBoard(frame: CGRectMake(0, 0, screenWidth, screenHeight - 44)) self.view.addSubview(board) self.printBoard = board self.printBoard?.delegate = self setUpBottomToolView() setUpcolorToolBoard() setUpFontToolBoard() } func setUpBottomToolView(){ let buttonWidth = screenWidth / 5 let bottomView = UIView(frame: CGRectMake(0, screenHeight - 44, screenWidth, 44)) bottomView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) let buttonTitleArray = Array(arrayLiteral: "颜色","上一步","清空","下一步","宽度") for index in 0...4 { let button = UIButton.init(frame: CGRectMake(CGFloat(index) * buttonWidth, 0, buttonWidth, 44)) button.setTitle(buttonTitleArray[index], forState: .Normal) button.setTitleColor(UIColor.blackColor(), forState: .Normal) if index == 0 { button.addTarget(self, action: #selector(colorButtonClick), forControlEvents: .TouchUpInside) } else if index == 1 { button.addTarget(self, action: #selector(revokeButtonClick), forControlEvents: .TouchUpInside) } else if index == 2 { button.addTarget(self, action: #selector(clearButtonClick), forControlEvents: .TouchUpInside) } else if index == 3 { button.addTarget(self, action: #selector(recoverButtonClick), forControlEvents: .TouchUpInside) } else { button.addTarget(self, action: #selector(fontButtonClick), forControlEvents: .TouchUpInside) } bottomView.addSubview(button) } self.bottomView = bottomView self.view.addSubview(bottomView) } func setUpcolorToolBoard(){ let buttonWidth = (UIScreen.mainScreen().bounds.width / 3) let colorToolView = UIView(frame: CGRectMake(0, screenHeight, screenWidth, 44)) for index in 0...2 { let button = UIButton.init(frame: CGRectMake(CGFloat(index) * buttonWidth, 0, buttonWidth, 44)) button.tag = index button.addTarget(self, action: #selector(colorToolSelect(_:)), forControlEvents: .TouchUpInside) if index == 0 { button.backgroundColor = UIColor.blackColor() } else if index == 1 { button.backgroundColor = UIColor.redColor() } else { button.backgroundColor = UIColor.greenColor() } colorToolView.addSubview(button) } self.colorToolBoard = colorToolView self.view.addSubview(self.colorToolBoard!) } func setUpFontToolBoard(){ let buttonWidth = (UIScreen.mainScreen().bounds.width / 3) let fontToolView = UIView(frame: CGRectMake(0, screenHeight, screenWidth, 44)) fontToolView.backgroundColor = UIColor.lightGrayColor() for index in 0...2 { let button = UIButton.init(frame: CGRectMake(CGFloat(index) * buttonWidth, 0, buttonWidth, 44)) button.addTarget(self, action: #selector(fontToolSelect(_:)), forControlEvents: .TouchUpInside) button.setTitleColor(UIColor.blackColor(), forState: .Normal) if index == 0 { button.tag = 3 button.setTitle("3", forState: .Normal) } else if index == 1 { button.tag = 10 button.setTitle("10", forState: .Normal) } else { button.tag = 23 button.setTitle("23", forState: .Normal) } fontToolView.addSubview(button) } self.fontToolBoard = fontToolView self.view.addSubview(self.fontToolBoard!) } func colorButtonClick(){ UIView.animateWithDuration(0.3, animations: { self.bottomView?.frame = CGRectMake(0, self.screenHeight, self.screenWidth, 44) }) { (Bool) in UIView.animateWithDuration(0.3, animations: { self.colorToolBoard?.frame = CGRectMake(0, self.screenHeight - 44, self.screenWidth, 44) }) } } func clearButtonClick() { self.printBoard!.clearBoard() } func revokeButtonClick() { self.printBoard!.revoke() } func recoverButtonClick() { self.printBoard?.recover() } func fontButtonClick(){ UIView.animateWithDuration(0.3, animations: { self.bottomView?.frame = CGRectMake(0, self.screenHeight, self.screenWidth, 44) }) { (Bool) in UIView.animateWithDuration(0.3, animations: { self.fontToolBoard?.frame = CGRectMake(0, self.screenHeight - 44, self.screenWidth, 44) }) } } func colorToolSelect(button : UIButton){ self.printBoard?.setPenColor(button.backgroundColor!.CGColor) UIView.animateWithDuration(0.3, animations: { self.colorToolBoard?.frame = CGRectMake(0, self.screenHeight, self.screenWidth, 44) }) { (Bool) in UIView.animateWithDuration(0.3, animations: { self.bottomView?.frame = CGRectMake(0, self.screenHeight - 44, self.screenWidth, 44) }) } } func fontToolSelect(button : UIButton) { self.printBoard?.setPenWidth(CGFloat(button.tag)) UIView.animateWithDuration(0.3, animations: { self.fontToolBoard?.frame = CGRectMake(0, self.screenHeight, self.screenWidth, 44) }) { (Bool) in UIView.animateWithDuration(0.3, animations: { self.bottomView?.frame = CGRectMake(0, self.screenHeight - 44, self.screenWidth, 44) }) } } func printSixMethod(){ let sixMethodView = WPPrintSixMethod(frame: UIScreen.mainScreen().bounds) sixMethodView.backgroundColor = UIColor.lightGrayColor() self.view.addSubview(sixMethodView) } func printImage(){ let printTool = WPPrintWithUIImge() let imageView = UIImageView(image: printTool.printImage()) self.view.addSubview(imageView) } func printWithCtx(){ let view = WPPrintWithCtx(frame: UIScreen.mainScreen().bounds) self.view.addSubview(view) view.backgroundColor = UIColor.whiteColor() } } extension ViewController : WPPrintBoardDelegate { func didNeedToUpdageImage(image: UIImage) { self.imageView?.image = image } }
mit
86354072dc6ce01c074ebc548c1c02a7
35.82439
111
0.599682
4.836003
false
false
false
false
tensorflow/swift-models
Tests/RecommendationModelTests/DLRMTests.swift
1
3744
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow import XCTest @testable import RecommendationModels final class DLRMTests: XCTestCase { override class func setUp() { Context.local.learningPhase = .inference } func testDLRM() { let nDense = 9 let dimEmbed = 4 let bottomMLPSize = [8, 4] let topMLPSize = [11, 4] let batchSize = 10 let model = DLRM( nDense: nDense, mSpa: dimEmbed, lnEmb: [10, 20], lnBot: bottomMLPSize, lnTop: topMLPSize) let result = model(denseInput: Tensor(ones: [batchSize, nDense]), sparseInput: [Tensor([7, 3, 1, 3, 1, 6, 7, 8, 9, 2]), Tensor([17, 13, 19, 0, 1, 6, 7, 8, 9, 10])]) XCTAssertEqual([batchSize], result.shape) } func testDLRMTraining() { let trainingSteps = 400 let nDense = 9 let dimEmbed = 4 let bottomMLPSize = [8, 4] let topMLPSize = [11, 4] let batchSize = 10 func lossFunc(predicted: Tensor<Float>, labels: Tensor<Float>) -> Tensor<Float> { let difference = predicted - labels let squared = difference * difference return squared.sum() } let trainingData = DLRMInput(dense: Tensor(randomNormal: [batchSize, nDense]), sparse: [Tensor([7, 3, 1, 3, 1, 6, 7, 8, 9, 2]), Tensor([17, 13, 19, 0, 1, 6, 7, 8, 9, 10])]) let labels = Tensor<Float>([1,0,0,1,1,1,0,1,0,1]) // Sometimes DLRM on such a small dataset can get "stuck" in a bad initialization. // To ensure a reliable test, we give ourselves a few reinitializations. for attempt in 1...5 { var model = DLRM( nDense: nDense, mSpa: dimEmbed, lnEmb: [10, 20], lnBot: bottomMLPSize, lnTop: topMLPSize) let optimizer = SGD(for: model, learningRate: 0.1) for step in 0...trainingSteps { let (loss, grads) = valueWithGradient(at: model) { model in lossFunc(predicted: model(trainingData), labels: labels) } if step % 50 == 0 { print(step, loss) if round(model(trainingData)) == labels { return } // Success } if step > 300 && step % 50 == 0 { print("\n\n-----------------------------------------") print("Step: \(step), loss: \(loss)\nGrads:\n\(grads)\nModel:\n\(model)") } optimizer.update(&model, along: grads) } print("Final model outputs (attempt: \(attempt)):\n\(model(trainingData))\nTarget:\n\(labels)") } XCTFail("Could not perfectly fit a single mini-batch after 5 reinitializations.") } } extension DLRMTests { static var allTests = [ ("testDLRM", testDLRM), ("testDLRMTraining", testDLRMTraining), ] }
apache-2.0
4ff7279ccab8781650c431838f217801
36.44
107
0.539797
4.323326
false
true
false
false
jpchmura/JPCActivityIndicatorButton
Source/ActivityIndicatorButton.swift
1
41797
// // ActivityIndicatorButton.swift // JPC.ActivityIndicatorButton // // Created by Jon Chmura on 3/9/15 (Happy Apple Watch Day!). // Copyright (c) 2015 Jon Chmura. All rights reserved. // /* The MIT License (MIT) Copyright (c) 2015 jpchmura 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 private extension CGRect { var center: CGPoint { get { return CGPoint(x: self.midX, y: self.midY) } } } private extension UIColor { func colorWithSaturation(_ sat: CGFloat) -> UIColor { var hue: CGFloat = 0, satOld: CGFloat = 0, bright: CGFloat = 0, alpha: CGFloat = 0 self.getHue(&hue, saturation: &satOld, brightness: &bright, alpha: &alpha) return UIColor(hue: hue, saturation: sat, brightness: bright, alpha: alpha) } } /** Defines the Style of the button. - Outline: For this style the button is clear. The image is tinted based on the current tint color. The button "track" outlines the image. This is comparible to the App Store download button. - Solid: In this style the button has a solid background. The background color is the current tint color and the image is tinted with the current foreground color. This is comparible to Google Material Design. */ public enum ActivityIndicatorButtonStyle { case outline, solid } /** Defines the state of the spinning and progress animations. - Inactive: No activity. In this state the ActivityIndicatorButton acts only like a button. - Spinning: A spinner analogous to UIActivityIndicator is animated around the bounds of the button. - Percentage: A circular progress bar surrounds the button. The value represents the percentage filled. */ public enum ActivityIndicatorButtonProgressBarStyle: Equatable { case inactive, spinning, percentage(value: Float) } /** * This struct defines the current state of an ActivityIndicatorButton. */ public struct ActivityIndicatorButtonState: Equatable { /// An optional property to help identify this button. Does not effect rendering is any way. Must be set to use the "SavedStates" feature. public let name: String? /// If this is set it will override the tintColor property on the button. public var tintColor: UIColor? /// If this is set it will override the "normalTrackColor" property on the button. public var trackColor: UIColor? /// If this is set it will override the "normalforegroundColor" property on the button. public var foregroundColor: UIColor? /// Optionally provide an image for this state. It is centered in the button. public var image: UIImage? /// The activity state of the button. /// :see: ActivityIndicatorButtonProgressBarStyle public var progressBarStyle: ActivityIndicatorButtonProgressBarStyle /** Default initializer. No properties are required. All have default values. - parameter name: Default value is nil - parameter tintColor: Default value is nil - parameter trackColor: Default value is nil - parameter foregroundColor: Default value is nil - parameter image: Default value is nil - parameter progressBarStyle: Default value is .Inactive */ public init(name: String? = nil, tintColor: UIColor? = nil, trackColor: UIColor? = nil, foregroundColor: UIColor? = nil, image: UIImage? = nil, progressBarStyle: ActivityIndicatorButtonProgressBarStyle = .inactive) { self.name = name self.tintColor = tintColor self.trackColor = trackColor self.foregroundColor = foregroundColor self.image = image self.progressBarStyle = progressBarStyle } /** Convenience function to set the progressBarStyle to .Percentage(value: value) */ public mutating func setProgress(_ value: Float) { self.progressBarStyle = .percentage(value: value) } } /* We need to have custom support for Equatable since on of our states has an input argument. */ public func == (lhs: ActivityIndicatorButtonProgressBarStyle, rhs: ActivityIndicatorButtonProgressBarStyle) -> Bool { switch lhs { case .inactive: switch rhs { case .inactive: return true default: return false } case .spinning: switch rhs { case .spinning: return true default: return false } case .percentage(let lhsValue): switch rhs { case .percentage(let rhsValue): return lhsValue == rhsValue default: return false } } } public func == (lhs: ActivityIndicatorButtonState, rhs: ActivityIndicatorButtonState) -> Bool { return lhs.tintColor == rhs.tintColor && lhs.trackColor == rhs.trackColor && lhs.image == rhs.image && lhs.progressBarStyle == rhs.progressBarStyle } @IBDesignable open class ActivityIndicatorButton: UIControl { // MARK: - Public API open override var isEnabled: Bool { didSet { self.updateAllColors() } } // MARK: State /// Internal storage of activityState fileprivate var _activityState: ActivityIndicatorButtonState = ActivityIndicatorButtonState(progressBarStyle: .inactive) /// Set the ActivityIndicatorButtonState. /// You may set custom defined activity states or directly modify the values here. /// Animation is implicit. (i.e. this is equivalent to calling transitionActivityState(toState: animated: true) /// :see: transitionActivityState(toState:animated:) open var activityState: ActivityIndicatorButtonState { get { return _activityState } set { _activityState = newValue self.updateForNextActivityState(animated: true) } } /** Set activityState with optional animation :see: activityState */ open func transitionActivityState(_ toState: ActivityIndicatorButtonState, animated: Bool = true) { self._activityState = toState self.updateForNextActivityState(animated: animated) } /// Returns the tintColor that is currently being used. If the current state provides no tint color self.tintColor is returned. /// :see: activityState /// :see: ActivityIndicatorButtonState open var tintColorForCurrentActivityState: UIColor { if let color = self.activityState.tintColor { return color } return self.tintColor } /// Returns the trackColor that is currently being used. If the current state provides no tint color self.normalTrackColor is returned. /// :see: activityState /// :see: ActivityIndicatorButtonState open var trackColorForCurrentActivityState: UIColor { if let color = self.activityState.trackColor { return color } return self.normalTrackColor } /// Returns the foregroundColor that is currently being used. If the current state provides no tint color self.normalForegroundColor is returned. /// :see: activityState /// :see: ActivityIndicatorButtonState open var foregroundColorForCurrentActivityState: UIColor { if let color = self.activityState.foregroundColor { return color } return self.normalForegroundColor } /// The color of the outline around the button. A track for the Progress Bar. /// This value may be overridden in ActivityIndicatorButtonState /// :see: activityState /// :see: ActivityIndicatorButtonState /// :see: trackColorForCurrentActivityState @IBInspectable open var normalTrackColor: UIColor = UIColor.lightGray { didSet { updateAllColors() } } /// The color of the image. Ignored when style == .Outline. /// This value may be overridden in ActivityIndicatorButtonState /// :see: activityState /// :see: ActivityIndicatorButtonState /// :see: foregroundColorForCurrentActivityState @IBInspectable open var normalForegroundColor: UIColor = UIColor.white { didSet { updateAllColors() } } /// Set the image of the current activityState /// This is equivalent to creating a new ActivityIndicatorButtonState and setting it to activityState /// :see: activityState /// :see: ActivityIndicatorButtonState @IBInspectable open var image: UIImage? { get { return self.activityState.image } set { self.activityState.image = newValue } } // MARK: State Animations /// Defines the length of the animation for ActivityState transitions. open var animationDuration: CFTimeInterval = 0.2 /// The timing function for ActivityState transitions. open var animationTimingFunction: CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // MARK: Hit Ripple Animation /// The distance past the edge of the button which the ripple animation will propagate on touch up and touch down @IBInspectable open var hitAnimationDistance: CGFloat = 5.0 /// The duration of the ripple hit animation @IBInspectable open var hitAnimationDuration: CFTimeInterval = 0.5 /// The color of the touch down and touch up ripple animation. Default value is UIColor.grayColor().colorWithAlphaComponent(0.5). @IBInspectable open var hitAnimationColor: UIColor = UIColor.gray.withAlphaComponent(0.5) // MARK: Style /// The color of the drop shadow or UIColor.clearColor() if you do not wish to display a shadow. The shadow never drawn is useSolidColorButtons is false. /// :see: useSolidColorButtons @IBInspectable open var shadowColor: UIColor = UIColor.black /// If true the circular background of this control is colored with the tint color and the image is colored white. Otherwise the background is clear and the image is tinted. Image color is only adjusted if it is a template image. /// :see: ActivityIndicatorButtonStyle @IBInspectable open var style: ActivityIndicatorButtonStyle = .solid { didSet { self.updateAllColors() } } // MARK: UI Configuration /// The width of the circular progress bar / activity indicator @IBInspectable open var progressBarWidth: CGFloat = 3 { didSet { self.updateButtonConstains() self.updateForCurrentBounds() } } /// The width of the track outline separating the progress bar from the button @IBInspectable open var trackWidth: CGFloat = 1.5 { didSet { self.updateButtonConstains() self.updateForCurrentBounds() } } /// The minimum amount of padding between the image and the side of the button @IBInspectable open var minimumImagePadding: CGFloat = 5 { didSet { self.updateButtonConstains() self.updateForCurrentBounds() } } // MARK: - State Management /// Internal storage of saved states fileprivate var savedStates: [String : ActivityIndicatorButtonState] = [:] /// The number of ActivityIndicatorButtonState stored open var savedStatesCount: Int { return savedStates.count } /** Store an ActivityIndicatorButtonState for simple access - parameter name: The key used to store the state. It doesn't have to be equal to state.name but it is probably good practice. For this API the name property on state is not required. - returns: The ActivityIndicatorButtonState or nil if a saved state could not be found. */ open subscript (name: String) -> ActivityIndicatorButtonState? { get { return savedStates[name] } set { savedStates[name] = newValue } } /** Convenience API for saving a group of states. - parameter states: An array of states. The name property MUST be set. If not an assertion is triggered. The states are keyed based on the value of "name". */ open func saveStates(_ states: [ActivityIndicatorButtonState]) { for aState in states { assert(aState.name != nil, "All saved states must have a name") self[aState.name!] = aState } } /** Convenience API for setting a saved state. Equivalent to button.activityState = button["name of state"] - parameter name: The key used to access the saved state - parameter animated: If animated is desired - returns: True is the state was found in saved states. */ open func transitionSavedState(_ name: String, animated: Bool = true) -> Bool { if let state = self[name] { self.transitionActivityState(state, animated: animated) return true } return false } // MARK: - Initialization public init() { super.init(frame: CGRect.zero) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } fileprivate func commonInit() { initialLayoutSetup() updateAllColors() updateForNextActivityState(animated: false) // Observe touch down and up for fire ripple animations self.addTarget(self, action: #selector(ActivityIndicatorButton.handleTouchUp(_:)), for: .touchUpInside) self.addTarget(self, action: #selector(ActivityIndicatorButton.handleTouchDown(_:)), for: .touchDown) } struct Constants { struct Layout { static let outerPadding: CGFloat = 1 /// The intrinsicContentSize if no images are provided. If images are provided this is the intrinsicContentSize. static let defaultContentSize: CGSize = CGSize(width: 35.0, height: 35.0) } struct Track { static let StartAngle = CGFloat(-M_PI_2) // Start angle is pointing directly upwards on the screen. This is where progress animations will begin static let EndAngle = CGFloat(3 * M_PI_2) } } // MARK: - IBDesignable open override func prepareForInterfaceBuilder() { // TODO: Improve rendering for interface builder preview } // MARK: - State Animations /// Holds the currently rendered State fileprivate var renderedActivityState: ActivityIndicatorButtonState? /** Does the real work of transitioning from one ActivityState to the next. If previous state is set will also update out of that state. */ fileprivate func updateForNextActivityState(animated: Bool) { struct DisplayState { let trackVisible: Bool let progressBarVisible: Bool let tintColor: UIColor let trackColor: UIColor let image: UIImage? let progressBarStyle: ActivityIndicatorButtonProgressBarStyle } var nextDisplayState = DisplayState( trackVisible: style == .solid || activityState.progressBarStyle != .spinning, progressBarVisible: activityState.progressBarStyle != .inactive, tintColor: tintColorForCurrentActivityState, trackColor: trackColorForCurrentActivityState, image: activityState.image, progressBarStyle: activityState.progressBarStyle) var prevDisplayState = DisplayState( trackVisible: backgroundView.shapeLayer.opacity > 0.5, progressBarVisible: progressView.progressLayer.opacity > 0.5, tintColor: UIColor(cgColor: (self.style == .solid ? backgroundView.shapeLayer.fillColor : backgroundView.shapeLayer.strokeColor)!), trackColor: UIColor(cgColor: backgroundView.shapeLayer.strokeColor!), image: imageView.image, progressBarStyle: renderedActivityState != nil ? renderedActivityState!.progressBarStyle : .inactive) // Progress View and Background View animations struct OpacityAnimation { let toValue: Float let fromValue: Float init(hidden: Bool) { self.toValue = hidden ? 0.0 : 1.0 self.fromValue = hidden ? 1.0 : 0.0 } func addToLayer(_ layer: CALayer, duration: CFTimeInterval, function: CAMediaTimingFunction) { let opacityanim = CABasicAnimation(keyPath: "opacity") opacityanim.toValue = self.toValue opacityanim.fromValue = self.fromValue opacityanim.duration = duration opacityanim.timingFunction = function layer.add(opacityanim, forKey: "opacity") layer.opacity = toValue } func setNoAnimation(_ layer: CALayer) { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) layer.opacity = toValue CATransaction.commit() } } var trackOpacity = OpacityAnimation(hidden: !nextDisplayState.trackVisible) var progressOpacity = OpacityAnimation(hidden: !nextDisplayState.progressBarVisible) // Only animate if value has changed let shouldAnimateTrack = animated && prevDisplayState.trackVisible != nextDisplayState.trackVisible let shouldAnimateProgressBar = animated && prevDisplayState.progressBarVisible != prevDisplayState.progressBarVisible let shouldAnimateImage = animated && prevDisplayState.image != nextDisplayState.image if shouldAnimateTrack { trackOpacity.addToLayer(self.backgroundView.shapeLayer, duration: self.animationDuration, function: self.animationTimingFunction) } else { trackOpacity.setNoAnimation(self.backgroundView.shapeLayer) } if shouldAnimateProgressBar { progressOpacity.addToLayer(self.progressView.progressLayer, duration: self.animationDuration, function: self.animationTimingFunction) } else { progressOpacity.setNoAnimation(self.progressView.progressLayer) } // A helper to get a "compressed" path represented by a single point at the center of the existing path. func compressPath(_ path: CGPath) -> CGPath { let bounds = path.boundingBoxOfPath let center = CGPoint(x: bounds.midX, y: bounds.midY) return UIBezierPath(arcCenter: center, radius: 0.0, startAngle: 0.0, endAngle: CGFloat(M_PI * 2), clockwise: true).cgPath } // Color transition for "useSolidColorButtons" // If the tint color is different between 2 states we animate the change by expanding the new color from the center of the button if prevDisplayState.tintColor != nextDisplayState.tintColor && self.style == .solid { // The transition layer provides the expanding color change in the state transition. The background view color isn't updating until completing this expand animation let transitionLayer = CAShapeLayer() transitionLayer.path = self.backgroundLayerPath CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) transitionLayer.fillColor = nextDisplayState.tintColor.cgColor CATransaction.commit() self.backgroundView.layer.addSublayer(transitionLayer) let completion = { () -> Void in transitionLayer.removeFromSuperlayer() self.updateAllColors() } CATransaction.begin() CATransaction.setCompletionBlock(completion) let bgAnim = CABasicAnimation(keyPath: "path") bgAnim.fromValue = compressPath(self.backgroundLayerPath) bgAnim.toValue = self.backgroundLayerPath bgAnim.duration = self.animationDuration bgAnim.timingFunction = self.animationTimingFunction transitionLayer.add(bgAnim, forKey: "bg_expand") CATransaction.commit() } else { self.updateAllColors() } // Update the image before we drive the animations self.setImage(nextDisplayState.image) // If image has changed and we're animating... // For image animations we reveal the new image from the center by expanding its mask if shouldAnimateImage { // Image mask expand let imageAnim = CABasicAnimation(keyPath: "path") imageAnim.fromValue = compressPath(self.imageViewMaskPath) imageAnim.toValue = self.imageViewMaskPath imageAnim.duration = self.animationDuration imageAnim.timingFunction = self.animationTimingFunction self.imageViewMask.add(imageAnim, forKey: "image_expand") } else { updateAllColors() } // Restart / adjust progress view if needed self.updateSpinningAnimation() switch prevDisplayState.progressBarStyle { case .percentage(let value): self.updateProgress(fromValue: value, animated: animated) default: self.updateProgress(fromValue: 0, animated: animated) } // Update the image constraints updateButtonConstains() // Finally update our current activity state self.renderedActivityState = activityState } fileprivate func updateProgress(fromValue prevValue: Float, animated: Bool) { switch self.activityState.progressBarStyle { case .percentage(let value): if animated { let anim = CABasicAnimation(keyPath: "strokeEnd") anim.fromValue = prevValue anim.toValue = value anim.duration = self.animationDuration anim.timingFunction = self.animationTimingFunction self.progressView.progressLayer.add(anim, forKey: "progress") self.progressView.progressLayer.strokeEnd = CGFloat(value) } else { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.progressView.progressLayer.strokeEnd = CGFloat(value) CATransaction.commit() } default: break } } /// This replicates the Google style activity spinner from Material Design fileprivate func updateSpinningAnimation() { let kStrokeAnim = "spinning_stroke" let kRotationAnim = "spinning_rotation" self.progressView.progressLayer.removeAnimation(forKey: kStrokeAnim) self.progressView.progressLayer.removeAnimation(forKey: kRotationAnim) if self.activityState.progressBarStyle == .spinning { // The animation is broken into stages that execute in order. All animations in "stage 1" execute simultaneously followed by animations in "stage 2" // "Head" refers to the strokeStart which is trailing behind the animation (i.e. the animation is moving clockwise away from the head) // "Tail refers to the strokeEnd which is leading the animation let stage1Time = 0.9 let pause1Time = 0.05 let stage2Time = 0.6 let pause2Time = 0.05 let stage3Time = 0.1 var animationTime = stage1Time // Stage1: The circle begins life empty, nothing is stroked. The tail moves ahead to travel the circumference of the circle. The head follows but lags behind 75% of the circumference. Now 75% of the circles circumference is stroked. let headStage1 = CABasicAnimation(keyPath: "strokeStart") headStage1.fromValue = 0.0 headStage1.toValue = 0.25 headStage1.duration = animationTime let tailStage1 = CABasicAnimation(keyPath: "strokeEnd") tailStage1.fromValue = 0.0 tailStage1.toValue = 1.0 tailStage1.duration = animationTime // Pause1: Maintain state from stage 1 for a moment let headPause1 = CABasicAnimation(keyPath: "strokeStart") headPause1.fromValue = 0.25 headPause1.toValue = 0.25 headPause1.beginTime = animationTime headPause1.duration = pause1Time let tailPause1 = CABasicAnimation(keyPath: "strokeEnd") tailPause1.fromValue = 1.0 tailPause1.toValue = 1.0 tailPause1.beginTime = animationTime tailPause1.duration = pause1Time animationTime += pause1Time // Stage2: The head whips around the circle to almost catch up with the tail. The tail stays at the end of the circle. Now 10% of the circles circumference is stroked. let headStage2 = CABasicAnimation(keyPath: "strokeStart") headStage2.fromValue = 0.25 headStage2.toValue = 0.9 headStage2.beginTime = animationTime headStage2.duration = stage2Time let tailStage2 = CABasicAnimation(keyPath: "strokeEnd") tailStage2.fromValue = 1.0 tailStage2.toValue = 1.0 tailStage2.beginTime = animationTime tailStage2.duration = stage2Time animationTime += stage2Time // Pause2: Maintain state from Stage2 for a moment. let headPause2 = CABasicAnimation(keyPath: "strokeStart") headPause2.fromValue = 0.9 headPause2.toValue = 0.9 headPause2.beginTime = animationTime headPause2.duration = pause2Time let tailPause2 = CABasicAnimation(keyPath: "strokeEnd") tailPause2.fromValue = 1.0 tailPause2.toValue = 1.0 tailPause2.beginTime = animationTime tailPause2.duration = pause2Time animationTime += pause2Time // Stage3: The head moves to 100% the circumference to finally catch up with the tail which remains stationary. Now none of the circle is stroked and we are back at the starting state. let headStage3 = CABasicAnimation(keyPath: "strokeStart") headStage3.fromValue = 0.9 headStage3.toValue = 1.0 headStage3.beginTime = animationTime headStage3.duration = stage3Time let tailStage3 = CABasicAnimation(keyPath: "strokeEnd") tailStage3.fromValue = 1.0 tailStage3.toValue = 1.0 tailStage3.beginTime = animationTime tailStage3.duration = stage3Time animationTime += stage3Time let group = CAAnimationGroup() group.repeatCount = Float.infinity group.duration = animationTime group.animations = [headStage1, tailStage1, headPause1, tailPause1, headStage2, tailStage2, headPause2, tailPause2, headStage3, tailStage3] self.progressView.progressLayer.add(group, forKey: kStrokeAnim) let rotationAnim = CABasicAnimation(keyPath: "transform.rotation") rotationAnim.fromValue = 0 rotationAnim.toValue = 2 * M_PI rotationAnim.duration = 3.0 rotationAnim.repeatCount = Float.infinity self.progressView.progressLayer.add(rotationAnim, forKey: kRotationAnim) } } // MARK: - Theming override open func tintColorDidChange() { super.tintColorDidChange() updateAllColors() } fileprivate func updateButtonColors() { var tintColor = self.tintColorForCurrentActivityState var foregroundColor = self.foregroundColorForCurrentActivityState if !isEnabled { tintColor = tintColor.colorWithSaturation(0.2) foregroundColor = foregroundColor.colorWithSaturation(0.2) } switch self.style { case .outline: self.backgroundView.shapeLayer.fillColor = UIColor.clear.cgColor self.imageView.tintColor = tintColor self.dropShadowLayer.shadowColor = UIColor.clear.cgColor case .solid: self.backgroundView.shapeLayer.fillColor = tintColor.cgColor self.imageView.tintColor = foregroundColor self.dropShadowLayer.shadowColor = self.shadowColor.cgColor } } fileprivate func updateTrackColors() { var tintColor = self.tintColorForCurrentActivityState if !isEnabled { tintColor = tintColor.colorWithSaturation(0.2) } let trackColor = self.trackColorForCurrentActivityState.cgColor let clear = UIColor.clear.cgColor self.progressView.progressLayer.strokeColor = tintColor.cgColor self.progressView.progressLayer.fillColor = clear self.backgroundView.shapeLayer.strokeColor = trackColor } fileprivate func updateAllColors() { self.updateButtonColors() self.updateTrackColors() } // MARK: - UI (Private) /* We are wrapping all our layers in views for easier arrangment. */ fileprivate class BackgroundView: UIView { var shapeLayer: CAShapeLayer { get { return self.layer as! CAShapeLayer } } override class var layerClass : AnyClass { return CAShapeLayer.self } } fileprivate class ProgressView: UIView { var progressLayer: CAShapeLayer { get { return self.layer as! CAShapeLayer } } override class var layerClass : AnyClass { return CAShapeLayer.self } } /// The layer from which to draw the button shadow fileprivate var dropShadowLayer: CALayer { get { return self.layer } } fileprivate lazy var imageView: UIImageView = UIImageView() fileprivate lazy var imageViewMask: CAShapeLayer = CAShapeLayer() fileprivate lazy var backgroundView: BackgroundView = BackgroundView() fileprivate lazy var progressView: ProgressView = ProgressView() fileprivate func setImage(_ image: UIImage?) { self.imageView.image = image self.imageView.sizeToFit() } // MARK: - Layout fileprivate var progressLayerPath: CGPath { get { let progressRadius = min(self.progressView.frame.width, self.progressView.frame.height) * 0.5 return UIBezierPath( arcCenter: self.progressView.bounds.center, radius: progressRadius - progressBarWidth * 0.5, startAngle: Constants.Track.StartAngle, endAngle: Constants.Track.EndAngle, clockwise: true).cgPath } } fileprivate var backgroundLayerPathRadius: CGFloat { get { return min(self.backgroundView.frame.width, self.backgroundView.frame.height) * 0.5 } } fileprivate var backgroundLayerPath: CGPath { get { return UIBezierPath(arcCenter: self.backgroundView.bounds.center, radius: self.backgroundLayerPathRadius, startAngle: Constants.Track.StartAngle, endAngle: Constants.Track.EndAngle, clockwise: true).cgPath } } fileprivate var imageViewMaskPath: CGPath { get { return UIBezierPath(arcCenter: self.imageView.bounds.center, radius: self.backgroundLayerPathRadius, startAngle: Constants.Track.StartAngle, endAngle: Constants.Track.EndAngle, clockwise: true).cgPath } } fileprivate var shadowPath: CGPath { get { return UIBezierPath(arcCenter: self.bounds.center, radius: self.backgroundLayerPathRadius, startAngle: Constants.Track.StartAngle, endAngle: Constants.Track.EndAngle, clockwise: true).cgPath } } // The "INNER" padding is the distance between the background and the track. Have to add the width of the progress and the half of the track (the track is the stroke of the background view) fileprivate var innerPadding: CGFloat { return Constants.Layout.outerPadding + progressBarWidth + 0.5 * trackWidth } fileprivate var buttonConstraints = [NSLayoutConstraint]() /** Should be called once and only once. Adds layers to view heirarchy. */ fileprivate func initialLayoutSetup() { self.imageView.translatesAutoresizingMaskIntoConstraints = false self.backgroundView.translatesAutoresizingMaskIntoConstraints = false self.progressView.translatesAutoresizingMaskIntoConstraints = false self.imageView.backgroundColor = UIColor.clear self.backgroundView.backgroundColor = UIColor.clear self.progressView.backgroundColor = UIColor.clear self.imageView.isUserInteractionEnabled = false self.backgroundView.isUserInteractionEnabled = false self.progressView.isUserInteractionEnabled = false self.backgroundColor = UIColor.clear self.addSubview(self.backgroundView) self.addSubview(self.imageView) self.addSubview(self.progressView) let views = ["progress" : self.progressView] let metrics = ["OUTER" : Constants.Layout.outerPadding] self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(OUTER)-[progress]-(OUTER)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(OUTER)-[progress]-(OUTER)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views)) self.addConstraint(NSLayoutConstraint(item: self.imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: self.imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) updateButtonConstains() // Set up imageViewMask self.imageViewMask.fillColor = UIColor.white.cgColor self.imageView.layer.mask = self.imageViewMask // Set up drop shadow let layer = self.dropShadowLayer layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowRadius = 2.5 layer.shadowOpacity = 0.5 layer.masksToBounds = false } /** The button constraints may change if progress bar or track width is changed. This method will handle updates */ fileprivate func updateButtonConstains() { // Clear old constraints self.removeConstraints(buttonConstraints) buttonConstraints.removeAll() let views = ["bg" : self.backgroundView, "image" : imageView] as [String : Any] let metrics = ["INNER" : innerPadding, "IMAGE_PAD" : innerPadding + minimumImagePadding] buttonConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(INNER)-[bg]-(INNER)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views) buttonConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(INNER)-[bg]-(INNER)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views) buttonConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(IMAGE_PAD)-[image]-(IMAGE_PAD)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views) buttonConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(IMAGE_PAD)-[image]-(IMAGE_PAD)-|", options: NSLayoutFormatOptions(), metrics: metrics, views: views) self.addConstraints(buttonConstraints) } /** Should be called when bounds change to update paths of shape layers. */ fileprivate func updateForCurrentBounds() { self.progressView.progressLayer.lineWidth = progressBarWidth self.backgroundView.shapeLayer.lineWidth = trackWidth self.progressView.progressLayer.path = self.progressLayerPath self.backgroundView.shapeLayer.path = self.backgroundLayerPath self.imageViewMask.path = self.imageViewMaskPath self.dropShadowLayer.shadowPath = self.shadowPath } open override func layoutSubviews() { super.layoutSubviews() updateForCurrentBounds() } open override var intrinsicContentSize : CGSize { var maxW: CGFloat = Constants.Layout.defaultContentSize.width var maxH: CGFloat = Constants.Layout.defaultContentSize.height let padding = 2 * (minimumImagePadding + trackWidth + progressBarWidth + Constants.Layout.outerPadding) if let imageSize = self.activityState.image?.size { maxW = max(imageSize.width, maxW) + padding maxH = max(imageSize.height, maxH) + padding } return CGSize(width: maxW, height: maxH) } // MARK: - Hit Animation func handleTouchUp(_ sender: ActivityIndicatorButton) { self.createRippleHitAnimation(true) } func handleTouchDown(_ sender: ActivityIndicatorButton) { self.createRippleHitAnimation(false) } /** Creates a new layer under the control which expands outward. */ fileprivate func createRippleHitAnimation(_ isTouchUp: Bool) { let duration = self.hitAnimationDuration let distance: CGFloat = self.hitAnimationDistance let color = self.hitAnimationColor.cgColor let timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) let layer = CAShapeLayer() layer.fillColor = color layer.strokeColor = UIColor.clear.cgColor self.layer.insertSublayer(layer, at: 0) let bounds = self.bounds let radius = max(bounds.width, bounds.height) * 0.5 let center = CGPoint(x: bounds.midX, y: bounds.midY) let fromPath = UIBezierPath(arcCenter: center, radius: 0.0, startAngle: 0.0, endAngle: CGFloat(2 * M_PI), clockwise: true).cgPath let toPath = UIBezierPath(arcCenter: center, radius: radius + distance, startAngle: 0.0, endAngle: CGFloat(2 * M_PI), clockwise: true).cgPath let completion = { () -> Void in layer.removeFromSuperlayer() } func scaleLayer(_ layer: CALayer, offset: CGFloat) { var scaleFromValue = CATransform3DIdentity var scaleToValue = CATransform3DMakeScale(0.98 - offset, 0.98 - offset, 1.0) if isTouchUp { swap(&scaleFromValue, &scaleToValue) } let scaleAnim = CABasicAnimation(keyPath: "transform") scaleAnim.fromValue = NSValue(caTransform3D: scaleFromValue) scaleAnim.toValue = NSValue(caTransform3D: scaleToValue) scaleAnim.duration = duration scaleAnim.timingFunction = timing layer.add(scaleAnim, forKey: "hit_scale") layer.transform = scaleToValue } CATransaction.begin() CATransaction.setCompletionBlock(completion) let pathAnim = CABasicAnimation(keyPath: "path") pathAnim.fromValue = fromPath pathAnim.toValue = toPath let fadeAnim = CABasicAnimation(keyPath: "opacity") fadeAnim.fromValue = 1.0 fadeAnim.toValue = 0.0 scaleLayer(self.backgroundView.layer, offset: 0.0) scaleLayer(self.dropShadowLayer, offset: 0.0) let group = CAAnimationGroup() group.animations = [pathAnim, fadeAnim] group.duration = duration group.timingFunction = timing layer.add(group, forKey: "ripple") CATransaction.commit() } }
mit
c065560f9c39bad96f73c263db60e79a
34.846484
245
0.648109
5.488051
false
false
false
false
delannoyk/SoundcloudSDK
sources/SoundcloudAppTest/UserListViewController.swift
1
2927
// // UserListViewController.swift // Soundcloud // // Created by Kevin DELANNOY on 2016-10-22. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import UIKit import Soundcloud class UserListViewController: UIViewController { // MARK: Outlets @IBOutlet private weak var tableView: UITableView? { didSet { tableView?.estimatedRowHeight = 44 tableView?.rowHeight = UITableViewAutomaticDimension } } // MARK: Properties var userResponse: PaginatedAPIResponse<User>? { didSet { users = userResponse?.response.result lastUserResponse = userResponse } } fileprivate var loading = false fileprivate var lastUserResponse: PaginatedAPIResponse<User>? { didSet { tableView?.reloadData() } } fileprivate var users: [User]? // MARK: Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == "User" { (segue.destination as? UserViewController)?.user = sender as? User } } } // MARK: - UITableViewDelegate extension UserListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == users?.count && !loading { loading = true //Now we have to unwrap the optional because of https://bugs.swift.org/browse/SR-1681 guard let lastUserResponse = lastUserResponse else { return } lastUserResponse.fetchNextPage { [weak self] response in self?.loading = false if case .success(let users) = response.response { self?.users?.append(contentsOf: users) } self?.lastUserResponse = response } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "User", sender: users?[indexPath.row]) } } // MARK: - UITableViewDataSource extension UserListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (users?.count ?? 0) + (lastUserResponse?.hasNextPage == true ? 1 : 0) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == users?.count { return tableView.dequeueReusableCell(withIdentifier: "Loading", for: indexPath) } let cell = tableView.dequeueReusableCell(withIdentifier: "User", for: indexPath) if let cell = cell as? UserTableViewCell { cell.user = users?[indexPath.row] } return cell } }
mit
5c3dffeace2ab8e3036ee71abcbdb192
29.8
112
0.637047
5.225
false
false
false
false
noprom/VPNOn
VPNOnKit/VPNManager+Domains.swift
19
2940
// // VPNManager+Domains.swift // VPNOn // // Created by Lex Tang on 1/29/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import Foundation let kOnDemandKey = "onDemand" let kOnDemandDomainsKey = "onDemandDomains" extension VPNManager { public var onDemand: Bool { get { if let onDemandObject = defaults.objectForKey(kOnDemandKey) as! NSNumber? { if onDemandObject.isKindOfClass(NSNumber.self) { return onDemandObject.boolValue } } return false } set { defaults.setObject(NSNumber(bool: newValue), forKey: kOnDemandKey) defaults.synchronize() } } public var onDemandDomains: String? { get { if let domainsObject = defaults.stringForKey(kOnDemandDomainsKey) { return domainsObject } return .None } set { if newValue == nil { defaults.removeObjectForKey(kOnDemandDomainsKey) } else { defaults.setObject(newValue, forKey: kOnDemandDomainsKey) } defaults.synchronize() } } public var onDemandDomainsArray: [String] { get { return self.domainsInString(onDemandDomains ?? "") } } public func domainsInString(string: String) -> [String] { let seperator = NSCharacterSet.whitespaceAndNewlineCharacterSet() let s = string.stringByTrimmingCharactersInSet(seperator) if s.isEmpty { return [String]() } var domains = s.componentsSeparatedByCharactersInSet(seperator) as [String] var wildCardDomains = [String]() if domains.count > 1 { if domains[domains.count - 1].isEmpty { domains.removeAtIndex(domains.count - 1) } } else { let ns = s as NSString let range = ns.rangeOfCharacterFromSet(seperator) if (range.location == NSNotFound) { domains = [String]() domains.append(s) } } for domain in domains { wildCardDomains.append(domain) if domain.rangeOfString("*.") == nil { wildCardDomains.append("*.\(domain)") } } return uniq(wildCardDomains) } // See: http://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro private func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] { var buffer = Array<T>() var addedDict = [T: Bool]() for elem in source { if addedDict[elem] == nil { addedDict[elem] = true buffer.append(elem) } } return buffer } }
mit
59c6b9faf20d75d30de02207030e4bd6
29.625
135
0.55
4.811784
false
false
false
false
MartinLep/Swift_Live
SwiftLive/SwiftLive/Classes/Main/Model/AnchorModel.swift
1
837
// // AnchorModel.swift // SwiftLive // // Created by MartinLee on 17/4/10. // Copyright © 2017年 MartinLee. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间) var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
0386415ee57f27fa6789d7e46a423c64
19.166667
73
0.559229
3.558824
false
false
false
false
mac-cain13/DocumentStore
DocumentStore/Index/Index.swift
1
3211
// // Index.swift // DocumentStore // // Created by Mathijs Kadijk on 03-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation /// Index for a `Document` used in a `Query` to filter and order `Document`s in an efficient way. public class Index<DocumentType: Document, ValueType: IndexableValue>: PartialIndex<DocumentType> { /// Create an `Index` /// /// - Warning: Changing the name or ValueType of this `Index` will trigger a repopulation /// of this index for all documents this `Index` is related to. This can be time /// consuming. /// /// - Parameters: /// - name: Unique (within one document) unchangable identifier /// - resolver: Resolver to get the value for this `Index` from a `Document` instance public init(name: String, resolver: @escaping (DocumentType) -> ValueType?) { let storageInformation = StorageInformation( documentNameResolver: { DocumentType.documentDescriptor.name }, propertyName: PropertyName.userDefined(name), storageType: ValueType.storageType, isOptional: true, sourceKeyPath: nil ) let resolver: (Any) -> Any? = { guard let document = $0 as? DocumentType else { fatalError("Index resolver type violation.") } return resolver(document) } super.init(storageInformation: storageInformation, resolver: resolver) } /// Create an `Index` with a `KeyPath` /// /// - Warning: Changing the name or ValueType of this `Index` will trigger a repopulation /// of this index for all documents this `Index` is related to. This can be time /// consuming. /// /// - Parameters: /// - name: Unique (within one document) unchangable identifier /// - resolver: Resolver to get the value for this `Index` from a `Document` instance public init(name: String, keyPath: KeyPath<DocumentType, ValueType>) { let storageInformation = StorageInformation( documentNameResolver: { DocumentType.documentDescriptor.name }, propertyName: .userDefined(name), storageType: ValueType.storageType, isOptional: true, sourceKeyPath: keyPath ) let resolver: (Any) -> Any? = { guard let document = $0 as? DocumentType else { fatalError("Index resolver type violation.") } return document[keyPath: keyPath] } super.init(storageInformation: storageInformation, resolver: resolver) } init(storageInformation: StorageInformation, resolver: @escaping (DocumentType) -> ValueType?) { let resolver: (Any) -> Any? = { guard let document = $0 as? DocumentType else { fatalError("Index resolver type violation.") } return resolver(document) } super.init(storageInformation: storageInformation, resolver: resolver) } } /// Type eraser for `Index` to make it possible to store them in for example an array. public class PartialIndex<DocumentType: Document>: AnyIndex {} public class AnyIndex { let storageInformation: StorageInformation let resolver: (Any) -> Any? init(storageInformation: StorageInformation, resolver: @escaping (Any) -> Any?) { self.storageInformation = storageInformation self.resolver = resolver } }
mit
a006ed1623b154804ab5f5201f7c3aba
38.62963
100
0.689408
4.546742
false
false
false
false
Lion-Hwang/sound-effector
ios/Pods/PKHUD/PKHUD/Window.swift
8
2875
// // HUDWindow.swift // PKHUD // // Created by Philip Kluz on 6/16/14. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// The window used to display the PKHUD within. Placed atop the applications main window. internal class Window: UIWindow { internal let frameView: FrameView internal init(frameView: FrameView = FrameView()) { self.frameView = frameView super.init(frame: UIApplication.sharedApplication().delegate!.window!!.bounds) commonInit() } required init?(coder aDecoder: NSCoder) { frameView = FrameView() super.init(coder: aDecoder) commonInit() } private func commonInit() { rootViewController = WindowRootViewController() windowLevel = UIWindowLevelNormal + 1.0 backgroundColor = UIColor.clearColor() addSubview(backgroundView) addSubview(frameView) } internal override func layoutSubviews() { super.layoutSubviews() frameView.center = center backgroundView.frame = bounds } internal func showFrameView() { layer.removeAllAnimations() makeKeyAndVisible() frameView.center = center frameView.alpha = 1.0 hidden = false } private var willHide = false internal func hideFrameView(animated anim: Bool, completion: ((Bool) -> Void)? = nil) { let finalize: (finished: Bool) -> (Void) = { finished in if finished { self.hidden = true self.resignKeyWindow() } self.willHide = false completion?(finished) } if hidden { return } willHide = true if anim { UIView.animateWithDuration(0.8, animations: { self.frameView.alpha = 0.0 self.hideBackground(animated: false) }, completion: finalize) } else { self.frameView.alpha = 0.0 finalize(finished: true) } } private let backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor(white:0.0, alpha:0.25) view.alpha = 0.0 return view }() internal func showBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.175) { self.backgroundView.alpha = 1.0 } } else { backgroundView.alpha = 1.0 } } internal func hideBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.65) { self.backgroundView.alpha = 0.0 } } else { backgroundView.alpha = 0.0 } } }
epl-1.0
2d02733a30578375b41df8459968ad30
25.62037
91
0.554087
5.017452
false
false
false
false
alex-alex/S2Geometry
Sources/S2Cell.swift
1
13470
// // S2Cell.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif /** An S2Cell is an S2Region object that represents a cell. Unlike S2CellIds, it supports efficient containment and intersection tests. However, it is also a more expensive representation. */ public struct S2Cell: S2Region, Equatable { private static let maxCellSize = 1 << S2CellId.maxLevel public let cellId: S2CellId public let face: UInt8 public let level: Int8 public let orientation: UInt8 public let uv: [[Double]] internal init(cellId: S2CellId = S2CellId(), face: UInt8 = 0, level: Int8 = 0, orientation: UInt8 = 0, uv: [[Double]] = [[0, 0], [0, 0]]) { self.cellId = cellId self.face = face self.level = level self.orientation = orientation self.uv = uv } /// An S2Cell always corresponds to a particular S2CellId. The other constructors are just convenience methods. public init(cellId: S2CellId) { self.cellId = cellId var i = 0 var j = 0 var mOrientation: Int? = 0 face = UInt8(cellId.toFaceIJOrientation(i: &i, j: &j, orientation: &mOrientation)) orientation = UInt8(mOrientation!) level = Int8(cellId.level) let cellSize = 1 << (S2CellId.maxLevel - Int(level)) var _uv: [[Double]] = [[0, 0], [0, 0]] for (d, ij) in [i, j].enumerated() { // Compute the cell bounds in scaled (i,j) coordinates. let sijLo = (ij & -cellSize) * 2 - S2Cell.maxCellSize let sijHi = sijLo + cellSize * 2 _uv[d][0] = S2Projections.stToUV(s: (1.0 / Double(S2Cell.maxCellSize)) * Double(sijLo)) _uv[d][1] = S2Projections.stToUV(s: (1.0 / Double(S2Cell.maxCellSize)) * Double(sijHi)) } uv = _uv } // This is a static method in order to provide named parameters. public init(face: Int, pos: UInt8, level: Int) { self.init(cellId: S2CellId(face: face, pos: Int64(pos), level: level)) } // Convenience methods. public init(point: S2Point) { self.init(cellId: S2CellId(point: point)) } public init(latlng: S2LatLng) { self.init(cellId: S2CellId(latlng: latlng)) } public var isLeaf: Bool { return Int(level) == S2CellId.maxLevel } public func getVertex(_ k: Int) -> S2Point { return S2Point.normalize(point: getRawVertex(k)) } /** Return the k-th vertex of the cell (k = 0,1,2,3). Vertices are returned in CCW order. The points returned by GetVertexRaw are not necessarily unit length. */ public func getRawVertex(_ k: Int) -> S2Point { // Vertices are returned in the order SW, SE, NE, NW. return S2Projections.faceUvToXyz(face: Int(face), u: uv[0][(k >> 1) ^ (k & 1)], v: uv[1][k >> 1]) } public func getEdge(_ k: Int) -> S2Point { return S2Point.normalize(point: getRawEdge(k)) } public func getRawEdge(_ k: Int) -> S2Point { switch (k) { case 0: return S2Projections.getVNorm(face: Int(face), v: uv[1][0]) // South case 1: return S2Projections.getUNorm(face: Int(face), u: uv[0][1]) // East case 2: return -S2Projections.getVNorm(face: Int(face), v: uv[1][1]) // North default: return -S2Projections.getUNorm(face: Int(face), u: uv[0][0]) // West } } /** Return the inward-facing normal of the great circle passing through the edge from vertex k to vertex k+1 (mod 4). The normals returned by GetEdgeRaw are not necessarily unit length. If this is not a leaf cell, set children[0..3] to the four children of this cell (in traversal order) and return true. Otherwise returns false. This method is equivalent to the following: for (pos=0, id=child_begin(); id != child_end(); id = id.next(), ++pos) children[i] = S2Cell(id); except that it is more than two times faster. */ public func subdivide() -> [S2Cell] { // This function is equivalent to just iterating over the child cell ids // and calling the S2Cell constructor, but it is about 2.5 times faster. guard !cellId.isLeaf else { return [] } // Compute the cell midpoint in uv-space. let uvMid = centerUV // Create four children with the appropriate bounds. var children: [S2Cell] = [] var id = cellId.childBegin() for pos in 0 ..< 4 { var _uv: [[Double]] = [[0, 0], [0, 0]] let ij = S2.posToIJ(orientation: Int(orientation), position: pos) for d in 0 ..< 2 { // The dimension 0 index (i/u) is in bit 1 of ij. let m = 1 - ((ij >> (1 - d)) & 1) _uv[d][m] = uvMid.get(index: d) _uv[d][1 - m] = uv[d][1 - m] } let child = S2Cell(cellId: id, face: face, level: level + 1, orientation: orientation ^ UInt8(S2.posToOrientation(position: pos)), uv: _uv) children.append(child) id = id.next() } return children } /** Return the direction vector corresponding to the center in (s,t)-space of the given cell. This is the point at which the cell is divided into four subcells; it is not necessarily the centroid of the cell in (u,v)-space or (x,y,z)-space. The point returned by GetCenterRaw is not necessarily unit length. */ public var center: S2Point { return S2Point.normalize(point: rawCenter) } public var rawCenter: S2Point { return cellId.rawPoint } /** Return the center of the cell in (u,v) coordinates (see `S2Projections`). Note that the center of the cell is defined as the point at which it is recursively subdivided into four children; in general, it is not at the midpoint of the (u,v) rectangle covered by the cell */ public var centerUV: R2Vector { var i = 0 var j = 0 var orientation: Int? = nil _ = cellId.toFaceIJOrientation(i: &i, j: &j, orientation: &orientation) let cellSize = 1 << (S2CellId.maxLevel - Int(level)) // TODO(dbeaumont): Figure out a better naming of the variables here (and elsewhere). let si = (i & -cellSize) * 2 + cellSize - S2Cell.maxCellSize let x = S2Projections.stToUV(s: (1.0 / Double(S2Cell.maxCellSize)) * Double(si)) let sj = (j & -cellSize) * 2 + cellSize - S2Cell.maxCellSize let y = S2Projections.stToUV(s: (1.0 / Double(S2Cell.maxCellSize)) * Double(sj)) return R2Vector(x: x, y: y) } public func contains(point p: S2Point) -> Bool { // We can't just call XYZtoFaceUV, because for points that lie on the // boundary between two faces (i.e. u or v is +1/-1) we need to return // true for both adjacent cells. guard let uvPoint = S2Projections.faceXyzToUv(face: Int(face), point: p) else { return false } return uvPoint.x >= uv[0][0] && uvPoint.x <= uv[0][1] && uvPoint.y >= uv[1][0] && uvPoint.y <= uv[1][1] } /** * Return the average area for cells at the given level. */ public static func averageArea(level: Int) -> Double { return S2Projections.avgArea.getValue(level: level) } /** Return the average area of cells at this level. This is accurate to within a factor of 1.7 (for S2_QUADRATIC_PROJECTION) and is extremely cheap to compute. */ public var averageArea: Double { return S2Cell.averageArea(level: Int(level)) } /** Return the approximate area of this cell. This method is accurate to within 3% percent for all cell sizes and accurate to within 0.1% for cells at level 5 or higher (i.e. 300km square or smaller). It is moderately cheap to compute. */ public var approxArea: Double { // All cells at the first two levels have the same area. if level < 2 { return averageArea } // First, compute the approximate area of the cell when projected // perpendicular to its normal. The cross product of its diagonals gives // the normal, and the length of the normal is twice the projected area. let flatArea = 0.5 * (getVertex(2) - getVertex(0)).crossProd((getVertex(3) - getVertex(1))).norm // Now, compensate for the curvature of the cell surface by pretending // that the cell is shaped like a spherical cap. The ratio of the // area of a spherical cap to the area of its projected disc turns out // to be 2 / (1 + sqrt(1 - r*r)) where "r" is the radius of the disc. // For example, when r=0 the ratio is 1, and when r=1 the ratio is 2. // Here we set Pi*r*r == flat_area to find the equivalent disc. return flatArea * 2 / (1 + sqrt(1 - min(M_1_PI * flatArea, 1.0))) } /** Return the area of this cell as accurately as possible. This method is more expensive but it is accurate to 6 digits of precision even for leaf cells (whose area is approximately 1e-18). */ public var exactArea: Double { let v0 = getVertex(0) let v1 = getVertex(1) let v2 = getVertex(2) let v3 = getVertex(3) return S2.area(a: v0, b: v1, c: v2) + S2.area(a: v0, b: v2, c: v3) } //////////////////////////////////////////////////////////////////////// // MARK: S2Region //////////////////////////////////////////////////////////////////////// public var capBound: S2Cap { // Use the cell center in (u,v)-space as the cap axis. This vector is // very close to GetCenter() and faster to compute. Neither one of these // vectors yields the bounding cap with minimal surface area, but they // are both pretty close. // // It's possible to show that the two vertices that are furthest from // the (u,v)-origin never determine the maximum cap size (this is a // possible future optimization). let u = 0.5 * (uv[0][0] + uv[0][1]) let v = 0.5 * (uv[1][0] + uv[1][1]) var cap = S2Cap(axis: S2Point.normalize(point: S2Projections.faceUvToXyz(face: Int(face), u: u, v: v)), height: 0) for k in 0 ..< 4 { cap = cap.add(point: getVertex(k)) } return cap } // We grow the bounds slightly to make sure that the bounding rectangle // also contains the normalized versions of the vertices. Note that the // maximum result magnitude is Pi, with a floating-point exponent of 1. // Therefore adding or subtracting 2**-51 will always change the result. private static let maxError = 1.0 / Double(1 << 51) // The 4 cells around the equator extend to +/-45 degrees latitude at the // midpoints of their top and bottom edges. The two cells covering the // poles extend down to +/-35.26 degrees at their vertices. // adding kMaxError (as opposed to the C version) because of asin and atan2 // roundoff errors private static let poleMinLat = asin(sqrt(1.0 / 3.0)) - maxError // 35.26 degrees public var rectBound: S2LatLngRect { if level > 0 { // Except for cells at level 0, the latitude and longitude extremes are // attained at the vertices. Furthermore, the latitude range is // determined by one pair of diagonally opposite vertices and the // longitude range is determined by the other pair. // // We first determine which corner (i,j) of the cell has the largest // absolute latitude. To maximize latitude, we want to find the point in // the cell that has the largest absolute z-coordinate and the smallest // absolute x- and y-coordinates. To do this we look at each coordinate // (u and v), and determine whether we want to minimize or maximize that // coordinate based on the axis direction and the cell's (u,v) quadrant. let u = uv[0][0] + uv[0][1] let v = uv[1][0] + uv[1][1] let i = S2Projections.getUAxis(face: Int(face)).z == 0 ? (u < 0 ? 1 : 0) : (u > 0 ? 1 : 0) let j = S2Projections.getVAxis(face: Int(face)).z == 0 ? (v < 0 ? 1 : 0) : (v > 0 ? 1 : 0) var lat = R1Interval(p1: getLatitude(i: i, j: j), p2: getLatitude(i: 1 - i, j: 1 - j)) lat = lat.expanded(radius: S2Cell.maxError).intersection(with: S2LatLngRect.fullLat) if (lat.lo == -M_PI_2 || lat.hi == M_PI_2) { return S2LatLngRect(lat: lat, lng: S1Interval.full) } let lng = S1Interval(p1: getLongitude(i: i, j: 1 - j), p2: getLongitude(i: 1 - i, j: j)) return S2LatLngRect(lat: lat, lng: lng.expanded(radius: S2Cell.maxError)) } // The face centers are the +X, +Y, +Z, -X, -Y, -Z axes in that order. // assert (S2Projections.getNorm(face).get(face % 3) == ((face < 3) ? 1 : -1)) switch face { case 0: return S2LatLngRect(lat: R1Interval(lo: -M_PI_4, hi: M_PI_4), lng: S1Interval(lo: -M_PI_4, hi: M_PI_4)) case 1: return S2LatLngRect(lat: R1Interval(lo: -M_PI_4, hi: M_PI_4), lng: S1Interval(lo: M_PI_4, hi: 3 * M_PI_4)) case 2: return S2LatLngRect(lat: R1Interval(lo: S2Cell.poleMinLat, hi: M_PI_2), lng: S1Interval(lo: -M_PI, hi: M_PI)) case 3: return S2LatLngRect(lat: R1Interval(lo: -M_PI_4, hi: M_PI_4), lng: S1Interval(lo: 3 * M_PI_4, hi: -3 * M_PI_4)) case 4: return S2LatLngRect(lat: R1Interval(lo: -M_PI_4, hi: M_PI_4), lng: S1Interval(lo: -3 * M_PI_4, hi: -M_PI_4)) default: return S2LatLngRect(lat: R1Interval(lo: -M_PI_2, hi: -S2Cell.poleMinLat), lng: S1Interval(lo: -M_PI, hi: M_PI)) } } public func contains(cell: S2Cell) -> Bool { return cellId.contains(other: cell.cellId) } public func mayIntersect(cell: S2Cell) -> Bool { return cellId.intersects(with: cell.cellId) } // Return the latitude or longitude of the cell vertex given by (i,j), // where "i" and "j" are either 0 or 1. private func getLatitude(i: Int, j: Int) -> Double { let p = S2Projections.faceUvToXyz(face: Int(face), u: uv[0][i], v: uv[1][j]) return atan2(p.z, sqrt(p.x * p.x + p.y * p.y)) } private func getLongitude(i: Int, j: Int) -> Double { let p = S2Projections.faceUvToXyz(face: Int(face), u: uv[0][i], v: uv[1][j]) return atan2(p.y, p.x) } } public func ==(lhs: S2Cell, rhs: S2Cell) -> Bool { return lhs.face == rhs.face && lhs.level == rhs.level && lhs.orientation == rhs.orientation && lhs.cellId == rhs.cellId }
mit
e98abf0d4ec8bad2aa73d7fa12efc941
36.728291
142
0.658327
2.995108
false
false
false
false
zeroc-ice/ice-demos
swift/Ice/bidir/Sources/Server/main.swift
1
2206
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice // Automatically flush stdout setbuf(__stdoutp, nil) class CallbackSenderI: CallbackSender { var clients: [CallbackReceiverPrx] = [] var num: Int32 = 0 func addClient(receiver: CallbackReceiverPrx?, current: Ice.Current) throws { if let client = receiver { DispatchQueue.global(qos: .background).async(flags: .barrier) { print("adding client `\(Ice.identityToString(id: client.ice_getIdentity()))'") self.clients.append(client.ice_fixed(current.con!)) } } } func dispatch() { if clients.count > 0 { num += 1 for c in clients { c.callbackAsync(num).catch { e in DispatchQueue.global(qos: .background).async(flags: .barrier) { precondition(e is Ice.Exception) if let i = self.clients.firstIndex(where: { $0 == c }) { print("removing client \(Ice.identityToString(id: c.ice_getIdentity())):\n:\(e)") self.clients.remove(at: i) } } } } } } } func run() -> Int32 { do { var args = CommandLine.arguments let communicator = try Ice.initialize(args: &args, configFile: "config.server") defer { communicator.destroy() } guard args.count == 1 else { print("too many arguments\n") return 1 } let adapter = try communicator.createObjectAdapter("Callback.Server") let sender = CallbackSenderI() try adapter.add(servant: CallbackSenderDisp(sender), id: Ice.stringToIdentity("sender")) try adapter.activate() Timer.scheduledTimer(withTimeInterval: TimeInterval(2.0), repeats: true) { _ in DispatchQueue.global(qos: .background).async(flags: .barrier) { sender.dispatch() } } RunLoop.main.run() } catch { print("Error: \(error)\n") return 1 } return 0 } exit(run())
gpl-2.0
a224792f45d904de6dbb03d384df1e26
28.810811
109
0.538078
4.447581
false
false
false
false
stephentyrone/swift
stdlib/private/StdlibUnittest/SymbolLookup.swift
3
1839
//===--- SymbolLookup.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) || os(WASI) import Glibc #elseif os(Windows) import MSVCRT import WinSDK #else #error("Unsupported platform") #endif #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(OpenBSD) let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) #elseif os(Linux) let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0) #elseif os(Android) #if arch(arm) || arch(i386) let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0xffffffff as UInt) #elseif arch(arm64) || arch(x86_64) let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0) #else #error("Unsupported platform") #endif #elseif os(Windows) let hStdlibCore: HMODULE = GetModuleHandleA("swiftCore.dll")! #elseif os(WASI) // WASI doesn't support dynamic linking yet. #else #error("Unsupported platform") #endif public func pointerToSwiftCoreSymbol(name: String) -> UnsafeMutableRawPointer? { #if os(Windows) return unsafeBitCast(GetProcAddress(hStdlibCore, name), to: UnsafeMutableRawPointer?.self) #elseif os(WASI) fatalError("\(#function) is not supported on WebAssembly/WASI") #else return dlsym(RTLD_DEFAULT, name) #endif }
apache-2.0
c3fa95bb62b1e8f5ed8c15df109143b5
33.698113
112
0.660141
3.912766
false
false
false
false
bmichotte/HSTracker
HSTracker/Utility/BoardDamage/EntityHelper.swift
1
1635
// // EntityHelper.swift // HSTracker // // Created by Benjamin Michotte on 9/06/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation // TODO: this class is very messy, clean it up class EntityHelper { class func isHero(entity: Entity) -> Bool { return entity.has(tag: .cardtype) && entity[.cardtype] == CardType.hero.rawValue && entity.has(tag: .zone) && entity[.zone] == Zone.play.rawValue } class func getHeroEntity(forPlayer: Bool, game: Game) -> Entity? { return getHeroEntity(forPlayer: forPlayer, entities: game.entities, id: game.player.id) } class func getHeroEntity(forPlayer: Bool, entities: [Int: Entity], id: Int) -> Entity? { var _id = id if !forPlayer { _id = (_id % 2) + 1 } let heros = entities.filter { isHero(entity: $0.1) }.map { $0.1 } return heros.first { $0[.controller] == id } } class func isPlayersTurn(eventHandler: PowerEventHandler) -> Bool { let entities = eventHandler.entities let firstPlayer = entities.map { $0.1 }.first { $0.has(tag: .first_player) } if let firstPlayer = firstPlayer { let offset = firstPlayer.isPlayer(eventHandler: eventHandler) ? 0 : 1 guard let gameRoot = entities.map({ $0.1 }).first({ $0.name == "GameEntity" }) else { return false } let turn = gameRoot[.turn] return turn > 0 && (turn + offset) % 2 == 1 } return false } }
mit
5f293f0905897e674cec29704b1b538f
29.259259
97
0.559364
3.881235
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Contacts List/Cells/AAContactActionCell.swift
2
1292
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AAContactActionCell: AATableViewCell { public let titleView = YYLabel() public let iconView = UIImageView() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleView.font = UIFont.systemFontOfSize(18) titleView.textColor = ActorSDK.sharedActor().style.cellTintColor titleView.displaysAsynchronously = true iconView.contentMode = UIViewContentMode.Center self.contentView.addSubview(titleView) self.contentView.addSubview(iconView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func bind(icon: String, actionTitle: String) { titleView.text = actionTitle iconView.image = UIImage.bundled(icon)?.tintImage(ActorSDK.sharedActor().style.cellTintColor) } public override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; iconView.frame = CGRectMake(30, 8, 40, 40); titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40); } }
agpl-3.0
601a2bc3b70c070552c0613532ab244d
33.026316
101
0.675697
4.802974
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Extensions/DownloadViewController+iOS.swift
1
8100
import Foundation import PopcornTorrent import MediaPlayer.MPMediaItem import PopcornKit extension DownloadViewController: DownloadDetailTableViewCellDelegate { func reloadData() { tableView?.reloadData() } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem tableView.tableFooterView = UIView() tableView.register(UINib(nibName: "DownloadTableViewHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: "header") } func torrentStatusDidChange(_ torrentStatus: PTTorrentStatus, for download: PTTorrentDownload) { reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { tableView.backgroundView = nil let dataSource = activeDataSource(in: 0) + activeDataSource(in: 1) if dataSource.isEmpty { let background: ErrorBackgroundView? = .fromNib() background?.setUpView(title: "Downloads Empty".localized, description: "Movies and episodes you download will show up here.".localized) tableView.backgroundView = background } return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let value = (downloadingEpisodes + downloadingMovies).count navigationController?.tabBarItem.badgeValue = value == 0 ? nil : NumberFormatter.localizedString(from: NSNumber(value: value), number: .none) return activeDataSource(in: section).count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") let label = header?.viewWithTag(1) as? UILabel let index = segmentedControl.selectedSegmentIndex label?.text = (section == 0 ? "Movies" : index == 0 ? "Episodes" : "Shows").localized return header } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return activeDataSource(in: section).count == 0 ? 0 : 40 } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete && segmentedControl.selectedSegmentIndex == 1 else { return } let downloads: [PTTorrentDownload] if indexPath.section == 0 { downloads = [completedMovies[indexPath.row]] } else { downloads = completedEpisodes.filter { guard let lhs = Episode($0.mediaMetadata)?.show, let rhs = activeDataSource(in: indexPath.section)[indexPath.row] as? Show else { return false } return lhs == rhs } } downloads.forEach({PTTorrentDownloadManager.shared().delete($0)}) tableView.deleteRows(at: [indexPath], with: .fade) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return segmentedControl.selectedSegmentIndex == 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: DownloadTableViewCell let image: String? if indexPath.section == 1 && segmentedControl.selectedSegmentIndex == 1 // Sort episodes by show instead. { let show = activeDataSource(in: indexPath.section)[indexPath.row] as! Show cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell") as! DownloadTableViewCell image = show.smallBackgroundImage cell.textLabel?.text = show.title let count = completedEpisodes.filter { return Episode($0.mediaMetadata)?.show == show }.count let singular = count == 1 cell.detailTextLabel?.text = "\(NumberFormatter.localizedString(from: NSNumber(value: count), number: .none)) \(singular ? "Episode".localized : "Episodes".localized)" } else { let download = activeDataSource(in: indexPath.section)[indexPath.row] as! PTTorrentDownload cell = { let cell = tableView.dequeueReusableCell(withIdentifier: "downloadDetailCell") as! DownloadDetailTableViewCell cell.delegate = self cell.downloadButton.progress = download.torrentStatus.totalProgress cell.downloadButton.downloadState = DownloadButton.buttonState(download.downloadStatus) cell.downloadButton.invalidateAppearance() return cell }() image = download.mediaMetadata[MPMediaItemPropertyBackgroundArtwork] as? String cell.textLabel?.text = download.mediaMetadata[MPMediaItemPropertyTitle] as? String if segmentedControl.selectedSegmentIndex == 0 { let speed: String let downloadSpeed = TimeInterval(download.torrentStatus.downloadSpeed) let sizeLeftToDownload = TimeInterval(download.fileSize.longLongValue - download.totalDownloaded.longLongValue) if downloadSpeed > 0 { let formatter = DateComponentsFormatter() formatter.unitsStyle = .full formatter.includesTimeRemainingPhrase = true formatter.includesApproximationPhrase = true formatter.allowedUnits = [.hour, .minute] let remainingTime = sizeLeftToDownload/downloadSpeed if let formattedTime = formatter.string(from: remainingTime) { speed = " • " + formattedTime } else { speed = "" } } else { speed = "" } cell.detailTextLabel?.text = download.downloadStatus == .paused ? "Paused".localized : ByteCountFormatter.string(fromByteCount: Int64(download.torrentStatus.downloadSpeed), countStyle: .binary) + "/s" + speed } else { cell.detailTextLabel?.text = download.fileSize.stringValue } } if let image = image, let url = URL(string: image) { cell.imageView?.af_setImage(withURL: url) } else { cell.imageView?.image = UIImage(named: "Episode Placeholder") } return cell } func cell(_ cell: DownloadDetailTableViewCell, accessoryButtonPressed button: DownloadButton) { guard let indexPath = tableView.indexPath(for: cell) else { return } let download = activeDataSource(in: indexPath.section)[indexPath.row] as! PTTorrentDownload AppDelegate.shared.downloadButton(button, wasPressedWith: download) { [unowned self] in self.tableView.reloadData() } } func cell(_ cell: DownloadDetailTableViewCell, longPressDetected gesture: UILongPressGestureRecognizer) { guard let indexPath = tableView.indexPath(for: cell) else { return } let download = activeDataSource(in: indexPath.section)[indexPath.row] as! PTTorrentDownload AppDelegate.shared.downloadButton(cell.downloadButton, wantsToStop: download) { [unowned self] in self.tableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DownloadDetailViewController, segue.identifier == "showDetail", let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { destination.show = activeDataSource(in: indexPath.section)[indexPath.row] as! Show } } }
gpl-3.0
e7e356b33526d340673731a6e065629c
44.494382
225
0.624722
5.780157
false
false
false
false
zwaldowski/Attendant
Attendant/Debounce.swift
1
5163
// // Debounce.swift // Attendant // // Created by Zachary Waldowski on 4/16/15. // Copyright © 2015-2016 Big Nerd Ranch. All rights reserved. // import Foundation private var debounceHashKey = false private extension StaticString { var debounceIdentifier: UInt { return withUnsafePointer(&debounceHashKey) { if hasPointerRepresentation { return unsafeBitCast(utf8Start, UInt.self) ^ unsafeBitCast($0, UInt.self) } else { return UInt(unicodeScalar.value) ^ unsafeBitCast($0, UInt.self) } } } } public protocol FunctionAssociation: AssociationType { init(identifier: UInt) } extension FunctionAssociation { public init(key: StaticString = __FUNCTION__) { self.init(identifier: key.debounceIdentifier) } public var policy: AssociationPolicy { return AssociationPolicy.Strong(atomic: true) } } private extension FunctionAssociation { private func reset(timer timer: dispatch_source_t, delay: NSTimeInterval) { dispatch_source_set_timer(timer, UInt64(delay * Double(NSEC_PER_SEC)), DISPATCH_TIME_FOREVER, NSEC_PER_SEC / 10) } private func makeTimer(delay delay: NSTimeInterval, upon queue: dispatch_queue_t, handler: () -> Void, cancelHandler: () -> Void) -> dispatch_source_t { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)! dispatch_source_set_event_handler(timer) { handler() dispatch_source_cancel(timer) } dispatch_source_set_cancel_handler(timer, cancelHandler) reset(timer: timer, delay: delay) return timer } private func scheduleTimer(after delay: NSTimeInterval, upon queue: dispatch_queue_t, @noescape getter: () -> dispatch_source_t?, setter: dispatch_source_t? -> Void, body: Void -> Void) { if let timer = getter() { reset(timer: timer, delay: delay) return } let timer = makeTimer(delay: delay, upon: queue, handler: body, cancelHandler: { setter(nil) }) setter(timer) dispatch_resume(timer) } func cancelTimer(@noescape getter: () -> dispatch_source_t?) { if let timer = getter() { dispatch_source_cancel(timer) } } } public struct EventAssociation<Sender: AnyObject>: FunctionAssociation { public typealias Value = dispatch_source_t public typealias Body = Sender -> Void public let identifier: UInt public init(identifier: UInt) { self.identifier = identifier } public var debugDescription: String { return "\(UnsafePointer<Void>(bitPattern: identifier)) for (\(Body.self))" } public func perform(onTarget target: Sender, after delay: NSTimeInterval = 0, upon queue: dispatch_queue_t = dispatch_get_main_queue(), body: Body) { scheduleTimer(after: delay, upon: queue, getter: { self[target] }, setter: { self[target] = $0 }, body: { body(target) }) } public func willBePerformed(onTarget target: Sender) -> Bool { return self[target] != nil } public func cancel(target target: Sender) { cancelTimer { self[target] } } } public struct TypeAssociation<Sender: NSObject>: FunctionAssociation { public typealias Value = dispatch_source_t public typealias Body = Sender.Type -> Void public let identifier: UInt public init(identifier: UInt) { self.identifier = identifier } public var debugDescription: String { return "\(UnsafePointer<Void>(bitPattern: identifier)) for (\(Body.self))" } public func perform(after delay: NSTimeInterval = 0, upon queue: dispatch_queue_t = dispatch_get_main_queue(), body: Sender.Type -> Void) { scheduleTimer(after: delay, upon: queue, getter: { self[Sender.self] }, setter: { self[Sender.self] = $0 }, body: { body(Sender.self) }) } public var willBePerformed: Bool { return self[Sender.self] != nil } public func cancel() { cancelTimer { self[Sender.self] } } } extension Association { public static func forEvent<Sender>(withKey key: StaticString = __FUNCTION__, withType _: Sender.Type = Sender.self) -> EventAssociation<Sender> { return .init(key: key) } public static func forEvent<Sender, Group: RawRepresentable where Group.RawValue == StaticString>(withKey key: Group, withType _: Sender.Type = Sender.self) -> EventAssociation<Sender> { return .init(key: key.rawValue) } public static func forEvent<Sender>(withKey key: StaticString = __FUNCTION__, uponType _: Sender.Type = Sender.self) -> TypeAssociation<Sender> { return .init(key: key) } public static func forEvent<Sender, Group: RawRepresentable where Group.RawValue == StaticString>(withKey key: Group, uponType _: Sender.Type = Sender.self) -> TypeAssociation<Sender> { return .init(key: key.rawValue) } }
mit
497e6a903eb406b2e73241e01b65b142
28.497143
191
0.63057
4.356118
false
false
false
false
Romdeau4/16POOPS
Helps_Kitchen_iOS/Help's Kitchen/CustomTableCell.swift
1
1516
// // CustomTableCell.swift // Help's Kitchen // // Created by Stephen Ulmer on 2/15/17. // Copyright © 2017 Stephen Ulmer. All rights reserved. // import UIKit class CustomTableCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setColors() { self.textLabel?.textColor = CustomColor.UCFGold self.backgroundColor = UIColor.black self.textLabel?.alpha = 1 } func setGreen() { self.textLabel?.textColor = CustomColor.green self.backgroundColor = UIColor.black self.textLabel?.alpha = 1 UIView.animate(withDuration: 0.7, delay: 0.0, options: [.repeat, .autoreverse, ], animations: { UIView.setAnimationRepeatCount(5) self.textLabel?.alpha = 0 }, completion: { (finished: Bool) in self.textLabel?.textColor = CustomColor.UCFGold self.textLabel?.alpha = 1 }) } func flashColor() { let when = DispatchTime.now() + 2 DispatchQueue.main.asyncAfter(deadline: when){ self.textLabel?.textColor = CustomColor.green self.backgroundColor = UIColor.black } } func setupTableNameLabel() { } }
mit
643fe86b0e762cb4931a7382bd3cb248
24.25
101
0.594059
4.704969
false
false
false
false
orta/apous
src/Utils.swift
1
1577
// // Utils.swift // apous // // Created by David Owens on 7/5/15. // Copyright © 2015 owensd.io. All rights reserved. // import Foundation /// Returns the root path that contains the script(s). /// This is func canonicalPath(item: String) throws -> String { func extract() -> String { if item.pathExtension == "swift" { let path = item.stringByDeletingLastPathComponent if path == "" { return NSFileManager.defaultManager().currentDirectoryPath } return path } else { return item } } let path = extract().stringByStandardizingPath var isDirectory: ObjCBool = false if NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) { return path } throw ErrorCode.PathNotFound } /// Exit the process error with the given `ErrorCode`. @noreturn func exit(code: ErrorCode) { exit(Int32(code.rawValue)) } /// Returns the full path of the valid script files at the given `path`. func filesAtPath(path: String) -> [String] { if DebugOutputEnabled { print("[debug] Finding script files at path: \(path)") } let items: [String] = { do { return try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) } catch { return [] } }() return items .filter() { $0 != ".apous.swift" && $0.pathExtension == "swift" } .map() { path.stringByAppendingPathComponent($0) } }
mit
c1d2abaacfe4b3cbba8877ecf56af91f
24.015873
89
0.589467
4.541787
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/HackerRank/Staircase/Staircase.swift
1
1193
// // Staircase.swift // WhiteBoardCodingChallenges // // Created by Boles on 07/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/staircase class Staircase: NSObject { class func staircase(height: Int) -> String { var staircaseString = "" for row in (0..<height).reversed() { var rowString = "" for element in 0..<height { var elementString = "" if element >= row { elementString = "#" } else { elementString = " " } rowString = "\(rowString)\(elementString)" } if staircaseString.count > 0 { staircaseString = "\(staircaseString)\n\(rowString)" } else { staircaseString = "\(rowString)" } } return staircaseString } }
mit
ddaadadca5975c7104090b883d74704d
22.372549
68
0.401007
5.90099
false
false
false
false
phr85/Shopy
Pods/EZLoadingActivity/EZLoadingActivity.swift
2
13169
// // EZLoadingActivity.swift // EZLoadingActivity // // Created by Goktug Yilmaz on 02/06/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit public struct EZLoadingActivity { //========================================================================================================== // Feel free to edit these variables //========================================================================================================== public struct Settings { public static var BackgroundColor = UIColor(red: 227/255, green: 232/255, blue: 235/255, alpha: 1.0) public static var ActivityColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0) public static var TextColor = UIColor(red: 80/255, green: 80/255, blue: 80/255, alpha: 1.0) public static var FontName = "HelveticaNeue-Light" // Other possible stuff: ✓ ✓ ✔︎ ✕ ✖︎ ✘ public static var SuccessIcon = "✔︎" public static var FailIcon = "✘" public static var SuccessText = "Success" public static var FailText = "Failure" public static var SuccessColor = UIColor(red: 68/255, green: 118/255, blue: 4/255, alpha: 1.0) public static var FailColor = UIColor(red: 255/255, green: 75/255, blue: 56/255, alpha: 1.0) public static var ActivityWidth = UIScreen.ScreenWidth / Settings.WidthDivision public static var ActivityHeight = ActivityWidth / 3 public static var ShadowEnabled = true public static var WidthDivision: CGFloat { get { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { return 3.5 } else { return 1.6 } } } public static var LoadOverApplicationWindow = false public static var DarkensBackground = false } fileprivate static var instance: LoadingActivity? fileprivate static var hidingInProgress = false fileprivate static var overlay: UIView! /// Disable UI stops users touch actions until EZLoadingActivity is hidden. Return success status @discardableResult public static func show(_ text: String, disableUI: Bool) -> Bool { guard instance == nil else { print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one") return false } guard topMostController != nil else { print("EZLoadingActivity Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.") return false } // Separate creation from showing instance = LoadingActivity(text: text, disableUI: disableUI) DispatchQueue.main.async { if Settings.DarkensBackground { if overlay == nil { overlay = UIView(frame: UIApplication.shared.keyWindow!.frame) } overlay.backgroundColor = UIColor.black.withAlphaComponent(0) topMostController?.view.addSubview(overlay) UIView.animate(withDuration: 0.2, animations: {overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0.5)}) } instance?.showLoadingActivity() } return true } @discardableResult public static func showWithDelay(_ text: String, disableUI: Bool, seconds: Double) -> Bool { let showValue = show(text, disableUI: disableUI) delay(seconds) { () -> () in _ = hide(true, animated: false) } return showValue } public static func showOnController(_ text: String, disableUI: Bool, controller:UIViewController) -> Bool{ guard instance == nil else { print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one") return false } instance = LoadingActivity(text: text, disableUI: disableUI) DispatchQueue.main.async { instance?.showLoadingWithController(controller) } return true } /// Returns success status @discardableResult public static func hide(_ success: Bool? = nil, animated: Bool = false) -> Bool { guard instance != nil else { print("EZLoadingActivity: You don't have an activity instance") return false } guard hidingInProgress == false else { print("EZLoadingActivity: Hiding already in progress") return false } if !Thread.current.isMainThread { DispatchQueue.main.async { instance?.hideLoadingActivity(success, animated: animated) } } else { instance?.hideLoadingActivity(success, animated: animated) } if overlay != nil { UIView.animate(withDuration: 0.2, animations: { overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0) }, completion: { _ in overlay.removeFromSuperview() }) } return true } fileprivate static func delay(_ seconds: Double, after: @escaping ()->()) { let queue = DispatchQueue.main let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: after) } fileprivate class LoadingActivity: UIView { var textLabel: UILabel! var activityView: UIActivityIndicatorView! var icon: UILabel! var UIDisabled = false convenience init(text: String, disableUI: Bool) { self.init(frame: CGRect(x: 0, y: 0, width: Settings.ActivityWidth, height: Settings.ActivityHeight)) center = CGPoint(x: topMostController!.view.bounds.midX, y: topMostController!.view.bounds.midY) autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin] backgroundColor = Settings.BackgroundColor alpha = 1 layer.cornerRadius = 8 if Settings.ShadowEnabled { createShadow() } let yPosition = frame.height/2 - 20 activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) activityView.frame = CGRect(x: 10, y: yPosition, width: 40, height: 40) activityView.color = Settings.ActivityColor activityView.startAnimating() textLabel = UILabel(frame: CGRect(x: 60, y: yPosition, width: Settings.ActivityWidth - 70, height: 40)) textLabel.textColor = Settings.TextColor textLabel.font = UIFont(name: Settings.FontName, size: 30) textLabel.adjustsFontSizeToFitWidth = true textLabel.minimumScaleFactor = 0.25 textLabel.textAlignment = NSTextAlignment.center textLabel.text = text if disableUI { UIApplication.shared.beginIgnoringInteractionEvents() UIDisabled = true } } func showLoadingActivity() { addSubview(activityView) addSubview(textLabel) //make it smoothly self.alpha = 0 if Settings.LoadOverApplicationWindow { UIApplication.shared.windows.first?.addSubview(self) } else { topMostController!.view.addSubview(self) } //make it smoothly UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 }) } func showLoadingWithController(_ controller:UIViewController){ addSubview(activityView) addSubview(textLabel) //make it smoothly self.alpha = 0 controller.view.addSubview(self) UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 }) } func createShadow() { layer.shadowPath = createShadowPath().cgPath layer.masksToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 5 layer.shadowOpacity = 0.5 } func createShadowPath() -> UIBezierPath { let myBezier = UIBezierPath() myBezier.move(to: CGPoint(x: -3, y: -3)) myBezier.addLine(to: CGPoint(x: frame.width + 3, y: -3)) myBezier.addLine(to: CGPoint(x: frame.width + 3, y: frame.height + 3)) myBezier.addLine(to: CGPoint(x: -3, y: frame.height + 3)) myBezier.close() return myBezier } func hideLoadingActivity(_ success: Bool?, animated: Bool) { hidingInProgress = true if UIDisabled { UIApplication.shared.endIgnoringInteractionEvents() } var animationDuration: Double = 0 if success != nil { if success! { animationDuration = 0.5 } else { animationDuration = 1 } } icon = UILabel(frame: CGRect(x: 10, y: frame.height/2 - 20, width: 40, height: 40)) icon.font = UIFont(name: Settings.FontName, size: 60) icon.textAlignment = NSTextAlignment.center if animated { textLabel.fadeTransition(animationDuration) } if success != nil { if success! { icon.textColor = Settings.SuccessColor icon.text = Settings.SuccessIcon textLabel.text = Settings.SuccessText } else { icon.textColor = Settings.FailColor icon.text = Settings.FailIcon textLabel.text = Settings.FailText } } addSubview(icon) if animated { icon.alpha = 0 activityView.stopAnimating() UIView.animate(withDuration: animationDuration, animations: { self.icon.alpha = 1 }, completion: { (value: Bool) in UIView.animate(withDuration: 0.2, animations: { self.alpha = 0 }, completion: { (success) in self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration) }) instance = nil hidingInProgress = false }) } else { activityView.stopAnimating() self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration) instance = nil hidingInProgress = false } } } } private extension UIView { /// Extension: insert view.fadeTransition right before changing content func fadeTransition(_ duration: CFTimeInterval) { let animation: CATransition = CATransition() animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.type = kCATransitionFade animation.duration = duration self.layer.add(animation, forKey: kCATransitionFade) } } private extension NSObject { func callSelectorAsync(_ selector: Selector, delay: TimeInterval) { let timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: selector, userInfo: nil, repeats: false) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) } } private extension UIScreen { class var Orientation: UIInterfaceOrientation { get { return UIApplication.shared.statusBarOrientation } } class var ScreenWidth: CGFloat { get { if UIInterfaceOrientationIsPortrait(Orientation) { return UIScreen.main.bounds.size.width } else { return UIScreen.main.bounds.size.height } } } class var ScreenHeight: CGFloat { get { if UIInterfaceOrientationIsPortrait(Orientation) { return UIScreen.main.bounds.size.height } else { return UIScreen.main.bounds.size.width } } } } private var topMostController: UIViewController? { var presentedVC = UIApplication.shared.keyWindow?.rootViewController while let pVC = presentedVC?.presentedViewController { presentedVC = pVC } return presentedVC }
mit
fc625caee19e0c4a6f7c0689b19e4c59
38.244776
142
0.564616
5.500837
false
false
false
false
hgani/ganilib-ios
glib/Classes/View/Layout/GHorizontalPanel.swift
1
4805
import SnapKit import UIKit open class GHorizontalPanel: UIView { fileprivate var helper: ViewHelper! private var previousView: UIView? private var previousLayoutPriority: UILayoutPriority? private var rightConstraint: Constraint? private var totalGap = Float(0.0) private var paddings: Paddings { return helper.paddings } public init() { super.init(frame: .zero) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { helper = ViewHelper(self) _ = paddings(top: 0, left: 0, bottom: 0, right: 0) } open override func didMoveToSuperview() { super.didMoveToSuperview() helper.didMoveToSuperview() } public func clearViews() { previousView = nil rightConstraint = nil for view in subviews { view.removeFromSuperview() } } public func addView(_ child: UIView, left: Float = 0) { totalGap += left // The hope is this makes things more predictable child.translatesAutoresizingMaskIntoConstraints = false super.addSubview(child) initChildConstraints(child: child, left: left) adjustParentBottomConstraint(child: child) previousView = child } @discardableResult public func append(_ child: UIView, left: Float = 0) -> Self { addView(child, left: left) return self } // See https://github.com/zaxonus/AutoLayScroll/blob/master/AutoLayScroll/ViewController.swift private func initChildConstraints(child: UIView, left: Float) { child.snp.makeConstraints { make in make.top.equalTo(self.snp.topMargin) if let view = previousView { make.left.equalTo(view.snp.right).offset(left) } else { make.left.equalTo(self.snp.leftMargin).offset(left) } } } private func adjustParentBottomConstraint(child: UIView) { snp.makeConstraints { make in // Don't use greaterThanOrEqualTo() or else this view will get stretched in HamburgerPanel. // make.bottomMargin.equalTo(child.snp.bottom) make.bottomMargin.greaterThanOrEqualTo(child.snp.bottom) } if helper.shouldWidthMatchParent() { rightConstraint?.deactivate() child.snp.makeConstraints { make in rightConstraint = make.right.lessThanOrEqualTo(self.snp.rightMargin).constraint } // Decrease resistance of the last view to avoid squashing the previous views which // would happen if the last view is longer than the available space. if let view = previousView, let priority = previousLayoutPriority { ViewHelper.setResistance(view: view, axis: .horizontal, priority: priority) } previousLayoutPriority = ViewHelper.decreaseResistance(view: child, axis: .horizontal) } else { rightConstraint?.deactivate() child.snp.makeConstraints { make in rightConstraint = make.right.equalTo(self.snp.rightMargin).constraint } } } public func split() -> Self { let count = subviews.count GLog.i("Splitting \(count) views ...") let weight = 1.0 / Float(count) let offset = -(totalGap + paddings.left + paddings.right) / Float(count) for view in subviews { if let weightable = view as? GWeightable { _ = weightable.width(weight: weight, offset: offset) } else { GLog.e("Invalid child view: \(view)") } } return self } open override func addSubview(_: UIView) { fatalError("Use addView() instead") } public func done() { // Ends chaining } } extension GHorizontalPanel: IView { public var size: CGSize { return helper.size } public func color(bg: UIColor) -> Self { backgroundColor = bg return self } public func width(_ width: Int) -> Self { helper.width(width) return self } public func width(_ width: LayoutSize) -> Self { helper.width(width) return self } public func height(_ height: Int) -> Self { helper.height(height) return self } public func height(_ height: LayoutSize) -> Self { helper.height(height) return self } public func paddings(top: Float? = nil, left: Float? = nil, bottom: Float? = nil, right: Float? = nil) -> Self { helper.paddings(t: top, l: left, b: bottom, r: right) return self } }
mit
2a67d4a992b41da3c31e506f20790802
27.431953
116
0.601041
4.73399
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/Storage Service/StorageServiceProto+Sync.swift
1
7311
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation // Helpers for building and restoring contact records. extension StorageServiceProtoContactRecord { // MARK: - Dependencies static var profileManager: OWSProfileManager { return .shared() } var profileManager: OWSProfileManager { return .shared() } static var blockingManager: OWSBlockingManager { return .shared() } var blockingManager: OWSBlockingManager { return .shared() } static var identityManager: OWSIdentityManager { return .shared() } var identityManager: OWSIdentityManager { return .shared() } static var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: - static func build( for accountId: AccountId, contactIdentifier: StorageService.ContactIdentifier, transaction: SDSAnyReadTransaction ) throws -> StorageServiceProtoContactRecord { guard let address = OWSAccountIdFinder().address(forAccountId: accountId, transaction: transaction) else { throw StorageService.StorageError.assertion } let builder = StorageServiceProtoContactRecord.builder(key: contactIdentifier.data) if let phoneNumber = address.phoneNumber { builder.setServiceE164(phoneNumber) } if let uuidString = address.uuidString { builder.setServiceUuid(uuidString) } var isInWhitelist: Bool = false var profileKey: Data? var profileName: String? var profileAvatarData: Data? databaseStorage.read { transaction in isInWhitelist = profileManager.isUser(inProfileWhitelist: address, transaction: transaction) profileKey = profileManager.profileKeyData(for: address, transaction: transaction) profileName = profileManager.profileName(for: address, transaction: transaction) profileAvatarData = profileManager.profileAvatarData(for: address, transaction: transaction) } builder.setBlocked(blockingManager.isAddressBlocked(address)) builder.setWhitelisted(isInWhitelist) // Identity let identityBuilder = StorageServiceProtoContactRecordIdentity.builder() if let identityKey = identityManager.identityKey(for: address, transaction: transaction) { identityBuilder.setKey(identityKey) } let verificationState = identityManager.verificationState(for: address, transaction: transaction) identityBuilder.setState(.from(verificationState)) builder.setIdentity(try identityBuilder.build()) // Profile let profileBuilder = StorageServiceProtoContactRecordProfile.builder() if let profileKey = profileKey { profileBuilder.setKey(profileKey) } if let profileName = profileName { profileBuilder.setName(profileName) } if let profileAvatarData = profileAvatarData { profileBuilder.setAvatar(profileAvatarData) } builder.setProfile(try profileBuilder.build()) return try builder.build() } enum MergeState { case resolved(AccountId) case needsUpdate(AccountId) case invalid } func mergeWithLocalContact(transaction: SDSAnyWriteTransaction) -> MergeState { guard let address = serviceAddress else { owsFailDebug("address unexpectedly missing for contact") return .invalid } // Mark the user as registered, only registered contacts should exist in the sync'd data. let recipient = SignalRecipient.mark(asRegisteredAndGet: address, transaction: transaction) var mergeState: MergeState = .resolved(recipient.accountId) // If we don't yet have a profile for this user, restore the profile information. // Otherwise, assume ours is the defacto version and mark this user as pending update. if let profile = profile, profileManager.profileKey(for: address, transaction: transaction) == nil { if let key = profile.key { profileManager.setProfileKeyData(key, for: address, transaction: transaction) } // TODO: Maybe restore the name and avatar? For now we'll refetch them once we set the key. } else { mergeState = .needsUpdate(recipient.accountId) } // If we don't yet have an identity key for this user, restore the identity information. // Otherwise, assume ours is the defacto version and mark this user as pending update. if let identity = identity, identityManager.identityKey(for: address) == nil { if let state = identity.state?.verificationState, let key = identity.key { identityManager.setVerificationState( state, identityKey: key, address: address, isUserInitiatedChange: false, transaction: transaction ) } } else { mergeState = .needsUpdate(recipient.accountId) } // If our block state doesn't match the conflicted version, default to whichever // version is currently blocked. We don't want to unblock someone accidentally // through a conflict resolution. if hasBlocked, blocked != blockingManager.isAddressBlocked(address) { if blocked { blockingManager.addBlockedAddress(address) } else { mergeState = .needsUpdate(recipient.accountId) } } // If our whitelist state doesn't match the conflicted version, default to // being whitelisted. There's currently no way to unwhitelist a contact. if hasWhitelisted, whitelisted != profileManager.isUser(inProfileWhitelist: address, transaction: transaction) { if whitelisted { profileManager.addUser(toProfileWhitelist: address) } else { mergeState = .needsUpdate(recipient.accountId) } } return mergeState } } // MARK: - extension StorageServiceProtoContactRecordIdentity.StorageServiceProtoContactRecordIdentityState { static func from(_ state: OWSVerificationState) -> StorageServiceProtoContactRecordIdentity.StorageServiceProtoContactRecordIdentityState { switch state { case .verified: return .verified case .default: return .default case .noLongerVerified: return .unverified @unknown default: owsFailDebug("unexpected verification state") return .default } } var verificationState: OWSVerificationState { switch self { case .verified: return .verified case .default: return .default case .unverified: return .noLongerVerified } } }
gpl-3.0
a8ee9078e0e95eba0ff87bde56c99dbd
33.814286
143
0.628779
5.872289
false
false
false
false
royhsu/chocolate-touch
Source/CHCacheTableViewController.swift
1
10232
// // CHCacheTableViewController.swift // Chocolate // // Created by 許郁棋 on 2016/7/9. // Copyright © 2016年 Tiny World. All rights reserved. // import CHFoundation import CoreData import PromiseKit // MARK: - CHTableViewCacheDataSource public protocol CHTableViewCacheDataSource: class { func numberOfSections() -> Int func numberOfRows(inSection section: Int) -> Int func jsonObject(with objects: [Any], forRowsAt indexPath: IndexPath) -> Any? } // TODO: a expiration time for refreshing data. // MARK: - CHCacheTableViewController open class CHCacheTableViewController: CHTableViewController, CHTableViewCacheDataSource, NSFetchedResultsControllerDelegate { public enum CacheTableViewError: Swift.Error { case fetchedResultsControllerNotReady case invalideCaches } // MARK: Property let cacheIdentifier: String private let cache = CHCache.default public private(set) var fetchedResultsController: NSFetchedResultsController<CHCacheEntity>? public var isCached: Bool { let fetchedObjects = fetchedResultsController?.fetchedObjects ?? [] return !fetchedObjects.isEmpty } public weak var cacheDataSource: CHTableViewCacheDataSource? /// An array that keeps all web requests. public var webRequests: [CHCacheWebRequest] = [] // MARK: Init public init(cacheIdentifier: String) { self.cacheIdentifier = cacheIdentifier super.init(style: .plain) cacheDataSource = self } private override init() { fatalError() } required public init?(coder aDecoder: NSCoder) { fatalError() } // MARK: Set Up public final func setUpFetchedResultsController(storeType: CoreDataStack.StoreType? = nil) -> Promise<Void> { return cache .loadStore(type: storeType) .then { stack -> Void in let fetchRequest = CHCacheEntity.fetchRequest fetchRequest.predicate = NSPredicate(format: "identifier==%@", self.cacheIdentifier) fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "section", ascending: true), NSSortDescriptor(key: "row", ascending: true) ] let fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: stack.viewContext, sectionNameKeyPath: "section", cacheName: self.cacheIdentifier ) fetchedResultsController.delegate = self self.fetchedResultsController = fetchedResultsController } .then { self.performFetch() } .then { self.clearInvalidCaches() } } // MARK: Web Request /** Perform all requests inside the webRequests property. - Returns: A promise object carries all transformed json objects for web requests. - Note: Please use this method the excute all the web requests instead of request them individually. */ internal final func performWebRequests() -> Promise<[Any]> { let requests = webRequests.map { $0.execute() } return when(fulfilled: requests) } // MARK: Cache internal final func clearCache() -> Promise<Void> { return cache .deleteCache(with: cacheIdentifier) .then { _ in self.saveCaches() } .then { _ -> Void in NSFetchedResultsController<CHCacheEntity>.deleteCache(withName: self.cacheIdentifier) } } /** Insert caches based on provided CHCacheTableViewDataSource. - Parameter objects: All feeding json objects for CHCacheTableViewDataSource. - Returns: A promise object. - Note: Please make sure to call save method on the cache context manually if you want to keep the insertions. */ internal final func insertCaches(with objects: [Any]) -> Promise<[NSManagedObjectID]> { let sections = cacheDataSource?.numberOfSections() ?? 0 var insertions: [Promise<NSManagedObjectID>] = [] for section in 0..<sections { let rows = cacheDataSource?.numberOfRows(inSection: section) ?? 0 for row in 0..<rows { let indexPath = IndexPath(row: row, section: section) let jsonObject = cacheDataSource?.jsonObject(with: objects, forRowsAt: indexPath) ?? [AnyHashable: Any]() let insertion = cache.insert( identifier: cacheIdentifier, section: section, row: row, jsonObject: jsonObject ) insertions.append(insertion) } } return when(fulfilled: insertions) } internal final func saveCaches() -> Promise<Void> { return cache.save().asVoid() } internal final func validateCaches() -> Promise<Void> { return Promise { fulfill, reject in guard let fetchedObjects = fetchedResultsController?.fetchedObjects else { reject(CacheTableViewError.fetchedResultsControllerNotReady) return } let sections = cacheDataSource?.numberOfSections() ?? 0 var numberOfObjectsDefinedInDataSource = 0 for section in 0..<sections { let rows = cacheDataSource?.numberOfRows(inSection: section) ?? 0 for _ in 0..<rows { numberOfObjectsDefinedInDataSource += 1 } } if numberOfObjectsDefinedInDataSource == fetchedObjects.count { fulfill() } else { reject(CacheTableViewError.invalideCaches) } } } private func clearInvalidCaches() -> Promise<Void> { return Promise { fulfill, reject in let _ = self.validateCaches() .then { fulfill() } .catch { if let error = $0 as? CacheTableViewError, error == .invalideCaches { let _ = self.clearCache() .then { self.performFetch() } .then { fulfill() } .catch { reject($0) } } else { reject($0) } } } } // MARK: Fetched Results Controller /// Trigger fetched results controller to perform fetching. internal final func performFetch() -> Promise<Void> { return Promise { fulfill, reject in guard let fetchedResultsController = fetchedResultsController else { reject(CacheTableViewError.fetchedResultsControllerNotReady) return } do { try fetchedResultsController.performFetch() fulfill() } catch { reject(error) } } } // MARK: Action public final func fetch() -> Promise<Void> { return performWebRequests() .then { self.insertCaches(with: $0).asVoid() } .then { self.saveCaches() } .then { self.performFetch() } } public final func refresh() -> Promise<Void> { return clearCache().then { self.fetch() } } // MARK: UITableViewDataSource public final override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } public final override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sectionInfo = fetchedResultsController?.sections?[section] else { return 0 } return sectionInfo.numberOfObjects } // MARK: JSON Object public final func jsonObject(at indexPath: IndexPath) -> Any? { if !isCached { return nil } guard let cache = fetchedResultsController?.object(at: indexPath), let jsonObject = try? cache.data.jsonObject() else { return nil } return jsonObject } // MARK: CHTableViewCacheDataSource open func numberOfSections() -> Int { return 0 } open func numberOfRows(inSection section: Int) -> Int { return 0 } open func jsonObject(with objects: [Any], forRowsAt indexPath: IndexPath) -> Any? { return nil } }
mit
d1ea94492da12a986e8d5b14daca998d
26.334225
126
0.496625
6.638312
false
false
false
false
jevy-wangfei/FeedMeIOS
SSRadioButton.swift
3
3223
// // SSRadioButton.swift // SampleProject // // Created by Shamas on 18/05/2015. // Copyright (c) 2015 Al Shamas Tufail. All rights reserved. // // Modified by Jun Chen on 30/03/2016. // Copyright © 2016 FeedMe. All rights reserved. // import UIKit @IBDesignable class SSRadioButton: UIButton { private var circleLayer = CAShapeLayer() private var fillCircleLayer = CAShapeLayer() override var selected: Bool { didSet { toggleButon() } } /** Color of the radio button circle. Default value is UIColor green. */ @IBInspectable var circleColor: UIColor = UIColor.blueColor() { didSet { circleLayer.strokeColor = circleColor.CGColor self.toggleButon() } } /** Radius of RadioButton circle. */ @IBInspectable var circleRadius: CGFloat = 15.0 @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } private func circleFrame() -> CGRect { var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius) circleFrame.origin.x = 0 + circleLayer.lineWidth circleFrame.origin.y = bounds.height/2 - circleFrame.height/2 return circleFrame } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } private func initialize() { circleLayer.frame = bounds circleLayer.lineWidth = 2 circleLayer.fillColor = UIColor.clearColor().CGColor circleLayer.strokeColor = circleColor.CGColor layer.addSublayer(circleLayer) fillCircleLayer.frame = bounds fillCircleLayer.lineWidth = 2 fillCircleLayer.fillColor = UIColor.clearColor().CGColor fillCircleLayer.strokeColor = UIColor.clearColor().CGColor layer.addSublayer(fillCircleLayer) self.titleEdgeInsets = UIEdgeInsetsMake(0, (4*circleRadius + 4*circleLayer.lineWidth), 0, 0) self.toggleButon() } /** Toggles selected state of the button. */ func toggleButon() { if self.selected { fillCircleLayer.fillColor = circleColor.CGColor } else { fillCircleLayer.fillColor = UIColor.clearColor().CGColor } } private func circlePath() -> UIBezierPath { return UIBezierPath(ovalInRect: circleFrame()) } private func fillCirclePath() -> UIBezierPath { return UIBezierPath(ovalInRect: CGRectInset(circleFrame(), 2, 2)) } override func layoutSubviews() { super.layoutSubviews() circleLayer.frame = bounds circleLayer.path = circlePath().CGPath fillCircleLayer.frame = bounds fillCircleLayer.path = fillCirclePath().CGPath self.titleEdgeInsets = UIEdgeInsetsMake(0, (2*circleRadius + 4*circleLayer.lineWidth), 0, 0) } override func prepareForInterfaceBuilder() { initialize() } }
mit
1395a68e6a7bd8078140c48a25b8fc54
27.767857
100
0.625698
5.058085
false
false
false
false
OAuthSwift/OAuthSwiftFutures
Sources/OAuthSwift+BrightFutures.swift
1
3105
// // OAuthSwift+BrightFutures.swift // OAuthSwift+BrightFutures // // Created by phimage on 13/12/15. // Copyright © 2015 phimage. All rights reserved. // import Foundation import OAuthSwift import BrightFutures extension OAuthSwift { public typealias FutureSuccess = (credential: OAuthSwiftCredential, response: OAuthSwiftResponse?, parameters: OAuthSwift.Parameters) // see OAuthSwift.TokenSuccessHandler public typealias FutureError = OAuthSwiftError public typealias FutureResult = (future: Future<FutureSuccess, FutureError>, handle: OAuthSwiftRequestHandle?) } extension OAuth1Swift { open func authorizeFuture(withCallbackURL callbackURL: String) -> FutureResult { let promise = Promise<FutureSuccess, FutureError>() let handle = authorize( withCallbackURL: callbackURL, success: { credential, response, parameters in promise.success((credential, response, parameters)) }, failure: { error in promise.failure(error) } ) return (promise.future, handle) } open func authorizeFuture(withCallbackURL callbackURL: URL) -> FutureResult { let promise = Promise<FutureSuccess, FutureError>() let handle = authorize( withCallbackURL: callbackURL, success: { credential, response, parameters in promise.success((credential, response, parameters)) }, failure:{ error in promise.failure(error) } ) return (promise.future, handle) } } extension OAuth2Swift { open func authorizeFuture(withCallbackURL callbackURL: URL, scope: String, state: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil) -> FutureResult { let promise = Promise<FutureSuccess, FutureError>() let handle = authorize( withCallbackURL: callbackURL, scope: scope, state: state, parameters: parameters, headers: headers, success: { credential, response, parameters in promise.success((credential, response, parameters)) }, failure:{ (error) -> Void in promise.failure(error) } ) return (promise.future, handle) } open func authorizeFuture(withCallbackURL callbackURL: String, scope: String, state: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil) -> FutureResult { let promise = Promise<FutureSuccess, FutureError>() let handle = authorize( withCallbackURL: callbackURL, scope: scope, state: state, parameters: parameters, headers: headers, success: { credential, response, parameters in promise.success((credential, response, parameters)) }, failure:{ (error) -> Void in promise.failure(error) } ) return (promise.future, handle) } }
mit
226b869f33ba5369945732e89d70a8d2
32.376344
191
0.620168
5.474427
false
false
false
false
JaSpa/swift
test/SILOptimizer/definite_init_protocol_init.swift
3
5216
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-sil %s | %FileCheck %s // Ensure that convenience initializers on concrete types can // delegate to factory initializers defined in protocol // extensions. protocol TriviallyConstructible { init(lower: Int) } extension TriviallyConstructible { init(middle: Int) { self.init(lower: middle) } init?(failingMiddle: Int) { self.init(lower: failingMiddle) } init(throwingMiddle: Int) throws { try self.init(lower: throwingMiddle) } } class TrivialClass : TriviallyConstructible { required init(lower: Int) {} // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B012TrivialClassCACSi5upper_tcfc // CHECK: bb0(%0 : $Int, %1 : $TrivialClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialClass // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick TrivialClass.Type, %1 // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $TrivialClass // CHECK-NEXT: apply [[FN]]<TrivialClass>([[RESULT]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[RESULT]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick TrivialClass.Type, %1 // CHECK-NEXT: dealloc_partial_ref %1 : $TrivialClass, [[METATYPE]] : $@thick TrivialClass.Type // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] convenience init(upper: Int) { self.init(middle: upper) } convenience init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } convenience init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } struct TrivialStruct : TriviallyConstructible { let x: Int init(lower: Int) { self.x = lower } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B013TrivialStructVACSi5upper_tcfC // CHECK: bb0(%0 : $Int, %1 : $@thin TrivialStruct.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialStruct // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialStruct.Type // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialStruct // CHECK-NEXT: apply [[FN]]<TrivialStruct>([[SELF_BOX]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[NEW_SELF]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } struct AddressOnlyStruct : TriviallyConstructible { let x: Any init(lower: Int) { self.x = lower } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B017AddressOnlyStructVACSi5upper_tcfC // CHECK: bb0(%0 : $*AddressOnlyStruct, %1 : $Int, %2 : $@thin AddressOnlyStruct.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $AddressOnlyStruct // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick AddressOnlyStruct.Type // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $AddressOnlyStruct // CHECK-NEXT: apply [[FN]]<AddressOnlyStruct>([[SELF_BOX]], %1, [[METATYPE]]) // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [initialization] [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[SELF]] to [initialization] %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[RESULT]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } enum TrivialEnum : TriviallyConstructible { case NotSoTrivial init(lower: Int) { self = .NotSoTrivial } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B011TrivialEnumOACSi5upper_tcfC // CHECK: bb0(%0 : $Int, %1 : $@thin TrivialEnum.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialEnum // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialEnum.Type // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialEnum // CHECK-NEXT: apply [[FN]]<TrivialEnum>([[SELF_BOX]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[NEW_SELF]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } }
apache-2.0
68df761f489f0e94176913d02748c22b
34.482993
119
0.666794
3.484302
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
iOS/Healthcare/DataSources/DataManager.swift
1
3778
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** Enum to report the state of the login attempt. */ enum LogInResultType { case Success case FailWrongUserID case FailWrongPassword } /** Data Manager is a wrapper to the database connection */ class DataManager: NSObject, WLDataDelegate { private(set) var currentPatient : Patient! private(set) var routines : Routine! private(set) var exercises : Exercise! typealias LogInCallback = (LogInResultType)->Void var userId : String! var logInCallback: LogInCallback! //Class variable that will return a singleton when requested class var dataManager : DataManager{ struct Singleton { static let instance = DataManager() } return Singleton.instance } /** Method called by to sign in a user - parameter userID: string value passed from another class - parameter password: string value passed from another class - parameter callback: function from the class that called this function. Is executed with a enum as a parameter */ func signIn(userID: String!, password: String!, callback: (LogInResultType)->()) { // Override point for customization after application launch. logInCallback = callback let adapterName : String = "HealthcareAdapter" let procedureName : String = "getUserObject" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName, dataDelegate: self) let params : [String] = [userID] self.userId = userID caller.invokeWithResponse(self, params: params) } /** Delgate method for WorkLight. Called when connection and return is successful - parameter response: Response from WorkLight */ func onSuccess(response: WLResponse!) { let responseJson = response.getResponseJson() as NSDictionary currentPatient = Patient(worklightResponseJson: responseJson) //routines = Routine(worklightResponseJson: responseJson) //exercises = Exercise(worklightResponseJson: responseJson) logInCallback(LogInResultType.Success) } /** Delgate method for WorkLight. Called when connection or return is unsuccessful - parameter response: Response from WorkLight */ func onFailure(response: WLFailResponse!) { print(response.responseText) logInCallback(LogInResultType.FailWrongPassword) } /** Delgate method for WorkLight. Task to do before executing a call. */ func onPreExecute() { } /** Delgate method for WorkLight. Task to do after executing a call. */ func onPostExecute() { } /* Method called to get routines :param: userId */ func getRoutines(userID: String!) { let adapterName : String = "HealthcareAdapter" let procedureName : String = "getRoutines" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName, dataDelegate: self) let params : [String] = [userID] caller.invokeWithResponse(self, params: params) } /* Method called to get routines :param: userId :param: routineTitle */ func getRoutinesForPatient(routineId: String!) { let adapterName : String = "HealthcareAdapter" let procedureName : String = "getRoutinesForPatient" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName, dataDelegate: self) let params : [String] = [routineId] caller.invokeWithResponse(self, params: params) } }
epl-1.0
31fec2802e0878e350dd8d8a0d34f289
29.967213
115
0.666931
5.224066
false
false
false
false