repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Movie-电影/Model/JENMovieItem.swift
mit
1
// // JENMovieItem.swift // ONE_Swift // // Created by 任玉祥 on 16/5/11. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit // MARK: - 电影列表模型 class JENMovieListItem: NSObject { /// id var detail_id: String? /// 标题 var title: String? /// 评分 var score: String? /// 图片url var cover: String? // var releasetime: String? // var scoretime: String? // var servertime: Int = 0 // var revisedscore: String? // var verse: String? // var verse_en: String? } // MARK: - 详情模型 class JENMovieDetailItem: JENMovieListItem { var detailcover: String? var keywords: String? var movie_id: String? var info: String? var charge_edt: String? var praisenum = 0 var sort: String? var maketime: String? var photo = [String]() var sharenum = 0 var commentnum = 0 var servertime = 0 // var indexcover: String? // var video: String? // var review: String? // var officialstory: String? // var web_url: String? // var releasetime: String? // var scoretime: String? // var last_update_date: String? // var read_num: String? // var push_id: String? } class JENMovieStroyResult: NSObject { var count = 0 var data = [JENMovieStoryItem]() } class JENMovieStoryItem: NSObject { /// id var story_id: String? var movie_id: String? var title: String? var content: String? var user_id: String? var sort: String? var praisenum = 0 var input_date: String? var story_type: String? var user = JENAuthorItem() }
0a6beb443c3c13c31a90c17b45aaa486
17.848837
47
0.595679
false
false
false
false
icapps/ios_objective_c_workshop
refs/heads/master
Students/Naomi/ObjcTextInput/ObjcTextInput/Modules/TextInput/TIITransitionManager.swift
mit
1
// // TIITransitionManager.swift // // // Created by Naomi De Leeuw on 16/11/2017. // import UIKit @objc class TIITransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = true func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let offScreenRight = CGAffineTransform(translationX: container.frame.width, y: 0) let offScreenLeft = CGAffineTransform(translationX: -container.frame.width, y: 0) if (self.presenting){ toView.transform = offScreenRight } else { toView.transform = offScreenLeft } container.addSubview(toView) container.addSubview(fromView) let duration = self.transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.curveEaseIn, animations: { if (self.presenting){ fromView.transform = offScreenLeft } else { fromView.transform = offScreenRight } toView.transform = .identity }, completion: { finished in transitionContext.completeTransition(true) }) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } }
b2e624a94b74e3602574bd79d4b8d80d
34.79661
174
0.696496
false
false
false
false
LbfAiYxx/douyuTV
refs/heads/master
DouYu/DouYu/Classes/Main/view/PageContentView.swift
mit
1
// // PageContentView.swift // DouYu // // Created by 刘冰峰 on 2016/12/15. // Copyright © 2016年 LBF. All rights reserved. // import UIKit protocol contentViewDelegate : class{ func contentView(progress: CGFloat,currentIndex: Int,oldIndex:Int) } class PageContentView: UIView { fileprivate var oldOffsetX :CGFloat = 0 fileprivate var currentOffsetX :CGFloat = 0 fileprivate var currentIndeX = 0 fileprivate var oldIndeX = 0 weak var delegate: contentViewDelegate? fileprivate var childVc: [UIViewController] //解除循环引用 fileprivate weak var parentcontroller: UIViewController? //懒加载collectionView fileprivate lazy var collectionView :UICollectionView = { [weak self] in //设置布局 let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 //强行解包 layout.itemSize = (self?.bounds.size)! layout.scrollDirection = .horizontal //创建collectionView let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self as UICollectionViewDelegate? collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID") return collectionView }() init(frame: CGRect,childVc: [UIViewController],parentcontroller: UIViewController?) { self.childVc = childVc self.parentcontroller = parentcontroller super.init(frame: frame) //添加scrollView setUpCollectionView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ //添加collectionView fileprivate func setUpCollectionView(){ //添加子控制器到父控制器中 for childvc in childVc { parentcontroller?.addChildViewController(childvc) } addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVc.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) //移除循环利用里面的View for view in cell.contentView.subviews { view.removeFromSuperview() } //添加控制器视图在cell里面 childVc[indexPath.item].view.frame = cell.contentView.frame cell.contentView.addSubview(childVc[indexPath.item].view) return cell } } extension PageContentView{ //对外暴露方法,传值 func changeIndex(Index : Int){ //计算平移量 let offsetX = CGFloat(Index) * CscreenW collectionView.contentOffset.x = offsetX } } extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { oldOffsetX = scrollView.contentOffset.x } //监听滚动 func scrollViewDidScroll(_ scrollView: UIScrollView) { //动态偏移量 currentOffsetX = scrollView.contentOffset.x //设置进度条变量 var progress :CGFloat = 0 //左滑动、滚动进度 if currentOffsetX > oldOffsetX { progress = currentOffsetX/CscreenW - floor(currentOffsetX/CscreenW) oldIndeX = Int(currentOffsetX/CscreenW) if oldIndeX < 3 { currentIndeX = Int(currentOffsetX/CscreenW) + 1 } if currentOffsetX - oldOffsetX == CscreenW { progress = 1 currentIndeX = oldIndeX } } //右滑动、滚动进度 if currentOffsetX < oldOffsetX { progress = 1 - (currentOffsetX/CscreenW - floor(currentOffsetX/CscreenW)) if oldOffsetX - currentOffsetX == CscreenW { progress = 1 } currentIndeX = Int(currentOffsetX/CscreenW) oldIndeX = Int(currentOffsetX/CscreenW) + 1 } //通知代理 delegate?.contentView(progress: progress, currentIndex: currentIndeX, oldIndex: oldIndeX) } }
656068d2b85b5f158eb8681ca0f68272
29.295302
132
0.651086
false
false
false
false
Jnosh/swift
refs/heads/master
test/IDE/complete_enum_elements.swift
apache-2.0
3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_TYPE_CONTEXT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_WITH_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT_ELEMENTS < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_WITH_QUAL_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_EXPR_ERROR_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_IN_PATTERN_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=WITH_GLOBAL_RESULTS < %t.enum.txt // RUN: %FileCheck %s -check-prefix=ENUM_SW_IN_PATTERN_1 < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_SW_IN_PATTERN_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=ENUM_SW_IN_PATTERN_2 < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_INT_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_T_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_NO_DOT_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_NO_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_1 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=FOO_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_2 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAR_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_3 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_INT_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_4 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=BAZ_T_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_QUAL_DOT_5 > %t.enum.txt // RUN: %FileCheck %s -check-prefix=QUX_ENUM_DOT < %t.enum.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=WITH_INVALID_DOT_1 | %FileCheck %s -check-prefix=WITH_INVALID_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_1 | %FileCheck %s -check-prefix=UNRESOLVED_1 //===--- //===--- Test that we can complete enum elements. //===--- //===--- Helper types. enum FooEnum { case Foo1 case Foo2 } // FOO_ENUM_TYPE_CONTEXT: Begin completions // FOO_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_TYPE_CONTEXT: End completions // FOO_ENUM_NO_DOT: Begin completions // FOO_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_NO_DOT-NEXT: End completions // FOO_ENUM_DOT: Begin completions // FOO_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT-NEXT: End completions // FOO_ENUM_DOT_ELEMENTS: Begin completions, 2 items // FOO_ENUM_DOT_ELEMENTS-NEXT: Decl[EnumElement]/ExprSpecific: Foo1[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT_ELEMENTS-NEXT: Decl[EnumElement]/ExprSpecific: Foo2[#FooEnum#]{{; name=.+$}} // FOO_ENUM_DOT_ELEMENTS-NEXT: End completions enum BarEnum { case Bar1 case Bar2() case Bar3(Int) case Bar4(a: Int, b: Float) case Bar5(a: Int, (Float)) case Bar6(a: Int, b: (Float)) case Bar7(a: Int, (b: Float, c: Double)) case Bar8(a: Int, b: (c: Float, d: Double)) case Bar9(Int) case Bar10(Int, Float) case Bar11(Int, (Float)) case Bar12(Int, (Float, Double)) mutating func barInstanceFunc() {} static var staticVar: Int = 12 static func barStaticFunc() {} } // BAR_ENUM_TYPE_CONTEXT: Begin completions // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_TYPE_CONTEXT: End completions // BAR_ENUM_NO_DOT: Begin completions // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar5({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc({#self: &BarEnum#})[#() -> Void#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .barStaticFunc()[#Void#]{{; name=.+$}} // BAR_ENUM_NO_DOT-NEXT: End completions // BAR_ENUM_DOT: Begin completions // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar1[#BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar2()[#() -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar3({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar4({#a: Int#}, {#b: Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar5({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar6({#a: Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar7({#a: Int#}, ({#b: Float#}, {#c: Double#}))[#(Int, (b: Float, c: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar8({#a: Int#}, b: ({#c: Float#}, {#d: Double#}))[#(Int, (c: Float, d: Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar9({#Int#})[#(Int) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar10({#Int#}, {#Float#})[#(Int, Float) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar11({#Int#}, {#Float#})[#(Int, (Float)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Bar12({#Int#}, ({#Float#}, {#Double#}))[#(Int, (Float, Double)) -> BarEnum#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: barInstanceFunc({#self: &BarEnum#})[#() -> Void#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: barStaticFunc()[#Void#]{{; name=.+$}} // BAR_ENUM_DOT-NEXT: End completions enum BazEnum<T> { case Baz1 case Baz2(T) mutating func bazInstanceFunc() {} static var staticVar: Int = 12 static var staticVarT: T = 17 static func bazStaticFunc() {} } // BAZ_ENUM_TYPE_CONTEXT: Begin completions // BAZ_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_ENUM_TYPE_CONTEXT: End completions // BAZ_INT_ENUM_NO_DOT: Begin completions, 6 items // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .bazInstanceFunc({#self: &BazEnum<Int>#})[#() -> Void#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVarT[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_INT_ENUM_NO_DOT-NEXT: End completions // BAZ_T_ENUM_NO_DOT: Begin completions // BAZ_T_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .bazInstanceFunc({#self: &BazEnum<T>#})[#() -> Void#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVarT[#T#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: == {#Any.Type?#}[#Bool#]; name=== Any.Type? // BAZ_T_ENUM_NO_DOT-NEXT: Decl[InfixOperatorFunction]/OtherModule[Swift]: != {#Any.Type?#}[#Bool#]; name=!= Any.Type? // BAZ_T_ENUM_NO_DOT-NEXT: End completions // BAZ_INT_ENUM_DOT: Begin completions, 6 items // BAZ_INT_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: bazInstanceFunc({#self: &BazEnum<Int>#})[#() -> Void#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVarT[#Int#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_INT_ENUM_DOT-NEXT: End completions // BAZ_T_ENUM_DOT: Begin completions, 6 items // BAZ_T_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz1[#BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Baz2({#T#})[#(T) -> BazEnum<T>#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: bazInstanceFunc({#self: &BazEnum<T>#})[#() -> Void#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVarT[#T#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: Decl[StaticMethod]/CurrNominal: bazStaticFunc()[#Void#]{{; name=.+$}} // BAZ_T_ENUM_DOT-NEXT: End completions enum QuxEnum : Int { case Qux1 = 10 case Qux2 = 20 } // QUX_ENUM_TYPE_CONTEXT: Begin completions // QUX_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_TYPE_CONTEXT-DAG: Decl[EnumElement]/ExprSpecific: .Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_TYPE_CONTEXT: End completions // QUX_ENUM_NO_DOT: Begin completions, 4 items // QUX_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[EnumElement]/CurrNominal: .Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .RawValue[#Int#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ({#rawValue: Int#})[#QuxEnum?#]{{; name=.+$}} // QUX_ENUM_NO_DOT-NEXT: End completions // QUX_ENUM_DOT: Begin completions, 4 items // QUX_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Qux1[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[EnumElement]/CurrNominal: Qux2[#QuxEnum#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[TypeAlias]/CurrNominal: RawValue[#Int#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: Decl[Constructor]/CurrNominal: init({#rawValue: Int#})[#QuxEnum?#]{{; name=.+$}} // QUX_ENUM_DOT-NEXT: End completions func freeFunc() {} // WITH_GLOBAL_RESULTS: Begin completions // WITH_GLOBAL_RESULTS: Decl[FreeFunction]/CurrModule: freeFunc()[#Void#]{{; name=.+$}} // WITH_GLOBAL_RESULTS: End completions //===--- Complete enum elements in 'switch'. func testSwitch1(e: FooEnum) { switch e { case #^ENUM_SW_1^# } } func testSwitch2(e: FooEnum) { switch e { case .Foo1: case #^ENUM_SW_2^# } } func testSwitch3(e: BarEnum) { switch e { case #^ENUM_SW_3^# } } func testSwitch4(e: BazEnum<Int>) { switch e { case #^ENUM_SW_4^# } } func testSwitch5(e: QuxEnum) { switch e { case #^ENUM_SW_5^# } } func testSwitchWithDot1(e: FooEnum) { switch e { case .#^ENUM_SW_WITH_DOT_1^# } } func testSwitchWithQualification1(e: FooEnum) { switch e { case FooEnum.#^ENUM_SW_WITH_QUAL_1^# } } func testSwitchExprError1() { switch unknown_var { case FooEnum.#^ENUM_SW_EXPR_ERROR_1^# } } // FIXME func testSwitchInPattern1(e: BazEnum<Int>) { switch e { case .Baz2(#^ENUM_SW_IN_PATTERN_1^# } } // ENUM_SW_IN_PATTERN_1-NOT: .Baz1 func testSwitchInPattern2(e: BazEnum<Int>) { switch e { case .Baz2(.#^ENUM_SW_IN_PATTERN_2^# } } // ENUM_SW_IN_PATTERN_2-NOT: .Baz1 //===--- Complete qualified references to enum elements. func testQualifiedNoDot1() { var e = FooEnum#^ENUM_QUAL_NO_DOT_1^# } func testQualifiedNoDot2() { var e = BarEnum#^ENUM_QUAL_NO_DOT_2^# } func testQualifiedNoDot3() { var e = BazEnum<Int>#^ENUM_QUAL_NO_DOT_3^# } func testQualifiedNoDot4() { var e = BazEnum#^ENUM_QUAL_NO_DOT_4^# } func testQualifiedNoDot5() { var e = QuxEnum#^ENUM_QUAL_NO_DOT_5^# } func testQualifiedDot1() { var e = FooEnum.#^ENUM_QUAL_DOT_1^# } func testQualifiedDot2() { var e = BarEnum.#^ENUM_QUAL_DOT_2^# } func testQualifiedDot3() { var e = BazEnum<Int>.#^ENUM_QUAL_DOT_3^# } func testQualifiedDot4() { var e = BazEnum.#^ENUM_QUAL_DOT_4^# } func testQualifiedDot5() { var e = QuxEnum.#^ENUM_QUAL_DOT_5^# } // ===--- Complete in the presence of invalid enum elements. enum WithInvalid { case Okay case NotOkay. case .AlsoNotOkay case case JustFine } func testWithInvalid1() { let x = WithInvalid.#^WITH_INVALID_DOT_1^# // WITH_INVALID_DOT: Begin completions // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: Okay[#WithInvalid#]; name=Okay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: NotOkay[#WithInvalid#]; name=NotOkay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: AlsoNotOkay[#WithInvalid#]; name=AlsoNotOkay // WITH_INVALID_DOT-DAG: Decl[EnumElement]/CurrNominal: JustFine[#WithInvalid#]; name=JustFine // WITH_INVALID_DOT: End completions var y : QuxEnum y = .#^UNRESOLVED_1^# // FIXME: Only contains resolvable ones. // UNRESOLVED_1: Begin completions // UNRESOLVED_1-NOT: Baz // UNRESOLVED_1-NOT: Bar // UNRESOLVED_1-DAG: Decl[EnumElement]/ExprSpecific: Qux1[#QuxEnum#]; name=Qux1 // UNRESOLVED_1-DAG: Decl[EnumElement]/ExprSpecific: Qux2[#QuxEnum#]; name=Qux2 // UNRESOLVED_1-NOT: Okay }
d77f3e029391753cbc9f54dfd69635ec
50.370079
170
0.653638
false
true
false
false
movabletype/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/Model/UploadItem.swift
mit
1
// // UploadItem.swift // MT_iOS // // Created by CHEEBOW on 2016/02/08. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class UploadItem: NSObject { internal(set) var data: NSData! = nil var blogID = "" var uploadPath = "" var uploaded = false var progress: Float = 0.0 internal(set) var _filename: String = "" var filename: String { get { if self._filename.isEmpty { return self.makeFilename() } return _filename } } func setup(completion: (() -> Void)) { completion() } func clear() { self.data = nil } internal func makeFilename()->String { return self._filename } func upload(progress progress: ((Int64!, Int64!, Int64!) -> Void)? = nil, success: (JSON! -> Void)!, failure: (JSON! -> Void)!) { let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo api.authenticationV2(authInfo.username, password: authInfo.password, remember: true, success:{_ in let filename = self.makeFilename() api.uploadAssetForSite(self.blogID, assetData: self.data, fileName: filename, options: ["path":self.uploadPath, "autoRenameIfExists":"true"], progress: progress, success: success, failure: failure) }, failure: failure ) } func thumbnail(size: CGSize, completion: (UIImage->Void)) { completion(UIImage()) } }
95a5cc9683789cfc441a8cd6779bb7d1
27.293103
214
0.577697
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/ColorPicker.swift
apache-2.0
1
import UIKit class ColorPicker: UIView { var hueValueForPreview: CGFloat = 1.0 { didSet { setNeedsDisplay() } } var accent = false func setAccent(accent: Bool) { self.accent = true } var allColors: [CGColor] { return accent ? GMPalette.allAccentCGColor() : GMPalette.allCGColor() } private var lastTouchLocation: CGPoint? private var decelerateTimer: Timer? private var decelerationSpeed: CGFloat = 0.0 { didSet { if let timer = decelerateTimer { if timer.isValid { timer.invalidate() } } decelerateTimer = Timer.scheduledTimer(timeInterval: 0.025, target: self, selector: #selector(decelerate), userInfo: nil, repeats: true) } } private lazy var panGesture: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) }() private(set) var value: CGFloat = 0.5 { didSet { if Int(self.value * CGFloat(allColors.count)) > allColors.count - 1 { self.value -= 1 } else if self.value < 0 { self.value += 1 } else { setNeedsDisplay() } // delegate?.valueChanged(self.value, accent: accent) } } private func colors(for value: Int) -> [CGColor] { var result = [CGColor]() let i = value - 2 var index = 0 for val in i...(i + 4) { if val < 0 { index = val + (allColors.count - 1) } else if val > (allColors.count - 1) { index = val - (allColors.count - 1) } else { index = val } result.append(allColors[index]) } return result } @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { if gesture.state == .began { lastTouchLocation = gesture.location(in: self) } else if gesture.state == .changed { if let location = lastTouchLocation { value += ((gesture.location(in: self).x - location.x) / frame.width) * 0.1 } lastTouchLocation = gesture.location(in: self) } else if gesture.state == .ended || gesture.state == .cancelled { decelerationSpeed = gesture.velocity(in: self).x } } @objc private func decelerate() { decelerationSpeed *= 0.7255 if abs(decelerationSpeed) <= 0.001 { if let decelerateTimer = decelerateTimer { decelerateTimer.invalidate() } return } value += ((decelerationSpeed * 0.025) / 100) * 0.2 } private func commonInit() { addGestureRecognizer(panGesture) layer.cornerRadius = 5.0 clipsToBounds = true } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() if let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors(for: Int(value * CGFloat(allColors.count))) as CFArray, locations: [0, 0.25, 0.50, 0.75, 1]) { ctx?.drawLinearGradient(gradient, start: CGPoint(x: rect.size.width, y: 0), end: CGPoint.zero, options: .drawsBeforeStartLocation) } let selectionPath = CGMutablePath() let verticalPadding = rect.height * 0.4 let horizontalPosition = rect.midX selectionPath.move(to: CGPoint(x: horizontalPosition, y: verticalPadding * 0.5)) selectionPath.addLine(to: CGPoint(x: horizontalPosition, y: rect.height - (verticalPadding * 0.5))) ctx?.addPath(selectionPath) ctx?.setLineWidth(1.0) ctx?.setStrokeColor(UIColor(white: 0, alpha: 0.5).cgColor) ctx?.strokePath() } }
8635697ce0a78a70da8d2b1a8a06d4d4
30.977273
190
0.544184
false
false
false
false
danielgindi/Charts
refs/heads/master
Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift
apache-2.0
2
// // BarLineScatterCandleBubbleRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(BarLineScatterCandleBubbleChartRenderer) open class BarLineScatterCandleBubbleRenderer: NSObject, DataRenderer { public let viewPortHandler: ViewPortHandler public final var accessibleChartElements: [NSUIAccessibilityElement] = [] public let animator: Animator internal var _xBounds = XBounds() // Reusable XBounds object public init(animator: Animator, viewPortHandler: ViewPortHandler) { self.viewPortHandler = viewPortHandler self.animator = animator super.init() } open func drawData(context: CGContext) { } open func drawValues(context: CGContext) { } open func drawExtras(context: CGContext) { } open func drawHighlighted(context: CGContext, indices: [Highlight]) { } /// Checks if the provided entry object is in bounds for drawing considering the current animation phase. internal func isInBoundsX(entry e: ChartDataEntry, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol) -> Bool { let entryIndex = dataSet.entryIndex(entry: e) return Double(entryIndex) < Double(dataSet.entryCount) * animator.phaseX } /// Calculates and returns the x-bounds for the given DataSet in terms of index in their values array. /// This includes minimum and maximum visible x, as well as range. internal func xBounds(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) -> XBounds { return XBounds(chart: chart, dataSet: dataSet, animator: animator) } /// - Returns: `true` if the DataSet values should be drawn, `false` if not. internal func shouldDrawValues(forDataSet set: ChartDataSetProtocol) -> Bool { return set.isVisible && (set.isDrawValuesEnabled || set.isDrawIconsEnabled) } open func initBuffers() { } open func isDrawingValuesAllowed(dataProvider: ChartDataProvider?) -> Bool { guard let data = dataProvider?.data else { return false } return data.entryCount < Int(CGFloat(dataProvider?.maxVisibleCount ?? 0) * viewPortHandler.scaleX) } /// Class representing the bounds of the current viewport in terms of indices in the values array of a DataSet. open class XBounds { /// minimum visible entry index open var min: Int = 0 /// maximum visible entry index open var max: Int = 0 /// range of visible entry indices open var range: Int = 0 public init() { } public init(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) { self.set(chart: chart, dataSet: dataSet, animator: animator) } /// Calculates the minimum and maximum x values as well as the range between them. open func set(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: BarLineScatterCandleBubbleChartDataSetProtocol, animator: Animator?) { let phaseX = Swift.max(0.0, Swift.min(1.0, animator?.phaseX ?? 1.0)) let low = chart.lowestVisibleX let high = chart.highestVisibleX let entryFrom = dataSet.entryForXValue(low, closestToY: .nan, rounding: .down) let entryTo = dataSet.entryForXValue(high, closestToY: .nan, rounding: .up) self.min = entryFrom == nil ? 0 : dataSet.entryIndex(entry: entryFrom!) self.max = entryTo == nil ? 0 : dataSet.entryIndex(entry: entryTo!) range = Int(Double(self.max - self.min) * phaseX) } } public func createAccessibleHeader(usingChart chart: ChartViewBase, andData data: ChartData, withDefaultDescription defaultDescription: String) -> NSUIAccessibilityElement { return AccessibleHeader.create(usingChart: chart, andData: data, withDefaultDescription: defaultDescription) } } extension BarLineScatterCandleBubbleRenderer.XBounds: RangeExpression { public func relative<C>(to collection: C) -> Swift.Range<Int> where C : Collection, Bound == C.Index { return Swift.Range<Int>(min...min + range) } public func contains(_ element: Int) -> Bool { return (min...min + range).contains(element) } } extension BarLineScatterCandleBubbleRenderer.XBounds: Sequence { public struct Iterator: IteratorProtocol { private var iterator: IndexingIterator<ClosedRange<Int>> fileprivate init(min: Int, max: Int) { self.iterator = (min...max).makeIterator() } public mutating func next() -> Int? { return self.iterator.next() } } public func makeIterator() -> Iterator { return Iterator(min: self.min, max: self.min + self.range) } } extension BarLineScatterCandleBubbleRenderer.XBounds: CustomDebugStringConvertible { public var debugDescription: String { return "min:\(self.min), max:\(self.max), range:\(self.range)" } }
3c2556d366af89d7ce864adeebdc57b9
34.429487
177
0.65768
false
false
false
false
EngrAhsanAli/AAFragmentManager
refs/heads/master
AAFragmentManager/Classes/AAFragmentManager+UIKit.swift
mit
1
// // AAFragmentManager+UIKit.swift // AAFragmentManager // // Created by MacBook Pro on 20/09/2018. // import UIKit // MARK: - UIView extension UIView { /// Add subview and for according to height /// /// - Parameters: /// - subview: Fragment to be added currently in the parent view /// - insets: Insets for current fragment func addAndFitSubview(_ subview: UIView, insets: UIEdgeInsets = .zero) { addSubview(subview) subview.fitInSuperview(with: insets) } /// Fits the given view in its superview fileprivate func fitInSuperview(with insets: UIEdgeInsets = .zero) { guard let superview = superview else { assertionFailure("AAFragmentManager: added fragment was not in a view hierarchy.") return } let applyInset: (NSLayoutConstraint.Attribute, UIEdgeInsets) -> CGFloat = { switch $0 { case .top: return $1.top case .bottom: return -$1.bottom case .left: return $1.left case .right: return -$1.right default: return 0 } } translatesAutoresizingMaskIntoConstraints = false let attributes = [NSLayoutConstraint.Attribute.top, .left, .right, .bottom] superview.addConstraints(attributes.map { return NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1, constant: applyInset($0, insets)) }) } } // MARK: - Array Collection extension Collection { // Checks if index exists in the given array subscript(optional i: Index) -> Iterator.Element? { return self.indices.contains(i) ? self[i] : nil } }
b5cc544d472b0bae10535a0030a292a7
30.296875
94
0.540689
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Scenes/Create terrain surface from a local raster/CreateTerrainSurfaceFromLocalRasterViewController.swift
apache-2.0
1
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class CreateTerrainSurfaceFromLocalRasterViewController: UIViewController { @IBOutlet weak var sceneView: AGSSceneView! { didSet { // Initialize a scene. sceneView.scene = makeScene() // Set scene's viewpoint. let camera = AGSCamera(latitude: 36.525, longitude: -121.80, altitude: 300.0, heading: 180, pitch: 80, roll: 0) sceneView.setViewpointCamera(camera) } } func makeScene() -> AGSScene { let scene = AGSScene(basemapStyle: .arcGISImagery) let surface = AGSSurface() // Create raster elevation source. let rasterURL = Bundle.main.url(forResource: "MontereyElevation", withExtension: "dt2")! let rasterElevationSource = AGSRasterElevationSource(fileURLs: [rasterURL]) // Add a raster source to the surface. surface.elevationSources.append(rasterElevationSource) scene.baseSurface = surface return scene } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["CreateTerrainSurfaceFromLocalRasterViewController"] } }
7f7b9bfe613b37406f2c7278870493df
36.823529
142
0.674443
false
false
false
false
amleszk/RxPasscode
refs/heads/master
RxPasscode/PasscodeNumberButton.swift
mit
1
import UIKit class PasscodeNumberButton: UIButton, PasscodeStyleView { var borderColor: UIColor = UIColor.whiteColor() var highlightBackgroundColor: UIColor = UIColor(white: 0.9, alpha: 0.8) var defaultBackgroundColor = UIColor.clearColor() let borderRadius: CGFloat let intrinsicSize: CGSize var displayedState: PasscodeStyleViewState = .Inactive init(buttonSize: CGFloat) { self.intrinsicSize = CGSizeMake(buttonSize, buttonSize) self.borderRadius = floor(buttonSize/2) super.init(frame: CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)) setupViewBorder() setupActions() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func intrinsicContentSize() -> CGSize { return intrinsicSize } private func setupActions() { addTarget(self, action: #selector(PasscodeNumberButton.handleTouchDown), forControlEvents: .TouchDown) addTarget(self, action: #selector(PasscodeNumberButton.handleTouchUp), forControlEvents: [.TouchUpInside, .TouchDragOutside, .TouchCancel]) } internal func handleTouchDown() { animateToState(.Active) } internal func handleTouchUp() { let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.07 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.animateToState(.Inactive) } } }
6d04d78d1dbff7363d07d03d416f3c1e
33.568182
147
0.675214
false
false
false
false
billdonner/sheetcheats9
refs/heads/master
sc9/TilesViewController.swift
apache-2.0
1
// // TilesViewController.swift // import UIKit final class TileCell: UICollectionViewCell { @IBOutlet var alphabetLabel: UILabel! @IBOutlet weak var track: UILabel! @IBOutlet weak var notes: UILabel! @IBOutlet weak var key: UILabel! @IBOutlet weak var bpm: UILabel! func configureCellFromTile(_ t:Tyle,invert:Bool = false) { let name = t.tyleTitle self.alphabetLabel.text = name self.track.text = "\(t.tyleID)" self.key.text = t.tyleKey self.bpm.text = t.tyleBpm self.notes.text = t.tyleNote let bc = t.tyleBackColor let fc = Corpus.findFast(name) ? t.tyleTextColor :Col.r(.collectionSectionHeaderAltText) // if the title isnt found make the label a plain gray let frontcolor = invert ? bc : fc let backcolor = invert ? fc : bc self.contentView.backgroundColor = backcolor self.backgroundColor = backcolor self.alphabetLabel.textColor = frontcolor self.key.textColor = frontcolor self.bpm.textColor = frontcolor self.notes.textColor = frontcolor } } final class TilesViewController: UIViewController , ModelData,UserInteractionSignalDelegate , UICollectionViewDelegate,UICollectionViewDataSource { let backColor = Col.r(.collectionBackground) @IBAction func choseMore(_ sender: AnyObject) { self.presentMore(self) } func backToModalMenu () {// can go directly back self.presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func backAction(_ sender: AnyObject) { backToModalMenu() } @IBOutlet weak var collectionView: UICollectionView! var longPressOneShot = false var observer0 : NSObjectProtocol? // emsure ots retained var observer1 : NSObjectProtocol? // emsure ots retained var av = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) var lastTapped : IndexPath? deinit{ // NotificationCenter.default.removeObserver(observer0!) // NotificationCenter.default.removeObserver(observer1!) self.cleanupFontSizeAware(self) } func refresh() { self.collectionView?.backgroundColor = backColor self.view.backgroundColor = backColor self.collectionView?.reloadData() longPressOneShot = false // now listen to longPressAgain self.av.removeFromSuperview() } // total surrender to storyboards, everything is done thru performSegue and unwindtoVC @IBAction func unwindToTilesViewController( _ segue:// unwindToVC(segue: UIStoryboardSegue) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.collectionView?.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) longPressOneShot = false } func noItemsSimulatePress() { self.performSegue(withIdentifier: "nogigfileseque", sender: self) } @objc func pressedLong() { // ensure not getting double hit let pvd = self.presentedViewController if pvd == nil { if longPressOneShot == false { //print ("Long Press Presenting Modal Menu ....") longPressOneShot = true self.presentingViewController?.dismiss(animated: true, completion: nil) } } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Col.r(.helpBackground) //self.clearsSelectionOnViewWillAppear = false self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView?.backgroundColor = Col.r(.collectionBackground) // self.view.backgroundColor = .darkGray // choseMoreButton.isEnabled = !performanceMode if performanceMode { // self.navigationItem.rightBarButtonItem = nil } self.setupFontSizeAware(self) // observer0 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceRestorationCompleteSignal), object: nil, queue: OperationQueue.main) { _ in // NSLog ("Restoration Complete, tilesviewController reacting....") // self.refresh() // if self.noTiles() { // no items // Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(TilesViewController.noItemsSimulatePress), userInfo: nil, repeats: false) // } // } // observer1 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceUpdatedSignal), object: nil, queue: OperationQueue.main) { _ in // print ("Surface was updated, tilesviewController reacting....") // self.refresh() // } refresh() if noTiles() { noItemsSimulatePress() } } func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return false } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var indexPaths:[IndexPath] indexPaths = [] // change colorization if a different cell than las if lastTapped != nil { indexPaths.append(lastTapped!) // record path of old cell } if indexPath != lastTapped { // if tapping new cell // now change this cell lastTapped = indexPath indexPaths.append(indexPath) if indexPaths.count != 0 { collectionView.reloadItems(at: indexPaths) } } // ok show the document showDoc(self,named:self.tileData(indexPath).tyleTitle) } } extension TilesViewController { //: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.tileSectionCount() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.tileCountInSection(section) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1 switch kind { //2 case UICollectionElementKindSectionHeader: //3 if let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionheaderid", for: indexPath) as? TilesSectionHeaderView { headerView.headerLabel.text = self.sectHeader((indexPath as NSIndexPath).section)[SectionProperties.NameKey] headerView.headerLabel.textColor = Col.r(.collectionSectionHeaderText) headerView.headerLabel.backgroundColor = .clear // headerView.headerLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) let tgr = UITapGestureRecognizer(//UILongPressGestureRecognizer target: self, action: #selector(TilesViewController.pressedLong)) headerView.addGestureRecognizer(tgr) return headerView } default: //4 fatalError("Unexpected element kind") } fatalError("Unexpected element kind") } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TileCellID", for: indexPath) as! TileCell let invert = lastTapped != nil && (indexPath as NSIndexPath).section == lastTapped!.section && (indexPath as NSIndexPath).item == lastTapped!.item // Configure the cell cell.configureCellFromTile(self.tileData(indexPath),invert:invert) return cell } } extension TilesViewController:SegueHelpers { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "nogigfileseque" { if let nav = segue.destination as? UINavigationController{ if let uivc = nav.topViewController as? NoGigsViewController { uivc.delegate = self } } } else if segue.identifier == nil { // unwinding self.refresh() } else { self.prepForSegue(segue , sender: sender) } longPressOneShot = false } } extension TilesViewController: FontSizeAware { func refreshFontSizeAware(_ vc: TilesViewController) { vc.collectionView?.reloadData() } } extension TilesViewController: ShowContentDelegate { func userDidDismiss() { // print("user dismissed Content View Controller") } } extension TilesViewController { //: UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { DispatchQueue.main.async(execute: { // get section from first visible cell let paths = self.collectionView?.indexPathsForVisibleItems if (paths != nil) { let path = paths![0] let section = (path as NSIndexPath).section let sectionHead = self.sectHeader(section) let sectionTitle = sectionHead[SectionProperties.NameKey] self.title = sectionTitle } }) } } ///////////////////////////////////////////////
120a6b4c80acdcf515801e047b636502
36.911538
184
0.62656
false
false
false
false
ppraveentr/MobileCore
refs/heads/master
Sources/CoreComponents/Contollers/ScrollViewControllerProtocol.swift
mit
1
// // ScrollViewControllerProtocol.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 18/08/17. // Copyright © 2017 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import Foundation import UIKit private var kAOScrollVC = "k.FT.AO.ScrollViewController" public protocol ScrollViewControllerProtocol: ViewControllerProtocol { var scrollView: UIScrollView { get } } public extension ScrollViewControllerProtocol { var scrollView: UIScrollView { get { guard let scroll = AssociatedObject<UIScrollView>.getAssociated(self, key: &kAOScrollVC) else { return self.setupScrollView() } return scroll } set { setupScrollView(newValue) } } } private extension ScrollViewControllerProtocol { @discardableResult func setupScrollView(_ local: UIScrollView = UIScrollView() ) -> UIScrollView { // Load Base view setupCoreView() if let scroll: UIScrollView = AssociatedObject<UIScrollView>.getAssociated(self, key: &kAOScrollVC) { scroll.removeSubviews() AssociatedObject<Any>.resetAssociated(self, key: &kAOScrollVC) } if local.superview == nil { self.mainView?.pin(view: local, edgeOffsets: .zero) local.setupContentView(local.contentView) } AssociatedObject<UIScrollView>.setAssociated(self, value: local, key: &kAOScrollVC) return local } }
280eb9b79c7c75ca49cdc8a23204f502
26.465517
109
0.647207
false
false
false
false
mokemokechicken/ObjectJsonMapperGenerator
refs/heads/master
tmp/entity_common.swift
mit
1
import Foundation private func encode(obj: AnyObject?) -> AnyObject { switch obj { case nil: return NSNull() case let ojmObject as EntityBase: return ojmObject.toJsonDictionary() default: return obj! } } private func decodeOptional(obj: AnyObject?) -> AnyObject? { switch obj { case let x as NSNull: return nil default: return obj } } private func JsonGenObjectFromJsonData(data: NSData!) -> AnyObject? { if data == nil { return nil } return NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: nil) } public class EntityBase { public init() { } public func toJsonDictionary() -> NSDictionary { return NSDictionary() } public class func toJsonArray(entityList: [EntityBase]) -> NSArray { return entityList.map {x in encode(x)} } public class func toJsonData(entityList: [EntityBase], pretty: Bool = false) -> NSData { var obj = toJsonArray(entityList) return toJson(obj, pretty: pretty) } public func toJsonData(pretty: Bool = false) -> NSData { var obj = toJsonDictionary() return EntityBase.toJson(obj, pretty: pretty) } public class func toJsonString(entityList: [EntityBase], pretty: Bool = false) -> NSString { return NSString(data: toJsonData(entityList, pretty: pretty), encoding: NSUTF8StringEncoding)! } public func toJsonString(pretty: Bool = false) -> NSString { return NSString(data: toJsonData(pretty: pretty), encoding: NSUTF8StringEncoding)! } public class func fromData(data: NSData!) -> AnyObject? { var object:AnyObject? = JsonGenObjectFromJsonData(data) switch object { case let hash as NSDictionary: return fromJsonDictionary(hash) case let array as NSArray: return fromJsonArray(array) default: return object } } public class func fromJsonDictionary(hash: NSDictionary?) -> EntityBase? { return nil } public class func fromJsonArray(array: NSArray?) -> [EntityBase]? { if array == nil { return nil } var ret = [EntityBase]() if let xx = array as? [NSDictionary] { for x in xx { if let obj = fromJsonDictionary(x) { ret.append(obj) } else { return nil } } } else { return nil } return ret } private class func toJson(obj: NSObject, pretty: Bool = false) -> NSData { let options = pretty ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions.allZeros return NSJSONSerialization.dataWithJSONObject(obj, options: options, error: nil)! } }
2da1f857e2818c3a054637a2878cb43c
26.846154
115
0.605318
false
false
false
false
tjw/swift
refs/heads/master
test/SILGen/protocol_optional.swift
apache-2.0
1
// RUN: %target-swift-frontend -module-name protocol_optional -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s @objc protocol P1 { @objc optional func method(_ x: Int) @objc optional var prop: Int { get } @objc optional subscript (i: Int) -> Int { get } } // CHECK-LABEL: sil hidden @$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalMethodGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed (Int) -> ()> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: alloc_stack $Optional<@callee_guaranteed (Int) -> ()> // CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign var methodRef = t.method } // CHECK: } // end sil function '$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF' // CHECK-LABEL: sil hidden @$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalPropertyGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign var propertyRef = t.prop } // CHECK: } // end sil function '$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalSubscriptGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5 // CHECK: [[INTCONV:%[0-9]+]] = function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC // CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign var subscriptRef = t[5] } // CHECK: } // end sil function '$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
1678b976aef42dbfa9e2b9d86927618d
52.308824
179
0.564414
false
false
false
false
omaralbeik/SwifterSwift
refs/heads/master
Tests/UIKitTests/UIStackViewExtensionsTest.swift
mit
1
// // UIStackViewExtensionsTest.swift // SwifterSwift // // Created by Benjamin Meyer on 2/18/18. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit final class UIStackViewExtensionsTest: XCTestCase { // MARK: - Initializers func testInitWithViews() { let view1 = UIView() let view2 = UIView() var stack = UIStackView(arrangedSubviews: [view1, view2], axis: .horizontal) XCTAssertEqual(stack.arrangedSubviews.count, 2) XCTAssertTrue(stack.arrangedSubviews[0] === view1) XCTAssertTrue(stack.arrangedSubviews[1] === view2) XCTAssertEqual(stack.axis, .horizontal) XCTAssertEqual(stack.alignment, .fill) XCTAssertEqual(stack.distribution, .fill) XCTAssertEqual(stack.spacing, 0.0) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical).axis, .vertical) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, alignment: .center).alignment, .center) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, distribution: .fillEqually).distribution, .fillEqually) XCTAssertEqual(UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, spacing: 16.0).spacing, 16.0) stack = UIStackView(arrangedSubviews: [view1, view2], axis: .vertical, spacing: 16.0, alignment: .center, distribution: .fillEqually) XCTAssertEqual(stack.axis, .vertical) XCTAssertEqual(stack.alignment, .center) XCTAssertEqual(stack.distribution, .fillEqually) XCTAssertEqual(stack.spacing, 16.0) } func testAddArrangedSubviews() { let view1 = UIView() let view2 = UIView() let stack = UIStackView() stack.addArrangedSubviews([view1, view2]) XCTAssertEqual(stack.arrangedSubviews.count, 2) } func testRemoveArrangedSubviews() { let view1 = UIView() let view2 = UIView() let stack = UIStackView() stack.addArrangedSubview(view1) stack.addArrangedSubview(view2) stack.removeArrangedSubviews() XCTAssert(stack.arrangedSubviews.isEmpty) } } #endif
ba782d15ecf7d60af14558f1d18a11d7
32.855072
116
0.657962
false
true
false
false
wibosco/CoalescingOperations-Example
refs/heads/master
CoalescingOperations-Example/Coalescing/CoalescingExampleManager.swift
mit
1
// // CoalescingExampleManager.swift // CoalescingOperations-Example // // Created by Boles on 28/02/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit /** An example manager that handles queuing operations. It exists as we don't really want our VCs to know anything about coalescing or the queue. */ class CoalescingExampleManager: NSObject { // MARK: - Add class func addExampleCoalescingOperation(queueManager: QueueManager = QueueManager.sharedInstance, completion: (QueueManager.CompletionClosure)?) { let coalescingOperationExampleIdentifier = "coalescingOperationExampleIdentifier" if let completion = completion { queueManager.addNewCompletionClosure(completion, identifier: coalescingOperationExampleIdentifier) } if !queueManager.operationIdentifierExistsOnQueue(coalescingOperationExampleIdentifier) { let operation = CoalescingExampleOperation() operation.identifier = coalescingOperationExampleIdentifier operation.completion = {(successful) in let closures = queueManager.completionClosures(coalescingOperationExampleIdentifier) if let closures = closures { for closure in closures { closure(successful: successful) } queueManager.clearClosures(coalescingOperationExampleIdentifier) } } queueManager.enqueue(operation) } } }
d60dc4b1d6e23986557a86ea45a14fc6
34.644444
151
0.650249
false
false
false
false
thedreamer979/Calvinus
refs/heads/master
Calvin/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Calvin // // Created by Arion Zimmermann on 27.01.17. // Copyright © 2017 AZEntreprise. All rights reserved. // import UIKit import UserNotifications @UIApplicationMain class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { @available(iOS 10.0, *) static let center = UNUserNotificationCenter.current() var window: UIWindow? var completionHandler : ((UIBackgroundFetchResult) -> Void)? = nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) if #available(iOS 10.0, *) { AppDelegate.center.delegate = self let options: UNAuthorizationOptions = [.alert, .badge, .sound] AppDelegate.center.requestAuthorization(options: options) { (granted, error) in if !granted { print(error ?? "Undefined") } } } else { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) }; AZEntrepriseServer.login(controller: window?.rootViewController, userHash: UserDefaults.standard.string(forKey: "user-hash"), onResponse: loginResponse) return true } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { self.completionHandler = completionHandler AZEntrepriseServer.login(controller: nil, userHash: UserDefaults.standard.string(forKey: "user-hash"), onResponse: handle) } func handle(dummy : Bool) { if self.completionHandler != nil { self.completionHandler!(.newData) self.completionHandler = nil } } func loginResponse(success : Bool) { if !success { DispatchQueue.main.async { let storyboard = UIStoryboard(name: "Main", bundle: nil) self.window?.rootViewController?.present(storyboard.instantiateViewController(withIdentifier: "tutorial"), animated: true, completion: nil) } } else { AZEntrepriseServer.dummyOnResponse(dummy: true) } } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
a4d38c017dee5e8bacf9adb5596f74ae
45.541667
285
0.69897
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Costello Reverb.xcplaygroundpage/Contents.swift
mit
1
//: ## Sean Costello Reverb //: This is a great sounding reverb that we just love. import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var reverb = AKCostelloReverb(player) reverb.cutoffFrequency = 9_900 // Hz reverb.feedback = 0.92 AudioKit.output = reverb AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { var cutoffFrequencySlider: AKSlider! var feedbackSlider: AKSlider! override func viewDidLoad() { addTitle("Sean Costello Reverb") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) cutoffFrequencySlider = AKSlider(property: "Cutoff Frequency", value: reverb.cutoffFrequency, range: 20 ... 5_000, format: "%0.1f Hz" ) { sliderValue in reverb.cutoffFrequency = sliderValue } addView(cutoffFrequencySlider) feedbackSlider = AKSlider(property: "Feedback", value: reverb.feedback) { sliderValue in reverb.feedback = sliderValue } addView(feedbackSlider) let presets = ["Short Tail", "Low Ringing Tail"] addView(AKPresetLoaderView(presets: presets) { preset in switch preset { case "Short Tail": reverb.presetShortTailCostelloReverb() case "Low Ringing Tail": reverb.presetLowRingingLongTailCostelloReverb() default: break } self.updateUI() }) } func updateUI() { cutoffFrequencySlider?.value = reverb.cutoffFrequency feedbackSlider?.value = reverb.feedback } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
9117ac5ec4b5157c75e92bc38237c090
28.028571
96
0.632874
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/VerticalSpacerView.swift
mit
1
import UIKit /// A vertical spacer (conceptually similar to SwiftUI's `Spacer`) class VerticalSpacerView: SetupView { // MARK: - Properties var space: CGFloat = 0 { didSet { spaceHeightAnchor?.constant = space } } fileprivate var spaceHeightAnchor: NSLayoutConstraint? // MARK: - Setup override func setup() { spaceHeightAnchor = heightAnchor.constraint(equalToConstant: space) spaceHeightAnchor?.isActive = true } // MARK: - Factory static func spacerWith(space: CGFloat) -> VerticalSpacerView { let spacer = VerticalSpacerView() spacer.space = space return spacer } }
fcb081cee571cb7422fa9c9397009daa
18.548387
69
0.722772
false
false
false
false
jhurray/SelectableTextView
refs/heads/master
Source/TextViewLayout.swift
mit
1
// // TextViewLayout.swift // SelectableTextView // // Created by Jeff Hurray on 2/4/17. // Copyright © 2017 jhurray. All rights reserved. // import UIKit internal protocol TextViewLayoutDataSource: class { func lineSpacing(forLayout layout: TextViewLayout) -> CGFloat func numberOfLines(forLayout layout: TextViewLayout) -> Int func numberOfTextModels(forLayout layout: TextViewLayout) -> Int func truncationMode(forLayout layout: TextViewLayout) -> TruncationMode func textAlignment(forLayout layout: TextViewLayout) -> TextAlignment func cellModel(atIndex index:Int, layout: TextViewLayout) -> TextCellModel func expansionButtonModel(layout: TextViewLayout) -> TextExpansionButtonModel? } fileprivate struct AttributeKey: Hashable { var indexPath: IndexPath var kind: String fileprivate var hashValue: Int { return kind.hashValue ^ indexPath.hashValue } } fileprivate func ==(left: AttributeKey, right: AttributeKey) -> Bool { return left.hashValue == right.hashValue } internal struct TruncationContext { let indexOfCellModelNeedingTruncation: Int let transformedText: String } internal struct MalformedTextCellContext { let indicesOfMalformedCells: [Int] } internal final class TextViewLayout: UICollectionViewLayout { weak internal var dataSource: TextViewLayoutDataSource? = nil internal var truncationContext: TruncationContext? = nil internal var malformedTextCellContext: MalformedTextCellContext? = nil internal var onLayout: () -> () = {} fileprivate var contentHeight: CGFloat = 0 fileprivate var contentWidth: CGFloat = 0 fileprivate var cellAttributes: [AttributeKey:UICollectionViewLayoutAttributes] = [:] override func prepare() { super.prepare() guard let dataSource = dataSource else { return } if cellAttributes.isEmpty { contentWidth = collectionView!.bounds.width - collectionView!.contentInset.left - collectionView!.contentInset.right let numberOfLines = dataSource.numberOfLines(forLayout: self) let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let lineSpacing = dataSource.lineSpacing(forLayout: self) var line: Int = 0 var item: Int = 0 var lineWidth: CGFloat = 0 let lineHeight: CGFloat = maxLineHeight() if numberOfModels > 0 { contentHeight = lineHeight } var attributeKeysForCurrentLine: [AttributeKey] = [] func alignCurrentLine() { var shiftValue = floor(contentWidth - lineWidth) switch dataSource.textAlignment(forLayout: self) { case .center: shiftValue /= 2 break case .right: // do nothing break case .left: shiftValue = 0 break } if shiftValue > 0 { for key: AttributeKey in attributeKeysForCurrentLine { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.origin.x += shiftValue return frame }) } } attributeKeysForCurrentLine.removeAll(keepingCapacity: true) } func isLastLine() -> Bool { return numberOfLines != 0 && line == numberOfLines } var indicesOfMalformedCells: [Int] = [] while (numberOfLines == 0 || line < numberOfLines) && item < numberOfModels { var xOrigin: CGFloat = lineWidth var width: CGFloat = 0 func newLine(additionalWidth: CGFloat) { line += 1 let isLastLine: Bool = (numberOfLines != 0 && line == numberOfLines) if (!isLastLine) { alignCurrentLine() // Start new line xOrigin = 0 lineWidth = additionalWidth contentHeight += lineHeight + lineSpacing } else { // Truncation let truncationMode = dataSource.truncationMode(forLayout: self) switch truncationMode { case .clipping: width = additionalWidth lineWidth += additionalWidth break case .truncateTail: let remainingWidth = contentWidth - lineWidth width = remainingWidth break } } } let model = dataSource.cellModel(atIndex: item, layout: self) switch model.type { case .newLine: newLine(additionalWidth: 0) default: let attributedText = model.attributedText width = attributedText.width // If this word will take up a whole line and not be the last line if width > contentWidth && line < numberOfLines - 2 { indicesOfMalformedCells.append(item) } if (lineWidth + width) > contentWidth { newLine(additionalWidth: width) } else { lineWidth += width } } if numberOfLines == 0 || line < numberOfLines || item == 0 { let indexPath = IndexPath(item: item, section: 0) let (attributes, key) = registerCell(cellType: TextCell.self, indexPath: indexPath) attributes.frame = CGRect(x: xOrigin, y: contentHeight - lineHeight, width: max(0, min(width, contentWidth)), height: lineHeight) attributeKeysForCurrentLine.append(key) item += 1 } } // Clean up the end of the text if expansionButtonNeedsNewLine() { // Expansion button needs a new line // Truncation for current line truncationContext = nil if let newLineWidth = adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: 0, expansionOnNewLine: true) { lineWidth = newLineWidth } // Align current line of text alignCurrentLine() // Add new linew contentHeight += lineHeight lineWidth = 0 // Put expansion button on new line let (_, expansionButtonKey) = adjustForExpansionButton(lineHeight: lineHeight, onNewLine: true) // Move Expansion Button if let key = expansionButtonKey { attributeKeysForCurrentLine.append(key) if let attributes = cellAttributes[key] { lineWidth += attributes.frame.width } } // Align last line of text alignCurrentLine() } else { // Expansion let (numberOfCellsHiddenByExpansion, expansionButtonKey) = adjustForExpansionButton(lineHeight: lineHeight, onNewLine: false) // Truncation truncationContext = nil if let newLineWidth = adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: numberOfCellsHiddenByExpansion, expansionOnNewLine:false) { lineWidth = newLineWidth } // Move Expansion Button if let key = expansionButtonKey { attributeKeysForCurrentLine.append(key) if lineWidth < contentWidth - widthForExpansionButtonCell() { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.origin.x = lineWidth lineWidth += frame.width return frame }) } } // Align last line of text alignCurrentLine() } malformedTextCellContext = indicesOfMalformedCells.isEmpty ? nil : MalformedTextCellContext(indicesOfMalformedCells: indicesOfMalformedCells) } onLayout() } fileprivate func expansionButtonNeedsNewLine() -> Bool { guard let dataSource = dataSource else { return false } let numberOfLines = dataSource.numberOfLines(forLayout: self) guard numberOfLines == 0 else { return false } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let (lastAttributes, _, _) = layoutInformationAtIndex(index: numberOfModels - 1) let remainingWidth = contentWidth - lastAttributes.frame.maxX let expansionButtonWidth = widthForExpansionButtonCell() return remainingWidth < expansionButtonWidth } fileprivate func widthForExpansionButtonCell() -> CGFloat { guard let expansionButtonModel = dataSource?.expansionButtonModel(layout: self) else { return 0 } let padding: CGFloat = TextExpansionButtonConfig.horizontalPadding return expansionButtonModel.attributedText.width + 2 * padding } fileprivate func layoutInformationAtIndex(index: Int) -> (UICollectionViewLayoutAttributes, TextCellModel, AttributeKey) { let indexPath = IndexPath(item: index, section: 0) let key = AttributeKey(indexPath: indexPath, kind: TextCell.kind) guard let attributes = cellAttributes[key] else { fatalError("Attributes should not be nil") } guard let dataSource = dataSource else { fatalError("DataSource should not be nil") } let model = dataSource.cellModel(atIndex: index, layout: self) return (attributes, model, key) } // Returns he number of cells hidden, the key for the button attributes, and whether or not a new line was added fileprivate func adjustForExpansionButton(lineHeight: CGFloat, onNewLine: Bool) -> (Int, AttributeKey?) { guard let dataSource = dataSource else { return (0, nil) } guard (dataSource.expansionButtonModel(layout: self)) != nil else { return (0, nil) } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) let expansionButtonWidth: CGFloat = widthForExpansionButtonCell() let indexPath = IndexPath(item: numberOfModels, section: 0) let (expansionButtonAttributes, expansionButtonKey) = registerCell(cellType: TextExpansionButtonCell.self, indexPath: indexPath) let xOrigin: CGFloat = onNewLine ? 0 : contentWidth - expansionButtonWidth expansionButtonAttributes.frame = CGRect(x: xOrigin, y: contentHeight - lineHeight, width: expansionButtonWidth, height: lineHeight) guard !onNewLine else { return (0, expansionButtonKey) } guard let attributeCollection = layoutAttributesForElements(in: expansionButtonAttributes.frame) else { return (0, expansionButtonKey) } var numberOfCellsHiddenByExpansion = 0 for attributes in attributeCollection { let index = attributes.indexPath.item guard index != numberOfModels else { continue } let (_, _, key) = layoutInformationAtIndex(index: index) let expansionButtonFrame = expansionButtonAttributes.frame if expansionButtonFrame.contains(attributes.frame) { hideCellForKey(key: key) numberOfCellsHiddenByExpansion += 1 } else { adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in assert(frame.height == expansionButtonFrame.height) assert(frame.minY == expansionButtonFrame.minY) assert(frame.minX <= expansionButtonFrame.minX) var frame = frame let intersection = expansionButtonFrame.intersection(frame) frame.size.width -= intersection.width return frame }) } } return (numberOfCellsHiddenByExpansion, expansionButtonKey) } // Returns new value of line width fileprivate func adjustForTruncationIfNecessary(numberOfCellsHiddenByExpansion: Int, expansionOnNewLine: Bool) -> CGFloat? { guard let dataSource = dataSource else { return nil } let truncationMode = dataSource.truncationMode(forLayout: self) guard truncationMode != .clipping else { return nil } let numberOfLines = dataSource.numberOfLines(forLayout: self) guard numberOfLines > 0 else { return nil } let numberOfModels = dataSource.numberOfTextModels(forLayout: self) var numberOfCells = cellAttributes.count - numberOfCellsHiddenByExpansion if (dataSource.expansionButtonModel(layout: self)) != nil { numberOfCells -= 1 } let expansionButtonWidth = expansionOnNewLine ? 0 : widthForExpansionButtonCell() guard numberOfCells > 0 else { return nil } // the last visible cell not covered by expansion let (lastCellAttributes, lastCellModel, lastKey) = layoutInformationAtIndex(index: numberOfCells - 1) let remainingWidth = contentWidth - lastCellAttributes.frame.minX - expansionButtonWidth let lastCellModelIsWordThatDoesntFit = (lastCellModel is Word) && (lastCellModel.attributedText.width > lastCellAttributes.frame.width) && (lastCellModel.text.truncatedString(fittingWidth: remainingWidth, attributes: lastCellModel.attributes) == nil) let needsTruncation: Bool = numberOfCells < numberOfModels || lastCellModelIsWordThatDoesntFit guard needsTruncation else { return nil } let isOnlyCell: Bool = (numberOfCells == 1) if lastCellModelIsWordThatDoesntFit { if isOnlyCell { return lastCellAttributes.frame.width } else { // hide last cell hideCellForKey(key: lastKey) numberOfCells -= 1 } } // get the last visible word and create truncation context for cellIndex in (0..<numberOfCells).reversed() { let (attributes, model, key) = layoutInformationAtIndex(index: cellIndex) if let word = model as? Word, !attributes.isHidden { let availableWidthForTruncatedText: CGFloat = floor(contentWidth - attributes.frame.minX - expansionButtonWidth) let text = word.displayText ?? word.text guard let truncatedString = text.truncatedString(fittingWidth: availableWidthForTruncatedText, attributes: word.attributes) else { // JHTODO assert? should ever happen? return nil } let truncatedStringWidth = truncatedString.width(withAttributes: word.attributes) let newMaxX = attributes.frame.minX + truncatedStringWidth adjustLayoutAttributesFrameForKey(key: key, frameAdjustment: { (frame) -> (CGRect) in var frame = frame frame.size.width = truncatedStringWidth return frame }) truncationContext = TruncationContext(indexOfCellModelNeedingTruncation: cellIndex, transformedText: truncatedString) return newMaxX } else { hideCellForKey(key: key) } } return nil } fileprivate func hideCellForKey(key: AttributeKey) { adjustLayoutAttributesForKey(key: key, adjustment: { (attributes) -> (UICollectionViewLayoutAttributes) in attributes.isHidden = true return attributes }) } fileprivate func adjustLayoutAttributesFrameForKey(key: AttributeKey, frameAdjustment: (CGRect) -> (CGRect)) { adjustLayoutAttributesForKey(key: key) { (attributes) -> (UICollectionViewLayoutAttributes) in let frame = frameAdjustment(attributes.frame) attributes.frame = frame return attributes } } fileprivate func adjustLayoutAttributesForKey(key: AttributeKey, adjustment: (UICollectionViewLayoutAttributes) -> (UICollectionViewLayoutAttributes)) { guard let attributes = cellAttributes[key] else { return } cellAttributes[key] = adjustment(attributes) } func maxLineHeight() -> CGFloat { guard let dataSource = dataSource else { return 0 } var maxHeight: CGFloat = 0 let numberOfModels = dataSource.numberOfTextModels(forLayout: self) var item = 0 while item < numberOfModels { let model = dataSource.cellModel(atIndex: item, layout: self) let attributedString = model.attributedText maxHeight = max(maxHeight, attributedString.size().height) item += 1 } return ceil(maxHeight) } override func invalidateLayout() { super.invalidateLayout() cellAttributes = [AttributeKey:UICollectionViewLayoutAttributes]() contentWidth = 0 contentHeight = 0 } override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cellAttributes.values.filter { return $0.frame.intersects(rect) } } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let key = AttributeKey(indexPath: indexPath, kind: TextCell.kind) return self.cellAttributes[key] } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return false } fileprivate func registerCell(cellType: UICollectionViewCell.Type, indexPath: IndexPath) -> (UICollectionViewLayoutAttributes, AttributeKey) { let key = AttributeKey(indexPath: indexPath, kind: cellType.kind) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) cellAttributes[key] = attributes return (attributes, key) } }
d70756cc46083733339d42aed3aed624
42
160
0.582005
false
false
false
false
EstefaniaGilVaquero/ciceIOS
refs/heads/master
App_VolksWagenFinal-/App_VolksWagenFinal-/VWUsersParseTableViewController.swift
apache-2.0
1
// // VWUsersParseTableViewController.swift // App_VolksWagenFinal_CICE // // Created by Formador on 19/10/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit import Parse class VWUsersParseTableViewController: UITableViewController { //MARK: - VARIABLES LOCALES GLOBALES var usersFromParse = [String]() var usersFollowing = [Bool]() //MARK: - LIFE VC override func viewDidLoad() { super.viewDidLoad() actualizarDatosUsuariosSeguidos() //consultaUsuariosParse() self.title = PFUser.currentUser()?.username } func actualizarDatosUsuariosSeguidos(){ //1. Consulta a Followers let queryFollowers = PFQuery(className: "Followers") queryFollowers.whereKey("follower", equalTo: (PFUser.currentUser()?.username)!) queryFollowers.findObjectsInBackgroundWithBlock { (objectFollowers, errorFollowers) in if errorFollowers == nil{ if let followingPersonas = objectFollowers{ //2. consulta de PFQuey let queryUsuariosFromParse = PFUser.query() queryUsuariosFromParse?.findObjectsInBackgroundWithBlock({ (objectsUsuarios, errorUsuarios) in self.usersFromParse.removeAll() self.usersFollowing.removeAll() for objectsData in objectsUsuarios!{ //3. Consulta let userData = objectsData as! PFUser if userData.username != PFUser.currentUser()?.username{ self.usersFromParse.append(userData.username!) var isFollowing = false for followingPersonaje in followingPersonas{ if followingPersonaje["following"] as? String == userData.username{ isFollowing = true } } self.usersFollowing.append(isFollowing) } } self.tableView.reloadData() }) } }else{ print("Error: \(errorFollowers?.userInfo)") } } } //TODO: - METODO DE CONSULTA DE USUARIOS DE PARSE func consultaUsuariosParse(){ let queryUsuariosFromParse = PFUser.query() queryUsuariosFromParse?.findObjectsInBackgroundWithBlock({ (objectsUsuarios, errorUsuarios) in self.usersFromParse.removeAll() for objectsData in objectsUsuarios!{ let userData = objectsData as! PFUser if userData.username != PFUser.currentUser()?.username{ self.usersFromParse.append(userData.username!) } } self.tableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return usersFromParse.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let modelData = usersFromParse[indexPath.row] let followingData = usersFollowing[indexPath.row] cell.textLabel?.text = modelData if followingData{ cell.accessoryType = UITableViewCellAccessoryType.Checkmark }else{ cell.accessoryType = UITableViewCellAccessoryType.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) if cell?.accessoryType == UITableViewCellAccessoryType.Checkmark{ cell?.accessoryType = UITableViewCellAccessoryType.None let queryFollowing = PFQuery(className: "Followers") queryFollowing.whereKey("follower", equalTo: (PFUser.currentUser()?.username)!) queryFollowing.whereKey("following", equalTo: (cell?.textLabel?.text)!) queryFollowing.findObjectsInBackgroundWithBlock({ (objectFollowers, errorFollowers) in if errorFollowers == nil{ if let objectFollowersData = objectFollowers{ for object in objectFollowersData{ object.deleteInBackgroundWithBlock(nil) } } }else{ print("Error: \(errorFollowers?.userInfo)") } }) }else{ cell?.accessoryType = UITableViewCellAccessoryType.Checkmark let following = PFObject(className: "Followers") following["following"] = cell?.textLabel?.text following["follower"] = PFUser.currentUser()?.username following.saveInBackgroundWithBlock(nil) } } }
0447c9dccb3b6f880ba30a7ec6301bfe
35.771242
118
0.584963
false
false
false
false
giaunv/cookiecrunch-swift-spritekit-ios
refs/heads/master
cookiecrunch/GameViewController.swift
mit
1
// // GameViewController.swift // cookiecrunch // // Created by giaunv on 3/8/15. // Copyright (c) 2015 366. All rights reserved. // import UIKit import SpriteKit import AVFoundation class GameViewController: UIViewController{ var scene: GameScene! var level: Level! var movesLeft = 0 var score = 0 var tapGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var movesLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var gameOverPanel: UIImageView! @IBOutlet weak var shuffleButton: UIButton! @IBAction func shuffleButtonPressed(AnyObject){ shuffle() decrementMoves() } lazy var backgroundMusic: AVAudioPlayer = { let url = NSBundle.mainBundle().URLForResource("Mining by Moonlight", withExtension: "mp3") let player = AVAudioPlayer(contentsOfURL: url, error: nil) player.numberOfLoops = -1 return player }() override func prefersStatusBarHidden() -> Bool { return true } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } override func viewDidLoad() { super.viewDidLoad() // Configure the view let skView = view as SKView skView.multipleTouchEnabled = false // Create and configure the scene scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill level = Level(filename: "Level_3") scene.level = level scene.addTiles() scene.swipeHandler = handleSwipe gameOverPanel.hidden = true shuffleButton.hidden = true // Present the scene skView.presentScene(scene) backgroundMusic.play() beginGame() } func beginGame(){ movesLeft = level.maximumMoves score = 0 updateLabels() level.resetComboMultiplier() scene.animateBeginGame(){ self.shuffleButton.hidden = false } shuffle() } func shuffle(){ scene.removeAllCookieSprites() let newCookies = level.shuffle() scene.addSpritesForCookies(newCookies) } func handleSwipe(swap: Swap){ view.userInteractionEnabled = false if level.isPossibleSwap(swap){ level.performSwap(swap) scene.animateSwap(swap, completion: handleMatches) } else{ scene.animateInvalidSwap(swap){ self.view.userInteractionEnabled = true } } } func handleMatches(){ let chains = level.removeMatches() if chains.count == 0{ beginNextTurn() return } scene.animateMatchedCookies(chains){ for chain in chains{ self.score += chain.score } self.updateLabels() let columns = self.level.fillHoles() self.scene.animateFallingCookies(columns){ let columns = self.level.topUpCookies() self.scene.animateNewCookies(columns){ self.handleMatches() } } } } func beginNextTurn(){ level.resetComboMultiplier() level.detectPossibleSwaps() view.userInteractionEnabled = true decrementMoves() } func updateLabels(){ targetLabel.text = NSString(format: "%ld", level.targetScore) movesLabel.text = NSString(format: "%ld", movesLeft) scoreLabel.text = NSString(format: "%ld", score) } func decrementMoves(){ --movesLeft updateLabels() if score >= level.targetScore{ gameOverPanel.image = UIImage(named: "LevelComplete") showGameOver() } else if movesLeft == 0{ gameOverPanel.image = UIImage(named: "GameOver") showGameOver() } } func showGameOver(){ shuffleButton.hidden = true gameOverPanel.hidden = false scene.userInteractionEnabled = false scene.animateGameOver(){ self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideGameOver") self.view.addGestureRecognizer(self.tapGestureRecognizer) } } func hideGameOver(){ view.removeGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer = nil gameOverPanel.hidden = true scene.userInteractionEnabled = true beginGame() } }
90b580fde05f5c4b4b79f9b7eb44e690
26.144444
100
0.580143
false
false
false
false
klundberg/sweep
refs/heads/master
Sources/grift/DependenciesCommand.swift
mit
1
// // DependenciesCommand.swift // Grift // // Created by Kevin Lundberg on 3/23/17. // Copyright © 2017 Kevin Lundberg. All rights reserved. // import Commandant import GriftKit import Result import SourceKittenFramework import SwiftGraph struct GriftError: Error, CustomStringConvertible { var message: String var description: String { return message } } struct DependenciesCommand: CommandProtocol { let verb: String = "dependencies" let function: String = "Generates a dependency graph from swift files in the given directory" func run(_ options: DependenciesOptions) -> Result<(), GriftError> { do { let structures = try GriftKit.structures(at: options.path) let graph = GraphBuilder.build(structures: structures) let dot = graph.graphviz() print(dot.description) return .success(()) } catch { return .failure(GriftError(message: "\(error)")) } } } struct DependenciesOptions: OptionsProtocol { let path: String static func create(_ path: String) -> DependenciesOptions { return DependenciesOptions(path: path) } static func evaluate(_ m: CommandMode) -> Result<DependenciesOptions, CommandantError<GriftError>> { return create <*> m <| Option(key: "path", defaultValue: ".", usage: "The path to generate a dependency graph from") } }
503d7101fef0acafb7f33dd969f91460
26.056604
114
0.658298
false
false
false
false
willpowell8/LocalizationKit_iOS
refs/heads/master
Tests/KeyParseTest.swift
mit
1
// // KeyParseTest.swift // LocalizationKit // // Created by Will Powell on 28/12/2017. // Copyright © 2017 willpowell8. All rights reserved. // import XCTest import LocalizationKit class KeyParseTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseSuccess() { XCTAssert(Localization.parse(str: "com.test") == "com.test") } func testParseSpace() { XCTAssert(Localization.parse(str: "com. test") == "com.test") } func testParsePunctuation() { XCTAssert(Localization.parse(str: "com.#?/<>,test") == "com.test") } }
a43b6d6384c3f6fe9d9a0447dd5dda31
24.472222
111
0.624864
false
true
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureInterest/Sources/FeatureInterestUI/Accessibility+InterestUIKit.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit extension Accessibility.Identifier { public enum Interest { enum Dashboard { enum Announcement { private static let prefix = "InterestAccountAnnouncementScreen." static let rateLineItem = "\(prefix)rateLineItem" static let paymentIntervalLineItem = "\(prefix)paymentIntervalLineItem" static let footerCell = "\(prefix)footerCell" } enum InterestDetails { private static let prefix = "InterestAccoundDetailsScreen." static let view = "\(prefix)view" static let balanceCellTitle = "\(prefix)balanceCellTitle" static let balanceCellDescription = "\(prefix)balanceCellDescription" static let balanceCellFiatAmount = "\(prefix)balanceCellFiatAmount" static let balanceCellCryptoAmount = "\(prefix)balanceCellCryptoAmount" static let balanceCellPending = "\(prefix)balanceCellPending" static let lineItem = "\(prefix)lineItem" static let footerCellTitle = "\(prefix)footerCellTitle" } } } }
c6629d722628a362d9d60e8a1d7ec832
42.206897
87
0.621708
false
false
false
false
rafaelGuerreiro/swift-websocket
refs/heads/master
Sources/App/WebSocketSession.swift
mit
1
import Vapor class WebSocketSession: Equatable, Hashable, CustomStringConvertible { let id: String let username: String let socket: WebSocket init(id: String, username: String, socket: WebSocket) { self.id = id self.username = username self.socket = socket } var description: String { return "\(id) -> \(username)" } var hashValue: Int { return id.hashValue } static func == (lhs: WebSocketSession, rhs: WebSocketSession) -> Bool { return lhs.id == rhs.id } func send(_ message: String) { send(MessageOutputData(message: message, sent: Date.currentTimestamp(), received: Date.currentTimestamp())) } func send(_ output: MessageOutputData) { if let json = try? output.makeJSON(), let bytes = try? json.makeBytes() { print("Sending to \(id)") try? socket.send(bytes.makeString()) } } }
fc4266ca10be63d8032b4ef2f49d872d
24.236842
115
0.596455
false
false
false
false
infinitedg/SwiftDDP
refs/heads/master
Examples/CoreData/SwiftTodos/AppDelegate.swift
mit
1
import UIKit import SwiftDDP import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? let todos = MeteorCoreDataCollection(collectionName: "Todos", entityName: "Todo") let lists = MeteorCoreDataCollection(collectionName: "Lists", entityName: "List") func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.preferredDisplayMode = .AllVisible splitViewController.delegate = self // let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController // let listViewController = masterNavigationController.topViewController as! Lists Meteor.client.logLevel = .Debug let url = "ws://localhost:3000/websocket" // let url = "wss://meteor-ios-todos.meteor.com/websocket" Meteor.connect(url) { Meteor.subscribe("lists.public") Meteor.subscribe("lists.private") } print("Application Did Finish Launching") return true } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { if let todosViewController = (secondaryViewController as? UINavigationController)?.topViewController as? Todos { if todosViewController.listId == nil { return true } } return false } // MARK: - Core Data Saving support /* func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }*/ }
c160cb26e51d9bc529dcc849f1e88c7a
37.53125
222
0.660989
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Extensions/ShareTo/SendToDevice.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage class SendToDevice: DevicePickerViewControllerDelegate, InstructionsViewControllerDelegate { var sharedItem: ShareItem? weak var delegate: ShareControllerDelegate? func initialViewController() -> UIViewController { if !hasAccount() { let instructionsViewController = InstructionsViewController() instructionsViewController.delegate = self return instructionsViewController } let devicePickerViewController = DevicePickerViewController() devicePickerViewController.pickerDelegate = self devicePickerViewController.profile = nil // This means the picker will open and close the default profile return devicePickerViewController } func finish() { delegate?.finish(afterDelay: 0) } func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) { guard let item = sharedItem else { return finish() } let profile = BrowserProfile(localName: "profile") profile.sendItem(item, toDevices: devices).uponQueue(.main) { _ in profile._shutdown() self.finish() addAppExtensionTelemetryEvent(forMethod: "send-to-device") } } func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) { finish() } func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { finish() } private func hasAccount() -> Bool { let profile = BrowserProfile(localName: "profile") defer { profile._shutdown() } return profile.hasAccount() } }
7c347cdc8a1e9c6b5a2d7372975d7ffa
32.966102
135
0.686627
false
false
false
false
ripventura/VCUIKit
refs/heads/master
VCUIKit/Classes/VCTheme/View Controller/Collection View/VCCollectionViewController.swift
mit
1
// // VCCollectionViewController.swift // FCAlertView // // Created by Vitor Cesco on 26/02/18. // import UIKit open class VCCollectionViewController: UICollectionViewController, RefreshControlManagerDelegate, SearchControlManagerDelegate { /** Whether the appearance is being set manually on Storyboard */ @IBInspectable var storyboardAppearance: Bool = false /** Whether the CollectionView should have a RefreshControl */ @IBInspectable open var includesRefreshControl: Bool = false /** Whether the CollectionView should have a RefreshControl */ @IBInspectable open var includesSearchControl: Bool = false /** Whether the CollectionView should disable the RefreshControl when searching */ @IBInspectable open var disablesRefreshWhenSearching: Bool = true open var refreshControlManager: RefreshControlManager = RefreshControlManager() open var searchControlManager: SearchControlManager = SearchControlManager() // MARK: - Lifecycle open override func viewDidLoad() { super.viewDidLoad() self.refreshControlManager.delegate = self if self.includesRefreshControl { self.refreshControlManager.setupRefreshControl(scrollView: self.collectionView) } self.searchControlManager.delegate = self if self.includesSearchControl { self.searchControlManager.setupSearchControl(viewController: self) } self.updateBackButtonStyle() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.applyAppearance() } // MARK: - Styling /** Override this if you want to change the Default Styles for this particular View Controller */ open func willSetDefaultStyles() { sharedAppearanceManager.initializeDefaultAppearance?() sharedAppearanceManager.appearance = defaultAppearance } override open func applyAppearance() -> Void { self.willSetDefaultStyles() super.applyAppearance() self.collectionView?.backgroundColor = sharedAppearanceManager.appearance.collectionViewBackgroundColor //Updates StatusBar Style UIApplication.shared.statusBarStyle = sharedAppearanceManager.appearance.applicationStatusBarStyle //Updates NavigationBar appearance self.navigationController?.applyAppearance() if !storyboardAppearance { self.view.tintColor = sharedAppearanceManager.appearance.viewControllerViewTintColor self.view.backgroundColor = sharedAppearanceManager.appearance.collectionViewBackgroundColor } //Updates TabBar colors self.tabBarController?.applyAppearance() } // MARK: - RefreshControlManagerDelegate open func refreshControlDidRefresh(manager: RefreshControlManager) { } // MARK: - SearchControlManagerDelegate open func searchControlDidBeginEditing(manager: SearchControlManager) { if self.disablesRefreshWhenSearching { // Disables the RefreshControl when searching self.collectionView?.bounces = false self.collectionView?.alwaysBounceVertical = false } } open func searchControlCancelButtonPressed(manager: SearchControlManager) { if self.disablesRefreshWhenSearching { // Enables back the RefreshControl self.collectionView?.bounces = true self.collectionView?.alwaysBounceVertical = true } } open func searchControl(manager: SearchControlManager, didSearch text: String?) { } }
31f07d38247b25c8a788015a7723d94f
36.876289
128
0.704682
false
false
false
false
15cm/AMM
refs/heads/master
AMM/Preferences/AboutViewController.swift
gpl-3.0
1
// // AboutViewÇontroller.swift // AMM // // Created by Sinkerine on 19/02/2017. // Copyright © 2017 sinkerine. All rights reserved. // import Cocoa class AboutViewController: NSViewController { let infoDictionary = Bundle.main.infoDictionary! @IBOutlet weak var appName: NSTextField! { didSet { appName.stringValue = infoDictionary["CFBundleName"] as! String } } @IBOutlet weak var appVersionBuild: NSTextField! { didSet { let version = infoDictionary["CFBundleShortVersionString"] as! String let build = infoDictionary["CFBundleVersion"] as! String appVersionBuild.stringValue = "v\(version) (Build \(build))" } } @IBOutlet weak var appSource: NSTextField! { didSet { let sourceRTFPath = Bundle.main.path(forResource: "Source", ofType: "rtf") do { if let path = sourceRTFPath { let data = try Data(contentsOf: URL(fileURLWithPath: path)) appSource.attributedStringValue = NSAttributedString(rtf: data, documentAttributes: nil)! } } catch { print(error) } } } @IBOutlet weak var contactMe: NSTextField! { didSet { do { let contactRTFPath = Bundle.main.path(forResource: "Contact", ofType: "rtf") if let path = contactRTFPath { let data = try Data(contentsOf: URL(fileURLWithPath: path)) contactMe.attributedStringValue = NSAttributedString(rtf: data, documentAttributes: nil)! } } catch { print(error) } } } @IBOutlet weak var copyright: NSTextField! { didSet { copyright.stringValue = infoDictionary["NSHumanReadableCopyright"] as! String } } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
2f6edf1267e7af3c61f30c41774d6bbc
31.548387
109
0.570367
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Controller/Departure/BusStopViewController.swift
gpl-3.0
1
import UIKit import RxSwift import RxCocoa import Realm import RealmSwift import Alamofire import StatefulViewController class BusStopViewController: MasterViewController, UITabBarDelegate, StatefulViewController { let dateFormat = "HH:mm" @IBOutlet weak var timeField: UITextField! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var autoCompleteTableView: UITableView! var selectedBusStop: BBusStop? var foundBusStations: [BBusStop] = [] var datePicker: UIDatePicker! var allDepartures: [Departure] = [] var disabledDepartures: [Departure] = [] var searchDate: Date! var refreshControl: UIRefreshControl! var working: Bool! = false var realm = Realm.busStops() init(busStop: BBusStop? = nil) { super.init(nibName: "BusStopViewController", title: L10n.Departures.title) self.selectedBusStop = busStop } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "DepartureViewCell", bundle: nil), forCellReuseIdentifier: "DepartureViewCell") tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() refreshControl = UIRefreshControl() refreshControl.tintColor = Theme.lightOrange refreshControl.addTarget(self, action: #selector(parseData), for: .valueChanged) refreshControl.attributedTitle = NSAttributedString( string: L10n.General.pullToRefresh, attributes: [NSForegroundColorAttributeName: Theme.darkGrey] ) tableView.refreshControl = refreshControl setupSearchDate() view.backgroundColor = Theme.darkGrey searchBar.barTintColor = .darkGray searchBar.tintColor = Theme.white searchBar.backgroundImage = UIImage() searchBar.setImage(Asset.icNavigationBus.image, for: UISearchBarIcon.search, state: UIControlState()) (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey (searchBar.value(forKey: "searchField") as! UITextField).clearButtonMode = UITextFieldViewMode.never navigationItem.rightBarButtonItem = getFilterButton() tabBar.items![0].title = L10n.Departures.Header.gps tabBar.items![1].title = L10n.Departures.Header.map tabBar.items![2].title = L10n.Departures.Header.favorites datePicker = UIDatePicker(frame: CGRect.zero) datePicker.datePickerMode = .dateAndTime datePicker.backgroundColor = Theme.darkGrey datePicker.tintColor = Theme.white datePicker.setValue(Theme.white, forKey: "textColor") timeField.textColor = Theme.white timeField.tintColor = Theme.transparent timeField.inputView = datePicker loadingView = LoadingView(frame: view.frame) emptyView = NoDeparturesView(frame: tableView.frame) errorView = ErrorView(frame: view.frame, target: self, action: #selector(parseData)) setupAutoCompleteTableView() setupBusStopSearchDate() if let stop = selectedBusStop { let tempStop = stop selectedBusStop = nil setBusStop(tempStop) } } override func leftDrawerButtonPress(_ sender: AnyObject?) { self.searchBar.endEditing(true) self.timeField.endEditing(true) super.leftDrawerButtonPress(sender) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let view = emptyView { view.frame = CGRect( x: view.frame.origin.x, y: view.frame.origin.y + tabBar.frame.size.height, width: view.frame.size.width, height: view.frame.size.height - 2 * tabBar.frame.size.height ) (view as? NoDeparturesView)?.setupView() } } override func viewDidAppear(_ animated: Bool) { tabBar.selectedItem = nil } fileprivate func setupAutoCompleteTableView() { self.autoCompleteTableView!.isHidden = true self.updateFoundBusStations("") self.view.addSubview(self.autoCompleteTableView!) self.autoCompleteTableView!.register(UINib(nibName: "DepartureAutoCompleteCell", bundle: nil), forCellReuseIdentifier: "DepartureAutoCompleteCell") } fileprivate func updateFoundBusStations(_ searchText: String) { let busStops: Results<BusStop> if searchText.isEmpty { busStops = realm.objects(BusStop.self) } else { busStops = realm.objects(BusStop.self) .filter("nameDe CONTAINS[c] %@ OR nameIt CONTAINS[c] %@ OR municDe CONTAINS[c] %@ OR municIt CONTAINS[c] %@", searchText, searchText, searchText, searchText) } let mapped = busStops.map { BBusStop(fromRealm: $0) } foundBusStations = Array(Set(mapped)) self.foundBusStations = foundBusStations.sorted(by: { $0.name(locale: Locales.get()) < $1.name(locale: Locales.get()) }) self.autoCompleteTableView.reloadData() } func setBusStationFromCurrentLocation() { // TODO /*if UserDefaultHelper.instance.isBeaconStationDetectionEnabled() { let currentBusStop = UserDefaultHelper.instance.getCurrentBusStop() if let stop = currentBusStop != nil { Log.info("Current bus stop: \(stop)") if let busStop = realm.objects(BusStop.self).filter("id == \(stop)").first { setBusStop(BBusStop(fromRealm: busStop)) setupBusStopSearchDate() autoCompleteTableView.isHidden = true tabBar.selectedItem = nil } } }*/ } func setupBusStopSearchDate() { setupSearchDate() datePicker.date = searchDate as Date let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat timeField.text = dateFormatter.string(from: searchDate as Date) } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 0 { let busStopGpsViewController = BusStopGpsViewController() navigationController!.pushViewController(busStopGpsViewController, animated: true) } else if item.tag == 1 { let busStopMapViewController = BusStopMapViewController() navigationController!.pushViewController(busStopMapViewController, animated: true) } else if item.tag == 2 { let busStopFavoritesViewController = BusStopFavoritesViewController(busStop: self.selectedBusStop) navigationController!.pushViewController(busStopFavoritesViewController, animated: true) } } func goToFilter() { let busStopFilterViewController = BusStopFilterViewController() navigationController!.pushViewController(busStopFilterViewController, animated: true) } func setBusStop(_ busStop: BBusStop) { if selectedBusStop != nil && selectedBusStop!.family == busStop.family { // Don't reload same bus stop return } Log.info("Setting bus stop '\(busStop.id)'") selectedBusStop = busStop autoCompleteTableView.isHidden = true searchBar.text = selectedBusStop?.name() searchBar.endEditing(true) searchBar.resignFirstResponder() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func parseData() { guard selectedBusStop != nil else { Log.error("No bus stop is currently selected") return } startLoading() _ = self.getDepartures() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { items in self.allDepartures.removeAll() self.allDepartures.append(contentsOf: items) self.updateFilter() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false) self.loadDelays() }, onError: { error in ErrorHelper.log(error, message: "Could not fetch departures") self.allDepartures.removeAll() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false, error: error) }) } func loadDelays() { _ = RealtimeApi.delays() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { buses in for bus in buses { for item in self.allDepartures { if item.trip == bus.trip { item.delay = bus.delay item.vehicle = bus.vehicle item.currentBusStop = bus.busStop break } } } self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }, onError: { error in ErrorHelper.log(error, message: "Could not load delays") self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }) } func updateFilter() { let disabledLines: [Int] = UserRealmHelper.getDisabledDepartures() disabledDepartures.removeAll() if disabledLines.isEmpty { disabledDepartures.append(contentsOf: allDepartures) } else { disabledDepartures.append(contentsOf: allDepartures.filter { !disabledLines.contains($0.lineId) }) } self.refreshControl.endRefreshing() self.tableView.reloadData() self.enableSearching() } func hasContent() -> Bool { return !allDepartures.isEmpty } func getDepartures() -> Observable<[Departure]> { return Observable.create { observer in let departures = DepartureMonitor() .atBusStopFamily(family: self.selectedBusStop?.family ?? 0) .at(date: self.searchDate) .collect() let mapped = departures.map { $0.asDeparture(busStopId: self.selectedBusStop?.id ?? 0) } observer.on(.next(mapped)) return Disposables.create() } } } extension BusStopViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { return self.foundBusStations.count } else { return disabledDepartures.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { let busStation = self.foundBusStations[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureAutoCompleteCell", for: indexPath) as! DepartureAutoCompleteCell cell.label.text = busStation.name() return cell } let departure = disabledDepartures[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureViewCell", for: indexPath) as! DepartureViewCell cell.timeLabel.text = departure.time if departure.delay == Departure.OPERATION_RUNNING { cell.delayLabel.text = L10n.Departures.Cell.loading cell.delayColor = Theme.darkGrey } else if departure.delay == Departure.NO_DELAY { cell.delayLabel.text = L10n.Departures.Cell.noData cell.delayColor = Theme.darkGrey } if departure.vehicle != 0 { cell.delayColor = Color.delay(departure.delay) if departure.delay == 0 { cell.delayLabel.text = L10n.General.delayPunctual } else if departure.delay < 0 { cell.delayLabel.text = L10n.General.delayEarly(abs(departure.delay)) } else { cell.delayLabel.text = L10n.General.delayDelayed(departure.delay) } } cell.infoLabel.text = Lines.line(id: departure.lineId) cell.directionLabel.text = departure.destination return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if autoCompleteTableView != nil && tableView.isEqual(autoCompleteTableView) { navigationItem.rightBarButtonItem = getFilterButton() let busStop = foundBusStations[indexPath.row] // Is this the right place to put this? UserRealmHelper.addRecentDeparture(group: busStop.family) setBusStop(busStop) } else { let item = disabledDepartures[indexPath.row] let busStopTripViewController = LineCourseViewController( tripId: item.trip, lineId: item.lineId, vehicle: item.vehicle, currentBusStop: item.currentBusStop, busStopGroup: item.busStopGroup, date: searchDate ) self.navigationController!.pushViewController(busStopTripViewController, animated: true) } } } extension BusStopViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return false } func textFieldDidBeginEditing(_ textField: UITextField) { let datePickerDoneButton = UIBarButtonItem( title: L10n.Departures.Button.done, style: UIBarButtonItemStyle.done, target: self, action: #selector(setSearchDate) ) navigationItem.rightBarButtonItem = datePickerDoneButton } func textFieldDidEndEditing(_ textField: UITextField) { navigationItem.rightBarButtonItem = nil allDepartures.removeAll() tableView.reloadData() textField.resignFirstResponder() } } extension BusStopViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if selectedBusStop != nil { selectedBusStop = nil } updateFoundBusStations(searchText) } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return !working } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(searchBarCancel) ) searchBar.text = "" updateFoundBusStations(searchBar.text!) autoCompleteTableView.isHidden = false errorView?.isHidden = true loadingView?.isHidden = true emptyView?.isHidden = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { foundBusStations = [] autoCompleteTableView.isHidden = true autoCompleteTableView.reloadData() startLoading(animated: false) endLoading(animated: false) errorView?.isHidden = false loadingView?.isHidden = false emptyView?.isHidden = false } } extension BusStopViewController { internal func disableSearching() { self.working = true (self.searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.grey self.timeField.isUserInteractionEnabled = false self.searchBar.alpha = 0.7 self.timeField.alpha = 0.7 let items = self.tabBar.items for item in items! { item.isEnabled = false } self.tabBar.setItems(items, animated: false) } internal func enableSearching() { working = false (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey timeField.isUserInteractionEnabled = true searchBar.alpha = 1.0 timeField.alpha = 1.0 let items = tabBar.items for item in items! { item.isEnabled = true } tabBar.setItems(items, animated: false) } func searchBarCancel() { searchBar.endEditing(true) searchBar.resignFirstResponder() navigationItem.rightBarButtonItem = getFilterButton() } func setSearchDate() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat searchDate = datePicker.date timeField.text = dateFormatter.string(from: searchDate as Date) timeField.endEditing(true) navigationItem.rightBarButtonItem = getFilterButton() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func setupSearchDate() { self.searchDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat } func getFilterButton() -> UIBarButtonItem { return UIBarButtonItem( image: Asset.filterIcon.image.withRenderingMode(UIImageRenderingMode.alwaysTemplate), style: .plain, target: self, action: #selector(goToFilter) ) } }
9622cb486f7a62beeccb02272bec941e
30.735
129
0.604695
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Profiler/pgo_foreach.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_foreach -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // need to move counts attached to expr for this // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=SIL // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=IR // need to check Opt support // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic // SIL-LABEL: // pgo_foreach.guessForEach1 // SIL-LABEL: sil @$s11pgo_foreach13guessForEach11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) { // IR-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF public func guessForEach1(x: Int32) -> Int32 { // SIL: switch_enum {{.*}} : $Optional<Int32>, case #Optional.some!enumelt.1: {{.*}} !case_count(798), case #Optional.none!enumelt: {{.*}} !case_count(42) var ret : Int32 = 0 for currVal in stride(from: 5, to: x, by: 5) { ret += currVal } return ret } // SIL-LABEL: // pgo_foreach.guessForEach2 // SIL-LABEL: sil @$s11pgo_foreach13guessForEach21xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) { // IR-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF public func guessForEach2(x: Int32) -> Int32 { // SIL: switch_enum {{.*}} : $Optional<(String, Int32)>, case #Optional.some!enumelt.1: {{.*}} !case_count(168), case #Optional.none!enumelt: {{.*}} !case_count(42) var ret : Int32 = 0 let names = ["John" : Int32(1), "Paul" : Int32(2), "George" : Int32(3), "Ringo" : Int32(x)] for (name, number) in names { ret += Int32(name.count) ret += number } return ret } // SIL-LABEL: // pgo_foreach.main() // IR-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s9pgo_foreach10guessWhiles5Int32VAD1x_tF func main() { // SIL: switch_enum {{.*}} : $Optional<Int>, case #Optional.some!enumelt.1: {{.*}} !case_count(42), case #Optional.none!enumelt: {{.*}} !case_count(1) var guesses : Int32 = 0; for _ in 1...42 { guesses += guessForEach1(x: 100) guesses += guessForEach2(x: 100) } } main() // IR: !{!"branch_weights", i32 421, i32 43} // IR: !{!"branch_weights", i32 176401, i32 421} // IR-OPT: !{!"branch_weights", i32 421, i32 43} // IR-OPT: !{!"branch_weights", i32 176401, i32 421}
89ab3ece097c6a949313dc809ab2d1da
46.306667
186
0.688275
false
false
false
false
almazrafi/Metatron
refs/heads/master
Sources/MPEG/MPEGHeader.swift
mit
1
// // MPEGHeader.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public class MPEGHeader { // MARK: Type Properties static let bitRates: [[[Int]]] = [[[32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448], [32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384], [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]], [[32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256], [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]]] static let sampleRates: [[Int]] = [[44100, 48000, 32000], [22050, 24000, 16000], [11025, 12000, 8000]] static let samplesPerFrames: [[Int]] = [[384, 1152, 1152], [384, 1152, 576]] static let allowedChannelModes: [[[Bool]]] = [[[true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true]], [[true, true, true, true], [false, false, false, true], [false, false, false, true], [false, false, false, true], [true, true, true, true], [false, false, false, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, false], [true, true, true, false], [true, true, true, false], [true, true, true, false]], [[true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true], [true, true, true, true]]] static let sideInfoLengths: [[Int]] = [[32, 32, 32, 17], [17, 17, 17, 9]] static let slotLengths: [Int] = [4, 1, 1] // MARK: static let anyDataLength: Int = 4 // MARK: Instance Properties public var version: MPEGVersion public var layer: MPEGLayer public var crc16: UInt16? public var bitRate: Int public var sampleRate: Int public var padding: Bool public var privatized: Bool public var channelMode: MPEGChannelMode public var copyrighted: Bool public var original: Bool public var emphasis: MPEGEmphasis // MARK: public var samplesPerFrame: Int { return MPEGHeader.samplesPerFrames[self.version.majorIndex][self.layer.index] } public var frameLength: Int { if (self.bitRate > 0) && (self.sampleRate > 0) { if self.padding { let slotLength = MPEGHeader.slotLengths[self.layer.index] return (self.samplesPerFrame * self.bitRate * 125) / self.sampleRate + slotLength } else { return (self.samplesPerFrame * self.bitRate * 125) / self.sampleRate } } return 0 } // MARK: var sideInfoLength: Int { return MPEGHeader.sideInfoLengths[self.version.majorIndex][self.channelMode.index] } var bitRateIndex: Int { let bitRates = MPEGHeader.bitRates[self.version.majorIndex][self.layer.index] for i in 0..<bitRates.count { if self.bitRate == bitRates[i] { return i + 1 } } return 15 } var sampleRateIndex: Int { let sampleRates = MPEGHeader.sampleRates[self.version.index] for i in 0..<sampleRates.count { if self.sampleRate == sampleRates[i] { return i } } return 3 } // MARK: public var isValid: Bool { let bitRateIndex = self.bitRateIndex if bitRateIndex >= 15 { return false } if self.sampleRateIndex >= 3 { return false } return MPEGHeader.allowedChannelModes[self.layer.index][bitRateIndex][self.channelMode.index] } // MARK: Initializers public init() { self.version = MPEGVersion.v1 self.layer = MPEGLayer.layer3 self.bitRate = 160 self.sampleRate = 44100 self.padding = false self.privatized = false self.channelMode = MPEGChannelMode.stereo self.copyrighted = false self.original = false self.emphasis = MPEGEmphasis.none } public init?(fromData data: [UInt8]) { guard data.count >= MPEGHeader.anyDataLength else { return nil } guard (data[0] == 255) && ((data[1] & 224) == 224) else { return nil } switch (data[1] >> 3) & 3 { case 0: self.version = MPEGVersion.v2x5 case 2: self.version = MPEGVersion.v2 case 3: self.version = MPEGVersion.v1 default: return nil } switch (data[1] >> 1) & 3 { case 1: self.layer = MPEGLayer.layer3 case 2: self.layer = MPEGLayer.layer2 case 3: self.layer = MPEGLayer.layer1 default: return nil } if ((data[1] & 1) == 0) && (data.count >= 6) { self.crc16 = (UInt16(data[4]) << 8) | UInt16(data[5]) } let bitRateIndex = Int((data[2] >> 4) & 15) if (bitRateIndex > 0) && (bitRateIndex < 15) { self.bitRate = MPEGHeader.bitRates[self.version.majorIndex][self.layer.index][bitRateIndex - 1] } else { self.bitRate = 0 } let sampleRateIndex = Int((data[2] >> 2) & 3) if sampleRateIndex < 3 { self.sampleRate = MPEGHeader.sampleRates[self.version.index][sampleRateIndex] } else { self.sampleRate = 0 } self.padding = ((data[2] & 2) != 0) self.privatized = ((data[2] & 1) != 0) self.channelMode = MPEGChannelMode(rawValue: (data[3] >> 4) & 15)! self.copyrighted = ((data[3] & 8) != 0) self.original = ((data[3] & 4) != 0) self.emphasis = MPEGEmphasis(rawValue: data[3] & 3)! } // MARK: Instance Methods public func toData() -> [UInt8]? { guard self.isValid else { return nil } var data: [UInt8] switch self.version { case MPEGVersion.v1: data = [255, 248, 0, 0] case MPEGVersion.v2: data = [255, 240, 0, 0] case MPEGVersion.v2x5: data = [255, 224, 0, 0] } switch self.layer { case MPEGLayer.layer1: data[1] |= 7 case MPEGLayer.layer2: data[1] |= 5 case MPEGLayer.layer3: data[1] |= 3 } if let crc16 = self.crc16 { data[1] &= 254 data.append(UInt8((crc16 >> 8) & 255)) data.append(UInt8(crc16 & 255)) } data[2] |= UInt8(self.bitRateIndex & 15) << 4 data[2] |= UInt8(self.sampleRateIndex & 3) << 2 if self.padding { data[2] |= 2 } if self.privatized { data[2] |= 1 } data[3] |= self.channelMode.rawValue << 4 if self.copyrighted { data[3] |= 8 } if self.original { data[3] |= 4 } data[3] |= self.emphasis.rawValue return data } }
f4d6318f93e601fbbc45fb97854c77a4
32.222874
108
0.439403
false
false
false
false
JeffESchmitz/RideNiceRide
refs/heads/master
RideNiceRide/ViewControllers/PullUp/BottomViewController.swift
mit
1
// // BottomViewController.swift // RideNiceRide // // Created by Jeff Schmitz on 11/17/16. // Copyright © 2016 Jeff Schmitz. All rights reserved. // import UIKit import ISHPullUp import MapKit import GoogleMaps import Willow import Device enum FavoriteViewState: Int { case unknown case addFavoriteStation case removeFavoriteStation } // TODO: Move out to a Protocol's file? Maybe, maybe not? /** * This protocol allows you to gain access to the Google PanoramaView nested inside the BottomViewController. * Basically, it's just call forwarding the same functions(with params) on the PanoramaView object. */ protocol PanoramaViewDelegate { func moveNearCoordinate(coordinate: CLLocationCoordinate2D) func didSelect(StationViewModel viewModel: StationViewModel) func didDeselect() } protocol ManageFavoriteDelegate { func addFavoriteStation() func removeFavoriteStation() } class BottomViewController: UIViewController, PanoramaViewDelegate { // MARK: - Public properties @IBOutlet weak var handleView: ISHPullUpHandleView! @IBOutlet weak var rootView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var topView: UIView! @IBOutlet weak var panoramaView: UIView! @IBOutlet weak var addFavoriteButton: UIButton! @IBOutlet weak var stationNameLabel: UILabel! @IBOutlet weak var stationAddressLabel: UILabel! @IBOutlet weak var bikesAvailableLabel: UILabel! @IBOutlet weak var docksAvailableLabel: UILabel! var firstAppearanceCompleted = false weak var pullUpController: ISHPullUpViewController! var panoView: GMSPanoramaView? var manageFavoriteDelegate: ManageFavoriteDelegate? // allow the pullup to snap to the half-way point var halfWayPoint = CGFloat(0) // MARK: - Private properties fileprivate var addRemoveState = FavoriteViewState.unknown fileprivate var selectedStationViewModel: StationViewModel? { didSet { var starImage: UIImage? if selectedStationViewModel == nil { starImage = UIImage(asset: .Star_off) } else { if let isAFavorite = selectedStationViewModel?.isStationAFavorite { if isAFavorite { addRemoveState = .removeFavoriteStation starImage = UIImage(asset: .Star_on) } else { addRemoveState = .addFavoriteStation starImage = UIImage(asset: .Star_off) } } } addFavoriteButton.setImage(starImage, for: .normal) setLabelValues() } } let panoViewStartHeight = UIScreen.main.bounds.height * 0.3 // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() let screenWidth = UIScreen.main.bounds.width log.info("screenWidth: \(screenWidth)") let panoHeight = UIScreen.main.bounds.height * 0.3 log.info("panoHeight: \(panoHeight)") let frameRect = CGRect(x: 0, y: 0, width: screenWidth, height: panoHeight) panoView = GMSPanoramaView(frame: frameRect) guard let panoView = panoView else { log.error("PanoramaView error - inside function '\(#function)'") return } self.panoramaView.frame = panoView.frame self.panoramaView.addSubview(panoView) self.panoramaView = panoView let centerOfBoston = CLLocationCoordinate2DMake(42.361145, -71.057083) panoView.moveNearCoordinate(centerOfBoston) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) firstAppearanceCompleted = true } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let screenWidth = size.width log.info("screenWidth: \(screenWidth)") log.info("panoHeight: \(self.panoViewStartHeight)") let frameRect = CGRect(x: 0, y: 0, width: screenWidth, height: panoViewStartHeight) log.event("panoView before frame update - width: \(self.panoView?.frame.width), before height: \(self.panoView?.frame.height)") panoView?.frame = frameRect log.event("panoView AFTER frame update - width: \(self.panoView?.frame.width), before height: \(self.panoView?.frame.height)") } @IBAction func favoriteTouched(_ sender: Any) { var starImage: UIImage? switch addRemoveState { case .addFavoriteStation: manageFavoriteDelegate?.addFavoriteStation() starImage = UIImage(asset: .Star_on) addRemoveState = .removeFavoriteStation case .removeFavoriteStation: manageFavoriteDelegate?.removeFavoriteStation() starImage = UIImage(asset: .Star_off) addRemoveState = .addFavoriteStation default: log.warn("An unknown state occured while tapping on the Add/Remove Favorite button") } addFavoriteButton.setImage(starImage, for: .normal) } private dynamic func handleTapGesture(gesture: UITapGestureRecognizer) { if pullUpController.isLocked { return } pullUpController.toggleState(animated: true) } private func addRemoveTextForState(_ state: FavoriteViewState) -> String { switch state { case .removeFavoriteStation: return "Add Favorite" case .addFavoriteStation: return "Remove Favorite" case .unknown: return "Unknown" } } private func setLabelValues() { stationNameLabel.text = selectedStationViewModel?.stationName stationAddressLabel.text = selectedStationViewModel?.address bikesAvailableLabel.text = selectedStationViewModel?.availableBikes docksAvailableLabel.text = selectedStationViewModel?.availableDocks } // MARK: - BottomPanoramaViewDelegate func moveNearCoordinate(coordinate: CLLocationCoordinate2D) { log.event("Inside function \(#function) - lat: \(coordinate.latitude), lon: \(coordinate.longitude)") panoView?.moveNearCoordinate(coordinate) } func didSelect(StationViewModel viewModel: StationViewModel) { addRemoveState = .addFavoriteStation self.selectedStationViewModel = viewModel } func didDeselect() { addRemoveState = .removeFavoriteStation self.selectedStationViewModel = nil } } // MARK: - GMSPanoramaViewDelegate extension BottomViewController: GMSPanoramaViewDelegate { func panoramaView(_ view: GMSPanoramaView, error: Error, onMoveNearCoordinate coordinate: CLLocationCoordinate2D) { log.event("Moving near coordinate (\(coordinate.latitude),\(coordinate.longitude) error: \(error.localizedDescription)") } func panoramaView(_ view: GMSPanoramaView, error: Error, onMoveToPanoramaID panoramaID: String) { log.event("Moving to PanoID \(panoramaID) error: \(error.localizedDescription)") } func panoramaView(_ view: GMSPanoramaView, didMoveTo panorama: GMSPanorama?) { log.event("Moved to panoramaID: \(panorama?.panoramaID) coordinates: (\(panorama?.coordinate.latitude),\(panorama?.coordinate.longitude))") } } // MARK: - ISHPullUpSizingDelegate extension BottomViewController: ISHPullUpSizingDelegate { func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, maximumHeightForBottomViewController bottomVC: UIViewController, maximumAvailableHeight: CGFloat) -> CGFloat { let totalHeight = rootView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height // let totalHeight = CGFloat(359.0) // Allow the pullUp to snap to the half way point, calculate the cached // value here and perform the snapping in ..targetHeightForBottomViewController.. halfWayPoint = totalHeight / 2.0 return totalHeight } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, minimumHeightForBottomViewController bottomVC: UIViewController) -> CGFloat { // let height = topView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height let height = CGFloat(0) return height } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, targetHeightForBottomViewController bottomVC: UIViewController, fromCurrentHeight height: CGFloat) -> CGFloat { // if around 30pt of the halfway point -> snap to it if abs(height - halfWayPoint) < 30 { return halfWayPoint } // default return height } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, update edgeInsets: UIEdgeInsets, forBottomViewController contentVC: UIViewController) { scrollView.contentInset = edgeInsets } } // MARK: - ISHPullUpStateDelegate extension BottomViewController: ISHPullUpStateDelegate { func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, didChangeTo state: ISHPullUpState) { topLabel.text = textForState(state) handleView.setState(ISHPullUpHandleView.handleState(for: state), animated: firstAppearanceCompleted) } private func textForState(_ state: ISHPullUpState) -> String { switch state { case .collapsed: return "Drag up or tap" case .intermediate: return "Intermediate" case .dragging: return "Hold on" case .expanded: return "Drag down or tap" } } }
21c1c0a289597be7093b22caebe3bae3
34.458824
188
0.74165
false
true
false
false
sajnabjohn/WebPage
refs/heads/master
WebPage/Classes/Reachability.swift
mit
1
// // Reachability.swift // Copyright © 2016 . All rights reserved. // import Foundation import SystemConfiguration public let ReachabilityDidChangeNotificationName = "ReachabilityDidChangeNotification" enum ReachabilityStatus { case notReachable case reachableViaWiFi case reachableViaWWAN } class Reachability: NSObject { private var networkReachability: SCNetworkReachability? private var notifying: Bool = false init?(hostAddress: sockaddr_in) { var address = hostAddress guard let defaultRouteReachability = withUnsafePointer(to: &address, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, $0) } }) else { return nil } networkReachability = defaultRouteReachability super.init() if networkReachability == nil { return nil } } static func networkReachabilityForInternetConnection() -> Reachability? { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) return Reachability(hostAddress: zeroAddress) } static func networkReachabilityForLocalWiFi() -> Reachability? { var localWifiAddress = sockaddr_in() localWifiAddress.sin_len = UInt8(MemoryLayout.size(ofValue: localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 (0xA9FE0000). localWifiAddress.sin_addr.s_addr = 0xA9FE0000 return Reachability(hostAddress: localWifiAddress) } func startNotifier() -> Bool { guard notifying == false else { return false } var context = SCNetworkReachabilityContext() context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) guard let reachability = networkReachability, SCNetworkReachabilitySetCallback(reachability, { (target: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in if let currentInfo = info { let infoObject = Unmanaged<AnyObject>.fromOpaque(currentInfo).takeUnretainedValue() if infoObject is Reachability { let networkReachability = infoObject as! Reachability NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityDidChangeNotificationName), object: networkReachability) } } }, &context) == true else { return false } guard SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) == true else { return false } notifying = true return notifying } func stopNotifier() { if let reachability = networkReachability, notifying == true { SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue ) notifying = false } } private var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags(rawValue: 0) if let reachability = networkReachability, withUnsafeMutablePointer(to: &flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) == true { return flags } else { return [] } } var currentReachabilityStatus: ReachabilityStatus { if flags.contains(.reachable) == false { // The target host is not reachable. return .notReachable } else if flags.contains(.isWWAN) == true { // WWAN connections are OK if the calling application is using the CFNetwork APIs. return .reachableViaWWAN } else if flags.contains(.connectionRequired) == false { // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi... return .reachableViaWiFi } else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false { // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed return .reachableViaWiFi } else { return .notReachable } } var isReachable: Bool { switch currentReachabilityStatus { case .notReachable: return false case .reachableViaWiFi, .reachableViaWWAN: return true } } deinit { stopNotifier() } }
a80e00ae47202a1c19398251557867da
38.834532
208
0.580459
false
false
false
false
Inquisitor0/LSB2
refs/heads/master
DribbbleCollection/Pods/Tabman/Sources/Tabman/TabmanBar/TabmanBar.swift
mit
3
// // TabmanBar.swift // Tabman // // Created by Merrick Sapsford on 17/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit import PureLayout import Pageboy /// A bar that displays the current page status of a TabmanViewController. open class TabmanBar: UIView, TabmanBarLifecycle { // // MARK: Types // /// The style of the bar. /// /// - bar: A simple horizontal bar only. /// - buttonBar: A horizontal bar with evenly distributed buttons for each page index. /// - scrollingButtonBar: A scrolling horizontal bar with buttons for each page index. /// - blockTabBar: A tab bar with sliding block style indicator behind tabs. /// - custom: A custom defined TabmanBar type. public enum Style { case bar case buttonBar case scrollingButtonBar case blockTabBar case custom(type: TabmanBar.Type) } /// The height for the bar. /// /// - auto: Autosize the bar according to its contents. /// - explicit: Explicit value for the bar height. public enum Height { case auto case explicit(value: CGFloat) } // // MARK: Properties // // Private internal var items: [TabmanBarItem]? { didSet { self.isHidden = (items?.count ?? 0) == 0 } } internal private(set) var currentPosition: CGFloat = 0.0 internal weak var transitionStore: TabmanBarTransitionStore? /// The object that acts as a delegate to the bar. internal weak var delegate: TabmanBarDelegate? /// The object that acts as a data source to the bar. public weak var dataSource: TabmanBarDataSource? { didSet { self.reloadData() } } /// Appearance configuration for the bar. public var appearance: Appearance = .defaultAppearance { didSet { self.updateCore(forAppearance: appearance) } } /// The height for the bar. Default: .auto public var height: Height = .auto { didSet { self.invalidateIntrinsicContentSize() self.superview?.setNeedsLayout() self.superview?.layoutIfNeeded() } } open override var intrinsicContentSize: CGSize { var autoSize = super.intrinsicContentSize switch self.height { case .explicit(let height): autoSize.height = height return autoSize default: return autoSize } } /// Background view of the bar. public private(set) var backgroundView: TabmanBarBackgroundView = TabmanBarBackgroundView(forAutoLayout: ()) /// The content view for the bar. public private(set) var contentView = UIView(forAutoLayout: ()) /// The bottom separator view for the bar. internal private(set) var bottomSeparator = TabmanSeparator() /// Indicator for the bar. public internal(set) var indicator: TabmanIndicator? { didSet { indicator?.delegate = self self.clear(indicator: oldValue) } } internal var indicatorLeftMargin: NSLayoutConstraint? internal var indicatorWidth: NSLayoutConstraint? internal var indicatorIsProgressive: Bool = TabmanBar.Appearance.defaultAppearance.indicator.isProgressive ?? false { didSet { guard indicatorIsProgressive != oldValue else { return } UIView.animate(withDuration: 0.3, animations: { self.updateForCurrentPosition() }) } } internal var indicatorBounces: Bool = TabmanBar.Appearance.defaultAppearance.indicator.bounces ?? false internal var indicatorCompresses: Bool = TabmanBar.Appearance.defaultAppearance.indicator.compresses ?? false internal var indicatorMaskView: UIView = { let maskView = UIView() maskView.backgroundColor = .black return maskView }() /// Preferred style for the indicator. /// Bar conforms at own discretion via usePreferredIndicatorStyle() public var preferredIndicatorStyle: TabmanIndicator.Style? { didSet { self.updateIndicator(forPreferredStyle: preferredIndicatorStyle) } } /// The limit that the bar has for the number of items it can display. public var itemCountLimit: Int? { get { return nil } } // // MARK: Init // required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initTabBar(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) initTabBar(coder: nil) } private func initTabBar(coder aDecoder: NSCoder?) { self.addSubview(backgroundView) backgroundView.autoPinEdgesToSuperviewEdges() self.addSubview(bottomSeparator) bottomSeparator.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .top) self.addSubview(contentView) contentView.autoPinEdgesToSuperviewEdges() self.indicator = self.create(indicatorForStyle: self.defaultIndicatorStyle()) } // // MARK: Lifecycle // open override func layoutSubviews() { super.layoutSubviews() // refresh intrinsic size for indicator self.indicator?.invalidateIntrinsicContentSize() } open override func addSubview(_ view: UIView) { if view !== self.backgroundView && view !== self.contentView && view !== self.bottomSeparator { fatalError("Please add subviews to the contentView rather than directly onto the TabmanBar") } super.addSubview(view) } /// The default indicator style for the bar. /// /// - Returns: The default indicator style. open func defaultIndicatorStyle() -> TabmanIndicator.Style { print("indicatorStyle() returning default. This should be overridden in subclass") return .clear } /// Whether the bar should use preferredIndicatorStyle if available /// /// - Returns: Whether to use preferredIndicatorStyle open func usePreferredIndicatorStyle() -> Bool { return true } /// The type of transition to use for the indicator (Internal use only). /// /// - Returns: The transition type. internal func indicatorTransitionType() -> TabmanIndicatorTransition.Type? { return nil } // // MARK: Data // /// Reload and reconstruct the contents of the bar. public func reloadData() { self.items = self.dataSource?.items(forBar: self) self.clearAndConstructBar() } // // MARK: Updating // internal func updatePosition(_ position: CGFloat, direction: PageboyViewController.NavigationDirection, bounds: CGRect? = nil) { guard let items = self.items else { return } let bounds = bounds ?? self.bounds self.layoutIfNeeded() self.currentPosition = position self.update(forPosition: position, direction: direction, indexRange: 0 ..< items.count - 1, bounds: bounds) } internal func updateForCurrentPosition(bounds: CGRect? = nil) { self.updatePosition(self.currentPosition, direction: .neutral, bounds: bounds) } // // MARK: TabmanBarLifecycle // open func constructTabBar(items: [TabmanBarItem]) { fatalError("constructTabBar() should be implemented in TabmanBar subclasses.") } open func addIndicatorToBar(indicator: TabmanIndicator) { fatalError("addIndicatorToBar() should be implemented in TabmanBar subclasses.") } open func update(forPosition position: CGFloat, direction: PageboyViewController.NavigationDirection, indexRange: Range<Int>, bounds: CGRect) { guard self.indicator != nil else { return } let indicatorTransition = self.transitionStore?.indicatorTransition(forBar: self) indicatorTransition?.transition(withPosition: position, direction: direction, indexRange: indexRange, bounds: bounds) let itemTransition = self.transitionStore?.itemTransition(forBar: self, indicator: self.indicator!) itemTransition?.transition(withPosition: position, direction: direction, indexRange: indexRange, bounds: bounds) } /// Appearance updates that are core to TabmanBar and must always be evaluated /// /// - Parameter appearance: The appearance config internal func updateCore(forAppearance appearance: Appearance) { let defaultAppearance = Appearance.defaultAppearance self.preferredIndicatorStyle = appearance.indicator.preferredStyle let backgroundStyle = appearance.style.background ?? defaultAppearance.style.background! self.backgroundView.backgroundStyle = backgroundStyle self.height = appearance.layout.height ?? .auto let bottomSeparatorColor = appearance.style.bottomSeparatorColor ?? defaultAppearance.style.bottomSeparatorColor! self.bottomSeparator.color = bottomSeparatorColor self.update(forAppearance: appearance, defaultAppearance: defaultAppearance) } open func update(forAppearance appearance: Appearance, defaultAppearance: Appearance) { let indicatorIsProgressive = appearance.indicator.isProgressive ?? defaultAppearance.indicator.isProgressive! self.indicatorIsProgressive = indicatorIsProgressive ? self.indicator?.isProgressiveCapable ?? false : false let indicatorBounces = appearance.indicator.bounces ?? defaultAppearance.indicator.bounces! self.indicatorBounces = indicatorBounces let indicatorCompresses = appearance.indicator.compresses ?? defaultAppearance.indicator.compresses! self.indicatorCompresses = indicatorBounces ? false : indicatorCompresses // only allow compression if bouncing disabled let indicatorColor = appearance.indicator.color self.indicator?.tintColor = indicatorColor ?? defaultAppearance.indicator.color! let indicatorWeight = appearance.indicator.lineWeight ?? defaultAppearance.indicator.lineWeight! if let lineIndicator = self.indicator as? TabmanLineIndicator { lineIndicator.weight = indicatorWeight } } } extension TabmanBar: TabmanIndicatorDelegate { func indicator(requiresLayoutInvalidation indicator: TabmanIndicator) { self.invalidateIntrinsicContentSize() self.setNeedsLayout() self.layoutIfNeeded() } } internal extension TabmanIndicator.Style { var rawType: TabmanIndicator.Type? { switch self { case .line: return TabmanLineIndicator.self case .dot: return TabmanDotIndicator.self case .chevron: return TabmanChevronIndicator.self case .custom(let type): return type case .clear: return TabmanClearIndicator.self } } }
0642b5998bd677d3bb80e2416558b63f
33.011594
128
0.623146
false
false
false
false
prolificinteractive/Bellerophon
refs/heads/master
Bellerophon/BellerophonTests/MockBPManager.swift
mit
1
// // MockBPManager.swift // Bellerophon // // Created by Shiyuan Jiang on 4/27/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // @testable import Bellerophon class MockBPManager: BellerophonManager { var displayKillSwitchIsCalled: Bool! var displayForceUpdateIsCalled: Bool! var startAutoCheckingIsCalled: Bool! var dismissKillSwitchIfNeededIsCalled: Bool! var displayForceUpdateFunctionIsCalled: Bool! var displayKillSwitchFunctionIsCalled: Bool! var updateDisplayIsCalled: Bool! override func displayWindow(for event: BellerophonEvent) { switch event { case .killSwitch: displayKillSwitchIsCalled = true displayForceUpdateIsCalled = false case .forceUpdate: displayForceUpdateIsCalled = true displayKillSwitchIsCalled = false } } override func updateDisplay(_ status: BellerophonObservable) { updateDisplayIsCalled = true super.updateDisplay(status) } override func displayForceUpdate() { displayForceUpdateFunctionIsCalled = true super.displayForceUpdate() } override func displayKillSwitch() { displayKillSwitchFunctionIsCalled = true super.displayKillSwitch() } override func startAutoChecking(_ status: BellerophonObservable) { startAutoCheckingIsCalled = true } override func dismissKillSwitchIfNeeded() { dismissKillSwitchIfNeededIsCalled = true super.dismissKillSwitchIfNeeded() } }
e1f4b5a3d45d9da33b669ef37fc1785a
26.910714
70
0.698017
false
false
false
false
antelope-app/Antelope
refs/heads/master
Antelope-ios/Antelope/TutorialStepZero.swift
gpl-2.0
1
// // TutorialStepZero.swift // AdShield // // Created by Jae Lee on 9/1/15. // Copyright © 2015 AdShield. All rights reserved. // import UIKit class TutorialStepZero: TutorialStep { @IBOutlet weak var logoImage: UIImageView! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var stepZeroHeader: UITextView! @IBOutlet weak var stepZeroSubheader: UITextView! @IBOutlet weak var stepZeroHeaderImage: UIImageView! @IBOutlet weak var secondSubHeader: UITextView! @IBOutlet weak var thirdSubHeader: UITextView! var overlaySoft: UIView = UIView() var overlayHard: UIView = UIView() @IBOutlet weak var barTwo: UIView! @IBOutlet weak var barOne: UIView! override func viewDidLoad() { super.viewDidLoad() stepZeroSubheader = self.paragraphStyle(stepZeroSubheader) stepZeroSubheader.userInteractionEnabled = false secondSubHeader.hidden = true secondSubHeader.text = "You'll use less data, see way fewer ads, have better battery life, and stop being tracked on the web." secondSubHeader = self.paragraphStyle(secondSubHeader) secondSubHeader.userInteractionEnabled = false thirdSubHeader.hidden = true thirdSubHeader.text = "Antelope receives none of your browsing data, and it's entirely open-source." thirdSubHeader = self.paragraphStyle(thirdSubHeader) thirdSubHeader.userInteractionEnabled = false self.constrainButton(nextButton) self.view.layoutSubviews() } override func viewDidAppear(animated: Bool) { } func initialize() { let translationDistance: CGFloat = 140.0 let headerFrame = self.stepZeroHeader.frame self.stepZeroSubheader.frame.origin.y = headerFrame.origin.y + headerFrame.size.height self.secondSubHeader.frame = stepZeroSubheader.frame self.secondSubHeader.frame.origin.x = self.view.frame.size.width self.secondSubHeader.hidden = false /*self.delay(7.0, closure: { UIView.animateWithDuration(0.5, animations: { let anchor = self.stepZeroSubheader.frame.origin.x self.stepZeroSubheader.frame.origin.x = 0 - self.stepZeroSubheader.frame.size.width self.secondSubHeader.frame.origin.x = anchor }) })*/ self.thirdSubHeader.frame = self.secondSubHeader.frame self.thirdSubHeader.frame.origin.x = self.view.frame.size.width self.thirdSubHeader.hidden = false /*self.delay(14.0, closure: { UIView.animateWithDuration(0.5, animations: { let anchor = self.secondSubHeader.frame.origin.x self.secondSubHeader.frame.origin.x = 0 - self.secondSubHeader.frame.size.width self.thirdSubHeader.frame.origin.x = anchor }) })*/ UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseInOut, animations: { // LOGO MOVING let currentPosY = self.logoImage.frame.origin.y self.logoImage.frame.origin.y = currentPosY - translationDistance //self.stepZeroHeaderImage.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, distanceFromToBeLogoToTop + inset) }, completion: {(Bool) in // LOGO MOVED UIView.animateWithDuration(0.7, animations: { self.stepZeroHeader.alpha = 1.0 }, completion: {(Bool) in }) // sub header, then bars self.delay(1.0) { UIView.animateWithDuration(0.7, animations: { self.nextButton.alpha = 0.5 self.stepZeroSubheader.alpha = 1.0 }) } }) } }
dd3b1b69347e4a7aff564c637c17e968
35.630631
139
0.599606
false
false
false
false
davedelong/DDMathParser
refs/heads/master
MathParser/Sources/MathParser/OperatorSet.swift
mit
1
// // OperatorSet.swift // DDMathParser // // Created by Dave DeLong on 8/7/15. // // import Foundation public final class OperatorSet { public static let `default` = OperatorSet() public enum Relation { case lessThan case equalTo case greaterThan } public init(interpretsPercentSignAsModulo: Bool = true) { var ops = Array<Operator>() var precedence = 1 // LogicalDisjunction ops.append(Operator(builtInOperator: .logicalOr, precedence: precedence)) precedence += 1 // LogicalConjunction ops.append(Operator(builtInOperator: .logicalAnd, precedence: precedence)) precedence += 1 // == and != have the same precedence // ComparisonPrecedence ops.append(Operator(builtInOperator: .logicalEqual, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalNotEqual, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalLessThan, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalGreaterThan, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalLessThanOrEqual, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalGreaterThanOrEqual, precedence: precedence)) precedence += 1 precedence += 1 // AdditionPrecedence precedence += 1 ops.append(Operator(builtInOperator: .add, precedence: precedence)) ops.append(Operator(builtInOperator: .minus, precedence: precedence)) ops.append(Operator(builtInOperator: .bitwiseOr, precedence: precedence)) ops.append(Operator(builtInOperator: .bitwiseXor, precedence: precedence)) precedence += 1 // MultiplicationPrecedence multiplyOperator = Operator(builtInOperator: .multiply, precedence: precedence) ops.append(multiplyOperator) ops.append(Operator(builtInOperator: .divide, precedence: precedence)) ops.append(Operator(builtInOperator: .bitwiseAnd, precedence: precedence)) precedence += 1 implicitMultiplyOperator = Operator(builtInOperator: .implicitMultiply, precedence: precedence) ops.append(implicitMultiplyOperator) precedence += 1 // NOTE: percent-as-modulo precedence goes here (after ImplicitMultiply) // BitwiseShiftPrecedence ops.append(Operator(builtInOperator: .leftShift, precedence: precedence)) ops.append(Operator(builtInOperator: .rightShift, precedence: precedence)) precedence += 1 // all right associative unary operators have the same precedence ops.append(Operator(builtInOperator: .bitwiseNot, precedence: precedence)) ops.append(Operator(builtInOperator: .unaryMinus, precedence: precedence)) ops.append(Operator(builtInOperator: .unaryPlus, precedence: precedence)) ops.append(Operator(builtInOperator: .squareRoot, precedence: precedence)) ops.append(Operator(builtInOperator: .cubeRoot, precedence: precedence)) ops.append(Operator(builtInOperator: .logicalNot, precedence: precedence)) precedence += 1 // all left associative unary operators have the same precedence ops.append(Operator(builtInOperator: .doubleFactorial, precedence: precedence)) ops.append(Operator(builtInOperator: .factorial, precedence: precedence)) // NOTE: percent-as-percent precedence goes here (same as Factorial) ops.append(Operator(builtInOperator: .degree, precedence: precedence)) precedence += 1 powerOperator = Operator(builtInOperator: .power, precedence: precedence) precedence += 1 ops.append(powerOperator) addFractionOperator = Operator(builtInOperator: .add, precedence: precedence) precedence += 1 ops.append(addFractionOperator) // these are defined as unary right/left associative for convenience ops.append(Operator(builtInOperator: .parenthesisOpen, precedence: precedence)) ops.append(Operator(builtInOperator: .parenthesisClose, precedence: precedence)) precedence += 1 ops.append(Operator(builtInOperator: .comma, precedence: precedence)) precedence += 1 self.operators = ops self.interpretsPercentSignAsModulo = interpretsPercentSignAsModulo self.knownTokens = Set(ops.flatMap { $0.tokens }) interpretPercentSignAsModulo(self.interpretsPercentSignAsModulo) } public var interpretsPercentSignAsModulo: Bool { didSet(oldValue) { if oldValue != interpretsPercentSignAsModulo { interpretPercentSignAsModulo(interpretsPercentSignAsModulo) } } } private func interpretPercentSignAsModulo(_ interpretAsModulo: Bool) { let percent = Operator(builtInOperator: .percent) let modulo = Operator(builtInOperator: .modulo) // remove the old one and add the new one if interpretAsModulo { removeOperator(percent) addOperator(modulo, relatedBy: .greaterThan, toOperator: Operator(builtInOperator: .implicitMultiply)) } else { removeOperator(modulo) addOperator(percent, relatedBy: .equalTo, toOperator: Operator(builtInOperator: .factorial)) } } private var _operatorTokenSet: OperatorTokenSet? = nil internal var operatorTokenSet: OperatorTokenSet { if _operatorTokenSet == nil { _operatorTokenSet = OperatorTokenSet(tokens: knownTokens) } guard let set = _operatorTokenSet else { fatalError("Missing operator token set") } return set } public private(set) var operators: Array<Operator> { didSet { operatorsDidChange() } } private func operatorsDidChange() { knownTokens = Set(operators.flatMap { $0.tokens }) _operatorTokenSet = nil } internal let addFractionOperator: Operator internal let multiplyOperator: Operator internal let implicitMultiplyOperator: Operator internal let powerOperator: Operator private var knownTokens: Set<String> private func removeOperator(_ op: Operator) { guard let index = operators.firstIndex(of: op) else { return } operators.remove(at: index) operatorsDidChange() } public func addTokens(_ tokens: Array<String>, forOperator op: Operator) { let allowed = tokens.map { $0.lowercased() }.filter { self.operatorForToken($0).isEmpty } guard let existing = existingOperator(op) else { return } existing.tokens.formUnion(allowed) operatorsDidChange() } public func addOperator(_ op: Operator, relatedBy: Relation, toOperator existingOp: Operator) { guard let existing = existingOperator(existingOp) else { return } guard let existingP = existing.precedence else { fatalError("Existing operator missing precedence \(existing)") } let newOperator = op newOperator.precedence = existing.precedence let sorter: (Operator) -> Bool switch relatedBy { case .equalTo: sorter = { _ in return false } case .lessThan: sorter = { other in guard let otherP = other.precedence else { fatalError("Operator missing precedence: \(other)") } return otherP >= existingP } case .greaterThan: sorter = { other in guard let otherP = other.precedence else { fatalError("Operator missing precedence: \(other)") } return otherP > existingP } } processOperator(newOperator, sorter: sorter) } private func existingOperator(_ op: Operator) -> Operator? { let matches = operators.filter { $0 == op } return matches.first } private func processOperator(_ op: Operator, sorter: (Operator) -> Bool) { if let existing = existingOperator(op) { existing.tokens.formUnion(op.tokens) operatorsDidChange() } else { let overlap = knownTokens.intersection(op.tokens) guard overlap.isEmpty == true else { NSLog("cannot add operator with conflicting tokens: \(overlap)") return } let newOperators = operators.map { orig -> Operator in let new = Operator(function: orig.function, arity: orig.arity, associativity: orig.associativity) new.tokens = orig.tokens var precedence = orig.precedence ?? 0 if sorter(orig) { precedence += 1 } new.precedence = precedence return new } operators = newOperators operators.append(op) operatorsDidChange() } } public func operatorForToken(_ token: String, arity: Operator.Arity? = nil, associativity: Operator.Associativity? = nil) -> Array<Operator> { return operators.filter { guard $0.tokens.contains(token) else { return false } if let arity = arity { if $0.arity != arity { return false } } if let associativity = associativity { if $0.associativity != associativity { return false } } return true } } }
8890c7464ac4b4f7018c7ef78549dd5e
38.388
146
0.624454
false
false
false
false
calebd/swift
refs/heads/master
test/SILGen/class_resilience.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_class // Accessing final property of resilient class from different resilience domain // through accessor // CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOthery010resilient_A022ResilientOutsideParentCF // CHECK: function_ref @_T015resilient_class22ResilientOutsideParentC13finalPropertySSfg public func finalPropertyOfOther(_ other: ResilientOutsideParent) { _ = other.finalProperty } public class MyResilientClass { public final var finalProperty: String = "MyResilientClass.finalProperty" } // Accessing final property of resilient class from my resilience domain // directly // CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyAA16MyResilientClassCF // CHECK: bb0([[ARG:%.*]] : $MyResilientClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: ref_element_addr [[BORROWED_ARG]] : $MyResilientClass, #MyResilientClass.finalProperty // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] public func finalPropertyOfMine(_ other: MyResilientClass) { _ = other.finalProperty }
be21be9e6af0c0a6acdbc578ff16d2a1
43.970588
181
0.768476
false
false
false
false
eonil/toolbox.swift
refs/heads/master
EonilToolbox/ObjectAddressID.swift
mit
1
// // ObjectAddressID.swift // EonilToolbox // // Created by Hoon H. on 2016/04/27. // Copyright © 2016 Eonil. All rights reserved. // /// An ID that is based on object address and unique in current process scope. /// /// - Note: /// Current implementation is kind of naive, consumes memory uselessly. /// public struct ObjectAddressID: Hashable, Comparable { fileprivate let dummy = Dummy() public init() {} public var hashValue: Int { get { return ObjectIdentifier(dummy).hashValue } } /// Same ID always returns same pointer value. /// Nothing is guaranteed about what actually is at pointed address. public func asObject() -> AnyObject { return dummy } } extension ObjectAddressID: CustomStringConvertible { public var description: String { get { return "(ObjectID: 0x" + String(format: "%X", UInt(bitPattern: ObjectIdentifier(dummy))) + ")" } } } extension ObjectAddressID: CustomDebugStringConvertible { public var debugDescription: String { get { return description } } } public func == (_ a: ObjectAddressID, _ b: ObjectAddressID) -> Bool { return a.dummy === b.dummy } public func < (_ a: ObjectAddressID, _ b: ObjectAddressID) -> Bool { return UInt(bitPattern: ObjectIdentifier(a.dummy)) < UInt(bitPattern: ObjectIdentifier(b.dummy)) } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private final class Dummy {}
3f3e11fb098d55009e62eee217598886
33.978723
128
0.568735
false
false
false
false
drmohundro/SWXMLHash
refs/heads/main
Source/FullXMLParser.swift
mit
1
// // FullXMLParser.swift // SWXMLHash // // Copyright (c) 2014 David Mohundro // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(Linux) import FoundationXML #endif /// The implementation of XMLParserDelegate and where the parsing actually happens. class FullXMLParser: NSObject, SimpleXmlParser, XMLParserDelegate { required init(_ options: XMLHashOptions) { root = XMLElement(name: rootElementName, options: options) self.options = options super.init() } let root: XMLElement var parentStack = Stack<XMLElement>() let options: XMLHashOptions var parsingError: ParsingError? func parse(_ data: Data) -> XMLIndexer { // clear any prior runs of parse... expected that this won't be necessary, // but you never know parentStack.removeAll() parentStack.push(root) let parser = XMLParser(data: data) parser.shouldProcessNamespaces = options.shouldProcessNamespaces parser.delegate = self _ = parser.parse() if options.detectParsingErrors, let err = parsingError { return XMLIndexer.parsingError(err) } else { return XMLIndexer(root) } } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { let currentNode = parentStack .top() .addElement(elementName, withAttributes: attributeDict, caseInsensitive: options.caseInsensitive) parentStack.push(currentNode) } func parser(_ parser: XMLParser, foundCharacters string: String) { let current = parentStack.top() current.addText(string) } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { parentStack.drop() } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { if let cdataText = String(data: CDATABlock, encoding: String.Encoding.utf8) { let current = parentStack.top() current.addText(cdataText) } } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { #if os(Linux) && !swift(>=4.1.50) if let err = parseError as? NSError { parsingError = ParsingError( line: err.userInfo["NSXMLParserErrorLineNumber"] as? Int ?? 0, column: err.userInfo["NSXMLParserErrorColumn"] as? Int ?? 0) } #else let err = parseError as NSError parsingError = ParsingError( line: err.userInfo["NSXMLParserErrorLineNumber"] as? Int ?? 0, column: err.userInfo["NSXMLParserErrorColumn"] as? Int ?? 0) #endif } }
2f7e4241b3a5b895bf56dbfefaa8a109
35.063063
113
0.65376
false
false
false
false
vmanot/swift-package-manager
refs/heads/master
Sources/Utility/StringMangling.swift
apache-2.0
1
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Extensions to `String` to provide various forms of identifier mangling. Many /// of them are programming-related. extension String { /// Returns a form of the string that is a valid bundle identifier public func mangledToBundleIdentifier() -> String { let mangledUnichars: [UInt16] = self.utf16.map({ switch $0 { case // A-Z 0x0041...0x005A, // a-z 0x0061...0x007A, // 0-9 0x0030...0x0039, // - 0x2D, // . 0x2E: return $0 default: return 0x2D } }) return String(utf16CodeUnits: mangledUnichars, count: mangledUnichars.count) } /// Returns a form of the string that is valid C99 Extended Identifier (by /// replacing any invalid characters in an unspecified but consistent way). /// The output string is guaranteed to be non-empty as long as the input /// string is non-empty. public func mangledToC99ExtendedIdentifier() -> String { // Map invalid C99-invalid Unicode scalars to a replacement character. let replacementUnichar: UnicodeScalar = "_" var mangledUnichars: [UnicodeScalar] = self.unicodeScalars.map({ switch $0.value { case // A-Z 0x0041...0x005A, // a-z 0x0061...0x007A, // 0-9 0x0030...0x0039, // _ 0x005F, // Latin (1) 0x00AA...0x00AA, // Special characters (1) 0x00B5...0x00B5, 0x00B7...0x00B7, // Latin (2) 0x00BA...0x00BA, 0x00C0...0x00D6, 0x00D8...0x00F6, 0x00F8...0x01F5, 0x01FA...0x0217, 0x0250...0x02A8, // Special characters (2) 0x02B0...0x02B8, 0x02BB...0x02BB, 0x02BD...0x02C1, 0x02D0...0x02D1, 0x02E0...0x02E4, 0x037A...0x037A, // Greek (1) 0x0386...0x0386, 0x0388...0x038A, 0x038C...0x038C, 0x038E...0x03A1, 0x03A3...0x03CE, 0x03D0...0x03D6, 0x03DA...0x03DA, 0x03DC...0x03DC, 0x03DE...0x03DE, 0x03E0...0x03E0, 0x03E2...0x03F3, // Cyrillic 0x0401...0x040C, 0x040E...0x044F, 0x0451...0x045C, 0x045E...0x0481, 0x0490...0x04C4, 0x04C7...0x04C8, 0x04CB...0x04CC, 0x04D0...0x04EB, 0x04EE...0x04F5, 0x04F8...0x04F9, // Armenian (1) 0x0531...0x0556, // Special characters (3) 0x0559...0x0559, // Armenian (2) 0x0561...0x0587, // Hebrew 0x05B0...0x05B9, 0x05BB...0x05BD, 0x05BF...0x05BF, 0x05C1...0x05C2, 0x05D0...0x05EA, 0x05F0...0x05F2, // Arabic (1) 0x0621...0x063A, 0x0640...0x0652, // Digits (1) 0x0660...0x0669, // Arabic (2) 0x0670...0x06B7, 0x06BA...0x06BE, 0x06C0...0x06CE, 0x06D0...0x06DC, 0x06E5...0x06E8, 0x06EA...0x06ED, // Digits (2) 0x06F0...0x06F9, // Devanagari and Special character 0x093D. 0x0901...0x0903, 0x0905...0x0939, 0x093D...0x094D, 0x0950...0x0952, 0x0958...0x0963, // Digits (3) 0x0966...0x096F, // Bengali (1) 0x0981...0x0983, 0x0985...0x098C, 0x098F...0x0990, 0x0993...0x09A8, 0x09AA...0x09B0, 0x09B2...0x09B2, 0x09B6...0x09B9, 0x09BE...0x09C4, 0x09C7...0x09C8, 0x09CB...0x09CD, 0x09DC...0x09DD, 0x09DF...0x09E3, // Digits (4) 0x09E6...0x09EF, // Bengali (2) 0x09F0...0x09F1, // Gurmukhi (1) 0x0A02...0x0A02, 0x0A05...0x0A0A, 0x0A0F...0x0A10, 0x0A13...0x0A28, 0x0A2A...0x0A30, 0x0A32...0x0A33, 0x0A35...0x0A36, 0x0A38...0x0A39, 0x0A3E...0x0A42, 0x0A47...0x0A48, 0x0A4B...0x0A4D, 0x0A59...0x0A5C, 0x0A5E...0x0A5E, // Digits (5) 0x0A66...0x0A6F, // Gurmukhi (2) 0x0A74...0x0A74, // Gujarti 0x0A81...0x0A83, 0x0A85...0x0A8B, 0x0A8D...0x0A8D, 0x0A8F...0x0A91, 0x0A93...0x0AA8, 0x0AAA...0x0AB0, 0x0AB2...0x0AB3, 0x0AB5...0x0AB9, 0x0ABD...0x0AC5, 0x0AC7...0x0AC9, 0x0ACB...0x0ACD, 0x0AD0...0x0AD0, 0x0AE0...0x0AE0, // Digits (6) 0x0AE6...0x0AEF, // Oriya and Special character 0x0B3D 0x0B01...0x0B03, 0x0B05...0x0B0C, 0x0B0F...0x0B10, 0x0B13...0x0B28, 0x0B2A...0x0B30, 0x0B32...0x0B33, 0x0B36...0x0B39, 0x0B3D...0x0B43, 0x0B47...0x0B48, 0x0B4B...0x0B4D, 0x0B5C...0x0B5D, 0x0B5F...0x0B61, // Digits (7) 0x0B66...0x0B6F, // Tamil 0x0B82...0x0B83, 0x0B85...0x0B8A, 0x0B8E...0x0B90, 0x0B92...0x0B95, 0x0B99...0x0B9A, 0x0B9C...0x0B9C, 0x0B9E...0x0B9F, 0x0BA3...0x0BA4, 0x0BA8...0x0BAA, 0x0BAE...0x0BB5, 0x0BB7...0x0BB9, 0x0BBE...0x0BC2, 0x0BC6...0x0BC8, 0x0BCA...0x0BCD, // Digits (8) 0x0BE7...0x0BEF, // Telugu 0x0C01...0x0C03, 0x0C05...0x0C0C, 0x0C0E...0x0C10, 0x0C12...0x0C28, 0x0C2A...0x0C33, 0x0C35...0x0C39, 0x0C3E...0x0C44, 0x0C46...0x0C48, 0x0C4A...0x0C4D, 0x0C60...0x0C61, // Digits (9) 0x0C66...0x0C6F, // Kannada 0x0C82...0x0C83, 0x0C85...0x0C8C, 0x0C8E...0x0C90, 0x0C92...0x0CA8, 0x0CAA...0x0CB3, 0x0CB5...0x0CB9, 0x0CBE...0x0CC4, 0x0CC6...0x0CC8, 0x0CCA...0x0CCD, 0x0CDE...0x0CDE, 0x0CE0...0x0CE1, // Digits (10) 0x0CE6...0x0CEF, // Malayam 0x0D02...0x0D03, 0x0D05...0x0D0C, 0x0D0E...0x0D10, 0x0D12...0x0D28, 0x0D2A...0x0D39, 0x0D3E...0x0D43, 0x0D46...0x0D48, 0x0D4A...0x0D4D, 0x0D60...0x0D61, // Digits (11) 0x0D66...0x0D6F, // Thai...including Digits 0x0E50...0x0E59 } 0x0E01...0x0E3A, 0x0E40...0x0E5B, // Lao (1) 0x0E81...0x0E82, 0x0E84...0x0E84, 0x0E87...0x0E88, 0x0E8A...0x0E8A, 0x0E8D...0x0E8D, 0x0E94...0x0E97, 0x0E99...0x0E9F, 0x0EA1...0x0EA3, 0x0EA5...0x0EA5, 0x0EA7...0x0EA7, 0x0EAA...0x0EAB, 0x0EAD...0x0EAE, 0x0EB0...0x0EB9, 0x0EBB...0x0EBD, 0x0EC0...0x0EC4, 0x0EC6...0x0EC6, 0x0EC8...0x0ECD, // Digits (12) 0x0ED0...0x0ED9, // Lao (2) 0x0EDC...0x0EDD, // Tibetan (1) 0x0F00...0x0F00, 0x0F18...0x0F19, // Digits (13) 0x0F20...0x0F33, // Tibetan (2) 0x0F35...0x0F35, 0x0F37...0x0F37, 0x0F39...0x0F39, 0x0F3E...0x0F47, 0x0F49...0x0F69, 0x0F71...0x0F84, 0x0F86...0x0F8B, 0x0F90...0x0F95, 0x0F97...0x0F97, 0x0F99...0x0FAD, 0x0FB1...0x0FB7, 0x0FB9...0x0FB9, // Georgian 0x10A0...0x10C5, 0x10D0...0x10F6, // Latin (3) 0x1E00...0x1E9B, 0x1EA0...0x1EF9, // Greek (2) 0x1F00...0x1F15, 0x1F18...0x1F1D, 0x1F20...0x1F45, 0x1F48...0x1F4D, 0x1F50...0x1F57, 0x1F59...0x1F59, 0x1F5B...0x1F5B, 0x1F5D...0x1F5D, 0x1F5F...0x1F7D, 0x1F80...0x1FB4, 0x1FB6...0x1FBC, // Special characters (4) 0x1FBE...0x1FBE, // Greek (3) 0x1FC2...0x1FC4, 0x1FC6...0x1FCC, 0x1FD0...0x1FD3, 0x1FD6...0x1FDB, 0x1FE0...0x1FEC, 0x1FF2...0x1FF4, 0x1FF6...0x1FFC, // Special characters (5) 0x203F...0x2040, // Latin (4) 0x207F...0x207F, // Special characters (6) 0x2102...0x2102, 0x2107...0x2107, 0x210A...0x2113, 0x2115...0x2115, 0x2118...0x211D, 0x2124...0x2124, 0x2126...0x2126, 0x2128...0x2128, 0x212A...0x2131, 0x2133...0x2138, 0x2160...0x2182, 0x3005...0x3007, 0x3021...0x3029, // Hiragana 0x3041...0x3093, 0x309B...0x309C, // Katakana 0x30A1...0x30F6, 0x30FB...0x30FC, // Bopmofo [sic] 0x3105...0x312C, // CJK Unified Ideographs 0x4E00...0x9FA5, // Hangul, 0xAC00...0xD7A3: return $0 default: return replacementUnichar } }) // Apply further restrictions to the prefix. loop: for (idx, c) in mangledUnichars.enumerated() { switch c.value { case // 0-9 0x0030...0x0039, // Annex D. 0x0660...0x0669, 0x06F0...0x06F9, 0x0966...0x096F, 0x09E6...0x09EF, 0x0A66...0x0A6F, 0x0AE6...0x0AEF, 0x0B66...0x0B6F, 0x0BE7...0x0BEF, 0x0C66...0x0C6F, 0x0CE6...0x0CEF, 0x0D66...0x0D6F, 0x0E50...0x0E59, 0x0ED0...0x0ED9, 0x0F20...0x0F33: mangledUnichars[idx] = replacementUnichar break loop default: break loop } } // Combine the characters as a string again and return it. // FIXME: We should only construct a new string if anything changed. // FIXME: There doesn't seem to be a way to create a string from an // array of Unicode scalars; but there must be a better way. return mangledUnichars.reduce("") { $0 + String($1) } } /// Mangles the contents to a valid C99 Extended Identifier. This method /// is the mutating version of `mangledToC99ExtendedIdentifier()`. public mutating func mangleToC99ExtendedIdentifier() { self = mangledToC99ExtendedIdentifier() } }
2d92d399ff5a4d9e8ca7103fd63e86f2
42.113281
84
0.48582
false
false
false
false
leizh007/HiPDA
refs/heads/master
HiPDA/HiPDA/Sections/Me/Settings/ForumList/ForumListViewController.swift
mit
1
// // ForumListViewController.swift // HiPDA // // Created by leizh007 on 2017/1/24. // Copyright © 2017年 HiPDA. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources /// 选择版块列表后的回调block typealias ForumListChoosenCompletionHandler = ([String]) -> Void /// 所有版块列表 class ForumListViewController: BaseViewController { /// 已选择的版块列表 var activeForumList = [String]() /// 选择完后的回调 var completion: ForumListChoosenCompletionHandler? /// tableView @IBOutlet fileprivate weak var tableView: BaseTableView! /// VC将要消失 fileprivate let willDismiss = PublishSubject<Void>() override func viewDidLoad() { super.viewDidLoad() configureTableView() } override func configureApperance(of navigationBar: UINavigationBar) { super.configureApperance(of: navigationBar) let cancel = UIBarButtonItem(title: "取消", style: .plain, target: nil, action: nil) cancel.rx.tap.subscribe(onNext: { [unowned self] _ in self.presentingViewController?.dismiss(animated: true, completion: nil) }).addDisposableTo(disposeBag) navigationItem.leftBarButtonItem = cancel let confirm = UIBarButtonItem(title: "确定", style: .plain, target: nil, action: nil) confirm.rx.tap.subscribe(onNext: { [unowned self] _ in self.presentingViewController?.dismiss(animated: true) { _ in self.willDismiss.onNext(()) } }).addDisposableTo(disposeBag) navigationItem.rightBarButtonItem = confirm } } // MARK: - StoryboardLoadable extension ForumListViewController: StoryboardLoadable { } // MARK: - Configurations extension ForumListViewController { /// 设置tabelView fileprivate func configureTableView() { tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height:CGFloat.leastNormalMagnitude)) tableView.rx.itemSelected.subscribe(onNext: { [unowned self] indexPath in self.tableView.deselectRow(at: indexPath, animated: true) }).addDisposableTo(disposeBag) let dataSource = RxTableViewSectionedReloadDataSource<ForumNameSection>() skinTableViewDataSource(dataSource) let viewModel = ForumListViewModel(activeForumList: activeForumList, selection: tableView.rx.itemSelected.asDriver()) viewModel.sections.drive(tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) willDismiss.withLatestFrom(viewModel.selectedForumList) .subscribe(onNext: { [unowned self] forumList in self.completion?(forumList) }).addDisposableTo(disposeBag) } /// 设置tableView的数据源 /// /// - Parameter dataSource: 数据源 fileprivate func skinTableViewDataSource(_ dataSource: RxTableViewSectionedReloadDataSource<ForumNameSection>) { dataSource.configureCell = { [unowned self] (_, tableView, indexPath, item) in let cell: ForumNameTableViewCell switch item.level { case .first: cell = (tableView.dequeueReusableCell(for: indexPath) as ForumNameTableViewCell) case .secondary: cell = (tableView.dequeueReusableCell(for: indexPath) as ForumNameSecondaryTableViewCell) case .secondaryLast: cell = (tableView.dequeueReusableCell(for: indexPath) as ForumNameSecondaryLastTableViewCell) } cell.forumName = item.forumName cell.accessoryType = item.isChoosed ? .checkmark : .none cell.detailDisclosureButton.isHidden = item.forumDescription == nil cell.detailDisclosureButton.rx.tap.asObservable() .subscribe(onNext: { _ in let alert = UIAlertController(title: "版块介绍", message: item.forumDescription, preferredStyle: .alert) let confirmAction = UIAlertAction(title: "确定", style: .default, handler: nil) alert.addAction(confirmAction) self.present(alert, animated: true, completion: nil) }).addDisposableTo(cell.disposeBagCell) return cell } } }
8a8450f9242fdb128125ea9d542d95be
37.54955
125
0.656228
false
true
false
false
Gilbertat/SYKanZhiHu
refs/heads/master
SYKanZhihu/SYKanZhihu/Class/Home/Model/SYHomeModel.swift
mit
1
// // SYHomeModel.swift // SYKanZhihu // // Created by shiyue on 16/2/17. // Copyright © 2016年 shiyue. All rights reserved. // import Foundation class HomeModel { //文章编号 var id:String? //发表日期 var date:String? //文章名称 var name:String? //抬头图 var pic:String? //发表时间戳 var publishtime:String? //文章包含答案数量 var count:String? //摘要文字 var excerpt:String? //收集状态转中文 var categoryName:Dictionary<String,String>? convenience init(dict:NSDictionary) { self.init() self.id = dict["id"] as? String self.date = dict["date"] as? String self.name = dict["name"] as? String self.pic = dict["pic"] as? String self.publishtime = dict["publishtime"] as? String self.count = dict["count"] as? String self.excerpt = dict["excerpt"] as? String self.categoryName = ["recent":"近日热门", "yesterday":"昨日最新", "archive":"历史精华"] } }
47e8dcd0bde6e188b10eb6af40ae6cf2
21.777778
57
0.549805
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
refs/heads/develop
Pods/FeedKit/Sources/FeedKit/Models/JSON/JSONFeedAuthor.swift
mit
2
// // JSONFeedAuthor.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 /// (optional, object) specifies the feed author. The author object has several /// members. These are all optional - but if you provide an author object, then at /// least one is required: public struct JSONFeedAuthor { /// (optional, string) is the author's name. public var name: String? /// (optional, string) is the URL of a site owned by the author. It could be a /// blog, micro-blog, Twitter account, and so on. Ideally the linked-to page /// provides a way to contact the author, but that's not required. The URL /// could be a mailto: link, though we suspect that will be rare. public var url: String? /// (optional, string) is the URL for an image for the author. As with icon, /// it should be square and relatively large - such as 512 x 512 - and should /// use transparency where appropriate, since it may be rendered on a non-white /// background. public var avatar: String? } // MARK: - Equatable extension JSONFeedAuthor: Equatable {} // MARK: - Codable extension JSONFeedAuthor: Codable { enum CodingKeys: String, CodingKey { case name case url case avatar } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(url, forKey: .url) try container.encode(avatar, forKey: .avatar) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) url = try values.decodeIfPresent(String.self, forKey: .url) avatar = try values.decodeIfPresent(String.self, forKey: .avatar) } }
6be4a662d5ffe4560b53e7ac1b21d47f
38
84
0.694972
false
false
false
false
blkbrds/intern09_final_project_tung_bien
refs/heads/master
MyApp/View/Controllers/Recent/RecentViewController.swift
mit
1
// // RecentViewController.swift // MyApp // // Created by AST on 7/19/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import UIKit import SwiftUtils import SVProgressHUD class RecentViewController: ViewController { // MARK: - Properties @IBOutlet weak var tableView: UITableView! private var refreshControl = UIRefreshControl() var viewModel = RecentViewModel() fileprivate var isLoadmore = false // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupUI() setupData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // MARK: - Private private func setupUI() { navigationItem.title = App.String.RecentViewControllerTitle tableView.register(RecentTableViewCell.self) tableView.register(LoadingTableViewCell.self) tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 70 tableView.rowHeight = UITableViewAutomaticDimension refreshControl.attributedTitle = NSAttributedString(string: App.String.RefreshString, attributes: [NSForegroundColorAttributeName: UIColor.gray]) refreshControl.addTarget(self, action: #selector(refreshData), for: UIControlEvents.valueChanged) refreshControl.backgroundColor = App.Color.grayBackground refreshControl.tintColor = .gray tableView.addSubview(refreshControl) SVProgressHUD.show() } @objc private func refreshData(sender: AnyObject) { view.isUserInteractionEnabled = false setupData() } private func setupData() { viewModel.fetchData { [weak self] (result) in guard let this = self else { return } if this.refreshControl.isRefreshing { this.refreshControl.endRefreshing() this.view.isUserInteractionEnabled = true } switch result { case .success: this.tableView.reloadData() case .failure(let error): this.alert(error: error) } SVProgressHUD.dismiss() } } fileprivate func loadMore() { isLoadmore = !isLoadmore if viewModel.recents?.nextPage != 0 { viewModel.loadMoreRecent { [weak self] (result) in guard let this = self else { return } switch result { case .success: this.tableView.reloadData() case .failure(let error): this.alert(error: error) } this.isLoadmore = !this.isLoadmore } } } } // MARK: - UITableViewDataSource extension RecentViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfItems(inSection: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let lastElement = viewModel.numberOfItems(inSection: indexPath.section) - 1 if viewModel.recents?.currentPage == viewModel.recents?.totalPage { let cell = tableView.dequeue(RecentTableViewCell.self) cell.viewModel = viewModel.viewModelForItem(at: indexPath) return cell } else { if (indexPath.row == lastElement) && !isLoadmore { let cell = tableView.dequeue(LoadingTableViewCell.self) cell.indicator.startAnimating() loadMore() return cell } else { let cell = tableView.dequeue(RecentTableViewCell.self) cell.viewModel = viewModel.viewModelForItem(at: indexPath) return cell } } } } // MARK: - UITableViewDelegate extension RecentViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) as? RecentTableViewCell, let viewModel = cell.viewModel else { return } let billVC = BillViewController() billVC.order = viewModel.order navigationController?.pushViewController(billVC, animated: true) } }
0de80a9335c4bcec48e10f518086023d
33.315385
153
0.631473
false
false
false
false
notbakaneko/JsonType
refs/heads/master
JsonType/JsonType.swift
mit
1
// // JsonType.swift // JsonType // // Created by bakaneko on 6/02/2015. // Copyright (c) 2015 bakaneko. All rights reserved. // import Foundation public enum JsonType { case DictionaryType(NSDictionary) case ArrayType(NSArray) case StringType(String) case NumberType(NSNumber) case BoolType(Bool) case NullType case InvalidType([String:AnyObject]) public init(_ rawValue: AnyObject) { switch rawValue { case let raw as NSNull: self = .NullType case let raw as NSString: self = .StringType(raw as! String) case let raw as String: self = .StringType(raw) case let raw as NSNumber: self = .NumberType(raw) case let raw as NSArray: self = .ArrayType(raw) case let raw as Bool: self = .BoolType(raw) case let raw as NSDictionary: self = .DictionaryType(raw) default: self = .InvalidType([:]) } } // MARK:- value overloads public func value() -> String? { switch self { case .StringType(let value): return value default: return nil } } public func value() -> NSURL? { switch self { case .StringType(let value): return NSURL(string: value) default: return nil } } public func value() -> Int? { switch self { case .NumberType(let value): return Int(value) case .StringType(let value): return value.toInt() case .BoolType(let value): return Int(value) default: return nil } } public func value() -> UInt? { switch self { case .NumberType(let value): return UInt(value) case .StringType(let value): if let int = value.toInt() { return UInt(int) } else { return nil } case .BoolType(let value): return UInt(value) default: return nil } } public func value() -> Bool? { switch self { case .BoolType(let value): return value case .NumberType(let value): return Bool(value) default: return nil } } public func value() -> Double? { switch self { case .NumberType(let value): return Double(value) case .StringType(let value): return ((value as NSString).doubleValue) // use strtod? default: return nil } } public func value() -> NSDictionary? { switch self { case .DictionaryType(let value): return value default: return nil } } public func value() -> NSArray? { switch self { case .ArrayType(let value): return value default: return nil } } // MARK:- non-operator format public static func jsonType(json: [String: AnyObject], _ key: String) -> JsonType? { let type = json[key].map { JsonType($0) } return type } } // MARK:- operators infix operator <- { associativity right precedence 90 } public func <-(inout left: Int, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Int?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: UInt, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: UInt?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Double, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Double?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: String, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: String?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Bool, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Bool?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSDictionary, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSDictionary?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSArray, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSArray?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } // MARK:- operators for direct assignment prefix operator <-? {} public prefix func <-?(right: AnyObject?) -> Int? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> UInt? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> Double? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> String? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> Bool? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> NSDictionary? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> NSArray? { let type = right.map { JsonType($0) } return type?.value() }
741b245a58f245338be0bcf028d8de50
23.916318
94
0.572628
false
false
false
false
emericspiroux/Open42
refs/heads/develop
Example/Pods/p2.OAuth2/Sources/Base/OAuth2Error.swift
apache-2.0
3
// // OAuth2Error.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** All errors that might occur. The response errors return a description as defined in the spec: http://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ public enum OAuth2Error: ErrorType, CustomStringConvertible, Equatable { /// An error for which we don't have a specific one. case Generic(String) /// An error holding on to an NSError. case NSError(Foundation.NSError) /// Invalid URL components, failed to create a URL case InvalidURLComponents(NSURLComponents) // MARK: - Client errors /// There is no client id. case NoClientId /// There is no client secret. case NoClientSecret /// There is no redirect URL. case NoRedirectURL /// There is no username. case NoUsername /// There is no password. case NoPassword /// There is no authorization context. case NoAuthorizationContext /// The authorization context is invalid. case InvalidAuthorizationContext /// The redirect URL is invalid; with explanation. case InvalidRedirectURL(String) /// There is no refresh token. case NoRefreshToken /// There is no registration URL. case NoRegistrationURL // MARK: - Request errors /// The request is not using SSL/TLS. case NotUsingTLS /// Unable to open the authorize URL. case UnableToOpenAuthorizeURL /// The request is invalid. case InvalidRequest /// The request was cancelled. case RequestCancelled // MARK: - Response Errors /// There was no token type in the response. case NoTokenType /// The token type is not supported. case UnsupportedTokenType(String) /// There was no data in the response. case NoDataInResponse /// Some prerequisite failed; with explanation. case PrerequisiteFailed(String) /// The state parameter was invalid. case InvalidState /// The JSON response could not be parsed. case JSONParserError /// Unable to UTF-8 encode. case UTF8EncodeError /// Unable to decode to UTF-8. case UTF8DecodeError // MARK: - OAuth2 errors /// The client is unauthorized. case UnauthorizedClient /// Access was denied. case AccessDenied /// Response type is not supported. case UnsupportedResponseType /// Scope was invalid. case InvalidScope /// A 500 was thrown. case ServerError /// The service is temporarily unavailable. case TemporarilyUnavailable /// Other response error, as defined in its String. case ResponseError(String) /** Instantiate the error corresponding to the OAuth2 response code, if it is known. - parameter code: The code, like "access_denied", that should be interpreted - parameter fallback: The error string to use in case the error code is not known - returns: An appropriate OAuth2Error */ public static func fromResponseError(code: String, fallback: String? = nil) -> OAuth2Error { switch code { case "invalid_request": return .InvalidRequest case "unauthorized_client": return .UnauthorizedClient case "access_denied": return .AccessDenied case "unsupported_response_type": return .UnsupportedResponseType case "invalid_scope": return .InvalidScope case "server_error": return .ServerError case "temporarily_unavailable": return .TemporarilyUnavailable default: return .ResponseError(fallback ?? "Authorization error: \(code)") } } /// Human understandable error string. public var description: String { switch self { case .Generic(let message): return message case .NSError(let error): return error.localizedDescription case .InvalidURLComponents(let components): return "Failed to create URL from components: \(components)" case NoClientId: return "Client id not set" case NoClientSecret: return "Client secret not set" case NoRedirectURL: return "Redirect URL not set" case NoUsername: return "No username" case NoPassword: return "No password" case NoAuthorizationContext: return "No authorization context present" case InvalidAuthorizationContext: return "Invalid authorization context" case InvalidRedirectURL(let url): return "Invalid redirect URL: \(url)" case .NoRefreshToken: return "I don't have a refresh token, not trying to refresh" case .NoRegistrationURL: return "No registration URL defined" case .NotUsingTLS: return "You MUST use HTTPS/SSL/TLS" case .UnableToOpenAuthorizeURL: return "Cannot open authorize URL" case .InvalidRequest: return "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed." case .RequestCancelled: return "The request has been cancelled" case NoTokenType: return "No token type received, will not use the token" case UnsupportedTokenType(let message): return message case NoDataInResponse: return "No data in the response" case PrerequisiteFailed(let message): return message case InvalidState: return "The state was either empty or did not check out" case JSONParserError: return "Error parsing JSON" case UTF8EncodeError: return "Failed to UTF-8 encode the given string" case UTF8DecodeError: return "Failed to decode given data as a UTF-8 string" case .UnauthorizedClient: return "The client is not authorized to request an access token using this method." case .AccessDenied: return "The resource owner or authorization server denied the request." case .UnsupportedResponseType: return "The authorization server does not support obtaining an access token using this method." case .InvalidScope: return "The requested scope is invalid, unknown, or malformed." case .ServerError: return "The authorization server encountered an unexpected condition that prevented it from fulfilling the request." case .TemporarilyUnavailable: return "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server." case .ResponseError(let message): return message } } } public func ==(lhs: OAuth2Error, rhs: OAuth2Error) -> Bool { switch (lhs, rhs) { case (.Generic(let lhm), .Generic(let rhm)): return lhm == rhm case (.NSError(let lhe), .NSError(let rhe)): return lhe.isEqual(rhe) case (.InvalidURLComponents(let lhe), .InvalidURLComponents(let rhe)): return lhe.isEqual(rhe) case (.NoClientId, .NoClientId): return true case (.NoClientSecret, .NoClientSecret): return true case (.NoRedirectURL, .NoRedirectURL): return true case (.NoUsername, .NoUsername): return true case (.NoPassword, .NoPassword): return true case (.NoAuthorizationContext, .NoAuthorizationContext): return true case (.InvalidAuthorizationContext, .InvalidAuthorizationContext): return true case (.InvalidRedirectURL(let lhu), .InvalidRedirectURL(let rhu)): return lhu == rhu case (.NoRefreshToken, .NoRefreshToken): return true case (.NotUsingTLS, .NotUsingTLS): return true case (.UnableToOpenAuthorizeURL, .UnableToOpenAuthorizeURL): return true case (.InvalidRequest, .InvalidRequest): return true case (.RequestCancelled, .RequestCancelled): return true case (.NoTokenType, .NoTokenType): return true case (.UnsupportedTokenType(let lhm), .UnsupportedTokenType(let rhm)): return lhm == rhm case (.NoDataInResponse, .NoDataInResponse): return true case (.PrerequisiteFailed(let lhm), .PrerequisiteFailed(let rhm)): return lhm == rhm case (.InvalidState, .InvalidState): return true case (.JSONParserError, .JSONParserError): return true case (.UTF8EncodeError, .UTF8EncodeError): return true case (.UTF8DecodeError, .UTF8DecodeError): return true case (.UnauthorizedClient, .UnauthorizedClient): return true case (.AccessDenied, .AccessDenied): return true case (.UnsupportedResponseType, .UnsupportedResponseType): return true case (.InvalidScope, .InvalidScope): return true case (.ServerError, .ServerError): return true case (.TemporarilyUnavailable, .TemporarilyUnavailable): return true case (.ResponseError(let lhm), .ResponseError(let rhm)): return lhm == rhm default: return false } }
4c04497a16cf777d01ead8c3d47a8c53
31.742049
157
0.703
false
false
false
false
Samarkin/PixelEditor
refs/heads/master
PixelEditor/ViewController.swift
mit
1
import Cocoa class ViewController: NSViewController { @IBOutlet var colorSelectorView: ColorSelectorView! @IBOutlet var selectedColorView: SolidColorView! @IBOutlet var selectedAltColorView: SolidColorView! @IBOutlet var canvasView: CanvasView! override func viewDidLoad() { super.viewDidLoad() colorSelectorView.colorSelected = { [weak self] in self?.selectedColorView?.backgroundColor = $0 } colorSelectorView.altColorSelected = { [weak self] in self?.selectedAltColorView?.backgroundColor = $0 } canvasView.delegate = { [weak self] in let colorMap: [CanvasColor : NSColor?] = [ .Main : self?.selectedColorView?.backgroundColor, .Alternative : self?.selectedAltColorView?.backgroundColor ] // TODO: Is there a better way to unwrap a double optional? if let color = colorMap[$2], let c = color { self?.document?.setPixel(i: $0, j: $1, color: c) } } } var document: Document? { didSet { oldValue?.removeObserver(self, forKeyPath: "pixels") if let document = document { canvasView.loadImage(document.pixels) document.addObserver(self, forKeyPath: "pixels", options: NSKeyValueObservingOptions.New, context: nil) } } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let document = document where object as? Document == document { if keyPath == "pixels" { // TODO: better changes tracking, don't reload the whole image every single time it changes canvasView.loadImage(document.pixels) } } } func export(sender: AnyObject?) { guard let window = self.view.window else { return } let panel = NSSavePanel() panel.allowedFileTypes = ["png"] if let fileName = self.document?.displayName { panel.nameFieldStringValue = fileName } panel.canSelectHiddenExtension = true panel.beginSheetModalForWindow(window) { guard $0 == NSFileHandlingPanelOKButton, let url = panel.URL else { return } print("exporting to \(url)...") self.document?.export().writeToURL(url, atomically: true) } } deinit { document?.removeObserver(self, forKeyPath: "pixels") } }
90fb5e1906864ca722674351c5fe4ae3
34.621622
157
0.594461
false
false
false
false
augmify/Eureka
refs/heads/master
Example/Example/ViewController.swift
mit
3
// ViewController.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Eureka import CoreLocation //MARK: HomeViewController class HomeViewController : FormViewController { override func viewDidLoad() { super.viewDidLoad() ImageRow.defaultCellUpdate = { cell, row in cell.accessoryView?.layer.cornerRadius = 17 cell.accessoryView?.frame = CGRectMake(0, 0, 34, 34) } form +++= Section(footer: "These are 8 ButtonRow rows") { $0.header = HeaderFooterView<EurekaLogoView>(HeaderFooterProvider.Class) } <<< ButtonRow("Rows") { $0.title = $0.tag $0.presentationMode = .SegueName(segueName: "RowsExampleViewControllerSegue", completionCallback: nil) } <<< ButtonRow("Native iOS Event Form") { row in row.title = row.tag row.presentationMode = .SegueName(segueName: "NativeEventsFormNavigationControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Accesory View Navigation") { (row: ButtonRow) in row.title = row.tag row.presentationMode = .SegueName(segueName: "AccesoryViewControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Custom Cells") { (row: ButtonRow) -> () in row.title = row.tag row.presentationMode = .SegueName(segueName: "CustomCellsControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Customization of rows with text input") { (row: ButtonRow) -> Void in row.title = row.tag row.presentationMode = .SegueName(segueName: "FieldCustomizationControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Hidden rows") { (row: ButtonRow) -> Void in row.title = row.tag row.presentationMode = .SegueName(segueName: "HiddenRowsControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Disabled rows") { (row: ButtonRow) -> Void in row.title = row.tag row.presentationMode = .SegueName(segueName: "DisabledRowsControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } <<< ButtonRow("Formatters") { (row: ButtonRow) -> Void in row.title = row.tag row.presentationMode = .SegueName(segueName: "FormattersControllerSegue", completionCallback:{ vc in vc.dismissViewControllerAnimated(true, completion: nil) }) } } } //MARK: Emoji typealias Emoji = String let 👦🏼 = "👦🏼", 🍐 = "🍐", 💁🏻 = "💁🏻", 🐗 = "🐗", 🐼 = "🐼", 🐻 = "🐻", 🐖 = "🐖", 🐡 = "🐡" //Mark: RowsExampleViewController class RowsExampleViewController: FormViewController { override func viewDidLoad() { super.viewDidLoad() URLRow.defaultCellUpdate = { cell, row in cell.textField.textColor = .blueColor() } LabelRow.defaultCellUpdate = { cell, row in cell.detailTextLabel?.textColor = .orangeColor() } CheckRow.defaultCellSetup = { cell, row in cell.tintColor = .orangeColor() } DateRow.defaultRowInitializer = { row in row.minimumDate = NSDate() } form = Section() <<< LabelRow () { $0.title = "LabelRow" $0.value = "tap the row" } .onCellSelection { $0.cell.detailTextLabel?.text? += " 🇺🇾 " } <<< DateRow() { $0.value = NSDate(); $0.title = "DateRow" } <<< CheckRow() { $0.title = "CheckRow" $0.value = true } <<< SwitchRow() { $0.title = "SwitchRow" $0.value = true } +++ Section("SegmentedRow examples") <<< SegmentedRow<String>() { $0.options = ["One", "Two", "Three"] } <<< SegmentedRow<Emoji>(){ $0.title = "Who are you?" $0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻 ] $0.value = 🍐 } +++ Section("Selectors Rows Examples") <<< ActionSheetRow<String>() { $0.title = "ActionSheetRow" $0.selectorTitle = "Your favourite player?" $0.options = ["Diego Forlán", "Edinson Cavani", "Diego Lugano", "Luis Suarez"] $0.value = "Luis Suarez" } <<< AlertRow<Emoji>() { $0.title = "AlertRow" $0.selectorTitle = "Who is there?" $0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻] $0.value = 👦🏼 }.onChange { row in print(row.value) } .onPresent{ _, to in to.view.tintColor = .purpleColor() } <<< PushRow<Emoji>() { $0.title = "PushRow" $0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻] $0.value = 👦🏼 $0.selectorTitle = "Choose an Emoji!" } <<< LocationRow(){ $0.title = "LocationRow" $0.value = CLLocation(latitude: -34.91, longitude: -56.1646) } <<< ImageRow(){ $0.title = "ImageRow" } <<< MultipleSelectorRow<Emoji>() { $0.title = "MultipleSelectorRow" $0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻] $0.value = [👦🏼, 🍐, 🐗] $0.selectorTitle = "" } .onPresent { from, to in to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: from, action: "multipleSelectorDone:") } +++ Section("FieldRow examples") <<< TextRow() { $0.title = "TextRow" $0.placeholder = "Placeholder" } <<< DecimalRow() { $0.title = "DecimalRow" $0.value = 5 } <<< URLRow() { $0.title = "URLRow" $0.value = NSURL(string: "http://xmartlabs.com") } <<< PhoneRow() { $0.title = "PhoneRow (disabled)" $0.value = "+598 9898983510" $0.disabled = true } <<< NameRow() { $0.title = "NameRow" } <<< PasswordRow() { $0.title = "PasswordRow" $0.value = "password" } <<< IntRow() { $0.title = "IntRow" $0.value = 2015 } <<< EmailRow() { $0.title = "EmailRow" $0.value = "[email protected]" } <<< TwitterRow() { $0.title = "TwitterRow" $0.value = "@xmartlabs" } <<< AccountRow() { $0.title = "AccountRow" $0.placeholder = "Placeholder" } } func multipleSelectorDone(item:UIBarButtonItem) { navigationController?.popViewControllerAnimated(true) } } //MARK: Custom Cells Example class CustomCellsController : FormViewController { override func viewDidLoad() { super.viewDidLoad() form +++ Section() { var header = HeaderFooterView<EurekaLogoViewNib>(HeaderFooterProvider.NibFile(name: "EurekaSectionHeader", bundle: NSBundle.mainBundle())) header.onSetupView = { (view, section, form) -> () in view.imageView.alpha = 0; UIView.animateWithDuration(2.0, animations: { [weak view] in view?.imageView.alpha = 1 }) view.layer.transform = CATransform3DMakeScale(0.9, 0.9, 1) UIView.animateWithDuration(1.0, animations: { [weak view] in view?.layer.transform = CATransform3DIdentity }) } $0.header = header } +++ Section("WeekDay cell") <<< WeekDayRow(){ $0.value = [.Monday, .Wednesday, .Friday] } <<< FloatLabelRow() { $0.title = "Float Label Row, type something to see.." } } } //MARK: Field row customization Example class FieldRowCustomizationController : FormViewController { override func viewDidLoad() { super.viewDidLoad() form +++ Section(header: "Default field rows", footer: "Rows with title have a right-aligned text field.\nRows without title have a left-aligned text field.\nBut this can be changed...") <<< NameRow() { $0.title = "Your name:" $0.placeholder = "(right alignment)" } <<< NameRow() { $0.placeholder = "Name (left alignment)" } +++ Section("Customized Alignment") <<< NameRow() { $0.title = "Your name:" }.cellUpdate { cell, row in cell.textField.textAlignment = .Left cell.textField.placeholder = "(left alignment)" } <<< NameRow().cellUpdate { cell, row in cell.textField.textAlignment = .Right cell.textField.placeholder = "Name (right alignment)" } +++ Section(header: "Customized Text field width", footer: "Eureka allows us to set up a specific UITextField width using textFieldPercentage property. In the section above we have also right aligned the textLabels.") <<< NameRow() { $0.title = "Title" $0.textFieldPercentage = 0.6 $0.placeholder = "textFieldPercentage = 0.6" } .cellUpdate { $0.cell.textField.textAlignment = .Left $0.cell.textLabel?.textAlignment = .Right } <<< NameRow() { $0.title = "Another Title" $0.textFieldPercentage = 0.6 $0.placeholder = "textFieldPercentage = 0.6" } .cellUpdate { $0.cell.textField.textAlignment = .Left $0.cell.textLabel?.textAlignment = .Right } <<< NameRow() { $0.title = "One more" $0.textFieldPercentage = 0.7 $0.placeholder = "textFieldPercentage = 0.7" } .cellUpdate { $0.cell.textField.textAlignment = .Left $0.cell.textLabel?.textAlignment = .Right } +++ Section("TextAreaRow") <<< TextAreaRow() { $0.placeholder = "TextAreaRow" } } } //MARK: Navigation Accessory View Example class NavigationAccessoryController : FormViewController { override func viewDidLoad() { super.viewDidLoad() navigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow) form = Section(header: "Settings", footer: "These settings change how the navigation accessory view behaves") <<< SwitchRow("set_none") { $0.title = "Navigation accessory view" $0.value = self.navigationOptions?.contains(.Enabled) } <<< CheckRow("set_disabled") { $0.title = "Stop at disabled row" $0.value = self.navigationOptions?.contains(.StopDisabledRow) $0.hidden = "$set_none == false" // .Predicate(NSPredicate(format: "$set_none == false")) }.onChange { [weak self] row in if row.value ?? false { self?.navigationOptions = self?.navigationOptions?.union(.StopDisabledRow) } else{ self?.navigationOptions = self?.navigationOptions?.subtract(.StopDisabledRow) } } <<< CheckRow("set_skip") { $0.title = "Skip non first responder view" $0.value = self.navigationOptions?.contains(.SkipCanNotBecomeFirstResponderRow) $0.hidden = "$set_none == false" }.onChange { [weak self] row in if row.value ?? false { self?.navigationOptions = self?.navigationOptions?.union(.SkipCanNotBecomeFirstResponderRow) } else{ self?.navigationOptions = self?.navigationOptions?.subtract(.SkipCanNotBecomeFirstResponderRow) } } +++ NameRow() { $0.title = "Your name:" } <<< PasswordRow() { $0.title = "Your password:" } +++ Section() <<< SegmentedRow<Emoji>() { $0.title = "Favourite food:" $0.options = [🐗, 🐖, 🐡, 🍐] } <<< PhoneRow() { $0.title = "Your phone number" } <<< URLRow() { $0.title = "Disabled" $0.disabled = true } <<< TextRow() { $0.title = "Your father's name"} <<< TextRow(){ $0.title = "Your mother's name"} } } //MARK: Native Event Example class NativeEventNavigationController: UINavigationController, RowControllerType { var completionCallback : ((UIViewController) -> ())? } class NativeEventFormViewController : FormViewController { override func viewDidLoad() { super.viewDidLoad() initializeForm() self.navigationItem.leftBarButtonItem?.target = self self.navigationItem.leftBarButtonItem?.action = "cancelTapped:" } private func initializeForm() { form = TextRow("Title").cellSetup { cell, row in cell.textField.placeholder = row.tag } <<< TextRow("Location").cellSetup { $0.cell.textField.placeholder = $0.row.tag } +++ SwitchRow("All-day") { $0.title = $0.tag }.onChange { [weak self] row in let startDate: DateTimeRow! = self?.form.rowByTag("Starts") let endDate: DateTimeRow! = self?.form.rowByTag("Ends") if row.value ?? false { startDate.dateFormatter?.dateStyle = .MediumStyle startDate.dateFormatter?.timeStyle = .NoStyle endDate.dateFormatter?.dateStyle = .MediumStyle endDate.dateFormatter?.timeStyle = .NoStyle } else { startDate.dateFormatter?.dateStyle = .ShortStyle startDate.dateFormatter?.timeStyle = .ShortStyle endDate.dateFormatter?.dateStyle = .ShortStyle endDate.dateFormatter?.timeStyle = .ShortStyle } startDate.cellUpdate { cell, dateRow in if row.value ?? false { cell.datePicker.datePickerMode = .Date } else { cell.datePicker.datePickerMode = .DateAndTime } } endDate.cellUpdate { cell, dateRow in if row.value ?? false { cell.datePicker.datePickerMode = .Date dateRow.dateFormatter?.dateStyle = .MediumStyle dateRow.dateFormatter?.timeStyle = .NoStyle } else { cell.datePicker.datePickerMode = .DateAndTime dateRow.dateFormatter?.dateStyle = .ShortStyle dateRow.dateFormatter?.timeStyle = .ShortStyle } } startDate.updateCell() endDate.updateCell() } <<< DateTimeRow("Starts") { $0.title = $0.tag $0.value = NSDate().dateByAddingTimeInterval(60*60*24) } .onChange { [weak self] row in let endRow: DateTimeRow! = self?.form.rowByTag("Ends") if row.value?.compare(endRow.value!) == .OrderedDescending { endRow.value = NSDate(timeInterval: 60*60*24, sinceDate: row.value!) endRow.cell!.backgroundColor = .whiteColor() endRow.updateCell() } } <<< DateTimeRow("Ends"){ $0.title = $0.tag $0.value = NSDate().dateByAddingTimeInterval(60*60*25) } .onChange { [weak self] row in let startRow: DateTimeRow! = self?.form.rowByTag("Starts") if row.value?.compare(startRow.value!) == .OrderedAscending { row.cell!.backgroundColor = .redColor() } else{ row.cell!.backgroundColor = .whiteColor() } row.updateCell() } form +++= PushRow<RepeatInterval>("Repeat") { $0.title = $0.tag $0.options = RepeatInterval.allValues $0.value = .Never } form +++= PushRow<EventAlert>() { $0.title = "Alert" $0.options = EventAlert.allValues $0.value = .Never } .onChange { [weak self] row in if row.value == .Never { if let second : PushRow<EventAlert> = self?.form.rowByTag("Another Alert"), let secondIndexPath = second.indexPath() { row.section?.removeAtIndex(secondIndexPath.row) } } else{ guard let _ : PushRow<EventAlert> = self?.form.rowByTag("Another Alert") else { let second = PushRow<EventAlert>("Another Alert") { $0.title = $0.tag $0.value = .Never $0.options = EventAlert.allValues } row.section?.insert(second, atIndex: row.indexPath()!.row + 1) return } } } form +++= PushRow<EventState>("Show As") { $0.title = "Show As" $0.options = EventState.allValues } form +++= URLRow("URL") { $0.placeholder = "URL" } <<< TextAreaRow("notes") { $0.placeholder = "Notes" } } func cancelTapped(barButtonItem: UIBarButtonItem) { (navigationController as? NativeEventNavigationController)?.completionCallback?(self) } enum RepeatInterval : String, CustomStringConvertible { case Never = "Never" case Every_Day = "Every Day" case Every_Week = "Every Week" case Every_2_Weeks = "Every 2 Weeks" case Every_Month = "Every Month" case Every_Year = "Every Year" var description : String { return rawValue } static let allValues = [Never, Every_Day, Every_Week, Every_2_Weeks, Every_Month, Every_Year] } enum EventAlert : String, CustomStringConvertible { case Never = "None" case At_time_of_event = "At time of event" case Five_Minutes = "5 minutes before" case FifTeen_Minutes = "15 minutes before" case Half_Hour = "30 minutes before" case One_Hour = "1 hour before" case Two_Hour = "2 hours before" case One_Day = "1 day before" case Two_Days = "2 days before" var description : String { return rawValue } static let allValues = [Never, At_time_of_event, Five_Minutes, FifTeen_Minutes, Half_Hour, One_Hour, Two_Hour, One_Day, Two_Days] } enum EventState { case Busy case Free static let allValues = [Busy, Free] } } //MARK: HiddenRowsExample class HiddenRowsExample : FormViewController { override func viewDidLoad() { super.viewDidLoad() TextRow.defaultCellUpdate = { cell, row in cell.textLabel?.font = UIFont.italicSystemFontOfSize(12) } form = Section("What do you want to talk about:") <<< SegmentedRow<String>("segments"){ $0.options = ["Sport", "Music", "Films"] $0.value = "Films" } +++ Section(){ $0.tag = "sport_s" $0.hidden = "$segments != 'Sport'" // .Predicate(NSPredicate(format: "$segments != 'Sport'")) } <<< TextRow(){ $0.title = "Which is your favourite soccer player?" } <<< TextRow(){ $0.title = "Which is your favourite coach?" } <<< TextRow(){ $0.title = "Which is your favourite team?" } +++ Section(){ $0.tag = "music_s" $0.hidden = "$segments != 'Music'" } <<< TextRow(){ $0.title = "Which music style do you like most?" } <<< TextRow(){ $0.title = "Which is your favourite singer?" } <<< TextRow(){ $0.title = "How many CDs have you got?" } +++ Section(){ $0.tag = "films_s" $0.hidden = "$segments != 'Films'" } <<< TextRow(){ $0.title = "Which is your favourite actor?" } <<< TextRow(){ $0.title = "Which is your favourite film?" } +++ Section() <<< SwitchRow("Show Next Row"){ $0.title = $0.tag } <<< SwitchRow("Show Next Section"){ $0.title = $0.tag $0.hidden = .Function(["Show Next Row"], { form -> Bool in let row: RowOf<Bool>! = form.rowByTag("Show Next Row") return row.value ?? false == false }) } +++ Section(footer: "This section is shown only when 'Show Next Row' switch is enabled"){ $0.hidden = .Function(["Show Next Section"], { form -> Bool in let row: RowOf<Bool>! = form.rowByTag("Show Next Section") return row.value ?? false == false }) } <<< TextRow() { $0.placeholder = "Gonna dissapear soon!!" } } } //MARK: DisabledRowsExample class DisabledRowsExample : FormViewController { override func viewDidLoad() { super.viewDidLoad() form = Section() <<< SegmentedRow<String>("segments"){ $0.options = ["Enabled", "Disabled"] $0.value = "Disabled" } <<< TextRow(){ $0.title = "choose enabled, disable above..." $0.disabled = "$segments = 'Disabled'" } <<< SwitchRow("Disable Next Section?"){ $0.title = $0.tag $0.disabled = "$segments = 'Disabled'" } +++ Section() <<< TextRow() { $0.title = "Gonna be disabled soon.." $0.disabled = Condition.Function(["Disable Next Section?"], { (form) -> Bool in let row: SwitchRow! = form.rowByTag("Disable Next Section?") return row.value ?? false }) } +++ Section() <<< SegmentedRow<String>(){ $0.options = ["Always Disabled"] $0.disabled = true } } } //MARK: FormatterExample class FormatterExample : FormViewController { override func viewDidLoad() { super.viewDidLoad() form +++ Section("Number formatters") <<< DecimalRow(){ $0.useFormatterDuringInput = true $0.title = "Currency style" $0.value = 2015 let formatter = CurrencyFormatter() formatter.locale = NSLocale.currentLocale() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle $0.formatter = formatter } <<< DecimalRow(){ $0.title = "Scientific style" $0.value = 2015 let formatter = NSNumberFormatter() formatter.locale = NSLocale.currentLocale() formatter.numberStyle = NSNumberFormatterStyle.ScientificStyle $0.formatter = formatter } <<< IntRow(){ $0.title = "Spell out style" $0.value = 2015 let formatter = NSNumberFormatter() formatter.locale = NSLocale.currentLocale() formatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle $0.formatter = formatter } +++ Section("Date formatters") <<< DateRow(){ $0.title = "Short style" $0.value = NSDate() let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() formatter.dateStyle = NSDateFormatterStyle.ShortStyle $0.dateFormatter = formatter } <<< DateRow(){ $0.title = "Long style" $0.value = NSDate() let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() formatter.dateStyle = NSDateFormatterStyle.LongStyle $0.dateFormatter = formatter } +++ Section("Other formatters") <<< DecimalRow(){ $0.title = "Energy: Jules to calories" $0.value = 100.0 let formatter = NSEnergyFormatter() $0.formatter = formatter } <<< IntRow(){ $0.title = "Weight: Kg to lb" $0.value = 1000 $0.formatter = NSMassFormatter() } } class CurrencyFormatter : NSNumberFormatter, FormatterProtocol { override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool { guard obj != nil else { return false } var str : String str = string.stringByReplacingOccurrencesOfString("$", withString: "") str = str.stringByReplacingOccurrencesOfString(",", withString: "") guard let i = Float(str) else { return false } obj.memory = NSNumber(float: i) return true } func getNewPosition(forPosition position: UITextPosition, inTextField textField: UITextField, oldValue: String?, newValue: String?) -> UITextPosition { return textField.positionFromPosition(position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position } } } class EurekaLogoViewNib: UIView { @IBOutlet weak var imageView: UIImageView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class EurekaLogoView: UIView { override init(frame: CGRect) { super.init(frame: frame) let imageView = UIImageView(image: UIImage(named: "Eureka")) imageView.frame = CGRect(x: 0, y: 0, width: 320, height: 130) imageView.autoresizingMask = .FlexibleWidth self.frame = CGRect(x: 0, y: 0, width: 320, height: 130) imageView.contentMode = .ScaleAspectFit self.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
6a1a7bc8e40b04da01fee1ee62507400
38.059312
229
0.457588
false
false
false
false
lorentey/GlueKit
refs/heads/master
Tests/GlueKitTests/ValueMappingTests.swift
mit
1
// // SelectOperatorTests.swift // GlueKit // // Created by Károly Lőrentey on 2015-12-06. // Copyright © 2015–2017 Károly Lőrentey. // import XCTest import GlueKit private class Book { let title: Variable<String> let authors: SetVariable<String> let chapters: ArrayVariable<String> init(_ title: String, authors: Set<String> = [], chapters: [String] = []) { self.title = .init(title) self.authors = .init(authors) self.chapters = .init(chapters) } } class ValueMappingTests: XCTestCase { func test_value() { let book = Book("foo") let title = book.title.map { $0.uppercased() } XCTAssertEqual(title.value, "FOO") let mock = MockValueUpdateSink(title) mock.expecting(["begin", "FOO -> BAR", "end"]) { book.title.value = "bar" } XCTAssertEqual(title.value, "BAR") } func test_updatableValue() { let book = Book("foo") // This is a simple mapping that ignores that a book's title is itself observable. let title = book.title.map({ $0.uppercased() }, inverse: { $0.lowercased() }) XCTAssertEqual(title.value, "FOO") let mock = MockValueUpdateSink(title) mock.expecting(["begin", "FOO -> BAR", "end"]) { book.title.value = "bar" } XCTAssertEqual(title.value, "BAR") mock.expecting(["begin", "BAR -> BAZ", "end"]) { title.value = "BAZ" } XCTAssertEqual(title.value, "BAZ") XCTAssertEqual(book.title.value, "baz") } func test_sourceField() { let b1 = Book("foo") let v = Variable<Book>(b1) let titleChanges = v.map { $0.title.changes } var expected: [ValueChange<String>] = [] var actual: [ValueChange<String>] = [] let connection = titleChanges.subscribe { change in actual.append(change) } func expect(_ change: ValueChange<String>? = nil, file: StaticString = #file, line: UInt = #line, body: () -> ()) { if let change = change { expected.append(change) } body() if !expected.elementsEqual(actual, by: ==) { XCTFail("\(actual) is not equal to \(expected)", file: file, line: line) } expected = [] actual = [] } expect(ValueChange(from: "foo", to: "bar")) { b1.title.value = "bar" } let b2 = Book("fred") expect() { v.value = b2 } expect(ValueChange(from: "fred", to: "barney")) { b2.title.value = "barney" } connection.disconnect() } func test_valueField() { let book = Book("book") let v = Variable<Book>(book) let title = v.map{ $0.title.map { $0.uppercased() } } // The title is updatable; uppercasing it makes it observable only. XCTAssertEqual(title.value, "BOOK") let mock = MockValueUpdateSink(title) mock.expecting(["begin", "BOOK -> UPDATED", "end"]) { book.title.value = "updated" } XCTAssertEqual(title.value, "UPDATED") let book2 = Book("other") mock.expecting(["begin", "UPDATED -> OTHER", "end"]) { v.value = book2 } XCTAssertEqual(title.value, "OTHER") } func test_updatableField() { let book = Book("book") let v = Variable<Book>(book) let title = v.map{$0.title} XCTAssertEqual(title.value, "book") let mock = MockValueUpdateSink(title) mock.expecting(["begin", "book -> updated", "end"]) { title.value = "updated" } XCTAssertEqual(title.value, "updated") XCTAssertEqual(book.title.value, "updated") let book2 = Book("other") mock.expecting(["begin", "updated -> other", "end"]) { v.value = book2 } XCTAssertEqual(title.value, "other") } func test_arrayField() { let book = Book("book", chapters: ["a", "b", "c"]) let v = Variable<Book>(book) let chapters = v.map{ $0.chapters.map { $0.uppercased() } } // Uppercasing is there to remove updatability. XCTAssertEqual(chapters.isBuffered, false) XCTAssertEqual(chapters.count, 3) XCTAssertEqual(chapters.observableCount.value, 3) XCTAssertEqual(chapters.value, ["A", "B", "C"]) XCTAssertEqual(chapters[0], "A") XCTAssertEqual(chapters[1 ..< 3], ["B", "C"]) let mock = MockArrayObserver(chapters) mock.expecting(["begin", "3.insert(D, at: 3)", "end"]) { book.chapters.append("d") } XCTAssertEqual(chapters.value, ["A", "B", "C", "D"]) let book2 = Book("other", chapters: ["10", "11"]) mock.expecting(["begin", "4.replaceSlice([A, B, C, D], at: 0, with: [10, 11])", "end"]) { v.value = book2 } XCTAssertEqual(chapters.value, ["10", "11"]) } func test_updatableArrayField() { let book = Book("book", chapters: ["1", "2", "3"]) let v = Variable<Book>(book) let chapters = v.map{$0.chapters} XCTAssertEqual(chapters.isBuffered, true) XCTAssertEqual(chapters.count, 3) XCTAssertEqual(chapters.observableCount.value, 3) XCTAssertEqual(chapters.value, ["1", "2", "3"]) XCTAssertEqual(chapters[0], "1") XCTAssertEqual(chapters[1 ..< 3], ["2", "3"]) let mock = MockArrayObserver(chapters) mock.expecting(["begin", "3.insert(4, at: 3)", "end"]) { book.chapters.append("4") } XCTAssertEqual(chapters.value, ["1", "2", "3", "4"]) mock.expecting(["begin", "4.remove(3, at: 2)", "end"]) { _ = chapters.remove(at: 2) } XCTAssertEqual(chapters.value, ["1", "2", "4"]) XCTAssertEqual(book.chapters.value, ["1", "2", "4"]) let book2 = Book("other", chapters: ["10", "11"]) mock.expecting(["begin", "3.replaceSlice([1, 2, 4], at: 0, with: [10, 11])", "end"]) { v.value = book2 } XCTAssertEqual(chapters.value, ["10", "11"]) mock.expecting(["begin", "2.replace(10, at: 0, with: 20)", "end"]) { chapters[0] = "20" } XCTAssertEqual(chapters.value, ["20", "11"]) XCTAssertEqual(book2.chapters.value, ["20", "11"]) mock.expecting(["begin", "2.insert(25, at: 1)", "end"]) { chapters.insert("25", at: 1) } XCTAssertEqual(chapters.value, ["20", "25", "11"]) XCTAssertEqual(book2.chapters.value, ["20", "25", "11"]) mock.expecting(["begin", "3.replaceSlice([25, 11], at: 1, with: [21, 22])", "end"]) { chapters[1 ..< 3] = ["21", "22"] } XCTAssertEqual(chapters.value, ["20", "21", "22"]) XCTAssertEqual(book2.chapters.value, ["20", "21", "22"]) mock.expecting(["begin", "3.replaceSlice([20, 21, 22], at: 0, with: [foo, bar])", "end"]) { chapters.value = ["foo", "bar"] } XCTAssertEqual(chapters.value, ["foo", "bar"]) XCTAssertEqual(book2.chapters.value, ["foo", "bar"]) } func test_setField() { let book = Book("book", authors: ["a", "b", "c"]) let v = Variable<Book>(book) let authors = v.map { $0.authors.map { $0.uppercased() } } // Uppercased to lose updatability. XCTAssertEqual(authors.isBuffered, false) XCTAssertEqual(authors.count, 3) XCTAssertEqual(authors.observableCount.value, 3) XCTAssertEqual(authors.value, ["A", "B", "C"]) XCTAssertEqual(authors.contains("A"), true) XCTAssertEqual(authors.contains("0"), false) XCTAssertEqual(authors.isSubset(of: ["A", "B", "C"]), true) XCTAssertEqual(authors.isSubset(of: ["A", "B", "C", "D"]), true) XCTAssertEqual(authors.isSubset(of: ["B", "C", "D"]), false) XCTAssertEqual(authors.isSuperset(of: ["A", "B", "C"]), true) XCTAssertEqual(authors.isSuperset(of: ["B", "C"]), true) XCTAssertEqual(authors.isSuperset(of: ["C", "D"]), false) let mock = MockSetObserver(authors) mock.expecting(["begin", "[]/[D]", "end"]) { book.authors.insert("d") } XCTAssertEqual(authors.value, ["A", "B", "C", "D"]) mock.expecting(["begin", "[B]/[]", "end"]) { book.authors.remove("b") } XCTAssertEqual(authors.value, ["A", "C", "D"]) mock.expecting(["begin", "[A, C, D]/[BARNEY, FRED]", "end"]) { v.value = Book("other", authors: ["fred", "barney"]) } XCTAssertEqual(authors.value, ["FRED", "BARNEY"]) } func test_updatableSetField() { let book = Book("book", authors: ["a", "b", "c"]) let v = Variable<Book>(book) let authors = v.map{$0.authors} XCTAssertEqual(authors.isBuffered, true) XCTAssertEqual(authors.count, 3) XCTAssertEqual(authors.observableCount.value, 3) XCTAssertEqual(authors.value, ["a", "b", "c"]) XCTAssertEqual(authors.contains("a"), true) XCTAssertEqual(authors.contains("0"), false) XCTAssertEqual(authors.isSubset(of: ["a", "b", "c"]), true) XCTAssertEqual(authors.isSubset(of: ["a", "b", "c", "d"]), true) XCTAssertEqual(authors.isSubset(of: ["b", "c", "d"]), false) XCTAssertEqual(authors.isSuperset(of: ["a", "b", "c"]), true) XCTAssertEqual(authors.isSuperset(of: ["b", "c"]), true) XCTAssertEqual(authors.isSuperset(of: ["c", "d"]), false) let mock = MockSetObserver(authors) mock.expecting(["begin", "[]/[d]", "end"]) { book.authors.insert("d") } XCTAssertEqual(authors.value, ["a", "b", "c", "d"]) mock.expecting(["begin", "[b]/[]", "end"]) { book.authors.remove("b") } XCTAssertEqual(authors.value, ["a", "c", "d"]) mock.expecting(["begin", "[]/[e]", "end"]) { authors.insert("e") } XCTAssertEqual(authors.value, ["a", "c", "d", "e"]) XCTAssertEqual(book.authors.value, ["a", "c", "d", "e"]) mock.expecting(["begin", "[c]/[]", "end"]) { authors.remove("c") } XCTAssertEqual(authors.value, ["a", "d", "e"]) XCTAssertEqual(book.authors.value, ["a", "d", "e"]) mock.expecting(["begin", "[]/[b, c]", "end"]) { authors.apply(SetChange(removed: [], inserted: ["b", "c"])) } XCTAssertEqual(authors.value, ["a", "b", "c", "d", "e"]) XCTAssertEqual(book.authors.value, ["a", "b", "c", "d", "e"]) mock.expecting(["begin", "[a, b, c, d, e]/[bar, foo]", "end"]) { authors.value = ["foo", "bar"] } XCTAssertEqual(authors.value, ["foo", "bar"]) XCTAssertEqual(book.authors.value, ["foo", "bar"]) mock.expecting(["begin", "[bar, foo]/[barney, fred]", "end"]) { v.value = Book("other", authors: ["fred", "barney"]) } XCTAssertEqual(authors.value, ["fred", "barney"]) } }
576d52d946f48dab41b500e3c77a52ec
34.584665
129
0.535195
false
false
false
false
LiuSky/XBKit
refs/heads/master
Sources/Styles/ColorPalette.swift
mit
1
// // ColorPalette.swift // XBKit // // Created by xiaobin liu on 2017/3/24. // Copyright © 2017年 Sky. All rights reserved. // import UIKit /** 颜色模版 */ public enum ColorPalette { public static let theme = ColorPalette.rgb(r: 0, g: 122, b: 255) public static let vice = ColorPalette.rgb(r: 170, g: 170, b: 170) public static let tint = UIColor.white public static let vcBG = UIColor(red: 0.937255, green: 0.937255, blue: 0.956863, alpha: 1.0) public static let line = ColorPalette.rgb(r: 206, g: 206, b: 206) public static let select = ColorPalette.rgb(r: 0, g: 102, b: 180) //RGB public static func rgb(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0) } }
0c4577465b472b45b9000ee8ea64bc7f
25.966667
96
0.619283
false
false
false
false
grantjbutler/Artikolo
refs/heads/master
Carthage/Checkouts/RxDataSources/Tests/NumberSection.swift
mit
3
// // NumberSection.swift // RxDataSources // // Created by Krunoslav Zaher on 1/7/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation import RxDataSources // MARK: Data struct NumberSection { var header: String var numbers: [IntItem] var updated: Date init(header: String, numbers: [Item], updated: Date) { self.header = header self.numbers = numbers self.updated = updated } } struct IntItem { let number: Int let date: Date } // MARK: Just extensions to say how to determine identity and how to determine is entity updated extension NumberSection : AnimatableSectionModelType { typealias Item = IntItem typealias Identity = String var identity: String { return header } var items: [IntItem] { return numbers } init(original: NumberSection, items: [Item]) { self = original self.numbers = items } } extension NumberSection : CustomDebugStringConvertible { var debugDescription: String { let interval = updated.timeIntervalSince1970 let numbersDescription = numbers.map { "\n\($0.debugDescription)" }.joined(separator: "") return "NumberSection(header: \"\(self.header)\", numbers: \(numbersDescription)\n, updated: \(interval))" } } extension IntItem : IdentifiableType , Equatable { typealias Identity = Int var identity: Int { return number } } // equatable, this is needed to detect changes func == (lhs: IntItem, rhs: IntItem) -> Bool { return lhs.number == rhs.number && lhs.date == rhs.date } // MARK: Some nice extensions extension IntItem : CustomDebugStringConvertible { var debugDescription: String { return "IntItem(number: \(number), date: \(date.timeIntervalSince1970))" } } extension IntItem : CustomStringConvertible { var description: String { return "\(number)" } } extension NumberSection: Equatable { } func == (lhs: NumberSection, rhs: NumberSection) -> Bool { return lhs.header == rhs.header && lhs.items == rhs.items && lhs.updated == rhs.updated }
3d4b113ede64d5f96846a523cbf084d8
20.66
114
0.653278
false
false
false
false
artemnovichkov/liftoff-templates
refs/heads/master
templates/UIColor+ApplicationColors.swift
mit
1
// // UIColor+ApplicationColors.swift // <%= project_name %> // // Created by <%= author %> on <%= Time.now.strftime("%-m/%-d/%y") %> // Copyright (c) <%= Time.now.strftime('%Y') %> <%= company %>. All rights reserved. // import UIKit extension UIColor { }
eb9adecb179d46a502b7d4f682e000c9
19.615385
85
0.567164
false
false
false
false
SeptAi/Cooperate
refs/heads/master
Cooperate/Cooperate/Class/ViewModel/MessageListViewModel.swift
mit
1
// // MessageListViewModel.swift // Cooperate // // Created by J on 2017/1/17. // Copyright © 2017年 J. All rights reserved. // import Foundation private let MaxPullNum = 3 class MessageListViewModel { private var PullNum = 0 // 视图模型数组懒加载 lazy var messageList = [MessageViewModel]() /// 请求数据 /// /// - Parameter comletion: 请求是否成功 func loadStatus(pullup:Bool = false,comletion:@escaping (_ isSuccess:Bool,_ isHasMore:Bool) -> ()) { // 判断上拉刷新次数 if pullup && PullNum > MaxPullNum{ // 次数超限 comletion(true,false) return } // - 数据缓存,通过DAL访问数据 // 数据请求 NetworkManager.sharedInstance.messageList(){ (list,isSuccess) in // 0.判断请求是否成功 if !isSuccess{ comletion(false, false) return } // 字典转模型 // yy_model(第三方框架支持嵌套的字典转模型 -- 与返回的属性值key需要一致) var array = [MessageViewModel]() // 便利服务器返回字典数组,字典转模型 for dict in list ?? []{ // 创建模型 guard let model = Notice.yy_model(with:dict) else{ continue } // 将model添加到数组 array.append(MessageViewModel(model: model)) } print("刷新到\(array.count)的数据,内容为\(array)") // 拼接参数 // FIXME: - 拼接参数 // self.projectList = pullup ? (self.projectList + array) : (array + self.projectList) self.messageList = array // 完成回调 if pullup && array.count == 0{ self.PullNum += 1 comletion(isSuccess, false) }else{ comletion(isSuccess,true) // 真正的回调 - 移到完成单张缓存之后执行 } } } }
876c7956dd268fb9e508130f417cc220
27.074627
104
0.479001
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
refs/heads/Development
MemorizeItForeverCore/MemorizeItForeverCoreTests/DataAccessTests/SetDataAccessTests.swift
mit
1
// // SetDataAccessTests.swift // MemorizeItForeverCore // // Created by Hadi Zamani on 10/22/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import XCTest @testable import MemorizeItForeverCore class SetDataAccessTests: XCTestCase { var setDataAccess: SetDataAccessProtocol! override func setUp() { super.setUp() let managedObjectContext = InMemoryManagedObjectContext() let dataAccess = MockGenericDataAccess<SetEntity>(context: managedObjectContext) setDataAccess = SetDataAccess(genericDataAccess: dataAccess) } override func tearDown() { setDataAccess = nil super.tearDown() } func testFetchSetNumberReturnAnInteger() { do{ let numberOfSets = try setDataAccess.fetchSetNumber() XCTAssertNotNil(Int(numberOfSets), "fetchSetNumber should retuen an integer") } catch{ XCTFail("fetchSetNumber should retuen an integer") } } func testSaveSetEntity(){ var setModel = SetModel() setModel.name = "Default" do{ try setDataAccess.save(setModel) } catch{ XCTFail("should be able to save an set") } } func testFetchSetNumberReturnCorrectNumber(){ do{ var setModel = SetModel() setModel.name = "Default" try setDataAccess.save(setModel) let numberOfSets = try setDataAccess.fetchSetNumber() XCTAssertEqual(numberOfSets, 1, "fetchSetNumber should retuen correct number of set stored") } catch{ XCTFail("fetchSetNumber should retuen correct number of set stored") } } func testFetchSet(){ do{ var setModel = SetModel() setModel.name = "Default" try setDataAccess.save(setModel) let sets = try setDataAccess.fetchAll() XCTAssertEqual(sets.count, 1, "should be able to fetch sets") } catch{ XCTFail("should be able to fetch sets") } } func testEditSet(){ do{ var setModel = SetModel() setModel.name = "Default" try setDataAccess.save(setModel) var sets = try setDataAccess.fetchAll() sets[0].name = "Edited" try setDataAccess.edit(sets[0]) let newSets = try setDataAccess.fetchAll() XCTAssertEqual(newSets[0].name, "Edited", "Should be able to edit a set") } catch{ XCTFail("Should be able to edit a set") } } func testDeleteSet(){ do{ var setModel = SetModel() setModel.name = "Default" try setDataAccess.save(setModel) let sets = try setDataAccess.fetchAll() try setDataAccess.delete(sets[0]) let newSets = try setDataAccess.fetchAll() XCTAssertEqual(newSets.count, 0, "Should be able to delete a set") } catch{ XCTFail("Should be able to delete a set") } } }
84cd36df4503d60ed9ea3187fe4f159a
28.453704
104
0.577491
false
true
false
false
chrisbudro/GrowlerHour
refs/heads/master
growlers/StyleBrowseTableViewController.swift
mit
1
// // StyleBrowseTableViewController.swift // growlers // // Created by Chris Budro on 9/8/15. // Copyright (c) 2015 chrisbudro. All rights reserved. // import UIKit class StyleBrowseTableViewController: BaseBrowseViewController { //MARK: Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() title = "Styles" cellReuseIdentifier = kStyleCellReuseIdentifier tableView.registerNib(UINib(nibName: kBeerStyleNibName, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier) dataSource = TableViewDataSource(cellReuseIdentifier: cellReuseIdentifier, configureCell: configureCell) tableView.dataSource = dataSource updateBrowseList() } } //MARK: Table View Delegate extension StyleBrowseTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = BeerStyleDetailViewController(style: .Plain) if let beerStyle = dataSource?.objectAtIndexPath(indexPath) as? BeerStyle { vc.beerStyle = beerStyle if let queryManager = queryManager { let styleQueryManager = QueryManager(type: .Tap, filter: queryManager.filter) vc.queryManager = styleQueryManager } } navigationController?.pushViewController(vc, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { //TODO: Not a valid solution. Need to solve UITableViewAutomaticDimension bug with insertRowAtIndexPaths return 60 } }
8b51906213c60b6236d71df8953ce570
31.3125
118
0.749194
false
false
false
false
mrdepth/EVEOnlineAPI
refs/heads/master
evecodegen/evecodegen/Schema.swift
mit
1
// // Schema.swift // evecodegen // // Created by Artem Shimanski on 29.04.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation class Property: Hashable { let name: String let type: Type let key: String let `class`: Class init(name: String, type: String, class: Class) throws { let c = name.components(separatedBy: "=") if c.count == 2 { self.name = c[0] self.key = c[1] } else if c.count == 1 { self.name = name self.key = name } else { throw ParserError.format(Swift.type(of:self).self, name) } self.type = try Type(type, namespace: `class`) self.class = `class` } var hashValue: Int { if case .schema = type { let schema = self.class.schema(name: type.typeName) return [name, type, schema!, key].hashValue } else { return [name, type, key].hashValue } } public static func ==(lhs: Property, rhs: Property) -> Bool { return lhs.hashValue == rhs.hashValue } lazy var propertyName: String = { var propertyName = self.name.camelBack return propertyName }() var defaultValue: String { switch type { case .array: return "[]" default: return "\(type.typeIdentifier)()" } } /*var typeName: String { return self.class.schema(name: type.typeName)!.namespaceIdentifier } var typeIdentifier: String { return typeName + (type.isOptional ? "?" : "") }*/ var definition: String { return "public var \(propertyName): \(type.typeIdentifier)\(type.isOptional ? "?" : "") = \(type.isOptional ? "nil" : defaultValue)" } var initialization: String { switch type { case let .array(item, isOptional): return isOptional ? "\(propertyName) = try dictionary.rowset(name: \"\(key)\")?.map {try \(item.typeIdentifier)(json: $0)}" : "guard let \(propertyName) = try dictionary.rowset(name: \"\(key)\")?.map ({try \(item.typeIdentifier)(json: $0)}) else {throw EVEError.invalidFormat(Swift.type(of: self), dictionary)}\n" + "self.\(propertyName) = \(propertyName)" case let .schema(_, _, isOptional): if type.isEnum { let item = self.class.schema(name: type.typeName) as! Enum return !isOptional ? "guard let \(propertyName) = \(type.typeIdentifier)(rawValue: dictionary[\"\(key)\"] as? \(item.type.typeIdentifier) ?? \(item.type.typeIdentifier)()) else {throw ESIError.invalidFormat(Swift.type(of: self), dictionary)}\n" + "self.\(propertyName) = \(propertyName)" : "\(propertyName) = \(type.typeIdentifier)(rawValue: dictionary[\"\(key)\"] as? \(item.type.typeIdentifier) ?? \(item.type.typeIdentifier)())" } else { return "\(propertyName) = \(isOptional ? "try?" : "try") \(type.typeIdentifier)(json: dictionary[\"\(key)\"] as? [String: Any] ?? [:])" } case let .date(isOptional): return isOptional ? "\(propertyName) = DateFormatter.eveDateFormatter.date(from: dictionary[\"\(key)\"] as? String ?? \"\")" : "guard let \(propertyName) = DateFormatter.eveDateFormatter.date(from: dictionary[\"\(key)\"] as? String ?? \"\") else {throw ESIError.invalidFormat(Swift.type(of: self), dictionary)}\n" + "self.\(propertyName) = \(propertyName)" default: return type.isOptional ? "\(propertyName) = dictionary[\"\(key)\"] as? \(type.typeIdentifier)" : "guard let \(propertyName) = dictionary[\"\(key)\"] as? \(type.typeIdentifier) else {throw EVEError.invalidFormat(Swift.type(of: self), dictionary)}\n" + "self.\(propertyName) = \(propertyName)" } } var decoding: String { switch type { case let .int(isOptional): return isOptional ? "\(propertyName) = aDecoder.containsValue(forKey: \"\(key)\") ? aDecoder.decodeInteger(forKey: \"\(key)\") : nil" : "\(propertyName) = aDecoder.decodeInteger(forKey: \"\(key)\")" case let .int64(isOptional): return isOptional ? "\(propertyName) = aDecoder.containsValue(forKey: \"\(key)\") ? aDecoder.decodeInt64(forKey: \"\(key)\") : nil" : "\(propertyName) = aDecoder.decodeInt64(forKey: \"\(key)\")" case let .double(isOptional): return isOptional ? "\(propertyName) = aDecoder.containsValue(forKey: \"\(key)\") ? aDecoder.decodeDouble(forKey: \"\(key)\") : nil" : "\(propertyName) = aDecoder.decodeDouble(forKey: \"\(key)\")" case let .float(isOptional): return isOptional ? "\(propertyName) = aDecoder.containsValue(forKey: \"\(key)\") ? aDecoder.decodeFloat(forKey: \"\(key)\") : nil" : "\(propertyName) = aDecoder.decodeFloat(forKey: \"\(key)\")" case let .bool(isOptional): return isOptional ? "\(propertyName) = aDecoder.containsValue(forKey: \"\(key)\") ? aDecoder.decodeBool(forKey: \"\(key)\") : nil" : "\(propertyName) = aDecoder.decodeBool(forKey: \"\(key)\")" case .date, .string, .yaml: return "\(propertyName) = aDecoder.decodeObject(forKey: \"\(key)\") as? \(type.typeIdentifier)\(!type.isOptional ? " ?? \(defaultValue)" : "")" case let .array(item, isOptional): return "\(propertyName) = aDecoder.decodeObject(of: [\(item.typeIdentifier).self], forKey: \"\(key)\") as? \(type.typeIdentifier)\(!isOptional ? " ?? \(defaultValue)" : "")" case let .schema(_, _, isOptional): if type.isEnum { let item = self.class.schema(name: type.typeName) as! Enum return "\(propertyName) = \(type.typeIdentifier)(rawValue: aDecoder.decodeObject(forKey: \"\(key)\") as? \(item.type.typeIdentifier) ?? \(item.type.typeIdentifier)())\(!isOptional ? " ?? \(defaultValue)" : "")" } else { return "\(propertyName) = aDecoder.decodeObject(of: \(type.typeIdentifier).self, forKey: \"\(key)\") \(!isOptional ? " ?? \(defaultValue)" : "")" } } } var encoding: String { if type.isOptional { if case let .schema(name, namespace, _) = type, namespace.schema(name: name) is Enum { return "if let v = \(propertyName) {\n" + "aCoder.encode(v.rawValue, forKey: \"\(key)\")\n}" } else { return "if let v = \(propertyName) {\n" + "aCoder.encode(v, forKey: \"\(key)\")\n}" } } else { if case let .schema(name, namespace, _) = type, namespace.schema(name: name) is Enum { return "aCoder.encode(\(propertyName).rawValue, forKey: \"\(key)\")" } else { return "aCoder.encode(\(propertyName), forKey: \"\(key)\")" } } } var json: String { return !type.isOptional ? "json[\"\(name)\"] = \(propertyName).json": "if let v = \(propertyName)?.json {\njson[\"\(name)\"] = v\n}" } var hash: String { switch type { case .array: return "self.\(propertyName)\(!type.isOptional ? "" : "?").forEach {hashCombine(seed: &hash, value: $0.hashValue)}" default: return !type.isOptional ? "hashCombine(seed: &hash, value: self.\(propertyName).hashValue)" : "hashCombine(seed: &hash, value: self.\(propertyName)?.hashValue ?? 0)" } } var copy: String { return "\(propertyName) = \(type.copy(from: "other." + propertyName, isRequired: !type.isOptional))" } } class Schema: Namespace { init(name: String, namespace: Namespace) throws { super.init() self.name = name self.parent = namespace } } class Enum: Schema { let cases: [(String, Any)] let type: Type init(_ value: Any, name: String, namespace: Namespace) throws { guard let array = value as? [String] else {throw ParserError.format(Swift.type(of: self).self, value)} var type: Type = .string(false) var cases = [(String, Any)]() for s in array { let c = s.components(separatedBy: "=") if c.count == 2 { if let i = Int(c[1]) { cases.append((c[0].camelBack, i)) type = .int(false) } else { cases.append((c[0].camelBack, c[1])) type = .string(false) } } else { cases.append((s.camelBack, s)) } } cases.sort(by: {$0.0 < $1.0}) self.type = type self.cases = cases try super.init(name: name, namespace: namespace) } override var hashValue: Int { var h: [AnyHashable] = cases.map({$0.0}) h.append(name) return h.hashValue } public var enumDefinition: String { func caseName(_ s: String) -> String { if s == "en-us" { return "enUS" } let s = s.replacingOccurrences(of: "#", with: "h").camelBack if CharacterSet.decimalDigits.contains(UnicodeScalar(s.utf8[s.utf8.startIndex])) { return "i" + s } switch s { case "public": return "`public`" case "private": return "`private`" default: let r = s.startIndex..<s.index(after: s.startIndex) return s.replacingCharacters(in: r, with: s[r].lowercased()) } } let enumName = name var template = try! String(contentsOf: enumURL) template = template.replacingOccurrences(of: "{enum}", with: enumName) let def = cases.first! template.replaceSubrange(template.range(of: "{default}")!, with: caseName(def.0)) let s: String = { if case .string = type { return self.cases.map { "\tcase \(caseName($0.0)) = \"\($0.1)\"" }.joined(separator: "\n") } else { return self.cases.map { "\tcase \(caseName($0.0)) = \($0.1)" }.joined(separator: "\n") } }() template.replaceSubrange(template.range(of: "{cases}")!, with: s) template = template.replacingOccurrences(of: "{type}", with: type.typeName) return template } } class Class: Schema { var properties: [Property] = [] init(_ dictionary: Any, name: String, namespace: Namespace) throws { guard let dic = dictionary as? [String: Any] else {throw ParserError.format(Swift.type(of: self).self, dictionary)} try super.init(name: name, namespace: namespace) var properties = [Property]() var children = [Schema]() for (key, value) in dic { if let dic = value as? [String: Any] { children.append(try Class(dic, name: key, namespace: self)) } else if let string = value as? String { properties.append(try Property(name: key, type: string, class: self)) } else if let array = value as? [String] { children.append(try Enum(array, name: key, namespace: self)) } else { throw ParserError.format(Swift.type(of: self).self, value) } } properties.sort {$0.name < $1.name} self.properties = properties self.children = children classLoaders.insert(classLoader) } override var hashValue: Int { var h: [AnyHashable] = properties h.append(name) return h.hashValue } var typeDefinition: String { var template = try! String(contentsOf: classURL) var definitions = [String]() var initializations = [String]() var encodings = [String]() var decodings = [String]() var json = [String]() // var defaults = [String]() var hashes = [String]() var nested = [String]() var copy = [String]() for value in properties { definitions.append(value.definition) initializations.append(value.initialization) encodings.append(value.encoding) decodings.append(value.decoding) json.append(value.json) // defaults.append(value.defaultInitialization) hashes.append(value.hash) copy.append(value.copy) } for child in children.sorted(by: {$0.name < $1.name}) { if let item = child as? Class { let s = item.typeDefinition nested.append(s) } else if let item = child as? Enum { let s = item.enumDefinition nested.append(s) } } let typeIdentifier = namespaceIdentifier let className = name template = template.replacingOccurrences(of: "{className}", with: className) template = template.replacingOccurrences(of: "{classIdentifier}", with: typeIdentifier) template = template.replacingOccurrences(of: "{class}", with: typeIdentifier) template.replaceSubrange(template.range(of: "{definitions}")!, with: definitions.joined(separator: "\n")) template.replaceSubrange(template.range(of: "{initializations}")!, with: initializations.joined(separator: "\n")) // template.replaceSubrange(template.range(of: "{defaults}")!, with: defaults.joined(separator: "\n")) // template.replaceSubrange(template.range(of: "{encodings}")!, with: encodings.joined(separator: "\n")) // template.replaceSubrange(template.range(of: "{decodings}")!, with: decodings.joined(separator: "\n")) template.replaceSubrange(template.range(of: "{json}")!, with: json.joined(separator: "\n")) template.replaceSubrange(template.range(of: "{hash}")!, with: hashes.joined(separator: "\n")) template.replaceSubrange(template.range(of: "{nested}")!, with: nested.joined(separator: "\n")) template.replaceSubrange(template.range(of: "{copy}")!, with: copy.joined(separator: "\n")) return template } var classLoader: String { return "_ = \(namespaceIdentifier).classForCoder()" } }
5e4fb0ccdff597076939471b209c927d
32.029101
230
0.644453
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/UI/Tasks/TaskFormRows/TaskDifficultyRow.swift
gpl-3.0
1
// // HabitDifficultyRow.swift // Habitica // // Created by Phillip Thelen on 22.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Eureka public class TaskDifficultyCell: Cell<Float>, CellType { @IBOutlet weak var trivialControlView: UIView! @IBOutlet weak var trivialControlIconView: UIImageView! @IBOutlet weak var trivialControlLabel: UILabel! @IBOutlet weak var easyControlView: UIView! @IBOutlet weak var easyControlIconView: UIImageView! @IBOutlet weak var easyControlLabel: UILabel! @IBOutlet weak var mediumControlView: UIView! @IBOutlet weak var mediumControlIconView: UIImageView! @IBOutlet weak var mediumControlLabel: UILabel! @IBOutlet weak var hardControlView: UIView! @IBOutlet weak var hardControlIconView: UIImageView! @IBOutlet weak var hardControlLabel: UILabel! public override func setup() { super.setup() trivialControlView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(trivialTapped))) easyControlView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(easyTapped))) mediumControlView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(mediumTapped))) hardControlView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hardTapped))) backgroundColor = .clear selectionStyle = .none } @objc private func trivialTapped() { if row.isDisabled { return } row.value = 0.1 row.updateCell() if #available(iOS 10, *) { UISelectionFeedbackGenerator.oneShotSelectionChanged() } accessibilityValue = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.trivial) } @objc private func easyTapped() { if row.isDisabled { return } row.value = 1 row.updateCell() if #available(iOS 10, *) { UISelectionFeedbackGenerator.oneShotSelectionChanged() } accessibilityValue = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.easy) } @objc private func mediumTapped() { if row.isDisabled { return } row.value = 1.5 row.updateCell() if #available(iOS 10, *) { UISelectionFeedbackGenerator.oneShotSelectionChanged() } accessibilityValue = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.medium) } @objc private func hardTapped() { if row.isDisabled { return } row.value = 2 row.updateCell() if #available(iOS 10, *) { UISelectionFeedbackGenerator.oneShotSelectionChanged() } accessibilityValue = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.hard) } public override func update() { if let taskRow = row as? TaskDifficultyRow { updateViews(taskRow: taskRow) applyAccessibility() } contentView.backgroundColor = ThemeService.shared.theme.contentBackgroundColor.withAlphaComponent(0.8) } private func updateViews(taskRow: TaskDifficultyRow) { if taskRow.value == 0.1 { trivialControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 0.1, isActive: true) trivialControlLabel.textColor = taskRow.tintColor } else { trivialControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 0.1, isActive: false) trivialControlLabel.textColor = ThemeService.shared.theme.ternaryTextColor } if taskRow.value == 1 { easyControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 1, isActive: true) easyControlLabel.textColor = taskRow.tintColor } else { easyControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 1, isActive: false) easyControlLabel.textColor = ThemeService.shared.theme.ternaryTextColor } if taskRow.value == 1.5 { mediumControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 1.5, isActive: true) mediumControlLabel.textColor = ThemeService.shared.theme.ternaryTextColor } else { mediumControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 1.5, isActive: false) mediumControlLabel.textColor = ThemeService.shared.theme.ternaryTextColor } if taskRow.value == 2 { hardControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 2, isActive: true) hardControlLabel.textColor = taskRow.tintColor } else { hardControlIconView.image = HabiticaIcons.imageOfTaskDifficultyStars(taskTintColor: taskRow.tintColor, difficulty: 2, isActive: false) hardControlLabel.textColor = ThemeService.shared.theme.ternaryTextColor } } func updateTintColor(_ newTint: UIColor) { self.tintColor = newTint (row as? TaskDifficultyRow)?.tintColor = newTint update() } private func applyAccessibility() { if let taskRow = row as? TaskDifficultyRow { shouldGroupAccessibilityChildren = true isAccessibilityElement = true accessibilityTraits = .adjustable if taskRow.value == 0.1 { accessibilityLabel = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.trivial) } else if taskRow.value == 1.0 { accessibilityLabel = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.easy) } else if taskRow.value == 1.5 { accessibilityLabel = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.medium) } else if taskRow.value == 2.0 { accessibilityLabel = L10n.Tasks.Form.Accessibility.taskDifficulty(L10n.Tasks.Form.hard) } } } public override func accessibilityIncrement() { super.accessibilityIncrement() if let taskRow = row as? TaskDifficultyRow { if taskRow.value == 0.1 { easyTapped() } else if taskRow.value == 1.0 { mediumTapped() } else if taskRow.value == 1.5 { hardTapped() } else if taskRow.value == 2.0 { trivialTapped() } } } public override func accessibilityDecrement() { super.accessibilityIncrement() if let taskRow = row as? TaskDifficultyRow { if taskRow.value == 0.1 { hardTapped() } else if taskRow.value == 1.0 { trivialTapped() } else if taskRow.value == 1.5 { easyTapped() } else if taskRow.value == 2.0 { mediumTapped() } } } } final class TaskDifficultyRow: TaskRow<TaskDifficultyCell>, RowType { required public init(tag: String?) { super.init(tag: tag) cellProvider = CellProvider<TaskDifficultyCell>(nibName: "TaskDifficultyCell") } }
7635ed1e5d4ed463ecb2f0c5c3a6d301
40.065574
151
0.654025
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
MockKit/MockCGMDataSource.swift
mit
1
// // MockCGMDataSource.swift // LoopKit // // Created by Michael Pangburn on 11/23/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import HealthKit import LoopKit public struct MockCGMDataSource { public enum Model { public typealias SineCurveParameters = (baseGlucose: HKQuantity, amplitude: HKQuantity, period: TimeInterval, referenceDate: Date) case constant(_ glucose: HKQuantity) case sineCurve(parameters: SineCurveParameters) case noData case signalLoss case unreliableData public var isValidSession: Bool { switch self { case .noData: return false default: return true } } } public struct Effects { public typealias RandomOutlier = (chance: Double, delta: HKQuantity) public var glucoseNoise: HKQuantity? public var randomLowOutlier: RandomOutlier? public var randomHighOutlier: RandomOutlier? public var randomErrorChance: Double? public init( glucoseNoise: HKQuantity? = nil, randomLowOutlier: RandomOutlier? = nil, randomHighOutlier: RandomOutlier? = nil, randomErrorChance: Double? = nil ) { self.glucoseNoise = glucoseNoise self.randomLowOutlier = randomLowOutlier self.randomHighOutlier = randomHighOutlier self.randomErrorChance = randomErrorChance } } static let device = HKDevice( name: "MockCGMManager", manufacturer: "LoopKit", model: "MockCGMManager", hardwareVersion: nil, firmwareVersion: nil, softwareVersion: String(LoopKitVersionNumber), localIdentifier: nil, udiDeviceIdentifier: nil ) public var model: Model { didSet { glucoseProvider = MockGlucoseProvider(model: model, effects: effects) } } public var effects: Effects { didSet { glucoseProvider = MockGlucoseProvider(model: model, effects: effects) } } private var glucoseProvider: MockGlucoseProvider private var lastFetchedData = Locked(Date.distantPast) public var dataPointFrequency: MeasurementFrequency public var isValidSession: Bool { return model.isValidSession } public init( model: Model, effects: Effects = .init(), dataPointFrequency: MeasurementFrequency = .normal ) { self.model = model self.effects = effects self.glucoseProvider = MockGlucoseProvider(model: model, effects: effects) self.dataPointFrequency = dataPointFrequency } func fetchNewData(_ completion: @escaping (CGMReadingResult) -> Void) { let now = Date() // Give 5% wiggle room for producing data points let bufferedFrequency = dataPointFrequency.frequency - 0.05 * dataPointFrequency.frequency if now.timeIntervalSince(lastFetchedData.value) < bufferedFrequency { completion(.noData) return } lastFetchedData.value = now glucoseProvider.fetchData(at: now, completion: completion) } func backfillData(from interval: DateInterval, completion: @escaping (CGMReadingResult) -> Void) { lastFetchedData.value = interval.end let request = MockGlucoseProvider.BackfillRequest(datingBack: interval.duration, dataPointFrequency: dataPointFrequency.frequency) glucoseProvider.backfill(request, endingAt: interval.end, completion: completion) } } extension MockCGMDataSource: RawRepresentable { public typealias RawValue = [String: Any] public init?(rawValue: RawValue) { guard let model = (rawValue["model"] as? Model.RawValue).flatMap(Model.init(rawValue:)), let effects = (rawValue["effects"] as? Effects.RawValue).flatMap(Effects.init(rawValue:)), let dataPointFrequency = (rawValue["dataPointFrequency"] as? MeasurementFrequency.RawValue).flatMap(MeasurementFrequency.init(rawValue:)) else { return nil } self.init(model: model, effects: effects, dataPointFrequency: dataPointFrequency) } public var rawValue: RawValue { return [ "model": model.rawValue, "effects": effects.rawValue, "dataPointFrequency": dataPointFrequency.rawValue ] } } extension MockCGMDataSource.Model: RawRepresentable { public typealias RawValue = [String: Any] private enum Kind: String { case constant case sineCurve case noData case signalLoss case unreliableData } private static let unit = HKUnit.milligramsPerDeciliter public init?(rawValue: RawValue) { guard let kindRawValue = rawValue["kind"] as? Kind.RawValue, let kind = Kind(rawValue: kindRawValue) else { return nil } let unit = MockCGMDataSource.Model.unit func glucose(forKey key: String) -> HKQuantity? { guard let doubleValue = rawValue[key] as? Double else { return nil } return HKQuantity(unit: unit, doubleValue: doubleValue) } switch kind { case .constant: guard let quantity = glucose(forKey: "quantity") else { return nil } self = .constant(quantity) case .sineCurve: guard let baseGlucose = glucose(forKey: "baseGlucose"), let amplitude = glucose(forKey: "amplitude"), let period = rawValue["period"] as? TimeInterval, let referenceDateSeconds = rawValue["referenceDate"] as? TimeInterval else { return nil } let referenceDate = Date(timeIntervalSince1970: referenceDateSeconds) self = .sineCurve(parameters: (baseGlucose: baseGlucose, amplitude: amplitude, period: period, referenceDate: referenceDate)) case .noData: self = .noData case .signalLoss: self = .signalLoss case .unreliableData: self = .unreliableData } } public var rawValue: RawValue { var rawValue: RawValue = ["kind": kind.rawValue] let unit = MockCGMDataSource.Model.unit switch self { case .constant(let quantity): rawValue["quantity"] = quantity.doubleValue(for: unit) case .sineCurve(parameters: (baseGlucose: let baseGlucose, amplitude: let amplitude, period: let period, referenceDate: let referenceDate)): rawValue["baseGlucose"] = baseGlucose.doubleValue(for: unit) rawValue["amplitude"] = amplitude.doubleValue(for: unit) rawValue["period"] = period rawValue["referenceDate"] = referenceDate.timeIntervalSince1970 case .noData, .signalLoss, .unreliableData: break } return rawValue } private var kind: Kind { switch self { case .constant: return .constant case .sineCurve: return .sineCurve case .noData: return .noData case .signalLoss: return .signalLoss case .unreliableData: return .unreliableData } } } extension MockCGMDataSource.Effects: RawRepresentable { public typealias RawValue = [String: Any] private static let unit = HKUnit.milligramsPerDeciliter public init?(rawValue: RawValue) { self.init() let unit = MockCGMDataSource.Effects.unit func randomOutlier(forKey key: String) -> RandomOutlier? { guard let outlier = rawValue[key] as? [String: Double], let chance = outlier["chance"], let delta = outlier["delta"] else { return nil } return (chance: chance, delta: HKQuantity(unit: unit, doubleValue: delta)) } if let glucoseNoise = rawValue["glucoseNoise"] as? Double { self.glucoseNoise = HKQuantity(unit: unit, doubleValue: glucoseNoise) } self.randomLowOutlier = randomOutlier(forKey: "randomLowOutlier") self.randomHighOutlier = randomOutlier(forKey: "randomHighOutlier") self.randomErrorChance = rawValue["randomErrorChance"] as? Double } public var rawValue: RawValue { var rawValue: RawValue = [:] let unit = MockCGMDataSource.Effects.unit func insertOutlier(_ outlier: RandomOutlier, forKey key: String) { rawValue[key] = [ "chance": outlier.chance, "delta": outlier.delta.doubleValue(for: unit) ] } if let glucoseNoise = glucoseNoise { rawValue["glucoseNoise"] = glucoseNoise.doubleValue(for: unit) } if let randomLowOutlier = randomLowOutlier { insertOutlier(randomLowOutlier, forKey: "randomLowOutlier") } if let randomHighOutlier = randomHighOutlier { insertOutlier(randomHighOutlier, forKey: "randomHighOutlier") } if let randomErrorChance = randomErrorChance { rawValue["randomErrorChance"] = randomErrorChance } return rawValue } } extension MockCGMDataSource: CustomDebugStringConvertible { public var debugDescription: String { return """ ## MockCGMDataSource * model: \(model) * effects: \(effects) """ } } public enum MeasurementFrequency: Int, CaseIterable { case normal case fast case faster public var frequency: TimeInterval { switch self { case .normal: return TimeInterval(5*60) case .fast: return TimeInterval(60) case .faster: return TimeInterval(5) } } public var localizedDescription: String { switch self { case .normal: return "5 minutes" case .fast: return "1 minute" case .faster: return "5 seconds" } } }
8ca9257e0ea275596ae6b59a2b7edf06
30.194529
149
0.609958
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Blockchain/Announcements/AnnouncementPresenter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import Combine import DIKit import FeatureCryptoDomainDomain import FeatureCryptoDomainUI import FeatureDashboardUI import FeatureKYCDomain import FeatureNFTDomain import FeatureProductsDomain import MoneyKit import PlatformKit import PlatformUIKit import RxCocoa import RxSwift import RxToolKit import SwiftUI import ToolKit import UIComponentsKit import WalletPayloadKit /// Describes the announcement visual. Plays as a presenter / provide for announcements, /// By creating a list of pending announcements, on which subscribers can be informed. final class AnnouncementPresenter { // MARK: - Rx /// Returns a driver with `.none` as default value for announcement action /// Scheduled on be executed on main scheduler, its resources are shared and it remembers the last value. var announcement: Driver<AnnouncementDisplayAction> { announcementRelay .asDriver() .distinctUntilChanged() } // MARK: Services private let tabSwapping: TabSwapping private let walletOperating: WalletOperationsRouting private let backupFlowStarter: BackupFlowStarterAPI private let settingsStarter: SettingsStarterAPI private let app: AppProtocol private let featureFetcher: FeatureFetching private let cashIdentityVerificationRouter: CashIdentityVerificationAnnouncementRouting private let kycRouter: KYCRouterAPI private let kycSettings: KYCSettingsAPI private let reactiveWallet: ReactiveWalletAPI private let topMostViewControllerProvider: TopMostViewControllerProviding private let interactor: AnnouncementInteracting private let webViewServiceAPI: WebViewServiceAPI private let analyticsRecorder: AnalyticsEventRecorderAPI private let navigationRouter: NavigationRouterAPI private let exchangeProviding: ExchangeProviding private let accountsRouter: AccountsRouting private let viewWaitlistRegistration: ViewWaitlistRegistrationRepositoryAPI private let coincore: CoincoreAPI private let nabuUserService: NabuUserServiceAPI private let announcementRelay = BehaviorRelay<AnnouncementDisplayAction>(value: .hide) private let disposeBag = DisposeBag() private var currentAnnouncement: Announcement? // Combine private var cancellables = Set<AnyCancellable>() // MARK: - Setup init( app: AppProtocol = DIKit.resolve(), navigationRouter: NavigationRouterAPI = NavigationRouter(), exchangeProviding: ExchangeProviding = DIKit.resolve(), accountsRouter: AccountsRouting = DIKit.resolve(), interactor: AnnouncementInteracting = AnnouncementInteractor(), topMostViewControllerProvider: TopMostViewControllerProviding = DIKit.resolve(), featureFetcher: FeatureFetching = DIKit.resolve(), cashIdentityVerificationRouter: CashIdentityVerificationAnnouncementRouting = DIKit.resolve(), tabSwapping: TabSwapping = DIKit.resolve(), walletOperating: WalletOperationsRouting = DIKit.resolve(), backupFlowStarter: BackupFlowStarterAPI = DIKit.resolve(), settingsStarter: SettingsStarterAPI = DIKit.resolve(), kycRouter: KYCRouterAPI = DIKit.resolve(), reactiveWallet: ReactiveWalletAPI = DIKit.resolve(), kycSettings: KYCSettingsAPI = DIKit.resolve(), webViewServiceAPI: WebViewServiceAPI = DIKit.resolve(), viewWaitlistRegistration: ViewWaitlistRegistrationRepositoryAPI = DIKit.resolve(), analyticsRecorder: AnalyticsEventRecorderAPI = DIKit.resolve(), coincore: CoincoreAPI = DIKit.resolve(), nabuUserService: NabuUserServiceAPI = DIKit.resolve() ) { self.app = app self.interactor = interactor self.viewWaitlistRegistration = viewWaitlistRegistration self.webViewServiceAPI = webViewServiceAPI self.topMostViewControllerProvider = topMostViewControllerProvider self.cashIdentityVerificationRouter = cashIdentityVerificationRouter self.kycRouter = kycRouter self.reactiveWallet = reactiveWallet self.kycSettings = kycSettings self.featureFetcher = featureFetcher self.analyticsRecorder = analyticsRecorder self.tabSwapping = tabSwapping self.walletOperating = walletOperating self.backupFlowStarter = backupFlowStarter self.settingsStarter = settingsStarter self.navigationRouter = navigationRouter self.exchangeProviding = exchangeProviding self.accountsRouter = accountsRouter self.coincore = coincore self.nabuUserService = nabuUserService app.modePublisher() .asObservable() .bind { [weak self] _ in self?.calculate() } .disposed(by: disposeBag) announcement .asObservable() .filter(\.isHide) .mapToVoid() .bindAndCatch(weak: self) { (self) in self.currentAnnouncement = nil } .disposed(by: disposeBag) } /// Refreshes announcements on demand func refresh() { reactiveWallet .waitUntilInitialized .asObservable() .bind { [weak self] _ in self?.calculate() } .disposed(by: disposeBag) } // MARK: - Private Helpers private func calculate() { let announcementsMetadata = featureFetcher .fetch(for: .announcements, as: AnnouncementsMetadata.self) .asSingle() let delaySeconds = app.currentMode == .defi ? 0 : 10 let data: Single<AnnouncementPreliminaryData> = interactor.preliminaryData .asSingle() .delaySubscription(.seconds(delaySeconds), scheduler: MainScheduler.asyncInstance) Single .zip(announcementsMetadata, data) .flatMap(weak: self) { (self, payload) -> Single<AnnouncementDisplayAction> in let action = self.resolve(metadata: payload.0, preliminaryData: payload.1) return .just(action) } .catchAndReturn(.hide) .asObservable() .bindAndCatch(to: announcementRelay) .disposed(by: disposeBag) } /// Resolves the first valid announcement according by the provided types and preliminary data private func resolve( metadata: AnnouncementsMetadata, preliminaryData: AnnouncementPreliminaryData ) -> AnnouncementDisplayAction { // If Cowboys Promotios is enabled, do not display any announcement. if preliminaryData.cowboysPromotionIsEnabled { return .none } // For other users, keep the current logic in place for type in metadata.order { let announcement: Announcement = announcement( type: type, metadata: metadata, preliminaryData: preliminaryData ) // Wallets with no balance should show no announcements let shouldShowBalanceCheck = preliminaryData.hasAnyWalletBalance || type.showsWhenWalletHasNoBalance // For users that are not in the mode needed for the announcement we don't show it let shouldShowCurrentModeCheck = announcement.associatedAppModes.contains(app.currentMode) // Return the first different announcement that should show if shouldShowBalanceCheck, shouldShowCurrentModeCheck, announcement.shouldShow { if currentAnnouncement?.type != announcement.type { currentAnnouncement = announcement return .show(announcement.viewModel) } else { // Announcement is currently displaying return .none } } } // None of the types were resolved into a displayable announcement return .none } private func announcement( type: AnnouncementType, metadata: AnnouncementsMetadata, preliminaryData: AnnouncementPreliminaryData ) -> Announcement { switch type { case .majorProductBlocked: let reason = preliminaryData.majorProductBlocked return majorProductBlocked(reason) case .claimFreeCryptoDomain: return claimFreeCryptoDomainAnnouncement( claimFreeDomainEligible: preliminaryData.claimFreeDomainEligible ) case .resubmitDocumentsAfterRecovery: return resubmitDocumentsAfterRecovery(user: preliminaryData.user) case .sddUsersFirstBuy: return sddUsersFirstBuy( tiers: preliminaryData.tiers, isSDDEligible: preliminaryData.isSDDEligible, hasAnyWalletBalance: preliminaryData.hasAnyWalletBalance, reappearanceTimeInterval: metadata.interval ) case .verifyEmail: return verifyEmail( user: preliminaryData.user, reappearanceTimeInterval: metadata.interval ) case .twoFA: return twoFA( hasTwoFA: preliminaryData.hasTwoFA, hasAnyWalletBalance: preliminaryData.hasAnyWalletBalance, reappearanceTimeInterval: metadata.interval ) case .backupFunds: return backupFunds( isRecoveryPhraseVerified: preliminaryData.isRecoveryPhraseVerified, hasAnyWalletBalance: preliminaryData.hasAnyWalletBalance, reappearanceTimeInterval: metadata.interval ) case .buyBitcoin: return buyBitcoin( hasAnyWalletBalance: preliminaryData.hasAnyWalletBalance, reappearanceTimeInterval: metadata.interval ) case .transferBitcoin: return transferBitcoin( isKycSupported: preliminaryData.isKycSupported, reappearanceTimeInterval: metadata.interval ) case .verifyIdentity: return verifyIdentity(using: preliminaryData.user) case .viewNFTWaitlist: return viewNFTComingSoonAnnouncement() case .resubmitDocuments: return resubmitDocuments(user: preliminaryData.user) case .simpleBuyKYCIncomplete: return simpleBuyFinishSignup( tiers: preliminaryData.tiers, hasIncompleteBuyFlow: preliminaryData.hasIncompleteBuyFlow, reappearanceTimeInterval: metadata.interval ) case .newAsset: return newAsset(cryptoCurrency: preliminaryData.newAsset) case .assetRename: return assetRename( data: preliminaryData.assetRename ) case .walletConnect: return walletConnect() case .applePay: return applePay() } } /// Hides whichever announcement is now displaying private var announcementDismissAction: CardAnnouncementAction { { [weak self] in self?.announcementRelay.accept(.hide) } } private func actionForOpening(_ absoluteURL: String) -> CardAnnouncementAction { { [weak self] in guard let destination = self?.topMostViewControllerProvider.topMostViewController else { return } self?.webViewServiceAPI.openSafari( url: absoluteURL, from: destination ) } } } // MARK: - Computes announcements extension AnnouncementPresenter { /// Computes email verification announcement private func verifyEmail( user: NabuUser, reappearanceTimeInterval: TimeInterval ) -> Announcement { VerifyEmailAnnouncement( isEmailVerified: user.email.verified, reappearanceTimeInterval: reappearanceTimeInterval, action: UIApplication.shared.openMailApplication, dismiss: announcementDismissAction ) } /// Computes Simple Buy Finish Signup Announcement private func simpleBuyFinishSignup( tiers: KYC.UserTiers, hasIncompleteBuyFlow: Bool, reappearanceTimeInterval: TimeInterval ) -> Announcement { SimpleBuyFinishSignupAnnouncement( canCompleteTier2: tiers.canCompleteTier2, hasIncompleteBuyFlow: hasIncompleteBuyFlow, reappearanceTimeInterval: reappearanceTimeInterval, action: { [weak self] in guard let self = self else { return } self.announcementDismissAction() self.handleBuyCrypto() }, dismiss: announcementDismissAction ) } // Computes transfer in bitcoin announcement private func transferBitcoin(isKycSupported: Bool, reappearanceTimeInterval: TimeInterval) -> Announcement { TransferInCryptoAnnouncement( isKycSupported: isKycSupported, reappearanceTimeInterval: reappearanceTimeInterval, dismiss: announcementDismissAction, action: { [weak self] in guard let self = self else { return } self.announcementDismissAction() self.tabSwapping.switchTabToReceive() } ) } /// Computes identity verification card announcement private func verifyIdentity(using user: NabuUser) -> Announcement { VerifyIdentityAnnouncement( isCompletingKyc: kycSettings.isCompletingKyc, dismiss: announcementDismissAction, action: { [weak self] in guard let self = self else { return } let tier = user.tiers?.selected ?? .tier1 self.kycRouter.start( tier: tier, parentFlow: .announcement, from: self.tabSwapping ) } ) } /// Computes Major Product Blocked announcement private func majorProductBlocked(_ reason: ProductIneligibility?) -> Announcement { MajorProductBlockedAnnouncement( announcementMessage: reason?.message, dismiss: announcementDismissAction, action: { [actionForOpening] in if let learnMoreURL = reason?.learnMoreUrl { return actionForOpening(learnMoreURL.absoluteString) } return {} }(), showLearnMoreButton: reason?.learnMoreUrl != nil ) } private func showCoinView(for currency: CryptoCurrency) { app.post( event: blockchain.ux.asset[currency.code].select, context: [blockchain.ux.asset.select.origin: "ANNOUNCEMENT"] ) } /// Computes asset rename card announcement. private func assetRename( data: AnnouncementPreliminaryData.AssetRename? ) -> Announcement { AssetRenameAnnouncement( data: data, dismiss: announcementDismissAction, action: { [weak self] in guard let asset = data?.asset else { return } self?.showCoinView(for: asset) } ) } private func walletConnect() -> Announcement { let absolutURL = "https://medium.com/blockchain/" + "introducing-walletconnect-access-web3-from-your-blockchain-com-wallet-da02e49ccea9" return WalletConnectAnnouncement( dismiss: announcementDismissAction, action: actionForOpening(absolutURL) ) } private func applePay() -> Announcement { ApplePayAnnouncement( dismiss: announcementDismissAction, action: { [weak self] in self?.app.state.set(blockchain.ux.transaction.previous.payment.method.id, to: "APPLE_PAY") self?.handleBuyCrypto(currency: .bitcoin) } ) } /// Computes new asset card announcement. private func newAsset(cryptoCurrency: CryptoCurrency?) -> Announcement { NewAssetAnnouncement( cryptoCurrency: cryptoCurrency, dismiss: announcementDismissAction, action: { [weak self] in guard let cryptoCurrency = cryptoCurrency else { return } self?.handleBuyCrypto(currency: cryptoCurrency) } ) } /// Claim Free Crypto Domain Announcement for eligible users private func claimFreeCryptoDomainAnnouncement( claimFreeDomainEligible: Bool ) -> Announcement { ClaimFreeCryptoDomainAnnouncement( claimFreeDomainEligible: claimFreeDomainEligible, action: { [weak self] in self?.presentClaimIntroductionHostingController() }, dismiss: announcementDismissAction ) } private func registerEmailForNFTViewWaitlist() { viewWaitlistRegistration .registerEmailForNFTViewWaitlist() .sink(receiveCompletion: { [analyticsRecorder] result in switch result { case .finished: break case .failure(let error): switch error { case .emailUnavailable: analyticsRecorder .record( event: ClientEvent.clientError( id: nil, error: "VIEW_NFT_WAITLIST_EMAIL_ERROR", source: "WALLET", title: "", action: "ANNOUNCEMENT" ) ) case .network(let nabuNetworkError): Logger.shared.error("\(error)") analyticsRecorder .record( event: ClientEvent.clientError( id: nabuNetworkError.ux?.id, error: "VIEW_NFT_WAITLIST_REGISTRATION_ERROR", networkEndpoint: nabuNetworkError.request?.url?.absoluteString ?? "", networkErrorCode: "\(nabuNetworkError.code)", networkErrorDescription: nabuNetworkError.description, networkErrorId: nil, networkErrorType: nabuNetworkError.type.rawValue, source: "EXPLORER", title: "", action: "ANNOUNCEMENT" ) ) } } }, receiveValue: { _ in }) .store(in: &cancellables) } private func presentClaimIntroductionHostingController() { let vc = ClaimIntroductionHostingController( mainQueue: .main, analyticsRecorder: DIKit.resolve(), externalAppOpener: DIKit.resolve(), searchDomainRepository: DIKit.resolve(), orderDomainRepository: DIKit.resolve(), userInfoProvider: { [coincore, nabuUserService] in Deferred { [coincore] in Just([coincore[.ethereum], coincore[.bitcoin], coincore[.bitcoinCash], coincore[.stellar]]) } .eraseError() .flatMap { [nabuUserService] cryptoAssets -> AnyPublisher<([ResolutionRecord], NabuUser), Error> in guard let providers = cryptoAssets as? [DomainResolutionRecordProviderAPI] else { return .empty() } let recordPublisher = providers.map(\.resolutionRecord).zip() let nabuUserPublisher = nabuUserService.user.eraseError() return recordPublisher .zip(nabuUserPublisher) .eraseToAnyPublisher() } .map { records, nabuUser -> OrderDomainUserInfo in OrderDomainUserInfo( nabuUserId: nabuUser.identifier, nabuUserName: nabuUser .personalDetails .firstName? .replacingOccurrences(of: " ", with: "") ?? "", resolutionRecords: records ) } .eraseToAnyPublisher() } ) let nav = UINavigationController(rootViewController: vc) navigationRouter.present(viewController: nav, using: .modalOverTopMost) } /// Computes SDD Users Buy announcement private func sddUsersFirstBuy( tiers: KYC.UserTiers, isSDDEligible: Bool, hasAnyWalletBalance: Bool, reappearanceTimeInterval: TimeInterval ) -> Announcement { // For now, we want to target non-KYCed SDD eligible users specifically, but we're going to review all announcements soon for Onboarding BuyBitcoinAnnouncement( isEnabled: tiers.isTier0 && isSDDEligible && !hasAnyWalletBalance, reappearanceTimeInterval: reappearanceTimeInterval, dismiss: announcementDismissAction, action: { [weak self] in self?.handleBuyCrypto(currency: .bitcoin) } ) } /// Computes Buy BTC announcement private func buyBitcoin( hasAnyWalletBalance: Bool, reappearanceTimeInterval: TimeInterval ) -> Announcement { BuyBitcoinAnnouncement( isEnabled: !hasAnyWalletBalance, reappearanceTimeInterval: reappearanceTimeInterval, dismiss: announcementDismissAction, action: { [weak self] in self?.handleBuyCrypto(currency: .bitcoin) } ) } /// Computes Backup Funds (recovery phrase) private func backupFunds( isRecoveryPhraseVerified: Bool, hasAnyWalletBalance: Bool, reappearanceTimeInterval: TimeInterval ) -> Announcement { let shouldBackupFunds = !isRecoveryPhraseVerified && hasAnyWalletBalance return BackupFundsAnnouncement( shouldBackupFunds: shouldBackupFunds, reappearanceTimeInterval: reappearanceTimeInterval, dismiss: announcementDismissAction, action: { [weak self] in self?.backupFlowStarter.startBackupFlow() } ) } /// Computes 2FA announcement private func twoFA( hasTwoFA: Bool, hasAnyWalletBalance: Bool, reappearanceTimeInterval: TimeInterval ) -> Announcement { let shouldEnable2FA = !hasTwoFA && hasAnyWalletBalance return Enable2FAAnnouncement( shouldEnable2FA: shouldEnable2FA, reappearanceTimeInterval: reappearanceTimeInterval, dismiss: announcementDismissAction, action: { [weak self] in self?.settingsStarter.showSettingsView() } ) } private func viewNFTComingSoonAnnouncement() -> Announcement { ViewNFTComingSoonAnnouncement( dismiss: announcementDismissAction, action: { [weak self] in guard let self = self else { return } self.registerEmailForNFTViewWaitlist() } ) } /// Computes Upload Documents card announcement private func resubmitDocuments(user: NabuUser) -> Announcement { ResubmitDocumentsAnnouncement( needsDocumentResubmission: user.needsDocumentResubmission != nil && user.needsDocumentResubmission?.reason != 1, dismiss: announcementDismissAction, action: { [weak self] in guard let self = self else { return } let tier = user.tiers?.selected ?? .tier1 self.kycRouter.start( tier: tier, parentFlow: .announcement, from: self.tabSwapping ) } ) } private func resubmitDocumentsAfterRecovery(user: NabuUser) -> Announcement { ResubmitDocumentsAfterRecoveryAnnouncement( // reason 1: resubmission needed due to account recovery needsDocumentResubmission: user.needsDocumentResubmission?.reason == 1, action: { [weak self] in guard let self = self else { return } let tier = user.tiers?.selected ?? .tier1 self.kycRouter.start( tier: tier, parentFlow: .announcement, from: self.tabSwapping ) } ) } } extension AnnouncementPresenter { private func handleBuyCrypto(currency: CryptoCurrency = .bitcoin) { walletOperating.handleBuyCrypto(currency: currency) analyticsRecorder.record( event: AnalyticsEvents.New.SimpleBuy.buySellClicked(type: .buy, origin: .dashboardPromo) ) } }
e4b2d3de05dd7dc7cb170b80f56ae43c
38.084356
144
0.608327
false
false
false
false
woohyuknrg/GithubTrending
refs/heads/master
github/AppDelegate.swift
mit
1
// // AppDelegate.swift // github // // Created by krawiecp on 09/03/2016. // Copyright © 2016 Pawel Krawiec. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) if let window = window { let provider = GitHubProvider let tabBarController = UITabBarController() let discoverViewController = UIStoryboard.main.discoverViewController discoverViewController.viewModel = DiscoverViewModel(provider: provider) let searchViewController = UIStoryboard.main.searchViewController searchViewController.viewModel = SearchViewModel(provider: provider) tabBarController.viewControllers = [ UINavigationController(rootViewController: discoverViewController), UINavigationController(rootViewController: searchViewController) ] window.rootViewController = tabBarController window.makeKeyAndVisible() let appToken = Token() if !appToken.tokenExists { let loginViewController = UIStoryboard.main.loginViewController loginViewController.viewModel = LoginViewModel(provider: provider) window.rootViewController?.present(loginViewController, animated: false, completion: nil) } } return true } }
bd6b9239e5f67ab3922bdd7657e166b4
35.404255
144
0.652835
false
false
false
false
qutheory/vapor
refs/heads/master
Sources/Vapor/HTTP/Headers/HTTPHeaders.swift
mit
1
extension HTTPHeaders { /// `MediaType` specified by this message's `"Content-Type"` header. public var contentType: HTTPMediaType? { get { self.parseDirectives(name: .contentType).first.flatMap { HTTPMediaType(directives: $0) } } set { if let new = newValue?.serialize() { self.replaceOrAdd(name: .contentType, value: new) } else { self.remove(name: .contentType) } } } /// Returns a collection of `MediaTypePreference`s specified by this HTTP message's `"Accept"` header. /// /// You can returns all `MediaType`s in this collection to check membership. /// /// httpReq.accept.mediaTypes.contains(.html) /// /// Or you can compare preferences for two `MediaType`s. /// /// let pref = httpReq.accept.comparePreference(for: .json, to: .html) /// public var accept: [HTTPMediaTypePreference] { self.parseDirectives(name: .accept).compactMap { HTTPMediaTypePreference(directives: $0) } } } extension HTTPHeaders: Codable { public init(from decoder: Decoder) throws { let dictionary = try decoder.singleValueContainer().decode([String: String].self) self.init() for (name, value) in dictionary { self.add(name: name, value: value) } } public func encode(to encoder: Encoder) throws { var dictionary: [String: String] = [:] for (name, value) in self { dictionary[name] = value } var container = encoder.singleValueContainer() try container.encode(dictionary) } }
d9e1c6340bba4db34e5ed7e70898bb99
31.942308
106
0.58202
false
false
false
false
jesse-c/AutoVolume
refs/heads/master
AutoVolume/ViewController.swift
mit
1
import Cocoa class ViewController: NSViewController { let appDelegate = NSApplication.shared().delegate as! AppDelegate @IBOutlet weak var volumeSlider: NSSlider! @IBOutlet weak var currentVolume: NSTextField! @IBOutlet weak var loginStartCheckbox: NSButton! @IBOutlet weak var enabledCheckbox: NSButton! @IBOutlet weak var quitButton: NSButtonCell! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let volume = appDelegate.defaults.float(forKey: appDelegate.desiredVolumeKey) self.currentVolume.placeholderString = "?" self.currentVolume.stringValue = NSString(format: "%.2f", volume) as String self.currentVolume.isEditable = false self.currentVolume.isSelectable = false // Set slider to current volume volumeSlider.floatValue = volume // Set enabled button to current state let enabledButtonState = appDelegate.defaults.integer(forKey: appDelegate.enabledKey) enabledCheckbox.state = enabledButtonState // Set login enabled button to current state let loginStartButtonState = appDelegate.defaults.integer(forKey: appDelegate.loginStartKey) loginStartCheckbox.state = loginStartButtonState // Centre self.view.window?.center() // Prevent resizing _ = self.view.window?.styleMask.remove([.resizable]) // Notifications appDelegate.nc.addObserver(self, selector: #selector(self.handleVolumeChanged), name: NSNotification.Name.OnVolumeChanged, object: nil) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } @IBAction func sliderChanged(_ sender: NSSlider) { let val: Float = sender.floatValue let userInfo: ValInfo = ["val": val] NSLog("Slider changed to: \(val)") appDelegate.nc.post(name: NSNotification.Name.OnVolumeChanged, object: nil, userInfo: userInfo) } @IBAction func loginStartButtonPressed(_ sender: NSButton) { let buttonState = loginStartCheckbox.state let userInfo: LoginStartInfo = ["buttonState": buttonState] appDelegate.nc.post(name: NSNotification.Name.OnLoginStartButtonPressed, object: nil, userInfo: userInfo) } @IBAction func enabledButtonPressed(_ sender: NSButton) { let buttonState = enabledCheckbox.state let userInfo: EnabledInfo = ["buttonState": buttonState] NSLog("Enabled button pressed. State is: \(buttonState)") appDelegate.nc.post(name: NSNotification.Name.OnEnabledButtonPressed, object: nil, userInfo: userInfo) } @IBAction func quitButtonPressed(_ sender: Any) { NSLog("Quit button pressed") appDelegate.nc.post(name: NSNotification.Name.OnQuitButtonPressed, object: nil, userInfo: nil) } // This is done here in case we have multiple sources posting notifications // modifying the volume. func handleVolumeChanged(notification: Notification) { NSLog("Received \(notification.name)") let userInfo = notification.userInfo as! ValInfo let volume = userInfo["val"]! as Float currentVolume.stringValue = NSString(format: "%.2f", volume) as String } }
9eba8af6aaa050fa0dd26df14cc7b9fe
36.164835
141
0.678888
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/InputBar/SAIInputTextFieldItem.swift
mit
1
// // SAIInputTextFieldItem.swift // SAIInputBar // // Created by SAGESSE on 8/3/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit internal class SAIInputTextFieldItem: SAIInputItem { init(textView: UITextView, backgroundView: UIImageView) { super.init() _textView = textView _backgroundView = backgroundView _backgroundView.image = _SAInputDefaultTextFieldBackgroundImage } override var font: UIFont? { set { _cacheMinHeight = nil _textView.font = newValue } get { return _textView.font } } override var tintColor: UIColor? { set { return _textView.tintColor = newValue } get { return _textView.tintColor } } override var image: UIImage? { set { return _backgroundView.image = newValue } get { return _backgroundView.image } } var needsUpdateContent: Bool { let newValue = _textView.contentSize let oldValue = _cacheContentSize ?? _textView.contentSize if newValue.width != _textView.frame.width { return true } if newValue.height == oldValue.height { return false } if newValue.height <= _maxHeight { // 没有超出去 return true } if oldValue.height < _maxHeight { // 虽然己经超出去了, 但还没到最大值呢 return true } return false } var contentSize: CGSize { return size } override var size: CGSize { set { // don't set } get { if let size = _cacheSize { return size } let size = sizeThatFits() _cacheSize = size _cacheContentSize = _textView.contentSize return size } } func contentSizeChanged() { if needsUpdateContent { _cacheSize = nil } //self.setNeedsLayout() } func invalidateCache() { _cacheSize = nil _cacheContentSize = nil } func sizeThatFits() -> CGSize { var size = _textView.sizeThatFits(CGSize(width: _textView.bounds.width, height: CGFloat.greatestFiniteMagnitude)) //size.height = min(max(size.height, _minHeight), _maxHeight) size.height = min(size.height, _maxHeight) return size } var _maxHeight: CGFloat = 106 var _minHeight: CGFloat { if let height = _cacheMinHeight { return height } if let font = _textView.font { let edg = _textView.textContainerInset let mh = font.lineHeight + edg.top + edg.bottom _cacheMinHeight = mh return mh } return 0 } var _cacheMinHeight: CGFloat? var _cacheSize: CGSize? var _cacheContentSize: CGSize? weak var _textView: UITextView! weak var _backgroundView: UIImageView! }
d501aa409b8a79e176bbd0af5bcae01a
24.155738
121
0.543825
false
false
false
false
MxABC/swiftScan
refs/heads/master
Source/LBXScanViewStyle.swift
mit
1
// // LBXScanViewStyle.swift // swiftScan // // Created by xialibing on 15/12/8. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit /// 扫码区域动画效果 public enum LBXScanViewAnimationStyle { case LineMove // 线条上下移动 case NetGrid // 网格 case LineStill // 线条停止在扫码区域中央 case None // 无动画 } /// 扫码区域4个角位置类型 public enum LBXScanViewPhotoframeAngleStyle { case Inner // 内嵌,一般不显示矩形框情况下 case Outer // 外嵌,包围在矩形框的4个角 case On // 在矩形框的4个角上,覆盖 } public struct LBXScanViewStyle { // MARK: - 中心位置矩形框 /// 是否需要绘制扫码矩形框,默认YES public var isNeedShowRetangle = true /// 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比 public var whRatio: CGFloat = 1.0 /// 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移 public var centerUpOffset: CGFloat = 44 /// 矩形框(视频显示透明区)域离界面左边及右边距离,默认60 public var xScanRetangleOffset: CGFloat = 60 /// 矩形框线条颜色,默认白色 public var colorRetangleLine = UIColor.white /// 矩形框线条宽度,默认1 public var widthRetangleLine: CGFloat = 1.0 //MARK: - 矩形框(扫码区域)周围4个角 /// 扫码区域的4个角类型 public var photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Outer /// 4个角的颜色 public var colorAngle = UIColor(red: 0.0, green: 167.0 / 255.0, blue: 231.0 / 255.0, alpha: 1.0) /// 扫码区域4个角的宽度和高度 public var photoframeAngleW: CGFloat = 24.0 public var photoframeAngleH: CGFloat = 24.0 /// 扫码区域4个角的线条宽度,默认6,建议8到4之间 public var photoframeLineW: CGFloat = 6 //MARK: - 动画效果 /// 扫码动画效果:线条或网格 public var anmiationStyle = LBXScanViewAnimationStyle.LineMove /// 动画效果的图像,如线条或网格的图像 public var animationImage: UIImage? //MARK: - 非识别区域颜色, 默认 RGBA (0,0,0,0.5),范围(0--1) public var color_NotRecoginitonArea = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5) public init() { } }
c2988200ba85caa0988dbb39bdb29e31
22.307692
100
0.669967
false
false
false
false
dduan/swift
refs/heads/master
validation-test/Evolution/Inputs/struct_add_property.swift
apache-2.0
3
public func getVersion() -> Int { #if BEFORE return 0 #else return 1 #endif } #if BEFORE public struct AddStoredProperty { public init() { forth = "Chuck Moore" } public var forth: String public var languageDesigners: [String] { return [forth] } } #else public struct AddStoredProperty { public init() { forth = "Chuck Moore" lisp = "John McCarthy" c = "Dennis Ritchie" } public var forth: String public var lisp: String public var c: String public var languageDesigners: [String] { return [forth, lisp, c] } } #endif #if BEFORE var global: Int = 0 public struct ChangeEmptyToNonEmpty { public init() {} public var property: Int { get { return global } set { global = newValue } } } #else public struct ChangeEmptyToNonEmpty { public init() { property = 0 } public var property: Int } #endif public func getProperty(c: ChangeEmptyToNonEmpty) -> Int { return c.property }
5c7b2735afb173279aef62b2b483d1fd
12.472222
58
0.652577
false
false
false
false
Perfectorium/TaskTracker
refs/heads/master
TaskTracker/TaskTracker/Controllers/PFProjectsListViewController/PFProjectsListViewController.swift
mit
1
// // PRProjectsListViewController.swift // TaskTracker // // Created by Alex Tsonev on 23.06.17. // Copyright © 2017 Perfectorium. All rights reserved. // import UIKit private let reuseIdentifier = "PFProjectsListCollectionViewCell" class PFProjectsListViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { static func storyboardInstance() -> PFProjectsListViewController? { let storyboard = UIStoryboard(name: String(describing: self), bundle: nil) return storyboard.instantiateInitialViewController() as? PFProjectsListViewController } 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. } // MARK: - UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.frame.size.width/5.2 return CGSize(width: width, height: width) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PFProjectsListCollectionViewCell let labelText = "P\(indexPath.item)" cell.setupCell(withLabel: labelText, color: UIColor.randomColor()) return cell } func signOut() { PFAuthAdapter.signOut { (success) in if success { let appdelegate = UIApplication.shared.delegate as! AppDelegate let navigationVC = AppDelegate.createNavigationController() appdelegate.window!.rootViewController = navigationVC UserDefaults.standard.setValue(false, forKey: kIsSignedIn) } else { print("not succesful sign out") } } } }
bbb88adc25f8e0ff0036b88d0530e899
28.736842
109
0.582655
false
false
false
false
mackoj/iosMobileDeviceManager
refs/heads/master
MDM/PreviousUserViewController.swift
gpl-2.0
1
// // PreviousUserCollectionViewController.swift // MDM // // Created by Jeffrey Macko on 08/09/15. // Copyright (c) 2015 PagesJaunes. All rights reserved. // import UIKit import Parse struct PFObjectFake { let userInfo : PJUser let borrowedDevice : BorrowedDevice } typealias sectionCoordinatorType = Array< String > typealias borrowedDeviceListType = [String : Array< PFObjectFake > ] typealias dataControllerTupleType = (sectionCoordinatorType, borrowedDeviceListType) class PreviousUserViewController : UITableViewController { var sectionCoordinator : sectionCoordinatorType = [] var borrowedDeviceList : borrowedDeviceListType = borrowedDeviceListType() func generateBorrowedDeviceListFromParse(borrowedDevices: [BorrowedDevice], users: [PJUser]) -> dataControllerTupleType? { var sectionCoordinator : sectionCoordinatorType = [] var tmpBorrowedDeviceListType : borrowedDeviceListType = borrowedDeviceListType() var tmpObjtByDay : Array< PFObjectFake > = [] // remplir le section coordinator avec une liste de jour for aBorrowedDevice in borrowedDevices { if let tmpUpdatedAt : NSDate = aBorrowedDevice.updatedAt { let actualUpdatedAt = self.formatFromDate(tmpUpdatedAt) if !sectionCoordinator.contains(actualUpdatedAt) { sectionCoordinator.append(actualUpdatedAt) } } } // pour chaque section remplir la liste de device emprunté for aSectionIdx in sectionCoordinator { // filtrer la liste de device utiliser ce jour precis let filteredBorrowedArray = borrowedDevices.filter({ (aDevice) -> Bool in let tmpAdevice: BorrowedDevice = aDevice if let tmpUpdatedAt : NSDate = tmpAdevice.updatedAt { let actualUpdatedAt = self.formatFromDate(tmpUpdatedAt) if actualUpdatedAt == aSectionIdx { return true } } return false }) // recuperer la liste des utilisateus ayant emprunter un device ce jour et les coupler for aUser in users { for aBorrowedDevice in filteredBorrowedArray { if let userObjectId = aUser.objectId { if userObjectId == aBorrowedDevice.userId() { tmpObjtByDay.append(PFObjectFake(userInfo: aUser, borrowedDevice: aBorrowedDevice)) } } } } // remplir le tableau final tmpBorrowedDeviceListType[aSectionIdx] = tmpObjtByDay } return (sectionCoordinator, tmpBorrowedDeviceListType) } func formatFromDate(aDate : NSDate) -> String { let calendar = NSCalendar.currentCalendar() let components : NSDateComponents = calendar.components([NSCalendarUnit.Day , NSCalendarUnit.Month , NSCalendarUnit.Year], fromDate: aDate) let sectionIdx : String = "\(components.year)/\(components.month)/\(components.day)" return sectionIdx } func refreshCells() { print(__LINE__) // On remet tout a 0 self.borrowedDeviceList = borrowedDeviceListType() self.sectionCoordinator = [] print(__LINE__) // on charger les derniers BorrowedDevice let borrowedDeviceQuery = PFQuery(className: "BorrowedDevice") borrowedDeviceQuery.limit = 50 print(__LINE__) borrowedDeviceQuery.findObjectsInBackgroundWithBlock { (borrowedDevices, error) -> Void in print(__LINE__) // si tout ce passe bien... on charger les user lié a ces devices if let cleanedBorrowedDevices = borrowedDevices as! [BorrowedDevice]? { print(__LINE__) // On cherche les UserID let unfilteredUserIDs : Array<String> = cleanedBorrowedDevices.map { return $0.userId() } let userIDs = Array(Set(unfilteredUserIDs)) // On charge les user lié print(__LINE__) print(unfilteredUserIDs) print(userIDs) print(__LINE__) let pjUserQuery = PFQuery(className: "PJUser", predicate: NSPredicate(format: "objectId IN ", userIDs)) print(__LINE__) pjUserQuery.findObjectsInBackgroundWithBlock { (pjUsersDirty, errorUsers) -> Void in print(__LINE__) if let pjUsers = pjUsersDirty { print(__LINE__) // on trie et on nettoie if let deviceList = self.generateBorrowedDeviceListFromParse(cleanedBorrowedDevices, users: pjUsers as! [PJUser]) { print(__LINE__) self.sectionCoordinator = deviceList.0 self.borrowedDeviceList = deviceList.1 print(__LINE__) self.tableView.reloadData() } } } } } } // MARK override func viewWillAppear(animated: Bool) { self.refreshCells() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.sectionCoordinator.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let aSectionDate : String = self.sectionCoordinator[section] { return aSectionDate } return "" } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let aSectionDate : String = self.sectionCoordinator[section] { if let aSection : Array<PFObjectFake> = self.borrowedDeviceList[aSectionDate] { return aSection.count } } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(PreviousUserCustomCell.cellIdentifier()) as! PreviousUserCustomCell if let aSectionDate : String = self.sectionCoordinator[indexPath.section] { if let aSection : Array<PFObjectFake> = self.borrowedDeviceList[aSectionDate] { if let tmpfakeobject : PFObjectFake = aSection[indexPath.row] { if let stateSwitch = tmpfakeobject.borrowedDevice["broken"] as! Bool? { cell.deviceStateSwitch.on = stateSwitch } if let mail = tmpfakeobject.userInfo["mail"] as! String? { cell.loginUserLabel.text = mail } if let aDate = tmpfakeobject.borrowedDevice["updatedAt"] as! NSDate? { cell.dateLabel.text = aDate.description } } } } return cell } } class PreviousUserCustomCell : UITableViewCell { @IBOutlet weak var deviceStateSwitch: UISwitch! @IBOutlet weak var loginUserLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! static func cellIdentifier() -> String { return "customCellPikaPika" } }
544dc6c7bcb6e144ca332abd63792055
32.878788
144
0.663337
false
false
false
false
imodeveloperlab/ImoTableView
refs/heads/development
Carthage/Carthage/Checkouts/Nimble/Tests/NimbleTests/Matchers/PostNotificationTest.swift
mit
1
import XCTest import Nimble import Foundation final class PostNotificationTest: XCTestCase { let notificationCenter = NotificationCenter() func testPassesWhenNoNotificationsArePosted() { expect { // no notifications here! }.to(postNotifications(beEmpty())) } func testPassesWhenExpectedNotificationIsPosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) expect { self.notificationCenter.post(testNotification) }.to(postNotifications(equal([testNotification]), from: notificationCenter)) } func testPassesWhenAllExpectedNotificationsArePosted() { let foo = 1 as NSNumber let bar = 2 as NSNumber let n1 = Notification(name: Notification.Name("Foo"), object: foo) let n2 = Notification(name: Notification.Name("Bar"), object: bar) expect { self.notificationCenter.post(n1) self.notificationCenter.post(n2) }.to(postNotifications(equal([n1, n2]), from: notificationCenter)) } func testFailsWhenNoNotificationsArePosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) failsWithErrorMessage("expected to equal <[\(testNotification)]>, got no notifications") { expect { // no notifications here! }.to(postNotifications(equal([testNotification]), from: self.notificationCenter)) } } func testFailsWhenNotificationWithWrongNameIsPosted() { let n1 = Notification(name: Notification.Name("Foo"), object: nil) let n2 = Notification(name: Notification.Name(n1.name.rawValue + "a"), object: nil) failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") { expect { self.notificationCenter.post(n2) }.to(postNotifications(equal([n1]), from: self.notificationCenter)) } } func testFailsWhenNotificationWithWrongObjectIsPosted() { let n1 = Notification(name: Notification.Name("Foo"), object: nil) let n2 = Notification(name: n1.name, object: NSObject()) failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") { expect { self.notificationCenter.post(n2) }.to(postNotifications(equal([n1]), from: self.notificationCenter)) } } func testPassesWhenExpectedNotificationEventuallyIsPosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) expect { deferToMainQueue { self.notificationCenter.post(testNotification) } }.toEventually(postNotifications(equal([testNotification]), from: notificationCenter)) } #if os(macOS) func testPassesWhenAllExpectedNotificationsarePostedInDistributedNotificationCenter() { let center = DistributedNotificationCenter() let n1 = Notification(name: Notification.Name("Foo"), object: "1") let n2 = Notification(name: Notification.Name("Bar"), object: "2") expect { center.post(n1) center.post(n2) }.toEventually(postDistributedNotifications(equal([n1, n2]), from: center, names: [n1.name, n2.name])) } #endif }
96cd5864bb607880d3689af512c1d282
39.851852
110
0.646721
false
true
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Reading-阅读/Controller/Detail/JENSerialDetailViewController.swift
mit
1
// // JENSerialDetailViewController.swift // ONE_Swift // // Created by 任玉祥 on 16/5/4. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENSerialDetailViewController: JENReadDetailViewController { override var readType: JENReadType { return .Serial } override func viewDidLoad() { super.viewDidLoad() title = "连载" } override func loadRealtedData() { super.loadRealtedData() JENLoadData.loadReadSerialRelated("related/serial/" + detail_id) { (resObj) in if resObj.count > 0 { self.relatedItems = resObj } } } } extension JENSerialDetailViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) if indexPath.section == 0 && relatedItems.count > 0 { let serialDetailVC = JENSerialDetailViewController() let serialItem = relatedItems[indexPath.row] as! JENReadSerialItem guard let content_id = serialItem.content_id else { return } serialDetailVC.detail_id = content_id navigationController?.pushViewController(serialDetailVC, animated: true) } } }
3c682241304865f39eb8a6cbd14dd963
28.909091
101
0.65019
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00245-swift-constraints-constraintgraph-computeconnectedcomponents.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse enum S<T> : P { func f class func b() { struct c { so } protocol e { typealias h } func a(b: Int = 0) { } let c = a c() func b(c) -> <d>(() -> d) { } import Foundation class A { priv self.c = c } } im D : C { typealias Fr e: Int -> Int = { return $0 } let d: Int = { ce)
095c05bafe184018eb0ffc60010352bc
20.69697
78
0.613128
false
false
false
false
flodolo/firefox-ios
refs/heads/main
WidgetKit/OpenTabs/TabProvider.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import SwiftUI import WidgetKit import UIKit import Combine // Tab provider for Widgets struct TabProvider: TimelineProvider { public typealias Entry = OpenTabsEntry var tabsDict: [String: SimpleTab] = [:] func placeholder(in context: Context) -> OpenTabsEntry { OpenTabsEntry(date: Date(), favicons: [String: Image](), tabs: []) } func getSnapshot(in context: Context, completion: @escaping (OpenTabsEntry) -> Void) { let allOpenTabs = SimpleTab.getSimpleTabs() let openTabs = allOpenTabs.values.filter { !$0.isPrivate } var tabFaviconDictionary = [String: Image]() let simpleTabs = SimpleTab.getSimpleTabs() for (_, tab) in simpleTabs { guard !tab.imageKey.isEmpty else { continue } let fetchedImage = FaviconFetcher.getFaviconFromDiskCache(imageKey: tab.imageKey) let bundledFavicon = getBundledFavicon(siteUrl: tab.url) let letterFavicon = FaviconFetcher.letter(forUrl: tab.url ?? URL(string: "about:blank")!) let image = bundledFavicon ?? fetchedImage ?? letterFavicon tabFaviconDictionary[tab.imageKey] = Image(uiImage: image) } let openTabsEntry = OpenTabsEntry(date: Date(), favicons: tabFaviconDictionary, tabs: openTabs) completion(openTabsEntry) } func getBundledFavicon(siteUrl: URL?) -> UIImage? { guard let url = siteUrl else { return nil } // Get the bundled favicon if available guard let bundled = FaviconFetcher.getBundledIcon(forUrl: url), let image = UIImage(contentsOfFile: bundled.filePath) else { return nil } return image } func getTimeline(in context: Context, completion: @escaping (Timeline<OpenTabsEntry>) -> Void) { getSnapshot(in: context, completion: { openTabsEntry in let timeline = Timeline(entries: [openTabsEntry], policy: .atEnd) completion(timeline) }) } } struct OpenTabsEntry: TimelineEntry { let date: Date let favicons: [String: Image] let tabs: [SimpleTab] }
0aeaf02fce723b2fdfdf47d3549d1dd9
37.333333
145
0.666957
false
false
false
false
DannyvanSwieten/SwiftSignals
refs/heads/master
GameEngine/Texture.swift
gpl-3.0
1
// // File.swift // SwiftEngine // // Created by Danny van Swieten on 2/16/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import Foundation import AppKit enum TextureType { case TwoDimensional case Cube } class Texture { var desc = MTLTextureDescriptor() var texture: MTLTexture! = nil init(image: RawImage, type: TextureType){ loadFromImage(image, type: type) } init(filePath: String, type: TextureType){ loadFromFile(filePath, type: type) } private func loadFromFile(path: String, type: TextureType) { let image = RawImage(pathToFile: path) loadFromImage(image, type: type) } private func loadFromImage(image: RawImage, type: TextureType) { switch(type) { case .Cube: desc = MTLTextureDescriptor.textureCubeDescriptorWithPixelFormat(.RGBA8Unorm, size: image.width, mipmapped: false) texture = GameEngine.instance.device?.newTextureWithDescriptor(desc) for slice in 0..<6 { let region = MTLRegionMake2D(0, 0, image.width, image.width) let sliceSize = image.width * image.width texture.replaceRegion(region, mipmapLevel: texture.mipmapLevelCount, slice: slice, withBytes: image.data.advancedBy(slice * sliceSize * image.bytesPerPixel), bytesPerRow: image.bytesPerRow, bytesPerImage: sliceSize * image.bytesPerPixel) } case .TwoDimensional: desc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(.RGBA8Unorm, width: image.width, height: image.height, mipmapped: true) } } }
4b3feff6b20768017006de3ba2e73341
31.538462
253
0.647546
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Model/DataModel/SLVSellPriceCalculation.swift
mit
1
// // SLVSellPriceCalculation.swift // selluv-ios // // Created by 조백근 on 2017. 1. 12.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation /* 판매가 1,000,000 maxAdjustmentAmount 최대 정산금액 : 정산원금 + 최대 적립금 depositAmount 입금액 : 정산원금 selluvMaxAccumulatedAmount 최대 적립금 + 페이백 : 셀럽 머니 구매 적립금 + 거래 후기 작성 + SNS 공유 이벤트 + 프로모션 코드 페이백 paymentPrincipalAmount 구매자 결제 원금 : 판매가 (1,000,000) creditCardFee 신용카드 결제 수수료(결제원금 기준) : 3% (30,000) selluvFee 셀럽 서비스 수수료(결제원금 기준) : 9% (90,000) adjustmentPrincipalAmount 정산원금 : 구매자 결제 원금 - (신용카드 결제 수수료 + 셀럽 서비스 수수료)  (880,000) selluvMoneyPurchasedPoint 셀럽 머니 구매 적립금(정산원금 기준) : 2% (17,600) selluvPurchasedReviewPoint 거래 후기 작성 : 5,000 selluvPurchasedSNSSharePoint SNS 공유 이벤트 : 2,000 (공유 항목 당) selluvPromotionCodePayback 프로모션 코드 페이백(정산원금 기준) : 31. 쿠폰 코드 검증 [GET] /api/coupons API에 따름 -> 기본 3% 처리하고 입력값에 따라서 api호출해서 변경 depositAmount 입금액 : 정산원금 adjustmentAmount 정산금 : 입금액 + 최대 적립금+페이백 selluvMaxSNSSharePoint 공유이벤트 최대 적립금 : 공유이벤트 2000원 최대 5 -> 10,000원 api 퍼센트(계산) 금액(더하기) */ class SLVSellPriceCalculation: NSObject { static let shared = SLVSellPriceCalculation() private var updateAllBlock: (()->())? private var updateCouponBlock: (()->())? private var sellMoney: String? {//판매가 (문자) didSet { let numText = String.removeFormAmount(value: sellMoney!) let num = Float(numText) productAmount = num! } } private var productAmount: Float = 0//판매가 (숫자) 계산용 private var coupon: Coupon? private var isValidCoupon: Bool = false override init() { super.init() } public func updatePrice(sell: String) { self.sellMoney = sell if self.updateAllBlock != nil { self.updateAllBlock!() } } public func setupUpdateAll(block: @escaping (() -> ())) { self.updateAllBlock = block } public func setupUpdateCoupon(block: @escaping (() -> ())) { self.updateCouponBlock = block } public func setupCoupon(coupon: Coupon) { self.coupon = coupon guard coupon.useKind == "sell" else { return } if coupon.startDt != nil && coupon.endDt != nil { let isValidPeriod = Date.isBetween(start: coupon.startDt!, end: coupon.endDt!) self.isValidCoupon = isValidPeriod } if self.isValidCoupon == true { if self.updateCouponBlock != nil { self.updateCouponBlock!()// // adjustmentAmount,selluvMaxAccumulatedAmount, selluvPromotionCodePayback } } } public func myCoupon() -> Coupon? { if self.isValidCoupon { return self.coupon } else { return nil } } // 판매가 func productPriceAmount() -> Float { return self.productAmount } // 구매자 결제 원금 : 판매가 (1,000,000) func paymentPrincipalAmount() -> (String, Float) { let text = String.decimalAmountWithForm(value: self.productAmount, pointCount: 0) return (text, self.productAmount) } // 신용카드 결제 수수료(결제원금 기준) : 3% (30,000) func creditCardFee() -> (String, Float) { let fee = self.productAmount * 0.03 let text = String.decimalAmountWithForm(value: fee, pointCount: 0) return (text, fee) } // 셀럽 서비스 수수료(결제원금 기준) : 9% (90,000) func selluvFee() -> (String, Float) { let fee = self.productAmount * 0.09 let text = String.decimalAmountWithForm(value: fee, pointCount: 0) return (text, fee) } // 정산원금 : 구매자 결제 원금 - (신용카드 결제 수수료 + 셀럽 서비스 수수료)  (880,000) func adjustmentPrincipalAmount() -> (String, Float) { let principal = self.productAmount - (self.creditCardFee().1 + self.selluvFee().1) let text = String.decimalAmountWithForm(value: principal, pointCount: 0) return (text, principal) } // 셀럽 머니 구매 적립금(정산원금 기준) : 2% (17,600) func selluvMoneyPurchasedPoint() -> (String, Float) { let point = self.adjustmentPrincipalAmount().1 * 0.02 let text = String.decimalAmountWithForm(value: point, pointCount: 0) return (text, point) } // 거래 후기 작성 : 5,000 func selluvPurchasedReviewPoint() -> (String, Float) { let point = Float(5000) let text = String.decimalAmountWithForm(value: point, pointCount: 0) return (text, point) } // SNS 공유 이벤트 : 2,000 (공유 항목 당) func selluvPurchasedSNSSharePoint() -> (String, Float) { let point = Float(2000) let text = String.decimalAmountWithForm(value: point, pointCount: 0) return (text, point) } // 프로모션 코드 페이백(정산원금 기준) : 31. 쿠폰 코드 검증 [GET] /api/coupons API에 따름 -> 기본 3% 처리하고 입력값에 따라서 api호출해서 변경 // api 퍼센트(계산) / 금액(더하기) func selluvPromotionCodePayback() -> (String, Float) { if self.isValidCoupon == false { let payback = self.adjustmentPrincipalAmount().1 * 0.03 let text = String.decimalAmountWithForm(value: payback, pointCount: 0) return (text, payback) } else { let kind = self.coupon?.kind if kind == "percent" { let payback = self.adjustmentPrincipalAmount().1 * Float((self.coupon?.amount)!) / Float(100) let text = String.decimalAmountWithForm(value: payback, pointCount: 0) return (text, payback) } else { let payback = Float((self.coupon?.amount)!) let text = String.decimalAmountWithForm(value: payback, pointCount: 0) return (text, payback) } } } // selluvMaxSNSSharePoint 공유이벤트 최대 적립금 : 공유이벤트 2000원 최대 5 -> 10,000원 func selluvMaxSNSSharePoint() -> (String, Float) { let point = Float(10000) let text = String.decimalAmountWithForm(value: point, pointCount: 0) return (text, point) } // maxAdjustmentAmount 최대 정산금액 : 정산원금 + 최대 적립금 func maxAdjustmentAmount() -> (String, Float) { let amount = self.adjustmentPrincipalAmount().1 + self.selluvMaxSNSSharePoint().1 let text = String.decimalAmountWithForm(value: amount, pointCount: 0) return (text, amount) } // selluvMaxAccumulatedAmount 최대 적립금 + 페이백 : 셀럽 머니 구매 적립금 + 거래 후기 작성 + SNS 공유 이벤트 + 프로모션 코드 페이백 func selluvMaxAccumulatedAmount() -> (String, Float) { let point = self.selluvMoneyPurchasedPoint().1 + self.selluvPurchasedReviewPoint().1 + self.selluvMaxSNSSharePoint().1 + self.selluvPromotionCodePayback().1 let text = String.decimalAmountWithForm(value: point, pointCount: 0) return (text, point) } // depositAmount 입금액 : 정산원금 func depositAmount() -> (String, Float) { let amount = self.adjustmentPrincipalAmount().1 let text = String.decimalAmountWithForm(value: amount, pointCount: 0) return (text, amount) } // adjustmentAmount 정산금 : 입금액 + 최대 적립금+페이백 func adjustmentAmount() -> (String, Float) { let amount = self.depositAmount().1 + self.selluvMaxSNSSharePoint().1 + self.selluvPromotionCodePayback().1 let text = String.decimalAmountWithForm(value: amount, pointCount: 0) return (text, amount) } }
1c77224e1793cb1b23256e0df889e2c4
34.897059
164
0.611908
false
false
false
false
anisimovsergey/lumino-ios
refs/heads/master
Lumino/WebSocketClient.swift
mit
1
// // WebSocketAccess.swift // Lumino // // Created by Sergey Anisimov on 01/05/2017. // Copyright © 2017 Sergey Anisimov. All rights reserved. // import Foundation import Starscream import MulticastDelegateSwift struct RequestKey : Hashable { private let requestType: String private let resource: String init(_ requestType: String,_ resource: String) { self.requestType = requestType self.resource = resource } static func ==(lhs: RequestKey, rhs: RequestKey) -> Bool { return lhs.requestType == rhs.requestType && lhs.resource == rhs.resource } var hashValue: Int { return requestType.hashValue ^ resource.hashValue } } protocol WebSocketConnectionDelegate: class { func websocketDidConnect(client: WebSocketClient) func websocketDidDisconnect(client: WebSocketClient) } protocol WebSocketCommunicationDelegate: class { func websocketOnColorRead(client: WebSocketClient, color: Color) func websocketOnColorUpdated(client: WebSocketClient, color: Color) func websocketOnSettingsRead(client: WebSocketClient, settings: Settings) func websocketOnSettingsUpdated(client: WebSocketClient, settings: Settings) } class WebSocketClient: NSObject, WebSocketDelegate, WebSocketPongDelegate, NetServiceDelegate { private static let pingInterval = 3.0 private static let pongTimeout = 2.0 private static let disconnectTimeout = 1.0 private static let responseTime = 0.2 private static let coolingTime = 0.02 private let readRequestType = "read" private let updateRequestType = "update" private let updatedEventType = "updated" private let serializer: SerializationService private let service: NetService! private var socket: WebSocket! private var pingTimer: Timer! private var pongTimer: Timer! private var commTimer: Timer! private var pendingRequests: Dictionary<RequestKey, Request> = [:] private var lastID: String? = nil private var pingCounter: uint = 0 var connectionDelegate = MulticastDelegate<WebSocketConnectionDelegate>() var communicationDelegate = MulticastDelegate<WebSocketCommunicationDelegate>() var name: String { get { return service.name } } var isConnected: Bool { get { return socket != nil && socket.isConnected } } init(_ serializer: SerializationService,_ service: NetService) { self.serializer = serializer self.service = service } func connect() { if service.port == -1 { print("resolving service \(service.name) ...") service.delegate = self service.resolve(withTimeout: 10) } else { print("connecting to service \(service.name) ...") self.socket = WebSocket(url: URL(string: "ws://\(service.hostName!)/ws")!) self.socket.delegate = self self.socket.pongDelegate = self socket.connect() } } func netServiceDidResolveAddress(_ sender: NetService) { service.delegate = nil connect() } func disconnect() { print("disconnecting from service \(service.name) ...") socket.disconnect(forceTimeout: WebSocketClient.disconnectTimeout) } func requestColor() { print("requesting color from \(service.name) ...") self.sendRequest(requestType: readRequestType, resource: Color.resourceId, content: nil) } func updateColor(_ color: Color) { self.sendRequest(requestType: updateRequestType, resource: Color.resourceId, content: color) } func requestSettings() { print("requesting settings from \(service.name) ...") self.sendRequest(requestType: readRequestType, resource: Settings.resourceId, content: nil) } func updateSettings(_ settings: Settings) { self.sendRequest(requestType: updateRequestType, resource: Settings.resourceId, content: settings) } func websocketDidConnect(socket: WebSocket) { print("connected to service \(service.name)") clearPendingRequests() sendPing() connectionDelegate |> { delegate in delegate.websocketDidConnect(client: self) } } func clearPendingRequests() { self.lastID = nil self.pendingRequests.removeAll() } func sendPing() { print("send ping to service \(service.name)") self.socket.write(ping: Data()) self.pongTimer = Timer.scheduledTimer(timeInterval: WebSocketClient.pongTimeout, target: self, selector: #selector(self.noPong), userInfo: nil, repeats: false) } func noPong() { pingCounter += 1; if (pingCounter > 3) { disconnect() } else { sendPing() } } public func websocketDidReceivePong(socket: WebSocket, data: Data?) { print("received pong from service \(service.name)") pingCounter = 0; self.pongTimer.invalidate() self.pingTimer = Timer.scheduledTimer(timeInterval: WebSocketClient.pingInterval, target: self, selector: #selector(self.sendPing), userInfo: nil, repeats: false) } func websocketDidDisconnect(socket: WebSocket, error: NSError?) { print("disconnected from service \(service.name)") if self.pingTimer != nil { self.pingTimer.invalidate() } if self.pongTimer != nil { self.pongTimer.invalidate() } if self.commTimer != nil { self.commTimer.invalidate() } connectionDelegate |> { delegate in delegate.websocketDidDisconnect(client: self) } } func websocketDidReceiveMessage(socket: WebSocket, text: String) { switch serializer.deserializeFromString(text) { case let .Value(obj): switch obj { case let response as Response: processResponse(response) case let event as Event: processEvent(event) default: break } default: break } } func websocketDidReceiveData(socket: WebSocket, data: Data) { } private func processResponse(_ response: Response) { if self.lastID == response.id { self.commTimer.invalidate() self.commTimer = Timer.scheduledTimer(timeInterval: WebSocketClient.coolingTime, target: self, selector: #selector(self.coolingEnd), userInfo: nil, repeats: false) } if response.requestType == readRequestType { switch response.content { case let color as Color: print("received color from \(service.name)") communicationDelegate |> { delegate in delegate.websocketOnColorRead(client: self, color: color) } case let settings as Settings: print("received settings from \(service.name)") communicationDelegate |> { delegate in delegate.websocketOnSettingsRead(client: self, settings: settings) } default: break } } } private func processEvent(_ event: Event) { if event.eventType == updatedEventType { switch event.content { case let color as Color: communicationDelegate |> { delegate in delegate.websocketOnColorUpdated(client: self, color: color) } case let settings as Settings: communicationDelegate |> { delegate in delegate.websocketOnSettingsUpdated(client: self, settings: settings) } default: break } } } private func getRandomID() -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< 6 { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomString += NSString(characters: &nextChar, length: 1) as String } return randomString } private func sendRequest(requestType: String, resource: String, content: Serializible?) { let request = Request(id: getRandomID(), requestType: requestType, resource: resource, content: content) pendingRequests[RequestKey(requestType, resource)] = request sendFromPending(); } private func sendFromPending() { if self.lastID == nil { if let request = pendingRequests.first { _ = sendRequest(request: request.value) } } } private func sendRequest(request: Request) { self.lastID = request.id switch self.serializer.serializeToString(request) { case let .Value(json): socket.write(string: json) case .Error: return } self.commTimer = Timer.scheduledTimer(timeInterval: WebSocketClient.responseTime, target: self, selector: #selector(self.noResponse), userInfo: nil, repeats: false) } func noResponse() { print("no response, resending...") self.lastID = nil sendFromPending() } func coolingEnd() { _ = pendingRequests.popFirst() self.lastID = nil sendFromPending() } }
bebb5770f94445c6c164dd90f3d7b190
32.366197
175
0.627058
false
false
false
false
MartinOSix/DemoKit
refs/heads/master
dSwift/SwiftDemoKit/SwiftDemoKit/SystemDownUpPullRefreshViewController.swift
apache-2.0
1
// // SystemDownUpPullRefreshViewController.swift // SwiftDemoKit // // Created by runo on 17/3/17. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit class SystemDownUpPullRefreshViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let tableview = UITableView.init(frame: CGRect.zero, style: .plain) let refreshControl = UIRefreshControl()//只能下拉不能上拉 var dataSourceArr = ["first"] override var prefersStatusBarHidden: Bool{ return false } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white tableview.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight) tableview.separatorStyle = .none tableview.delegate = self tableview.dataSource = self tableview.tableFooterView = UIView.init()//这样不显示多余的view tableview.refreshControl = refreshControl refreshControl.backgroundColor = UIColor.cyan refreshControl.attributedTitle = NSAttributedString(string: "最后一次更新:\(NSDate())",attributes: [NSForegroundColorAttributeName: UIColor.black])//文字的颜色 refreshControl.tintColor = UIColor.orange//菊花颜色 refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) view.addSubview(tableview) } func refreshData() { DispatchQueue.global().async { sleep(1) print("refreshData") self.dataSourceArr.append("\(NSDate())") self.refreshControl.endRefreshing() self.tableview .reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSourceArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableview.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell.init(style: .default, reuseIdentifier: "cell") cell.textLabel?.text = dataSourceArr[indexPath.row] return cell } }
a9171125bbe935ba3a96ddacf78ab061
32.609375
156
0.662018
false
false
false
false
KerryJava/ios-charts
refs/heads/master
Charts/Classes/Data/ChartData.swift
apache-2.0
3
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } if self is ScatterChartData { // In scatter chart it makes sense to have more than one y-value value for an x-index return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(start start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis let firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis let firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += _dataSets[i].yValueSum } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// - returns: the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// - returns: the average value across all entries in this Data object (all entries from the DataSets this data object holds) public var average: Double { return yValueSum / Double(yValCount) } /// - returns: the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// - returns: the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// - returns: the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// - returns: the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// - returns: the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// - returns: the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// - returns: the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue initialize(_dataSets) } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// /// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.** /// /// - parameter dataSets: the DataSet array to search /// - parameter type: /// - parameter ignorecase: if true, the search is not case-sensitive /// - returns: the index of the DataSet Object with the given label. Sensitive or not. internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// - returns: the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// - returns: the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// - parameter highlight: /// - returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.** /// /// - parameter label: /// - parameter ignorecase: /// - returns: the DataSet Object with the given label. Sensitive or not. public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { let index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } let d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { let val = e.value let set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { let val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. /// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { let set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } /// - returns: the first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found. public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } /// - returns: the first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found. public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// - returns: all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { let clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. /// If set to true, this means that values can be highlighted programmatically or by touch gesture. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. /// - returns: true if so, false if not. public func contains(entry entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. /// - returns: true if so, false if not. public func contains(dataSet dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// - returns: the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
905b0bebe984b3c7063a167418fe0ec4
26.086225
169
0.480026
false
false
false
false
Idomeneus/duo-iOS
refs/heads/master
Duo/Duo/QuestionsService.swift
mit
1
// // QuestionsService.swift // Duo // // Created by Bobo on 10/17/15. // Copyright © 2015 Boris Emorine. All rights reserved. // import Foundation import CoreData struct QuestionsService { static func getQuestionsForCategory(category: Enums.questionsCategory, inManagedObjectContext context:NSManagedObjectContext, withCompletion completion:((questions: List?, error: NSError?) -> Void)?) { getQuestionsDictionaryForCategory(category) { (questionsDict, error) -> Void in if (error != nil) { completion?(questions: nil, error: error!) return } let questions: List = List.existingOrNewListWithDictionary(questionsDict!, inManageObjectContext: context) completion?(questions: questions, error: nil) } } static func getQuestionsDictionaryForCategory(category: Enums.questionsCategory, withCompletion completion: ((questionsDict: [String: AnyObject]?, error: NSError?) -> Void)?) { let URL: NSURL = Router.questionsURLWithParameters(nil) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(URL) { (data, response, error) -> Void in dispatch_async(dispatch_get_main_queue()) { if (error != nil) { completion?(questionsDict: nil, error: error) return } let response: NSHTTPURLResponse? = response as? NSHTTPURLResponse if (response != nil && data != nil) { if (response!.statusCode == 200) { if let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String: AnyObject] { completion?(questionsDict: dict, error: nil) return } else { completion?(questionsDict: nil, error: NSError(domain: "duo.main", code: 0, userInfo: [NSLocalizedDescriptionKey: "An unexpected error occured"])) return } } else { if let dict = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String: AnyObject] { completion?(questionsDict: nil, error: NSError(domain: "duo.main", code: response!.statusCode, userInfo: [NSLocalizedDescriptionKey: dict!["message"] as! String])) return } else { completion?(questionsDict: nil, error: NSError(domain: "duo.main", code: response!.statusCode, userInfo: [NSLocalizedDescriptionKey: "An unexpected error occured"])) return } } } else { completion?(questionsDict: nil, error: NSError(domain: "duo.main", code: 0, userInfo: [NSLocalizedDescriptionKey: "An unexpected error occured"])) return } } } task.resume() } }
d89193d3d3ffa22afb5d6bea775240c4
45.585714
205
0.552454
false
false
false
false
nkirby/Humber
refs/heads/master
_lib/HMCore/_src/Router/RoutePermission.swift
mit
1
// ======================================================= // HMCore // Nathaniel Kirby // ======================================================= import Foundation // ======================================================= public enum RoutePermission { case Internal }
b471f49cc4b9d82520e2b7ebca134ebd
22.083333
58
0.263538
false
false
false
false
finngaida/applemusic.info
refs/heads/master
Apple Music/ViewController.swift
mit
1
// // ViewController.swift // Apple Music // // Created by Finn Gaida on 24.06.15. // Copyright (c) 2015 Finn Gaida. All rights reserved. // import UIKit class Song { var title: String? var artist: String? var occasion: String? var date: NSDate? init(title: String?, artist: String?, occasion: String?, date: String?) { self.title = title ?? "No title availble" self.artist = artist ?? "No known artist" self.occasion = occasion ?? "Occasion unknown" if let dateStr = date { let format = NSDateFormatter() if (dateStr.characters.count == 4) { format.dateFormat = "yyyy" self.date = format.dateFromString(dateStr) } else if (dateStr.characters.count == 7) { format.dateFormat = "yyyy/MM" self.date = format.dateFromString(dateStr) } else if (dateStr.characters.count == 10) { format.dateFormat = "yyyy/MM/dd" self.date = format.dateFromString(dateStr) } else { self.date = nil } } } } class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var data = [Song]() override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") parseData({Void in self.tableView.reloadData() }) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { lazyLoad(data[indexPath.row], handler: { (img, uri, url) -> Void in print("URI is \(uri)") if (UIApplication.sharedApplication().canOpenURL(uri!)) { UIApplication.sharedApplication().openURL(uri!) } else { UIApplication.sharedApplication().openURL(url!) } }) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") //self.tableView.dequeueReusableCellWithIdentifier("Cell")! as! UITableViewCell let song = data[indexPath.row] as Song // TODO: lazyload images let cover = UIImageView(frame: CGRectMake(20, 20, 60, 60)) cell.contentView.addSubview(cover) lazyLoad(song, handler: {(image: UIImage?, uri, url) in if let img = image {cover.image = img} }) let title = UILabel(frame: CGRectMake(100, 15, cell.contentView.frame.width-40, 30)) title.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) if let ttl = song.title {title.text = ttl} cell.contentView.addSubview(title) let artist = UILabel(frame: CGRectMake(100, 40, cell.contentView.frame.width-40, 20)) artist.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) if let art = song.artist {artist.text = art} cell.contentView.addSubview(artist) let occasion = UILabel(frame: CGRectMake(100, 60, cell.contentView.frame.width-40, 20)) occasion.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) if let occ = song.occasion {occasion.text = occ} cell.contentView.addSubview(occasion) return cell } func parseData(handler: Void -> Void) { let path = NSBundle.mainBundle().pathForResource("music", ofType: "csv") if let unwrappedpath = path { let content: String? do { content = try String(contentsOfFile: unwrappedpath, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { content = nil print("There was an error: \(error1)") } let lines = content?.componentsSeparatedByString("\n") for segment in lines! { let columns = (segment as String).componentsSeparatedByString(",") data.append(Song(title: columns[2], artist: columns[3], occasion: columns[1], date: columns[0])) } data.removeAtIndex(0) // this is the headlines: Title, Artist, Date, ... handler() } } func lazyLoad(song: Song, handler: (UIImage?, NSURL?, NSURL?) -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let url = "https://api.spotify.com/v1/search?type=track&q=\(song.title!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)" let data = NSData(contentsOfURL: NSURL(string: url as String)!) var dict: Dictionary<String, AnyObject>? do { dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as? Dictionary<String, AnyObject> } catch { print("There was an error here") } var imgUrl: String? var spotifyUri: String? var spotifyUrl: String? // let's walk the safe path if let tracks: AnyObject = dict!["tracks"] { //print(tracks) if let items: AnyObject? = tracks["items"] { //print(items!.count, appendNewline: false) if items?.count > 0 { if let first: AnyObject? = items![0] { //print(first) spotifyUri = first!["uri"] as? String if let external: AnyObject? = first!["external_urls"] { spotifyUrl = external!["spotify"] as? String } if let album: AnyObject? = first!["album"] { //print(album) if let images: AnyObject? = album!["images"] { //print(images) if let smallest: AnyObject = images![images!.count - 1] { //print(smallest) if let url: AnyObject? = smallest["url"] { print(url, appendNewline: false) imgUrl = url as? String } } } } } } } } // that didn't work too well... here's the dirty one: //imgUrl = dict!["tracks"]!["items"]![0]!["album"]!["images"]![2]!["url"] if let img = imgUrl { dispatch_async(dispatch_get_main_queue()) { handler(UIImage(data: NSData(contentsOfURL: NSURL(string: img)!)!), NSURL(string: spotifyUri!), NSURL(string: spotifyUrl!)) } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9756185e913e3da300a0ce0a60a17f57
35.899123
173
0.49685
false
false
false
false
zerovagner/Desafio-Mobfiq
refs/heads/master
desafioMobfiq/desafioMobfiq/SubcategoryTableViewController.swift
mit
1
// // SubcategoryTableViewController.swift // desafioMobfiq // // Created by Vagner Oliveira on 6/16/17. // Copyright © 2017 Vagner Oliveira. All rights reserved. // import UIKit class SubcategoryTableViewController: UITableViewController { var baseCategory: Category? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = baseCategory?.title self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (baseCategory?.subcategories?.count)! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "subcategoryCell", for: indexPath) as! SubcategoryTableViewCell cell.setUp(fromCategory: (baseCategory?.subcategories?[indexPath.row])!) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "subcategoryProductSegue", sender: baseCategory?.subcategories?[indexPath.row]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "subcategoryProductSegue" { if let destination = segue.destination as? ProductViewController { if let category = sender as? Category { destination.apiQuery = category.apiQuery! } } } } }
aa91a715f92f7f9d340e280afc5b6a88
29.785714
128
0.720998
false
false
false
false
ichiko/UnitTestGenerator
refs/heads/master
UnitTestGeneratorPlugin/SourceEditorCommand.swift
mit
1
// // SourceEditorCommand.swift // UnitTestGeneratorPlugin // // Created by ichiko-moro on 2017/03/04. // Copyright © 2017年 ichiko-moro. All rights reserved. // import Foundation import XcodeKit class SourceEditorCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { // Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure. // Ref.) https://ez-net.jp/article/83/1AuGcndM/YL1DSTNKXeYD/ // ソースコードの編集が可能なバッファー元。 let textBuffer = invocation.buffer // ソースコードの各行を格納してあるNSMutableArray。各要素は Any型。 let lines = textBuffer.lines print(lines) // TODO: エラー時はErrorを渡す。 // let selections = textBuffer.selections // guard (selections.firstObject as? XCSourceTextRange) != nil else { // completionHandler(NSError(domain: "SampleExtension", code: 401, userInfo: ["reason": "text not selected"])) // return // } // TOOD: 各行をParseして、XCTestCaseファイル(既に存在している前提)にテストメソッドを新規作成できるようにする let parser = SwiftCodeParser() let result = parser.parse(source: textBuffer.completeBuffer) let generator = CodeGenerator() let parsedResult = generator.generateTestClass(fromClass: result[0]) self.runCopyCommand(result: parsedResult) // 処理が完了時or何もしなかった時はHandlerにnilを渡す。 completionHandler(nil) } // UNIXコマンドでパース結果をクリップボードにコピーする func runCopyCommand(result: String) { let pipe = Pipe() var task = Process() task.launchPath = "/bin/echo" task.standardOutput = pipe task.arguments = [result] task.launch() task.waitUntilExit() task = Process() task.launchPath = "/usr/bin/pbcopy" task.arguments = ["-c", String(format:"%@", self)] task.standardInput = pipe task.launch() task.waitUntilExit() } }
9e52005fd3af4754f3e6d10e9eea786f
33.816667
133
0.638583
false
false
false
false
justindarc/firefox-ios
refs/heads/master
Extensions/Today/TodayViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import NotificationCenter import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger struct TodayStrings { static let NewPrivateTabButtonLabel = NSLocalizedString("TodayWidget.NewPrivateTabButtonLabel", tableName: "Today", value: "New Private Tab", comment: "New Private Tab button label") static let NewTabButtonLabel = NSLocalizedString("TodayWidget.NewTabButtonLabel", tableName: "Today", value: "New Tab", comment: "New Tab button label") static let GoToCopiedLinkLabel = NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard") } private struct TodayUX { static let privateBrowsingColor = UIColor(rgb: 0xcf68ff) static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0) static let linkTextSize: CGFloat = 10.0 static let labelTextSize: CGFloat = 14.0 static let imageButtonTextSize: CGFloat = 14.0 static let copyLinkImageWidth: CGFloat = 23 static let margin: CGFloat = 8 static let buttonsHorizontalMarginPercentage: CGFloat = 0.1 } @objc (TodayViewController) class TodayViewController: UIViewController, NCWidgetProviding { var copiedURL: URL? fileprivate lazy var newTabButton: ImageButtonWithLabel = { let imageButton = ImageButtonWithLabel() imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside) imageButton.label.text = TodayStrings.NewTabButtonLabel let button = imageButton.button button.setImage(UIImage(named: "new_tab_button_normal")?.withRenderingMode(.alwaysTemplate), for: .normal) button.setImage(UIImage(named: "new_tab_button_highlight")?.withRenderingMode(.alwaysTemplate), for: .highlighted) let label = imageButton.label label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize) imageButton.sizeToFit() return imageButton }() fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = { let imageButton = ImageButtonWithLabel() imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside) imageButton.label.text = TodayStrings.NewPrivateTabButtonLabel let button = imageButton.button button.setImage(UIImage(named: "new_private_tab_button_normal"), for: .normal) button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted) let label = imageButton.label label.tintColor = TodayUX.privateBrowsingColor label.textColor = TodayUX.privateBrowsingColor label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize) imageButton.sizeToFit() return imageButton }() fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = { let button = ButtonWithSublabel() button.setTitle(TodayStrings.GoToCopiedLinkLabel, for: .normal) button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside) // We need to set the background image/color for .Normal, so the whole button is tappable. button.setBackgroundColor(UIColor.clear, forState: .normal) button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted) button.setImage(UIImage(named: "copy_link_icon")?.withRenderingMode(.alwaysTemplate), for: .normal) button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize) button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize) return button }() fileprivate lazy var widgetStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = TodayUX.margin / 2 stackView.distribution = UIStackView.Distribution.fill stackView.layoutMargins = UIEdgeInsets(top: TodayUX.margin, left: TodayUX.margin, bottom: TodayUX.margin, right: TodayUX.margin) stackView.isLayoutMarginsRelativeArrangement = true return stackView }() fileprivate lazy var buttonStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .fill stackView.spacing = 0 stackView.distribution = UIStackView.Distribution.fillEqually let edge = self.view.frame.size.width * TodayUX.buttonsHorizontalMarginPercentage stackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge) stackView.isLayoutMarginsRelativeArrangement = true return stackView }() fileprivate var scheme: String { guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else { // Something went wrong/weird, but we should fallback to the public one. return "firefox" } return string } override func viewDidLoad() { super.viewDidLoad() let widgetView: UIView! self.extensionContext?.widgetLargestAvailableDisplayMode = .compact let effectView = UIVisualEffectView(effect: UIVibrancyEffect.widgetPrimary()) self.view.addSubview(effectView) effectView.snp.makeConstraints { make in make.edges.equalTo(self.view) } widgetView = effectView.contentView buttonStackView.addArrangedSubview(newTabButton) buttonStackView.addArrangedSubview(newPrivateTabButton) widgetStackView.addArrangedSubview(buttonStackView) widgetStackView.addArrangedSubview(openCopiedLinkButton) widgetView.addSubview(widgetStackView) widgetStackView.snp.makeConstraints { make in make.edges.equalTo(widgetView) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateCopiedLink() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let edge = size.width * TodayUX.buttonsHorizontalMarginPercentage buttonStackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge) } func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return .zero } func updateCopiedLink() { UIPasteboard.general.asyncURL().uponQueue(.main) { res in if let copiedURL: URL? = res.successValue, let url = copiedURL { self.openCopiedLinkButton.isHidden = false self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked() self.openCopiedLinkButton.subtitleLabel.text = url.absoluteDisplayString self.copiedURL = url } else { self.openCopiedLinkButton.isHidden = true self.copiedURL = nil } } } // MARK: Button behaviour @objc func onPressNewTab(_ view: UIView) { openContainingApp("?private=false") } @objc func onPressNewPrivateTab(_ view: UIView) { openContainingApp("?private=true") } fileprivate func openContainingApp(_ urlSuffix: String = "") { let urlString = "\(scheme)://open-url\(urlSuffix)" self.extensionContext?.open(URL(string: urlString)!) { success in log.info("Extension opened containing app: \(success)") } } @objc func onPressOpenClibpoard(_ view: UIView) { if let url = copiedURL, let encodedString = url.absoluteString.escape() { openContainingApp("?url=\(encodedString)") } } } extension UIButton { func setBackgroundColor(_ color: UIColor, forState state: UIControl.State) { let colorView = UIView(frame: CGRect(width: 1, height: 1)) colorView.backgroundColor = color UIGraphicsBeginImageContext(colorView.bounds.size) if let context = UIGraphicsGetCurrentContext() { colorView.layer.render(in: context) } let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, for: state) } } class ImageButtonWithLabel: UIView { lazy var button = UIButton() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) performLayout() } func performLayout() { addSubview(button) addSubview(label) button.snp.makeConstraints { make in make.top.left.centerX.equalTo(self) } label.snp.makeConstraints { make in make.top.equalTo(button.snp.bottom) make.leading.trailing.bottom.equalTo(self) } label.numberOfLines = 1 label.lineBreakMode = .byWordWrapping label.textAlignment = .center label.textColor = UIColor.white } func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControl.Event) { button.addTarget(target, action: action, for: events) } } class ButtonWithSublabel: UIButton { lazy var subtitleLabel = UILabel() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { super.init(frame: frame) performLayout() } fileprivate func performLayout() { let titleLabel = self.label self.titleLabel?.removeFromSuperview() addSubview(titleLabel) let imageView = self.imageView! let subtitleLabel = self.subtitleLabel subtitleLabel.textColor = UIColor.lightGray self.addSubview(subtitleLabel) imageView.snp.makeConstraints { make in make.centerY.left.equalTo(self) make.width.equalTo(TodayUX.copyLinkImageWidth) } titleLabel.snp.makeConstraints { make in make.left.equalTo(imageView.snp.right).offset(TodayUX.margin) make.trailing.top.equalTo(self) } subtitleLabel.lineBreakMode = .byTruncatingTail subtitleLabel.snp.makeConstraints { make in make.bottom.equalTo(self) make.top.equalTo(titleLabel.snp.bottom) make.leading.trailing.equalTo(titleLabel) } } override func setTitle(_ text: String?, for state: UIControl.State) { self.label.text = text super.setTitle(text, for: state) } }
e8c550d63da418e17485fc3ca8d6eb3e
36.060606
186
0.681294
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Learn/10.属性和下标/结构体和枚举中的计算属性.playground/section-1.swift
mit
1
struct Department { let no: Int = 0 var name: String = "SALES" var fullName: String { return "Swift." + name + ".D" } } var dept = Department() print(dept.fullName) enum WeekDays: String { case Monday = "Mon." case Tuesday = "Tue." case Wednesday = "Wed." case Thursday = "Thu." case Friday = "Fri." var message: String { return "Today is " + self.rawValue } } var day = WeekDays.Monday print(day.message)
6790776d85c2ebe08e7d07e107d678f3
17.214286
42
0.539216
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
MinimedKit/PumpEvents/UnabsorbedInsulinPumpEvent.swift
mit
1
// // UnabsorbedInsulinPumpEvent.swift // RileyLink // // Created by Pete Schwamb on 3/7/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct UnabsorbedInsulinPumpEvent: PumpEvent { public struct Record : DictionaryRepresentable { var amount: Double var age: Int init(amount: Double, age: Int) { self.amount = amount self.age = age } public var dictionaryRepresentation: [String: Any] { return [ "amount": amount, "age": age, ] } } public let length: Int public let rawData: Data public let records: [Record] public init?(availableData: Data, pumpModel: PumpModel) { length = Int(max(availableData[1], 2)) var records = [Record]() guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) func d(_ idx: Int) -> Int { return Int(availableData[idx]) } let numRecords = (d(1) - 2) / 3 for idx in 0..<numRecords { let record = Record( amount: Double(d(2 + idx * 3)) / 40, age: d(3 + idx * 3) + ((d(4 + idx * 3) & 0b110000) << 4)) records.append(record) } self.records = records } public var dictionaryRepresentation: [String: Any] { return [ "_type": "UnabsorbedInsulin", "data": records.map({ (r: Record) -> [String: Any] in return r.dictionaryRepresentation }), ] } }
6f017a8db35965c13f19b3f25860909a
24.231884
73
0.504308
false
false
false
false
NjrSea/FlickTransition
refs/heads/master
FlickTransition/UIPanGestureRecognizer+Direction.swift
mit
1
// // UIPanGestureRecognizer+Direction.swift // FlickTransition // // Created by paul on 16/9/18. // Copyright © 2016年 paul. All rights reserved. // import UIKit public enum Direction { case Up case Down case Left case Right var isX: Bool { return self == .Left || self == .Right } var isY: Bool { return !isX } } extension UIPanGestureRecognizer { public var direction: Direction? { let vel = velocity(in: view) let vertical = fabs(vel.y) > fabs(vel.x) switch (vertical, vel.x, vel.y) { case (true, _, let y) where y < 0: return .Up case (true, _, let y) where y > 0: return .Down case (false, let x, _) where x > 0: return .Right case (false, let x, _) where x < 0: return .Left default: return nil } } }
01bf739bd30cf2b9c4ebd9109551c306
23.382353
60
0.577805
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift
mit
1
// // SidebarLayout.swift // NetNewsWire // // Created by Brent Simmons on 11/24/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import AppKit import RSCore // image - title - unreadCount struct SidebarCellLayout { let faviconRect: CGRect let titleRect: CGRect let unreadCountRect: CGRect init(appearance: SidebarCellAppearance, cellSize: NSSize, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) { let bounds = NSRect(x: 0.0, y: 0.0, width: floor(cellSize.width), height: floor(cellSize.height)) var rFavicon = NSRect.zero if shouldShowImage { rFavicon = NSRect(x: 0.0, y: 0.0, width: appearance.imageSize.width, height: appearance.imageSize.height) rFavicon = rFavicon.centeredVertically(in: bounds) } self.faviconRect = rFavicon let textFieldSize = SingleLineTextFieldSizer.size(for: textField.stringValue, font: textField.font!) var rTextField = NSRect(x: 0.0, y: 0.0, width: textFieldSize.width, height: textFieldSize.height) if shouldShowImage { rTextField.origin.x = NSMaxX(rFavicon) + appearance.imageMarginRight } rTextField = rTextField.centeredVertically(in: bounds) let unreadCountSize = unreadCountView.intrinsicContentSize let unreadCountIsHidden = unreadCountView.unreadCount < 1 var rUnread = NSRect.zero if !unreadCountIsHidden { rUnread.size = unreadCountSize rUnread.origin.x = NSMaxX(bounds) - unreadCountSize.width rUnread = rUnread.centeredVertically(in: bounds) let textFieldMaxX = NSMinX(rUnread) - appearance.unreadCountMarginLeft if NSMaxX(rTextField) > textFieldMaxX { rTextField.size.width = textFieldMaxX - NSMinX(rTextField) } } self.unreadCountRect = rUnread if NSMaxX(rTextField) > NSMaxX(bounds) { rTextField.size.width = NSMaxX(bounds) - NSMinX(rTextField) } self.titleRect = rTextField } }
101a3063c5221838a8a9713f5d4cd313
30.677966
141
0.749599
false
false
false
false
tndatacommons/Compass-iOS
refs/heads/master
Compass/src/Controller/AwardsController.swift
mit
1
// // AwardsController.swift // Compass // // Created by Ismael Alonso on 7/14/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit import Just import ObjectMapper import Crashlytics class AwardsController: UIViewController{ //MARK: Data private var badges = [Badge]() private var badgeQueue = [Badge]() private var displaying = false //MARK: UI components @IBOutlet weak var noAwards: UILabel! @IBOutlet weak var loadingAwards: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! var refreshControl = UIRefreshControl() //MARK: Lifecycle methods override func viewDidLoad(){ super.viewDidLoad() //Automatic height calculation tableView.rowHeight = UITableViewAutomaticDimension //Refresh refreshControl.addTarget( self, action: #selector(refresh(_:)), forControlEvents: .ValueChanged ) tableView.addSubview(refreshControl) print(DefaultsManager.getNewAwardArray()) } override func viewDidLayoutSubviews(){ super.viewDidLayoutSubviews() let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let navigationBarHeight = navigationController!.navigationBar.frame.size.height let top = statusBarHeight + navigationBarHeight tableView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) tableView.scrollIndicatorInsets = tableView.contentInset } override func viewWillAppear(animated: Bool){ super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow{ tableView.deselectRowAtIndexPath(indexPath, animated: true) } } override func viewDidAppear(animated: Bool){ super.viewDidAppear(animated) //Fetch every time the user access the controller if there are no awards if badges.isEmpty{ fetchAwards(false) } else{ //If there are awards, make sure the table is showing loadingAwards.hidden = true noAwards.hidden = true tableView.hidden = false //If there are badges in the queue add them and clear the queue if !badgeQueue.isEmpty{ var indexPaths = [NSIndexPath]() for badge in badgeQueue{ badges.append(badge) indexPaths.append(NSIndexPath(forRow: badges.count-1, inSection: 0)) } badgeQueue.removeAll() tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic) } } displaying = true } override func viewWillDisappear(animated: Bool){ super.viewWillDisappear(animated) displaying = false } //MARK: Fetch and refresh func refresh(refreshControl: UIRefreshControl){ fetchAwards(true) } private func fetchAwards(refreshing: Bool){ //Show the activity indicator if nor refreshing if !refreshing{ tableView.hidden = true noAwards.hidden = true loadingAwards.hidden = false } //Fetch the user's awards Just.get(API.getAwardsUrl(), headers: SharedData.user.getHeaderMap()){ (response) in if response.ok{ let awardList = Mapper<AwardList>().map(response.contentStr)! if !awardList.awards.isEmpty{ let newAwards = DefaultsManager.getNewAwardArray() self.badges.removeAll() for award in awardList.awards{ let badge = award.getBadge() badge.isNew = newAwards.contains(badge.getId()) self.badges.append(badge) } dispatch_async(dispatch_get_main_queue(), { if refreshing{ self.refreshControl.endRefreshing() } else{ self.loadingAwards.hidden = true self.tableView.hidden = false } print(self.tableView.numberOfRowsInSection(0)) self.tableView.reloadData() }) } else{ dispatch_async(dispatch_get_main_queue(), { if refreshing{ self.refreshControl.endRefreshing() } else{ self.loadingAwards.hidden = true self.noAwards.hidden = false } }) } } else{ dispatch_async(dispatch_get_main_queue(), { if refreshing{ self.refreshControl.endRefreshing() } else{ self.loadingAwards.hidden = true self.noAwards.hidden = false } }) } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ if let selectedCell = sender as? AwardCell{ if segue.identifier == "BadgeFromAwards"{ let badgeController = segue.destinationViewController as! BadgeController let indexPath = tableView.indexPathForCell(selectedCell)! let badge = badges[indexPath.row] if badge.isNew{ badge.isNew = false tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } badgeController.badge = badge } } } func addBadge(badge: Badge){ if badges.contains(badge){ badges.filter{ $0 == badge }[0].isNew = true tableView.reloadData() } else if !badges.isEmpty{ if displaying{ badges.append(badge) let paths = [NSIndexPath(forRow: badges.count-1, inSection: 0)] tableView.insertRowsAtIndexPaths(paths, withRowAnimation: .Automatic) } else{ badgeQueue.append(badge) } } } } extension AwardsController: UITableViewDataSource, UITableViewDelegate{ func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return badges.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("AwardCell", forIndexPath: indexPath) as! AwardCell cell.bind(badges[indexPath.row]) if badges[indexPath.row].isNew{ DefaultsManager.removeNewAward(badges[indexPath.row]) let newAwardCount = DefaultsManager.getNewAwardCount() if newAwardCount == 0{ tabBarController!.tabBar.items?[2].badgeValue = nil } else{ tabBarController!.tabBar.items?[2].badgeValue = "\(newAwardCount)" } } return cell } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{ return 100 } }
7436ee2496e317e37f39da442ed498f2
33.647321
114
0.554052
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
refs/heads/master
UberGoCore/UberGoCore/GeocodingPlaceObj.swift
mit
1
// // GeocodingObj.swift // UberGoCore // // Created by Nghia Tran on 8/3/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import CoreLocation import Unbox public final class GeocodingPlaceObj: NSObject, Unboxable { // MARK: - Variable public var address: String public var placeID: String public var location: [String: Float] // Coordinate public lazy var coordinate2D: CLLocationCoordinate2D = { let lat = self.location["lat"]!.toDouble let lng = self.location["lng"]!.toDouble return CLLocationCoordinate2D(latitude: lat, longitude: lng) }() // MARK: - Init public init(address: String, placeID: String, location: [String: Float]) { self.address = address self.placeID = placeID self.location = location } // Map public required init(unboxer: Unboxer) throws { address = try unboxer.unbox(key: "formatted_address") location = try unboxer.unbox(keyPath: "geometry.location") placeID = try unboxer.unbox(key: "place_id") } }
10909d274d5b73d39bb951516465a17b
27.157895
78
0.652336
false
false
false
false
donileo/RMessage
refs/heads/master
Sources/RMPresenter/RMPresenter+TouchCompletion.swift
mit
1
// // RMPresenter+TouchCompletion.swift // // Created by Adonis Peralta on 8/6/18. // Copyright © 2018 None. All rights reserved. // import Foundation import UIKit extension RMPresenter { func setupGestureRecognizers() { let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeMessage)) gestureRecognizer.direction = (targetPosition == .bottom) ? .down : .up message.addGestureRecognizer(gestureRecognizer) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapMessage)) message.addGestureRecognizer(tapRecognizer) } @objc func didTapMessage() { delegate?.messageTapped?(forPresenter: self, message: message) tapCompletion?() if message.spec.durationType != .endless && message.spec.durationType != .swipe { dismiss() } } /* called after the following gesture depending on message position during initialization UISwipeGestureRecognizerDirectionUp when message position set to Top, UISwipeGestureRecognizerDirectionDown when message position set to bottom */ @objc func didSwipeMessage() { delegate?.messageSwiped?(forPresenter: self, message: message) if message.spec.durationType != .endless && message.spec.durationType != .tap { dismiss() } } }
f5c0e609e7c98208159d01949c41ee0c
36.558824
102
0.749413
false
false
false
false
irace/Nibble
refs/heads/master
Carthage/Checkouts/alexander/Alexander/JSON.swift
mit
1
// // JSON.swift // Alexander // // Created by Caleb Davenport on 6/24/15. // Copyright (c) 2015 Hodinkee. All rights reserved. // import Foundation public struct JSON { // MARK: - Initializers public init(object: AnyObject) { self.object = object } // MARK: - Properties public var object: AnyObject public subscript(index: Int) -> JSON? { let array = object as? [AnyObject] return (array?[index]).map({ JSON(object: $0) }) } public subscript(key: String) -> JSON? { let dictionary = object as? [String: AnyObject] return (dictionary?[key]).map({ JSON(object: $0) }) } public var string: String? { return object as? String } public var dictionary: [String: JSON]? { return (object as? [String: AnyObject])?.mapValues({ JSON(object: $0) }) } public var array: [JSON]? { return (object as? [AnyObject])?.map({ JSON(object: $0) }) } public var int: Int? { return object as? Int } public var double: Double? { return object as? Double } public var bool: Bool? { return object as? Bool } public var url: NSURL? { return string.flatMap({ NSURL(string: $0) }) } public var timeInterval: NSTimeInterval? { return object as? NSTimeInterval } public var date: NSDate? { return timeInterval.map({ NSDate(timeIntervalSince1970: $0) }) } // MARK: - Functions public func decodeArray<T>(transform: JSON -> T?) -> [T]? { let block: ([T], AnyObject) -> [T] = { array, element in switch transform(JSON(object: element)) { case .Some(let object): return array + CollectionOfOne(object) case .None: return array } } return (object as? [AnyObject]).map({ reduce($0, [T](), block) }) } } extension JSON { public init?(data: NSData, options: NSJSONReadingOptions = .allZeros) { if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: options, error: nil) { self.object = object } else { return nil } } public func data(options: NSJSONWritingOptions = .allZeros) -> NSData? { if NSJSONSerialization.isValidJSONObject(object) { return NSJSONSerialization.dataWithJSONObject(object, options: options, error: nil) } return nil } } extension JSON: DebugPrintable { public var debugDescription: String { if let data = self.data(options: .PrettyPrinted), let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return String(string) } return "Invalid JSON." } }
99bc229dcfbc43926e6ed4709ed41334
23.947368
111
0.568917
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Sources/Lexer/Lexer+Operator.swift
apache-2.0
2
/* Copyright 2015-2017, 2019 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ extension Lexer /* operator */ { func lexReservedOperator(prev: Role) -> Token.Kind { let opString = char.string let operatorRole = char.role _consume(operatorRole) let operatorKind = opString.toOperator(following: prev, followed: char.role) switch (operatorRole, operatorKind) { case (.lessThan, .prefixOperator): return .leftChevron case (.greaterThan, .postfixOperator): return .rightChevron case (.amp, .prefixOperator): return .prefixAmp case (.question, .prefixOperator): return .prefixQuestion case (.question, .binaryOperator): return .binaryQuestion case (.question, .postfixOperator): return .postfixQuestion case (.exclaim, .postfixOperator): return .postfixExclaim default: return operatorKind } } func lexOperator(prev: Role, enableDotOperator: Bool = false) -> Token.Kind { var opString = "" repeat { opString.append(char.string) _consume(char.role) } while char.shouldContinue(enableDotOperator: enableDotOperator) return opString.toOperator(following: prev, followed: char.role) } } fileprivate extension Char { func shouldContinue(enableDotOperator: Bool) -> Bool { if self == .eof { return false } switch self.role { case .operatorHead, .operatorBody, .lessThan, .greaterThan, .amp, .question, .exclaim, .equal, .arrow, .minus, .singleLineCommentHead, .multipleLineCommentHead, .multipleLineCommentTail, .dotOperatorHead where enableDotOperator, .period where enableDotOperator: return true default: return false } } } fileprivate extension String { func toOperator(following head: Role, followed tail: Role) -> Token.Kind { let headSeparated = head.isHeadSeparator let tailSeparated = tail.isTailSeparator if tail == .eof && !headSeparated { return .postfixOperator(self) } else if headSeparated && !tailSeparated { return .prefixOperator(self) } else if !headSeparated && tailSeparated { return .postfixOperator(self) } else if !headSeparated && (self == "?" || self == "!") { return .postfixOperator(self) } else { return .binaryOperator(self) } } }
b1e119f1c52d71711e17b541d8e7c685
31.633333
81
0.684031
false
false
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/PostsViewController.swift
apache-2.0
1
// // PostsViewController.swift // edX // // Created by Tang, Jeff on 5/19/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class PostsViewController: TDSwiftBaseViewController, UITableViewDataSource, UITableViewDelegate, PullRefreshControllerDelegate, InterfaceOrientationOverriding, DiscussionNewPostViewControllerDelegate { typealias Environment = protocol<NetworkManagerProvider, OEXRouterProvider, OEXAnalyticsProvider, OEXStylesProvider> enum Context { case Topic(DiscussionTopic) case Following case Search(String) case AllPosts var allowsPosting : Bool { switch self { case Topic: return true case Following: return true case Search: return false case AllPosts: return true } } var topic : DiscussionTopic? { switch self { case let Topic(topic): return topic case Search(_): return nil case Following(_): return nil case AllPosts(_): return nil } } var navigationItemTitle : String? { switch self { case let Topic(topic): return topic.name case Search(_): return Strings.searchResults case Following(_): return Strings.postsImFollowing case AllPosts(_): return Strings.allPosts } } //Strictly to be used to pass on to DiscussionNewPostViewController. var selectedTopic : DiscussionTopic? { switch self { case let Topic(topic): return topic.isSelectable ? topic : topic.firstSelectableChild() case Search(_): return nil case Following(_): return nil case AllPosts(_): return nil } } var noResultsMessage : String { switch self { case Topic(_): return Strings.noResultsFound case AllPosts: return Strings.noCourseResults case Following: return Strings.noFollowingResults case let .Search(string) : return Strings.emptyResultset(queryString: string) } } private var queryString: String? { switch self { case Topic(_): return nil case AllPosts: return nil case Following: return nil case let .Search(string) : return string } } } var environment: Environment! private var paginationController : PaginationController<DiscussionThread>? private lazy var tableView = UITableView(frame: CGRectZero, style: .Plain) private let viewSeparator = UIView() private let loadController = LoadStateViewController() private let refreshController = PullRefreshController() private let insetsController = ContentInsetsController() private let refineLabel = UILabel() private let headerButtonHolderView = UIView() private let headerView = UIView() private var searchBar : UISearchBar? private let filterButton = PressableCustomButton() private let sortButton = PressableCustomButton() private let newPostButton = UIButton(type: .System) private let courseID: String private var isDiscussionBlackedOut: Bool = true { didSet { updateNewPostButtonStyle() } } private var stream: Stream<(DiscussionInfo)>? private let contentView = UIView() private var context : Context? private let topicID: String? private var posts: [DiscussionThread] = [] private var selectedFilter: DiscussionPostsFilter = .AllPosts private var selectedOrderBy: DiscussionPostsSort = .RecentActivity var searchBarDelegate : DiscussionSearchBarDelegate? private var queryString : String? private var refineTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } private var filterTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().primaryBaseColor()) } private var hasResults:Bool = false required init(environment: Environment, courseID: String, topicID: String?, context: Context?) { self.courseID = courseID self.environment = environment self.topicID = topicID self.context = context super.init(nibName: nil, bundle: nil) configureSearchBar() } convenience init(environment: Environment, courseID: String, topicID: String?) { self.init(environment: environment, courseID : courseID, topicID: topicID, context: nil) } convenience init(environment: Environment, courseID: String, topic: DiscussionTopic) { self.init(environment: environment, courseID : courseID, topicID: nil, context: .Topic(topic)) } convenience init(environment: Environment,courseID: String, queryString : String) { self.init(environment: environment, courseID : courseID, topicID: nil, context : .Search(queryString)) } ///Convenience initializer for All Posts and Followed posts convenience init(environment: Environment, courseID: String, following : Bool) { self.init(environment: environment, courseID : courseID, topicID: nil, context : following ? .Following : .AllPosts) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() addSubviews() setConstraints() setStyles() tableView.registerClass(PostTableViewCell.classForCoder(), forCellReuseIdentifier: PostTableViewCell.identifier) tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView.init() tableView.estimatedRowHeight = 150 tableView.rowHeight = UITableViewAutomaticDimension tableView.applyStandardSeparatorInsets() if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } filterButton.oex_addAction( {[weak self] _ in self?.showFilterPicker() }, forEvents: .TouchUpInside) sortButton.oex_addAction( {[weak self] _ in self?.showSortPicker() }, forEvents: .TouchUpInside) newPostButton.oex_addAction( {[weak self] _ in if let owner = self { owner.environment.router?.showDiscussionNewPostFromController(owner, courseID: owner.courseID, selectedTopic : owner.context?.selectedTopic) } }, forEvents: .TouchUpInside) loadController.setupInController(self, contentView: contentView) insetsController.setupInController(self, scrollView: tableView) refreshController.setupInScrollView(tableView) insetsController.addSource(refreshController) refreshController.delegate = self //set visibility of header view updateHeaderViewVisibility() loadContent() setAccessibility() } private func setAccessibility() { if let searchBar = searchBar { view.accessibilityElements = [searchBar, tableView] } else { view.accessibilityElements = [refineLabel, filterButton, sortButton, tableView, newPostButton] } updateAccessibility() } private func updateAccessibility() { filterButton.accessibilityLabel = Strings.Accessibility.discussionFilterBy(filterBy: titleForFilter(selectedFilter)) filterButton.accessibilityHint = Strings.accessibilityShowsDropdownHint sortButton.accessibilityLabel = Strings.Accessibility.discussionSortBy(sortBy: titleForSort(selectedOrderBy)) sortButton.accessibilityHint = Strings.accessibilityShowsDropdownHint } private func configureSearchBar() { guard let context = context where !context.allowsPosting else { return } searchBar = UISearchBar() searchBar?.applyStandardStyles(withPlaceholder: Strings.searchAllPosts) searchBar?.text = context.queryString searchBarDelegate = DiscussionSearchBarDelegate() { [weak self] text in self?.context = Context.Search(text) self?.loadController.state = .Initial self?.searchThreads(text) self?.searchBar?.delegate = self?.searchBarDelegate } } private func addSubviews() { view.addSubview(contentView) view.addSubview(headerView) if let searchBar = searchBar { view.addSubview(searchBar) } contentView.addSubview(tableView) headerView.addSubview(refineLabel) headerView.addSubview(headerButtonHolderView) headerButtonHolderView.addSubview(filterButton) headerButtonHolderView.addSubview(sortButton) view.addSubview(newPostButton) contentView.addSubview(viewSeparator) } private func setConstraints() { contentView.snp_remakeConstraints { (make) -> Void in if context?.allowsPosting ?? false { make.top.equalTo(view) } //Else the top is equal to searchBar.snp_bottom make.leading.equalTo(view) make.trailing.equalTo(view) //The bottom is equal to newPostButton.snp_top } headerView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.top.equalTo(contentView) make.height.equalTo(context?.allowsPosting ?? false ? 40 : 0) } searchBar?.snp_remakeConstraints(closure: { (make) -> Void in make.top.equalTo(view) make.trailing.equalTo(contentView) make.leading.equalTo(contentView) make.bottom.equalTo(contentView.snp_top) }) refineLabel.snp_remakeConstraints { (make) -> Void in make.leadingMargin.equalTo(headerView).offset(StandardHorizontalMargin) make.centerY.equalTo(headerView) } refineLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) headerButtonHolderView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(refineLabel.snp_trailing) make.trailing.equalTo(headerView) make.bottom.equalTo(headerView) make.top.equalTo(headerView) } filterButton.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(headerButtonHolderView) make.trailing.equalTo(sortButton.snp_leading) make.centerY.equalTo(headerButtonHolderView) } sortButton.snp_remakeConstraints{ (make) -> Void in make.trailingMargin.equalTo(headerButtonHolderView) make.centerY.equalTo(headerButtonHolderView) make.width.equalTo(filterButton.snp_width) } newPostButton.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(view) make.trailing.equalTo(view) make.height.equalTo(context?.allowsPosting ?? false ? OEXStyles.sharedStyles().standardFooterHeight : 0) make.top.equalTo(contentView.snp_bottom) make.bottom.equalTo(view) } tableView.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(contentView) make.top.equalTo(viewSeparator.snp_bottom) make.trailing.equalTo(contentView) make.bottom.equalTo(newPostButton.snp_top) } viewSeparator.snp_remakeConstraints{ (make) -> Void in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.height.equalTo(OEXStyles.dividerSize()) make.top.equalTo(headerView.snp_bottom) } } private func setStyles() { view.backgroundColor = environment.styles.baseColor5() self.refineLabel.attributedText = self.refineTextStyle.attributedStringWithText(Strings.refine) var buttonTitle = NSAttributedString.joinInNaturalLayout( [Icon.Filter.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(self.titleForFilter(self.selectedFilter))]) filterButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(Strings.recentActivity)]) sortButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) updateNewPostButtonStyle() let style = OEXTextStyle(weight : .Normal, size: .Base, color: environment.styles.neutralWhite()) buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Create.attributedTextWithStyle(style.withSize(.XSmall)), style.attributedStringWithText(Strings.createANewPost)]) newPostButton.setAttributedTitle(buttonTitle, forState: .Normal) newPostButton.contentVerticalAlignment = .Center self.titleViewLabel.text = context?.navigationItemTitle viewSeparator.backgroundColor = environment.styles.neutralXLight() } private func updateNewPostButtonStyle() { newPostButton.backgroundColor = isDiscussionBlackedOut ? environment.styles.neutralBase() : environment.styles.primaryXDarkColor() newPostButton.enabled = !isDiscussionBlackedOut } func setIsDiscussionBlackedOut(value : Bool){ isDiscussionBlackedOut = value } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let selectedIndex = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(selectedIndex, animated: false) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } private func logScreenEvent() { guard let context = context else { return } switch context { case let .Topic(topic): self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: topic.name, threadId: nil, topicId: topic.id, responseID: nil) case let .Search(query): self.environment.analytics.trackScreenWithName(OEXAnalyticsScreenSearchThreads, courseID: self.courseID, value: query, additionalInfo:["search_string":query]) case .Following: self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: "posts_following", threadId: nil, topicId: "posts_following", responseID: nil) case .AllPosts: self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenViewTopicThreads, courseId: self.courseID, value: "all_posts", threadId: nil, topicId: "all_posts", responseID: nil) } } private func loadContent() { let apiRequest = DiscussionAPI.getDiscussionInfo(courseID) stream = environment.networkManager.streamForRequest(apiRequest) stream?.listen(self, success: { [weak self] (discussionInfo) in self?.isDiscussionBlackedOut = discussionInfo.isBlackedOut self?.loadPostContent() } ,failure: { [weak self] (error) in self?.loadController.state = LoadState.failed(error) }) } private func loadPostContent() { guard let context = context else { // context is only nil in case if topic is selected loadTopic() return } logScreenEvent() switch context { case let .Topic(topic): loadPostsForTopic(topic, filter: selectedFilter, orderBy: selectedOrderBy) case let .Search(query): searchThreads(query) case .Following: loadFollowedPostsForFilter(selectedFilter, orderBy: selectedOrderBy) case .AllPosts: loadPostsForTopic(nil, filter: selectedFilter, orderBy: selectedOrderBy) } } private func loadTopic() { guard let topicID = topicID else { loadController.state = LoadState.failed(NSError.oex_unknownError()) return } let apiRequest = DiscussionAPI.getTopicByID(courseID, topicID: topicID) self.environment.networkManager.taskForRequest(apiRequest) {[weak self] response in if let topics = response.data { //Sending signle topic id so always get a single topic self?.context = .Topic(topics[0]) self?.titleViewLabel.text = self?.context?.navigationItemTitle self?.setConstraints() self?.loadContent() } else { self?.loadController.state = LoadState.failed(response.error) } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } private func updateHeaderViewVisibility() { tableView.scrollEnabled = posts.count * 53 > TDScreenHeight - 180 ? true : false // if post has results then set hasResults yes hasResults = context?.allowsPosting ?? false && self.posts.count > 0 headerView.hidden = !hasResults } private func loadFollowedPostsForFilter(filter : DiscussionPostsFilter, orderBy: DiscussionPostsSort) { let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.getFollowedThreads(courseID: self.courseID, filter: filter, orderBy: orderBy, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func searchThreads(query : String) { let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.searchThreads(courseID: self.courseID, searchText: query, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func loadPostsForTopic(topic : DiscussionTopic?, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort) { var topicIDApiRepresentation : [String]? if let identifier = topic?.id { topicIDApiRepresentation = [identifier] } //Children's topic IDs if the topic is root node else if let discussionTopic = topic { topicIDApiRepresentation = discussionTopic.children.mapSkippingNils { $0.id } } let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in return DiscussionAPI.getThreads(courseID: self.courseID, topicIDs: topicIDApiRepresentation, filter: filter, orderBy: orderBy, pageNumber: page) } paginationController = PaginationController (paginator: paginator, tableView: self.tableView) loadThreads() } private func loadThreads() { paginationController?.stream.listen(self, success: { [weak self] threads in self?.posts.removeAll() self?.updatePostsFromThreads(threads) self?.refreshController.endRefreshing() }, failure: { [weak self] (error) -> Void in self?.loadController.state = LoadState.failed(error) }) paginationController?.loadMore() } private func updatePostsFromThreads(threads : [DiscussionThread]) { for thread in threads { self.posts.append(thread) } self.tableView.reloadData() let emptyState = LoadState.empty(icon : nil , message: errorMessage()) self.loadController.state = self.posts.isEmpty ? emptyState : .Loaded // set visibility of header view updateHeaderViewVisibility() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } func titleForFilter(filter : DiscussionPostsFilter) -> String { switch filter { case .AllPosts: return Strings.allPosts case .Unread: return Strings.unread case .Unanswered: return Strings.unanswered } } func titleForSort(filter : DiscussionPostsSort) -> String { switch filter { case .RecentActivity: return Strings.recentActivity case .MostActivity: return Strings.mostActivity case .VoteCount: return Strings.mostVotes } } func isFilterApplied() -> Bool { switch self.selectedFilter { case .AllPosts: return false case .Unread: return true case .Unanswered: return true } } func errorMessage() -> String { guard let context = context else { return "" } if isFilterApplied() { return context.noResultsMessage + " " + Strings.removeFilter } else { return context.noResultsMessage } } func showFilterPicker() { let options = [.AllPosts, .Unread, .Unanswered].map { return (title : self.titleForFilter($0), value : $0) } let controller = UIAlertController.actionSheetWithItems(options, currentSelection : self.selectedFilter) {filter in self.selectedFilter = filter self.loadController.state = .Initial self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Filter.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForFilter(filter))]) self.filterButton.setAttributedTitle(buttonTitle, forState: .Normal, animated : false) self.updateAccessibility() } controller.addCancelAction() self.presentViewController(controller, animated: true, completion:nil) } func showSortPicker() { let options = [.RecentActivity, .MostActivity, .VoteCount].map { return (title : self.titleForSort($0), value : $0) } let controller = UIAlertController.actionSheetWithItems(options, currentSelection : self.selectedOrderBy) {sort in self.selectedOrderBy = sort self.loadController.state = .Initial self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForSort(sort))]) self.sortButton.setAttributedTitle(buttonTitle, forState: .Normal, animated: false) self.updateAccessibility() } controller.addCancelAction() self.presentViewController(controller, animated: true, completion:nil) } private func updateSelectedPostAttributes(indexPath: NSIndexPath) { posts[indexPath.row].read = true posts[indexPath.row].unreadCommentCount = 0 tableView.reloadData() } //MARK :- DiscussionNewPostViewControllerDelegate method func newPostController(controller: DiscussionNewPostViewController, addedPost post: DiscussionThread) { loadContent() } // MARK - Pull Refresh func refreshControllerActivated(controller: PullRefreshController) { loadContent() } // MARK - Table View Delegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } var cellTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().primaryBaseColor()) } var unreadIconTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .Large, color: OEXStyles.sharedStyles().primaryBaseColor()) } var readIconTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBase()) } func styledCellTextWithIcon(icon : Icon, text : String?) -> NSAttributedString? { let style = cellTextStyle.withSize(.Small) return text.map {text in return NSAttributedString.joinInNaturalLayout([icon.attributedTextWithStyle(style), style.attributedStringWithText(text)]) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableView.tableFooterView = UIView.init() let cell = tableView.dequeueReusableCellWithIdentifier(PostTableViewCell.identifier, forIndexPath: indexPath) as! PostTableViewCell cell.useThread(posts[indexPath.row], selectedOrderBy : selectedOrderBy) cell.applyStandardSeparatorInsets() return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { updateSelectedPostAttributes(indexPath) environment.router?.showDiscussionResponsesFromViewController(self, courseID : courseID, threadID: posts[indexPath.row].threadID, isDiscussionBlackedOut: isDiscussionBlackedOut) } } //We want to make sure that only non-root node topics are selectable public extension DiscussionTopic { var isSelectable : Bool { return self.depth != 0 || self.id != nil } func firstSelectableChild(forTopic topic : DiscussionTopic? = nil) -> DiscussionTopic? { let discussionTopic = topic ?? self if let matchedIndex = discussionTopic.children.firstIndexMatching({$0.isSelectable }) { return discussionTopic.children[matchedIndex] } if discussionTopic.children.count > 0 { return firstSelectableChild(forTopic : discussionTopic.children[0]) } return nil } } extension UITableView { //Might be worth adding a section argument in the future func isLastRow(indexPath indexPath : NSIndexPath) -> Bool { return indexPath.row == self.numberOfRowsInSection(indexPath.section) - 1 && indexPath.section == self.numberOfSections - 1 } } // Testing only extension PostsViewController { var t_loaded : Stream<()> { return self.stream!.map {_ in () } } var t_loaded_pagination : Stream<()> { return self.paginationController!.stream.map {_ in return } } }
b14b624d71f7abfc2f09829856cfe21e
37.994374
215
0.646456
false
false
false
false
baottran/nSURE
refs/heads/master
nSURE/AssessmentListViewController.swift
mit
1
// // AssessmentListViewController.swift // nSURE // // Created by Bao Tran on 7/6/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit class AssessmentListViewController: UITableViewController { var assessmentArray: [PFObject]! override func viewDidLoad() { } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return assessmentArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AssessmentItem") let assessment = assessmentArray[indexPath.row] if let customerObj = assessment["customer"] as? PFObject { let customerQuery = PFQuery(className: "Customer") let customer = customerQuery.getObjectWithId(customerObj.objectId!) let firstName = customer!["firstName"] as! String let lastName = customer!["lastName"] as! String cell!.textLabel!.text = "\(firstName) \(lastName)" } if let date = assessment["assessmentDate"] as? NSDate { cell!.detailTextLabel?.text = date.toLongString() } return cell! } @IBAction func dismiss(){ self.dismissViewControllerAnimated(true, completion: nil) } }
a913306f5017a04da12fe030bc60ccc1
30.195652
118
0.645296
false
false
false
false
kickstarter/ios-oss
refs/heads/main
KsApi/models/ProjectState.swift
apache-2.0
1
import Foundation public enum ProjectState: String, CaseIterable, Decodable, Equatable { case canceled = "CANCELED" case failed = "FAILED" case live = "LIVE" case purged = "PURGED" case started = "STARTED" case submitted = "SUBMITTED" case successful = "SUCCESSFUL" case suspended = "SUSPENDED" }
234735db18c0174baf86a09d66402d2e
25.166667
70
0.713376
false
false
false
false
HarrisLee/Utils
refs/heads/master
MySampleCode-master/SwiftTips/SwiftTips/main.swift
mit
1
// // main.swift // SwiftTips // // Created by 张星宇 on 16/2/2. // Copyright © 2016年 zxy. All rights reserved. // import Foundation var person = Person() person.changeName("kt") // 可以获取name属性的值 print(person.name) // 报错,不能在PrivateSet.swift文件外对name属性赋值 //person.name = "newName" /// 可以简化reuseIdentifier let reuseIdentifier = String(TableViewCell) print(reuseIdentifier) // 可以把多个相关联的变量声明在一个元组中 var (top, left, width, height) = (0.0, 0.0, 100.0, 50.0) //rect.width = width /** * 自定义断点 */ customDebug()
133bd91213b4b26f084f178b059f42ea
15.387097
56
0.692913
false
false
false
false
harlanhaskins/swift
refs/heads/master
stdlib/public/core/FloatingPoint.swift
apache-2.0
2
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// /// A floating-point numeric type. /// /// Floating-point types are used to represent fractional numbers, like 5.5, /// 100.0, or 3.14159274. Each floating-point type has its own possible range /// and precision. The floating-point types in the standard library are /// `Float`, `Double`, and `Float80` where available. /// /// Create new instances of floating-point types using integer or /// floating-point literals. For example: /// /// let temperature = 33.2 /// let recordHigh = 37.5 /// /// The `FloatingPoint` protocol declares common arithmetic operations, so you /// can write functions and algorithms that work on any floating-point type. /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// Because the `hypotenuse(_:_:)` function uses a generic parameter /// constrained to the `FloatingPoint` protocol, you can call it using any /// floating-point type. /// /// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// Floating-point values are represented as a *sign* and a *magnitude*, where /// the magnitude is calculated using the type's *radix* and the instance's /// *significand* and *exponent*. This magnitude calculation takes the /// following form for a floating-point value `x` of type `F`, where `**` is /// exponentiation: /// /// x.significand * F.radix ** x.exponent /// /// Here's an example of the number -8.5 represented as an instance of the /// `Double` type, which defines a radix of 2. /// /// let y = -8.5 /// // y.sign == .minus /// // y.significand == 1.0625 /// // y.exponent == 3 /// /// let magnitude = 1.0625 * Double(2 ** 3) /// // magnitude == 8.5 /// /// Types that conform to the `FloatingPoint` protocol provide most basic /// (clause 5) operations of the [IEEE 754 specification][spec]. The base, /// precision, and exponent range are not fixed in any way by this protocol, /// but it enforces the basic requirements of any IEEE 754 floating-point /// type. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// Additional Considerations /// ========================= /// /// In addition to representing specific numbers, floating-point types also /// have special values for working with overflow and nonnumeric results of /// calculation. /// /// Infinity /// -------- /// /// Any value whose magnitude is so great that it would round to a value /// outside the range of representable numbers is rounded to *infinity*. For a /// type `F`, positive and negative infinity are represented as `F.infinity` /// and `-F.infinity`, respectively. Positive infinity compares greater than /// every finite value and negative infinity, while negative infinity compares /// less than every finite value and positive infinity. Infinite values with /// the same sign are equal to each other. /// /// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] /// print(values.sorted()) /// // Prints "[-inf, -10.0, 10.0, 25.0, inf]" /// /// Operations with infinite values follow real arithmetic as much as possible: /// Adding or subtracting a finite value, or multiplying or dividing infinity /// by a nonzero finite value, results in infinity. /// /// NaN ("not a number") /// -------------------- /// /// Floating-point types represent values that are neither finite numbers nor /// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with /// any value, including another NaN, results in `false`. /// /// let myNaN = Double.nan /// print(myNaN > 0) /// // Prints "false" /// print(myNaN < 0) /// // Prints "false" /// print(myNaN == .nan) /// // Prints "false" /// /// Because testing whether one NaN is equal to another NaN results in `false`, /// use the `isNaN` property to test whether a value is NaN. /// /// print(myNaN.isNaN) /// // Prints "true" /// /// NaN propagates through many arithmetic operations. When you are operating /// on many values, this behavior is valuable because operations on NaN simply /// forward the value and don't cause runtime errors. The following example /// shows how NaN values operate in different contexts. /// /// Imagine you have a set of temperature data for which you need to report /// some general statistics: the total number of observations, the number of /// valid observations, and the average temperature. First, a set of /// observations in Celsius is parsed from strings to `Double` values: /// /// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] /// let tempsCelsius = temperatureData.map { Double($0) ?? .nan } /// print(tempsCelsius) /// // Prints "[21.5, 19.25, 27, nan, 28.25, nan, 23.0]" /// /// /// Note that some elements in the `temperatureData ` array are not valid /// numbers. When these invalid strings are parsed by the `Double` failable /// initializer, the example uses the nil-coalescing operator (`??`) to /// provide NaN as a fallback value. /// /// Next, the observations in Celsius are converted to Fahrenheit: /// /// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } /// print(tempsFahrenheit) /// // Prints "[70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]" /// /// The NaN values in the `tempsCelsius` array are propagated through the /// conversion and remain NaN in `tempsFahrenheit`. /// /// Because calculating the average of the observations involves combining /// every value of the `tempsFahrenheit` array, any NaN values cause the /// result to also be NaN, as seen in this example: /// /// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count) /// // badAverage.isNaN == true /// /// Instead, when you need an operation to have a specific numeric result, /// filter out any NaN values using the `isNaN` property. /// /// let validTemps = tempsFahrenheit.filter { !$0.isNaN } /// let average = validTemps.reduce(0.0, +) / Double(validTemps.count) /// /// Finally, report the average temperature and observation counts: /// /// print("Average: \(average)°F in \(validTemps.count) " + /// "out of \(tempsFahrenheit.count) observations.") /// // Prints "Average: 74.84°F in 5 out of 7 observations." public protocol FloatingPoint: SignedNumeric, Strideable, Hashable where Magnitude == Self { /// A type that can represent any written exponent. associatedtype Exponent: SignedInteger /// Creates a new value from the given sign, exponent, and significand. /// /// The following example uses this initializer to create a new `Double` /// instance. `Double` is a binary floating-point type that has a radix of /// `2`. /// /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) /// // x == 0.375 /// /// This initializer is equivalent to the following calculation, where `**` /// is exponentiation, computed as if by a single, correctly rounded, /// floating-point operation: /// /// let sign: FloatingPointSign = .plus /// let exponent = -2 /// let significand = 1.5 /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent /// // y == 0.375 /// /// As with any basic operation, if this value is outside the representable /// range of the type, overflow or underflow occurs, and zero, a subnormal /// value, or infinity may result. In addition, there are two other edge /// cases: /// /// - If the value you pass to `significand` is zero or infinite, the result /// is zero or infinite, regardless of the value of `exponent`. /// - If the value you pass to `significand` is NaN, the result is NaN. /// /// For any floating-point value `x` of type `F`, the result of the following /// is equal to `x`, with the distinction that the result is canonicalized /// if `x` is in a noncanonical encoding: /// /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) /// /// This initializer implements the `scaleB` operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign to use for the new value. /// - exponent: The new value's exponent. /// - significand: The new value's significand. init(sign: FloatingPointSign, exponent: Exponent, significand: Self) /// Creates a new floating-point value using the sign of one value and the /// magnitude of another. /// /// The following example uses this initializer to create a new `Double` /// instance with the sign of `a` and the magnitude of `b`: /// /// let a = -21.5 /// let b = 305.15 /// let c = Double(signOf: a, magnitudeOf: b) /// print(c) /// // Prints "-305.15" /// /// This initializer implements the IEEE 754 `copysign` operation. /// /// - Parameters: /// - signOf: A value from which to use the sign. The result of the /// initializer has the same sign as `signOf`. /// - magnitudeOf: A value from which to use the magnitude. The result of /// the initializer has the same magnitude as `magnitudeOf`. init(signOf: Self, magnitudeOf: Self) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init(_ value: Int) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init<Source: BinaryInteger>(_ value: Source) /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. init?<Source: BinaryInteger>(exactly value: Source) /// The radix, or base of exponentiation, for a floating-point type. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// A conforming type may use any integer radix, but values other than 2 (for /// binary floating-point types) or 10 (for decimal floating-point types) /// are extraordinarily rare in practice. static var radix: Int { get } /// A quiet NaN ("not a number"). /// /// A NaN compares not equal, not greater than, and not less than every /// value, including itself. Passing a NaN to an operation generally results /// in NaN. /// /// let x = 1.21 /// // x > Double.nan == false /// // x < Double.nan == false /// // x == Double.nan == false /// /// Because a NaN always compares not equal to itself, to test whether a /// floating-point value is NaN, use its `isNaN` property instead of the /// equal-to operator (`==`). In the following example, `y` is NaN. /// /// let y = x + Double.nan /// print(y == Double.nan) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" static var nan: Self { get } /// A signaling NaN ("not a number"). /// /// The default IEEE 754 behavior of operations involving a signaling NaN is /// to raise the Invalid flag in the floating-point environment and return a /// quiet NaN. /// /// Operations on types conforming to the `FloatingPoint` protocol should /// support this behavior, but they might also support other options. For /// example, it would be reasonable to implement alternative operations in /// which operating on a signaling NaN triggers a runtime error or results /// in a diagnostic for debugging purposes. Types that implement alternative /// behaviors for a signaling NaN must document the departure. /// /// Other than these signaling operations, a signaling NaN behaves in the /// same manner as a quiet NaN. static var signalingNaN: Self { get } /// Positive infinity. /// /// Infinity compares greater than all finite numbers and equal to other /// infinite values. /// /// let x = Double.greatestFiniteMagnitude /// let y = x * 2 /// // y == Double.infinity /// // y > x static var infinity: Self { get } /// The greatest finite number representable by this type. /// /// This value compares greater than or equal to all finite numbers, but less /// than `infinity`. /// /// This value corresponds to type-specific C macros such as `FLT_MAX` and /// `DBL_MAX`. The naming of those macros is slightly misleading, because /// `infinity` is greater than this value. static var greatestFiniteMagnitude: Self { get } /// The mathematical constant pi. /// /// This value should be rounded toward zero to keep user computations with /// angles from inadvertently ending up in the wrong quadrant. A type that /// conforms to the `FloatingPoint` protocol provides the value for `pi` at /// its best possible precision. /// /// print(Double.pi) /// // Prints "3.14159265358979" static var pi: Self { get } // NOTE: Rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastNonzeroMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of this value. /// /// This is the unit of the least significant digit in this value's /// significand. For most numbers `x`, this is the difference between `x` /// and the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - If `x` is not a finite number, then `x.ulp` is NaN. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. If a type does not support subnormals, `x.ulp` may be rounded /// to zero. /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next /// greater representable value is `infinity`. /// /// See also the `ulpOfOne` static property. var ulp: Self { get } /// The unit in the last place of 1.0. /// /// The positive difference between 1.0 and the next greater representable /// number. `ulpOfOne` corresponds to the value represented by the C macros /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or /// *machine epsilon*. Swift deliberately avoids using the term "epsilon" /// because: /// /// - Historically "epsilon" has been used to refer to several different /// concepts in different languages, leading to confusion and bugs. /// /// - The name "epsilon" suggests that this quantity is a good tolerance to /// choose for approximate comparisons, but it is almost always unsuitable /// for that purpose. /// /// See also the `ulp` member property. static var ulpOfOne: Self { get } /// The least positive normal number. /// /// This value compares less than or equal to all positive normal numbers. /// There may be smaller positive numbers, but they are *subnormal*, meaning /// that they are represented with less precision than normal numbers. /// /// This value corresponds to type-specific C macros such as `FLT_MIN` and /// `DBL_MIN`. The naming of those macros is slightly misleading, because /// subnormals, zeros, and negative numbers are smaller than this value. static var leastNormalMagnitude: Self { get } /// The least positive number. /// /// This value compares less than or equal to all positive numbers, but /// greater than zero. If the type supports subnormal values, /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; /// otherwise they are equal. static var leastNonzeroMagnitude: Self { get } /// The sign of the floating-point value. /// /// The `sign` property is `.minus` if the value's signbit is set, and /// `.plus` otherwise. For example: /// /// let x = -33.375 /// // x.sign == .minus /// /// Do not use this property to check whether a floating point value is /// negative. For a value `x`, the comparison `x.sign == .minus` is not /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` /// could be either `.plus` or `.minus`. var sign: FloatingPointSign { get } /// The exponent of the floating-point value. /// /// The *exponent* of a floating-point value is the integer part of the /// logarithm of the value's magnitude. For a value `x` of a floating-point /// type `F`, the magnitude can be calculated as the following, where `**` /// is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// The `exponent` property has the following edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// This property implements the `logB` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var exponent: Exponent { get } /// The significand of the floating-point value. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// If a type's radix is 2, then for finite nonzero numbers, the significand /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` /// is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinite, then `x.significand` is infinity. /// - If `x` is NaN, then `x.significand` is NaN. /// - Note: The significand is frequently also called the *mantissa*, but /// significand is the preferred terminology in the [IEEE 754 /// specification][spec], to allay confusion with the use of mantissa for /// the fractional part of a logarithm. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var significand: Self { get } /// Adds two values and produces their sum, rounded to a /// representable value. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// let x = 1.5 /// let y = x + 2.25 /// // y == 3.75 /// /// The `+` operator implements the addition operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable, /// rounded to a representable value. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Calculates the additive inverse of a value. /// /// The unary minus operator (prefix `-`) calculates the negation of its /// operand. The result is always exact. /// /// let x = 21.5 /// let y = -x /// // y == -21.5 /// /// - Parameter operand: The value to negate. override static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The result is always exact. This example uses the `negate()` method to /// negate the value of the variable `x`: /// /// var x = 21.5 /// x.negate() /// // x == -21.5 override mutating func negate() /// Subtracts one value from another and produces their difference, rounded /// to a representable value. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x - 2.25 /// // y == 5.25 /// /// The `-` operator implements the subtraction operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in /// the left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product, rounding to a /// representable value. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x * 2.25 /// // y == 16.875 /// /// The `*` operator implements the multiplication operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the quotient of dividing the first value by the second, rounded /// to a representable value. /// /// The division operator (`/`) calculates the quotient of the division if /// `rhs` is nonzero. If `rhs` is zero, the result of the division is /// infinity, with the sign of the result matching the sign of `lhs`. /// /// let x = 16.875 /// let y = x / 2.25 /// // y == 7.5 /// /// let z = x / 0 /// // z.isInfinite == true /// /// The `/` operator implements the division operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of this value divided by the given value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// let r = x.remainder(dividingBy: 0.75) /// // r == -0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `remainder(dividingBy:)` method is always exact. This method implements /// the remainder operation defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other`. func remainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// x.formRemainder(dividingBy: 0.75) /// // x == -0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `formRemainder(dividingBy:)` method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formRemainder(dividingBy other: Self) /// Returns the remainder of this value divided by the given value using /// truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// let r = x.truncatingRemainder(dividingBy: 0.75) /// // r == 0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method /// is always exact. /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other` using /// truncating division. func truncatingRemainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value using truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// x.formTruncatingRemainder(dividingBy: 0.75) /// // x == 0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` /// method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formTruncatingRemainder(dividingBy other: Self) /// Returns the square root of the value, rounded to a representable value. /// /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// /// func hypotenuse(_ a: Double, _ b: Double) -> Double { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// - Returns: The square root of the value. func squareRoot() -> Self /// Replaces this value with its square root, rounded to a representable /// value. mutating func formSquareRoot() /// Returns the result of adding the product of the two given values to this /// value, computed without intermediate rounding. /// /// This method is equivalent to the C `fma` function and implements the /// `fusedMultiplyAdd` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. /// - Returns: The product of `lhs` and `rhs`, added to this value. func addingProduct(_ lhs: Self, _ rhs: Self) -> Self /// Adds the product of the two given values to this value in place, computed /// without intermediate rounding. /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. mutating func addProduct(_ lhs: Self, _ rhs: Self) /// Returns the lesser of the two given values. /// /// This method returns the minimum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.minimum(10.0, -25.0) /// // -25.0 /// Double.minimum(10.0, .nan) /// // 10.0 /// Double.minimum(.nan, -25.0) /// // -25.0 /// Double.minimum(.nan, .nan) /// // nan /// /// The `minimum` method implements the `minNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The minimum of `x` and `y`, or whichever is a number if the /// other is NaN. static func minimum(_ x: Self, _ y: Self) -> Self /// Returns the greater of the two given values. /// /// This method returns the maximum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.maximum(10.0, -25.0) /// // 10.0 /// Double.maximum(10.0, .nan) /// // 10.0 /// Double.maximum(.nan, -25.0) /// // -25.0 /// Double.maximum(.nan, .nan) /// // nan /// /// The `maximum` method implements the `maxNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The greater of `x` and `y`, or whichever is a number if the /// other is NaN. static func maximum(_ x: Self, _ y: Self) -> Self /// Returns the value with lesser magnitude. /// /// This method returns the value with lesser magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.minimumMagnitude(10.0, -25.0) /// // 10.0 /// Double.minimumMagnitude(10.0, .nan) /// // 10.0 /// Double.minimumMagnitude(.nan, -25.0) /// // -25.0 /// Double.minimumMagnitude(.nan, .nan) /// // nan /// /// The `minimumMagnitude` method implements the `minNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is /// a number if the other is NaN. static func minimumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns the value with greater magnitude. /// /// This method returns the value with greater magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.maximumMagnitude(10.0, -25.0) /// // -25.0 /// Double.maximumMagnitude(10.0, .nan) /// // 10.0 /// Double.maximumMagnitude(.nan, -25.0) /// // -25.0 /// Double.maximumMagnitude(.nan, .nan) /// // nan /// /// The `maximumMagnitude` method implements the `maxNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is /// a number if the other is NaN. static func maximumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns this value rounded to an integral value using the specified /// rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// let x = 6.5 /// /// // Equivalent to the C 'round' function: /// print(x.rounded(.toNearestOrAwayFromZero)) /// // Prints "7.0" /// /// // Equivalent to the C 'trunc' function: /// print(x.rounded(.towardZero)) /// // Prints "6.0" /// /// // Equivalent to the C 'ceil' function: /// print(x.rounded(.up)) /// // Prints "7.0" /// /// // Equivalent to the C 'floor' function: /// print(x.rounded(.down)) /// // Prints "6.0" /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `rounded()` /// method instead. /// /// print(x.rounded()) /// // Prints "7.0" /// /// - Parameter rule: The rounding rule to use. /// - Returns: The integral value found by rounding using `rule`. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Rounds the value to an integral value using the specified rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// // Equivalent to the C 'round' function: /// var w = 6.5 /// w.round(.toNearestOrAwayFromZero) /// // w == 7.0 /// /// // Equivalent to the C 'trunc' function: /// var x = 6.5 /// x.round(.towardZero) /// // x == 6.0 /// /// // Equivalent to the C 'ceil' function: /// var y = 6.5 /// y.round(.up) /// // y == 7.0 /// /// // Equivalent to the C 'floor' function: /// var z = 6.5 /// z.round(.down) /// // z == 6.0 /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `round()` method /// instead. /// /// var w1 = 6.5 /// w1.round() /// // w1 == 7.0 /// /// - Parameter rule: The rounding rule to use. mutating func round(_ rule: FloatingPointRoundingRule) /// The least representable value that compares greater than this value. /// /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or /// `infinity`, `x.nextUp` is `x` itself. The following special cases also /// apply: /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. var nextUp: Self { get } /// The greatest representable value that compares less than this value. /// /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. var nextDown: Self { get } /// Returns a Boolean value indicating whether this instance is equal to the /// given value. /// /// This method serves as the basis for the equal-to operator (`==`) for /// floating-point values. When comparing two values with this method, `-0` /// is equal to `+0`. NaN is not equal to any value, including itself. For /// example: /// /// let x = 15.0 /// x.isEqual(to: 15.0) /// // true /// x.isEqual(to: .nan) /// // false /// Double.nan.isEqual(to: .nan) /// // false /// /// The `isEqual(to:)` method implements the equality predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; /// otherwise, `false`. If either this value or `other` is NaN, the result /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the /// given value. /// /// This method serves as the basis for the less-than operator (`<`) for /// floating-point values. Some special cases apply: /// /// - Because NaN compares not less than nor greater than any value, this /// method returns `false` when called on NaN or when NaN is passed as /// `other`. /// - `-infinity` compares less than all values except for itself and NaN. /// - Every value except for NaN and `+infinity` compares less than /// `+infinity`. /// /// let x = 15.0 /// x.isLess(than: 20.0) /// // true /// x.isLess(than: .nan) /// // false /// Double.nan.isLess(than: x) /// // false /// /// The `isLess(than:)` method implements the less-than predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if this value is less than `other`; otherwise, `false`. /// If either this value or `other` is NaN, the result of this method is /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or /// equal to the given value. /// /// This method serves as the basis for the less-than-or-equal-to operator /// (`<=`) for floating-point values. Some special cases apply: /// /// - Because NaN is incomparable with any value, this method returns `false` /// when called on NaN or when NaN is passed as `other`. /// - `-infinity` compares less than or equal to all values except NaN. /// - Every value except NaN compares less than or equal to `+infinity`. /// /// let x = 15.0 /// x.isLessThanOrEqualTo(20.0) /// // true /// x.isLessThanOrEqualTo(.nan) /// // false /// Double.nan.isLessThanOrEqualTo(x) /// // false /// /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal /// predicate defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` is greater than this value; otherwise, /// `false`. If either this value or `other` is NaN, the result of this /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool /// Returns a Boolean value indicating whether this instance should precede /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including /// signed zeros and NaNs. /// /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } /// print(numbers) /// // Prints "[-9.5, 2.5, 3.0, 21.25, nan]" /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. /// - Returns: `true` if this value is ordered below or the same as `other` /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. /// /// A *normal* value is a finite number that uses the full precision /// available to values of a type. Zero is neither a normal nor a subnormal /// number. var isNormal: Bool { get } /// A Boolean value indicating whether this instance is finite. /// /// All values other than NaN and infinity are considered finite, whether /// normal or subnormal. var isFinite: Bool { get } /// A Boolean value indicating whether the instance is equal to zero. /// /// The `isZero` property of a value `x` is `true` when `x` represents either /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: /// `x == 0.0`. /// /// let x = -0.0 /// x.isZero // true /// x == 0.0 // true var isZero: Bool { get } /// A Boolean value indicating whether the instance is subnormal. /// /// A *subnormal* value is a nonzero number that has a lesser magnitude than /// the smallest normal number. Subnormal values do not use the full /// precision available to values of a type. /// /// Zero is neither a normal nor a subnormal number. Subnormal numbers are /// often called *denormal* or *denormalized*---these are different names /// for the same concept. var isSubnormal: Bool { get } /// A Boolean value indicating whether the instance is infinite. /// /// Note that `isFinite` and `isInfinite` do not form a dichotomy, because /// they are not total: If `x` is `NaN`, then both properties are `false`. var isInfinite: Bool { get } /// A Boolean value indicating whether the instance is NaN ("not a number"). /// /// Because NaN is not equal to any value, including NaN, use this property /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) /// to test whether a value is or is not NaN. For example: /// /// let x = 0.0 /// let y = x * .infinity /// // y is a NaN /// /// // Comparing with the equal-to operator never returns 'true' /// print(x == Double.nan) /// // Prints "false" /// print(y == Double.nan) /// // Prints "false" /// /// // Test with the 'isNaN' property instead /// print(x.isNaN) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" /// /// This property is `true` for both quiet and signaling NaNs. var isNaN: Bool { get } /// A Boolean value indicating whether the instance is a signaling NaN. /// /// Signaling NaNs typically raise the Invalid flag when used in general /// computing operations. var isSignalingNaN: Bool { get } /// The classification of this value. /// /// A value's `floatingPointClass` property describes its "class" as /// described by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var floatingPointClass: FloatingPointClassification { get } /// A Boolean value indicating whether the instance's representation is in /// its canonical form. /// /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, /// encoding of a floating-point value. On platforms that fully support /// IEEE 754, every `Float` or `Double` value is canonical, but /// non-canonical values can exist on other platforms or for other types. /// Some examples: /// /// - On platforms that flush subnormal numbers to zero (such as armv7 /// with the default floating-point environment), Swift interprets /// subnormal `Float` and `Double` values as non-canonical zeros. /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these /// values, which is the incorrect value.) /// /// - On i386 and x86_64, `Float80` has a number of non-canonical /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are /// interpreted as non-canonical encodings of subnormal values. /// /// - Decimal floating-point types admit a large number of non-canonical /// encodings. Consult the IEEE 754 standard for additional details. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var isCanonical: Bool { get } } /// The sign of a floating-point value. @frozen public enum FloatingPointSign: Int { /// The sign for a positive value. case plus /// The sign for a negative value. case minus // Explicit declarations of otherwise-synthesized members to make them // @inlinable, promising that we will never change the implementation. @inlinable public init?(rawValue: Int) { switch rawValue { case 0: self = .plus case 1: self = .minus default: return nil } } @inlinable public var rawValue: Int { switch self { case .plus: return 0 case .minus: return 1 } } @_transparent @inlinable public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool { return a.rawValue == b.rawValue } @inlinable public var hashValue: Int { return rawValue.hashValue } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable public func _rawHashValue(seed: Int) -> Int { return rawValue._rawHashValue(seed: seed) } } /// The IEEE 754 floating-point classes. @frozen public enum FloatingPointClassification { /// A signaling NaN ("not a number"). /// /// A signaling NaN sets the floating-point exception status when used in /// many floating-point operations. case signalingNaN /// A silent NaN ("not a number") value. case quietNaN /// A value equal to `-infinity`. case negativeInfinity /// A negative value that uses the full precision of the floating-point type. case negativeNormal /// A negative, nonzero number that does not use the full precision of the /// floating-point type. case negativeSubnormal /// A value equal to zero with a negative sign. case negativeZero /// A value equal to zero with a positive sign. case positiveZero /// A positive, nonzero number that does not use the full precision of the /// floating-point type. case positiveSubnormal /// A positive value that uses the full precision of the floating-point type. case positiveNormal /// A value equal to `+infinity`. case positiveInfinity } /// A rule for rounding a floating-point number. public enum FloatingPointRoundingRule { /// Round to the closest allowed value; if two values are equally close, the /// one with greater magnitude is chosen. /// /// This rounding rule is also known as "schoolbook rounding." The following /// example shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrAwayFromZero) /// // 5.0 /// (5.5).rounded(.toNearestOrAwayFromZero) /// // 6.0 /// (-5.2).rounded(.toNearestOrAwayFromZero) /// // -5.0 /// (-5.5).rounded(.toNearestOrAwayFromZero) /// // -6.0 /// /// This rule is equivalent to the C `round` function and implements the /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrAwayFromZero /// Round to the closest allowed value; if two values are equally close, the /// even one is chosen. /// /// This rounding rule is also known as "bankers rounding," and is the /// default IEEE 754 rounding mode for arithmetic. The following example /// shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrEven) /// // 5.0 /// (5.5).rounded(.toNearestOrEven) /// // 6.0 /// (4.5).rounded(.toNearestOrEven) /// // 4.0 /// /// This rule implements the `roundToIntegralTiesToEven` operation defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrEven /// Round to the closest allowed value that is greater than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.up) /// // 6.0 /// (5.5).rounded(.up) /// // 6.0 /// (-5.2).rounded(.up) /// // -5.0 /// (-5.5).rounded(.up) /// // -5.0 /// /// This rule is equivalent to the C `ceil` function and implements the /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case up /// Round to the closest allowed value that is less than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.down) /// // 5.0 /// (5.5).rounded(.down) /// // 5.0 /// (-5.2).rounded(.down) /// // -6.0 /// (-5.5).rounded(.down) /// // -6.0 /// /// This rule is equivalent to the C `floor` function and implements the /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case down /// Round to the closest allowed value whose magnitude is less than or equal /// to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.towardZero) /// // 5.0 /// (5.5).rounded(.towardZero) /// // 5.0 /// (-5.2).rounded(.towardZero) /// // -5.0 /// (-5.5).rounded(.towardZero) /// // -5.0 /// /// This rule is equivalent to the C `trunc` function and implements the /// `roundToIntegralTowardZero` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case towardZero /// Round to the closest allowed value whose magnitude is greater than or /// equal to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.awayFromZero) /// // 6.0 /// (5.5).rounded(.awayFromZero) /// // 6.0 /// (-5.2).rounded(.awayFromZero) /// // -6.0 /// (-5.5).rounded(.awayFromZero) /// // -6.0 case awayFromZero } extension FloatingPoint { @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.isEqual(to: rhs) } @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.isLess(than: rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs.isLessThanOrEqualTo(rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs.isLess(than: lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return rhs.isLessThanOrEqualTo(lhs) } } /// A radix-2 (binary) floating-point type. /// /// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol /// with operations specific to floating-point binary types, as defined by the /// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in /// the standard library by `Float`, `Double`, and `Float80` where available. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { /// A type that represents the encoded significand of a value. associatedtype RawSignificand: UnsignedInteger /// A type that represents the encoded exponent of a value. associatedtype RawExponent: UnsignedInteger /// Creates a new instance from the specified sign and bit patterns. /// /// The values passed as `exponentBitPattern` and `significandBitPattern` are /// interpreted in the binary interchange format defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign of the new value. /// - exponentBitPattern: The bit pattern to use for the exponent field of /// the new value. /// - significandBitPattern: The bit pattern to use for the significand /// field of the new value. init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Double) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float80) #endif /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. init<Source: BinaryFloatingPoint>(_ value: Source) /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. A value that is NaN ("not a number") cannot be /// represented exactly if its payload cannot be encoded exactly. /// /// - Parameter value: A floating-point value to be converted. init?<Source: BinaryFloatingPoint>(exactly value: Source) /// The number of bits used to represent the type's exponent. /// /// A binary floating-point type's `exponentBitCount` imposes a limit on the /// range of the exponent for normal, finite values. The *exponent bias* of /// a type `F` can be calculated as the following, where `**` is /// exponentiation: /// /// let bias = 2 ** (F.exponentBitCount - 1) - 1 /// /// The least normal exponent for values of the type `F` is `1 - bias`, and /// the largest finite exponent is `bias`. An all-zeros exponent is reserved /// for subnormals and zeros, and an all-ones exponent is reserved for /// infinity and NaN. /// /// For example, the `Float` type has an `exponentBitCount` of 8, which gives /// an exponent bias of `127` by the calculation above. /// /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 /// // bias == 127 /// print(Float.greatestFiniteMagnitude.exponent) /// // Prints "127" /// print(Float.leastNormalMagnitude.exponent) /// // Prints "-126" static var exponentBitCount: Int { get } /// The available number of fractional significand bits. /// /// For fixed-width floating-point types, this is the actual number of /// fractional significand bits. /// /// For extensible floating-point types, `significandBitCount` should be the /// maximum allowed significand width (without counting any leading integral /// bit of the significand). If there is no upper limit, then /// `significandBitCount` should be `Int.max`. /// /// Note that `Float80.significandBitCount` is 63, even though 64 bits are /// used to store the significand in the memory representation of a /// `Float80` (unlike other floating-point types, `Float80` explicitly /// stores the leading integral significand bit, but the /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't /// need to be aware of this detail). static var significandBitCount: Int { get } /// The raw encoding of the value's exponent field. /// /// This value is unadjusted by the type's exponent bias. var exponentBitPattern: RawExponent { get } /// The raw encoding of the value's significand field. /// /// The `significandBitPattern` property does not include the leading /// integral bit of the significand, even for types like `Float80` that /// store it explicitly. var significandBitPattern: RawSignificand { get } /// The floating-point value with the same sign and exponent as this value, /// but with a significand of 1.0. /// /// A *binade* is a set of binary floating-point values that all have the /// same sign and exponent. The `binade` property is a member of the same /// binade as this value, but with a unit significand. /// /// In this example, `x` has a value of `21.5`, which is stored as /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is /// equal to `1.0 * 2**4`, or `16.0`. /// /// let x = 21.5 /// // x.significand == 1.34375 /// // x.exponent == 4 /// /// let y = x.binade /// // y == 16.0 /// // y.significand == 1.0 /// // y.exponent == 4 var binade: Self { get } /// The number of bits required to represent the value's significand. /// /// If this value is a finite nonzero number, `significandWidth` is the /// number of fractional bits required to represent the value of /// `significand`; otherwise, `significandWidth` is -1. The value of /// `significandWidth` is always -1 or between zero and /// `significandBitCount`. For example: /// /// - For any representable power of two, `significandWidth` is zero, because /// `significand` is `1.0`. /// - If `x` is 10, `x.significand` is `1.01` in binary, so /// `x.significandWidth` is 2. /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in /// binary, and `x.significandWidth` is 23. var significandWidth: Int { get } } extension FloatingPoint { @inlinable // FIXME(sil-serialize-all) public static var ulpOfOne: Self { return (1 as Self).ulp } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs } @_transparent public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } @_transparent public mutating func round() { round(.toNearestOrAwayFromZero) } @inlinable // FIXME(inline-always) public var nextDown: Self { @inline(__always) get { return -(-self).nextUp } } @inlinable // FIXME(inline-always) @inline(__always) public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self lhs.formTruncatingRemainder(dividingBy: other) return lhs } @inlinable // FIXME(inline-always) @inline(__always) public func remainder(dividingBy other: Self) -> Self { var lhs = self lhs.formRemainder(dividingBy: other) return lhs } @_transparent public func squareRoot( ) -> Self { var lhs = self lhs.formSquareRoot( ) return lhs } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self addend.addProduct(lhs, rhs) return addend } @inlinable public static func minimum(_ x: Self, _ y: Self) -> Self { if x <= y || y.isNaN { return x } return y } @inlinable public static func maximum(_ x: Self, _ y: Self) -> Self { if x > y || y.isNaN { return x } return y } @inlinable public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude <= y.magnitude || y.isNaN { return x } return y } @inlinable public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude > y.magnitude || y.isNaN { return x } return y } @inlinable public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity } if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal } if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal } return sign == .minus ? .negativeZero : .positiveZero } } extension BinaryFloatingPoint { @inlinable @inline(__always) public static var radix: Int { return 2 } @inlinable public init(signOf: Self, magnitudeOf: Self) { self.init( sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern ) } @inlinable public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self, exact: Bool) { guard _fastPath(!source.isZero) else { return (source.sign == .minus ? -0.0 : 0, true) } guard _fastPath(source.isFinite) else { if source.isInfinite { return (source.sign == .minus ? -.infinity : .infinity, true) } // IEEE 754 requires that any NaN payload be propagated, if possible. let payload_ = source.significandBitPattern & ~(Source.nan.significandBitPattern | Source.signalingNaN.significandBitPattern) let mask = Self.greatestFiniteMagnitude.significandBitPattern & ~(Self.nan.significandBitPattern | Self.signalingNaN.significandBitPattern) let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern, // we do not *need* to rely on this relation, and therefore we do not. let value = source.isSignalingNaN ? Self( sign: source.sign, exponentBitPattern: Self.signalingNaN.exponentBitPattern, significandBitPattern: payload | Self.signalingNaN.significandBitPattern) : Self( sign: source.sign, exponentBitPattern: Self.nan.exponentBitPattern, significandBitPattern: payload | Self.nan.significandBitPattern) // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. return (value, false) } let exponent = source.exponent var exemplar = Self.leastNormalMagnitude let exponentBitPattern: Self.RawExponent let leadingBitIndex: Int let shift: Int let significandBitPattern: Self.RawSignificand if exponent < exemplar.exponent { // The floating-point result is either zero or subnormal. exemplar = Self.leastNonzeroMagnitude let minExponent = exemplar.exponent if exponent + 1 < minExponent { return (source.sign == .minus ? -0.0 : 0, false) } if _slowPath(exponent + 1 == minExponent) { // Although the most significant bit (MSB) of a subnormal source // significand is explicit, Swift BinaryFloatingPoint APIs actually // omit any explicit MSB from the count represented in // significandWidth. For instance: // // Double.leastNonzeroMagnitude.significandWidth == 0 // // Therefore, we do not need to adjust our work here for a subnormal // source. return source.significandWidth == 0 ? (source.sign == .minus ? -0.0 : 0, false) : (source.sign == .minus ? -exemplar : exemplar, false) } exponentBitPattern = 0 as Self.RawExponent leadingBitIndex = Int(Self.Exponent(exponent) - minExponent) shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let leadingBit = source.isNormal ? (1 as Self.RawSignificand) << leadingBitIndex : 0 significandBitPattern = leadingBit | (shift >= 0 ? Self.RawSignificand(source.significandBitPattern) << shift : Self.RawSignificand(source.significandBitPattern >> -shift)) } else { // The floating-point result is either normal or infinite. exemplar = Self.greatestFiniteMagnitude if exponent > exemplar.exponent { return (source.sign == .minus ? -.infinity : .infinity, false) } exponentBitPattern = exponent < 0 ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent) : (1 as Self).exponentBitPattern + Self.RawExponent(exponent) leadingBitIndex = exemplar.significandWidth shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let sourceLeadingBit = source.isSubnormal ? (1 as Source.RawSignificand) << (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) : 0 significandBitPattern = shift >= 0 ? Self.RawSignificand( sourceLeadingBit ^ source.significandBitPattern) << shift : Self.RawSignificand( (sourceLeadingBit ^ source.significandBitPattern) >> -shift) } let value = Self( sign: source.sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) if source.significandWidth <= leadingBitIndex { return (value, true) } // We promise to round to the closest representation. Therefore, we must // take a look at the bits that we've just truncated. let ulp = (1 as Source.RawSignificand) << -shift let truncatedBits = source.significandBitPattern & (ulp - 1) if truncatedBits < ulp / 2 { return (value, false) } let rounded = source.sign == .minus ? value.nextDown : value.nextUp if _fastPath(truncatedBits > ulp / 2) { return (rounded, false) } // If two representable values are equally close, we return the value with // more trailing zeros in its significand bit pattern. return significandBitPattern.trailingZeroBitCount > rounded.significandBitPattern.trailingZeroBitCount ? (value, false) : (rounded, false) } /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init<Source: BinaryFloatingPoint>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init?<Source: BinaryFloatingPoint>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } @inlinable public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } if other > self { return false } // Self and other are either equal or unordered. // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // sign bit of self. if sign != other.sign { return sign == .minus } // Sign bits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return sign == .minus } if exponentBitPattern < other.exponentBitPattern { return sign == .plus } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return sign == .minus } if significandBitPattern < other.significandBitPattern { return sign == .plus } // Sign, exponent, and significand all match. return true } } extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger { @inlinable public // @testable static func _convert<Source: BinaryInteger>( from source: Source ) -> (value: Self, exact: Bool) { // Useful constants: let exponentBias = (1 as Self).exponentBitPattern let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1 // Zero is really extra simple, and saves us from trying to normalize a // value that cannot be normalized. if _fastPath(source == 0) { return (0, true) } // We now have a non-zero value; convert it to a strictly positive value // by taking the magnitude. let magnitude = source.magnitude var exponent = magnitude._binaryLogarithm() // If the exponent would be larger than the largest representable // exponent, the result is just an infinity of the appropriate sign. guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } // If exponent <= significandBitCount, we don't need to round it to // construct the significand; we just need to left-shift it into place; // the result is always exact as we've accounted for exponent-too-large // already and no rounding can occur. if exponent <= Self.significandBitCount { let shift = Self.significandBitCount &- exponent let significand = RawSignificand(magnitude) &<< shift let value = Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ) return (value, true) } // exponent > significandBitCount, so we need to do a rounding right // shift, and adjust exponent if needed let shift = exponent &- Self.significandBitCount let halfway = (1 as Source.Magnitude) << (shift - 1) let mask = 2 * halfway - 1 let fraction = magnitude & mask var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask if fraction > halfway || (fraction == halfway && significand & 1 == 1) { var carry = false (significand, carry) = significand.addingReportingOverflow(1) if carry || significand > significandMask { exponent += 1 guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } } } return (Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ), fraction == 0) } /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init<Source: BinaryInteger>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init?<Source: BinaryInteger>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate a floating-point value within a specific /// range when you are using a custom random number generator. This example /// creates three new values in the range `10.0 ..< 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ..< 20.0, using: &myGenerator)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random(in:using:)` static method chooses a random value from a /// continuous uniform distribution in `range`, and then converts that value /// to the nearest representable value in this type. Depending on the size /// and span of `range`, some concrete values may be represented more /// frequently than others. /// /// - Note: The algorithm used to create random values may change in a future /// version of Swift. If you're passing a generator that results in the /// same sequence of floating-point values each time you run your program, /// that sequence may change when your program is compiled using a /// different version of Swift. /// /// - Parameters: /// - range: The range in which to create a random value. /// `range` must be finite and non-empty. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: Range<Self>, using generator: inout T ) -> Self { _precondition( !range.isEmpty, "Can't get random value with an empty range" ) let delta = range.upperBound - range.lowerBound // TODO: this still isn't quite right, because the computation of delta // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and // .lowerBound = -.upperBound); this should be re-written with an // algorithm that handles that case correctly, but this precondition // is an acceptable short-term fix. _precondition( delta.isFinite, "There is no uniform distribution on an infinite range" ) let rand: Self.RawSignificand if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 { rand = generator.next() } else { let significandCount = Self.significandBitCount + 1 let maxSignificand: Self.RawSignificand = 1 << significandCount // Rather than use .next(upperBound:), which has to work with arbitrary // upper bounds, and therefore does extra work to avoid bias, we can take // a shortcut because we know that maxSignificand is a power of two. rand = generator.next() & (maxSignificand - 1) } let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2) let randFloat = delta * unitRandom + range.lowerBound if randFloat == range.upperBound { return Self.random(in: range, using: &generator) } return randFloat } /// Returns a random value within the specified range. /// /// Use this method to generate a floating-point value within a specific /// range. This example creates three new values in the range /// `10.0 ..< 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ..< 20.0)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random()` static method chooses a random value from a continuous /// uniform distribution in `range`, and then converts that value to the /// nearest representable value in this type. Depending on the size and span /// of `range`, some concrete values may be represented more frequently than /// others. /// /// This method is equivalent to calling `random(in:using:)`, passing in the /// system's default random generator. /// /// - Parameter range: The range in which to create a random value. /// `range` must be finite and non-empty. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: Range<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate a floating-point value within a specific /// range when you are using a custom random number generator. This example /// creates three new values in the range `10.0 ... 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ... 20.0, using: &myGenerator)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random(in:using:)` static method chooses a random value from a /// continuous uniform distribution in `range`, and then converts that value /// to the nearest representable value in this type. Depending on the size /// and span of `range`, some concrete values may be represented more /// frequently than others. /// /// - Note: The algorithm used to create random values may change in a future /// version of Swift. If you're passing a generator that results in the /// same sequence of floating-point values each time you run your program, /// that sequence may change when your program is compiled using a /// different version of Swift. /// /// - Parameters: /// - range: The range in which to create a random value. Must be finite. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: ClosedRange<Self>, using generator: inout T ) -> Self { _precondition( !range.isEmpty, "Can't get random value with an empty range" ) let delta = range.upperBound - range.lowerBound // TODO: this still isn't quite right, because the computation of delta // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and // .lowerBound = -.upperBound); this should be re-written with an // algorithm that handles that case correctly, but this precondition // is an acceptable short-term fix. _precondition( delta.isFinite, "There is no uniform distribution on an infinite range" ) let rand: Self.RawSignificand if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 { rand = generator.next() let tmp: UInt8 = generator.next() & 1 if rand == Self.RawSignificand.max && tmp == 1 { return range.upperBound } } else { let significandCount = Self.significandBitCount + 1 let maxSignificand: Self.RawSignificand = 1 << significandCount rand = generator.next(upperBound: maxSignificand + 1) if rand == maxSignificand { return range.upperBound } } let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2) let randFloat = delta * unitRandom + range.lowerBound return randFloat } /// Returns a random value within the specified range. /// /// Use this method to generate a floating-point value within a specific /// range. This example creates three new values in the range /// `10.0 ... 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ... 20.0)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random()` static method chooses a random value from a continuous /// uniform distribution in `range`, and then converts that value to the /// nearest representable value in this type. Depending on the size and span /// of `range`, some concrete values may be represented more frequently than /// others. /// /// This method is equivalent to calling `random(in:using:)`, passing in the /// system's default random generator. /// /// - Parameter range: The range in which to create a random value. Must be finite. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: ClosedRange<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } }
d08de330bdb56b50fa13dd5123cbd6d5
37.283461
94
0.641028
false
false
false
false
WilliamNi/SwiftXmlSerializable
refs/heads/master
XmlSerializableExample/Test.swift
mit
1
// // Test.swift // XmlSerializable // // Created by ixprt13 on 9/16/15. // Copyright © 2015 williamni. All rights reserved. // import Foundation struct InternalStruct: XmlSavable, XmlRetrievable{ var a:Int = 10 var b:String = "b" var c:Bool = true var d:Double = 20.20 var e:NSDate = NSDate() var optA:Int? = nil var optB:String? = "optB" } // //conforming XmlSerializable extension InternalStruct{ static func fromXmlElem(root:AEXMLElement)throws -> InternalStruct { var ret = InternalStruct() do{ ret.a = try Int.fromXmlElem(root["a"]) ret.b = try String.fromXmlElem(root["b"]) ret.c = try Bool.fromXmlElem(root["c"]) ret.d = try Double.fromXmlElem(root["d"]) ret.e = try NSDate.fromXmlElem(root["e"]) ret.optA = try (Int?).fromXmlElem(root["optA"]) ret.optB = try (String?).fromXmlElem(root["optB"]) } return ret } } class MyClass: XmlSavable, XmlRetrievable{ var internalStruct:InternalStruct var arr:[String] var dict:[String: Int] required init(){ internalStruct = InternalStruct() arr = [String]() dict = [:] } } // //conforming XmlSerializable extension MyClass{ static func fromXmlElem(root:AEXMLElement)throws -> Self { let ret = self.init() do{ ret.internalStruct = try InternalStruct.fromXmlElem(root["internalStruct"]) ret.arr = try [String].fromXmlElem(root["arr"]) ret.dict = try [String: Int].fromXmlElem(root["dict"]) } return ret } } func compare(lVal:MyClass, rVal:MyClass) -> Bool{ if lVal.internalStruct.a != rVal.internalStruct.a {return false} if lVal.internalStruct.b != rVal.internalStruct.b {return false} if lVal.internalStruct.c != rVal.internalStruct.c {return false} if lVal.internalStruct.d != rVal.internalStruct.d {return false} if (lVal.internalStruct.e.timeIntervalSince1970 - rVal.internalStruct.e.timeIntervalSince1970) > 0.01 {return false} if lVal.internalStruct.optA != rVal.internalStruct.optA {return false} if lVal.internalStruct.optB != rVal.internalStruct.optB {return false} for var i = 0; i < lVal.arr.count; i++ { if lVal.arr[i] != rVal.arr[i] {return false} } for (key, _) in lVal.dict { if lVal.dict[key] != rVal.dict[key] {return false} } return true }
4034b9d10f3fd40a4b2c5e1c5eab83a8
27.872093
120
0.619815
false
false
false
false