repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
marko1503/Algorithms-and-Data-Structures-Swift
Sort/Insertion Sort/InsertionSort.playground/Pages/Version_1.xcplaygroundpage/Contents.swift
1
1903
//: Playground - noun: a place where people can play import Foundation // MARK: - Insertion sort algorithm //: Comlexity: O(n^2), Storage: 2N //: ![Sort example](Insertion_sort_example_n_storage.pdf) func insertionSort<Element>(array: [Element]) -> [Element] where Element: Comparable { // check for tirivial case // we have only 1 element in array guard array.count > 1 else { return array } var output: [Element] = array let elementsCount = output.count for primaryIndex in 0..<elementsCount { let primaryElement = output[primaryIndex] var tempIndex = primaryIndex - 1 while tempIndex > -1 && output[tempIndex] > primaryElement { // primaryElement and element at tempIndex are not ordered. We need to change them // Then, remove primary element // tempIndex + 1 - primaryElement always after tempIndex output.remove(at: tempIndex + 1) // and insert primary element before tempElement output.insert(primaryElement, at: tempIndex) tempIndex -= 1 } } return output } //func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { // var a = array // for x in 1..<a.count { // var y = x // let temp = a[y] // while y > 0 && isOrderedBefore(temp, a[y - 1]) { // a[y] = a[y - 1] // y -= 1 // } // a[y] = temp // } // return a //} //let array = [Int]() //insertionSort(array: array) //let array = [5] //insertionSort(array: array) //let array = [5, 8] //insertionSort(array: array) //let array = [8, 5] //insertionSort(array: array) //let array = [1, 2, 3, 4, 5, 6, 7, 8] //insertionSort(array: array) //let array = [8, 7, 6, 5, 4, 3, 2, 1] //insertionSort(array: array) let array = [7, 2, 1, 6, 8, 5, 3, 4] insertionSort(array: array) //: [Next](@next)
apache-2.0
2c2eea769fd3d68864a0d32f0a9e8803
25.430556
94
0.584341
3.435018
false
false
false
false
MooseMagnet/DeliciousPubSub
DeliciousPubSub/PubSub.swift
1
3923
// // PubSub.swift // DeliciousPubSub // import Foundation open class PubSub { private var handlers: [String: ArrayReference<Handler>] = [:] internal let dispatchImmediately: Bool private var unhandledMessages: Array<Any> = [] public init(dispatchImmediately: Bool) { self.dispatchImmediately = dispatchImmediately } public convenience init() { self.init(dispatchImmediately: true) } deinit { handlers.removeAll() } // // MARK: Sub. // open func sub<T: Any>(_ fn: @escaping (T) -> Void) -> () -> Void { let typeName = String(describing: T.self) if (handlers[typeName] == nil) { handlers[typeName] = ArrayReference<Handler>(array: []) } var unsubbed = false let handler = Handler(handlingFunction: { (any: Any) in if (unsubbed) { return } fn(any as! T) }) handlers[typeName]!.append(handler) return { if (unsubbed) { return } self.handlers[typeName]!.remove(handler) unsubbed = true } } open func sub<T: Any>(_ type: T.Type, fn: @escaping (T) -> Void) -> () -> Void { return sub(fn) } open func sub<T: Any>(predicate: @escaping (T) -> Bool, fn: @escaping (T) -> Void) -> () -> Void { let predicatedFn: (T) -> Void = { if predicate($0) { fn($0) } } return sub(predicatedFn) } open func sub<T: Any>(_ type: T.Type, predicate: @escaping (T) -> Bool, fn: @escaping (T) -> Void) -> () -> Void { return sub(predicate: predicate, fn: fn) } // // MARK: Sub Once. // open func subOnce<T: Any>(_ fn: @escaping (T) -> Void) -> () -> Void { var unsub: () -> Void = { fatalError("unsub should be re-assigned to the unsub function.") } let unsubbingFn: (T) -> Void = { fn($0) unsub() } unsub = sub(unsubbingFn) return unsub } open func subOnce<T: Any>(_ type: T.Type, fn: @escaping (T) -> Void) -> () -> Void { return subOnce(fn) } open func subOnce<T: Any>(predicate: @escaping (T) -> Bool, fn: @escaping (T) -> Void) -> () -> Void { var unsub: () -> Void = { fatalError("unsub should be re-assigned to the unsub function.") } let unsubbingFn: (T) -> Void = { fn($0) unsub() } unsub = sub(predicate: predicate, fn: unsubbingFn) return unsub } open func subOnce<T: Any>(_ type: T.Type, predicate: @escaping (T) -> Bool, fn: @escaping (T) -> Void) -> () -> Void { return subOnce(predicate: predicate, fn: fn) } // // MARK: Pub and Dispatch. // open func pub(_ message: Any) { if (dispatchImmediately) { dispatchMessageOfType(getTypeNameOf(message), message: message) } else { unhandledMessages.append(message) } } open func dispatchMessages() { while (unhandledMessages.count > 0) { let message = unhandledMessages.removeFirst() dispatchMessageOfType( getTypeNameOf(message), message: message) } } fileprivate func getTypeNameOf(_ object: Any) -> String { return String(describing: Mirror(reflecting: object).subjectType) } fileprivate func dispatchMessageOfType(_ typeName: String, message: Any) { guard let typeHandlers = handlers[typeName] else { return } for (_, handler) in typeHandlers.array.enumerated() { handler.handle(message) } } }
mit
a8c1601989960989c4d92922c5721ea6
25.687075
122
0.506755
4.133825
false
false
false
false
imsz5460/DouYu
DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift
1
9316
// // RecommendViewController.swift // DYZB // // Created by shizhi on 17/2/24. // Copyright © 2017年 shizhi. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kItemW = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH = kItemW * 3 / 4 private let kPrettyItemH = kItemW * 4 / 3 private let kHeaderViewH : CGFloat = 50 private let kHeaderViewID = "kHeaderViewID" private let kPrettyCellID = "kPrettyCellID" private let kNormalCellID = "kNormalCellID" class RecommendViewController: UIViewController { // //懒加载属性 // private lazy var anchorGroups: [AnchorGroup] = [AnchorGroup]() // private lazy var bigdataGroup: AnchorGroup = AnchorGroup() // private lazy var prettyGroup: AnchorGroup = AnchorGroup() private lazy var recommendVM: RecommendVM = RecommendVM() private lazy var collectionView: UICollectionView = { [weak self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = kItemMargin layout.minimumInteritemSpacing = 0 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //2.创建UIcollectionview let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] collectionView.contentInset = UIEdgeInsetsMake(100, 0, kTabbarH, 0) collectionView.backgroundColor = UIColor.whiteColor() collectionView.registerNib(UINib(nibName: "CollectionNormalCell", bundle: nil),forCellWithReuseIdentifier: kNormalCellID) collectionView.registerNib(UINib(nibName: "CollectionPrettyCell", bundle: nil),forCellWithReuseIdentifier: kPrettyCellID) collectionView.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setUpUI() loadData() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: UI界面设置 extension RecommendViewController { func setUpUI() { view.addSubview(collectionView) } } extension RecommendViewController { func loadData() { recommendVM.loadData { self.collectionView.reloadData() } /* // let nowTime = NSDate().timeIntervalSince1970 // //// http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1488167931.49921 // // let parameters = ["limit": "4","offset":"0", "time" :"\(nowTime)"] // //创建队列组 //// let group: dispatch_group_t = dispatch_group_create(); // // 2.创建Group // let dGroup = dispatch_group_create() // // // 3.请求第一部分推荐数据 // dispatch_group_enter(dGroup) // // //多次执行耗时的异步操作 //// dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // // NetworkTools.requestDate(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" :"\(nowTime)"]) { (result) in // // guard let resultDict = result as? [String : NSObject] else { return } // guard let resultArray = resultDict["data"] as? [[String: NSObject]] else {return} // // // 3.1.设置组的属性 // self.bigdataGroup.tag_name = "热门" // self.bigdataGroup.icon_name = "home_header_hot" // // for dict in resultArray { // self.bigdataGroup.anchors.append(AnchorModel(dict: dict)) // } // // dispatch_group_leave(dGroup) // } // // // 3.3.离开组 //// } // // // dispatch_group_enter(dGroup) // //多次执行耗时的异步操作 //// dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // // NetworkTools.requestDate(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in // // self.prettyGroup.tag_name = "颜值" // self.prettyGroup.icon_name = "home_header_phone" // // guard let resultDict = result as? [String : NSObject] else { return } // guard let resultArray = resultDict["data"] as? [[String: NSObject]] else {return} // for dict in resultArray { // self.prettyGroup.anchors.append(AnchorModel(dict: dict)) // } // // // 3.3.离开组 // dispatch_group_leave(dGroup) // } // //// } // // // dispatch_group_enter(dGroup) // // //多次执行耗时的异步操作 //// dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // // NetworkTools.requestDate(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in // // guard let resultDict = result as? [String : NSObject] else { return } // guard let resultArray = resultDict["data"] as? [[String: NSObject]] else {return} // for dict in resultArray { // self.anchorGroups.append(AnchorGroup(dict: dict)) // } // // dispatch_group_leave(dGroup) // } // // //// } // // // // dispatch_group_notify(dGroup, dispatch_get_global_queue(0,0)) { // self.anchorGroups.insert(self.prettyGroup, atIndex: 0) // self.anchorGroups.insert(self.bigdataGroup, atIndex: 0) // // // // // 1.展示推荐数据 // // dispatch_async(dispatch_get_main_queue(), { // self.collectionView.reloadData() // }) // // } */ } } //MARK: -UICollectionViewDataSource extension RecommendViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return recommendVM.anchorGroups.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recommendVM.anchorGroups[section].anchors.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // var cell: UICollectionViewCell if indexPath.section == 1 { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kPrettyCellID, forIndexPath: indexPath) as! CollectionPrettyCell let group = recommendVM.anchorGroups[indexPath.section] cell.anchor = group.anchors[indexPath.item] return cell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kNormalCellID, forIndexPath: indexPath) as! CollectionNormalCell let group = recommendVM.anchorGroups[indexPath.section] cell.anchor = group.anchors[indexPath.item] return cell } // cell.backgroundColor = UIColor.redColor() // return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // 1.取出section的HeaderView let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeaderViewID, forIndexPath: indexPath) as! CollectionHeaderView headerView.group = recommendVM.anchorGroups[indexPath.section] return headerView } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } else { return CGSize(width: kItemW, height: kNormalItemH) } } }
mit
b97f73bfed597cd6cf939166177a8316
33.730038
189
0.593562
4.912856
false
false
false
false
hughbe/swift
test/SILGen/class_bound_protocols.swift
6
12351
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -module-name Swift -emit-silgen %s | %FileCheck %s enum Optional<T> { case some(T) case none } precedencegroup AssignmentPrecedence {} // -- Class-bound archetypes and existentials are *not* address-only and can // be manipulated using normal reference type value semantics. protocol NotClassBound { func notClassBoundMethod() } protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBound2Method() } class ConcreteClass : NotClassBound, ClassBound, ClassBound2 { func notClassBoundMethod() {} func classBoundMethod() {} func classBound2Method() {} } class ConcreteSubclass : ConcreteClass { } // CHECK-LABEL: sil hidden @_T0s19class_bound_generic{{[_0-9a-zA-Z]*}}F func class_bound_generic<T : ClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: destroy_value [[X_ADDR]] // CHECK: destroy_value [[X]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s21class_bound_generic_2{{[_0-9a-zA-Z]*}}F func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s20class_bound_protocol{{[_0-9a-zA-Z]*}}F func class_bound_protocol(x: ClassBound) -> ClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F func class_bound_protocol_composition(x: ClassBound & NotClassBound) -> ClassBound & NotClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound & NotClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s19class_bound_erasure{{[_0-9a-zA-Z]*}}F func class_bound_erasure(x: ConcreteClass) -> ClassBound { return x // CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound // CHECK: return [[PROTO]] } // CHECK-LABEL: sil hidden @_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF : func class_bound_existential_upcast(x: ClassBound & ClassBound2) -> ClassBound { return x // CHECK: bb0([[ARG:%.*]] : $ClassBound & ClassBound2): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[BORROWED_ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]] // CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] // CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[PROTO]] } // CHECK: } // end sil function '_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF' // CHECK-LABEL: sil hidden @_T0s41class_bound_to_unbound_existential_upcasts13NotClassBound_ps0hI0_sABp1x_tF : // CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[X_OPENED:%.*]] = open_existential_ref [[BORROWED_ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]] // CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]] // CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]] // CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] func class_bound_to_unbound_existential_upcast (x: ClassBound & NotClassBound) -> NotClassBound { return x } // CHECK-LABEL: sil hidden @_T0s18class_bound_methodys10ClassBound_p1x_tF : // CHECK: bb0([[ARG:%.*]] : $ClassBound): func class_bound_method(x: ClassBound) { var x = x x.classBoundMethod() // CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x" // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound // CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound // CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1 // CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]]) // CHECK: destroy_value [[PROJ]] // CHECK: destroy_value [[XBOX]] // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T0s18class_bound_methodys10ClassBound_p1x_tF' // rdar://problem/31858378 struct Value {} protocol HasMutatingMethod { mutating func mutateMe() var mutatingCounter: Value { get set } var nonMutatingCounter: Value { get nonmutating set } } protocol InheritsMutatingMethod : class, HasMutatingMethod {} func takesInOut<T>(_: inout T) {} // CHECK-LABEL: sil hidden @_T0s27takesInheritsMutatingMethodys0bcD0_pz1x_s5ValueV1ytF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () { func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod, y: Value) { // CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutateMe!1 : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutateMe() // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $Value // CHECK-NEXT: [[RESULT:%.*]] = mark_uninitialized [var] [[RESULT_BOX]] : $*Value // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!getter.1 : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%21) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: [[X_VALUE:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: destroy_value [[X_VALUE]] : $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: assign [[RESULT_VALUE]] to [[RESULT]] : $*Value // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*Value _ = x.mutatingCounter // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!setter.1 : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%1, [[TEMPORARY]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutatingCounter = y takesInOut(&x.mutatingCounter) _ = x.nonMutatingCounter x.nonMutatingCounter = y takesInOut(&x.nonMutatingCounter) }
apache-2.0
6f5fddb6c93766074feeca56e32269b7
54.522523
363
0.618936
3.572754
false
false
false
false
iOSTestApps/Cherry
Cherry WatchKit Extension/InterfaceControllers/KTWatchGlanceInterfaceController.swift
1
2469
// // KTWatchGlanceInterfaceController.swift // Cherry // // Created by Kenny Tang on 2/24/15. // // import WatchKit import Foundation class KTWatchGlanceInterfaceController: WKInterfaceController { @IBOutlet weak var timerRingGroup:WKInterfaceGroup? @IBOutlet weak var timeLabel:WKInterfaceLabel? @IBOutlet weak var activityNameLabel:WKInterfaceLabel? var currentBackgroundImageString:String? override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) self.currentBackgroundImageString = "circles_background"; } override func willActivate() { super.willActivate() self.updateInterfaceWithActiveActivity() self.updateUserActivityForHandOff() } // MARK: willActivate helper methods func updateInterfaceWithActiveActivity() { if let activity = KTActivityManager.sharedInstance.activeActivityInSharedStorage() { self.activityNameLabel!.setText(activity.activityName) let displayMinutesString = KTTimerFormatter.formatTimeIntToTwoDigitsString(KTTimerFormatter.formatPomoRemainingMinutes(activity.elapsedSecs)) let displaySecsString = KTTimerFormatter.formatTimeIntToTwoDigitsString(KTTimerFormatter.formatPomoRemainingSecsInCurrentMinute(activity.elapsedSecs)) self.timeLabel!.setText("\(displayMinutesString):\(displaySecsString)") self.updateTimerBackgroundImage(activity.elapsedSecs) } } func updateUserActivityForHandOff() { if let activity = KTActivityManager.sharedInstance.activeActivityInSharedStorage() { let userInfo = ["type" : "bb.com.corgitoergosum.KTPomodoro.select_activity", "activityID" : activity.activityID] self.updateUserActivity("bb.com.corgitoergosum.KTPomodoro.active_task", userInfo: userInfo, webpageURL: nil) } } // MARK: updateInterfaceWithActiveActivity helper methods func updateTimerBackgroundImage(elapsedSecs:Int) { let elapsedSections = elapsedSecs/((KTSharedUserDefaults.pomoDuration*60)/12) let backgroundImageString = "circles_\(elapsedSections)" println("backgroundImageString: \(backgroundImageString)") if (backgroundImageString != self.currentBackgroundImageString!) { self.currentBackgroundImageString = backgroundImageString self.timerRingGroup!.setBackgroundImageNamed(backgroundImageString) } } }
mit
a8386ac902fb2e0a40e18f23f7cfb765
35.850746
162
0.738761
5.008114
false
false
false
false
matthewpurcell/firefox-ios
Client/Frontend/Browser/BrowserPrompts.swift
1
6251
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit @objc protocol JSPromptAlertControllerDelegate: class { func promptAlertControllerDidDismiss(alertController: JSPromptAlertController) } /// A simple version of UIAlertController that attaches a delegate to the viewDidDisappear method /// to allow forwarding the event. The reason this is needed for prompts from Javascript is we /// need to invoke the completionHandler passed to us from the WKWebView delegate or else /// a runtime exception is thrown. class JSPromptAlertController: UIAlertController { var alertInfo: JSAlertInfo? weak var delegate: JSPromptAlertControllerDelegate? override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) alertInfo?.alertWillDismiss() delegate?.promptAlertControllerDidDismiss(self) } } /** * An JSAlertInfo is used to store information about an alert we want to show either immediately or later. * Since alerts are generated by web pages and have no upper limit it would be unwise to allocate a * UIAlertController instance for each generated prompt which could potentially be queued in the background. * Instead, the JSAlertInfo structure retains the relevant data needed for the prompt along with a copy * of the provided completionHandler to let us generate the UIAlertController when needed. */ protocol JSAlertInfo { /** * A word about this mutating keyword here. These prompts should be calling their completion handlers when * the prompt is actually dismissed - not when the user selects an option. Ideally this would be handled * inside the JSPromptAlertController subclass in the viewDidDisappear callback but UIAlertController * was built to not be subclassed. Instead, when allocate the JSPromptAlertController we pass along a * reference to the alertInfo structure and manipulate the required state from the action handlers. */ mutating func alertController() -> JSPromptAlertController func alertWillDismiss() func cancel() } struct MessageAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: () -> Void mutating func alertController() -> JSPromptAlertController { let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: UIConstants.OKString, style: UIAlertActionStyle.Default, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler() } func cancel() { completionHandler() } } struct ConfirmPanelAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: (Bool) -> Void var didConfirm: Bool = false init(message: String, frame: WKFrameInfo, completionHandler: (Bool) -> Void) { self.message = message self.frame = frame self.completionHandler = completionHandler } mutating func alertController() -> JSPromptAlertController { // Show JavaScript confirm dialogs. let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: UIConstants.OKString, style: UIAlertActionStyle.Default, handler: { _ in self.didConfirm = true })) alertController.addAction(UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.Cancel, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler(didConfirm) } func cancel() { completionHandler(false) } } struct TextInputAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: (String?) -> Void let defaultText: String? var input: UITextField! init(message: String, frame: WKFrameInfo, completionHandler: (String?) -> Void, defaultText: String?) { self.message = message self.frame = frame self.completionHandler = completionHandler self.defaultText = defaultText } mutating func alertController() -> JSPromptAlertController { let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField) in self.input = textField self.input.text = self.defaultText }) alertController.addAction(UIAlertAction(title: UIConstants.OKString, style: UIAlertActionStyle.Default, handler: nil)) alertController.addAction(UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.Cancel, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler(input.text) } func cancel() { completionHandler(nil) } } /// Show a title for a JavaScript Panel (alert) based on the WKFrameInfo. On iOS9 we will use the new securityOrigin /// and on iOS 8 we will fall back to the request URL. If the request URL is nil, which happens for JavaScript pages, /// we fall back to "JavaScript" as a title. private func titleForJavaScriptPanelInitiatedByFrame(frame: WKFrameInfo) -> String { var title: String = "JavaScript" if #available(iOS 9, *) { title = "\(frame.securityOrigin.`protocol`)://\(frame.securityOrigin.host)" if frame.securityOrigin.port != 0 { title += ":\(frame.securityOrigin.port)" } } else { if let url = frame.request.URL { title = "\(url.scheme)://\(url.hostPort))" } } return title }
mpl-2.0
c55a5640cc9ff4ee2b390dda21771c12
38.815287
172
0.718445
5.333618
false
false
false
false
amdaza/HackerBooks
HackerBooks/HackerBooks/NotesTableViewController.swift
1
2263
// // NotesTableViewController.swift // HackerBooks // // Created by Home on 5/10/16. // Copyright © 2016 Alicia Daza. All rights reserved. // import Foundation import UIKit import CoreData class NotesTableViewController: CoreDataTableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Get note let note = fetchedResultsController?.object(at: indexPath) as! Note // Cell type let cellId = "LibraryCell" // Create cell var cell = tableView.dequeueReusableCell(withIdentifier: cellId) if cell == nil { // Optional empty, create one cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId) } // Syncronize book and cell cell?.imageView?.image = note.photo?.image cell?.textLabel?.text = note.creationDate?.description cell?.detailTextLabel?.text = "Modified: " + (note.modificationDate?.description)! return cell! } override func viewDidLoad() { super.viewDidLoad() self.title = "Notes" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Get note let note = fetchedResultsController?.object(at: indexPath) as! Note let noteVC = NoteViewController(model: note) navigationController?.pushViewController(noteVC, animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let indx = IndexPath(row: 0, section: 0) if let aux = fetchedResultsController?.object(at: indx) as? Note, let bookTitle = aux.book?.title{ self.title = "Notes in " + bookTitle } self.tableView.reloadData() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } }
gpl-3.0
436f603bf7ae5d7d7ad7cae4a474f805
25.611765
90
0.581786
5.4375
false
false
false
false
chunzhiying/MeiPaiDemo
MeiPaiDemo/MeiPaiDemo/RecordViewController.swift
1
8976
// // RecordViewController.swift // MeiPaiDemo // // Created by 陈智颖 on 15/9/29. // Copyright © 2015年 YY. All rights reserved. // import UIKit import AVFoundation import AssetsLibrary class RecordViewController: UIViewController { @IBOutlet weak var recordButton: UIView! @IBOutlet weak var photoImage: UIImageView! private var bigPhotoImage: UIImageView? private var blackBackground: UIView! private var recordVideoView: RecordVideoView! private var filterScrollView: FilterScrollView! private var loadingBox: LoadingBox? = LoadingBox() private var model = RecordModel() private var filterIndex = 0 private var filters = [ CIFilter(name: "Normal"), CIFilter(name: "CIPhotoEffectInstant"), CIFilter(name: "CIPhotoEffectTransfer"), CIFilter(name: "CIPhotoEffectProcess")] private var canRecord: Bool = true // MARK: - Life Circle override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) model.deleteTempVideo() recordVideoView.startRunning() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) recordVideoView.stopRunning() } override func viewDidLoad() { super.viewDidLoad() initView() navigationController?.navigationBar.hidden = true } func initView() { func initRecordButton() { recordButton.layer.cornerRadius = recordButton.bounds.size.width / 2 recordButton.layer.masksToBounds = true let centerLayer = CALayer() centerLayer.frame = CGRectMake(5, 5, recordButton.frame.size.width - 10, recordButton.frame.size.height - 10) centerLayer.backgroundColor = CommonColor.mainColor.CGColor centerLayer.cornerRadius = centerLayer.frame.size.width / 2 centerLayer.masksToBounds = true recordButton.layer.addSublayer(centerLayer) let longTap = UILongPressGestureRecognizer(target: self, action: "handleLongGesture:") recordButton.addGestureRecognizer(longTap) let tap = UITapGestureRecognizer(target: self, action: "handleRecordTap:") recordButton.addGestureRecognizer(tap) } func initRecordVideoView() { recordVideoView = RecordVideoView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height * 3 / 4)) recordVideoView.recordVideoDelegate = self view.addSubview(recordVideoView) } func initPhotoImage() { let tap = UITapGestureRecognizer(target: self, action: "handlePhotoTap:") photoImage.userInteractionEnabled = true photoImage.addGestureRecognizer(tap) blackBackground = UIView(frame: view.frame) blackBackground.backgroundColor = UIColor.blackColor() blackBackground.alpha = 0 view.addSubview(blackBackground) } func initFilterScrollView() { filterScrollView = FilterScrollView(frame: CGRectMake(0, recordVideoView.frame.origin.y + recordVideoView.frame.size.height + 10 , view.frame.width, 30), filters: filters) view.addSubview(filterScrollView) let leftSwipe = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") leftSwipe.direction = .Left let rightSwipe = UISwipeGestureRecognizer(target: self, action: "handleSwipe:") rightSwipe.direction = .Right recordVideoView.addGestureRecognizer(leftSwipe) recordVideoView.addGestureRecognizer(rightSwipe) } initRecordButton() initRecordVideoView() initFilterScrollView() initPhotoImage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Gesture func handleLongGesture(sender: UILongPressGestureRecognizer) { guard canRecord else { return } switch sender.state { case .Began: recordVideoView.startRecordingOnUrl(model.outputFileUrl) model.addNewVideoFilePath() case .Ended: recordVideoView.stopRecording() default: return } } func handleRecordTap(sender: UITapGestureRecognizer) { guard let photo = recordVideoView.takePhoto() else { return } photoImage.image = photo } func handlePhotoTap(sender: UITapGestureRecognizer) { if sender.view == photoImage { bigPhotoImage = UIImageView(frame: photoImage.frame) bigPhotoImage?.image = photoImage.image view.addSubview(bigPhotoImage!) let tap = UITapGestureRecognizer(target: self, action: "handlePhotoTap:") bigPhotoImage?.userInteractionEnabled = true bigPhotoImage?.addGestureRecognizer(tap) UIView.animateWithDuration(0.5) { self.bigPhotoImage?.frame = UIScreen.mainScreen().bounds self.bigPhotoImage?.transform = CGAffineTransformMakeScale(0.9, 0.9) self.blackBackground.alpha = 0.7 } photoImage.userInteractionEnabled = false } else if sender.view == bigPhotoImage { UIView.animateWithDuration(0.5, animations: { self.bigPhotoImage?.frame = self.photoImage.frame self.bigPhotoImage?.transform = CGAffineTransformMakeScale(1, 1) self.blackBackground.alpha = 0 }, completion: { finish in self.bigPhotoImage?.removeFromSuperview() self.photoImage.userInteractionEnabled = true }) } } func handleSwipe(sender: UISwipeGestureRecognizer) { guard (sender.direction == UISwipeGestureRecognizerDirection.Left) || (sender.direction == UISwipeGestureRecognizerDirection.Right) else { return } let oldFilterIndex = filterIndex if sender.direction == .Left { filterIndex++ } else if sender.direction == .Right { filterIndex-- } if filterIndex == filters.count { filterIndex = filters.count - 1 } else if filterIndex == -1 { filterIndex = 0 } let filter = filters[filterIndex % filters.count] recordVideoView.changeRecordFilter(filter) filterScrollView.changeFIlterFromOldIndex(oldFilterIndex, toNewIndex: filterIndex) } // MARK: - Alert Handle func handleAlertController() { canRecord = false loadingBox?.showInView(view, withText: "处理视频中..") recordVideoView.resetRecordVideoUIAndHandleEndingImageByUrl(model.outputFileUrl) // model.addNewVideoFilePath() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [weak self] in self?.model.saveToCameraRoll { self?.canRecord = true self?.loadingBox?.hide() } } } } extension RecordViewController: RecordVideoUIDelegate { func dismissViewController() { self.dismissViewControllerAnimated(true, completion: nil) } func didFinishRecordWithCanContinue(canContinue: Bool) { if canContinue { let alertController = UIAlertController(title: "提示", message: "是否要结束录制", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "No,继续取景", style: .Cancel, handler: nil) let confirmAction = UIAlertAction(title: "Yes,存入图库", style: .Default) { [weak self] _ in self?.handleAlertController() } alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "提示", message: "您最多只能录制10秒!", preferredStyle: .Alert) let confirmAction = UIAlertAction(title: "确定", style: .Default) { [weak self] _ in self?.handleAlertController() } alertController.addAction(confirmAction) self.presentViewController(alertController, animated: true, completion: nil) } } }
apache-2.0
c58f0668ca1e551cbe9823f49926d65c
33.351351
183
0.605485
5.557152
false
false
false
false
Yoseob/Trevi
Lime/Lime/Request.swift
1
3484
// // Request.swift // Trevi // // Created by LeeYoseob on 2015. 11. 23.. // Copyright © 2015년 LeeYoseob. All rights reserved. // import Foundation import Trevi // Currently, you don't use this class, but will use the next. public class Request { // HTTP method like GET, POST. public var method: HTTPMethodType = HTTPMethodType.UNDEFINED public var httpVersionMajor : String? = "1" public var httpVersionMinor : String? = "1" public var version : String { return "\(httpVersionMajor).\(httpVersionMinor)" } // Original HTTP data include header & body public var headerString: String! { didSet { parse() } } // HTTP header public var header = [ String: String ] () // HTTP body public var body = [String : AnyObject]() public var bodyFragments = [String]() // Body parsed to JSON public var json: [String:AnyObject!]! // Parameter in url for semantic URL // ex) /url/:name public var params = [ String: String ] () // Qeury string from requested url // ex) /url?id="123" public var query = [ String: String ] () // Seperated path by component from the requested url public var pathComponent: [String] = [ String ] () // Requested url public var path: String { didSet { let segment = self.path.componentsSeparatedByString ( "/" ) for idx in 0 ..< segment.count where idx != 0 { pathComponent.append ( segment[idx] ) } } } public let startTime: NSDate // A variable to contain something needs by user. public var attribute = [ String : String ] () public init () { self.path = String () self.startTime = NSDate () } public init ( _ headerStr: String ) { self.path = String () self.startTime = NSDate () self.headerString = headerStr parse() } private final func parse () { // TODO : error when file uploaded.. guard let converted = headerString else { return } let requestHeader: [String] = converted.componentsSeparatedByString ( CRLF ) let requestLineElements: [String] = requestHeader.first!.componentsSeparatedByString ( SP ) // This is only for HTTP/1.x if requestLineElements.count == 3 { if let method = HTTPMethodType ( rawValue: requestLineElements[0] ) { self.method = method } let httpProtocolString = requestLineElements.last! let versionComponents: [String] = httpProtocolString.componentsSeparatedByString( "/" ) let version: [String] = versionComponents.last!.componentsSeparatedByString( "." ) httpVersionMajor = version.first! httpVersionMinor = version.last! parseHeader( requestHeader ) } } private final func parseHeader ( fields: [String] ) { for _idx in 1 ..< fields.count { if let fieldSet: [String] = fields[_idx].componentsSeparatedByString ( ":" ) where fieldSet.count > 1 { self.header[fieldSet[0].trim()] = fieldSet[1].trim(); self.header[fieldSet[0].trim().lowercaseString] = fieldSet[1].trim(); } } } }
apache-2.0
55bf53a931f394e1bc1da08a1948b0fe
28.252101
115
0.566217
4.788171
false
false
false
false
interstateone/SlackAPI
Sources/Slack.swift
1
5587
import Core import Zeal import OpenSSL import WebSocket import Venice import HTTP import JSONCore public final class Slack { let http = HTTPClient(host: "slack.com", port: 443, SSL: SSLClientContext()) let token: String var user: User? public init(token: String) { self.token = token } public func startRTM() throws -> SlackRTM { // post to rtm.start let formEncodedBody = "token=\(token)" let contentLength: Int = formEncodedBody.data.count let headers = [ "Content-Type": "application/x-www-form-urlencoded", "Content-Length": String(contentLength) ] let startChannel = Channel<(Response, StreamType)>() print("posting to rtm.start") co { self.http.post("/api/rtm.start", headers: headers, body: formEncodedBody) { result in do { let (response, stream) = try result() startChannel.send(response, stream) } catch { print(error) } } } let (response, stream) = startChannel.receive()! let resultJSON = try JSONParser.parseString(response.bodyString!) // create user from self info user = User(ID: resultJSON["self"]!["id"]!.string!, name: resultJSON["self"]!["name"]!.string!) // get WS URL from response let URL = resultJSON["url"]!.string! // create RTM with URL let RTM = SlackRTM(slack: self, URL: URL, response: response, stream: stream) return RTM } } public final class SlackRTM { private let http: HTTPClient private let webSocketClient: WebSocketClient private let webSocket: WebSocket private let slack: Slack public typealias Listener = (Event) -> Void private var listeners = [Listener]() let URL: String public let done = Channel<Void>() public var user: User? { return slack.user } init(slack: Slack, URL: String, response: Response, stream: StreamType) { self.slack = slack self.URL = URL let webSocketChannel = Channel<WebSocket>() let headers: [String: String] = [ "Upgrade": "websocket", "Connection": "Upgrade", // TODO: Generate a random nonce "Sec-WebSocket-Key": Base64.encode(Data(bytes: [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5])).string!, "Sec-WebSocket-Version": "13" ] let webSocketClient = WebSocketClient { webSocket in webSocketChannel.send(webSocket) } let uri = URI(string: URL) let http = HTTPClient(host: uri.host!, port: 443, SSL: SSLClientContext()) co { http.get(uri.path!, headers: headers) { result in do { let (response, stream) = try result() print("response: \(response)") webSocketClient.handleResponse(response, stream) } catch { print("error: \(error)") } } } self.http = http self.webSocketClient = webSocketClient webSocket = webSocketChannel.receive()! webSocket.listen { webSocketEvent in switch webSocketEvent { case .Text(let text): do { let event = try self.createEvent(text) self.dispatchEvent(event) } catch { print("Unable to create event for JSON: \(text)") } case .Ping(let buffer): self.webSocket.pong(buffer) case .Close(let code, let reason): print("Received close event with code: \(code), reason: \(reason)") self.done.receive() default: print("Received unhandled event: \(webSocketEvent)") } } let ticker = Ticker(period: 2 * second) co { for _ in ticker.channel { // self.send(Ping()) } } } private func createEvent(JSONString: String) throws -> Event { let json = try JSONParser.parseString(JSONString) guard let eventTypeString = json["type"]?.string, eventType = EventType(rawValue: eventTypeString) else { throw Errors.InvalidJSON } switch eventType { case .Message: return Message(json: json) case .Ping: return Ping(json: json) case .PresenceChange: return PresenceChange(json: json) case .ChannelJoined: return ChannelJoined(json: json) default: throw Errors.InvalidJSON } } func dispatchEvent(event: Event) { print("Dispatching event \(event)") for listener in listeners { listener(event) } } public func listen(listener: Listener) { listeners.append(listener) } public func waitUntilClosed() { done.send() } private var lastEventID: Int64 = 0 public func send(event: Event) { lastEventID += 1 var json = event.JSON json["id"] = JSONValue.JSONNumber(.JSONIntegral(lastEventID)) do { let jsonString = try JSONSerializer.serializeValue(json) print("Sending \(jsonString)") webSocket.send(jsonString) } catch { print("Error serializing JSON for event: \(error)") } } } enum Errors: ErrorType { case InvalidJSON }
mit
275da5aab192af6adba6fcf51630e0d1
29.36413
113
0.551996
4.644223
false
false
false
false
SkrewEverything/Web-Tracker
Web Tracker/Web Tracker/SQLight/PreparedStatement.swift
1
14376
// // PreparedStatement.swift // SQLight // // Created by Skrew Everything on 30/06/17. // Copyright © 2017 SkrewEverything. All rights reserved. // import Foundation public class PreparedStatement { /// SQL Query of the prepared statement public let SQLQuery: String /// Compiled SQL Query: byte-code internal var preparedStatement: OpaquePointer! /// Database connection currently opened where queries need to be executed private let db: SQLight /// Compiles SQL query into a byte-code for execution. /// - Note: To execute an SQL query, it must first be compiled into a byte-code program /// - parameter SQLQuery: Any SQL query /// - parameter SQLightDB: Object returned from SQLight(type:) /// - throws: If any error occurs during compiling. Mostly syntax errors. init(SQLQuery: String, SQLightDB: SQLight) throws { self.SQLQuery = SQLQuery self.db = SQLightDB self.preparedStatement = try self.prepareStatement() } /// Compiles SQL query into a byte-code for execution. /// - Note: To execute an SQL query, it must first be compiled into a byte-code program /// # More Info: /// [https://sqlite.org/c3ref/prepare.html]() /// /// Using: `sqlite3_prepare_v2()` /// - returns: Compiled SQL Query which can be used to execute /// - throws: If any error occurs during compiling. Mostly syntax errors. private func prepareStatement() throws -> OpaquePointer { /// Temporary prepared statement(byte-code) to return var pStmt: OpaquePointer? = nil // Third parameter can be -1 but giving length of string can increase performance slightly let rc = sqlite3_prepare_v2(self.db.dbPointer, self.SQLQuery, -1, &pStmt, nil) if rc != SQLITE_OK { throw DBError(db: self.db, ec: rc) } if pStmt == nil { throw DBError(db: self.db, ec: rc) } return pStmt! } /// Bind values from left to right in prepared statement. /// - parameter elements: All the values/elements to bind to prepared statement /// - throws: If any error occurs while binding values public func bindValues(_ elements: [Any]) throws { var parameterIndexesandElements = [Int:Any]() var index = 1 for i in elements { parameterIndexesandElements[index] = i index += 1 } try self.bind(parameterIndexesandElements) } /// Bind values based on parameter name. /// - parameter parameterNamesandElements: Parameter name as key and Binding value as value in the form of dictionary /// - throws: If any error occurs while binding values public func bindValues(_ parameterNamesandElements: [String:Any]) throws { var parameterIndexesandElements = [Int:Any]() for i in parameterNamesandElements { parameterIndexesandElements[self.getParameterIndex(parameterName: i.key)] = i.value } try self.bind(parameterIndexesandElements) } /// Bind values based on parameter index. /// - parameter parameterIndexesandElements: Parameter index as key and Binding value as value in the form of dictionary /// - throws: If any error occurs while binding values public func bindValues(_ parameterIndexesandElements: [Int:Any]) throws { try self.bind(parameterIndexesandElements) } /// Bind values based on parameter index. /// - parameter parameterIndexesandElements: Parameter index as key and Binding value as value in the form of dictionary /// - throws: If any error occurs while binding values private func bind(_ parameterIndexesandElements: [Int:Any]) throws { var rc: Int32 = 0 for i in parameterIndexesandElements { if i.value is Int { rc = sqlite3_bind_int(self.preparedStatement, Int32(i.key), Int32(i.value as! Int)) } else if i.value is String { rc = sqlite3_bind_text(self.preparedStatement, Int32(i.key), i.value as! String, Int32((i.value as! String).lengthOfBytes(using: .utf8)), SQLITE_TRANSIENT) } else if i.value is Double { rc = sqlite3_bind_double(self.preparedStatement, Int32(i.key), i.value as! Double) } else { print("Unknown datatype") throw DBError(db: self.db, ec: 0, customMessage: "Unknown type or blob and null not supported") } if rc != SQLITE_OK { throw DBError(db: self.db, ec: rc) } } } /// Number of bind parameters in a prepared statement. /// - returns: Number of bind parameters. public func getParameterCount() -> Int { let count = sqlite3_bind_parameter_count(self.preparedStatement) return Int(count) } /// Get the parameter index using parameter name /// - note: Index starts from **1**, not from **0**. /// - parameter parameterName: Name of the parameter /// - returns: Index of the specified parameter. public func getParameterIndex(parameterName: String) -> Int { let id = sqlite3_bind_parameter_index(self.preparedStatement, parameterName) return Int(id) } /// Parameter name specified by index /// - note: Index starts from **1**, not from **0**. /// - parameter parameterIndex: Index of the required bind paramter. /// - returns: Parameter name or nil. public func getParameterName(parameterIndex: Int) -> String? { if let name = sqlite3_bind_parameter_name(self.preparedStatement, Int32(parameterIndex)) { return String(cString: name) } else { return nil } } /// Returns column names in `SELECT` statement. /// - returns: Column names as `String` array. If the statement is not `SELECT` then `nil` is returned. public func getColumnNames() -> [String]? { if SQLQuery.lowercased().contains("select") { var columns = [String]() for i in 0..<sqlite3_column_count(self.preparedStatement) { columns.append(String(cString: sqlite3_column_name(self.preparedStatement, Int32(i)))) } return columns } else { return nil } } /// Executes all types of SQL queries. /// - note: Doesn't support binding of values. /// # More Info: /// [https://sqlite.org/c3ref/exec.html]() /// - parameter callbackForSelectQuery: Closure or func literal which is called for every row retrieved for SELECT command. /// Pass nil for other commands. callback is used for SELECT commands only. /// - throws: If any error occurs while exeuting the command/query. public func execute(callbackForSelectQuery callback: SQLiteExecCallBack?) throws { var zErrMsg:UnsafeMutablePointer<Int8>? = nil var rc: Int32 = 0 rc = sqlite3_exec(self.db.dbPointer, self.SQLQuery, callback ?? nil , nil, &zErrMsg) if rc != SQLITE_OK { let msg = String(cString: zErrMsg!) sqlite3_free(zErrMsg) throw DBError(db: self.db, ec: rc, customMessage: msg) } } /// Executes a query (which modifies the table like `UPDATE`, `INSERT`, `DELETE` etc). /// - note: Use `fetchAllRows(preparedStatement:)` or `fetchNextRow(preparedStatement:)` to execute queries with **SELECT**. /// - returns: Number of rows changed. /// - throws: If any error occurs while exeuting the command/query. public func modify() throws -> Int { let rc = sqlite3_step(self.preparedStatement) if rc == SQLITE_DONE // SQLITE_DONE is returned for sql queries other than select query(it returns SQLITE_ROW) { /* The sqlite3_reset() function is called to reset a prepared statement object back to its initial state, ready to be re-executed. It does not change the values of any bindings on the prepared statement Use sqlite3_clear_bindings() to reset the bindings. */ try self.reset() return Int(sqlite3_changes(self.db.dbPointer)) } else { try self.reset() throw DBError(db: self.db, ec: rc, customMessage: "") } } /// Executes and returns all the rows while using `SELECT` query. /// - warning: If the data being retrieved is large, it is advised not to use this method as all the retrieved rows are stored in the memory and returned. Use `fetchNextRow(preparedStatement:)` as it returns only 1 row at a time or use `execute(SQLQuery:callbackForSelectQuery:)` which uses closure /// - returns: All the retrieved rows and columns as a 2D Array /// - throws: If any error occurs while exeuting the command/query. public func fetchAllRows() throws -> [[Any]] { var data = [[Any]]() var data1 = [Any]() while true { let rc = sqlite3_step(self.preparedStatement) if rc == SQLITE_ROW // SQLITE_ROW is returned for select query. Other queries returns SQLITE_DONE { for i in 0..<sqlite3_column_count(self.preparedStatement) { let type = sqlite3_column_type(self.preparedStatement, i) switch type { case SQLiteDataType.integer.rawValue: data1.append(sqlite3_column_int(self.preparedStatement, i)) case SQLiteDataType.float.rawValue: data1.append(sqlite3_column_double(self.preparedStatement, i)) case SQLiteDataType.text.rawValue: data1.append(String(cString: sqlite3_column_text(self.preparedStatement, i))) case SQLiteDataType.blob.rawValue: print("It is BLOB!") // should do something case SQLiteDataType.null.rawValue: print("It is NULL!") default: print("Just to stop crying of swift.") } } data.append(data1) data1.removeAll() } else if rc == SQLITE_DONE { break; } else { try self.reset() throw DBError(db: self.db, ec: rc) } } /* The sqlite3_reset() function is called to reset a prepared statement object back to its initial state, ready to be re-executed. It does not change the values of any bindings on the prepared statement Use sqlite3_clear_bindings() to reset the bindings. */ try self.reset() return data } /// Executes and returns 1 row for every call while using `SELECT` query. /// - returns: A row is returned as an array. If there is no row left to return, nil is returned. /// - throws: If any error occurs while exeuting the command/query. public func fetchNextRow() throws -> [Any]? { var data = [Any]() let rc = sqlite3_step(self.preparedStatement) if rc == SQLITE_ROW // SQLITE_ROW is returned for select query. Other queries returns SQLITE_DONE { for i in 0..<sqlite3_column_count(self.preparedStatement) { let type = sqlite3_column_type(self.preparedStatement, i) switch type { case SQLiteDataType.integer.rawValue: data.append(sqlite3_column_int(self.preparedStatement, i)) case SQLiteDataType.float.rawValue: data.append(sqlite3_column_double(self.preparedStatement, i)) case SQLiteDataType.text.rawValue: data.append(String(cString: sqlite3_column_text(self.preparedStatement, i))) case SQLiteDataType.blob.rawValue: print("It is BLOB!") // should do something case SQLiteDataType.null.rawValue: print("It is NULL!") default: print("Just to stop crying of swift.") } } } else if rc == SQLITE_DONE { try self.reset() return nil } else { try self.reset() throw DBError(db: self.db, ec: rc) } return data } /// Resets a prepared statement object back to its initial state, ready to be re-executed. /// - note: It does not change the values of any bindings on the prepared statement. Use sqlite3_clear_bindings() to reset the bindings. /// # More Info: /// [https://sqlite.org/c3ref/reset.html]() /// - throws: If any error occurs while resetting the prepared statement. public func reset() throws { let rc = sqlite3_reset(self.preparedStatement) if rc != SQLITE_OK { throw DBError(db: self.db, ec: rc) } } /// Removes all the bindings on a prepared statement public func resetBindValues() { sqlite3_clear_bindings(self.preparedStatement) } /// The application must destroy every prepared statement in order to avoid resource leaks. /// - warning: It is a grievous error for the application to try to use a prepared statement after it has been finalized. Any use of a prepared statement after it has been finalized can result in undefined and undesirable behavior such as segfaults and heap corruption. /// # More Info : /// [https://sqlite.org/c3ref/finalize.html]() /// - throws: If any error occurs while destroying the prepared statement. public func destroy() throws { let rc = sqlite3_finalize(self.preparedStatement) if rc != SQLITE_OK { throw DBError(db: self.db, ec: rc) } } }
mit
3b51d2f32d093466ae51b3179731422f
38.383562
302
0.592557
4.566391
false
false
false
false
yangyueguang/MyCocoaPods
CarryOn/PublicTools.swift
1
11480
// // PublicTools.swift // project // // Created by Super on 2017/9/8. // Copyright © 2017年 Super. All rights reserved. // import UIKit import StoreKit import AudioToolbox import Foundation import LocalAuthentication import CoreSpotlight import CoreLocation import MobileCoreServices @objcMembers public class PublicTools:NSObject{ public let app = APP() /// 弹出指纹验证的视图 class func showTouchID(desc:String="",_ block: @escaping (_ error:LAError?,_ m:String?) -> Void){ if NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_8_0 { block(LAError(_nsError:NSError()),"系统版本不支持TouchID") return } let context = LAContext() context.localizedFallbackTitle = desc var error:NSError? guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else { block(LAError(_nsError: error!),"当前设备不支持TouchID") return } context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: desc, reply: {(_ success: Bool, _ error: Error?) -> Void in var m = "验证通过" if success{ block(nil,m) }else if let error=error{ let laerror = LAError.init(_nsError: error as NSError) switch laerror.code{ case LAError.authenticationFailed:m="验证失败";break; case LAError.userCancel:m="被用户手动取消";break; case LAError.userFallback:m="选择手动输入密码";break; case LAError.systemCancel:m="被系统取消";break; case LAError.passcodeNotSet:m="没有设置密码";break; case LAError.touchIDNotAvailable:m="TouchID无效";break; case LAError.touchIDNotEnrolled:m="没有设置TouchID";break; case LAError.touchIDLockout:m="多次验证TouchID失败";break; case LAError.appCancel:m="当前软件被挂起并取消了授权 (如App进入了后台等)";break; case LAError.invalidContext:m="当前软件被挂起并取消了授权";break; case LAError.notInteractive:m="当前设备不支持TouchID";break; default:m="当前设备不支持TouchID";break; } block(laerror,m) } }); } /// 软件自更新 class func updateAPPWithPlistURL(_ url:String="http://dn-mypure.qbox.me/iOS_test.plist",block: @escaping(Bool)->Void){ let serviceURL = "itms-services:///?action=download-manifest&url=" let realUrl = URL(string:"\(serviceURL)\(url)") UIApplication.shared.open(realUrl!, options: [:]) { (success) in block(success) if success{ exit(0) } } } /// 打开系统的设置 public static func openSettings(_ closure: @escaping (Bool) -> Void) { if NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_8_0 { closure(false) } else { let url = URL(string: UIApplication.openSettingsURLString) if let anUrl = url { if UIApplication.shared.canOpenURL(anUrl) { UIApplication.shared.open(anUrl, options: [:], completionHandler: { success in closure(success) }) } else { closure(false) } } } } /// 添加系统层面的搜索 class func addSearchItem(title:String?,des:String?,thumURL:URL?,identifier:String?,keywords:[String]?){ let sias = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String) sias.title = title sias.thumbnailURL = thumURL sias.contentDescription = des sias.keywords = keywords let searchableItem = CSSearchableItem(uniqueIdentifier:identifier,domainIdentifier:"items",attributeSet:sias) addSearchItems([searchableItem]) } ///批量添加系统层面的搜索 class func addSearchItems(_ searchItems:[CSSearchableItem]){ let searchIndex = CSSearchableIndex.default() searchIndex.indexSearchableItems(searchItems){error in if let error = error { print(error.localizedDescription) } } } ///删除系统层面的搜索 class func deleteSearchItem(identifiers:[String],closure:((Error?) -> Swift.Void)? = nil){ let searchIndex = CSSearchableIndex.default() searchIndex.deleteSearchableItems(withIdentifiers: identifiers, completionHandler: closure) } //播放提示音 func playSystemSound() { // var sound: SystemSoundID //系统声音的id 取值范围为:1000-2000 /*ReceivedMessage.caf--收到信息,仅在短信界面打开时播放。 sms-received1.caf-------三全音sms-received2.caf-------管钟琴sms-received3.caf-------玻璃sms-received4.caf-------圆号 sms-received5.caf-------铃声sms-received6.caf-------电子乐SentMessage.caf--------发送信息 */ // let path = "/System/Library/Audio/UISounds/\("sms-received1").\("caf")" // Bundle(identifier: "com.apple.UIKit")?.path(forResource: soundName, ofType: soundType) //得到苹果框架资源UIKit.framework ,从中取出所要播放的系统声音的路径 // Bundle.main.url(forResource: "tap", withExtension: "aif") //获取自定义的声音 // let url: CFURL = URL(fileURLWithPath: path) as CFURL // let error: OSStatus = AudioServicesCreateSystemSoundID(url, &sound) // if error != kAudioServicesNoError { // print("获取的声音的时候,出现错误") // } // AudioServicesPlaySystemSound(sound) //震动 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } /// 在主线程运行 func performSelectorOnMainThread(selector aSelector: Selector,withObject object:AnyObject! ,waitUntilDone wait:Bool = false){ if self.responds(to: aSelector){ var continuego = false let group = DispatchGroup() let queue = DispatchQueue(label: "com.fsh.dispatch", attributes: []) queue.async(group: group,execute: { queue.async(execute: { Thread.detachNewThreadSelector(aSelector, toTarget:self, with: object) continuego = true }) }) if wait{ let ret = RunLoop.current.run(mode: RunLoop.Mode.default, before: Foundation.Date.distantFuture ) while (!continuego && ret){ } } } } /// json转Data class func jsonToData(_ jsonResponse: AnyObject) -> Data? { do{ let data = try JSONSerialization.data(withJSONObject: jsonResponse, options: JSONSerialization.WritingOptions.prettyPrinted) return data; }catch{ return nil } } /// data转json class func dataToJson(_ data: Data) -> AnyObject? { do{ let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) return json as AnyObject? }catch{ return nil } } /// 变成没有null的字符串 func notEmpty(_ item:Any)->String{ if item is NSNull{ return "-" }else if item is String{ var ss = String(describing:item) if ss == ""{ ss = "-" } return ss }else if item is NSNumber{ return String(describing:item) }else{ return "-" } } /// 变成decimalNumber func decimalNumber(_ s:Any)->NSDecimalNumber{ if s is String{ let ss:NSString = s as! NSString let doubleValue = (ss.replacingOccurrences(of:",", with: "") as NSString).doubleValue return NSDecimalNumber(value: doubleValue) }else if s is NSNumber{ return NSDecimalNumber(value: (s as! NSNumber).doubleValue) }else{ return NSDecimalNumber(value:0.0) } } /// 计算方位角,正北向为0度,以顺时针方向递增 func computeAzimuthCLL(_ la1: CLLocationCoordinate2D, la2: CLLocationCoordinate2D) -> Double { var lat1: Double = la1.latitude var lon1: Double = la1.longitude var lat2: Double = la2.latitude var lon2: Double = la2.longitude var result: Double = 0.0 let ilat1 = Int(0.50 + lat1 * 360000.0) let ilat2 = Int(0.50 + lat2 * 360000.0) let ilon1 = Int(0.50 + lon1 * 360000.0) let ilon2 = Int(0.50 + lon2 * 360000.0) lat1 = lat1 * .pi / 180 lon1 = lon1 * .pi / 180 lat2 = lat2 * .pi / 180 lon2 = lon2 * .pi / 180 if (ilat1 == ilat2) && (ilon1 == ilon2) { return result } else if ilon1 == ilon2 { if ilat1 > ilat2 { result = 180.0 } } else { let c = acos(sin(lat2) * sin(lat1) + cos(lat2) * cos(lat1) * cos((lon2 - lon1))) let A = asin(cos(lat2) * sin((lon2 - lon1)) / sin(c)) result = A * 180 / .pi if (ilat2 > ilat1) && (ilon2 > ilon1) { } else if (ilat2 < ilat1) && (ilon2 < ilon1) { result = 180.0 - result } else if (ilat2 < ilat1) && (ilon2 > ilon1) { result = 180.0 - result } else if (ilat2 > ilat1) && (ilon2 < ilon1) { result += 360.0 } } return result } /// 联合各个异步请求信号量 public func combineAsyncRequest(count:Int, requestClosure: @escaping ((Int, DispatchSemaphore) -> DispatchWorkItem), completion: (() -> Void)? = nil) { let semaphore = DispatchSemaphore(value: 0) let queue = DispatchQueue.global(qos: .default) let group = DispatchGroup() for i in 0..<count { queue.async(group: group, execute: requestClosure(i, semaphore)) } let item = DispatchWorkItem { DispatchQueue.main.async(execute: { completion?() }) } group.notify(queue: queue, work: item) } } extension PublicTools: SKStoreProductViewControllerDelegate { /// 根据appid打开AppStore func openAppStore(_ appId: String) { let urlStr = "itms-apps://itunes.apple.com/app/id\(appId)" let url = URL(string: urlStr) if let anUrl = url { UIApplication.shared.open(anUrl, options: [:]) { (isSuccess) in } } let storeProductVC = SKStoreProductViewController() storeProductVC.delegate = self let dict = [SKStoreProductParameterITunesItemIdentifier : appId] storeProductVC.loadProduct(withParameters: dict, completionBlock: { result, error in if result { UIApplication.shared.keyWindow?.rootViewController?.present(storeProductVC, animated: true) } }) } public func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) { viewController.dismiss(animated: true) {} } }
mit
4c1cc6f54e57c0810278f10bc4c4967a
37.371025
155
0.57823
4.319411
false
false
false
false
yannickl/SnappingStepper
Example/SnappingStepperExample/ViewController.swift
1
5011
// // ViewController.swift // SnappingStepperExample // // Created by Yannick Loriot on 02/05/15. // Copyright (c) 2015 Yannick Loriot. All rights reserved. // import DynamicColor import UIKit class ViewController: UIViewController { @IBOutlet weak var classicStepper: SnappingStepper! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var tubeStepper: SnappingStepper! @IBOutlet weak var roundedStepper: SnappingStepper! @IBOutlet weak var customStepper: SnappingStepper! @IBOutlet weak var verticalRoundedStepper: SnappingStepper! override func viewDidLoad() { super.viewDidLoad() assignStepperDefaultSettings(classicStepper) assignStepperDefaultSettings(tubeStepper) tubeStepper.style = .tube tubeStepper.thumbStyle = .tube tubeStepper.backgroundColor = UIColor(hex: 0xB2DFDB) tubeStepper.thumbBackgroundColor = UIColor(hex: 0x009688) tubeStepper.hintStyle = .box assignStepperDefaultSettings(roundedStepper) roundedStepper.style = .rounded roundedStepper.thumbStyle = .rounded roundedStepper.backgroundColor = .clear roundedStepper.thumbBackgroundColor = UIColor(hex: 0xFFC107) roundedStepper.borderColor = UIColor(hex: 0xFFC107) roundedStepper.borderWidth = 0.5 roundedStepper.hintStyle = .thumb assignStepperDefaultSettings(customStepper) customStepper.style = .custom(path: customDoubleArrowPath()) customStepper.thumbStyle = .thumb customStepper.backgroundColor = .clear customStepper.borderColor = UIColor(hex: 0x607D8B) customStepper.thumbBackgroundColor = UIColor(hex: 0x607D8B) customStepper.borderWidth = 0.5 customStepper.hintStyle = .rounded assignStepperDefaultSettings(verticalRoundedStepper) verticalRoundedStepper.style = .rounded verticalRoundedStepper.thumbStyle = .rounded verticalRoundedStepper.backgroundColor = .clear verticalRoundedStepper.thumbBackgroundColor = UIColor(hex: 0xFFC107) verticalRoundedStepper.borderColor = UIColor(hex: 0xFFC107) verticalRoundedStepper.borderWidth = 0.5 verticalRoundedStepper.hintStyle = .thumb verticalRoundedStepper.direction = .vertical } func assignStepperDefaultSettings(_ snappingStepper: SnappingStepper) { snappingStepper.symbolFont = UIFont(name: "TrebuchetMS-Bold", size: 20) snappingStepper.symbolFontColor = .black snappingStepper.backgroundColor = UIColor(hex: 0xc0392b) snappingStepper.thumbWidthRatio = 0.4 snappingStepper.thumbText = nil snappingStepper.thumbFont = UIFont(name: "TrebuchetMS-Bold", size: 18) snappingStepper.thumbBackgroundColor = UIColor(hex: 0xe74c3c) snappingStepper.thumbTextColor = .black snappingStepper.continuous = true snappingStepper.autorepeat = true snappingStepper.wraps = false snappingStepper.minimumValue = 0 snappingStepper.maximumValue = 1000 snappingStepper.stepValue = 1 } func customDoubleArrowPath() -> UIBezierPath { let da = UIBezierPath() da.move(to: CGPoint(x: 232, y: 969)) da.addLine(to: CGPoint(x: 189, y: 941)) da.addLine(to: CGPoint(x: 189, y: 955)) da.addLine(to: CGPoint(x: 62, y: 955)) da.addLine(to: CGPoint(x: 62, y: 941)) da.addLine(to: CGPoint(x: 17, y: 972)) da.addLine(to: CGPoint(x: 62, y: 1000)) da.addLine(to: CGPoint(x: 62, y: 986)) da.addLine(to: CGPoint(x: 189, y: 986)) da.addLine(to: CGPoint(x: 189, y: 1000)) da.addLine(to: CGPoint(x: 232, y: 972)) da.close() return da } func updateThumbAttributes(_ snappingStepper: SnappingStepper, index: Int) { switch index { case 1: snappingStepper.thumbText = "" case 2: snappingStepper.thumbText = "Move Me" snappingStepper.thumbFont = UIFont(name: "TrebuchetMS-Bold", size: 10) default: snappingStepper.thumbText = nil snappingStepper.thumbFont = UIFont(name: "TrebuchetMS-Bold", size: 20) } } @IBAction func stepperValueChangedAction(_ sender: SnappingStepper) { for stepper in [classicStepper, tubeStepper, roundedStepper, verticalRoundedStepper, customStepper] { if stepper != sender { stepper?.value = sender.value } } valueLabel.text = "\(sender.value)" } @IBAction func segmentedValueChangedAction(_ sender: UISegmentedControl) { updateThumbAttributes(classicStepper, index: sender.selectedSegmentIndex) updateThumbAttributes(customStepper, index: sender.selectedSegmentIndex) updateThumbAttributes(tubeStepper, index: sender.selectedSegmentIndex) updateThumbAttributes(roundedStepper, index: sender.selectedSegmentIndex) updateThumbAttributes(verticalRoundedStepper, index: sender.selectedSegmentIndex) } }
mit
7588aeb6931fed14bb80bc0cd779c7cc
37.844961
105
0.696069
4.182805
false
false
false
false
jrothwell/dumb-slider-swift
DumbSlider/AppDelegate.swift
1
1058
// // AppDelegate.swift // DumbSlider // // Copyright © 2014 Jonathan Rothwell. See COPYING.md for licence // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow? @IBOutlet var textField: NSTextField? @IBOutlet var slider: NSSlider? let track = Track() func applicationDidFinishLaunching(aNotification: NSNotification?) { updateUserInterface() } func applicationWillTerminate(aNotification: NSNotification?) { // Nothing to see here } func updateUserInterface() { if let theTextField = textField { theTextField.stringValue = NSString(format: "%2f", track.volume) } if let theSlider = slider { theSlider.floatValue = track.volume } } @IBAction func mute(sender : AnyObject) { track.mute() updateUserInterface() } @IBAction func takeFloatValueForVolumeFrom(sender : AnyObject) { let newValue = sender.floatValue track.volume = newValue updateUserInterface() } }
mit
e0102af17387b2aded7a4912dd4f7827
21.020833
72
0.666036
4.441176
false
false
false
false
psoamusic/PourOver
PourOver/POSettingsTableViewController.swift
1
6081
// // POSettingsTableViewController.swift // PourOver // // Created by kevin on 6/21/16. // Copyright © 2016 labuser. All rights reserved. // import UIKit class POSettingsTableViewController: POViewController, UITableViewDataSource, UITableViewDelegate { //=================================================================================== //MARK: Properties //=================================================================================== /** Array of Dictionaries representing .pd files scanned from the Documents directory. "title" : String "description" : String "filePath" : String and possibly: "defaultLength" : String */ internal var cellDictionaries: [[String : AnyObject]] = [] internal let tableView = UITableView() //=================================================================================== //MARK: View Lifecycle //=================================================================================== private func setupSettingsTableViewController() { title = " " //single space for no 'Back' on pushed view controller back button } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setupSettingsTableViewController() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupSettingsTableViewController() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.appBackgroundColor() //push the navigation bar off screen if let navBar = navigationController?.navigationBar { //if we'd rather avoid seeing the navbar entirely (we keep for free swipe-to-go-back gesture) let offsetY = CGRectGetHeight(navBar.bounds) navBar.transform = CGAffineTransformMakeTranslation(0, -offsetY) navBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navBar.shadowImage = UIImage() navBar.translucent = true navBar.userInteractionEnabled = false navigationController?.view.backgroundColor = UIColor.clearColor() } let gradientLayer = CAGradientLayer() gradientLayer.frame = view.bounds gradientLayer.colors = [UIColor.highlightColorLight().CGColor, UIColor.appBackgroundColor().CGColor, UIColor.highlightColorLight().CGColor] view.layer.addSublayer(gradientLayer) addDefaultBackButton() if let _ = title { addDefaultTitleViewWithText(title!) } tableView.frame = view.bounds tableView.dataSource = self tableView.delegate = self tableView.registerClass(POTableViewCell.self, forCellReuseIdentifier: "POTableViewCell") tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "EmptyTableViewCell") tableView.separatorStyle = .None tableView.backgroundColor = UIColor.clearColor() tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tableView.delaysContentTouches = false if let _ = titleView { //inset let bottomOfTitleView = CGRectGetMaxY(titleView!.frame) tableView.contentInset = UIEdgeInsets(top: bottomOfTitleView + 60, left: 0, bottom: 0, right: 0) } view.addSubview(tableView) cellDictionaries = [ ["title" : "There"], ["title" : "are"], ["title" : "no"], ["title" : "settings."] ]; } override func prefersStatusBarHidden() -> Bool { return true } //=================================================================================== //MARK: Table View Data Source //=================================================================================== func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellDictionaries.count //includes both spacer cells } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("POTableViewCell", forIndexPath: indexPath) as! POTableViewCell cell.backgroundColor = UIColor.interfaceColorMedium().colorWithAlphaComponent(0.1) cell.titleLabel.textAlignment = .Left if let title = cellDictionaries[indexPath.row]["title"] as? String { cell.setTitle(title) } if let description = cellDictionaries[indexPath.row]["description"] as? String { cell.setDescription(description) } return cell as UITableViewCell } func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.shrinkALittleForTouchDown() } return true } func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.unshrinkForTouchUp() } } //=================================================================================== //MARK: Table View Delegate Methods //=================================================================================== func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //always deselect tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
gpl-3.0
782ce2d8454106a4560c12ad7e50a301
37.238994
147
0.571875
6.27451
false
false
false
false
imeraj/TestApp-Vapor1.0
Sources/App/main.swift
1
1786
import Vapor import HTTP import VaporMySQL import Foundation import SwiftyBeaverVapor import SwiftyBeaver import Hash import Auth import Sessions // Initialize middlewares/providers let console = ConsoleDestination() let sbProvider = SwiftyBeaverProvider(destinations: [console]) // Initialize Droplet let drop = Droplet(preparations: [Sighting.self, User.self], providers: [VaporMySQL.Provider.self], initializedProviders: [sbProvider]) // as workaround of framework bug, we add all middlewares here drop.addConfigurable(middleware: SessionsMiddleware(sessions: MemorySessions()), name: "sessions") drop.addConfigurable(middleware: AbortMiddleware(), name: "abort") drop.addConfigurable(middleware: DateMiddleware(), name: "date") drop.addConfigurable(middleware: TypeSafeErrorMiddleware(), name: "type-safe") drop.addConfigurable(middleware: ValidationMiddleware(), name: "validation") drop.addConfigurable(middleware: FileMiddleware(publicDir: drop.workDir + "Public/"), name: "file") drop.addConfigurable(middleware: SightingErrorMiddleware(), name: "sighting-error") drop.addConfigurable(middleware: UserErrorMiddleware(), name: "user-error") drop.addConfigurable(middleware: AuthMiddleware(user: User.self), name: "auth") drop.addConfigurable(middleware: ValidationErrorMiddleware(), name: "validation-error") drop.addConfigurable(middleware: ResponseMiddleware(), name: "response") var log = drop.log.self if drop.environment == .production { drop.log.enabled = [LogLevel.error] } User.database = drop.database Sighting.database = drop.database // Register routes drop.collection(V1RouteCollection(drop)) drop.collection(LoginRouteCollection(drop)) log.info("API registration done!") drop.get("/") { request in return try drop.view.make("welcome") } drop.run()
mit
4aef85ec0b315c19f603e38463d38ada
35.44898
135
0.790594
4.115207
false
true
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
iOS/Healthcare/Models/PainData.swift
1
6617
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import Foundation import CoreData let painDataName = "PainData" /** Class representing the PainData entity in code from the core data model. */ class PainData: NSManagedObject { @NSManaged var painRating: NSNumber @NSManaged var painDescription: String @NSManaged var timeStamp: NSDate /** Helper method to easily create a new instance of PainData - parameter moc: the managedObjectContext for the whole application - parameter rating: the submitted pain rating from the user - parameter description: the description of the users pain - returns: PainData object reference of what was created */ class func createInManagedObjectContext(moc: NSManagedObjectContext, rating: Int, description: String) -> PainData { let newItem = NSEntityDescription.insertNewObjectForEntityForName(painDataName, inManagedObjectContext: moc) as! PainData newItem.painRating = rating newItem.painDescription = description newItem.timeStamp = NSDate() return newItem } /** This method saves data to persist through multiple app sessions - parameter moc: the managedObjectContext for the whole application */ class func saveData(moc: NSManagedObjectContext) { var error: NSError? do { try moc.save() if error != nil { print(error?.localizedDescription) } } catch let error1 as NSError { error = error1 } } /** Method to simply log all the data currently in the PainData entity. - parameter moc: the managedObjectContext for the whole application */ class func presentAllData(moc: NSManagedObjectContext) throws { let fetchRequest = NSFetchRequest(entityName: painDataName) if let fetchResults = try moc.executeFetchRequest(fetchRequest) as? [PainData] { for result in fetchResults { print("desc: \(result.painDescription), rating: \(result.painRating), date: \(result.timeStamp)") } if fetchResults.count == 0 { print(NSLocalizedString("No data was found", comment: "n/a")) } } } /** Method for developer use to delete all data in the PainData entity. - parameter moc: the managedObjectContext for the whole application */ class func deleteAllPainData(moc: NSManagedObjectContext) throws { let fetchRequest = NSFetchRequest(entityName: painDataName) if let fetchResults = try moc.executeFetchRequest(fetchRequest) as? [PainData] { for result in fetchResults { moc.deleteObject(result) PainData.saveData(moc) } } } /** Method to grab data within date range at different points in that range and return in json - parameter moc: the managedobjectcontext for the app - parameter start: the start date range - parameter end: the end date range - parameter dateComps: a date component used to calculate the interval - parameter timeUnit: identifies if we are looking at days, weeks, months, or years - returns: a string of Json */ class func fetchDataInRange(moc: NSManagedObjectContext ,start: NSDate, end: NSDate, dateComps: NSDateComponents, timeUnit: String) -> (json: String, average: String) { var resultAverages: [AnyObject] = [AnyObject]() var jsonObject: [AnyObject] = [AnyObject]() var xValue: Int = 1 let cal = NSCalendar.currentCalendar() var totalAverage = (0, 0) //Constants that determine how many data points for each time interval we need to generate let NUM_POINTS_DAY = 48 let NUM_POINTS_WEEK = 14 let NUM_POINTS_MONTH = 8 let NUM_POINTS_YEAR = 24 var num_points = 0 if timeUnit == "day" { num_points = NUM_POINTS_DAY dateComps.hour = -1 } else if timeUnit == "week" { num_points = NUM_POINTS_WEEK dateComps.day = -1 } else if timeUnit == "month" { num_points = NUM_POINTS_MONTH dateComps.day = -7 } else if timeUnit == "year" { num_points = NUM_POINTS_YEAR dateComps.year = -1 } // Fetch all the data within range and then sort it out after let fetchRequest = NSFetchRequest(entityName: painDataName) let datePredicate = NSPredicate(format: "timeStamp > %@ AND timeStamp < %@", start, end) fetchRequest.predicate = datePredicate do { if let results: [PainData] = try moc.executeFetchRequest(fetchRequest) as? [PainData] { // iterate through dates var date: NSDate = end.copy() as! NSDate var previousDate = date while resultAverages.count < num_points { date = cal.dateByAddingComponents(dateComps, toDate: date, options: [])! var avg = 0 var count = 0 // find all dates in sub range and average them out before inserting into json for result in results { let tempDate = result.timeStamp if tempDate.timeIntervalSinceDate(previousDate) <= 0 && tempDate.timeIntervalSinceDate(date) >= 0 { avg += result.painRating.integerValue count++ } } if count > 0 { avg = avg / count totalAverage.0 += avg totalAverage.1++ } resultAverages.append(avg) xValue++ previousDate = date } } } catch { print("Caught exception: \(error)") } for (index, avg) in resultAverages.enumerate() { jsonObject.append(["x": resultAverages.count - index, "y":avg]) } jsonObject = Array(jsonObject.reverse()) let finalValue = totalAverage.1 == 0 ? "0" : "\(totalAverage.0 / totalAverage.1)" return (Utils.JSONStringify(jsonObject, prettyPrinted: false), finalValue) } }
epl-1.0
8f2848fb9c1f1b6eff51f2063c8040b8
36.805714
172
0.580713
5.164715
false
false
false
false
hisekaldma/Polyhymnia
Sources/Language/Lexer.swift
1
5821
typealias Char = UInt16 final class Lexer { let tabSize = 2 var source = "" var tokens = [TokenInfo]() var indents = [0] var chars: [Char] var context: Context = .pattern var pos = 0 var col = 0 init(source: String) { // Use UTF16 to iterate through string for performance, // and to make char counts work with NSAttributedString self.source = source self.chars = Array(source.utf16) } var finished: Bool { return pos >= chars.count } func consume(_ steps: Int = 1) { self.pos += steps self.col += steps } func rewind(to pos: Int, col: Int) { self.pos = pos self.col = col } var current: Char { if pos < chars.count { return chars[pos] } else { return 0 } } func lookahead(_ steps: Int) -> Char { let index = pos + steps if index < chars.count { return chars[index] } else { return 0 } } // Create a token func createToken(_ value: Token) { tokens.append(TokenInfo(value: value, start: pos-1, end: pos)) } func createToken(_ value: Token, start: Int) { tokens.append(TokenInfo(value: value, start: start, end: pos)) } // Lex indentation at the start of a line func lexIndents() { // Based on Python lexing: while current != 0 { switch current { case " ": consume() case "\t": consume() col += tabSize - 1 case "\n": return // Lines with only whitespace don't affect indentation case "#": return // Lines with comments don't affect indentation default: break lexing } } // Create indent token if col > indents.last { createToken(.indent) indents.append(col) } // Create dedent tokens while col < indents.last { createToken(.dedent) indents.removeLast() } } // Lex comment until the end of the line func lexComment() { let start = pos var comment = "" lexing: while !finished { switch current { case "\n": break lexing default: comment.append(current) consume() } } createToken(.comment(comment), start: start) } // Scan a name func scanName() -> Token { var string = "" lexing: while !finished { switch current { case "a"..."z", "A"..."Z", "0"..."9": string.append(current) consume() default: break lexing } } return .name(string) } // Scan an integer func scanNumber() -> Token { var string = "" // Lex leading digits integer: while !finished { switch current { case "0"..."9": string.append(current) consume() default: break integer } } return .number(Int(string)!) } // Scan unknown stuff, until we find something known func scanUnknown() -> Token { lexing: while !finished { switch current { case " ", "\t", "\n", ",", ":", "=", "|", "_": break lexing default: consume() } } return .unknown } func lexNewline() { consume() // Reset column and context col = 0 context = .pattern // Skip empty lines while current == "\n" { consume() } createToken(.eol) } func lexToken(_ token: Token) { consume() createToken(token) } func lex() -> [TokenInfo] { lexing: while !finished { // Indentation if col == 0 { lexIndents() } // Regular tokens switch current { case " ": consume(); continue lexing case "\t": consume(); continue lexing case ",": lexToken(.comma); context = .function case ":": lexToken(.colon) case "=": lexToken(.assign) case "\n": lexNewline() default: switch context { case .pattern: lexPatternToken() case .function: lexFunctionToken() } } } // Always end with a line break if tokens.count > 0 && tokens.last?.value != .eol { createToken(.eol) } // Clear remaining indentation while indents.last > 0 { createToken(.dedent) indents.removeLast() } return tokens } class func lex(_ source: String) -> [TokenInfo] { let lexer = Lexer(source: source) return lexer.lex() } enum Context { case pattern case function } } // Make string literals work as char literals extension Char: UnicodeScalarLiteralConvertible { public init(unicodeScalarLiteral value: UnicodeScalar) { self.init(value.value) } } extension String { mutating func append(_ u: Char) { self.append(UnicodeScalar(u)) } }
mit
04a7b965c4ecde7d33f1ab91de56c0c2
22.662602
77
0.450438
4.983733
false
false
false
false
Hxucaa/ReactiveArray
Pod/Classes/ReactiveArray.swift
1
7079
// // ReactiveArray.swift // ReactiveArray // // Created by Guido Marucci Blas on 6/29/15. // Copyright (c) 2015 Wolox. All rights reserved. // import Foundation import ReactiveCocoa import Result public final class ReactiveArray<T>: MutableCollectionType { public typealias OperationProducer = SignalProducer<Operation<T>, NoError> public typealias OperationSignal = Signal<Operation<T>, NoError> private var _elements: Array<T> = [] private let (_signal, _observer) = OperationSignal.pipe() private let _mutableCount: MutableProperty<Int> // MARK: - Initializers public init(elements:[T]) { _elements = elements _mutableCount = MutableProperty<Int>(elements.count) _signal.observeNext { [unowned self] operation in self.updateArray(operation) } } public convenience init(producer: OperationProducer) { self.init() producer .start(_observer) } public convenience init(producer: OperationProducer, startWithElements: Array<T>) { self.init() _elements = startWithElements producer .start(_observer) } public convenience init() { self.init(elements: []) } // MARK: - API // MARK: Observable Signals public var signal: OperationSignal { return _signal } public var producer: OperationProducer { let appendCurrentElements = OperationProducer(value: Operation.Initiate(values: _elements)) let forwardOperations = OperationProducer { (observer, dispoable) in self._signal.observe(observer) } return appendCurrentElements .concat(forwardOperations) } private lazy var _observableCount: AnyProperty<Int> = AnyProperty(self._mutableCount) public var observableCount: AnyProperty<Int> { return _observableCount } // MARK: Operations /** Append newElement to the `ReactiveArray`. - parameter element: newElement */ public func append(element: T) { let operation: Operation<T> = .Append(value: element) _observer.sendNext(operation) } /** Append the elements of newElements to self. - parameter elements: Array of new elements. */ public func appendContentsOf(elements: [T]) { let operation: Operation<T> = .AppendContentsOf(values: elements) _observer.sendNext(operation) } /** Insert newElement at index i. Requires: i <= count Complexity: O(count). - parameter element: newElement - parameter index: The index i. */ public func insert(element: T, atIndex index: Int) { let operation: Operation<T> = .Insert(value: element, atIndex: index) _observer.sendNext(operation) } /** Replace and return the element at index i with another element. - parameter newElement: The new element. - parameter index: The index i. - returns: The original element at index i */ public func replace(newElement: T, atIndex index : Int) -> T { let operation: Operation<T> = .Replace(value: newElement, atIndex: index) // temporarily save the element before replace happens let toBeReplacedElement = _elements[index] _observer.sendNext(operation) return toBeReplacedElement } /** Remove and return the element at index i. - parameter index: The index of the element that is to be removed. - returns: Element at index i. */ public func removeAtIndex(index: Int) -> T { let operation: Operation<T> = .RemoveElement(atIndex: index) // temporarily save the element before removal happens let toBeRemovedElement = _elements[index] _observer.sendNext(operation) return toBeRemovedElement } /** Replace the underlying array of elements with a new one. - parameter elements: The new array of elements. */ public func replaceAll(elements: [T]) { let operation: Operation<T> = .ReplaceAll(values: elements) _observer.sendNext(operation) } /** Remove all elements. - parameter keepCapacity: A boolean value. */ public func removeAll(keepCapacity: Bool) { let operation: Operation<T> = .RemoveAll(keepCapacity: keepCapacity) _observer.sendNext(operation) } // MARK: Array Functions public func mirror<U>(transformer: T -> U) -> ReactiveArray<U> { return ReactiveArray<U>(producer: producer.map { $0.map(transformer) }, startWithElements: _elements.map(transformer)) } public subscript(index: Int) -> T { get { return _elements[index] } set(newValue) { replace(newValue, atIndex: index) } } /// Exposing the underlying array of elements that is being encapsulated. public var array: Array<T> { return _elements } // MARK: - Others private func updateArray(operation: Operation<T>) { switch operation { case .Initiate(_): // do nothing as the data is present when `Initiate` opearation occurs break case .Append(let value): _elements.append(value) case .AppendContentsOf(let values): _elements.appendContentsOf(values) case .Insert(let value, let index): _elements.insert(value, atIndex: index) case .Replace(let value, let index): _elements[index] = value case .RemoveElement(let index): _elements.removeAtIndex(index) case .ReplaceAll(let values): _elements = values case .RemoveAll(let keepCapacity): _elements.removeAll(keepCapacity: keepCapacity) } _mutableCount.value = _elements.count } } extension ReactiveArray : CollectionType { /// true if and only if the Array is empty public var isEmpty: Bool { return _elements.isEmpty } /// How many elements the Array stores public var count: Int { return _elements.count } /// Always zero, which is the index of the first element when non-empty. public var startIndex: Int { return _elements.startIndex } /// A "past-the-end" element index; the successor of the last valid subscript argument. public var endIndex: Int { return _elements.endIndex } /// The first element, or nil if the array is empty public var first: T? { return _elements.first } /// The last element, or nil if the array is empty public var last: T? { return _elements.last } } extension ReactiveArray : CustomDebugStringConvertible { public var debugDescription: String { return _elements.debugDescription } }
mit
7d2070a04b0aa2a8bae4513a09ada525
27.663968
126
0.612516
4.835383
false
false
false
false
paulgriffiths/macvideopoker
VideoPokerTests/RankComboCounterTests.swift
1
4498
// // RankComboCounterTests.swift // VideoPoker // // Created by Paul Griffiths on 5/9/15. // Copyright (c) 2015 Paul Griffiths. All rights reserved. // import Cocoa import XCTest class RankComboCounterTests: XCTestCase { let counter: RankComboCounter = RankComboCounter(rankCounter: RankCounter(cardList: CardList(cards: Cards.ThreeClubs.card, Cards.FiveHearts.card, Cards.FiveDiamonds.card, Cards.SixSpades.card, Cards.SixHearts.card, Cards.NineHearts.card, Cards.NineClubs.card, Cards.NineSpades.card, Cards.JackDiamonds.card, Cards.QueenSpades.card, Cards.KingDiamonds.card, Cards.AceSpades.card, Cards.AceClubs.card))) func testNumberByCount() { for (index, count) in [0, 4, 3, 1, 0, 0, 0].enumerate() { XCTAssertEqual(count, counter.numberByCount(index)) } } func testHasCountWhenPresent() { for index in 1...3 { XCTAssertTrue(counter.containsCount(index)) } } func testHasCountWhenNotPresent() { for index in 4...6 { XCTAssertFalse(counter.containsCount(index)) } } func testHighestByCountWhenPresent() { for (index, expectedRank) in [Rank.King, Rank.Ace, Rank.Nine].enumerate() { if let rank = counter.highestByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testHighestByCountWhenNotPresent() { for index in 4...6 { if counter.highestByCount(index) != nil { XCTFail("rank found when not expected") } } } func testSecondHighestByCountWhenPresent() { for (index, expectedRank) in [Rank.Queen, Rank.Six].enumerate() { if let rank = counter.secondHighestByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testSecondHighestByCountWhenNotPresent() { for index in 3...6 { if counter.secondHighestByCount(index) != nil { XCTFail("rank found when not expected") } } } func testLowestByCountWhenPresent() { for (index, expectedRank) in [Rank.Three, Rank.Five, Rank.Nine].enumerate() { if let rank = counter.lowestByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testLowestByCountWhenNotPresent() { for index in 4...6 { if counter.lowestByCount(index) != nil { XCTFail("rank found when not expected") } } } func testRangeByCountWhenPresent() { for (index, expectedRange) in [13 - 3, 14 - 5, 9 - 9].enumerate() { if let range = counter.rangeByCount(index + 1) { XCTAssertEqual(expectedRange, range) } else { XCTFail("expected range not found") } } } func testRangeByCountWhenNotPresent() { for index in 4...6 { if counter.rangeByCount(index) != nil { XCTFail("range found when not expected") } } } func testScoreByCountWhenPresent() { func sCmpt(rank: Rank, index: Int) -> Int { return rank.value * Int(pow(Double(Rank.numberOfRanks), Double(index))) } let expectedScores = [ (sCmpt(Rank.King, index: 3) + sCmpt(Rank.Queen, index: 2) + sCmpt(Rank.Jack, index: 1) + sCmpt(Rank.Three, index: 0)), (sCmpt(Rank.Ace, index: 2) + sCmpt(Rank.Six, index: 1) + sCmpt(Rank.Five, index: 0)), (sCmpt(Rank.Nine, index: 0)) ] for (index, expectedScore) in expectedScores.enumerate() { if let score = counter.scoreByCount(index + 1) { XCTAssertEqual(expectedScore, score) } else { XCTFail("expected score not found") } } } func testScoreByCountWhenNotPresent() { for index in 4...6 { if counter.scoreByCount(index) != nil { XCTFail("score found when not expected") } } } }
gpl-3.0
268434b0066367e98d2d28f354bd1dec
30.900709
130
0.550912
4.251418
false
true
false
false
stripe/stripe-ios
Tests/installation_tests/swift_package_manager/with_swift/SPMTest/ViewController.swift
1
1379
// // ViewController.swift // SPMTest // // Created by Mel Ludowise on 8/3/21. // Copyright © 2021 Stripe. All rights reserved. // import Stripe import StripeApplePay import StripeCardScan import StripeFinancialConnections import StripeIdentity import StripePaymentSheet import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() StripeAPI.defaultPublishableKey = "foo" if #available(iOS 14.3, *) { let _ = IdentityVerificationSheet(verificationSessionClientSecret: "test") } if #available(iOS 12.0, *) { let _ = FinancialConnectionsSheet( financialConnectionsSessionClientSecret: "", returnURL: nil ) } // Initialize a card field to make sure we can load image resources let cardField = STPPaymentCardTextField() cardField.frame = CGRect(x: 0, y: 0, width: 300, height: 100) self.view.addSubview(cardField) let _ = CardImageVerificationSheet( cardImageVerificationIntentId: "foo", cardImageVerificationIntentSecret: "foo" ) let _ = PaymentSheet( setupIntentClientSecret: "", configuration: PaymentSheet.Configuration() ) // Do any additional setup after loading the view. } }
mit
4db37973f077576d2f14325188f5e3c0
26.56
86
0.637155
5.141791
false
false
false
false
trujillo138/MyExpenses
MyExpenses/MyExpenses/Scenes/ExpensePeriods/ExpensePeriodsViewController.swift
1
15524
// // ExpensePeriodsViewController.swift // MyExpenses // // Created by Tomas Trujillo on 6/11/17. // Copyright © 2017 TOMApps. All rights reserved. // import UIKit class ExpensePeriodsViewController: ExpensesKeyBoardViewController, StateControllerHandler, UITableViewDelegate { //MARK: Outlets @IBOutlet fileprivate weak var tableView: UITableView! @IBOutlet private var addPreviousExpenseView: UIView! @IBOutlet private weak var previousExpensePeriodDate: ExpenseDateTextField! { didSet { previousExpensePeriodDate.date = Date() previousExpensePeriodDate.define(maximumDate: Date(), minimumDate: nil) } } @IBOutlet private weak var addPreviousExpenseNavigationBar: UINavigationBar! @IBOutlet private weak var previousPeriodMonthlyIncomeLabel: UILabel! { didSet { previousPeriodMonthlyIncomeLabel.text = LStrings.User.MonthlyIncomeLabel } } @IBOutlet fileprivate weak var previousPeriodMonthlyIncomeTextField: ExpenseAmountTextField! { didSet { previousPeriodMonthlyIncomeTextField.text = stateController?.user.budgetPerPeriod.currencyFormat ?? Double(0.0).currencyFormat } } @IBOutlet private weak var perviousPeriodMontlyGoalLabel: UILabel! { didSet { perviousPeriodMontlyGoalLabel.text = LStrings.User.MonthlyGoalLabel } } @IBOutlet fileprivate weak var previousPeriodMonthlyGoalTextField: ExpenseAmountTextField! { didSet { previousPeriodMonthlyGoalTextField.text = stateController?.user.savingGoalPerPeriod.currencyFormat ?? Double(0.0).currencyFormat } } @IBOutlet weak var previousPeriodCurrencyLabel: UILabel! { didSet { previousPeriodCurrencyLabel.text = LStrings.User.CurrencyLabel } } @IBOutlet weak var currencyPickerTextfield: ExpensePickerViewTextField! { didSet { let dataSource = Currency.CurrencyDataSource() currencyPickerTextfield.pickerViewData = dataSource currencyPickerTextfield.setInitialValue(value: stateController?.user.currentCurrency.rawValue ?? "USD") } } @IBOutlet private weak var scrollView: UIScrollView! //MARK: Variables private var dataSource: ExpensePeriodDataSource? private let ExpensePeriodCellIdentifier = "ExpensePeriodCell" private let ShowExpensePeriodSegueIdentifier = "Show expense period" fileprivate let ShowExpensePeriodPDFSegueIdentifier = "Show PDF expense period" var stateController: StateController? fileprivate var expensePeriods: [ExpensePeriod] { return stateController?.expensePeriods ?? [ExpensePeriod]() } fileprivate var menuController: UIMenuController! fileprivate var selectedPeriod: ExpensePeriod? private var editingPeriod: ExpensePeriod? //MARK: Viewcontroller Lifecycle override func viewDidLoad() { super.viewDidLoad() title = LStrings.ExpensePeriod.ExpensePeriodsTitle registerExpensePeriodCell() tableView.delegate = self initDataSource() addBigTitleToNavController() registerForPreviewing(with: self, sourceView: view) configureMenuController() useScrollViewForKeyboardReaction(scrollView: scrollView, inSuperView: self.view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) MyExpensesNotifications.NotifyShowAddButton() tableView.reloadData() registerForKeyboardReaction() addFooterToTable() } private func addFooterToTable() { let footerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 30.0)) footerView.backgroundColor = UIColor.clear tableView.tableFooterView = footerView } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unRegisterForKeyboardReaction() } private func initDataSource() { guard let unwrappedStatecontroller = stateController else { return } let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ExpensePeriodsViewController.longPressedCell(longPressedGesture:))) let expensePeriodDataSource = ExpensePeriodDataSource(cellIdentifier: ExpensePeriodCellIdentifier, stateController: unwrappedStatecontroller) self.view.addGestureRecognizer(longPressGestureRecognizer) tableView.dataSource = expensePeriodDataSource dataSource = expensePeriodDataSource } private func registerExpensePeriodCell() { tableView.register(UINib.init(nibName: "ExpensePeriodCell", bundle: nil), forCellReuseIdentifier: ExpensePeriodCellIdentifier) } //MARK: TableView Delegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: ShowExpensePeriodSegueIdentifier, sender: tableView.cellForRow(at: indexPath)) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let period = self.expensePeriods[indexPath.row] let editAction = UITableViewRowAction(style: .normal, title: LStrings.User.EditButtonLabel) { _, indexPath in self.editingPeriod = period self.setupExpensePeriodWindow(withGoal: period.formattedGoal, andIncome: period.formattedIncome, inCurrency: period.currency.rawValue, date: period.date) } let exportAction = UITableViewRowAction(style: .normal, title: LStrings.ExpensePeriod.ExportExpensePeriodMenuItem) { _, indexPath in self.selectedPeriod = period self.performSegue(withIdentifier:self.ShowExpensePeriodPDFSegueIdentifier, sender: nil) } return [editAction, exportAction] } //MARK: Actions private func setupExpensePeriodWindow(withGoal savingGoal: String, andIncome income: String, inCurrency currency: String, date: Date) { previousPeriodMonthlyGoalTextField.text = savingGoal previousPeriodMonthlyIncomeTextField.text = income currencyPickerTextfield.setInitialValue(value: currency) previousExpensePeriodDate.date = date previousExpensePeriodDate.define(maximumDate: date, minimumDate: nil) previousExpensePeriodDate.isEnabled = editingPeriod != nil ? false : true currencyPickerTextfield.isEnabled = editingPeriod != nil ? false : true let width: CGFloat = 300.0 let height: CGFloat = 200.0 let previouseExpensePeriodViewOrigin = CGPoint(x: view.bounds.midX - width / 2, y: view.bounds.midY - height / 2) let previouseExpensePeriodViewSize = CGSize(width: width, height: height) self.addPreviousExpenseView.frame = CGRect(origin: previouseExpensePeriodViewOrigin, size: previouseExpensePeriodViewSize) self.addPreviousExpenseView.setRoundedCorners() UIView.animate(withDuration: 0.4) { self.addPreviousExpenseView.alpha = 1.0 self.addViewToDimmedBlackView(view: self.addPreviousExpenseView) } } @IBAction private func addPreviousExpensePeriodButtonPressed(_ sender: Any) { let savingGoal = stateController?.user.savingGoalPerPeriod.currencyFormat ?? Double(0.0).currencyFormat let income = stateController?.user.budgetPerPeriod.currencyFormat ?? Double(0.0).currencyFormat let currency = stateController?.user.currentCurrency.rawValue ?? "USD" let date = Date() setupExpensePeriodWindow(withGoal: savingGoal, andIncome: income, inCurrency: currency, date: date) editingPeriod = nil } @IBAction private func cancelAddingPreviousExpensePeriodButtonPressed(_ sender: Any) { removePreviousExpensePeriodView() editingPeriod = nil } @IBAction private func savePreviousExpensePeriodButtonPressed(_ sender: Any) { let monthlyIncome = previousPeriodMonthlyIncomeTextField.amount let monthlyGoal = previousPeriodMonthlyGoalTextField.amount let currency = currencyPickerTextfield.text ?? "" let date = previousExpensePeriodDate.date if editingPeriod != nil { editExpensePeriod(monthlyIncome: monthlyIncome, monthlyGoal: monthlyGoal) removePreviousExpensePeriodView() } else { self.addExpensePeriod(monthlyIncome: monthlyIncome, monthlyGoal: monthlyGoal, date: date, currency: currency) } editingPeriod = nil } private func editExpensePeriod(monthlyIncome: Double, monthlyGoal: Double) { guard let period = editingPeriod else { return } stateController?.updateExpensePeriod(period ,monthlyIncome: monthlyIncome, monthlyGoal: monthlyGoal) } private func addExpensePeriod(monthlyIncome: Double, monthlyGoal: Double, date: Date, currency: String) { do { guard let stc = stateController else { return } let row = try stc.addPreviousExpensePeriodWith(monthlyIncome: monthlyIncome, monthlyGoal: monthlyGoal, date: date, currency: currency) removePreviousExpensePeriodView() tableView.insertRows(at: [IndexPath(row: row, section: 0)], with: .automatic) } catch UserErrors.RepeatedPeriod { ExpenseAlerts.presentSimpleAlert(in: self, title: LStrings.Alerts.RepeatedPreviousPeriodTitle, message: LStrings.Alerts.RepeatedPreviousPeriodMessage) } catch { print("THIS SHOULD NEVER HAPPEN") } } private func removePreviousExpensePeriodView() { UIView.animate(withDuration: 0.4) { self.addPreviousExpenseView.alpha = 0.0 // self.addPreviousExpenseView.removeFromSuperview() self.removeDimmedBlackView() } } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueIdentifier = segue.identifier else { return } if segueIdentifier == ShowExpensePeriodSegueIdentifier { prepareForExpensePeriodViewControllerWith(segue: segue, sender: sender) } else if segueIdentifier == ShowExpensePeriodPDFSegueIdentifier { prepareForPDFViewControllerWith(segue: segue, sender: sender) } } private func prepareForExpensePeriodViewControllerWith(segue: UIStoryboardSegue, sender: Any?) { guard let dvc = segue.destination as? ExpensePeriodViewController, let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else { return } dvc.stateController = stateController dvc.period = expensePeriods[indexPath.row] } private func prepareForPDFViewControllerWith(segue: UIStoryboardSegue, sender: Any?) { guard let nav = segue.destination as? UINavigationController, let dvc = nav.viewControllers.first as? PDFDisplayViewController, let period = selectedPeriod else { return } dvc.expensePeriods = [period] } } //MARK: Preview delegate extension ExpensePeriodsViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let newLocation = view.convert(location, to: tableView) guard let indexPath = tableView.indexPathForRow(at: newLocation), let cell = tableView.cellForRow(at: indexPath) else { return nil } let frame = tableView.convert(cell.frame, to: view) previewingContext.sourceRect = frame guard let expensePeriodController = storyboard?.instantiateExpensePeriodViewController() else { return nil } expensePeriodController.period = expensePeriods[indexPath.row] expensePeriodController.stateController = stateController expensePeriodController.delegate = self return expensePeriodController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { navigationController?.pushViewController(viewControllerToCommit, animated: true) } } //MARK: Menucontroller extension ExpensePeriodsViewController { private func configureMenuController() { self.menuController = UIMenuController.shared let exportMenuItem = UIMenuItem(title: LStrings.ExpensePeriod.ExportExpensePeriodMenuItem, action: #selector(ExpensePeriodsViewController.exportPeriod(sender:))) let editMenuItem = UIMenuItem(title: LStrings.User.EditButtonLabel, action: #selector(ExpensePeriodsViewController.editPeriod(sender:))) self.menuController.menuItems = [editMenuItem, exportMenuItem] } @objc func longPressedCell(longPressedGesture: UILongPressGestureRecognizer) { if longPressedGesture.state == .began { self.selectedPeriod = nil let point = longPressedGesture.location(in: self.view) let tablePoint = view.convert(point, to: self.tableView) guard let indexPath = self.tableView.indexPathForRow(at: tablePoint), let cell = self.tableView.cellForRow(at: indexPath) else { return } self.selectedPeriod = self.expensePeriods[indexPath.row] showMenuController(forCell: cell) } } private func showMenuController(forCell cell: UITableViewCell) { self.menuController.setTargetRect(cell.bounds.insetBy(dx: 0.0, dy: 0.1), in: cell) menuController.setMenuVisible(true, animated: true) menuController.update() } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { switch action { case #selector(ExpensePeriodsViewController.exportPeriod(sender:)): return true case #selector(ExpensePeriodsViewController.editPeriod(sender:)): return true default: return false } } override var canBecomeFirstResponder: Bool { return true } @objc func exportPeriod(sender: UIMenuItem) { performSegue(withIdentifier: ShowExpensePeriodPDFSegueIdentifier, sender: nil) } @objc func editPeriod(sender: UIMenuItem) { guard let period = self.selectedPeriod else { return } self.setupExpensePeriodWindow(withGoal: period.formattedGoal, andIncome: period.formattedIncome, inCurrency: period.currency.rawValue, date: period.date) } } //MARK: Preview Action Listener extension ExpensePeriodsViewController: ExpensePeriodPreviewActionListener { func exportPeriod(_ period: ExpensePeriod) { selectedPeriod = period performSegue(withIdentifier: ShowExpensePeriodPDFSegueIdentifier, sender: nil) } func editPeriod(_ period: ExpensePeriod) { self.editingPeriod = period self.setupExpensePeriodWindow(withGoal: period.formattedGoal, andIncome: period.formattedIncome, inCurrency: period.currency.rawValue, date: period.date) } }
apache-2.0
c66099bb7fb21cef7691d80a0af73905
44.388889
169
0.702377
5.230121
false
false
false
false
Elors/LunarCore-Swift
LunarCore-Swift/LunarCore.swift
1
81696
// // LunarCore.swift // LunarCore-Swift // // Created by Elors on 2016/11/6. // Copyright © 2016年 elors. All rights reserved. // import Foundation private let minYear = 1890 // 最小年限 private let maxYear = 2100 // 最大年限 private let weekStart = 0 // 周首日(可改成 app 配置) /** * 获得本地化的字符串 这里 app 可以自行实现 * * @param text key * * @return 本地化字符串 */ private func i18n(_ key: String?) -> String { return key ?? "" } /** * 获得不为空的字符串 * * @param text text * * @return text */ private func $(_ text: String?) -> String { return (text != nil ? text! : "") } // MARK: - LunarCore class LunarCore { /** * 1890 - 2100 年的农历数据 * 数据格式:[0,2,9,21936] * [闰月所在月,0为没有闰月; *正月初一对应公历月; *正月初一对应公历日; *农历每月的天数的数组(需转换为二进制,得到每月大小,0=小月(29日),1=大月(30日));] */ private let lunarInfo = [ [2,1,21,22184],[0,2,9,21936],[6,1,30,9656],[0,2,17,9584],[0,2,6,21168],[5,1,26,43344],[0,2,13,59728],[0,2,2,27296],[3,1,22,44368],[0,2,10,43856], [8,1,30,19304],[0,2,19,19168],[0,2,8,42352],[5,1,29,21096],[0,2,16,53856],[0,2,4,55632],[4,1,25,27304],[0,2,13,22176],[0,2,2,39632],[2,1,22,19176], [0,2,10,19168],[6,1,30,42200],[0,2,18,42192],[0,2,6,53840],[5,1,26,54568],[0,2,14,46400],[0,2,3,54944],[2,1,23,38608],[0,2,11,38320],[7,2,1,18872], [0,2,20,18800],[0,2,8,42160],[5,1,28,45656],[0,2,16,27216],[0,2,5,27968],[4,1,24,44456],[0,2,13,11104],[0,2,2,38256],[2,1,23,18808],[0,2,10,18800], [6,1,30,25776],[0,2,17,54432],[0,2,6,59984],[5,1,26,27976],[0,2,14,23248],[0,2,4,11104],[3,1,24,37744],[0,2,11,37600],[7,1,31,51560],[0,2,19,51536], [0,2,8,54432],[6,1,27,55888],[0,2,15,46416],[0,2,5,22176],[4,1,25,43736],[0,2,13,9680],[0,2,2,37584],[2,1,22,51544],[0,2,10,43344],[7,1,29,46248], [0,2,17,27808],[0,2,6,46416],[5,1,27,21928],[0,2,14,19872],[0,2,3,42416],[3,1,24,21176],[0,2,12,21168],[8,1,31,43344],[0,2,18,59728],[0,2,8,27296], [6,1,28,44368],[0,2,15,43856],[0,2,5,19296],[4,1,25,42352],[0,2,13,42352],[0,2,2,21088],[3,1,21,59696],[0,2,9,55632],[7,1,30,23208],[0,2,17,22176], [0,2,6,38608],[5,1,27,19176],[0,2,15,19152],[0,2,3,42192],[4,1,23,53864],[0,2,11,53840],[8,1,31,54568],[0,2,18,46400],[0,2,7,46752],[6,1,28,38608], [0,2,16,38320],[0,2,5,18864],[4,1,25,42168],[0,2,13,42160],[10,2,2,45656],[0,2,20,27216],[0,2,9,27968],[6,1,29,44448],[0,2,17,43872],[0,2,6,38256], [5,1,27,18808],[0,2,15,18800],[0,2,4,25776],[3,1,23,27216],[0,2,10,59984],[8,1,31,27432],[0,2,19,23232],[0,2,7,43872],[5,1,28,37736],[0,2,16,37600], [0,2,5,51552],[4,1,24,54440],[0,2,12,54432],[0,2,1,55888],[2,1,22,23208],[0,2,9,22176],[7,1,29,43736],[0,2,18,9680],[0,2,7,37584],[5,1,26,51544], [0,2,14,43344],[0,2,3,46240],[4,1,23,46416],[0,2,10,44368],[9,1,31,21928],[0,2,19,19360],[0,2,8,42416],[6,1,28,21176],[0,2,16,21168],[0,2,5,43312], [4,1,25,29864],[0,2,12,27296],[0,2,1,44368],[2,1,22,19880],[0,2,10,19296],[6,1,29,42352],[0,2,17,42208],[0,2,6,53856],[5,1,26,59696],[0,2,13,54576], [0,2,3,23200],[3,1,23,27472],[0,2,11,38608],[11,1,31,19176],[0,2,19,19152],[0,2,8,42192],[6,1,28,53848],[0,2,15,53840],[0,2,4,54560],[5,1,24,55968], [0,2,12,46496],[0,2,1,22224],[2,1,22,19160],[0,2,10,18864],[7,1,30,42168],[0,2,17,42160],[0,2,6,43600],[5,1,26,46376],[0,2,14,27936],[0,2,2,44448], [3,1,23,21936],[0,2,11,37744],[8,2,1,18808],[0,2,19,18800],[0,2,8,25776],[6,1,28,27216],[0,2,15,59984],[0,2,4,27424],[4,1,24,43872],[0,2,12,43744], [0,2,2,37600],[3,1,21,51568],[0,2,9,51552],[7,1,29,54440],[0,2,17,54432],[0,2,5,55888],[5,1,26,23208],[0,2,14,22176],[0,2,3,42704],[4,1,23,21224], [0,2,11,21200],[8,1,31,43352],[0,2,19,43344],[0,2,7,46240],[6,1,27,46416],[0,2,15,44368],[0,2,5,21920],[4,1,24,42448],[0,2,12,42416],[0,2,2,21168], [3,1,22,43320],[0,2,9,26928],[7,1,29,29336],[0,2,17,27296],[0,2,6,44368],[5,1,26,19880],[0,2,14,19296],[0,2,3,42352],[4,1,24,21104],[0,2,10,53856], [8,1,30,59696],[0,2,18,54560],[0,2,7,55968],[6,1,27,27472],[0,2,15,22224],[0,2,5,19168],[4,1,25,42216],[0,2,12,42192],[0,2,1,53584],[2,1,21,55592], [0,2,9,54560] ] // 阳历每月天数 private let solarDaysOfMonth = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] // Memory Cache private lazy var memoryCache: LCMemoryCache = { return LCMemoryCache() }() // GMT 0 的时区 private lazy var timeZone: TimeZone = { return TimeZone(secondsFromGMT: 0)! }() // 错误码表 private lazy var errorCode: [Int: String] = { return [ 100: "输入的年份超过了可查询范围,仅支持1891至2100年", 101: "参数输入错误,请查阅文档" ] }() // 1890 ~ 2100 年农历新年数据 private lazy var springFestival: [[Int]] = { return [ [1,21],[2,9],[1,30],[2,17],[2,6],[1,26],[2,14],[2,2],[1,22],[2,10],[1,31],[2,19],[2,8],[1,29],[2,16],[2,4],[1,25],[2,13],[2,2],[1,22],[2,10],[1,30], [2,18],[2,6],[1,26],[2,14],[2,4],[1,23],[2,11],[2,1],[2,20],[2,8],[1,28],[2,16],[2,5],[1,24],[2,13],[2,2],[1,23],[2,10],[1,30],[2,17],[2,6],[1,26], [2,14],[2,4],[1,24],[2,11],[1,31],[2,19],[2,8],[1,27],[2,15],[2,5],[1,25],[2,13],[2,2],[1,22],[2,10],[1,29],[2,17],[2,6],[1,27],[2,14],[2,3],[1,24], [2,12],[1,31],[2,18],[2,8],[1,28],[2,15],[2,5],[1,25],[2,13],[2,2],[1,21],[2,9],[1,30],[2,17],[2,6],[1,27],[2,15],[2,3],[1,23],[2,11],[1,31],[2,18], [2,7],[1,28],[2,16],[2,5],[1,25],[2,13],[2,2],[2,20],[2,9],[1,29],[2,17],[2,6],[1,27],[2,15],[2,4],[1,23],[2,10],[1,31],[2,19],[2,7],[1,28],[2,16], [2,5],[1,24],[2,12],[2,1],[1,22],[2,9],[1,29],[2,18],[2,7],[1,26],[2,14],[2,3],[1,23],[2,10],[1,31],[2,19],[2,8],[1,28],[2,16],[2,5],[1,25],[2,12], [2,1],[1,22],[2,10],[1,29],[2,17],[2,6],[1,26],[2,13],[2,3],[1,23],[2,11],[1,31],[2,19],[2,8],[1,28],[2,15],[2,4],[1,24],[2,12],[2,1],[1,22],[2,10], [1,30],[2,17],[2,6],[1,26],[2,14],[2,2],[1,23],[2,11],[2,1],[2,19],[2,8],[1,28],[2,15],[2,4],[1,24],[2,12],[2,2],[1,21],[2,9],[1,29],[2,17],[2,5], [1,26],[2,14],[2,3],[1,23],[2,11],[1,31],[2,19],[2,7],[1,27],[2,15],[2,5],[1,24],[2,12],[2,2],[1,22],[2,9],[1,29],[2,17],[2,6],[1,26],[2,14],[2,3], [1,24],[2,10],[1,30],[2,18],[2,7],[1,27],[2,15],[2,5],[1,25],[2,12],[2,1],[1,21],[2,9] ] }() // 农历数据 private lazy var lunarCalendarData: [String: [String]] = { var dict = [String: [String]]() // 天干 dict["heavenlyStems"] = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"] // 地支 dict["earthlyBranches"] = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"] // 对应地支十二生肖 dict["zodiac"] = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"] // 二十四节气 dict["solarTerm"] = ["小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"] dict["monthCn"] = ["正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊"] dict["dateCn"] = ["初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十", "卅一"] return dict }() // 中国节日放假安排,外部设置,0无特殊安排,1工作,2放假 private lazy var worktime: [String: [String: Int]] = { var dicts = [String: [String: Int]]() dicts["y2013"] = ["d0101":2,"d0102":2,"d0103":2,"d0105":1,"d0106":1,"d0209":2,"d0210":2,"d0211":2,"d0212":2,"d0213":2,"d0214":2,"d0215":2,"d0216":1, "d0217":1,"d0404":2,"d0405":2,"d0406":2,"d0407":1,"d0427":1,"d0428":1,"d0429":2,"d0430":2,"d0501":2,"d0608":1,"d0609":1,"d0610":2, "d0611":2,"d0612":2,"d0919":2,"d0920":2,"d0921":2,"d0922":1,"d0929":1,"d1001":2,"d1002":2,"d1003":2,"d1004":2,"d1005":2,"d1006":2, "d1007":2,"d1012":1] dicts["y2014"] = ["d0101":2,"d0126":1,"d0131":2,"d0201":2,"d0202":2,"d0203":2,"d0204":2,"d0205":2,"d0206":2,"d0208":1,"d0405":2,"d0407":2,"d0501":2, "d0502":2,"d0503":2,"d0504":1,"d0602":2,"d0908":2,"d0928":1,"d1001":2,"d1002":2,"d1003":2,"d1004":2,"d1005":2,"d1006":2,"d1007":2, "d1011":1] dicts["y2015"] = ["d0101":2,"d0102":2,"d0103":2,"d0104":1,"d0215":1,"d0218":2,"d0219":2,"d0220":2,"d0221":2,"d0222":2,"d0223":2,"d0224":2,"d0228":1, "d0404":2,"d0405":2,"d0406":2,"d0501":2,"d0502":2,"d0503":2,"d0620":2,"d0621":2,"d0622":2,"d0903":2,"d0904":2,"d0905":2,"d0906":1, "d0926":2,"d0927":2,"d1001":2,"d1002":2,"d1003":2,"d1004":2,"d1005":2,"d1006":2,"d1007":2,"d1010":1] dicts["y2016"] = ["d0101":2,"d0102":2,"d0103":2,"d0206":1,"d0207":2,"d0208":2,"d0209":2,"d0210":2,"d0211":2,"d0212":2,"d0213":2,"d0214":1,"d0402":2, "d0403":2,"d0404":2,"d0430":2,"d0501":2,"d0502":2,"d0609":2,"d0610":2,"d0611":2,"d0612":1,"d0915":2,"d0916":2,"d0917":2,"d0918":1, "d1001":2,"d1002":2,"d1003":2,"d1004":2,"d1005":2,"d1006":2,"d1007":2,"d1008":1,"d1009":1] return dicts }() // 公历节日 // 星号表示不重要的节日 // 破折号前面的是缩略写法 private lazy var solarFestival: [String: String] = { return [ "d0101":"元旦节", "d0120":"水瓶", "d0202":"湿地日-世界湿地日", "d0210":"*国际气象节", "d0214":"情人节", "d0219":"双鱼", "d0301":"*国际海豹日", "d0303":"*全国爱耳日", "d0305":"学雷锋-学雷锋纪念日", "d0308":"妇女节", "d0312":"植树节 孙中山逝世纪念日", "d0314":"*国际警察日", "d0315":"消费者-消费者权益日", "d0317":"*中国国医节 国际航海日", "d0321":"白羊 世界森林日 消除种族歧视国际日 世界儿歌日", "d0322":"*世界水日", "d0323":"*世界气象日", "d0324":"*世界防治结核病日", "d0325":"*全国中小学生安全教育日", "d0330":"*巴勒斯坦国土日", "d0401":"愚人节 全国爱国卫生运动月 税收宣传月", "d0407":"*世界卫生日", "d0420":"金牛", "d0422":"地球日-世界地球日", "d0423":"*世界图书和版权日", "d0424":"*亚非新闻工作者日", "d0501":"劳动节", "d0504":"青年节", "d0505":"*碘缺乏病防治日", "d0508":"*世界红十字日", "d0512":"护士节-国际护士节", "d0515":"*国际家庭日", "d0517":"*世界电信日", "d0518":"博物馆-国际博物馆日", "d0520":"*全国学生营养日", "d0521":"双子", "d0522":"*国际生物多样性日", "d0531":"*世界无烟日", "d0601":"儿童节-国际儿童节", "d0605":"环境日-世界环境日", "d0606":"*全国爱眼日", "d0617":"*防治荒漠化和干旱日", "d0622":"巨蟹", "d0623":"奥林匹克-国际奥林匹克日", "d0625":"*全国土地日", "d0626":"*国际禁毒日", "d0701":"建党节 香港回归纪念日 中共诞辰 世界建筑日", "d0702":"*国际体育记者日", "d0707":"*抗日战争纪念日", "d0711":"*世界人口日", "d0723":"狮子", "d0730":"*非洲妇女日", "d0801":"建军节", "d0808":"*中国男子节(爸爸节)", "d0823":"处女", "d0903":"抗日战争-抗日战争胜利纪念", "d0908":"*国际扫盲日 国际新闻工作者日", "d0909":"*毛泽东逝世纪念", "d0910":"教师节-中国教师节", "d0914":"*世界清洁地球日", "d0916":"*国际臭氧层保护日", "d0918":"*九一八事变纪念日", "d0920":"*国际爱牙日", "d0923":"天秤", "d0927":"*世界旅游日", "d0928":"*孔子诞辰", "d1001":"国庆节 世界音乐日 国际老人节", "d1002":"*国际和平与民主自由斗争日", "d1004":"*世界动物日", "d1006":"*老人节", "d1008":"*全国高血压日", "d1009":"*世界邮政日 万国邮联日", "d1010":"*辛亥革命纪念日 世界精神卫生日", "d1013":"*世界保健日 国际教师节", "d1014":"*世界标准日", "d1015":"*国际盲人节(白手杖节)", "d1016":"*世界粮食日", "d1017":"*世界消除贫困日", "d1022":"*世界传统医药日", "d1024":"天蝎 联合国日 世界发展信息日", "d1031":"万圣节 世界勤俭日", "d1107":"*十月社会主义革命纪念日", "d1108":"*中国记者日", "d1109":"*全国消防安全宣传教育日", "d1110":"*世界青年节", "d1111":"光棍节 国际科学与和平周(本日所属的一周)", "d1112":"*孙中山诞辰纪念日", "d1114":"*世界糖尿病日", "d1117":"*国际大学生节 世界学生节", "d1121":"*世界问候日 世界电视日", "d1123":"射手", "d1129":"*国际声援巴勒斯坦人民国际日", "d1201":"艾滋病-世界艾滋病日", "d1203":"*世界残疾人日", "d1205":"*国际经济和社会发展志愿人员日", "d1208":"*国际儿童电视日", "d1209":"*世界足球日", "d1210":"*世界人权日", "d1212":"*西安事变纪念日", "d1213":"*南京大屠杀(1937年)纪念日!紧记血泪史!", "d1220":"*澳门回归纪念", "d1221":"*国际篮球日", "d1222":"摩羯", "d1224":"平安夜", "d1225":"圣诞节", "d1226":"*毛泽东诞辰纪念" ] }() // 农历节日 private lazy var lunarFestival: [String: String] = { return [ "d0101":"春节", "d0115":"元宵节", "d0202":"龙抬头节", "d0505":"端午节", "d0707":"七夕节", "d0715":"中元节", "d0815":"中秋节", "d0909":"重阳节", "d1001":"寒衣节", "d1015":"下元节", "d1208":"腊八节", "d1223":"小年", "d0100":"除夕" ] }() // 周节日 private lazy var weekFestival: [String: String] = { return [ "0513":"*世界哮喘日", "0521":"母亲节-国际母亲节 救助贫困母亲日", "0531":"*全国助残日", "0533":"*国际牛奶日", "0627":"*中国文化遗产日", "0631":"父亲节", "0717":"*国际合作节", "0731":"*被奴役国家周", "0933":"*国际和平日", "0937":"*全民国防教育日", "0941":"*国际聋人节 世界儿童日", "0951":"*世界海事日 世界心脏病日", "1012":"*国际住房日 世界建筑日 世界人居日", "1024":"*国际减灾日", "1025":"*世界视觉日", "1145":"感恩节", "1221":"*国际儿童电视广播日" ] }() // 节气 private lazy var solarTerms: [Int: [String]] = { return [ 1890: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1891: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1892: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 1893: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 1894: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1895: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1896: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 1897: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 1898: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1899: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1900: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1901: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1902: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1903: ["d0205","d0220","d0307","d0322","d0406","d0421","d0507","d0522","d0607","d0622","d0708","d0724","d0809","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1904: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0107","d0121"], 1905: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1906: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1907: ["d0205","d0220","d0307","d0322","d0406","d0421","d0507","d0522","d0607","d0622","d0708","d0724","d0809","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1908: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0107","d0121"], 1909: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1910: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1911: ["d0205","d0220","d0307","d0322","d0406","d0421","d0507","d0522","d0607","d0622","d0708","d0724","d0809","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1912: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1122","d1207","d1222","d0107","d0121"], 1913: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1914: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1915: ["d0205","d0220","d0306","d0322","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1916: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0121"], 1917: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1918: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1919: ["d0205","d0220","d0306","d0322","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1920: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0121"], 1921: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1922: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1923: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1924: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0121"], 1925: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1926: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1927: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0909","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1928: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1929: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1930: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1931: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0607","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1932: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1933: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1934: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1935: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1936: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1937: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1938: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1939: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1940: ["d0205","d0220","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1941: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1942: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1943: ["d0205","d0219","d0306","d0321","d0406","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1944: ["d0205","d0220","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1945: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0120"], 1946: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1947: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1948: ["d0205","d0220","d0305","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1949: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1950: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1951: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0724","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1223","d0106","d0121"], 1952: ["d0205","d0220","d0305","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1953: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1954: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1955: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1956: ["d0205","d0220","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1957: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1958: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1959: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1960: ["d0205","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1961: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1962: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1963: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1964: ["d0205","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1965: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1966: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1967: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1968: ["d0205","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1969: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1970: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1971: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0924","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1972: ["d0205","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1973: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1974: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1975: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0522","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0121"], 1976: ["d0205","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1977: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1978: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1979: ["d0204","d0219","d0306","d0321","d0405","d0421","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1980: ["d0205","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1981: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1982: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0120"], 1983: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0708","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1208","d1222","d0106","d0120"], 1984: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0106","d0121"], 1985: ["d0204","d0219","d0305","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1986: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1987: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0824","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1988: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 1989: ["d0204","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1990: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 1991: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1992: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 1993: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1994: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1995: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 1996: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 1997: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1998: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 1999: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 2000: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 2001: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2002: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2003: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 2004: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 2005: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2006: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2007: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1009","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 2008: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 2009: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2010: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2011: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1123","d1207","d1222","d0106","d0120"], 2012: ["d0204","d0219","d0305","d0320","d0404","d0420","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0121"], 2013: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2014: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2015: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0622","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0106","d0120"], 2016: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0120"], 2017: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2018: ["d0204","d0219","d0305","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2019: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 2020: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0106","d0120"], 2021: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2022: ["d0204","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2023: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1024","d1108","d1122","d1207","d1222","d0105","d0120"], 2024: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2025: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2026: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2027: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2028: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2029: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2030: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2031: ["d0204","d0219","d0306","d0321","d0405","d0420","d0506","d0521","d0606","d0621","d0707","d0723","d0808","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2032: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2033: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2034: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2035: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2036: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2037: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2038: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2039: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2040: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2041: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2042: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2043: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2044: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1122","d1206","d1221","d0106","d0120"], 2045: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2046: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2047: ["d0204","d0219","d0306","d0321","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0908","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2048: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0106","d0120"], 2049: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0119"], 2050: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2051: ["d0204","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0606","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2052: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0105","d0120"], 2053: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0119"], 2054: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2055: ["d0204","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2056: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0105","d0120"], 2057: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2058: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2059: ["d0204","d0219","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2060: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2061: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2062: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2063: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2064: ["d0204","d0219","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2065: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2066: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2067: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2068: ["d0204","d0219","d0305","d0320","d0404","d0419","d0504","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2069: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2070: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2071: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2072: ["d0204","d0219","d0305","d0320","d0404","d0419","d0504","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2073: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2074: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0520","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2075: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2076: ["d0204","d0219","d0305","d0320","d0404","d0419","d0504","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2077: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2078: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0823","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2079: ["d0204","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2080: ["d0204","d0219","d0305","d0320","d0404","d0419","d0504","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2081: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0105","d0119"], 2082: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2083: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2084: ["d0204","d0219","d0304","d0319","d0404","d0419","d0504","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0906","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2085: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0104","d0119"], 2086: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0119"], 2087: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], 2088: ["d0204","d0219","d0304","d0319","d0404","d0419","d0504","d0520","d0604","d0620","d0706","d0722","d0806","d0822","d0906","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2089: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1023","d1107","d1121","d1206","d1221","d0104","d0119"], 2090: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2091: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2092: ["d0204","d0219","d0304","d0319","d0404","d0419","d0504","d0520","d0604","d0620","d0706","d0722","d0806","d0822","d0906","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2093: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0807","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0104","d0119"], 2094: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2095: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2096: ["d0204","d0218","d0304","d0319","d0404","d0419","d0504","d0520","d0604","d0620","d0706","d0722","d0806","d0822","d0906","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0105","d0120"], 2097: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0620","d0706","d0722","d0806","d0822","d0907","d0922","d1007","d1022","d1106","d1121","d1206","d1221","d0104","d0119"], 2098: ["d0203","d0218","d0305","d0320","d0404","d0419","d0505","d0520","d0605","d0621","d0706","d0722","d0807","d0822","d0907","d0922","d1008","d1023","d1107","d1122","d1206","d1221","d0105","d0119"], 2099: ["d0203","d0218","d0305","d0320","d0404","d0420","d0505","d0521","d0605","d0621","d0707","d0722","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1221","d0105","d0120"], 2100: ["d0204","d0218","d0305","d0320","d0405","d0420","d0505","d0521","d0605","d0621","d0707","d0723","d0807","d0823","d0907","d0923","d1008","d1023","d1107","d1122","d1207","d1222","d0105","d0120"], ] }() /** * 格式化日期 * * @param month 月份 * @param day 日期 * * @return 格式化后的日期 */ private func formatDay(_ month: Int, _ day: Int) -> String { return String(format: "d%02d%02d", (month+1), day) } /** * 以年月和长度构造一个日历 * * @param year 年 * @param month 月 * @param len 参数 * @param start 开始日期 * * @return 整月日历 */ private func createMonthData(_ year: Int, _ month: Int, _ len: Int, _ start: Int) -> [[String: Int]] { var monthData = [[String: Int]]() if len < 1 { return monthData } var k = start for _ in 0..<len { let dict = ["year": year, "month": month, "day": k] k += 1 monthData.append(dict) } return monthData } /** * 构造 NSDate * * @param year 年 * @param month 月 * @param day 日 * * @return NSDate */ private func date(_ year: Int, _ month: Int, _ day: Int) -> Date? { let calendar = Calendar.current var comp = DateComponents() comp.year = year comp.month = month+1 comp.day = day let date = calendar.date(from: comp) return date } /** * 构造 NSDate * * @param year 年 * @param month 月 * @param day 日 * * @return NSDate */ private func newDate(_ year: Int, _ month: Int, _ day: Int) -> Date { return date(year, month-1, day)! } /** * 获得以周为单位的节日 * * @param year 年 * @param month 月 * @param day 日 * * @return 节日 */ private func getWeekFestival(_ year: Int, _ month: Int, _ day: Int) -> String? { let date = newDate(year, month, day) let gregorian = Calendar(identifier: Calendar.Identifier.gregorian) let comps = gregorian.dateComponents([Calendar.Component.weekday], from: date) let weekDay = comps.weekday! // 这个时候要数出cWeekDay是第几个 var weekDayCount = 0 for _ in 1...day { let curDate = newDate(year, month, day) let weekComp = gregorian.dateComponents([Calendar.Component.weekday], from: curDate) if weekComp.weekday == weekDay { weekDayCount += 1 } } let key = String(format: "%02d%d%d", month, weekDayCount, weekDay) let festival = weekFestival[key] if festival != nil { return i18n(festival) } return nil } /** * 判断农历年闰月数 * * @param year 农历年 * * @return 闰月数 (月份从1开始) */ private func getLunarLeapYear(_ year: Int) -> Int { let yearData = lunarInfo[year - minYear] return yearData[0] } private func toString(_ num: Int?) -> [Any?] { var arr = [Any?]() var tempNum = num while tempNum != 0 { arr.append(String(tempNum! & 1)) tempNum = tempNum! >> 1 } return arr.reversed() } /** * 获取农历年份一年的每月的天数及一年的总天数 * * @param year 农历年 * * @return 总天数 */ private func getLunarYearDays(_ year: Int) -> [String: Any?] { let yearData = lunarInfo[year - minYear] let leapMonth = yearData[safe: 0] // 闰月 let monthData = yearData[safe: 3] var monthDataArr = toString(monthData) // 还原数据至16位,少于16位的在前面插入0(二进制存储时前面的0被忽略) for _ in 0..<(16-monthDataArr.count) { monthDataArr.insert(0, at: 0) } let len = (leapMonth != 0) ? 13 : 12 // 该年有几个月 var yearDays = 0 var monthDays = [Int]() for i in 0..<len { if let num = (monthDataArr[safe: i] as? String), num == "0" { yearDays += 29 monthDays.append(29) }else { yearDays += 30 monthDays.append(30) } } return [ "yearDays": yearDays, "monthDays": monthDays ] } /** * 通过间隔天数查找农历日期 * * @param year 农历年 * @param between 间隔天数 * * @return 农历日期 */ private func getLunarDateByBetween(_ year: Int, _ between: Int) -> [Int] { let lunarYearDays = getLunarYearDays(year) let end = between > 0 ? between : (lunarYearDays["yearDays"] as! Int) - abs(between) let monthDays = lunarYearDays["monthDays"] as! [Int] var tempDays = 0 var month = 0 for i in 0..<monthDays.count { let monthDaysI = monthDays[safe: i] tempDays += monthDaysI! if tempDays > end { month = i tempDays = tempDays - monthDaysI! break } } return [year, month, (end - tempDays + 1)] } /** * 两个公历日期之间的天数 * * @param year 年 * @param month 月 * @param day 日 * @param year1 年2 * @param month1 月2 * @param day1 日2 * * @return 间隔天数 */ private func getDaysBetweenSolar(_ year: Int, _ month: Int, _ day: Int, _ year1: Int, _ month1: Int, _ day1: Int) -> Int { var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = timeZone var comp = DateComponents() comp.year = year; comp.month = month + 1; comp.day = day let date = calendar.date(from: comp)! comp.year = year1; comp.month = month1 + 1; comp.day = day1 let date1 = calendar.date(from: comp)! return Int((date1.timeIntervalSince1970 - date.timeIntervalSince1970) / 86400) } /** * 根据距离正月初一的天数计算农历日期 * * @param year 公历年 * @param month 月 * @param day 日 * * @return 农历日期 */ private func getLunarByBetween(_ year: Int, _ month: Int, _ day: Int) -> [Int] { let yearData = lunarInfo[safe: (year - minYear)] let zenMonth = yearData?[safe: 1] let zenDay = yearData?[safe: 2] let between = getDaysBetweenSolar(year, zenMonth! - 1, zenDay!, year, month, day) if between == 0 { //正月初一 return [year, 0, 1] }else { let lunarYear = between > 0 ? year : year - 1 return getLunarDateByBetween(lunarYear, between) } } /** * 根据 NSDate 获得天 * * @param date date * * @return 天 */ private func getDay(_ date: Date) -> Int { let gregorian = Calendar(identifier: Calendar.Identifier.gregorian) let components = gregorian.dateComponents([Calendar.Component.weekday], from: date) return (components.weekday! - 1) } /** * 获取公历年一年的二十四节气 * * @param year 年 * * @return 日期: 节气名 */ private func getYearTerm(_ year: Int) -> [String: String] { var res = [String: String]() let keys = solarTerms[year] let values = lunarCalendarData["solarTerm"]! if let keys = keys { for (index, value) in keys.enumerated() { res[value] = i18n(values[index]) } } return res } /** * 获得生肖 * * @param year 年 * * @return 生肖 */ private func getYearZodiac(_ year: Int) -> String? { let num = year - 1890 + 25 // 参考干支纪年的计算,生肖对应地支 return i18n((lunarCalendarData["zodiac"]?[num % 12])) } /** * 计算天干地支 * * @param num 60进制中的位置(把60个天干地支,当成一个60进制的数) * * @return 天干地支 */ private func cyclical(_ num: Double) -> String { let tiangan = i18n(lunarCalendarData["heavenlyStems"]![Int(num.truncatingRemainder(dividingBy: 10))]) let dizhi = i18n(lunarCalendarData["earthlyBranches"]![Int(num.truncatingRemainder(dividingBy: 12))]) return String(format: "%@%@", tiangan, dizhi) } /** * 获取干支纪年 * * @param year 干支所在年 * @param offset 偏移量,默认为0,便于查询一个年跨两个干支纪年(以立春为分界线) * * @return 干支纪年 */ private func getLunarYearName(_ year: Int, _ offset: Int) -> String { // 1890年1月小寒(小寒一般是1月5或6日)以前为己丑年,在60进制中排25 let temp = year + offset - 1865/* -1890+25 */ return cyclical(Double(temp)) } /** * 判断公历年是否是闰年 * * @param year 公历年 * * @return 是否是闰年 */ private func isLeapYear(_ year: Int) -> Bool { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) } /** * 获取公历月份的天数 * * @param year 公历年 * @param month 公历月 * * @return 该月天数 */ private func getSolarMonthDays(_ year: Int, _ month: Int) -> Int { if month == 1 { // 二月 闰月处理 return isLeapYear(year) ? 29 : 28 }else { // 普通月份查表 return solarDaysOfMonth[month] } } /** * 统一日期输入参数(输入月份从1开始,内部月份统一从0开始) * * @param year 年 * @param month 月 * @param day 日 * * @return 格式化后的日期 */ private func formatDate(_ year: Int, _ month: Int, _ day: Int) -> [String: Any] { let now = Date() var gregorian = Calendar(identifier: Calendar.Identifier.gregorian) gregorian.timeZone = timeZone let components = gregorian.dateComponents([.year, .month, .day], from: now) let _year = year let _month = month - 1 let _day = day > 0 ? day : components.day! if (year < minYear) || (year > maxYear) { return ["error": 100, "msg": errorCode[100]!] } return [ "year": _year, "month": _month, "day": _day ] } /** * 判断是否处于农历新年 * * @param year 阳历年 * @param month 阳历月 * @param day 阳历日 * * @return YES 表示处于农历新年 */ private func isNewLunarYear(_ year: Int, _ month: Int, _ day: Int) -> Bool { let springFestivalDate = springFestival[year - minYear] let springFestivalMonth = springFestivalDate[0] let springFestivalDay = springFestivalDate[1] if month > springFestivalMonth { return true }else if month == springFestivalMonth { return (day >= springFestivalDay) }else { return false } } /** * 公历转换成农历 * * @param _year 公历年 * @param _month 公历月 * @param _day 公历日 * * @return 农历年月日 */ func solarToLunar(_ _year: Int, _ _month: Int, _ _day: Int) -> [String: Any?] { var inputDate = formatDate(_year, _month, _day) if inputDate["error"] != nil { return inputDate } let year = inputDate["year"]! as! Int let month = inputDate["month"]! as! Int let day = inputDate["day"]! as! Int memoryCache.current = year // 二十四节气 var termList = [String: Any]() let termListCache = memoryCache.get(key: "termList") if termListCache != nil { termList = termListCache as! [String : Any] }else { termList = getYearTerm(year) memoryCache.setKey("termList", Value: termList) } // 干支所在年份 let GanZhiYear = isNewLunarYear(_year, _month, _day) ? (year + 1) : (year) let lunarDate = getLunarByBetween(year, month, day) let lunarDate0 = Int(lunarDate[0]) let lunarDate1 = Int(lunarDate[1]) let lunarDate2 = Int(lunarDate[2]) let lunarLeapMonth = getLunarLeapYear(lunarDate0) var lunarMonthName = String() if lunarLeapMonth > 0 && lunarLeapMonth == lunarDate1 { let mStr = i18n((lunarCalendarData["monthCn"]?[lunarDate1 - 1])); lunarMonthName = String(format: "闰%@月", mStr) } else if(lunarLeapMonth > 0 && lunarDate1 > lunarLeapMonth) { let mStr = i18n((lunarCalendarData["monthCn"]?[lunarDate1 - 1])); lunarMonthName = String(format:"%@月", mStr) } else { let mStr = i18n((lunarCalendarData["monthCn"]?[lunarDate1])); lunarMonthName = String(format:"%@月", mStr) } // 农历节日判断 let lunarFtv: String? let lunarMonthDays = getLunarYearDays(lunarDate0)["monthDays"]! as! [Int] // 除夕 if (lunarDate1 == lunarMonthDays.count - 1) && (lunarDate2 == (lunarMonthDays[lunarMonthDays.count - 1] as Int)) { lunarFtv = lunarFestival["d0100"]; } else if (lunarLeapMonth > 0 && lunarDate1 >= lunarLeapMonth) { let date = formatDay(lunarDate1 - 1, lunarDate2) lunarFtv = lunarFestival[date]; } else { let date = formatDay(lunarDate1, lunarDate2) lunarFtv = lunarFestival[date] } // 放假安排:0无特殊安排,1工作,2放假 let yearKey = String(format: "y%d", year) let dayKey = formatDay(month, day) var workTime = 0 if let hasData = worktime[yearKey]?[dayKey] { workTime = hasData } return [ "lunarDay": lunarDate[2], "lunarMonthName": lunarMonthName, "lunarDayName": lunarCalendarData["dateCn"]![lunarDate2 - 1], "solarFestival": i18n(solarFestival[formatDay(month, day)]), "lunarFestival": i18n(lunarFtv), "weekFestival": getWeekFestival(year, month + 1, day), "worktime": workTime, "GanZhiYear": getLunarYearName(GanZhiYear, 0), "zodiac": getYearZodiac(GanZhiYear), "term": termList[formatDay(month, day)] ] } /** * 某月公历 * * @param _year 公历年 * @param _month 公历月 * * @return 公历 */ private func solarCalendar(_ _year: Int, _ _month: Int) -> [String: Any] { let inputDate = formatDate(_year, _month, -1) if inputDate["eror"] != nil { return inputDate } let year = inputDate["year"]! as! Int let month = inputDate["month"]! as! Int let firstDate = date(year, month, 1) var res: [String: Any] = [ "firstDay": getDay(firstDate!), // 该月1号星期几 "monthDays": getSolarMonthDays(year, month), // 该月天数 "monthData": [] ] res["monthData"] = createMonthData(year, month + 1, (res["monthDays"] as! Int), 1) var firstDay = res["firstDay"] as! Int let identifier = NSLocale.current.identifier.lowercased() if identifier.hasSuffix("japanese") || identifier.hasSuffix("buddhist") { // 处理日本日历和佛教日历 firstDay += 1 } let moveDays = (firstDay >= weekStart) ? firstDay : (firstDay + 7) let preFillDays = moveDays - weekStart // 前补齐 let preYear = (month - 1 < 0) ? (year - 1) : (year) let preMonth = (month - 1 < 0) ? (11) : (month - 1) let preMonthDays = getSolarMonthDays(preYear, preMonth) let preMonthData = createMonthData(preYear, preMonth + 1, preFillDays, preMonthDays - preFillDays + 1) var tempResMonthData: NSArray = res["monthData"] as! [Any] as NSArray res["monthData"] = (preMonthData as NSArray).addingObjects(from: tempResMonthData as! [Any]) // 后补齐 let length = (res["monthData"] as! [Any]).count let fillLen = 7 * 6 - length // [matrix 7 * 6] if fillLen != 0 { let nextYear = (month + 1 > 11) ? (year + 1) : (year) let nextMonth = (month + 1 > 11) ? (0) : (month + 1) let nextMonthData = createMonthData(nextYear, nextMonth + 1, fillLen, 1) tempResMonthData = (res["monthData"] as! [[String: Int]]) as NSArray res["monthData"] = tempResMonthData.addingObjects(from: nextMonthData) } return res } func calendar(_ year: Int, _ month: Int) -> [String: Any] { var inputDate = formatDate(year, month, -1) if inputDate["error"] != nil { return inputDate } let year = inputDate["year"]! as! Int let month = inputDate["month"]! as! Int var calendarData = solarCalendar(year, month + 1) var monthData = calendarData["monthData"] as! [[String: Int]] for i in 0..<monthData.count { var cData = monthData[i] let lunarData = solarToLunar(Int(cData["year"]!), Int(cData["month"]!), Int(cData["day"]!)) var array = calendarData["monthData"] as! [[String: Any]] for (key, value) in lunarData { array[i][key] = value } calendarData["monthData"] = array } return calendarData } /// 计算农历日期离正月初一有多少天 /// /// - Parameters: /// - year: 农历年 /// - month: 月(0-12,有闰月) /// - day: 日 /// - Returns: 天数 public func getDaysBetweenZheng(_ year: Int, _ month: Int, _ day: Int) -> Int { let lunarYearDays = getLunarYearDays(year) let monthDays = lunarYearDays["monthDays"] as! [Int] var days = 0 for i in 0..<monthDays.count { if i < month { days += monthDays[i] as Int }else { break } } return (days + day - 1) } /// 将农历转换为公历 /// /// - Parameters: /// - _year: 农历年 /// - _month: 月(1-13,有闰月) /// - _day: 日 /// - Returns: 公历数据 public func lunarToSolar(_ _year: Int, _ _month: Int, _ _day: Int) -> [String: Any?] { var inputDate = formatDate(_year, _month, _day) if inputDate["error"] != nil { return inputDate } let year = inputDate["year"]! as! Int let month = inputDate["month"]! as! Int let day = inputDate["day"]! as! Int let between = getDaysBetweenZheng(year, month, day) // 离正月初一的天数 let yearData = lunarInfo[year - minYear] let zenMonth = yearData[1] let zenDay = yearData[2] let timeInterval = date(year, zenMonth - 1, zenDay)!.timeIntervalSince1970 + Double(between) * 86400.0 let offDate = Date(timeIntervalSince1970: timeInterval as TimeInterval) let gregorian = Calendar(identifier: Calendar.Identifier.gregorian) let components = gregorian.dateComponents([.year, .month, .day], from: offDate) return [ "year": components.year, "month": components.month, "day": components.day, ] } }
mit
5e974ffb5aaba535afb46d30ccd0e8a8
68.210151
212
0.541886
2.420825
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/SHRoute/Base/SNRoutePathSchemeAnalysisService.swift
1
1822
// // SNRoutePathSchemeAnalysisService.swift // StudyNote // // Created by wuyp on 2020/3/16. // Copyright © 2020 Raymond. All rights reserved. // import UIKit class SNRoutePathSchemeAnalysisService: NSObject { } // MARK: - SNRouteAnalysisRouteServiceProtocol extension SNRoutePathSchemeAnalysisService: SNRouteAnalysisRouteServiceProtocol { func getRouteResult(url: URL) -> Result<SNRouteEntity, SNRouteError> { return .success(getRouteEntity(url: url)) } } // MARK: - Private Method extension SNRoutePathSchemeAnalysisService { @objc private dynamic func getRouteEntity(url: URL) -> SNRouteEntity { let entity = SNRouteEntity() entity.href = url.absoluteString let routePath = getRouteModulePath(path: url.path.uppercased()) entity.module = routePath.0 entity.page = routePath.1 let paramsArr = url.query?.componentsSeparatedByString("&") ?? [] for item in paramsArr { let temp = item.componentsSeparatedByString("=") if temp.count == 2 { entity.params[temp[0]] = temp[1] } } return entity } /// 获取 module和path private func getRouteModulePath(path: String) -> (String, String) { // 1.删除开始/ var actualPath = path.uppercased() if path.hasPrefix("/") { actualPath = path[1..<path.count] } //2.如果不是module-page格式 guard actualPath.contains("/") else { return ("", actualPath) } //3.是正常的module-page格式 let arr = actualPath.componentsSeparatedByString("/") if arr.count >= 2 { return (arr[0], actualPath) } return ("", actualPath) } }
apache-2.0
a9c82cfc9daf45b2da3ab497460a2945
27.301587
81
0.600112
4.296386
false
false
false
false
nekrich/Localize-Swift
genstrings.swift
1
4629
#!/usr/bin/swift import Foundation class GenStrings { var str = "Hello, playground" let fileManager = FileManager.default let acceptedFileExtensions = ["swift"] let excludedFolderNames = ["Carthage"] let excludedFileNames = ["genstrings.swift"] var regularExpresions = [String:NSRegularExpression]() let localizedRegex = "(?<=\")([^\"]*)(?=\".(localized|localizedFormat))|(?<=(Localized|NSLocalizedString)\\(\")([^\"]*?)(?=\")" enum GenstringsError: Error { case Error } // Performs the genstrings functionality func perform() { let rootPath = URL(fileURLWithPath:fileManager.currentDirectoryPath) let allFiles = fetchFilesInFolder(rootPath: rootPath) // We use a set to avoid duplicates var localizableStrings = Set<String>() for filePath in allFiles { let stringsInFile = localizableStringsInFile(filePath: filePath) localizableStrings = localizableStrings.union(stringsInFile) } // We sort the strings let sortedStrings = localizableStrings.sorted(by: { $0 < $1 }) var processedStrings = String() for string in sortedStrings { processedStrings.append("\"\(string)\" = \"\(string)\"; \n") } print(processedStrings) } // Applies regex to a file at filePath. func localizableStringsInFile(filePath: URL) -> Set<String> { do { let fileContentsData = try Data(contentsOf: filePath) guard let fileContentsString = NSString(data: fileContentsData, encoding: String.Encoding.utf8.rawValue) else { return Set<String>() } let localizedStringsArray = try regexMatches(pattern: localizedRegex, string: fileContentsString as String).map({fileContentsString.substring(with: $0.range)}) return Set(localizedStringsArray) } catch {} return Set<String>() } //MARK: Regex func regexWithPattern(pattern: String) throws -> NSRegularExpression { var safeRegex = regularExpresions if let regex = safeRegex[pattern] { return regex } else { do { let currentPattern: NSRegularExpression currentPattern = try NSRegularExpression(pattern: pattern, options:NSRegularExpression.Options.caseInsensitive) safeRegex.updateValue(currentPattern, forKey: pattern) regularExpresions = safeRegex return currentPattern } catch { throw GenstringsError.Error } } } func regexMatches(pattern: String, string: String) throws -> [NSTextCheckingResult] { do { let internalString = string let currentPattern = try regexWithPattern(pattern: pattern) // NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range. let nsString = internalString as NSString let stringRange = NSMakeRange(0, nsString.length) let matches = currentPattern.matches(in: internalString, options: [], range: stringRange) return matches } catch { throw GenstringsError.Error } } //MARK: File manager func fetchFilesInFolder(rootPath: URL) -> [URL] { var files = [URL]() do { let directoryContents = try fileManager.contentsOfDirectory(at: rootPath as URL, includingPropertiesForKeys: [], options: .skipsHiddenFiles) for urlPath in directoryContents { let stringPath = urlPath.path let lastPathComponent = urlPath.lastPathComponent let pathExtension = urlPath.pathExtension var isDir : ObjCBool = false if fileManager.fileExists(atPath: stringPath, isDirectory:&isDir) { if isDir.boolValue { if !excludedFolderNames.contains(lastPathComponent) { let dirFiles = fetchFilesInFolder(rootPath: urlPath) files.append(contentsOf: dirFiles) } } else { if acceptedFileExtensions.contains(pathExtension) && !excludedFileNames.contains(lastPathComponent) { files.append(urlPath) } } } } } catch {} return files } } let genStrings = GenStrings() genStrings.perform()
mit
6f95fdbf1bcb2a6d92f283605426beeb
37.907563
171
0.598833
5.302405
false
false
false
false
machelix/DSFacebookImagePicker
Source/Photo.swift
2
2252
// // Photo.swift // DSFacebookImagePicker // // Created by Home on 2014-10-14. // Copyright (c) 2014 Sanche. All rights reserved. // import UIKit class Photo { let photoID : String? let ownerName : String? let fullImageURL : NSURL? var thumbnailURL : NSURL? var thumbnailData : UIImage? var imageLoadFailed : Bool var isCached : Bool init(json:NSDictionary, fullImageSize:Int=Int.max) { let fromDict = json["from"] as? [String : String] if let newID = json["id"] as? String{ photoID = newID } else { photoID = nil } if let newName = fromDict?["name"]{ ownerName = newName } else { ownerName = nil } imageLoadFailed = false isCached = false if let imageArray = json["images"] as? NSArray { thumbnailURL = FacebookNetworking.findBestImageURL(imageArray, minImageSize:Int.min) fullImageURL = FacebookNetworking.findBestImageURL(imageArray, minImageSize:fullImageSize) } else { thumbnailURL = nil fullImageURL = nil } } func loadThumbnail(){ imageLoadFailed = false var desiredURL = self.thumbnailURL if desiredURL == nil{ desiredURL = self.fullImageURL if desiredURL == nil{ imageLoadFailed = true return } } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { var readError: NSError? let data = NSData(contentsOfURL:desiredURL!, options: nil, error: &readError) if let error = readError{ self.imageLoadFailed = true } else if data != nil { self.thumbnailData = UIImage(data:data!) } }) } func attemptImageCache(){ if !isCached && thumbnailData != nil{ let tempDirectory = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) if photoID != nil && tempDirectory != nil{ let cacheURL = tempDirectory!.URLByAppendingPathComponent(photoID!) let success = UIImagePNGRepresentation(thumbnailData).writeToURL(cacheURL, atomically: true) if(success){ thumbnailURL = cacheURL isCached = true } } } imageLoadFailed = false thumbnailData = nil } }
mit
038d0c8426965945da4be939c7b7033c
24.590909
100
0.630551
4.540323
false
false
false
false
paulz/PerspectiveTransform
Example/PerspectiveTransform/Visual.playground/Pages/Animate.xcplaygroundpage/Contents.swift
1
1916
//: Animation to show tranformation of subview //: open Playground timeline to see it import UIKit import PerspectiveTransform import PlaygroundSupport import Nimble func viewWithFrame(origin: CGPoint = CGPoint.zero, size: CGSize) -> UIView { return UIView(frame: CGRect(origin: origin, size: size)) } let page = PlaygroundPage.current let containerView = viewWithFrame(size: CGSize(width: 300, height: 600)) containerView.backgroundColor = #colorLiteral(red: 0.8374180198, green: 0.8374378085, blue: 0.8374271393, alpha: 1) page.liveView = containerView let startView = viewWithFrame(size: CGSize(width: 150, height: 120)) startView.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 0.501389954) let destinationView = viewWithFrame(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 200, height: 200)) destinationView.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 0.5081000767) let view = viewWithFrame(size: CGSize(width: 150, height: 120)) view.backgroundColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 0.5061709164) view.resetAnchorPoint() containerView.addSubview(startView) containerView.addSubview(destinationView) containerView.addSubview(view) let start = Perspective(view.frame) let transform = start.projectiveTransform(destination: Perspective(destinationView.frame)) print(transform) UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: { view.layer.transform = transform }, completion: nil) transform.m11 == destinationView.frame.size.width / startView.frame.size.width expect(transform.m22) ≈ destinationView.frame.size.height / startView.frame.size.height transform.m33 == 1 transform.m41 == 100 transform.m42 == 100 transform.m43 == 0
mit
d22fe3a3c0cf7f1c7f510cecc9abbd3d
36.529412
128
0.754441
3.57757
false
false
false
false
damoguyan8844/actor-platform
actor-apps/app-ios/ActorApp/AppDelegate.swift
3
12960
// // Copyright (C) 2014-2015 Actor LLC. <https://actor.im> // import Foundation @objc class AppDelegate : UIResponder, UIApplicationDelegate { var window : UIWindow? private var binder = Binder() private var syncTask: UIBackgroundTaskIdentifier? private var completionHandler: ((UIBackgroundFetchResult) -> Void)? private let badgeView = UIImageView() private var badgeCount = 0 private var isBadgeVisible = false func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { createActor() // Apply crash logging // WARRING: Disabled because Mint doesn't support bitcode // if AppConfig.mint != nil { // Mint.sharedInstance().disableNetworkMonitoring() // Mint.sharedInstance().initAndStartSession(AppConfig.mint!) // } // Register hockey app if AppConfig.hockeyapp != nil { BITHockeyManager.sharedHockeyManager().configureWithIdentifier(AppConfig.hockeyapp!) BITHockeyManager.sharedHockeyManager().disableCrashManager = true BITHockeyManager.sharedHockeyManager().updateManager.checkForUpdateOnLaunch = true BITHockeyManager.sharedHockeyManager().startManager() BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation() } // Register notifications // Register always even when not enabled in build for local notifications if #available(iOS 8.0, *) { let types: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes([.Alert, .Badge, .Sound]) } // Apply styles MainAppTheme.applyAppearance(application) // Bind Messenger LifeCycle binder.bind(Actor.getAppState().getIsSyncing(), closure: { (value: JavaLangBoolean?) -> () in if value!.booleanValue() { if self.syncTask == nil { self.syncTask = application.beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in }) } } else { if self.syncTask != nil { application.endBackgroundTask(self.syncTask!) self.syncTask = nil } if self.completionHandler != nil { self.completionHandler!(UIBackgroundFetchResult.NewData) self.completionHandler = nil } } }) // Creating main window window = UIWindow(frame: UIScreen.mainScreen().bounds); window?.backgroundColor = UIColor.whiteColor() if (Actor.isLoggedIn()) { onLoggedIn(false) } else { // Create root layout for login let phoneController = AuthPhoneViewController() let loginNavigation = AANavigationController(rootViewController: phoneController) loginNavigation.navigationBar.tintColor = MainAppTheme.navigation.barColor loginNavigation.makeBarTransparent() window?.rootViewController = loginNavigation } window?.makeKeyAndVisible(); badgeView.image = Imaging.roundedImage(UIColor.RGB(0xfe0000), size: CGSizeMake(16, 16), radius: 8) // badgeView.frame = CGRectMake(16, 22, 32, 16) badgeView.alpha = 0 let badgeText = UILabel() badgeText.text = "0" badgeText.textColor = UIColor.whiteColor() // badgeText.frame = CGRectMake(0, 0, 32, 16) badgeText.font = UIFont.systemFontOfSize(12) badgeText.textAlignment = NSTextAlignment.Center badgeView.addSubview(badgeText) window?.addSubview(badgeView) // Bind badge counter binder.bind(Actor.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in self.badgeCount = Int((value!).integerValue) application.applicationIconBadgeNumber = self.badgeCount badgeText.text = "\(self.badgeCount)" if (self.isBadgeVisible && self.badgeCount > 0) { self.badgeView.showView() } else if (self.badgeCount == 0) { self.badgeView.hideView() } badgeText.frame = CGRectMake(0, 0, 128, 16) badgeText.sizeToFit() if badgeText.frame.width < 8 { self.badgeView.frame = CGRectMake(16, 22, 16, 16) } else { self.badgeView.frame = CGRectMake(16, 22, badgeText.frame.width + 8, 16) } badgeText.frame = self.badgeView.bounds }) return true; } func onLoggedIn(isAfterLogin: Bool) { // Create root layout for app Actor.onAppVisible() var rootController : UIViewController? = nil if (isIPad) { let splitController = MainSplitViewController() splitController.viewControllers = [MainTabViewController(isAfterLogin: isAfterLogin), NoSelectionViewController()] rootController = splitController } else { let tabController = MainTabViewController(isAfterLogin: isAfterLogin) binder.bind(Actor.getAppState().getIsAppLoaded(), valueModel2: Actor.getAppState().getIsAppEmpty()) { (loaded: JavaLangBoolean?, empty: JavaLangBoolean?) -> () in if (empty!.booleanValue()) { if (loaded!.booleanValue()) { tabController.showAppIsEmptyPlaceholder() } else { tabController.showAppIsSyncingPlaceholder() } } else { tabController.hidePlaceholders() } } rootController = tabController } window?.rootViewController = rootController! } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { print("open url: \(url)") if (url.scheme == "actor") { if (url.host == "invite") { if (Actor.isLoggedIn()) { let token = url.query?.componentsSeparatedByString("=")[1] if token != nil { UIAlertView.showWithTitle(nil, message: localized("GroupJoinMessage"), cancelButtonTitle: localized("AlertNo"), otherButtonTitles: [localized("GroupJoinAction")], tapBlock: { (view, index) -> Void in if (index == view.firstOtherButtonIndex) { self.execute(Actor.joinGroupViaLinkCommandWithUrl(token), successBlock: { (val) -> Void in let groupId = val as! JavaLangInteger self.openChat(ACPeer.groupWithInt(groupId.intValue)) }, failureBlock: { (val) -> Void in if let res = val as? ACRpcException { if res.getTag() == "USER_ALREADY_INVITED" { UIAlertView.showWithTitle(nil, message: localized("ErrorAlreadyJoined"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) return } } UIAlertView.showWithTitle(nil, message: localized("ErrorUnableToJoin"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) }) } }) } } return true } } return false } func applicationWillEnterForeground(application: UIApplication) { createActor() Actor.onAppVisible(); // Hack for resync phone book Actor.onPhoneBookChanged() } func applicationDidEnterBackground(application: UIApplication) { createActor() Actor.onAppHidden(); if Actor.isLoggedIn() { var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid }) // Wait for 40 secs before app shutdown dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid } } } // MARK: - // MARK: Notifications func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenString = "\(deviceToken)".stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "") if AppConfig.pushId != nil { Actor.registerApplePushWithApnsId(jint(AppConfig.pushId!), withToken: tokenString) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } func execute(command: ACCommand) { execute(command, successBlock: nil, failureBlock: nil) } func execute(command: ACCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { let window = UIApplication.sharedApplication().windows[1] let hud = MBProgressHUD(window: window) hud.mode = MBProgressHUDMode.Indeterminate hud.removeFromSuperViewOnHide = true window.addSubview(hud) window.bringSubviewToFront(hud) hud.show(true) command.startWithCallback(CocoaCallback(result: { (val:Any?) -> () in dispatchOnUi { hud.hide(true) successBlock?(val: val) } }, error: { (val) -> () in dispatchOnUi { hud.hide(true) failureBlock?(val: val) } })) } func openChat(peer: ACPeer) { for i in UIApplication.sharedApplication().windows { if let tab = i.rootViewController as? MainTabViewController { let controller = tab.viewControllers![tab.selectedIndex] as! AANavigationController let destController = ConversationViewController(peer: peer) destController.hidesBottomBarWhenPushed = true controller.pushViewController(destController, animated: true) return } else if let split = i.rootViewController as? MainSplitViewController { split.navigateDetail(ConversationViewController(peer: peer)) return } } } func showBadge() { isBadgeVisible = true if badgeCount > 0 { self.badgeView.showView() } } func hideBadge() { isBadgeVisible = false self.badgeView.hideView() } }
mit
9fb8d653b87dc9929238dea87fbd83d4
41.081169
223
0.574151
6.039143
false
false
false
false
tombooth/Bookmarks
Sources/Bookmark.swift
1
843
import Foundation func extractBookmarksFrom(dict: NSDictionary) -> [Bookmark] { if let children: [NSDictionary] = dict["Children"] as! [NSDictionary]? { return [Bookmark](children.map(extractBookmarksFrom).flatten()) } else if let url: String = dict["URLString"] as! String? { let uriDictionary = (dict["URIDictionary"] as! NSDictionary?)! let title = (uriDictionary["title"] as! String?)! return [Bookmark(title: title, url: url)] } else { return [Bookmark]() } } public struct Bookmark { public let title: String public let url: String static public func readFrom(path: String) -> [Bookmark]? { if let plist = NSDictionary(contentsOfFile: path) { return extractBookmarksFrom(dict: plist) } else { return nil } } }
mit
e0c92bfbcf91cf81acd7ee9e8a28f621
27.1
76
0.620403
4.30102
false
false
false
false
mrgerych/Cuckoo
Generator/Source/CuckooGeneratorFramework/Generator.swift
1
17826
// // Generator.swift // CuckooGenerator // // Created by Tadeas Kriz on 13/01/16. // Copyright © 2016 Brightify. All rights reserved. // public struct Generator { private let declarations: [Token] private let code = CodeBuilder() public init(file: FileRepresentation) { declarations = file.declarations } public func generate() -> String { code.clear() declarations.forEach { generate(for: $0, withOuterAccessibility: .Internal, fromProtocolDefinition: false) } return code.code } private func generate(for token: Token, withOuterAccessibility outerAccessibility: Accessibility, fromProtocolDefinition: Bool) { switch token { case let classToken as ClassDeclaration: generateClass(for: classToken, fromProtocolDefinition: false) generateNoImplStubClass(for: classToken) case let protocolToken as ProtocolDeclaration: generateClass(for: protocolToken, fromProtocolDefinition: true) generateNoImplStubClass(for: protocolToken) case let property as InstanceVariable: generateProperty(for: property, withOuterAccessibility: outerAccessibility) case let method as Method: generateMethod(for: method, withOuterAccessibility: outerAccessibility, fromProtocolDefinition: fromProtocolDefinition) default: print("\(token)\n") break } } private func generateClass(for token: ContainerToken, fromProtocolDefinition: Bool) { guard token.accessibility.isAccessible else { return } code += "" code += "\(token.accessibility.sourceName)class \(mockClassName(of: token.name)): \(token.name), Cuckoo.Mock {" code.nest { code += "\(token.accessibility.sourceName)typealias MocksType = \(token.name)" code += "\(token.accessibility.sourceName)typealias Stubbing = \(stubbingProxyName(of: token.name))" code += "\(token.accessibility.sourceName)typealias Verification = \(verificationProxyName(of: token.name))" code += "\(token.accessibility.sourceName)let cuckoo_manager = Cuckoo.MockManager()" code += "" code += "private var observed: \(token.name)?" code += "" code += "\(token.accessibility.sourceName)func spy(on victim: \(token.name)) -> Self {" code.nest { code += "observed = victim" code += "return self" } code += "}" token.children.forEach { generate(for: $0, withOuterAccessibility: token.accessibility, fromProtocolDefinition: fromProtocolDefinition) } code += "" generateStubbing(for: token) code += "" generateVerification(for: token) } code += "}" } private func minAccessibility(_ val1: Accessibility, _ val2: Accessibility) -> Accessibility { if val1 == .Open || val2 == .Open { return .Open } if val1 == .Public || val2 == .Public { return .Public } if val1 == .Internal || val2 == .Internal { return .Internal } return .Private } private func generateProperty(for token: InstanceVariable, withOuterAccessibility outerAccessibility: Accessibility) { guard token.accessibility.isAccessible else { return } let accessibility = minAccessibility(token.accessibility, outerAccessibility) code += "" code += "\(accessibility.sourceName)\(token.overriding ? "override " : "")var \(token.name): \(token.type) {" code.nest { code += "get {" code.nest("return cuckoo_manager.getter(\"\(token.name)\", original: observed.map { o in return { () -> \(token.type) in o.\(token.name) } })") code += "}" if token.readOnly == false { code += "set {" code.nest("cuckoo_manager.setter(\"\(token.name)\", value: newValue, original: observed != nil ? { self.observed?.\(token.name) = $0 } : nil)") code += "}" } } code += "}" } private func generateMethod(for token: Method, withOuterAccessibility outerAccessibility: Accessibility, fromProtocolDefinition: Bool) { guard token.accessibility.isAccessible else { return } guard (!token.isInit && !token.isDeinit) || fromProtocolDefinition else { return } let override = token is ClassMethod ? "override " : "" let parametersSignature = token.parameters.enumerated().map { "\($1.labelAndName): \($1.type)" }.joined(separator: ", ") let parametersSignatureWithoutNames = token.parameters.map { "\($0.name): \($0.type)" }.joined(separator: ", ") var managerCall: String let tryIfThrowing: String if token.isThrowing { managerCall = "try cuckoo_manager.callThrows(\"\(token.fullyQualifiedName)\"" tryIfThrowing = "try " } else { managerCall = "cuckoo_manager.call(\"\(token.fullyQualifiedName)\"" tryIfThrowing = "" } managerCall += ", parameters: (\(token.parameters.map { $0.name }.joined(separator: ", ")))" let methodCall = token.parameters.enumerated().map { if let label = $1.label { return "\(label): \($1.name)" } else { return $1.name } }.joined(separator: ", ") if let protocolMethod = token as? ProtocolMethod { managerCall += ", original: observed.map { o in return { (\(parametersSignatureWithoutNames))\(token.returnSignature) in \(tryIfThrowing)o.\(token.rawName)" + (protocolMethod.isOptional ? "?" : "") + "(\(methodCall)) } })" } else { managerCall += ", original: observed.map { o in return { (\(parametersSignatureWithoutNames))\(token.returnSignature) in \(tryIfThrowing)o.\(token.rawName)(\(methodCall)) } })" } let accessibility = minAccessibility(token.accessibility, outerAccessibility) code += "" code += "\(accessibility.sourceName)\(override)\(token.isInit || token.isDeinit ? (fromProtocolDefinition ? "required " : "") : "func " )\(token.rawName)(\(parametersSignature))\(token.returnSignature) {" if !token.isInit && !token.isDeinit { code.nest("return \(managerCall)") } code += "}" } private func generateStubbing(for token: Token) { switch token { case let containerToken as ContainerToken: generateStubbingClass(for: containerToken) case let property as InstanceVariable: generateStubbingProperty(for: property) case let method as Method: generateStubbingMethod(for: method) default: break } } private func generateStubbingClass(for token: ContainerToken) { guard token.accessibility.isAccessible else { return } code += "\(token.accessibility.sourceName)struct \(stubbingProxyName(of: token.name)): Cuckoo.StubbingProxy {" code.nest { code += "private let cuckoo_manager: Cuckoo.MockManager" code += "" code += "\(token.accessibility.sourceName)init(cuckoo_manager: Cuckoo.MockManager) {" code.nest("self.cuckoo_manager = cuckoo_manager") code += "}" token.children.forEach { generateStubbing(for: $0) } } code += "}" } private func generateStubbingProperty(for token: InstanceVariable) { guard token.accessibility.isAccessible else { return } let propertyType = token.readOnly ? "Cuckoo.ToBeStubbedReadOnlyProperty" : "Cuckoo.ToBeStubbedProperty" code += "" code += "var \(token.name): \(propertyType)<\(genericSafeType(from: token.type))> {" code.nest("return \(propertyType)(cuckoo_manager: cuckoo_manager, name: \"\(token.name)\")") code += "}" } private func generateStubbingMethod(for token: Method) { guard token.accessibility.isAccessible else { return } guard !token.isInit && !token.isDeinit else { return } let stubFunction: String if token.isThrowing { if token.returnType == "Void" { stubFunction = "Cuckoo.StubNoReturnThrowingFunction" } else { stubFunction = "Cuckoo.StubThrowingFunction" } } else { if token.returnType == "Void" { stubFunction = "Cuckoo.StubNoReturnFunction" } else { stubFunction = "Cuckoo.StubFunction" } } let inputTypes = token.parameters.map { $0.typeWithoutAttributes }.joined(separator: ", ") var returnType = "\(stubFunction)<(\(genericSafeType(from: inputTypes)))" if token.returnType != "Void" { returnType += ", " returnType += genericSafeType(from: token.returnType) } returnType += ">" code += "" code += ("\(token.accessibility.sourceName)func \(token.rawName)\(matchableGenerics(with: token.parameters))" + "(\(matchableParameterSignature(with: token.parameters))) -> \(returnType)\(matchableGenerics(where: token.parameters)) {") let matchers: String if token.parameters.isEmpty { matchers = "[]" } else { code.nest(parameterMatchers(for: token.parameters)) matchers = "matchers" } code.nest("return \(stubFunction)(stub: cuckoo_manager.createStub(\"\(token.fullyQualifiedName)\", parameterMatchers: \(matchers)))") code += "}" } private func generateVerification(for token: Token) { switch token { case let containerToken as ContainerToken: generateVerificationClass(for: containerToken) case let property as InstanceVariable: generateVerificationProperty(for: property) case let method as Method: generateVerificationMethod(for: method) default: break } } private func generateVerificationClass(for token: ContainerToken) { guard token.accessibility.isAccessible else { return } code += "\(token.accessibility.sourceName)struct \(verificationProxyName(of: token.name)): Cuckoo.VerificationProxy {" code.nest { code += "private let cuckoo_manager: Cuckoo.MockManager" code += "private let callMatcher: Cuckoo.CallMatcher" code += "private let sourceLocation: Cuckoo.SourceLocation" code += "" code += "\(token.accessibility.sourceName)init(cuckoo_manager: Cuckoo.MockManager, callMatcher: Cuckoo.CallMatcher, sourceLocation: Cuckoo.SourceLocation) {" code.nest { code += "self.cuckoo_manager = cuckoo_manager" code += "self.callMatcher = callMatcher" code += "self.sourceLocation = sourceLocation" } code += "}" token.children.forEach { generateVerification(for: $0) } } code += "}" } private func generateVerificationProperty(for token: InstanceVariable) { guard token.accessibility.isAccessible else { return } let propertyType = token.readOnly ? "Cuckoo.VerifyReadOnlyProperty" : "Cuckoo.VerifyProperty" code += "" code += "var \(token.name): \(propertyType)<\(genericSafeType(from: token.type))> {" code.nest("return \(propertyType)(cuckoo_manager: cuckoo_manager, name: \"\(token.name)\", callMatcher: callMatcher, sourceLocation: sourceLocation)") code += "}" } private func generateVerificationMethod(for token: Method) { guard token.accessibility.isAccessible else { return } guard !token.isInit && !token.isDeinit else { return } code += "" code += "@discardableResult" code += ("\(token.accessibility.sourceName)func \(token.rawName)\(matchableGenerics(with: token.parameters))" + "(\(matchableParameterSignature(with: token.parameters))) -> Cuckoo.__DoNotUse<\(genericSafeType(from: token.returnType))>\(matchableGenerics(where: token.parameters)) {") let matchers: String if token.parameters.isEmpty { matchers = "[] as [Cuckoo.ParameterMatcher<Void>]" } else { code.nest(parameterMatchers(for: token.parameters)) matchers = "matchers" } code.nest("return cuckoo_manager.verify(\"\(token.fullyQualifiedName)\", callMatcher: callMatcher, parameterMatchers: \(matchers), sourceLocation: sourceLocation)") code += "}" } private func generateNoImplStubClass(for token: ContainerToken) { guard token.accessibility.isAccessible else { return } code += "" code += "\(token.accessibility.sourceName)class \(stubClassName(of: token.name)): \(token.name) {" code.nest { token.children.forEach { generateNoImplStub(for: $0, withOuterAccessibility: token.accessibility, fromProtocolDefinition: token is ProtocolDeclaration) } } code += "}" } private func generateNoImplStub(for token: Token, withOuterAccessibility outerAccessibility: Accessibility, fromProtocolDefinition: Bool) { switch token { case let property as InstanceVariable: generateNoImplStubProperty(for: property, withOuterAccessibility: outerAccessibility) case let method as Method: generateNoImplStubMethod(for: method, withOuterAccessibility: outerAccessibility, fromProtocolDefinition: fromProtocolDefinition) default: break } } private func generateNoImplStubProperty(for token: InstanceVariable, withOuterAccessibility outerAccessibility: Accessibility) { guard token.accessibility.isAccessible else { return } let accessibility = minAccessibility(token.accessibility, outerAccessibility) code += "" code += "\(accessibility.sourceName)\(token.overriding ? "override " : "")var \(token.name): \(token.type) {" code.nest { code += "get {" code.nest("return DefaultValueRegistry.defaultValue(for: (\(token.type)).self)") code += "}" if token.readOnly == false { code += "set {" code += "}" } } code += "}" } private func generateNoImplStubMethod(for token: Method, withOuterAccessibility outerAccessibility: Accessibility, fromProtocolDefinition: Bool) { guard token.accessibility.isAccessible else { return } guard (!token.isInit && !token.isDeinit ) || fromProtocolDefinition else { return } let override = token is ClassMethod ? "override " : "" let parametersSignature = token.parameters.enumerated().map { "\($1.labelAndName): \($1.type)" }.joined(separator: ", ") let accessibility = minAccessibility(token.accessibility, outerAccessibility) code += "" code += "\(accessibility.sourceName)\(override)\(token.isInit ? (fromProtocolDefinition ? "required " : "") : "func " )\(token.rawName)(\(parametersSignature))\(token.returnSignature) {" if !token.isInit { code.nest("return DefaultValueRegistry.defaultValue(for: (\(token.returnType)).self)") } code += "}" } private func mockClassName(of originalName: String) -> String { return "Mock" + originalName } private func stubClassName(of originalName: String) -> String { return originalName + "Stub" } private func stubbingProxyName(of originalName: String) -> String { return "__StubbingProxy_" + originalName } private func verificationProxyName(of originalName: String) -> String { return "__VerificationProxy_" + originalName } private func matchableGenerics(with parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "" } let genericParameters = (1...parameters.count).map { "M\($0): Cuckoo.Matchable" }.joined(separator: ", ") return "<\(genericParameters)>" } private func matchableGenerics(where parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "" } let whereClause = parameters.enumerated().map { "M\($0 + 1).MatchedType == \(genericSafeType(from: $1.typeWithoutAttributes))" }.joined(separator: ", ") return " where \(whereClause)" } private func matchableParameterSignature(with parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "" } return parameters.enumerated().map { "\($1.labelAndName): M\($0 + 1)" }.joined(separator: ", ") } private func parameterMatchers(for parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "" } let tupleType = parameters.map { $0.typeWithoutAttributes }.joined(separator: ", ") let matchers = parameters.enumerated().map { "wrap(matchable: \($1.name)) { $0\(parameters.count > 1 ? ".\($0)" : "") }" }.joined(separator: ", ") return "let matchers: [Cuckoo.ParameterMatcher<(\(genericSafeType(from: tupleType)))>] = [\(matchers)]" } private func genericSafeType(from type: String) -> String { return type.replacingOccurrences(of: "!", with: "?") } }
mit
058aecf2990aaead312936c9c241ac0d
43.786432
234
0.609649
4.849021
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Class/FirstVC/Controllers/PhoneCodeViewController.swift
1
1757
// // PhoneCodeViewController.swift // MyTools // // Created by gongrong on 2017/5/12. // Copyright © 2017年 zhangk. All rights reserved. // import UIKit class PhoneCodeViewController: BaseViewController { private lazy var sendMessageBtn:SendMessageButton = { let btn = SendMessageButton(frame: CGRect(x: 50, y: 150, w: 100, h: 20), countdownTime: 5) btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside) btn.setTitle("发送", for: .normal) btn.backgroundColor = UIColor.red return btn }() private lazy var messageLabel:UILabel = { let label = ZKTools.createLabel(CGRect(x: 50, y: 100, w: 100, h: 20), title: "0次", textAlignment: .center, font: nil, textColor: UIColor.black) label.backgroundColor = UIColor.gray return label }() private lazy var sendMessageCount:Int=0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.addSubview(messageLabel) view.addSubview(sendMessageBtn) } @objc private func sendAction(){ sendMessageCount += 1 messageLabel.text = "\(sendMessageCount)次" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
1d310456356e8951d7898ab7da5f376f
30.178571
151
0.656357
4.511628
false
false
false
false
JaySonGD/SwiftDayToDay
MapVew/MapVew/ViewController.swift
1
2245
// // ViewController.swift // MapVew // // Created by czljcb on 16/3/11. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController { lazy var locationM: CLLocationManager = { let locationM = CLLocationManager() return locationM }() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mapView.delegate = self //mapView.mapType = .Standard //mapView.scrollEnabled = !true //mapView.zoomEnabled = !true mapView.showsUserLocation = true //mapView.userTrackingMode = .Follow // youbug locationM.requestAlwaysAuthorization() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: MKMapViewDelegate{ func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { //print(userLocation.location?.coordinate) //mapView.setCenterCoordinate((userLocation.location?.coordinate)!, animated: true) mapView.userLocation.title = "Json" mapView.userLocation.subtitle = "czljcb" let span = MKCoordinateSpan(latitudeDelta: 0.0741179875659827, longitudeDelta: 0.0621865116864046) let region = MKCoordinateRegion(center: (userLocation.location?.coordinate)!, span: span) mapView.setRegion(region, animated: true) let annotation = CZAnnotation(coordinate: userLocation.coordinate, title: "json", subtitle: "czljcb") mapView.addAnnotation(annotation) } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { //print( mapView.region.span) } func mapViewDidFailLoadingMap(mapView: MKMapView, withError error: NSError) { // print("加载mapView失败",error) } func mapViewDidFinishLoadingMap(mapView: MKMapView) { // print("加载完成mapView",mapView) } }
mit
af2ae4a574b701d14d34e410fde9786d
28.302632
109
0.65858
5.024831
false
false
false
false
Deekor/JSONWebToken.swift
JWT/Claims.swift
1
1745
import Foundation func validateClaims(payload:Payload, audience:String?, issuer:String?) -> InvalidToken? { return validateIssuer(payload, issuer) ?? validateAudience(payload, audience) ?? validateDate(payload, "exp", .OrderedAscending, .ExpiredSignature, "Expiration time claim (exp) must be an integer") ?? validateDate(payload, "nbf", .OrderedDescending, .ImmatureSignature, "Not before claim (nbf) must be an integer") ?? validateDate(payload, "iat", .OrderedDescending, .InvalidIssuedAt, "Issued at claim (iat) must be an integer") } func validateAudience(payload:Payload, audience:String?) -> InvalidToken? { if let audience = audience { if let aud = payload["aud"] as? [String] { if !contains(aud, audience) { return .InvalidAudience } } else if let aud = payload["aud"] as? String { if aud != audience { return .InvalidAudience } } else { return .DecodeError("Invalid audience claim, must be a string or an array of strings") } } return nil } func validateIssuer(payload:Payload, issuer:String?) -> InvalidToken? { if let issuer = issuer { if let iss = payload["iss"] as? String { if iss != issuer { return .InvalidIssuer } } else { return .InvalidIssuer } } return nil } func validateDate(payload:Payload, key:String, comparison:NSComparisonResult, failure:InvalidToken, decodeError:String) -> InvalidToken? { if let timestamp = payload[key] as? NSTimeInterval { let date = NSDate(timeIntervalSince1970: timestamp) if date.compare(NSDate()) == comparison { return failure } } else if let timestamp:AnyObject = payload[key] { return .DecodeError(decodeError) } return nil }
bsd-2-clause
08fc1b44ddd0b9e20da49d853984229a
31.924528
138
0.677937
4.077103
false
false
false
false
jeffersonaguilar/FacturaLab
FacturaLab/FacturaLab/Login/Login.swift
1
6148
// // Login.swift // FacturaLab // // Created by Jefferson Aguilar on 5/04/16. // Copyright © 2016 InSoTechno. All rights reserved. // import UIKit class Login: UITableViewController, UITextFieldDelegate { @IBOutlet weak var txtUserName: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var btnViewPassword: UIButton! @IBOutlet weak var btnLogin: UIButton! var userNameString:String! var passwordString:String! override func viewDidLoad() { super.viewDidLoad() passwordViewConfig() loginViewConfig() } func passwordViewConfig(){ btnViewPassword.setImage(UIImage(named: "EyeOpen"), forState: UIControlState.Normal) } func loginViewConfig(){ let imageBackground = makeImageWithColor(UIColor(red: 255/255, green: 108/255, blue: 96/255, alpha: 1.0)) btnLogin.setBackgroundImage(imageBackground, forState: UIControlState.Normal) btnLogin.tintColor = UIColor.whiteColor() } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == txtUserName { textField.resignFirstResponder() txtPassword.becomeFirstResponder() } if textField == txtPassword { userNameString = txtUserName.text passwordString = txtPassword.text if userNameString.isEmpty || passwordString.isEmpty { textField.resignFirstResponder() txtUserName.becomeFirstResponder() } else { login_Click(self) } } return true } func queryToServerLogin(){ let url:String = "http://dev-facturalab.herokuapp.com/api/user/signin" let postString:String = "email=\(userNameString)&password=\(passwordString)" self.queryToServer(url, queryData: postString, method: "POST") { (dataResult, errorResult) -> () in if errorResult != nil { let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil) self.alertView("Error", message: "No se ha prodido Conectar con el servidor", alertStyle: UIAlertControllerStyle.Alert, alertAction: alertAction) } else { self.extractDataWithNSDictionary(dataResult, result: { (statusResult, message, errorResult) in if errorResult != nil { let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil) self.alertView("Error !", message: "Error Ususario y contrasñea", alertStyle: UIAlertControllerStyle.Alert, alertAction: alertAction) } else { if statusResult == 1 { let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil) self.alertView("Login", message: "Login Susess", alertStyle: UIAlertControllerStyle.Alert, alertAction: alertAction) } else { let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil) self.alertView("Login", message: message, alertStyle: UIAlertControllerStyle.Alert, alertAction: alertAction) } } }) } } } func extractDataWithNSDictionary(data:NSData, result:(statusResult:Int32!, message:String!, errorResult:NSError!) -> ()){ var json:NSDictionary! var errorParse:NSError! do{ json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary } catch let error as NSError { errorParse = error json = nil } if errorParse != nil { result(statusResult: nil, message: nil, errorResult: errorParse) } else { let resultstatus:Int32 = 0 let resultMessage:String = json["message"] as! String result(statusResult: resultstatus, message: resultMessage, errorResult: nil) } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 && indexPath.row == 0 { txtUserName.becomeFirstResponder() } if indexPath.section == 0 && indexPath.row == 1 { txtPassword.becomeFirstResponder() } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return self.tableView.frame.height / 2 - self.tableView.frame.height / 4 } @IBAction func viewPassword_Click(sender: AnyObject) { passwordString = txtPassword.text if btnViewPassword.currentImage!.isEqual(UIImage(named:"EyeClose")){ btnViewPassword.setImage(UIImage(named: "EyeOpen"), forState: UIControlState.Normal) txtPassword.secureTextEntry = false txtPassword.text = nil txtPassword.text = passwordString }else{ btnViewPassword.setImage(UIImage(named: "EyeClose"), forState: UIControlState.Normal) txtPassword.secureTextEntry = true txtPassword.text = passwordString } } @IBAction func login_Click(sender: AnyObject) { userNameString = txtUserName.text passwordString = txtPassword.text if userNameString.isEmpty || passwordString.isEmpty { let alertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in self.txtUserName.becomeFirstResponder() }) alertView("Error", message: "ingrese todos los datos", alertStyle: UIAlertControllerStyle.Alert, alertAction: alertAction) } else { queryToServerLogin() } } }
apache-2.0
2a90129fad14de0e3f1c7b5d9dd1d1a6
40.809524
161
0.618451
5.358326
false
false
false
false
chrislzm/TimeAnalytics
Time Analytics/TANetConvenience.swift
1
13243
// // TANetConvenience.swift // Time Analytics // // Time Analytics Network Client convenience methods. Utilizes core network client methods to exchange information with the Moves REST API. // // This class is used by: // -TAModel for accessing Moves data // -TALoginViewController for login auth flow // -TASettingsViewController for allowing the user see the last time we checked for udpates // // // Created by Chris Leung on 5/14/17. // Copyright © 2017 Chris Leung. All rights reserved. // import CoreData import Foundation import UIKit extension TANetClient { // Handles Part 1 of Moves Auth Flow: Getting an auth code from the Moves app func obtainMovesAuthCode() { let moveHook = "moves://app/authorize?" + "client_id=Z0hQuORANlkEb_BmDVu8TntptuUoTv6o&redirect_uri=time-analytics://app&scope=activity location".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! let moveUrl = URL(string: moveHook) let app = UIApplication.shared // Try to open the Moves app, if we have it installed if app.canOpenURL(moveUrl!) { app.open(moveUrl!, options: [:]) { (result) in } // Else try to open the App Store app page for moves } else if let url = URL(string: "itms-apps://itunes.apple.com/app/id509204969"), app.canOpenURL(url){ app.open(url, options: [:], completionHandler: nil) // Else open moves app page website } else { app.open(URL(string: "https://moves-app.com")!,options: [:],completionHandler: nil) } } // Handles Part 2 of Moves Auth Flow: Use the auth code to get OAuth access and refresh tokens func loginWithMovesAuthCode(authCode:String, completionHandler: @escaping (_ error: String?) -> Void) { // 1. Save the auth code to our client movesAuthCode = authCode /* 2. Create and run HTTP request to authenticate the userId and password with Udacity */ let parameters:[String:String] = [TANetClient.MovesApi.ParameterKeys.GrantType:TANetClient.MovesApi.ParameterValues.AuthCode, TANetClient.MovesApi.ParameterKeys.Code:authCode, TANetClient.MovesApi.ParameterKeys.ClientId:TANetClient.MovesApi.Constants.ClientId, TANetClient.MovesApi.ParameterKeys.ClientSecret:TANetClient.MovesApi.Constants.ClientSecret, TANetClient.MovesApi.ParameterKeys.RedirectUri:TANetClient.TimeAnalytics.RedirectUri] let _ = taskForHTTPMethod(TANetClient.Constants.ApiScheme, TANetClient.Constants.HttpPost, TANetClient.MovesApi.Constants.Host, TANetClient.MovesApi.Methods.Auth, apiParameters: parameters, valuesForHTTPHeader: nil, httpBody: nil) { (results,error) in /* 3. Send response to auth response handler */ self.movesAuthResponseHandler(results,error,completionHandler) } } // Part 2 of Moves Auth Flow continued func movesAuthResponseHandler(_ results:AnyObject?, _ error:NSError?,_ completionHandler: @escaping (_ error: String?) -> Void) { /* 1. Check for error response from Moves */ guard error == nil else { let errorString = self.getNiceMessageFromHttpNSError(error!) completionHandler(errorString) return } /* 2. Verify we have received an access token and are logged in */ guard let response = results as? [String:AnyObject], let accessToken = response[TANetClient.MovesApi.JSONResponseKeys.AccessToken] as? String, let expiresIn = response[TANetClient.MovesApi.JSONResponseKeys.ExpiresIn] as? Int, let refreshToken = response[TANetClient.MovesApi.JSONResponseKeys.RefreshToken] as? String, let userId = response[TANetClient.MovesApi.JSONResponseKeys.UserId] as? UInt64 else { completionHandler("Error creating Moves session") return } /* 4. Save retrieved session variables */ // Calculate expiration time of the access token var accessTokenExpiration = Date() accessTokenExpiration.addTimeInterval(TimeInterval(expiresIn - TANetClient.MovesApi.Constants.AccessTokenExpirationBuffer)) movesUserId = userId movesAccessTokenExpiration = accessTokenExpiration movesAccessToken = accessToken movesRefreshToken = refreshToken /* 5. Now retrieve user's first date so we'll know how to download all his/her data later */ getMovesUserFirstDate() { (userFirstDate,error) in guard error == nil else { completionHandler(error!) return } self.movesUserFirstDate = userFirstDate! /* 6. Save all session info to user defaults for persistence */ TAModel.sharedInstance.saveMovesSessionData(self.movesAuthCode!, userId, accessToken, accessTokenExpiration, refreshToken, userFirstDate!) /* 7. Complete login with no errors */ completionHandler(nil) } } // Ensures our session is authorized before we make any calls to the Moves API, otherwise send an error func verifyLoggedIntoMoves(completionHandler: @escaping (_ error: String?) -> Void) { // Check: Are we logged in? guard movesAccessTokenExpiration != nil else { completionHandler("Error: Not logged into Moves") return } // Check: Has our session expired? if Date() > movesAccessTokenExpiration! { // Attempt to refresh our session /* 1. Create and run HTTP request to authenticate the userId and password with Udacity */ let parameters:[String:String] = [TANetClient.MovesApi.ParameterKeys.GrantType:TANetClient.MovesApi.ParameterValues.RefreshToken, TANetClient.MovesApi.ParameterKeys.RefreshToken:movesRefreshToken!, TANetClient.MovesApi.ParameterKeys.ClientId:TANetClient.MovesApi.Constants.ClientId, TANetClient.MovesApi.ParameterKeys.ClientSecret:TANetClient.MovesApi.Constants.ClientSecret] let _ = taskForHTTPMethod(TANetClient.Constants.ApiScheme, TANetClient.Constants.HttpPost, TANetClient.MovesApi.Constants.Host, TANetClient.MovesApi.Methods.Auth, apiParameters: parameters, valuesForHTTPHeader: nil, httpBody: nil) { (results,error) in self.movesAuthResponseHandler(results,error,completionHandler) } } // Our session hasn't expired -- return with no error completionHandler(nil) } // Retrieves Moves StoryLne data for a given time period func getMovesDataFrom(_ startDate:Date, _ endDate:Date,_ lastUpdate:Date?, _ completionHandler: @escaping (_ response:[AnyObject]?, _ error: String?) -> Void) { verifyLoggedIntoMoves() { (error) in guard error == nil else { completionHandler(nil,error!) return } let formattedStartDate = self.getFormattedDate(startDate) let formattedEndDate = self.getFormattedDate(endDate) var parameters:[String:String] = [TANetClient.MovesApi.ParameterKeys.AccessToken:self.movesAccessToken!, TANetClient.MovesApi.ParameterKeys.FromDate:formattedStartDate, TANetClient.MovesApi.ParameterKeys.ToDate:formattedEndDate, TANetClient.MovesApi.ParameterKeys.TrackPoints:TANetClient.MovesApi.ParameterValues.False] if let lastUpdate = lastUpdate { parameters[TANetClient.MovesApi.ParameterKeys.UpdatedSince] = self.getFormattedDateISO8601Date(lastUpdate) } let _ = self.taskForHTTPMethod(TANetClient.Constants.ApiScheme, TANetClient.Constants.HttpGet, TANetClient.MovesApi.Constants.Host, TANetClient.MovesApi.Methods.StoryLine, apiParameters: parameters, valuesForHTTPHeader: nil, httpBody: nil) { (results,error) in /* 2. Check for error response from Moves */ guard error == nil else { let errorString = self.getNiceMessageFromHttpNSError(error!) completionHandler(nil, errorString) return } /* 3. Verify we have received the data array */ guard let response = results as? [AnyObject] else { completionHandler(nil,"Error retrieving data from Moves") return } /* 4. Return the data */ completionHandler(response,nil) } } } // Retrieves the Moves user's first data date from his profile func getMovesUserFirstDate(completionHandler: @escaping (_ date:String?, _ error: String?) -> Void) { getMovesUserProfile() { (response,error) in guard error == nil else { completionHandler(nil,error!) return } guard let profile = response?[TANetClient.MovesApi.JSONResponseKeys.UserProfile.Profile] as? [String:AnyObject], let firstDate = profile[TANetClient.MovesApi.JSONResponseKeys.UserProfile.FirstDate] as? String else { completionHandler(nil,"Unable to parse user profile data") return } completionHandler(firstDate,nil) } } // Retrieves user profile data func getMovesUserProfile(completionHandler: @escaping (_ response:[String:AnyObject]?, _ error: String?) -> Void) { verifyLoggedIntoMoves() { (error) in guard error == nil else { completionHandler(nil,error!) return } /* 1. Create and run HTTP request to get user profile */ let parameters:[String:String] = [TANetClient.MovesApi.ParameterKeys.AccessToken:self.movesAccessToken!] let _ = self.taskForHTTPMethod(TANetClient.Constants.ApiScheme, TANetClient.Constants.HttpGet, TANetClient.MovesApi.Constants.Host, TANetClient.MovesApi.Methods.UserProfile, apiParameters: parameters, valuesForHTTPHeader: nil, httpBody: nil) { (results,error) in /* 2. Check for error response from Moves */ guard error == nil else { let errorString = self.getNiceMessageFromHttpNSError(error!) completionHandler(nil,errorString) return } /* 3. Verify we have received the array of data*/ guard let response = results as? [String:AnyObject] else { completionHandler(nil,"Error retrieving user profile") return } /* 4. Return the response */ completionHandler(response,nil) } } } // MARK: Private helper methods // Handles NSErrors -- Turns them into user-friendly messages before sending them to the controller's completion handler private func getNiceMessageFromHttpNSError(_ error:NSError) -> String { // TODO: Write the actual error to a log file let errorString = error.userInfo[NSLocalizedDescriptionKey].debugDescription var userFriendlyErrorString = "Please try again." if errorString.contains("timed out") { userFriendlyErrorString = "Couldn't reach server (timed out)" } else if errorString.contains("400") || errorString.contains("500"){ userFriendlyErrorString = "Error receiving authorization from Moves. Please close Time Analytics and try again." } else if errorString.contains("401"){ userFriendlyErrorString = "Unauthorized" } else if errorString.contains("404"){ userFriendlyErrorString = "Invalid Moves token" } else if errorString.contains("network connection was lost"){ userFriendlyErrorString = "The network connection was lost" } else if errorString.contains("Internet connection appears to be offline") { userFriendlyErrorString = "The Internet connection appears to be offline" } return userFriendlyErrorString } private func getFormattedDate(_ date:Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyMMdd" return formatter.string(from: date) } private func getFormattedDateISO8601Date(_ date:Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmssZ" return formatter.string(from: date) } }
mit
ec5f9d8c8774c80e5b52dc116b239db1
47.505495
411
0.623999
5.12065
false
false
false
false
loudnate/Loop
LoopUI/Views/BasalRateHUDView.swift
1
2306
// // BasalRateHUDView.swift // Naterade // // Created by Nathan Racklyeft on 5/1/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit import LoopKitUI public final class BasalRateHUDView: BaseHUDView { override public var orderPriority: HUDViewOrderPriority { return 3 } @IBOutlet private weak var basalStateView: BasalStateView! @IBOutlet private weak var basalRateLabel: UILabel! { didSet { basalRateLabel?.text = String(format: basalRateFormatString, "–") updateTintColor() accessibilityValue = LocalizedString("Unknown", comment: "Accessibility value for an unknown value") } } public override func tintColorDidChange() { super.tintColorDidChange() updateTintColor() } private func updateTintColor() { basalRateLabel?.textColor = tintColor } private lazy var basalRateFormatString = LocalizedString("%@ U", comment: "The format string describing the basal rate.") public func setNetBasalRate(_ rate: Double, percent: Double, at date: Date) { let time = timeFormatter.string(from: date) caption?.text = time if let rateString = decimalFormatter.string(from: rate) { basalRateLabel?.text = String(format: basalRateFormatString, rateString) accessibilityValue = String(format: LocalizedString("%1$@ units per hour at %2$@", comment: "Accessibility format string describing the basal rate. (1: localized basal rate value)(2: last updated time)"), rateString, time) } else { basalRateLabel?.text = nil accessibilityValue = nil } basalStateView.netBasalPercent = percent } private lazy var decimalFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 1 formatter.minimumIntegerDigits = 1 formatter.positiveFormat = "+0.0##" formatter.negativeFormat = "-0.0##" return formatter }() private lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() }
apache-2.0
c72cbd476c6230d5f97be1b80e897bfa
30.121622
234
0.65914
5.039387
false
true
false
false
or1onsli/Fou.run-
MusicRun/DrawingFuncs.swift
1
2683
// // drawingFuncs.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // import Foundation import UIKit func drawCustomImageCustom(size: CGSize, redStart: CGFloat, greenStart: CGFloat, blueStart: CGFloat, redEnd: CGFloat, greenEnd: CGFloat, blueEnd: CGFloat) -> UIImage { // Setup our context let bounds = CGRect(origin: CGPoint.zero, size: size) let opaque = false let scale: CGFloat = 0 UIGraphicsBeginImageContextWithOptions(size, opaque, scale) let context = UIGraphicsGetCurrentContext() // Setup complete, do drawing here let color1: [CGFloat] = [ redStart, greenStart, blueStart, 1.0] let color2: [CGFloat] = [ redEnd, greenEnd, blueEnd, 1.0] let colors = [ CGColor.init(colorSpace: CGColorSpaceCreateDeviceRGB(), components: color1), CGColor.init(colorSpace: CGColorSpaceCreateDeviceRGB(), components: color2)] let locations: [CGFloat] = [0.0, 1.0] let startPoint = CGPoint(x: bounds.maxX, y: bounds.maxY) let endPoint = CGPoint(x: bounds.minX, y: bounds.minY) let gradient = CGGradient(colorsSpace: nil , colors: colors as CFArray, locations: locations ) context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: .drawsAfterEndLocation) // Drawing complete, retrieve the finished image and cleanup let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } func drawCustomImage(size: CGSize) -> UIImage { // Setup our context let bounds = CGRect(origin: CGPoint.zero, size: size) let opaque = false let scale: CGFloat = 0 UIGraphicsBeginImageContextWithOptions(size, opaque, scale) let context = UIGraphicsGetCurrentContext() // Setup complete, do drawing here let color1: [CGFloat] = [ 0.93, 0.11, 0.14, 1.0] let color2: [CGFloat] = [ 0.98, 0.93, 0.13, 1.0] let colors = [ CGColor.init(colorSpace: CGColorSpaceCreateDeviceRGB(), components: color1), CGColor.init(colorSpace: CGColorSpaceCreateDeviceRGB(), components: color2)] let locations: [CGFloat] = [0.0, 1.0] let startPoint = CGPoint(x: bounds.maxX, y: bounds.maxY) let endPoint = CGPoint(x: bounds.minX, y: bounds.minY) let gradient = CGGradient(colorsSpace: nil , colors: colors as CFArray, locations: locations ) context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: .drawsAfterEndLocation) // Drawing complete, retrieve the finished image and cleanup let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! }
mit
43cf3ec21d73874878c46796e44eecb4
36.25
172
0.697241
4.382353
false
false
false
false
midjuly/cordova-plugin-iosrtc
src/PluginGetUserMedia.swift
2
6810
import Foundation import AVFoundation class PluginGetUserMedia { var rtcPeerConnectionFactory: RTCPeerConnectionFactory init(rtcPeerConnectionFactory: RTCPeerConnectionFactory) { NSLog("PluginGetUserMedia#init()") self.rtcPeerConnectionFactory = rtcPeerConnectionFactory } deinit { NSLog("PluginGetUserMedia#deinit()") } func call( constraints: NSDictionary, callback: (data: NSDictionary) -> Void, errback: (error: String) -> Void, eventListenerForNewStream: (pluginMediaStream: PluginMediaStream) -> Void ) { NSLog("PluginGetUserMedia#call()") let audioRequested = constraints.objectForKey("audio") as? Bool ?? false let videoRequested = constraints.objectForKey("video") as? Bool ?? false let videoDeviceId = constraints.objectForKey("videoDeviceId") as? String let videoMinWidth = constraints.objectForKey("videoMinWidth") as? Int ?? 0 let videoMaxWidth = constraints.objectForKey("videoMaxWidth") as? Int ?? 0 let videoMinHeight = constraints.objectForKey("videoMinHeight") as? Int ?? 0 let videoMaxHeight = constraints.objectForKey("videoMaxHeight") as? Int ?? 0 let videoMinFrameRate = constraints.objectForKey("videoMinFrameRate") as? Float ?? 0.0 let videoMaxFrameRate = constraints.objectForKey("videoMaxFrameRate") as? Float ?? 0.0 var rtcMediaStream: RTCMediaStream var pluginMediaStream: PluginMediaStream? var rtcAudioTrack: RTCAudioTrack? var rtcVideoTrack: RTCVideoTrack? var rtcVideoCapturer: RTCVideoCapturer? var rtcVideoSource: RTCVideoSource? var videoDevice: AVCaptureDevice? var mandatoryConstraints: [RTCPair] = [] var constraints: RTCMediaConstraints if videoRequested == true { switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) { case AVAuthorizationStatus.NotDetermined: NSLog("PluginGetUserMedia#call() | video authorization: not determined") case AVAuthorizationStatus.Authorized: NSLog("PluginGetUserMedia#call() | video authorization: authorized") case AVAuthorizationStatus.Denied: NSLog("PluginGetUserMedia#call() | video authorization: denied") errback(error: "video denied") return case AVAuthorizationStatus.Restricted: NSLog("PluginGetUserMedia#call() | video authorization: restricted") errback(error: "video restricted") return } } if audioRequested == true { switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeAudio) { case AVAuthorizationStatus.NotDetermined: NSLog("PluginGetUserMedia#call() | audio authorization: not determined") case AVAuthorizationStatus.Authorized: NSLog("PluginGetUserMedia#call() | audio authorization: authorized") case AVAuthorizationStatus.Denied: NSLog("PluginGetUserMedia#call() | audio authorization: denied") errback(error: "audio denied") return case AVAuthorizationStatus.Restricted: NSLog("PluginGetUserMedia#call() | audio authorization: restricted") errback(error: "audio restricted") return } } rtcMediaStream = self.rtcPeerConnectionFactory.mediaStreamWithLabel(NSUUID().UUIDString) if videoRequested == true { // No specific video device requested. if videoDeviceId == nil { NSLog("PluginGetUserMedia#call() | video requested (device not specified)") for device: AVCaptureDevice in (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! Array<AVCaptureDevice>) { if device.position == AVCaptureDevicePosition.Front { videoDevice = device break } } } // Video device specified. else { NSLog("PluginGetUserMedia#call() | video requested (specified device id: \(videoDeviceId!))") for device: AVCaptureDevice in (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! Array<AVCaptureDevice>) { if device.uniqueID == videoDeviceId { videoDevice = device break } } } if videoDevice == nil { NSLog("PluginGetUserMedia#call() | video requested but no suitable device found") errback(error: "no suitable camera device found") return } NSLog("PluginGetUserMedia#call() | chosen video device: \(videoDevice!)") rtcVideoCapturer = RTCVideoCapturer(deviceName: videoDevice!.localizedName) if videoMinWidth > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [minWidth:\(videoMinWidth)]") mandatoryConstraints.append(RTCPair(key: "minWidth", value: String(videoMinWidth))) } if videoMaxWidth > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [maxWidth:\(videoMaxWidth)]") mandatoryConstraints.append(RTCPair(key: "maxWidth", value: String(videoMaxWidth))) } if videoMinHeight > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [minHeight:\(videoMinHeight)]") mandatoryConstraints.append(RTCPair(key: "minHeight", value: String(videoMinHeight))) } if videoMaxHeight > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [maxHeight:\(videoMaxHeight)]") mandatoryConstraints.append(RTCPair(key: "maxHeight", value: String(videoMaxHeight))) } if videoMinFrameRate > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [videoMinFrameRate:\(videoMinFrameRate)]") mandatoryConstraints.append(RTCPair(key: "minFrameRate", value: String(videoMinFrameRate))) } if videoMaxFrameRate > 0 { NSLog("PluginGetUserMedia#call() | adding media constraint [videoMaxFrameRate:\(videoMaxFrameRate)]") mandatoryConstraints.append(RTCPair(key: "maxFrameRate", value: String(videoMaxFrameRate))) } constraints = RTCMediaConstraints( mandatoryConstraints: mandatoryConstraints, optionalConstraints: [] ) rtcVideoSource = self.rtcPeerConnectionFactory.videoSourceWithCapturer(rtcVideoCapturer, constraints: constraints ) // If videoSource state is "ended" it means that constraints were not satisfied so // invoke the given errback. if (rtcVideoSource!.state == RTCSourceStateEnded) { NSLog("PluginGetUserMedia() | rtcVideoSource.state is 'ended', constraints not satisfied") errback(error: "constraints not satisfied") return } rtcVideoTrack = self.rtcPeerConnectionFactory.videoTrackWithID(NSUUID().UUIDString, source: rtcVideoSource ) rtcMediaStream.addVideoTrack(rtcVideoTrack) } if audioRequested == true { NSLog("PluginGetUserMedia#call() | audio requested") rtcAudioTrack = self.rtcPeerConnectionFactory.audioTrackWithID(NSUUID().UUIDString) rtcMediaStream.addAudioTrack(rtcAudioTrack!) } pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream) pluginMediaStream!.run() // Let the plugin store it in its dictionary. eventListenerForNewStream(pluginMediaStream: pluginMediaStream!) callback(data: [ "stream": pluginMediaStream!.getJSON() ]) } }
mit
6627340e4857258c4b2ef9949632e7c4
35.031746
120
0.746843
4.274953
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
16
20022
// // HorizontalBarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/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 CoreGraphics import UIKit public class HorizontalBarChartRenderer: BarChartRenderer { public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler) } internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context) var barData = delegate!.barChartRendererData(self) var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self) var dataSetOffset = (barData.dataSetCount - 1) var groupSpace = barData.groupSpace var groupSpaceHalf = groupSpace / 2.0 var barSpace = dataSet.barSpace var barSpaceHalf = barSpace / 2.0 var containsStacks = dataSet.isStacked var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var barWidth: CGFloat = 0.5 var phaseY = _animator.phaseY var barRect = CGRect() var barShadow = CGRect() var y: Double // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf let values = e.values if (!containsStacks || values == nil) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextFillRect(context, barRect) } else { let vals = values! var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // fill the stack for (var k = 0; k < vals.count; k++) { let value = vals[k] if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right: CGFloat, left: CGFloat if isInverted { left = y >= yStart ? CGFloat(y) : CGFloat(yStart) right = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { right = y >= yStart ? CGFloat(y) : CGFloat(yStart) left = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase right *= phaseY left *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsBottom(barRect.origin.y)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor) CGContextFillRect(context, barRect) } } } CGContextRestoreGState(context) } internal override func prepareBarHighlight(#x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 var top = x - barWidth + barspacehalf var bottom = x + barWidth - barspacehalf var left = CGFloat(y1) var right = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY) } public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY) } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self) var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self) var dataSets = barData.dataSets var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self) let textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right let valueOffsetPlus: CGFloat = 5.0 var posOffset: CGFloat var negOffset: CGFloat for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i] as! BarChartDataSet if (!dataSet.isDrawValuesEnabled) { continue } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var yOffset = -valueFont.lineHeight / 2.0 var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i) // if only single values are drawn (sum) if (!dataSet.isStacked) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = entries[j].value var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } else { // if each value of a potential stack should be drawn for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j] let values = e.values // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = e.value var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } else { let vals = values! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for (var k = 0; k < vals.count; k++) { let value = vals[k] var y: Double if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: CGFloat(y) * _animator.phaseY, y: 0.0)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { var val = vals[k] var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } var x = transformed[k].x + (val >= 0 ? posOffset : negOffset) var y = valuePoints[j].y if (!viewPortHandler.isInBoundsTop(y)) { break } if (!viewPortHandler.isInBoundsX(x)) { continue } if (!viewPortHandler.isInBoundsBottom(y)) { continue } drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } } } } } } internal override func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return false } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY } }
mit
540bc565359c08cdfa547500f8ca5e4b
41.602128
170
0.414094
7.030197
false
false
false
false
elpassion/el-space-ios
ELSpaceTests/TestCases/Commons/Presenters/Modal/ModalViewControllerPresenterSpec.swift
1
3447
import Quick import Nimble import UIKit @testable import ELSpace class ModalViewControllerPresenterSpec: QuickSpec { override func spec() { describe("ModalViewControllerPresenter") { var sut: ModalViewControllerPresenter! var presentTransitionStub: TransitionStub! var dismissTransitionStub: TransitionStub! beforeEach { presentTransitionStub = TransitionStub() dismissTransitionStub = TransitionStub() let configuration = ModalPresentationConfiguration( animated: false, presentTransition: presentTransitionStub, dismissTransition: dismissTransitionStub, presentationStyle: .overFullScreen) sut = ModalViewControllerPresenter(configuration: configuration) } it("should return correct presentAnimationController") { let presentAnimationController = sut.animationController( forPresented: UIViewController(), presenting: UIViewController(), source: UIViewController() ) expect(presentAnimationController).to(be(presentTransitionStub)) } it("should return correct dismissAnimationController") { let dismissAnimationController = sut.animationController( forDismissed: UIViewController() ) expect(dismissAnimationController).to(be(dismissTransitionStub)) } context("when presenting") { var viewController: UIViewController! var baseViewControllerSpy: ViewControllerSpy! beforeEach { viewController = UIViewController() baseViewControllerSpy = ViewControllerSpy() sut.present(viewController: viewController, on: baseViewControllerSpy) } it("should view controller has correct modal presentation style") { expect(viewController.modalPresentationStyle).to(equal(UIModalPresentationStyle.overFullScreen)) } it("should view controller has correct transitioning delegate") { expect(viewController.transitioningDelegate).to(be(sut)) } it("should present correct viewController") { expect(baseViewControllerSpy.didPresentViewController).to(be(viewController)) } } context("when dissmissing") { var viewControllerSpy: ViewControllerSpy! beforeEach { viewControllerSpy = ViewControllerSpy() sut.dismiss(viewController: viewControllerSpy) } it("should view controller has correct modal presentation style") { expect(viewControllerSpy.modalPresentationStyle).to(equal(UIModalPresentationStyle.overFullScreen)) } it("should view controller has correct transitioning delegate") { expect(viewControllerSpy.transitioningDelegate).to(be(sut)) } it("should dismiss") { expect(viewControllerSpy.didDismiss).to(beTrue()) } } } } }
gpl-3.0
1b403496c169182baefec847a687065b
38.62069
119
0.582826
6.921687
false
false
false
false
andrebocchini/SwiftChattyOSX
Pods/SwiftChatty/SwiftChatty/Common Models/Mappable/EventLolCountUpdate.swift
1
1212
// // EventLolCountUpdate.swift // SwiftChatty // // Created by Andre Bocchini on 1/26/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Genome public struct EventLolCountUpdates: EventDataType { public var updates: [LolCountUpdate] = [] public init() {} } /// An event indicating that lol counts have been updated for one or more posts. /// /// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451658 extension EventLolCountUpdates: CommonMappableModel { public mutating func sequence(map: Map) throws { try updates <~ map["updates"] } } /// Model for a single lol count update, for a single post. /// /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451658 public struct LolCountUpdate { public var postId: Int = 0 public var tag: LolTag = .Unknown public var count: Int = 0 public init() {} } extension LolCountUpdate: CommonMappableModel { public mutating func sequence(map: Map) throws { try postId <~ map["postId"] var tagString = "" try tagString <~ map["tag"] if let tag = LolTag(rawValue: tagString) { self.tag = tag } try count <~ map["count"] } }
mit
ec01441b6ab6f62eb7046e16dc1d73bb
20.245614
80
0.647399
3.749226
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InstantVideoPIP.swift
1
15621
// // InstantVideoPIP.swift // Telegram // // Created by keepcoder on 22/05/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox import SwiftSignalKit enum InstantVideoPIPCornerAlignment { case topLeft case topRight case bottomLeft case bottomRight } class InstantVideoPIPView : GIFPlayerView { let playingProgressView: RadialProgressView = RadialProgressView(theme:RadialProgressTheme(backgroundColor: .clear, foregroundColor: NSColor.white.withAlphaComponent(0.8), lineWidth: 3), twist: false) override init() { super.init() } required init(frame frameRect: NSRect) { super.init() setFrameSize(NSMakeSize(200, 200)) playingProgressView.userInteractionEnabled = false } override func viewDidMoveToWindow() { if let _ = window { playingProgressView.frame = bounds addSubview(playingProgressView) } else { playingProgressView.removeFromSuperview() } } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class InstantVideoPIP: GenericViewController<InstantVideoPIPView>, APDelegate { private var controller:APController private var context: AccountContext private weak var tableView:TableView? private var listener:TableScrollListener! private let dataDisposable = MetaDisposable() private let fetchDisposable = MetaDisposable() private var currentMessage:Message? = nil private var scrollTime: TimeInterval = CFAbsoluteTimeGetCurrent() private var alignment:InstantVideoPIPCornerAlignment = .topRight private var isShown:Bool = false private var timebase: CMTimebase? = nil { didSet { genericView.reset(with: timebase) } } init(_ controller:APController, context: AccountContext, window:Window) { self.controller = controller self.context = context super.init() listener = TableScrollListener({ [weak self] _ in self?.updateScrolled() }) controller.add(listener: self) context.bindings.rootNavigation().add(listener: WeakReference(value: self)) } override var window:Window? { return mainWindow } override func viewDidLoad() { super.viewDidLoad() view.layer?.borderColor = NSColor.clear.cgColor view.layer?.borderWidth = 0 view.autoresizingMask = [.maxYMargin, .minXMargin] } override func navigationWillChangeController() { if let controller = context.bindings.rootNavigation().controller as? ChatController { updateTableView(controller.genericView.tableView, context: context, controller: self.controller) } else { updateTableView(nil, context: context, controller: self.controller) } } private func updateScrolled() { scrollTime = CFAbsoluteTimeGetCurrent() let isAnimateScrolling = tableView?.clipView.isAnimateScrolling ?? false if !isAnimateScrolling { if let currentMessage = currentMessage { var needShow:Bool = true tableView?.enumerateVisibleViews(with: { view in if let view = view as? ChatRowView, let item = view.item as? ChatRowItem { if let stableId = item.stableId.base as? ChatHistoryEntryId { if case .message(let message) = stableId { if message.id == currentMessage.id, view.visibleRect.size == view.frame.size { if let state = item.entry.additionalData.transribeState { loop: switch state { case .collapsed: needShow = false default: break loop } } else { needShow = false } } } } } }) if needShow { showIfNeeded(animated: !isShown) } else { if isShown { hide() } } } else { hide() } } } deinit { tableView?.removeScroll(listener: listener) controller.remove(listener: self) window?.removeAllHandlers(for: self) if isShown { hide() } dataDisposable.dispose() fetchDisposable.dispose() } func showIfNeeded(animated: Bool = true) { loadViewIfNeeded() isShown = true genericView.animatesAlphaOnFirstTransition = false if let message = currentMessage, let media = message.effectiveMedia as? TelegramMediaFile { let signal:Signal<ImageDataTransformation, NoError> = chatMessageVideo(postbox: context.account.postbox, fileReference: FileMediaReference.message(message: MessageReference(message), media: media), scale: view.backingScaleFactor) let resource = FileMediaReference.message(message: MessageReference(message), media: media) let data: Signal<AVGifData?, NoError> = context.account.postbox.mediaBox.resourceData(resource.media.resource) |> map { resource in if resource.complete { return AVGifData.dataFrom(resource.path) } else if let resource = media.resource as? LocalFileReferenceMediaResource { return AVGifData.dataFrom(resource.localFilePath) } else { return nil } } |> deliverOnMainQueue genericView.setSignal(signal) dataDisposable.set(data.start(next: { [weak self] data in self?.genericView.set(data: data, timebase: self?.timebase) })) } if let contentView = window?.contentView, genericView.superview == nil { contentView.addSubview(genericView) genericView.layer?.cornerRadius = view.frame.width/2 if genericView.frame.minX == 0 { if let contentView = window?.contentView { switch alignment { case .topRight: genericView.setFrameOrigin(NSMakePoint(contentView.frame.width, contentView.frame.height - view.frame.height - 130)) case .topLeft: genericView.setFrameOrigin(NSMakePoint(-genericView.frame.width, contentView.frame.height - view.frame.height - 130)) case .bottomRight: genericView.setFrameOrigin(NSMakePoint(contentView.frame.width, 100)) case .bottomLeft: genericView.setFrameOrigin(NSMakePoint(-genericView.frame.width, 100)) } } } alignToCorner(alignment) } let context = self.context var startDragPosition:NSPoint? = nil var startViewPosition:NSPoint = view.frame.origin window?.set(mouseHandler: { [weak self] (_) -> KeyHandlerResult in if let strongSelf = self, let _ = startDragPosition { if startViewPosition.x == strongSelf.view.frame.origin.x && startViewPosition.y == strongSelf.view.frame.origin.y { context.audioPlayer?.playOrPause() } startDragPosition = nil if let opacity = strongSelf.view.layer?.opacity, opacity < 0.5 { context.audioPlayer?.notifyCompleteQueue(animated: true) context.audioPlayer?.cleanup() } else { strongSelf.findCorner() } strongSelf.view._change(opacity: 1.0) return .invoked } return .rejected }, with: self, for: .leftMouseUp, priority: .high) window?.set(mouseHandler: { [weak self] (_) -> KeyHandlerResult in if let strongSelf = self, strongSelf.view._mouseInside() { startDragPosition = strongSelf.window?.mouseLocationOutsideOfEventStream startViewPosition = strongSelf.view.frame.origin return .invoked } return .rejected }, with: self, for: .leftMouseDown, priority: .high) window?.set(mouseHandler: { [weak self] (_) -> KeyHandlerResult in if let strongSelf = self, let startDragPosition = startDragPosition, let current = strongSelf.window?.mouseLocationOutsideOfEventStream, let frame = strongSelf.window?.contentView?.frame { let difference = NSMakePoint(startDragPosition.x - current.x, startDragPosition.y - current.y) let point = NSMakePoint(startViewPosition.x - difference.x, startViewPosition.y - difference.y) strongSelf.view.setFrameOrigin(point) if strongSelf.view.frame.maxX > frame.width { let difference = strongSelf.view.frame.maxX - frame.width strongSelf.view.layer?.opacity = (1.0 - Float(difference / strongSelf.view.frame.width)) } else if point.x < 0 { let difference = abs(point.x) strongSelf.view.layer?.opacity = (1.0 - Float(difference / strongSelf.view.frame.width)) } else { strongSelf.view.layer?.opacity = 1.0 } return .invoked } return .rejected }, with: self, for: .leftMouseDragged, priority: .high) } func hide(_ animated:Bool = true) { isShown = false if let contentView = window?.contentView, genericView.superview != nil { let point:NSPoint switch alignment { case .topRight: point = NSMakePoint(contentView.frame.width, contentView.frame.height - view.frame.height - 130) case .topLeft: point = NSMakePoint(-view.frame.width, contentView.frame.height - view.frame.height - 130) case .bottomRight: point = NSMakePoint(contentView.frame.width, 100) case .bottomLeft: point = NSMakePoint(-view.frame.width, 100) } genericView._change(pos: point, animated: animated, completion: { [weak view] completed in view?.removeFromSuperview() }) } window?.removeAllHandlers(for: self) } func alignToCorner(_ corner:InstantVideoPIPCornerAlignment, _ animated: Bool = true) { if let contentView = window?.contentView { switch corner { case .topRight: genericView._change(pos: NSMakePoint(contentView.frame.width - view.frame.width - 20, contentView.frame.height - view.frame.height - 130), animated: animated) case .topLeft: genericView._change(pos: NSMakePoint(20, contentView.frame.height - view.frame.height - 130), animated: animated) case .bottomRight: genericView._change(pos: NSMakePoint(contentView.frame.width - view.frame.width - 20, 100), animated: animated) case .bottomLeft: genericView._change(pos: NSMakePoint(20, 100), animated: animated) } } } func findCorner() { if let contentView = window?.contentView { let center = NSMakePoint(contentView.frame.width/2, contentView.frame.height/2) let viewCenterPoint = NSMakePoint(view.frame.origin.x + view.frame.width/2, view.frame.origin.y + view.frame.height/2) if viewCenterPoint.x > center.x { if viewCenterPoint.y > center.y { alignment = .topRight } else { alignment = .bottomRight } } else { if viewCenterPoint.y > center.y { alignment = .topLeft } else { alignment = .bottomLeft } } alignToCorner(alignment) } } func updateTableView(_ tableView:TableView?, context: AccountContext, controller: APController) { self.tableView?.removeScroll(listener: listener) self.tableView = tableView self.context = context self.tableView?.addScroll(listener: listener) if controller != self.controller { self.controller = controller controller.add(listener: self) } updateScrolled() } func songDidChanged(song:APSongItem, for controller:APController, animated: Bool) { var msg:Message? = nil switch song.entry { case let .song(message): if let md = (message.effectiveMedia as? TelegramMediaFile), md.isInstantVideo { msg = message } default: break } if let msg = msg { if let currentMessage = currentMessage, !isShown && currentMessage.id != msg.id, CFAbsoluteTimeGetCurrent() - scrollTime > 1.0 { if let item = tableView?.item(stableId: msg.chatStableId) { tableView?.scroll(to: .center(id: item.stableId, innerId: nil, animated: true, focus: .init(focus: false), inset: 0)) } } currentMessage = msg // genericView.reset(with: controller.timebase, false) } else { currentMessage = nil self.timebase = nil } updateScrolled() } func songDidChangedState(song: APSongItem, for controller: APController, animated: Bool) { switch song.state { case let .playing(_, _, progress): genericView.playingProgressView.state = .ImpossibleFetching(progress: Float(progress), force: false) case .stoped, .waiting, .fetching: genericView.playingProgressView.state = .None case let .paused(_, _, progress): genericView.playingProgressView.state = .ImpossibleFetching(progress: Float(progress), force: true) } } func songDidStartPlaying(song:APSongItem, for controller:APController, animated: Bool) { } func songDidStopPlaying(song:APSongItem, for controller:APController, animated: Bool) { if song.stableId == currentMessage?.chatStableId { //self.timebase = nil } } func playerDidChangedTimebase(song:APSongItem, for controller:APController, animated: Bool) { if song.stableId == currentMessage?.chatStableId { self.timebase = controller.timebase } } func audioDidCompleteQueue(for controller:APController, animated: Bool) { hide() } }
gpl-2.0
a7e88fb1d49ae6b134027d6b1b778857
38.846939
241
0.567926
5.307509
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/ChapterView.swift
1
6126
// // ChapterView.swift // MrGreen // // Created by Benzi on 27/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit import UIKit /// MARK: class ChapterView : SKNode { required init?(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } var chapter:ChapterItem! = nil var levelNodeSideLength:CGFloat = factor2(forPhone: 64.0, forPhone3x: 96.0, forPad: 112.0) var levelNumberFontSize:CGFloat = factor2(forPhone: 25.0, forPhone3x: 40.0, forPad: 50.0) let emotionScale:CGFloat = 0.761904762 var levelNodes = [String:SKSpriteNode]() init(_ chapter:ChapterItem, nextLevelToPlay:LevelItem?, theme:ThemeManager) { super.init() self.chapter = chapter let levelNodeSize:CGSize = CGSizeMake(levelNodeSideLength, levelNodeSideLength*1.125) let playerNodeSize:CGSize = CGSizeMake(levelNodeSideLength, levelNodeSideLength).scale(0.9) var position = CGPointMake(levelNodeSideLength/2.0, 0.0) let levelCount = chapter.levels.count-1 for (index, level) in chapter.levels.enumerate() { // create the level node grid cell let texture = theme.getTextureName(levelTexture(index, levelCount)) let levelSprite = SKSpriteNode(texture: SpriteManager.Shared.grid.texture(texture)) levelSprite.size = levelNodeSize levelSprite.position = position levelSprite.colorBlendFactor = 1.0 levelSprite.color = UIColor.whiteColor() // theme.getCellColor(column: level.number, row: 0) levelSprite.zPosition = 10.0 // if we have not completed this level, we need to fade it out // slightly if !level.isCompleted { levelSprite.alpha = 0.3 } // apply a shadow beaneath the cell let shadowTextureName = shadowTexture(index, levelCount) let shadowSprite = SKSpriteNode(texture: SpriteManager.Shared.grid.texture(shadowTextureName)) shadowSprite.size = levelNodeSize shadowSprite.position = position.offset(dx: 0, dy: -levelNodeSize.height/2.0) shadowSprite.zPosition = 5.0 // add a level number let levelNumberSprite = SKLabelNode(fontNamed: FactoredSizes.numberFont) levelNumberSprite.text = "\(level.number)" levelNumberSprite.fontColor = level.isCompleted ? UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.8) // black : UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) // white levelNumberSprite.fontSize = levelNumberFontSize levelNumberSprite.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center levelNumberSprite.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center levelNumberSprite.position = CGPointMake(0.0, 0.0625*levelNodeSize.height) if nextLevelToPlay?.levelKey == level.levelKey { // add a player sprite to indicate which is the next logical level to complete let playerSprite = entitySprite("player") playerSprite.size = playerNodeSize playerSprite.zPosition = 11.0 playerSprite.setItem("level", value: level) let playerEmotion = entitySprite("emotion_happy") playerEmotion.size = playerNodeSize.scale(emotionScale) playerEmotion.setItem("level", value: level) playerSprite.addChild(playerEmotion) // lets try to move in the player let playerTargetPosition = position.offset(dx: 0, dy: levelNodeSize.height*0.125) var playerStartPosition = playerTargetPosition.offset(dx: -levelNodeSideLength, dy: 0.0) if level.isFirstLevelInChapter { playerStartPosition = playerTargetPosition.offset(dx: 0.0, dy: +levelNodeSideLength) playerSprite.alpha = 0.0 } playerSprite.position = playerStartPosition let moveIn = ActionFactory.sharedInstance.createPopInActionWithoutDelay(playerSprite, destination: playerTargetPosition) let fadeIn = SKAction.fadeInWithDuration(0.3) let arrive = SKAction.group([fadeIn,moveIn]) if level.isFirstLevelInChapter { playerSprite.runAction(SKAction.sequence([arrive,ActionFactory.sharedInstance.playPop])) } else { playerSprite.runAction(arrive) } self.addChild(playerSprite) } // level sprite will hold a reference to the level for later reference // also we save a reference to the level sprite based on the level key levelSprite.setItem("level", value: level) levelNodes[level.levelKey as String] = levelSprite // add the sprites levelSprite.addChild(levelNumberSprite) self.addChild(levelSprite) self.addChild(shadowSprite) // update the position offset to apply to the next level node position = position.offset(dx: levelNodeSideLength, dy: 0) } } func levelTexture(index:Int, _ levelCount:Int) -> String { if levelCount == 0 { return "cell_all" } else if index == 0 { return "cell_left" } else if index == levelCount { return "cell_right" } else { return "cell" } } func shadowTexture(index:Int, _ levelCount:Int) -> String { if levelCount == 0 { return "shadow_bottom" } else if index == 0 { return "shadow_left" } else if index == levelCount { return "shadow_right" } else { return "shadow_mid" } } }
isc
1ab14ae4a1d7a2c8ed5ad03cef0d9c5a
43.071942
136
0.599576
4.767315
false
false
false
false
NghiaTranUIT/Hakuba
Source/Hakuba.swift
2
15825
// // Hakuba.swift // Hakuba // // Created by Le Van Nghia on 1/13/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import UIKit public protocol SectionIndex { var intValue: Int { get } } @objc public protocol HakubaDelegate : class { optional func scrollViewDidScroll(scrollView: UIScrollView) optional func scrollViewWillBeginDecelerating(scrollView: UIScrollView) optional func scrollViewWillBeginDragging(scrollView: UIScrollView) } public class Hakuba : NSObject { public weak var delegate: HakubaDelegate? public var loadmoreHandler: (() -> ())? public var loadmoreEnabled = false public var loadmoreThreshold: CGFloat = 25 public var sectionCount: Int { return sections.count } private weak var tableView: UITableView? private var sections: [MYSection] = [] private let reloadTracker = MYReloadTracker() private var selectedCells = [MYBaseViewProtocol]() private var heightCalculationCells: [String: MYTableViewCell] = [:] private var currentTopSection = 0 private var willFloatingSection = -1 private var insertedSectionsRange: (Int, Int) = (100, -1) // inserting or deleting rows public var cellEditable = false public var commitEditingHandler: ((UITableViewCellEditingStyle, NSIndexPath) -> ())? public init(tableView: UITableView) { super.init() self.tableView = tableView tableView.delegate = self tableView.dataSource = self } public func deselectAllCells() { for view in selectedCells { view.unhighlight(true) } selectedCells.removeAll(keepCapacity: false) } public func resetAll() -> Self { sections = [] selectedCells = [] heightCalculationCells = [:] currentTopSection = 0 willFloatingSection = -1 return self } public subscript(section: SectionIndex) -> MYSection { return self[section.intValue] } public subscript(index: Int) -> MYSection { get { if let s = sections.my_get(index) { return s } let length = index + 1 - sectionCount let newSections = (sectionCount...index).map { i -> MYSection in let ns = MYSection() ns.delegate = self ns.index = i return ns } //let insertSet: NSIndexSet = NSIndexSet(indexesInRange: NSMakeRange(sectionCount, length)) //tableView?.insertSections(insertSet, withRowAnimation: .None) let begin = min(insertedSectionsRange.0, sectionCount) let end = max(insertedSectionsRange.1, index + 1) insertedSectionsRange = (begin, end) sections += newSections return sections[index] } } private func syncSections(animation: MYAnimation) -> Bool { let modifiedSections = sections.filter { $0.isChanged } // reload all tableview when the number of modified sections is greater than 1 if modifiedSections.count > 1 { self.slide(animation) return true } let length = insertedSectionsRange.1 - insertedSectionsRange.0 if length > 0 { let insertSet: NSIndexSet = NSIndexSet(indexesInRange: NSMakeRange(insertedSectionsRange.0, length)) insertedSectionsRange = (100, -1) tableView?.insertSections(insertSet, withRowAnimation: animation) return true } return false } } // MARK - UITableView methods public extension Hakuba { func setEditing(editing: Bool, animated: Bool) { tableView?.setEditing(editing, animated: animated) } } public extension Hakuba { func insertSection(section: MYSection, atIndex index: Int) -> Self { // TODO : implementation return self } func removeSectionAtIndex(index: Int) -> Self { // TODO : implementation return self } func slide(_ animation: MYAnimation = .None) -> Self { // TODO : implementation tableView?.reloadData() insertedSectionsRange = (100, -1) // reset all section reload tracker for sec in sections { sec.didReloadTableView() } return self } } // MARK - MYSectionDelegate extension Hakuba : MYSectionDelegate { func reloadSections(index: Int, animation: MYAnimation) { if !syncSections(animation) { let indexSet = NSIndexSet(index: index) tableView?.reloadSections(indexSet, withRowAnimation: animation) } } func insertRows(indexPaths: [NSIndexPath], animation: MYAnimation) { if !syncSections(animation) { tableView?.insertRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } } func deleteRows(indexPaths: [NSIndexPath], animation: MYAnimation) { if !syncSections(animation) { tableView?.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } } func willAddCellViewModels(viewmodels: [MYCellModel]) { setBaseViewDataDelegate(viewmodels) } } // MARK - MYViewModelDelegate extension Hakuba : MYViewModelDelegate { public func didCallSelectionHandler(view: MYBaseViewProtocol) { addSelectedView(view) } public func reloadView(index: Int, section: Int, animation: MYAnimation) { let indexPath = NSIndexPath(forRow: index, inSection: section) tableView?.reloadRowsAtIndexPaths([indexPath], withRowAnimation: animation) } public func reloadHeader(section: Int) { if let headerView = tableView?.headerViewForSection(section) as? MYHeaderFooterView { if let viewmodel = sections[section].header { headerView.configureView(viewmodel) } } } public func reloadFooter(section: Int) { if let footerView = tableView?.footerViewForSection(section) as? MYHeaderFooterView { if let viewmodel = sections[section].footer { footerView.configureView(viewmodel) } } } } // MARK - UITableViewDelegate extension Hakuba : UITableViewDelegate { public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if let cellModel = self.cellViewModelAtIndexPath(indexPath) { if !cellModel.dynamicHeightEnabled { return cellModel.cellHeight } if let h = cellModel.calculatedHeight { return h } if heightCalculationCells[cellModel.identifier] == nil { heightCalculationCells[cellModel.identifier] = tableView.dequeueReusableCellWithIdentifier(cellModel.identifier) as? MYTableViewCell } if let cell = heightCalculationCells[cellModel.identifier] { cell.configureCell(cellModel) cellModel.calculatedHeight = calculateHeightForConfiguredSizingCell(cell) return cellModel.calculatedHeight! } } return 0 } /* public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if let cellModel = self.cellViewModelAtIndexPath(indexPath) { return cellModel.cellHeight } return 0 } */ public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let header = self.sections.my_get(section)?.header { return header.isEnabled ? header.viewHeight : 0 } return 0 } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let header = self.sections.my_get(section)?.header { if !header.isEnabled { return nil } if let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(header.identifier) as? MYHeaderFooterView { headerView.configureView(header) return headerView } } return nil } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let footer = self.sections.my_get(section)?.footer { return footer.isEnabled ? footer.viewHeight : 0 } return 0 } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if let footer = self.sections.my_get(section)?.footer { if !footer.isEnabled { return nil } if let footerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(footer.identifier) as? MYHeaderFooterView { footerView.configureView(footer) return footerView } } return nil } public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cellModel = self.cellViewModelAtIndexPath(indexPath) { if let myCell = cell as? MYTableViewCell { myCell.willAppear(cellModel) } } } public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cellModel = self.cellViewModelAtIndexPath(indexPath) { if let myCell = cell as? MYTableViewCell { myCell.didDisappear(cellModel) } } } } // MARK - UITableViewDataSource extension Hakuba : UITableViewDataSource { public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sectionCount } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sections.my_get(section)?.count ?? 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cellModel = self.cellViewModelAtIndexPath(indexPath) { if let cell = tableView.dequeueReusableCellWithIdentifier(cellModel.identifier, forIndexPath: indexPath) as? MYTableViewCell { cell.configureCell(cellModel) return cell } } return UITableViewCell() } // inserting or deleting delegate public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { commitEditingHandler?(editingStyle, indexPath) } public func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let cellmodel = self.cellViewModelAtIndexPath(indexPath) { return cellmodel.editable || cellEditable } return false } } // MARK - register cell and header/footer view public extension Hakuba { func registerCellClass(cellClass: AnyClass) -> Self { return registerCellClasses(cellClass) } func registerCellClasses(cellClasses: AnyClass...) -> Self { for cellClass in cellClasses { let identifier = String.my_className(cellClass) tableView?.registerClass(cellClass, forCellReuseIdentifier: identifier) } return self } func registerCellNib(cellClass: AnyClass) -> Self { return registerCellNibs(cellClass) } func registerCellNibs(cellClasses: AnyClass...) -> Self { for cellClass in cellClasses { let identifier = String.my_className(cellClass) let nib = UINib(nibName: identifier, bundle: nil) tableView?.registerNib(nib, forCellReuseIdentifier: identifier) } return self } func registerHeaderFooterViewClass(viewClass: AnyClass) -> Self { return registerHeaderFooterViewClasses(viewClass) } func registerHeaderFooterViewClasses(viewClasses: AnyClass...) -> Self { for viewClass in viewClasses { let identifier = String.my_className(viewClass) tableView?.registerClass(viewClass, forHeaderFooterViewReuseIdentifier: identifier) } return self } func registerHeaderFooterViewNib(viewClass: AnyClass) -> Self { return registerHeaderFooterViewNibs(viewClass) } func registerHeaderFooterViewNibs(viewClasses: AnyClass...) -> Self { for viewClass in viewClasses { let identifier = String.my_className(viewClass) let nib = UINib(nibName: identifier, bundle: nil) tableView?.registerNib(nib, forHeaderFooterViewReuseIdentifier: identifier) } return self } } // MARK - UIScrollViewDelegate extension Hakuba { public func scrollViewDidScroll(scrollView: UIScrollView) { delegate?.scrollViewDidScroll?(scrollView) if let indexPath = tableView?.indexPathsForVisibleRows()?.first as? NSIndexPath { if currentTopSection != indexPath.section { if let headerView = tableView?.headerViewForSection(currentTopSection) as? MYHeaderFooterView { headerView.didChangeFloatingState(false) } if let headerView = tableView?.headerViewForSection(indexPath.section) as? MYHeaderFooterView { headerView.didChangeFloatingState(true) } if currentTopSection > indexPath.section { willFloatingSection = indexPath.section } currentTopSection = indexPath.section } } if !loadmoreEnabled { return } let offset = scrollView.contentOffset let y = offset.y + scrollView.bounds.height - scrollView.contentInset.bottom let h = scrollView.contentSize.height if y > h - loadmoreThreshold { loadmoreEnabled = false self.loadmoreHandler?() } } public func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if section == willFloatingSection { if let view = view as? MYHeaderFooterView { view.didChangeFloatingState(true) willFloatingSection = -1 } } } public func scrollViewWillBeginDecelerating(scrollView: UIScrollView) { delegate?.scrollViewWillBeginDecelerating?(scrollView) } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { delegate?.scrollViewWillBeginDragging?(scrollView) } } // MARK - private methods private extension Hakuba { func cellViewModelAtIndexPath(indexPath: NSIndexPath) -> MYCellModel? { return self.sections.my_get(indexPath.section)?[indexPath.row] } func addSelectedView(view: MYBaseViewProtocol) { deselectAllCells() selectedCells = [view] } func setBaseViewDataDelegate(dataList: [MYViewModel]) { for data in dataList { data.delegate = self } } func calculateHeightForConfiguredSizingCell(cell: MYTableViewCell) -> CGFloat { cell.bounds = CGRectMake(0, 0, tableView?.bounds.width ?? UIScreen.mainScreen().bounds.width, cell.bounds.height) cell.setNeedsLayout() cell.layoutIfNeeded() let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) return size.height + 1.0 } }
mit
df83e3a0d610e2aa15bf0b94cc623a49
34.013274
155
0.637472
5.451257
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Graphics/KLGraphicsContext.swift
1
3415
/** * @file KLGraphicsContext.swift * @brief Define KLGraphicsContext class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import CoconutData import KiwiEngine import JavaScriptCore import Foundation @objc public protocol KLGraphicsContextProtocol: JSExport { var logicalFrame: JSValue { get } func setFillColor(_ val: JSValue) func setStrokeColor(_ val: JSValue) func setPenSize(_ val: JSValue) func moveTo(_ xval: JSValue, _ yval: JSValue) func lineTo(_ xval: JSValue, _ yval: JSValue) func rect(_ xval: JSValue, _ yval: JSValue, _ width: JSValue, _ height: JSValue, _ dofill: JSValue) func circle(_ xval: JSValue, _ yval: JSValue, _ radval: JSValue, _ dofill: JSValue) } @objc public class KLGraphicsContext: NSObject, KLGraphicsContextProtocol { private var mGContext: CNGraphicsContext private var mJContext: KEContext private var mConsole: CNConsole public init(graphicsContext gctxt: CNGraphicsContext, scriptContext sctxt: KEContext, console cons: CNConsole) { mGContext = gctxt mJContext = sctxt mConsole = cons super.init() } public var logicalFrame: JSValue { get { return mGContext.logicalFrame.toJSValue(context: mJContext) } } public func setFillColor(_ val: JSValue) { if let col = val.toObject() as? KLColor { mGContext.setFillColor(color: col.core) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func setStrokeColor(_ val: JSValue) { if let col = val.toObject() as? KLColor { mGContext.setStrokeColor(color: col.core) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func setPenSize(_ val: JSValue) { if val.isNumber { let width = val.toDouble() mGContext.setPenSize(width: CGFloat(width)) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func moveTo(_ xval: JSValue, _ yval: JSValue) { if xval.isNumber && yval.isNumber { let x = xval.toDouble() let y = yval.toDouble() mGContext.move(to: CGPoint(x: x, y: y)) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func lineTo(_ xval: JSValue, _ yval: JSValue) { if xval.isNumber && yval.isNumber { let x = xval.toDouble() let y = yval.toDouble() mGContext.line(to: CGPoint(x: x, y: y)) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func rect(_ xval: JSValue, _ yval: JSValue, _ widval: JSValue, _ hgtval: JSValue, _ dofill: JSValue) { if xval.isNumber && yval.isNumber && widval.isNumber && hgtval.isNumber && dofill.isBoolean { let x = xval.toDouble() let y = yval.toDouble() let width = widval.toDouble() let height = hgtval.toDouble() let fill = dofill.toBool() mGContext.rect(rect: CGRect(x: x, y: y, width: width, height: height), doFill: fill) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } public func circle(_ xval: JSValue, _ yval: JSValue, _ radval: JSValue, _ dofill: JSValue) { if xval.isNumber && yval.isNumber && radval.isNumber && dofill.isBoolean { let x = xval.toDouble() let y = yval.toDouble() let rad = radval.toDouble() let fill = dofill.toBool() mGContext.circle(center: CGPoint(x: x, y: y), radius: CGFloat(rad), doFill: fill) } else { mConsole.error(string: "Invalid parameter at \(#function)\n") } } }
lgpl-2.1
4a36e70eeb8a6e26963c2a6f9ef2cc0d
28.695652
113
0.681406
3.159112
false
false
false
false
olaf-olaf/finalProject
drumPad/ReverbParameterViewController.swift
1
2433
// // ReverbParameterViewController.swift // drumPad // // Created by Olaf Kroon on 24/01/17. // Student number: 10787321 // Course: Programmeerproject // // ReverbParameterViewController consists of rotary knobs that are used to determine the parameters // of the reverb object in AudioContoller. // // Copyright © 2017 Olaf Kroon. All rights reserved. // import UIKit class ReverbParameterViewController: UIViewController { // MARK: - Variables. let enabledColor = UIColor(red: (246/255.0), green: (124/255.0), blue: (113/255.0), alpha: 1.0) var decayKnob: Knob! var delayKnob: Knob! var reflectionKnob: Knob! // MARK: - UIViewController lifecycle. @IBOutlet weak var setReverbButton: UIButton! @IBOutlet weak var decayKnobPlaceHolder: UIView! @IBOutlet weak var delayKnobPlaceholder: UIView! @IBOutlet weak var reflectionKnobPlaceholder: UIView! // MARK: - UIViewController lifecycle. override func viewDidLoad() { super.viewDidLoad() setReverbButton.layer.cornerRadius = 5 decayKnob = Knob(frame: decayKnobPlaceHolder.bounds) decayKnobPlaceHolder.addSubview(decayKnob) decayKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 2) decayKnob.value = Float(AudioController.sharedInstance.reverb.decayTimeAtNyquist) delayKnob = Knob(frame: delayKnobPlaceholder.bounds) delayKnobPlaceholder.addSubview(delayKnob) delayKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 1) delayKnob.value = Float(AudioController.sharedInstance.reverb.maxDelayTime) reflectionKnob = Knob(frame: reflectionKnobPlaceholder.bounds) reflectionKnobPlaceholder.addSubview(reflectionKnob) reflectionKnob.setKnobDisplay(largeButton: true, minimum: 1, maximum: 15) reflectionKnob.value = Float(AudioController.sharedInstance.reverb.randomizeReflections) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Actions. @IBAction func setReverb(_ sender: Any) { if setReverbButton.isTouchInside { setReverbButton.backgroundColor = enabledColor AudioController.sharedInstance.setReverbParameters(randomInflections: Double(reflectionKnob.value), maxDelay: Double(delayKnob.value), Decay: Double(decayKnob.value)) } } }
mit
f9521c26ce053d27ab1c99087c54a124
36.415385
178
0.710115
4.350626
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Fitting/Fleet/FleetBarCell.swift
2
2288
// // FleetBarCell.swift // Neocom // // Created by Artem Shimanski on 4/30/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import Expressible struct FleetBarCell: View { @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.self) private var environment @ObservedObject var currentShip: DGMShip @EnvironmentObject private var gang: DGMGang var pilot: DGMCharacter var onClose: () -> Void private var closeButton: some View { Group { if gang.pilots.count > 1 { Button(action: onClose) { Image(systemName: "xmark") .frame(width: 32, height: 32) .contentShape(Rectangle()) }.accentColor(.primary) } } } var body: some View { let type = pilot.ship?.type(from: managedObjectContext) let name = pilot.ship?.name let isSelected = currentShip == pilot.ship return HStack { Spacer() if type != nil { Icon(type!.image).cornerRadius(4) } VStack(alignment: .leading) { type?.typeName.map {Text($0)} ?? Text("Unknown") if name?.isEmpty == false { Text(name!).modifier(SecondaryLabelModifier()) } }.lineLimit(1) Spacer() closeButton.layoutPriority(1) } .frame(maxWidth: .infinity, alignment: .center) .frame(minHeight: 50) .padding(8) .background(isSelected ? RoundedRectangle(cornerRadius: 8).foregroundColor(Color(.systemBackground)).edgesIgnoringSafeArea(.all) : nil) .opacity(isSelected ? 1.0 : 0.5) } } #if DEBUG struct FleetBarCell_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() return HStack { FleetBarCell(currentShip: gang.pilots[0].ship!, pilot: gang.pilots[0]) {} FleetBarCell(currentShip: gang.pilots[0].ship!, pilot: gang.pilots[1]) {} }.padding() .environmentObject(gang) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
8b5eebed1948f40b8246ad933df5ef8e
29.905405
143
0.57324
4.510848
false
false
false
false
wenluma/swift
test/Interpreter/builtin_bridge_object.swift
16
5076
// RUN: %empty-directory(%t) // RUN: %target-build-swift -parse-stdlib %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Swift import SwiftShims class C { deinit { print("deallocated") } } #if arch(i386) || arch(arm) // We have no ObjC tagged pointers, and two low spare bits due to alignment. let NATIVE_SPARE_BITS: UInt = 0x0000_0003 let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(x86_64) // We have ObjC tagged pointers in the lowest and highest bit let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006 let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001 #elseif arch(arm64) // We have ObjC tagged pointers in the highest bit let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0007 let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000 #elseif arch(powerpc64) || arch(powerpc64le) // We have no ObjC tagged pointers, and three low spare bits due to alignment. let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(s390x) // We have no ObjC tagged pointers, and three low spare bits due to alignment. let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 let OBJC_TAGGED_POINTER_BITS: UInt = 0 #endif func bitPattern(_ x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } func nonPointerBits(_ x: Builtin.BridgeObject) -> UInt { return bitPattern(x) & NATIVE_SPARE_BITS } // Try without any bits set. if true { let x = C() let bo = Builtin.castToBridgeObject(x, 0._builtinWordValue) let bo2 = bo let x1: C = Builtin.castReferenceFromBridgeObject(bo) let x2: C = Builtin.castReferenceFromBridgeObject(bo2) // CHECK: true print(x === x1) // CHECK-NEXT: true print(x === x2) print(nonPointerBits(bo) == 0) // CHECK-NEXT: true var bo3 = Builtin.castToBridgeObject(C(), 0._builtinWordValue) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: true let bo4 = bo3 print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) _fixLifetime(bo4) } // CHECK-NEXT: deallocated // CHECK-NEXT: deallocated // Try with all spare bits set. if true { let x = C() let bo = Builtin.castToBridgeObject(x, NATIVE_SPARE_BITS._builtinWordValue) let bo2 = bo let x1: C = Builtin.castReferenceFromBridgeObject(bo) let x2: C = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) print(nonPointerBits(bo) == NATIVE_SPARE_BITS) // CHECK-NEXT: true var bo3 = Builtin.castToBridgeObject(C(), NATIVE_SPARE_BITS._builtinWordValue) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: true let bo4 = bo3 print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) _fixLifetime(bo4) } // CHECK-NEXT: deallocated // CHECK-NEXT: deallocated import Foundation func nonNativeBridgeObject(_ o: AnyObject) -> Builtin.BridgeObject { let tagged = ((Builtin.reinterpretCast(o) as UInt) & OBJC_TAGGED_POINTER_BITS) != 0 return Builtin.castToBridgeObject( o, tagged ? 0._builtinWordValue : NATIVE_SPARE_BITS._builtinWordValue) } // Try with a (probably) tagged pointer. No bits may be masked into a // non-native object. if true { let x = NSNumber(value: 22) let bo = nonNativeBridgeObject(x) let bo2 = bo let x1: NSNumber = Builtin.castReferenceFromBridgeObject(bo) let x2: NSNumber = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) var bo3 = nonNativeBridgeObject(NSNumber(value: 22)) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) } var unTaggedString: NSString { return NSString(format: "A long string that won't fit in a tagged pointer") } // Try with an un-tagged pointer. if true { let x = unTaggedString let bo = nonNativeBridgeObject(x) let bo2 = bo let x1: NSString = Builtin.castReferenceFromBridgeObject(bo) let x2: NSString = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) var bo3 = nonNativeBridgeObject(unTaggedString) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) } func hitOptionalGenerically<T>(_ x: T?) { switch x { case .some: print("some") case .none: print("none") } } func hitOptionalSpecifically(_ x: Builtin.BridgeObject?) { switch x { case .some: print("some") case .none: print("none") } } if true { // CHECK-NEXT: true print(MemoryLayout<Optional<Builtin.BridgeObject>>.size == MemoryLayout<Builtin.BridgeObject>.size) var bo: Builtin.BridgeObject? // CHECK-NEXT: none hitOptionalSpecifically(bo) // CHECK-NEXT: none hitOptionalGenerically(bo) bo = Builtin.castToBridgeObject(C(), 0._builtinWordValue) // CHECK-NEXT: some hitOptionalSpecifically(bo) // CHECK: some hitOptionalGenerically(bo) }
mit
67dabfceedaa1a189c1721e18c988ea6
24.766497
85
0.70134
3.304688
false
false
false
false
druva/dSwiftUtils
Shared/IntExtensions.swift
1
883
// // IntExtensions.swift // MobiCoreFramework // // Created by Druva Yarlagadda on 4/26/18. // Copyright © 2018 Druva Yarlagadda. All rights reserved. // import Foundation extension Int { /** Generates Random Number from the given range - parameter min: default value 0 - parameter max: provide integer - returns: Integer between given range */ public static func random(min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } /** Checks if given number is Even or not - returns: returns true of false */ public var isEven: Bool { return (self % 2) == 0 } /** Checks if given number is Odd or not - returns: returns true of false */ public var isOdd: Bool { return (self % 2) == 1 } }
mit
cdb5b82922802be0f1ab9db9eb76b23d
20.512195
69
0.577098
4.027397
false
false
false
false
davidrothera/SUPSemVer
SUPSemVer/SUPSemVer.swift
1
2669
// // SUPSemVer.swift // SUPSemVer // // Created by David Rothera on 26/12/2015. // Copyright © 2015 Supratude Ltd. All rights reserved. // import Foundation extension Collection { // A safe way to return an index if it exists and a nil if not public subscript(safe index: Index) -> _Element? { return index >= startIndex && index < endIndex ? self[index] : nil } } open class SemVer: CustomStringConvertible, Comparable { var major: Int var minor: Int var patch: Int var prerelease: String? open var description: String { if prerelease == nil { return "SemVer(Major: \(major), Minor: \(minor), Patch: \(patch))" } return "SemVer(Major: \(major), Minor: \(minor), Patch: \(patch), " + "Prerelease: \(prerelease!))" } public init?(_ semVer: String) { let versionComponents = semVer.components(separatedBy: "-") let versions = versionComponents[0].components(separatedBy: ".") prerelease = versionComponents.count > 1 ? versionComponents[1] : nil // The first element of the array always exists, try and convert to an Int if let majorComponent = Int(versions[0]) { self.major = majorComponent } else { self.major = 0 } // The second element might not exist, use the safe extension if let minorComponent = versions[safe: 1] { self.minor = Int(minorComponent) ?? 0 } else { self.minor = 0 } // The third element might not exist, use the safe extension if let patchComponent = versions[safe: 2] { self.patch = Int(patchComponent) ?? 0 } else { self.patch = 0 } } public init(major: Int, minor: Int, patch: Int) { self.major = major self.minor = minor self.patch = patch } public init(major: Int, minor: Int, patch: Int, prerelease: String) { self.major = major self.minor = minor self.patch = patch self.prerelease = prerelease } } public func == (lhs: SemVer, rhs: SemVer) -> Bool { if lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch && lhs.prerelease == rhs.prerelease { return true } return false } public func < (lhs: SemVer, rhs: SemVer) -> Bool { if lhs.major < rhs.major { return true } else if lhs.major <= rhs.major && lhs.minor < rhs.minor { return true } else if lhs.major <= rhs.major && lhs.minor <= rhs.minor && lhs.patch < rhs.patch { return true } return false }
mit
c485be53bd9125ba42d1b91caa1fe4cc
27.382979
89
0.578711
3.994012
false
false
false
false
sambatech/player_sdk_ios
SambaPlayer/SambaCast.swift
1
15515
// // SambaCast.swift // SambaPlayer // // Created by Kesley Vaz on 18/09/2018. // Copyright © 2018 Samba Tech. All rights reserved. // import Foundation import GoogleCast @objc public class SambaCast: NSObject { @objc public static var sharedInstance = SambaCast() fileprivate var internalDelegates: [SambaCastDelegate] = [] fileprivate var delegates: [SambaCastDelegate] = [] private var channel: SambaCastChannel? private var sambaCastRequest: SambaCastRequest = SambaCastRequest() private var currentMedia: SambaMedia? private var currentCaptionTheme: String? public var enableSDKLogging: Bool = false public internal(set) var isCastDialogShowing: Bool = false private weak var buttonForIntrucions: SambaCastButton? private override init() {} public internal(set) var playbackState: SambaCastPlaybackState { get { return getCurrentCastState() } set { persistCurrentCastState(state: newValue) } } //MARK: - Public Methods @objc public func subscribe(delegate: SambaCastDelegate) { let index = delegates.index(where: {$0 === delegate}) guard index == nil else { return } delegates.append(delegate) } @objc public func unSubscribe(delegate: SambaCastDelegate) { guard let index = delegates.index(where: {$0 === delegate}) else { return } delegates.remove(at: index) } func subscribeInternal(delegate: SambaCastDelegate) { let index = internalDelegates.index(where: {$0 === delegate}) guard index == nil else { return } internalDelegates.append(delegate) } func unSubscribeInternal(delegate: SambaCastDelegate) { guard let index = internalDelegates.index(where: {$0 === delegate}) else { return } internalDelegates.remove(at: index) } @objc public func config() { let criteria = GCKDiscoveryCriteria(applicationID: Helpers.settings["cast_application_id_prod"]!) let options = GCKCastOptions(discoveryCriteria: criteria) options.stopReceiverApplicationWhenEndingSession = true GCKCastContext.setSharedInstanceWith(options) // setupCastLogging() GCKCastContext.sharedInstance().sessionManager.add(self) GCKCastContext.sharedInstance().imagePicker = self NotificationCenter.default.addObserver(self, selector: #selector(self.castDialogWillShow), name: NSNotification.Name.gckuiCastDialogWillShow, object: GCKCastContext.sharedInstance()) NotificationCenter.default.addObserver(self, selector: #selector(self.castDialogDidHide), name: NSNotification.Name.gckuiCastDialogDidHide, object: GCKCastContext.sharedInstance()) } @objc public func isCasting() -> Bool { return GCKCastContext.sharedInstance().sessionManager.hasConnectedCastSession() } @objc public func presentCastInstruction(with button: SambaCastButton) { self.buttonForIntrucions = button NotificationCenter.default.addObserver(self, selector: #selector(self.castDeviceDidChange), name: NSNotification.Name.gckCastStateDidChange, object: GCKCastContext.sharedInstance()) } @objc public func stopCasting() { GCKCastContext.sharedInstance().sessionManager.endSessionAndStopCasting(true) } @objc public func loadMedia(with media: SambaMedia, currentTime: CLong = 0, captionTheme: String? = nil, completion: @escaping (SambaCastCompletionType, Error?) -> Void) { guard hasCastSession() else { return } let castModel = CastModel.castModelFrom(media: media, currentTime: currentTime, captionTheme: captionTheme) guard let jsonCastModel = castModel.toStringJson() else { return } let metadata = GCKMediaMetadata(metadataType: .movie) metadata.setString(media.title, forKey: kGCKMetadataKeyTitle) if let thumbUrlString = media.thumbURL, let thumbUrl = URL(string: thumbUrlString) { let image = GCKImage(url: thumbUrl, width: 720, height: 480) metadata.addImage(image) } currentMedia = media currentCaptionTheme = captionTheme if getPersistedCurrentMedia() != castModel.m { let mediaInfo = GCKMediaInformation(contentID: jsonCastModel, streamType: .buffered, contentType: "video/mp4", metadata: metadata, streamDuration: TimeInterval(media.duration), mediaTracks: nil, textTrackStyle: nil, customData: nil) let builder = GCKMediaQueueItemBuilder() builder.mediaInformation = mediaInfo builder.autoplay = false let item = builder.build() let request = GCKCastContext.sharedInstance().sessionManager.currentCastSession?.remoteMediaClient?.queueLoad([item], start: 0, playPosition: 0, repeatMode: .off, customData: nil) sambaCastRequest.set { [weak self] error in guard let strongSelf = self else { return } guard error == nil else { completion(.error, error) return } strongSelf.persistCurrentMedia(id: castModel.m!) completion(.loaded, nil) } request?.delegate = sambaCastRequest } else { completion(.resumed, nil) } } //MARK: - Internal Methods func replayCast() { guard let media = currentMedia else { return } clearCaches() loadMedia(with: media, currentTime: 0, captionTheme: currentCaptionTheme) { [weak self] (sambaCastCompletionType, error) in guard let strongSelf = self else {return} strongSelf.pauseCast() } } func playCast() { let message = "{\"type\": \"play\"}" sendRequest(with: message); } func pauseCast() { let message = "{\"type\": \"pause\"}" sendRequest(with: message); } func seek(to position: CLong) { let message = "{\"type\": \"seek\", \"data\": \(position) }" sendRequest(with: message); } func changeSubtitle(to language: String?) { let data: String! if let mLanguage = language?.lowercased().replacingOccurrences(of: "_", with: "-"), !mLanguage.isEmpty { data = "{\"lang\": \"\(mLanguage)\"}" } else { data = "{\"lang\": \"none\"}" } let message = "{\"type\": \"changeSubtitle\", \"data\": \(data!) }" sendRequest(with: message) } func changeSpeed(to speed: Float?) { let data: String! if let mSpeed = speed { data = "{\"times\": \(mSpeed)}" } else { data = "{\"times\": \(1.0)}" } let message = "{\"type\": \"changeSpeed\", \"data\": \(data!) }" sendRequest(with: message) } func registerDeviceForProgress(enable: Bool) { let message = "{\"type\": \"registerForProgressUpdate\", \"data\": \(enable) }" sendRequest(with: message) } //MARK: - Private Methods private func setupCastLogging() { let logFilter = GCKLoggerFilter() let classesToLog = ["GCKDeviceScanner", "GCKDeviceProvider", "GCKDiscoveryManager", "GCKCastChannel", "GCKMediaControlChannel", "GCKUICastButton", "GCKUIMediaController", "NSMutableDictionary"] logFilter.setLoggingLevel(.verbose, forClasses: classesToLog) GCKLogger.sharedInstance().filter = logFilter GCKLogger.sharedInstance().delegate = self } fileprivate func onCastSessionConnected() { enableChannel() enableChannelForReceiveMessages() internalDelegates.forEach({$0.onCastConnected?()}) delegates.forEach({$0.onCastConnected?()}) } fileprivate func onCastSessionResumed() { enableChannel() enableChannelForReceiveMessages() internalDelegates.forEach({$0.onCastResumed?()}) delegates.forEach({$0.onCastResumed?()}) } fileprivate func onCastSessionDisconnected() { currentMedia = nil currentCaptionTheme = nil disableChannel() clearCaches() internalDelegates.forEach({$0.onCastDisconnected?()}) delegates.forEach({$0.onCastDisconnected?()}) } private func hasCastSession() -> Bool { guard let currentCastSession = GCKCastContext.sharedInstance().sessionManager.currentCastSession else { return false } guard currentCastSession.connectionState == .connected else { return false } return true } private func sendRequest(with message: String) { if hasCastSession() { channel?.sendTextMessage(message, error: nil) } } private func enableChannel() { if channel == nil && hasCastSession() { channel = SambaCastChannel(namespace: Helpers.settings["cast_namespace_prod"]!) GCKCastContext.sharedInstance().sessionManager.currentCastSession?.add(channel!) } } private func disableChannel() { if channel != nil { GCKCastContext.sharedInstance().sessionManager.currentCastSession?.remove(channel!) channel?.delegate = nil channel = nil } } //MARK: - Helpers private func enableChannelForReceiveMessages() { registerDeviceForProgress(enable: true) channel?.delegate = self } private func persistCurrentMedia(id: String) { UserDefaults.standard.set(id, forKey: "media_id") } private func persistCurrentCastState(state: SambaCastPlaybackState) { UserDefaults.standard.set(state.rawValue, forKey: "cast_state") } private func getCurrentCastState() -> SambaCastPlaybackState { guard let state = UserDefaults.standard.object(forKey: "cast_state") as? String else { return .empty } return SambaCastPlaybackState(rawValue: state) ?? .empty } private func getPersistedCurrentMedia() -> String? { return UserDefaults.standard.string(forKey: "media_id") } func clearCaches() { UserDefaults.standard.removeObject(forKey: "cast_state") UserDefaults.standard.removeObject(forKey: "media_id") } //MARK: - Observers @objc private func castDeviceDidChange() { if let mButton = self.buttonForIntrucions, GCKCastContext.sharedInstance().castState != .noDevicesAvailable { GCKCastContext.sharedInstance().presentCastInstructionsViewControllerOnce(with: mButton) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.gckCastStateDidChange, object: GCKCastContext.sharedInstance()) self.buttonForIntrucions = nil } } @objc private func castDialogWillShow() { isCastDialogShowing = true } @objc private func castDialogDidHide() { isCastDialogShowing = false } } //MARK: - Extensions extension SambaCast: GCKLoggerDelegate { public func logMessage(_ message: String, fromFunction function: String) { if enableSDKLogging { print("\(function) \(message)") } } } extension SambaCast: GCKUIImagePicker { public func getImageWith(_ imageHints: GCKUIImageHints, from metadata: GCKMediaMetadata) -> GCKImage? { let images = metadata.images guard !images().isEmpty else { print("No images available in media metadata."); return nil } if images().count > 1 && imageHints.imageType == .background { return images()[1] as? GCKImage } else { return images()[0] as? GCKImage } } } extension SambaCast: GCKSessionManagerListener { public func sessionManager(_ sessionManager: GCKSessionManager, didStart session: GCKSession) { print("sessionManager didStartSession \(session)") onCastSessionConnected() } public func sessionManager(_ sessionManager: GCKSessionManager, didResumeSession session: GCKSession) { print("SessionManager didResumeSession \(session)") onCastSessionResumed() } public func sessionManager(_ sessionManager: GCKSessionManager, didEnd session: GCKSession, withError error: Error?) { print("Session ended with error: \(String(describing: error))") onCastSessionDisconnected() } public func sessionManager(_ sessionManager: GCKSessionManager, didFailToStartSessionWithError error: Error?) { if let error = error { print("Session fail to start with error: \(String(describing: error))") } onCastSessionDisconnected() } public func sessionManager(_ sessionManager: GCKSessionManager, didFailToResumeSession session: GCKSession, withError error: Error?) { print("Session fail to resume with error: \(String(describing: error))") onCastSessionDisconnected() } } extension SambaCast: SambaCastChannelDelegate { func didReceiveMessage(message: String) { guard let jsonDicitonary = Helpers.convertToDictionary(text: message) else { return } if let position = jsonDicitonary["progress"] as? Double, let duration = jsonDicitonary["duration"] as? Double { internalDelegates.forEach({ $0.onCastProgress?(position: CLong(position), duration: CLong(duration))}) delegates.forEach({ $0.onCastProgress?(position: CLong(position), duration: CLong(duration))}) } else if let type = jsonDicitonary["type"] as? String { if type.lowercased().elementsEqual("finish") { internalDelegates.forEach({ $0.onCastFinish?() }) delegates.forEach({ $0.onCastFinish?() }) } } } } //MARK: - Protocols @objc public protocol SambaCastDelegate: class { @objc optional func onCastConnected() @objc optional func onCastResumed() @objc optional func onCastDisconnected() @objc optional func onCastPlay() @objc optional func onCastPause() @objc optional func onCastProgress(position: CLong, duration: CLong) @objc optional func onCastFinish() } //MARK: - Enums @objc public enum SambaCastCompletionType: Int { case loaded case resumed case error } public enum SambaCastPlaybackState: String { case empty case playing case paused case finished }
mit
556c7fa9dd25247677f9b8ab8dfe4047
33.706935
175
0.606098
4.993241
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Models/Prompts/Announcement.swift
1
10434
// // Announcement.swift // breadwallet // // Created by Ray Vander Veen on 2019-02-21. // Copyright © 2019 Breadwinner AG. All rights reserved. // import Foundation // Announcements are special types of prompts that are provided by the /announcemnts API. enum AnnouncementType: String { // General announcement without user input. case announcement // Announcement that can obtain an email address from the user for a mailing list subscription. case announcementEmail = "announcement-email" // A promotional announcement. case announcementPromo = "announcement-promo" } /** * Represents an action that can be displayed as part of an announcement prompt. */ struct AnnouncementAction: Decodable { enum Keys: String, CodingKey { case title case titleKey case url } // English title text for the action. var title: String? // Key for localized title. var titleKey: String? // URL to be invoked in response to the action. var url: String? // Text to be displayed as a button title, either the raw title or a localized string based // on the title key. var titleText: String { if let key = titleKey { return NSLocalizedString(key, comment: "") } else if let title = title { return title } return "" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) do { title = try container.decodeIfPresent(String.self, forKey: .title) titleKey = try container.decodeIfPresent(String.self, forKey: .titleKey) url = try container.decodeIfPresent(String.self, forKey: .url) } catch { // missing element } } } /** * Represents a page in a single or multi-page announcement entity returned from the /announcements API endpoint. */ struct AnnouncementPage: Decodable { enum Keys: String, CodingKey { case title case titleKey case body case bodyKey case footnote case footnoteKey case imageName case imageUrl case emailList case actions } // English title text. var title: String? // Key for a localized title. var titleKey: String? // English body text. var body: String? // Key for a localized body. var bodyKey: String? // English footnote text. var footnote: String? // Key for a localized footnote. var footnoteKey: String? // Name of image asset included in our asset catalog. var imageName: String? // URL for a downloadable image that may be used if 'imageName' is not available. var imageUrl: String? // Name of a mailing list to be used if this announcement if of type 'announcement-email'. var emailList: String? // Actions associated with this announcement page. var actions: [AnnouncementAction]? init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) do { title = try container.decodeIfPresent(String.self, forKey: .title) titleKey = try container.decodeIfPresent(String.self, forKey: .titleKey) body = try container.decodeIfPresent(String.self, forKey: .body) bodyKey = try container.decodeIfPresent(String.self, forKey: .bodyKey) footnote = try container.decodeIfPresent(String.self, forKey: .footnote) footnoteKey = try container.decodeIfPresent(String.self, forKey: .footnoteKey) imageName = try container.decodeIfPresent(String.self, forKey: .imageName) imageUrl = try container.decodeIfPresent(String.self, forKey: .imageUrl) emailList = try container.decodeIfPresent(String.self, forKey: .emailList) actions = try container.decodeIfPresent([AnnouncementAction].self, forKey: .actions) } catch { assert(false, "missing Announcement page element") } } } /** * Represents an announcement entity returned from the `/announcements` API endpoint. * * An announcement typically displays a title, body, and may include an email address * input field or a CTA that invokes a URL. */ struct Announcement: Decodable { // N.B. Add supported types here otherwise they will be ignored by PromptFactory. static var supportedTypes: [String] { return [AnnouncementType.announcementEmail.rawValue, AnnouncementType.announcementPromo.rawValue] } enum Keys: String, CodingKey { case id = "slug" // the server sends 'slug' but we'll call it 'id' case type case pages } static let hasShownKeyPrefix = "has-shown-prompt-" var id: String? var type: String? var pages: [AnnouncementPage]? // default initializer to help unit testing init() {} init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) do { id = try container.decode(String.self, forKey: .id) type = try container.decode(String.self, forKey: .type) pages = try container.decodeIfPresent([AnnouncementPage].self, forKey: .pages) } catch { // missing element assert(false, "missing Announcement element") } } var isSupported: Bool { return Announcement.supportedTypes.contains(self.type ?? "") } var isGetEmailAnnouncement: Bool { return self.type == AnnouncementType.announcementEmail.rawValue } func page(at step: PromptPageStep) -> AnnouncementPage? { if let pages = pages, !pages.isEmpty && step.step < pages.count { return pages[step.rawValue] } return nil } var title: String { return title(for: .initialDisplay) } var body: String { return body(for: .initialDisplay) } var footnote: String { return footnote(for: .initialDisplay) } var imageName: String? { if let page = page(at: .initialDisplay), let imageName = page.imageName { return imageName } return nil } private var showHideKey: String { return Announcement.hasShownKeyPrefix + (self.id ?? "") } func shouldPrompt(walletAuthenticator: WalletAuthenticator?) -> Bool { // If didPrompt() has not been called for our id, this defaults to false. return !UserDefaults.standard.bool(forKey: self.showHideKey) } func didPrompt() { // Record that we displayed the announcement prompt with our unique 'id' as key so that it's not shown again. UserDefaults.standard.set(true, forKey: self.showHideKey) } func actions(for step: PromptPageStep) -> [AnnouncementAction]? { if let page = page(at: .initialDisplay) { return page.actions } return nil } // MARK: convenience functions func title(for step: PromptPageStep) -> String { if let page = page(at: step) { if let key = page.titleKey { return NSLocalizedString(key, comment: "") } else if let title = page.title { return title } } return "" } func body(for step: PromptPageStep) -> String { if let page = page(at: step) { if let key = page.bodyKey { return NSLocalizedString(key, comment: "") } else if let body = page.body { return body } } return "" } func footnote(for step: PromptPageStep) -> String { if let page = page(at: step) { if let key = page.footnoteKey { return NSLocalizedString(key, comment: "") } else if let footnote = page.footnote { return footnote } } return "" } func imageName(for step: PromptPageStep) -> String? { if let page = page(at: step), let name = page.imageName { return name } return nil } } /** * Protocol for prompts that are based on an announcement entity returned from the /announcements API endpoint. */ protocol AnnouncementBasedPrompt: Prompt { var announcement: Announcement { get } } /** * Announcement-based prompt default implementation. */ extension AnnouncementBasedPrompt { var order: Int { return PromptType.announcement.order } var title: String { return announcement.title } var body: String { return announcement.body } var footnote: String? { return announcement.footnote } var imageName: String? { return announcement.imageName } func shouldPrompt(walletAuthenticator: WalletAuthenticator?) -> Bool { return announcement.shouldPrompt(walletAuthenticator: walletAuthenticator) } func didPrompt() { announcement.didPrompt() } } /** * A Prompt that is based on an announcement object returned from the /announcements API endpoint. */ struct StandardAnnouncementPrompt: AnnouncementBasedPrompt { let announcement: Announcement init(announcement: Announcement) { self.announcement = announcement } } /** * A prompt based on an announcement that can obtain an email address from the user. */ struct AnnouncementBasedEmailCollectingPrompt: AnnouncementBasedPrompt, EmailCollectingPrompt { let announcement: Announcement init(announcement: Announcement) { self.announcement = announcement } // MARK: EmailCollecting var confirmationTitle: String { return announcement.title(for: .confirmation) } var confirmationBody: String { return announcement.body(for: .confirmation) } var confirmationFootnote: String? { return nil } var confirmationImageName: String? { return announcement.imageName(for: .confirmation) } var emailList: String? { if let page = announcement.page(at: .initialDisplay), let list = page.emailList { return list } return nil } func didSubscribe() { } }
mit
bb56920389e09e01b0cb65040a6c3b37
28.388732
117
0.621298
4.708032
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableviewCells/Challenges/ChallengeDescriptionTableViewCell.swift
1
2571
// // ChallengeDescriptionTableViewCell.swift // Habitica // // Created by Elliot Schrock on 10/25/17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import Down import Habitica_Models class ChallengeDescriptionTableViewCell: ResizableTableViewCell, ChallengeConfigurable { @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var caretButton: UIButton! @IBOutlet weak var marginConstraint: NSLayoutConstraint! private var heightConstraint: NSLayoutConstraint? private var isExpanded = true override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(with challenge: ChallengeProtocol) { if let notes = challenge.notes { descriptionLabel.attributedText = try? Down(markdownString: notes.unicodeEmoji).toHabiticaAttributedString(baseSize: descriptionLabel.font.pointSize) } } func expand() { rotateCaret() marginConstraint.constant = 8 if let constraint = self.heightConstraint { descriptionLabel.removeConstraint(constraint) } resizingDelegate?.cellResized() } func collapse() { rotateCaret() self.marginConstraint.constant = 0 if heightConstraint == nil, let label = descriptionLabel { heightConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.height, relatedBy: .equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 0) } if let constraint = self.heightConstraint { descriptionLabel.addConstraint(constraint) } UIView.animate(withDuration: 0.25) {[weak self] in self?.contentView.updateLayout() } resizingDelegate?.cellResized() } func rotateCaret() { caretButton.isEnabled = false UIView.animate(withDuration: 0.25, animations: {[weak self] in let angle = self?.isExpanded == true ? 0 : CGFloat.pi self?.caretButton.transform = CGAffineTransform(rotationAngle: angle) }, completion: {[weak self] _ in self?.caretButton.isEnabled = true }) } @IBAction func caretPressed(_ sender: Any) { isExpanded = !isExpanded if isExpanded { expand() } else { collapse() } } }
gpl-3.0
2458167dbf45e6ddcbad08dd49bf7fd9
29.595238
161
0.618677
5.444915
false
false
false
false
twobitlabs/Nimble
Sources/Nimble/Matchers/SatisfyAllOf.swift
27
3143
import Foundation /// A Nimble matcher that succeeds when the actual value matches with all of the matchers /// provided in the variable list of matchers. public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T> where U: Matcher, U.ValueType == T { return satisfyAllOf(matchers.map { $0.predicate }) } internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> { return Predicate.define { actualExpression in var postfixMessages = [String]() var matches = true for predicate in predicates { let result = try predicate.satisfies(actualExpression) if result.toBoolean(expectation: .toNotMatch) { matches = false } postfixMessages.append("{\(result.message.expectedMessage)}") } var msg: ExpectationMessage if let actualValue = try actualExpression.evaluate() { msg = .expectedCustomValueTo( "match all of: " + postfixMessages.joined(separator: ", and "), "\(actualValue)" ) } else { msg = .expectedActualValueTo( "match all of: " + postfixMessages.joined(separator: ", and ") ) } return PredicateResult(bool: matches, message: msg) } } public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> { return satisfyAllOf(left, right) } #if canImport(Darwin) extension NMBObjCMatcher { @objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate { return NMBPredicate { actualExpression in if matchers.isEmpty { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( fail: "satisfyAllOf must be called with at least one matcher" ) ) } var elementEvaluators = [Predicate<NSObject>]() for matcher in matchers { let elementEvaluator = Predicate<NSObject> { expression in if let predicate = matcher as? NMBPredicate { // swiftlint:disable:next line_length return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift() } else { let failureMessage = FailureMessage() let success = matcher.matches( // swiftlint:disable:next force_try { try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location ) return PredicateResult(bool: success, message: failureMessage.toExpectationMessage()) } } elementEvaluators.append(elementEvaluator) } return try satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC() } } } #endif
apache-2.0
31eea18c41fd27d4ad0aee8158b9795c
38.2875
128
0.56252
5.602496
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressTest/TestUtilities/JSONLoader.swift
1
1560
import Foundation @objc open class JSONLoader: NSObject { public typealias JSONDictionary = Dictionary<String, AnyObject> /** * @brief Loads the specified json file name and returns a dictionary representing it. * * @param path The path of the json file to load. * * @returns A dictionary representing the contents of the json file. */ open func loadFile(_ name: String, type: String) -> JSONDictionary? { let path = Bundle(for: Swift.type(of: self)).path(forResource: name, ofType: type) if let unwrappedPath = path { return loadFile(unwrappedPath) } else { return nil } } /** * @brief Loads the specified json file name and returns a dictionary representing it. * * @param path The path of the json file to load. * * @returns A dictionary representing the contents of the json file. */ open func loadFile(_ path: String) -> JSONDictionary? { if let contents = try? Data(contentsOf: URL(fileURLWithPath: path)) { return parseData(contents) } return nil } fileprivate func parseData(_ data: Data) -> JSONDictionary? { let options: JSONSerialization.ReadingOptions = [.mutableContainers, .mutableLeaves] do { let parseResult = try JSONSerialization.jsonObject(with: data as Data, options: options) return parseResult as? JSONDictionary } catch { return nil } } }
gpl-2.0
f1d0997b1caf382b302a7ee843389f16
29.588235
100
0.609615
4.785276
false
false
false
false
kenada/advent-of-code
src/2015/day 2.swift
1
2858
// // day 2.swift // Advent of Code 2015 // // Copyright © 2015–2016 Randy Eckenrode // // 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 AdventSupport import Foundation struct Box { var length: Int var width: Int var height: Int var surfaceArea: Int { return 2 * (length * width + length * height + width * height) } var volume: Int { return length * width * height } } extension Box { var slack: Int { return min(length * width, length * height, width * height) } var ribbonLength: Int { return min(2 * length + 2 * width, 2 * length + 2 * height, 2 * width + 2 * height) } } func parse(string: String) -> [Box] { let rawData = string.characters.split(separator: "\n") return rawData .lazy .map { (line) -> Box? in let dims = line.split(separator: "x") if dims.count != 3 { return nil } let components = dims.map { Int(String($0)) } guard let l = components[0], let w = components[1], let h = components[2] else { return nil } return Box(length: l, width: w, height: h) } .filter { $0 != nil } .map { $0! } } // MARK: - Solution class Day2: Solution { required init() {} var name = "Day 2" func part1(input: String) { let boxes = parse(string: input) let sqFeet = boxes.reduce(0) { $0 + $1.surfaceArea + $1.slack } print("The elves should order \(sqFeet) square feet of wrapping paper.") } func part2(input: String) { let boxes = parse(string: input) let ribbonLength = boxes.reduce(0) { $0 + $1.ribbonLength + $1.volume } print("The elves should order \(ribbonLength) feet of ribbon.") } }
mit
a1af56636d58144744cacfe12ad2f4cb
31.078652
92
0.628722
3.965278
false
false
false
false
zehrer/SOGraphDB
Sources/SOGraphDB/Frontend/Node.swift
1
9642
// // Node.swift // SOGraphDB-Mac // // Created by Stephan Zehrer on 17.11.17. // Copyright © 2017 Stephan Zehrer. All rights reserved. // import Foundation public class Node : Hashable { // TODO: improve basic type sytem // uid = 0 is reserved for instanceOf type static var maxUID : UID = 1 //Equatable public init() { Node.maxUID += 1 self.uid = Node.maxUID } public init(uid: UID) { self.uid = uid Node.maxUID = max(Node.maxUID,uid) } public convenience init(type : Node) { self.init() setType(of: type) } // MARK: OUT // direct access in the insert methode !! lazy var _outRelationships = [Relationship]() public var outRelationships: [Relationship] { get { /** if (_outRelationships == nil) { _outRelationships = [Relationship]() // read data // //assert(graphStore != nil, "No GraphContext available") //TODO ??? } */ return _outRelationships; } } public func outNodes(type : Node? = nil) -> [Node] { var result = [Node]() for rel in _outRelationships { if type != nil { // add only a specifc type to the result /** // TODO if rel.typeNodeID == type!.uid { result.append(rel.endNode) } */ } else { // add all nodes to the result result.append(rel.endNode) } } return result } public var outRelationshipCount: Int { get { return outRelationships.count } } // find out relationship @discardableResult public func outRelationshipTo(endNode: Node) -> Relationship? { assert(graphStore != nil, "No GrapheStore available") return graphStore.findRelationship(from: self, to:endNode) } // Create a new relation add it to the start node (this node) and the end node // This methode update // - create and register a new relationship // - add the relationship to the itself (call insert) // - add the relationship to the end node (call insert) // TODO: the old version the return value was optional, why? @discardableResult public func addOutRelationshipTo(endNode: Node) -> Relationship { assert(graphStore != nil, "No GrapheStore available") let relationship = Relationship(startNode: self, endNode: endNode) // TODO: implement self register graphStore.register(relationship) endNode.insert(inRelationship: relationship) self.insert(outRelationship: relationship) return relationship } // Delete a existing relationship between this node (start node) and the specified end node public func deleteOutRelationshipTo(endNode: Node) { assert(graphStore != nil, "No GrapheStore available") let relationship = self.outRelationshipTo(endNode: endNode) if (relationship != nil) { relationship!.delete() } } /** func delete(outRelationship aRel: Relationship) { let nextRelationshipID = aRelationship.startNodeNextRelationID let previousRelationshipID = aRelationship.startNodePreviousRelationID if (nextRelationshipID > 0) { nextRelationship = context!.readRelationship(nextRelationshipID) nextRelationship.startNodePreviousRelationID = previousRelationshipID // CONTEXT WRITE context!.updateRelationship(nextRelationship) } if (previousRelationshipID > 0) { previousRelationship = context!.readRelationship(previousRelationshipID) previousRelationship.startNodeNextRelationID = nextRelationshipID // CONTEXT WRITE context!.updateRelationship(previousRelationship) } else { // seems this is the first relationship in the chain outRelationshipID = nextRelationshipID // CONTEXT WRITE // update of self is only required if the id was set self.update() } //let index = find(outRelationships, aRelationship)// init outRelationships in worst case let index = outRelationships.indexOf(aRelationship) if let index = index { _outRelationships.removeAtIndex(index) } } */ // Update the outRelationship and notify the graphStore func insert(outRelationship aRel: Relationship) { assert(graphStore != nil, "No GrapheStore available") _outRelationships.append(aRel) // TODO: improve details graphStore.update(self) } // MARK: IN // direct access in the insert methode !! lazy var _inRelationships = [Relationship]() public var inRelationships: [Relationship] { get { /** if (_inRelationships == nil) { _inRelationships = [Relationship]() // read data // //assert(graphStore != nil, "No GraphContext available") //TODO ??? } */ return _inRelationships; } } public var inRelationshipCount: Int { get { return inRelationships.count } } // Create a new relation add it to the start node and the end node (this node) // This methode update // - create and register a new relationship // - add the relationship to the start node (call insert) // - add the relationship to the itself (call insert) public func addInRelationshipFrom(startNode: Node) -> Relationship { assert(graphStore != nil, "No GrapheStore available") let relationship = Relationship(startNode: startNode, endNode: self) // TODO: implement self register graphStore.register(relationship) self.insert(inRelationship: relationship) startNode.insert(outRelationship: relationship) return relationship } // Update the inRelationship and notify the graphStore func insert(inRelationship aRel: Relationship) { assert(graphStore != nil, "No GrapheStore available") _inRelationships.append(aRel) // TODO: improve details graphStore.update(self) } // MARK: - type system public func setType(of type:Node) { let rel = self.addOutRelationshipTo(endNode: type) // TODO //rel.setTypeRelationship() } // Mark: - former Property Element part public var uid: UID! public var graphStore: SOGraphDBStore! public var dirty: Bool = true lazy var properties = [UID : Property]() // MARK: - Hashable public var hashValue: Int { get{ return uid.hashValue } } public static func == (lhs: Node, rhs: Node) -> Bool { return lhs.uid == rhs.uid } // MARK: - public func onAllProperties(_ closure: (Property) -> Void) { for property in properties.values { closure(property) } } public subscript(keyNode: Node) -> Property { get { //assert(context != nil, "No GraphContext available") if let result = properties[keyNode.uid] { return result } else { return createPropertyFor(keyNode) } } } public subscript(keyNodeID : UID) -> Property { get { if let result = properties[keyNodeID] { return result } else { return createPropertyForKeyNode(uid: keyNodeID) } } set(newValue) { properties[keyNodeID] = newValue } } func createPropertyForKeyNode(uid: UID) -> Property { let property = Property(keyNodeID: uid) properties[uid] = property return property } // Create a new property and add it to this element // This methode update // - (optional) the lastProperty -> the property was appended directly // - (optional) the element -> the property was appended // PreConditions: Element is in a context func createPropertyFor(_ keyNode: Node) -> Property { //assert(context != nil, "No GraphContext available") //assert(keyNode.uid != nil, "KeyNode without a uid") //var property = Property(related: self) let property = Property(keyNodeID: keyNode.uid) //property.related = //property.keyNodeID = keyNode.uid! //context.registerProperty(&property) //context.updateProperty(property) //append(&property) properties[keyNode.uid] = property return property } /** public func propertyByKey(_ keyNode: Node) -> Property? { if properties.isEmpty { return nil } return properties[keyNode.uid!] } */ public func propertyByKeyNodeID(uid: UID) -> Property? { return properties[uid] } }
mit
8a40b4f213228e93407eacdef8d82090
28.039157
97
0.561664
4.954265
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/MomentModule/View/CWMomentCell.swift
2
4989
// // CWMomentCell.swift // CWWeChat // // Created by wei chen on 2017/3/30. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import YYText import Kingfisher import RxSwift protocol CWMomentCellDelegate: NSObjectProtocol { func shareCell(_ cell:CWMomentCell, didClickImageAtIndex index:Int) func shareCell(_ cell:CWMomentCell, didClickInText text:NSAttributedString, textRange: NSRange) } class CWMomentCell: UITableViewCell { weak var delegate: CWMomentCellDelegate? var cellLayout: CWMomentLayout? // 头像 lazy var avatarImageView: UIImageView = { let avatarView = UIImageView() return avatarView }() // 用户名 lazy var nameLabel: YYLabel = { let nameLabel = YYLabel() return nameLabel }() // 内容 lazy var contentLabel: YYLabel = { let contentLabel = YYLabel() return contentLabel }() lazy var pictureView: CWMomentPictureView = { let pictureView = CWMomentPictureView() return pictureView }() lazy var multimediaView: CWMomentMultimediaView = { let frame = CGRect(x: 0, y: 0, width: CWMomentUI.kContentWidth, height: 50) let multimediaView = CWMomentMultimediaView(frame: frame) return multimediaView }() lazy var timeLabel: YYLabel = { let timeLabel = YYLabel() return timeLabel }() lazy var toolButton: UIButton = { let toolButton = UIButton(type: .custom) toolButton.setImage(UIImage(named: "share_action"), for: .normal) return toolButton }() // 评论部分 lazy var commmetView: CWMomentCommentView = { let commmetView = CWMomentCommentView() return commmetView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none setupUI() } func setupUI() { // 头像 姓名 self.contentView.addSubview(avatarImageView) self.contentView.addSubview(nameLabel) // 文字 self.contentView.addSubview(contentLabel) self.contentView.addSubview(pictureView) self.contentView.addSubview(multimediaView) self.contentView.addSubview(timeLabel) self.contentView.addSubview(toolButton) self.contentView.addSubview(commmetView) } func setLayout(_ layout: CWMomentLayout) { if layout === cellLayout { return } self.cellLayout = layout let moment = layout.moment // 头像 let avatarURL = URL(string: "\(kImageBaseURLString)\(moment.userId).jpg") self.avatarImageView.kf.setImage(with: avatarURL, placeholder: defaultHeadeImage) self.avatarImageView.frame = layout.avatarFrame // 姓名 self.nameLabel.textLayout = layout.usernameTextLayout self.nameLabel.frame = layout.usernameFrame // 文字 self.contentLabel.textLayout = layout.contentTextLayout self.contentLabel.frame = layout.contentFrame // 先隐藏 self.pictureView.isHidden = true self.multimediaView.isHidden = true // switch moment.type { case .normal: self.pictureView.isHidden = false self.pictureView.setupView(with: layout.multimediaFrame, imageArray: moment.imageArray, pictureSize: layout.pictureSize) break case .url,.music: self.multimediaView.isHidden = false self.multimediaView.frame = layout.multimediaFrame if let multimedia = moment.multimedia { self.multimediaView.contentLabel.text = multimedia.title self.multimediaView.imageView.kf.setImage(with: multimedia.imageURL, placeholder: nil) } break default: break } // 时间和操作 self.toolButton.frame = layout.toolButtonFrame self.timeLabel.textLayout = layout.timeTextLayout self.timeLabel.frame = layout.timeFrame let top: CGFloat = layout.timeFrame.maxY // 点赞和评论列表 let frame = CGRect(x: contentLabel.left, y: top, width: CWMomentUI.kContentWidth, height: layout.commentHeight) self.commmetView.frame = frame } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
8d46528ff88128048b7ef1d37ab68125
28.939024
102
0.617719
4.91
false
false
false
false
embryoconcepts/TIY-Assignments
22 -- DudeCar/DudeCar/DudeCar/PopupViewController.swift
1
3451
// // PopupViewController.swift // DudeCar // // Created by Jennifer Hamilton on 11/3/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreLocation class PopupViewController: UIViewController, CLLocationManagerDelegate, UITextFieldDelegate { @IBOutlet weak var addLocationButton: UIButton! @IBOutlet weak var locationTextField: UITextField! var delegate: PopupViewControllerDelegate? var locationString: String = "" var locations = [Location]() let locationManager = CLLocationManager() let geocoder = CLGeocoder() override func viewDidLoad() { super.viewDidLoad() configureLocationManager() addLocationButton.enabled = false locationTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if locationTextField.text != "" { locationString = textField.text! textField.resignFirstResponder() locationManager.startUpdatingLocation() rc = true } return rc } // MARK: - CLLocation related methods func configureLocationManager() { if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined { locationManager.requestWhenInUseAuthorization() } else { addLocationButton.enabled = true } } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.AuthorizedWhenInUse { addLocationButton.enabled = true } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error.localizedDescription) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last geocoder.reverseGeocodeLocation(location!, completionHandler: {(placemark: [CLPlacemark]?, error: NSError?) -> Void in if error != nil { print(error?.localizedDescription) } else { self.locationManager.stopUpdatingLocation() let name = self.locationString let lat = location?.coordinate.latitude let lng = location?.coordinate.longitude let aLocation = Location(name: name, lat: lat!, lng: lng!) self.locations.append(aLocation) self.delegate?.locationWasAdded(aLocation) } }) } // MARK: - Action Handlers @IBAction func addLocationButtonTapped(sender: UIButton) { locationString = locationTextField.text! locationManager.startUpdatingLocation() } }
cc0-1.0
38eb8de9db619434712ba03d85e25edc
28.237288
161
0.624058
6.25
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MediaTailor/MediaTailor_Shapes.swift
1
31360
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension MediaTailor { // MARK: Enums public enum Mode: String, CustomStringConvertible, Codable { case behindLiveEdge = "BEHIND_LIVE_EDGE" case off = "OFF" public var description: String { return self.rawValue } } public enum OriginManifestType: String, CustomStringConvertible, Codable { case multiPeriod = "MULTI_PERIOD" case singlePeriod = "SINGLE_PERIOD" public var description: String { return self.rawValue } } // MARK: Shapes public struct AdMarkerPassthrough: AWSEncodableShape & AWSDecodableShape { public let enabled: Bool? public init(enabled: Bool? = nil) { self.enabled = enabled } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" } } public struct AvailSuppression: AWSEncodableShape & AWSDecodableShape { public let mode: Mode? /// Sets the mode for avail suppression, also known as ad suppression. By default, ad suppression is off and all ad breaks are filled by MediaTailor with ads or slate. public let value: String? public init(mode: Mode? = nil, value: String? = nil) { self.mode = mode self.value = value } private enum CodingKeys: String, CodingKey { case mode = "Mode" case value = "Value" } } public struct Bumper: AWSEncodableShape & AWSDecodableShape { public let endUrl: String? public let startUrl: String? public init(endUrl: String? = nil, startUrl: String? = nil) { self.endUrl = endUrl self.startUrl = startUrl } private enum CodingKeys: String, CodingKey { case endUrl = "EndUrl" case startUrl = "StartUrl" } } public struct CdnConfiguration: AWSEncodableShape & AWSDecodableShape { /// A non-default content delivery network (CDN) to serve ad segments. By default, AWS Elemental MediaTailor uses Amazon CloudFront with default cache settings as its CDN for ad segments. To set up an alternate CDN, create a rule in your CDN for the following origin: ads.mediatailor.&lt;region>.amazonaws.com. Then specify the rule's name in this AdSegmentUrlPrefix. When AWS Elemental MediaTailor serves a manifest, it reports your CDN as the source for ad segments. public let adSegmentUrlPrefix: String? /// A content delivery network (CDN) to cache content segments, so that content requests don’t always have to go to the origin server. First, create a rule in your CDN for the content segment origin server. Then specify the rule's name in this ContentSegmentUrlPrefix. When AWS Elemental MediaTailor serves a manifest, it reports your CDN as the source for content segments. public let contentSegmentUrlPrefix: String? public init(adSegmentUrlPrefix: String? = nil, contentSegmentUrlPrefix: String? = nil) { self.adSegmentUrlPrefix = adSegmentUrlPrefix self.contentSegmentUrlPrefix = contentSegmentUrlPrefix } private enum CodingKeys: String, CodingKey { case adSegmentUrlPrefix = "AdSegmentUrlPrefix" case contentSegmentUrlPrefix = "ContentSegmentUrlPrefix" } } public struct DashConfiguration: AWSDecodableShape { /// The URL generated by MediaTailor to initiate a playback session. The session uses server-side reporting. This setting is ignored in PUT operations. public let manifestEndpointPrefix: String? /// The setting that controls whether MediaTailor includes the Location tag in DASH manifests. MediaTailor populates the Location tag with the URL for manifest update requests, to be used by players that don't support sticky redirects. Disable this if you have CDN routing rules set up for accessing MediaTailor manifests, and you are either using client-side reporting or your players support sticky HTTP redirects. Valid values are DISABLED and EMT_DEFAULT. The EMT_DEFAULT setting enables the inclusion of the tag and is the default value. public let mpdLocation: String? /// The setting that controls whether MediaTailor handles manifests from the origin server as multi-period manifests or single-period manifests. If your origin server produces single-period manifests, set this to SINGLE_PERIOD. The default setting is MULTI_PERIOD. For multi-period manifests, omit this setting or set it to MULTI_PERIOD. public let originManifestType: OriginManifestType? public init(manifestEndpointPrefix: String? = nil, mpdLocation: String? = nil, originManifestType: OriginManifestType? = nil) { self.manifestEndpointPrefix = manifestEndpointPrefix self.mpdLocation = mpdLocation self.originManifestType = originManifestType } private enum CodingKeys: String, CodingKey { case manifestEndpointPrefix = "ManifestEndpointPrefix" case mpdLocation = "MpdLocation" case originManifestType = "OriginManifestType" } } public struct DashConfigurationForPut: AWSEncodableShape { /// The setting that controls whether MediaTailor includes the Location tag in DASH manifests. MediaTailor populates the Location tag with the URL for manifest update requests, to be used by players that don't support sticky redirects. Disable this if you have CDN routing rules set up for accessing MediaTailor manifests, and you are either using client-side reporting or your players support sticky HTTP redirects. Valid values are DISABLED and EMT_DEFAULT. The EMT_DEFAULT setting enables the inclusion of the tag and is the default value. public let mpdLocation: String? /// The setting that controls whether MediaTailor handles manifests from the origin server as multi-period manifests or single-period manifests. If your origin server produces single-period manifests, set this to SINGLE_PERIOD. The default setting is MULTI_PERIOD. For multi-period manifests, omit this setting or set it to MULTI_PERIOD. public let originManifestType: OriginManifestType? public init(mpdLocation: String? = nil, originManifestType: OriginManifestType? = nil) { self.mpdLocation = mpdLocation self.originManifestType = originManifestType } private enum CodingKeys: String, CodingKey { case mpdLocation = "MpdLocation" case originManifestType = "OriginManifestType" } } public struct DeletePlaybackConfigurationRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "name", location: .uri(locationName: "Name")) ] public let name: String public init(name: String) { self.name = name } private enum CodingKeys: CodingKey {} } public struct DeletePlaybackConfigurationResponse: AWSDecodableShape { public init() {} } public struct GetPlaybackConfigurationRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "name", location: .uri(locationName: "Name")) ] public let name: String public init(name: String) { self.name = name } private enum CodingKeys: CodingKey {} } public struct GetPlaybackConfigurationResponse: AWSDecodableShape { /// The URL for the ad decision server (ADS). This includes the specification of static parameters and placeholders for dynamic parameters. AWS Elemental MediaTailor substitutes player-specific and session-specific parameters as needed when calling the ADS. Alternately, for testing, you can provide a static VAST URL. The maximum length is 25,000 characters. public let adDecisionServerUrl: String? /// The configuration for Avail Suppression. public let availSuppression: AvailSuppression? /// The configuration for bumpers. Bumpers are short audio or video clips that play at the start or before the end of an ad break. public let bumper: Bumper? /// The configuration for using a content delivery network (CDN), like Amazon CloudFront, for content and ad segment management. public let cdnConfiguration: CdnConfiguration? /// The configuration for DASH content. public let dashConfiguration: DashConfiguration? /// The configuration for HLS content. public let hlsConfiguration: HlsConfiguration? /// The configuration for pre-roll ad insertion. public let livePreRollConfiguration: LivePreRollConfiguration? /// The configuration for manifest processing rules. Manifest processing rules enable customization of the personalized manifests created by MediaTailor. public let manifestProcessingRules: ManifestProcessingRules? /// The identifier for the playback configuration. public let name: String? /// The maximum duration of underfilled ad time (in seconds) allowed in an ad break. public let personalizationThresholdSeconds: Int? /// The Amazon Resource Name (ARN) for the playback configuration. public let playbackConfigurationArn: String? /// The URL that the player accesses to get a manifest from AWS Elemental MediaTailor. This session will use server-side reporting. public let playbackEndpointPrefix: String? /// The URL that the player uses to initialize a session that uses client-side reporting. public let sessionInitializationEndpointPrefix: String? /// The URL for a high-quality video asset to transcode and use to fill in time that's not used by ads. AWS Elemental MediaTailor shows the slate to fill in gaps in media content. Configuring the slate is optional for non-VPAID playback configurations. For VPAID, the slate is required because MediaTailor provides it in the slots designated for dynamic ad content. The slate must be a high-quality asset that contains both audio and video. public let slateAdUrl: String? /// The tags assigned to the playback configuration. public let tags: [String: String]? /// The name that is used to associate this playback configuration with a custom transcode profile. This overrides the dynamic transcoding defaults of MediaTailor. Use this only if you have already set up custom profiles with the help of AWS Support. public let transcodeProfileName: String? /// The URL prefix for the master playlist for the stream, minus the asset ID. The maximum length is 512 characters. public let videoContentSourceUrl: String? public init(adDecisionServerUrl: String? = nil, availSuppression: AvailSuppression? = nil, bumper: Bumper? = nil, cdnConfiguration: CdnConfiguration? = nil, dashConfiguration: DashConfiguration? = nil, hlsConfiguration: HlsConfiguration? = nil, livePreRollConfiguration: LivePreRollConfiguration? = nil, manifestProcessingRules: ManifestProcessingRules? = nil, name: String? = nil, personalizationThresholdSeconds: Int? = nil, playbackConfigurationArn: String? = nil, playbackEndpointPrefix: String? = nil, sessionInitializationEndpointPrefix: String? = nil, slateAdUrl: String? = nil, tags: [String: String]? = nil, transcodeProfileName: String? = nil, videoContentSourceUrl: String? = nil) { self.adDecisionServerUrl = adDecisionServerUrl self.availSuppression = availSuppression self.bumper = bumper self.cdnConfiguration = cdnConfiguration self.dashConfiguration = dashConfiguration self.hlsConfiguration = hlsConfiguration self.livePreRollConfiguration = livePreRollConfiguration self.manifestProcessingRules = manifestProcessingRules self.name = name self.personalizationThresholdSeconds = personalizationThresholdSeconds self.playbackConfigurationArn = playbackConfigurationArn self.playbackEndpointPrefix = playbackEndpointPrefix self.sessionInitializationEndpointPrefix = sessionInitializationEndpointPrefix self.slateAdUrl = slateAdUrl self.tags = tags self.transcodeProfileName = transcodeProfileName self.videoContentSourceUrl = videoContentSourceUrl } private enum CodingKeys: String, CodingKey { case adDecisionServerUrl = "AdDecisionServerUrl" case availSuppression = "AvailSuppression" case bumper = "Bumper" case cdnConfiguration = "CdnConfiguration" case dashConfiguration = "DashConfiguration" case hlsConfiguration = "HlsConfiguration" case livePreRollConfiguration = "LivePreRollConfiguration" case manifestProcessingRules = "ManifestProcessingRules" case name = "Name" case personalizationThresholdSeconds = "PersonalizationThresholdSeconds" case playbackConfigurationArn = "PlaybackConfigurationArn" case playbackEndpointPrefix = "PlaybackEndpointPrefix" case sessionInitializationEndpointPrefix = "SessionInitializationEndpointPrefix" case slateAdUrl = "SlateAdUrl" case tags case transcodeProfileName = "TranscodeProfileName" case videoContentSourceUrl = "VideoContentSourceUrl" } } public struct HlsConfiguration: AWSDecodableShape { /// The URL that is used to initiate a playback session for devices that support Apple HLS. The session uses server-side reporting. public let manifestEndpointPrefix: String? public init(manifestEndpointPrefix: String? = nil) { self.manifestEndpointPrefix = manifestEndpointPrefix } private enum CodingKeys: String, CodingKey { case manifestEndpointPrefix = "ManifestEndpointPrefix" } } public struct ListPlaybackConfigurationsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")) ] public let maxResults: Int? public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListPlaybackConfigurationsResponse: AWSDecodableShape { /// Array of playback configurations. This might be all the available configurations or a subset, depending on the settings that you provide and the total number of configurations stored. public let items: [PlaybackConfiguration]? /// Pagination token returned by the GET list request when results exceed the maximum allowed. Use the token to fetch the next page of results. public let nextToken: String? public init(items: [PlaybackConfiguration]? = nil, nextToken: String? = nil) { self.items = items self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case items = "Items" case nextToken = "NextToken" } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "ResourceArn")) ] public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct LivePreRollConfiguration: AWSEncodableShape & AWSDecodableShape { /// The URL for the ad decision server (ADS) for pre-roll ads. This includes the specification of static parameters and placeholders for dynamic parameters. AWS Elemental MediaTailor substitutes player-specific and session-specific parameters as needed when calling the ADS. Alternately, for testing, you can provide a static VAST URL. The maximum length is 25,000 characters. public let adDecisionServerUrl: String? /// The maximum allowed duration for the pre-roll ad avail. AWS Elemental MediaTailor won't play pre-roll ads to exceed this duration, regardless of the total duration of ads that the ADS returns. public let maxDurationSeconds: Int? public init(adDecisionServerUrl: String? = nil, maxDurationSeconds: Int? = nil) { self.adDecisionServerUrl = adDecisionServerUrl self.maxDurationSeconds = maxDurationSeconds } private enum CodingKeys: String, CodingKey { case adDecisionServerUrl = "AdDecisionServerUrl" case maxDurationSeconds = "MaxDurationSeconds" } } public struct ManifestProcessingRules: AWSEncodableShape & AWSDecodableShape { /// For HLS, when set to true, MediaTailor passes through EXT-X-CUE-IN, EXT-X-CUE-OUT, and EXT-X-SPLICEPOINT-SCTE35 ad markers from the origin manifest to the MediaTailor personalized manifest.No logic is applied to these ad markers. For example, if EXT-X-CUE-OUT has a value of 60, but no ads are filled for that ad break, MediaTailor will not set the value to 0. public let adMarkerPassthrough: AdMarkerPassthrough? public init(adMarkerPassthrough: AdMarkerPassthrough? = nil) { self.adMarkerPassthrough = adMarkerPassthrough } private enum CodingKeys: String, CodingKey { case adMarkerPassthrough = "AdMarkerPassthrough" } } public struct PlaybackConfiguration: AWSDecodableShape { public let adDecisionServerUrl: String? public let cdnConfiguration: CdnConfiguration? public let dashConfiguration: DashConfiguration? public let hlsConfiguration: HlsConfiguration? public let name: String? public let personalizationThresholdSeconds: Int? public let playbackConfigurationArn: String? public let playbackEndpointPrefix: String? public let sessionInitializationEndpointPrefix: String? public let slateAdUrl: String? public let tags: [String: String]? public let transcodeProfileName: String? public let videoContentSourceUrl: String? public init(adDecisionServerUrl: String? = nil, cdnConfiguration: CdnConfiguration? = nil, dashConfiguration: DashConfiguration? = nil, hlsConfiguration: HlsConfiguration? = nil, name: String? = nil, personalizationThresholdSeconds: Int? = nil, playbackConfigurationArn: String? = nil, playbackEndpointPrefix: String? = nil, sessionInitializationEndpointPrefix: String? = nil, slateAdUrl: String? = nil, tags: [String: String]? = nil, transcodeProfileName: String? = nil, videoContentSourceUrl: String? = nil) { self.adDecisionServerUrl = adDecisionServerUrl self.cdnConfiguration = cdnConfiguration self.dashConfiguration = dashConfiguration self.hlsConfiguration = hlsConfiguration self.name = name self.personalizationThresholdSeconds = personalizationThresholdSeconds self.playbackConfigurationArn = playbackConfigurationArn self.playbackEndpointPrefix = playbackEndpointPrefix self.sessionInitializationEndpointPrefix = sessionInitializationEndpointPrefix self.slateAdUrl = slateAdUrl self.tags = tags self.transcodeProfileName = transcodeProfileName self.videoContentSourceUrl = videoContentSourceUrl } private enum CodingKeys: String, CodingKey { case adDecisionServerUrl = "AdDecisionServerUrl" case cdnConfiguration = "CdnConfiguration" case dashConfiguration = "DashConfiguration" case hlsConfiguration = "HlsConfiguration" case name = "Name" case personalizationThresholdSeconds = "PersonalizationThresholdSeconds" case playbackConfigurationArn = "PlaybackConfigurationArn" case playbackEndpointPrefix = "PlaybackEndpointPrefix" case sessionInitializationEndpointPrefix = "SessionInitializationEndpointPrefix" case slateAdUrl = "SlateAdUrl" case tags case transcodeProfileName = "TranscodeProfileName" case videoContentSourceUrl = "VideoContentSourceUrl" } } public struct PutPlaybackConfigurationRequest: AWSEncodableShape { /// The URL for the ad decision server (ADS). This includes the specification of static parameters and placeholders for dynamic parameters. AWS Elemental MediaTailor substitutes player-specific and session-specific parameters as needed when calling the ADS. Alternately, for testing you can provide a static VAST URL. The maximum length is 25,000 characters. public let adDecisionServerUrl: String? /// The configuration for Avail Suppression. public let availSuppression: AvailSuppression? /// The configuration for bumpers. Bumpers are short audio or video clips that play at the start or before the end of an ad break. public let bumper: Bumper? /// The configuration for using a content delivery network (CDN), like Amazon CloudFront, for content and ad segment management. public let cdnConfiguration: CdnConfiguration? /// The configuration for DASH content. public let dashConfiguration: DashConfigurationForPut? /// The configuration for pre-roll ad insertion. public let livePreRollConfiguration: LivePreRollConfiguration? /// The configuration for manifest processing rules. Manifest processing rules enable customization of the personalized manifests created by MediaTailor. public let manifestProcessingRules: ManifestProcessingRules? /// The identifier for the playback configuration. public let name: String? /// The maximum duration of underfilled ad time (in seconds) allowed in an ad break. public let personalizationThresholdSeconds: Int? /// The URL for a high-quality video asset to transcode and use to fill in time that's not used by ads. AWS Elemental MediaTailor shows the slate to fill in gaps in media content. Configuring the slate is optional for non-VPAID configurations. For VPAID, the slate is required because MediaTailor provides it in the slots that are designated for dynamic ad content. The slate must be a high-quality asset that contains both audio and video. public let slateAdUrl: String? /// The tags to assign to the playback configuration. public let tags: [String: String]? /// The name that is used to associate this playback configuration with a custom transcode profile. This overrides the dynamic transcoding defaults of MediaTailor. Use this only if you have already set up custom profiles with the help of AWS Support. public let transcodeProfileName: String? /// The URL prefix for the master playlist for the stream, minus the asset ID. The maximum length is 512 characters. public let videoContentSourceUrl: String? public init(adDecisionServerUrl: String? = nil, availSuppression: AvailSuppression? = nil, bumper: Bumper? = nil, cdnConfiguration: CdnConfiguration? = nil, dashConfiguration: DashConfigurationForPut? = nil, livePreRollConfiguration: LivePreRollConfiguration? = nil, manifestProcessingRules: ManifestProcessingRules? = nil, name: String? = nil, personalizationThresholdSeconds: Int? = nil, slateAdUrl: String? = nil, tags: [String: String]? = nil, transcodeProfileName: String? = nil, videoContentSourceUrl: String? = nil) { self.adDecisionServerUrl = adDecisionServerUrl self.availSuppression = availSuppression self.bumper = bumper self.cdnConfiguration = cdnConfiguration self.dashConfiguration = dashConfiguration self.livePreRollConfiguration = livePreRollConfiguration self.manifestProcessingRules = manifestProcessingRules self.name = name self.personalizationThresholdSeconds = personalizationThresholdSeconds self.slateAdUrl = slateAdUrl self.tags = tags self.transcodeProfileName = transcodeProfileName self.videoContentSourceUrl = videoContentSourceUrl } public func validate(name: String) throws { try self.validate(self.personalizationThresholdSeconds, name: "personalizationThresholdSeconds", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case adDecisionServerUrl = "AdDecisionServerUrl" case availSuppression = "AvailSuppression" case bumper = "Bumper" case cdnConfiguration = "CdnConfiguration" case dashConfiguration = "DashConfiguration" case livePreRollConfiguration = "LivePreRollConfiguration" case manifestProcessingRules = "ManifestProcessingRules" case name = "Name" case personalizationThresholdSeconds = "PersonalizationThresholdSeconds" case slateAdUrl = "SlateAdUrl" case tags case transcodeProfileName = "TranscodeProfileName" case videoContentSourceUrl = "VideoContentSourceUrl" } } public struct PutPlaybackConfigurationResponse: AWSDecodableShape { public let adDecisionServerUrl: String? public let availSuppression: AvailSuppression? public let bumper: Bumper? public let cdnConfiguration: CdnConfiguration? public let dashConfiguration: DashConfiguration? public let hlsConfiguration: HlsConfiguration? public let livePreRollConfiguration: LivePreRollConfiguration? public let manifestProcessingRules: ManifestProcessingRules? public let name: String? public let playbackConfigurationArn: String? public let playbackEndpointPrefix: String? public let sessionInitializationEndpointPrefix: String? public let slateAdUrl: String? public let tags: [String: String]? public let transcodeProfileName: String? public let videoContentSourceUrl: String? public init(adDecisionServerUrl: String? = nil, availSuppression: AvailSuppression? = nil, bumper: Bumper? = nil, cdnConfiguration: CdnConfiguration? = nil, dashConfiguration: DashConfiguration? = nil, hlsConfiguration: HlsConfiguration? = nil, livePreRollConfiguration: LivePreRollConfiguration? = nil, manifestProcessingRules: ManifestProcessingRules? = nil, name: String? = nil, playbackConfigurationArn: String? = nil, playbackEndpointPrefix: String? = nil, sessionInitializationEndpointPrefix: String? = nil, slateAdUrl: String? = nil, tags: [String: String]? = nil, transcodeProfileName: String? = nil, videoContentSourceUrl: String? = nil) { self.adDecisionServerUrl = adDecisionServerUrl self.availSuppression = availSuppression self.bumper = bumper self.cdnConfiguration = cdnConfiguration self.dashConfiguration = dashConfiguration self.hlsConfiguration = hlsConfiguration self.livePreRollConfiguration = livePreRollConfiguration self.manifestProcessingRules = manifestProcessingRules self.name = name self.playbackConfigurationArn = playbackConfigurationArn self.playbackEndpointPrefix = playbackEndpointPrefix self.sessionInitializationEndpointPrefix = sessionInitializationEndpointPrefix self.slateAdUrl = slateAdUrl self.tags = tags self.transcodeProfileName = transcodeProfileName self.videoContentSourceUrl = videoContentSourceUrl } private enum CodingKeys: String, CodingKey { case adDecisionServerUrl = "AdDecisionServerUrl" case availSuppression = "AvailSuppression" case bumper = "Bumper" case cdnConfiguration = "CdnConfiguration" case dashConfiguration = "DashConfiguration" case hlsConfiguration = "HlsConfiguration" case livePreRollConfiguration = "LivePreRollConfiguration" case manifestProcessingRules = "ManifestProcessingRules" case name = "Name" case playbackConfigurationArn = "PlaybackConfigurationArn" case playbackEndpointPrefix = "PlaybackEndpointPrefix" case sessionInitializationEndpointPrefix = "SessionInitializationEndpointPrefix" case slateAdUrl = "SlateAdUrl" case tags case transcodeProfileName = "TranscodeProfileName" case videoContentSourceUrl = "VideoContentSourceUrl" } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "ResourceArn")) ] public let resourceArn: String public let tags: [String: String] public init(resourceArn: String, tags: [String: String]) { self.resourceArn = resourceArn self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "ResourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] public let resourceArn: String public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } private enum CodingKeys: CodingKey {} } }
apache-2.0
b211de3e74092dfab5bba4304c265729
55.399281
701
0.700714
5.210701
false
true
false
false
Acidburn0zzz/firefox-ios
Sync/SyncTelemetryUtils.swift
1
12551
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import Storage import SwiftyJSON import SyncTelemetry fileprivate let log = Logger.syncLogger public enum SyncReason: String { case startup = "startup" case scheduled = "scheduled" case backgrounded = "backgrounded" case user = "user" case syncNow = "syncNow" case didLogin = "didLogin" case push = "push" case engineEnabled = "engineEnabled" case clientNameChanged = "clientNameChanged" } public enum SyncPingReason: String { case shutdown = "shutdown" case schedule = "schedule" case idChanged = "idchanged" } public protocol Stats { func hasData() -> Bool } private protocol DictionaryRepresentable { func asDictionary() -> [String: Any] } public struct SyncUploadStats: Stats { var sent: Int = 0 var sentFailed: Int = 0 public func hasData() -> Bool { return sent > 0 || sentFailed > 0 } } extension SyncUploadStats: DictionaryRepresentable { func asDictionary() -> [String: Any] { return [ "sent": sent, "failed": sentFailed ] } } public struct SyncDownloadStats: Stats { var applied: Int = 0 var succeeded: Int = 0 var failed: Int = 0 var newFailed: Int = 0 var reconciled: Int = 0 public func hasData() -> Bool { return applied > 0 || succeeded > 0 || failed > 0 || newFailed > 0 || reconciled > 0 } } extension SyncDownloadStats: DictionaryRepresentable { func asDictionary() -> [String: Any] { return [ "applied": applied, "succeeded": succeeded, "failed": failed, "newFailed": newFailed, "reconciled": reconciled ] } } public struct ValidationStats: Stats, DictionaryRepresentable { let problems: [ValidationProblem] let took: Int64 let checked: Int? public func hasData() -> Bool { return !problems.isEmpty } func asDictionary() -> [String: Any] { var dict: [String: Any] = [ "problems": problems.map { $0.asDictionary() }, "took": took ] if let checked = self.checked { dict["checked"] = checked } return dict } } public struct ValidationProblem: DictionaryRepresentable { let name: String let count: Int func asDictionary() -> [String: Any] { return ["name": name, "count": count] } } public class StatsSession { var took: Int64 = 0 var when: Timestamp? private var startUptimeNanos: UInt64? public func start(when: UInt64 = Date.now()) { self.when = when self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds } public func hasStarted() -> Bool { return startUptimeNanos != nil } public func end() -> Self { guard let startUptime = startUptimeNanos else { assertionFailure("SyncOperationStats called end without first calling start!") return self } // Casting to Int64 should be safe since we're using uptime since boot in both cases. // Convert to milliseconds as stated in the sync ping format took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000 return self } } // Stats about a single engine's sync. public class SyncEngineStatsSession: StatsSession { public var validationStats: ValidationStats? private(set) var uploadStats: SyncUploadStats private(set) var downloadStats: SyncDownloadStats public init(collection: String) { self.uploadStats = SyncUploadStats() self.downloadStats = SyncDownloadStats() } public func recordDownload(stats: SyncDownloadStats) { self.downloadStats.applied += stats.applied self.downloadStats.succeeded += stats.succeeded self.downloadStats.failed += stats.failed self.downloadStats.newFailed += stats.newFailed self.downloadStats.reconciled += stats.reconciled } public func recordUpload(stats: SyncUploadStats) { self.uploadStats.sent += stats.sent self.uploadStats.sentFailed += stats.sentFailed } } extension SyncEngineStatsSession: DictionaryRepresentable { func asDictionary() -> [String: Any] { var dict: [String: Any] = [ "took": took, ] if downloadStats.hasData() { dict["incoming"] = downloadStats.asDictionary() } if uploadStats.hasData() { dict["outgoing"] = [uploadStats.asDictionary()] } if let validation = self.validationStats, validation.hasData() { dict["validation"] = validation.asDictionary() } return dict } } // Stats and metadata for a sync operation. public class SyncOperationStatsSession: StatsSession { public let why: SyncReason public var uid: String? public var deviceID: String? fileprivate let didLogin: Bool public init(why: SyncReason, uid: String, deviceID: String?) { self.why = why self.uid = uid self.deviceID = deviceID self.didLogin = (why == .didLogin) } } extension SyncOperationStatsSession: DictionaryRepresentable { func asDictionary() -> [String: Any] { let whenValue = when ?? 0 return [ "when": whenValue, "took": took, "didLogin": didLogin, "why": why.rawValue ] } } public enum SyncPingError: MaybeErrorType { case failedToRestoreScratchpad case emptyPing public var description: String { switch self { case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs" case .emptyPing: return "Can't send ping without events or syncs" } } } public enum SyncPingFailureReasonName: String { case httpError = "httperror" case unexpectedError = "unexpectederror" case sqlError = "sqlerror" case otherError = "othererror" } public protocol SyncPingFailureFormattable { var failureReasonName: SyncPingFailureReasonName { get } } public struct SyncPing: SyncTelemetryPing { public private(set) var payload: JSON static func pingFields(prefs: Prefs, why: SyncPingReason) -> Deferred<Maybe<(token: TokenServerToken, fields: [String: Any])>> { // Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for // our ping's identifiers return RustFirefoxAccounts.shared.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kSync) in let scratchpadPrefs = prefs.branch("sync.scratchpad") guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) else { return deferMaybe(SyncPingError.failedToRestoreScratchpad) } let ping: [String: Any] = pingCommonData( why: why, hashedUID: token.hashedFxAUID, hashedDeviceID: (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString ) return deferMaybe((token, ping)) } } public static func from(result: SyncOperationResult, remoteClientsAndTabs: RemoteClientsAndTabs, prefs: Prefs, why: SyncPingReason) -> Deferred<Maybe<SyncPing>> { return pingFields(prefs: prefs, why: why) >>== { (token, fields) in var ping = fields // TODO: We don't cache our sync pings so if it fails, it fails. Once we add // some kind of caching we'll want to make sure we don't dump the events if // the ping has failed. let events = Event.takeAll(fromPrefs: prefs).map { $0.toArray() } ping["events"] = events return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in // TODO: Split the sync ping metadata from storing a single sync. ping["syncs"] = [syncDict] return deferMaybe(SyncPing(payload: JSON(ping))) } } } public static func fromQueuedEvents(prefs: Prefs, why: SyncPingReason) -> Deferred<Maybe<SyncPing>> { if !Event.hasQueuedEvents(inPrefs: prefs) { return deferMaybe(SyncPingError.emptyPing) } return pingFields(prefs: prefs, why: why) >>== { (_, fields) in var ping = fields ping["events"] = Event.takeAll(fromPrefs: prefs).map { $0.toArray() } return deferMaybe(SyncPing(payload: JSON(ping))) } } static func pingCommonData(why: SyncPingReason, hashedUID: String, hashedDeviceID: String) -> [String: Any] { return [ "version": 1, "why": why.rawValue, "uid": hashedUID, "deviceID": hashedDeviceID, "os": [ "name": "iOS", "version": UIDevice.current.systemVersion, "locale": Locale.current.identifier ] ] } // Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping. private static func dictionaryFrom(result: SyncOperationResult, storage: RemoteClientsAndTabs, token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> { return connectedDevices(fromStorage: storage, token: token) >>== { devices in guard let stats = result.stats else { return deferMaybe([String: Any]()) } var dict = stats.asDictionary() if let engineResults = result.engineResults.successValue { dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults) } else if let failure = result.engineResults.failureValue { var errorName: SyncPingFailureReasonName if let formattableFailure = failure as? SyncPingFailureFormattable { errorName = formattableFailure.failureReasonName } else { errorName = .unexpectedError } dict["failureReason"] = [ "name": errorName.rawValue, "error": "\(type(of: failure))", ] } dict["devices"] = devices return deferMaybe(dict) } } // Returns a list of connected devices formatted for use in the 'devices' property in the sync ping. private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs, token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> { func dictionaryFrom(client: RemoteClient) -> [String: Any]? { var device = [String: Any]() if let os = client.os { device["os"] = os } if let version = client.version { device["version"] = version } if let guid = client.guid { device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString } return device } return storage.getClients() >>== { deferMaybe($0.compactMap(dictionaryFrom)) } } private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] { return engineResults.map { result in let (name, status) = result var engine: [String: Any] = [ "name": name ] // For complete/partial results, extract out the collect stats // and add it to engine information. For syncs that were not able to // start, return why and a reason. switch status { case .completed(let stats): engine.merge(with: stats.asDictionary()) case .partial(let stats): engine.merge(with: stats.asDictionary()) case .notStarted(let reason): engine.merge(with: [ "status": reason.telemetryId ]) } return engine } } }
mpl-2.0
a4b5b667a4eae14d51c71a225b77a28c
31.515544
132
0.595729
4.853442
false
false
false
false
hanwanjie853710069/Easy-living
易持家/Class/Class_project/ECAdd/Controller/ELAddressVC.swift
1
1243
// // ELAddressVC.swift // EasyLiving // // Created by 王木木 on 16/5/26. // Copyright © 2016年 王木木. All rights reserved. // import UIKit class ELAddressVC: CMBaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{ lazy var tableView : UITableView = { let tabV = UITableView.init(frame: self.view.bounds, style: .Plain) tabV.delegate = self tabV.dataSource = self tabV.tableFooterView = UIView() tabV.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20) return tabV }() var funcBlock = {(cityids:String ,cityName:String)->() in} let cellid = "cellid" var arrayData :NSMutableArray = [] var arrayTemp :NSMutableArray = [] lazy var searchbar:UISearchBar = { let searc = UISearchBar.init(frame: CGRectMake(0, 0, ScreenWidth, 40)) searc.delegate = self return searc }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "地点" self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.tableView) getData() } }
apache-2.0
88b1d02ef41e35acd8daafdd47f88777
23.48
75
0.61683
4.235294
false
false
false
false
xedin/swift
test/IDE/print_ast_overlay.swift
16
2410
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-module -module-name Foo -o %t -F %S/Inputs/mock-sdk %s -Xfrontend -enable-objc-interop -Xfrontend -disable-objc-attr-requires-foundation-module // // RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo -access-filter-public -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_WITH_OVERLAY -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_NO_INTERNAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo.FooSub -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: %FileCheck %s -check-prefix=PASS_WITHOUT_OVERLAY -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test -print-module -source-filename %s -I %t -F %S/Inputs/mock-sdk -module-to-print=Foo -access-filter-public -annotate-print -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.annotated.txt // RUN: %FileCheck %s -check-prefix=PASS_ANNOTATED -strict-whitespace < %t.annotated.txt // REQUIRES: executable_test // REQUIRES: swift_tools_extra @_exported import Foo public func overlay_func() {} internal func overlay_func_internal() {} public class FooOverlayClassBase { public func f() {} } public class FooOverlayClassDerived : FooOverlayClassBase { override public func f() {} } // Check that given a top-level module with an overlay, AST printer prints // declarations from both of them. // PASS_WITH_OVERLAY-LABEL: {{^}}class FooClassBase { // PASS_WITH_OVERLAY-LABEL: {{^}}class FooOverlayClassDerived : FooOverlayClassBase { // PASS_WITH_OVERLAY-NEXT: {{^}} override func f() // PASS_WITH_OVERLAY: {{^}}func overlay_func(){{$}} // But when printing a submodule, AST printer should not print the overlay, // because overlay declarations are logically in the top-level module. // PASS_WITHOUT_OVERLAY-NOT: overlay_func // PASS_NO_INTERNAL-NOT: overlay_func_internal // PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>Foo</ref>.<ref:module>FooSub</ref></decl> // PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>Foo</ref></decl> // PASS_ANNOTATED: <decl:Import>@_exported import <ref:module>FooHelper</ref></decl>
apache-2.0
95bceba3d7a674250756b96008c44ed5
51.391304
237
0.733195
3.319559
false
true
false
false
Quick/Spry
Source/Spry/Matchers/endWith.swift
1
1240
import Foundation /// A Nimble matcher that succeeds when the actual sequence's last element /// is equal to the expected value. public func endWith<S: Sequence, T: Equatable>(_ endingElement: T) -> Matcher<S> where S.Iterator.Element == T { return Matcher { actualExpression in if let actualValue = try actualExpression.evaluate() { var actualGenerator = actualValue.makeIterator() var lastItem: T? var item: T? repeat { lastItem = item item = actualGenerator.next() } while(item != nil) return lastItem == endingElement } return false } } /// A Nimble matcher that succeeds when the actual string contains the expected substring /// where the expected substring's location is the actual string's length minus the /// expected substring's length. public func endWith(_ endingSubstring: String) -> Matcher<String> { return Matcher { actualExpression in if let collection = try actualExpression.evaluate() { return collection.hasSuffix(endingSubstring) } return false } }
apache-2.0
80e37542bfc2e03982e803a0462689b6
34.428571
89
0.6
5.438596
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/User Interface/Waveform.swift
1
8907
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import QuartzCore #if os(macOS) import AppKit /// NSColor on macOS public typealias CrossPlatformColor = NSColor #else import UIKit /// UIColor when not on macOS public typealias CrossPlatformColor = UIColor #endif /// Container CALayer based class for multiple CAWaveformLayers public class Waveform: CALayer { private var halfWidth: Int = 0 private var reverseDirection: CGFloat = 1 private var plotSize = CGSize(width: 200, height: 20) /// controls whether to use the default CoreAnimation actions or not for property transitions public var allowActions: Bool = true /// Array of waveform layers public private(set) var plots = [WaveformLayer]() /// Number of samples per pixel public private(set) var samplesPerPixel: Int = 0 /// Number of channels public private(set) var channels: Int = 2 /// Minimum height when in stereo public var minimumStereoHeight: CGFloat = 50 /// Whether or not to display as stereo public var showStereo: Bool = true { didSet { updateLayer() } } /// show the negative view as well. false saves space public var isMirrored: Bool = true { didSet { for plot in plots { plot.isMirrored = isMirrored } } } /// Opacity public var waveformOpacity: Float = 1 { didSet { for plot in plots { plot.opacity = waveformOpacity } } } /// Color public var waveformColor: CGColor = CrossPlatformColor.black.cgColor { didSet { for plot in plots { plot.fillColor = waveformColor } } } /// Reverse the waveform public var isReversed: Bool = false { didSet { updateReverse() } } /// display channels backwards, so Right first public var flipStereo: Bool = false { didSet { updateLayer() } } /// Whether or not to mix down to a mono view public var mixToMono: Bool = false { didSet { updateLayer() } } // MARK: - Initialization /// Initialize with parameters /// - Parameters: /// - channels: Channel count /// - size: Rectangular size /// - waveformColor: Foreground color /// - backgroundColor: Background color public convenience init(channels: Int = 2, size: CGSize? = nil, waveformColor: CGColor? = nil, backgroundColor: CGColor? = nil) { self.init() self.channels = channels self.backgroundColor = backgroundColor if let size = size { plotSize = size } // make a default size frame = CGRect(origin: CGPoint(), size: plotSize) self.waveformColor = waveformColor ?? CrossPlatformColor.black.cgColor self.backgroundColor = backgroundColor isOpaque = false initPlots() } deinit { // Log("* { Waveform \(name ?? "") } *") } // MARK: - Private functions // creates plots without data private func initPlots() { let color = waveformColor let leftPlot = createPlot(data: [], color: color) plots.insert(leftPlot, at: 0) addSublayer(leftPlot) // guard !displayAsMono else { return } if channels == 2 { let rightPlot = createPlot(data: [], color: color) plots.insert(rightPlot, at: 1) addSublayer(rightPlot) } } private func updateReverse() { guard !plots.isEmpty else { Log("Waveform isn't ready to be reversed yet. No data.", type: .error) return } let direction: CGFloat = isReversed ? -1.0 : 1.0 // Log("Current Direction:", reverseDirection, "proposed direction:", direction) guard direction != reverseDirection else { return } var xf: CGAffineTransform = .identity xf = xf.scaledBy(x: direction, y: 1) for plot in plots { plot.setAffineTransform(xf) } reverseDirection = direction // Log("REVERSING:", reverseDirection) } private func fillPlots(with data: FloatChannelData, completionHandler: (() -> Void)? = nil) { // just setting the table data here if !plots.isEmpty { if let left = data.first { // Log("** Updating table data", left.count, "points") plots[0].table = left samplesPerPixel = left.count } if data.count > 1, let right = data.last, plots.count > 1 { plots[1].table = right } completionHandler?() return } // create the plots // Log("** Creating plots... channels:", data.count) if let left = data.first { let leftPlot = createPlot(data: left, color: waveformColor) plots.insert(leftPlot, at: 0) addSublayer(leftPlot) samplesPerPixel = left.count } // if the file is stereo add a second plot for the right channel if data.count > 1, let right = data.last { let rightPlot = createPlot(data: right, color: waveformColor) plots.insert(rightPlot, at: 1) addSublayer(rightPlot) } completionHandler?() } private func createPlot(data: [Float], color: CGColor) -> WaveformLayer { // Log(data.count, "plotSize", plotSize) let plot = WaveformLayer(table: data, size: plotSize, fillColor: color, strokeColor: nil, backgroundColor: nil, opacity: waveformOpacity, isMirrored: isMirrored) plot.allowActions = false return plot } // MARK: - Public functions /// controls whether to use the default CoreAnimation actions or not for property transitions override public func action(forKey event: String) -> CAAction? { return allowActions ? super.action(forKey: event) : nil } /// Upodate layers public func updateLayer() { guard plots.isNotEmpty else { Log("Plots are empty... nothing to layout.", type: .error) return } let width = frame.size.width let height = frame.size.height let floatChannels = CGFloat(channels) var heightDivisor = floatChannels if (!showStereo || height < minimumStereoHeight) || mixToMono { heightDivisor = 1 } let adjustedHeight = height / heightDivisor let size = CGSize(width: width, height: adjustedHeight) plotSize = CGSize(width: round(size.width), height: round(size.height)) let leftFrame = CGRect(origin: CGPoint(x: 0, y: heightDivisor == 1 ? 0 : adjustedHeight), size: plotSize) let rightFrame = CGRect(origin: CGPoint(), size: plotSize) plots.first?.frame = flipStereo && plots.count > 1 ? rightFrame : leftFrame plots.first?.updateLayer(with: plotSize) if floatChannels > 1, plots.count > 1 { plots.last?.frame = flipStereo ? leftFrame : rightFrame plots.last?.updateLayer(with: plotSize) } } /// Fill with new data, can be called from any thread /// - Parameter data: Float channel data public func fill(with data: FloatChannelData) { fillPlots(with: data) { DispatchQueue.main.async { if self.isReversed { self.updateReverse() } self.updateLayer() } } } /// Create a copy /// - Returns: New waveform public func duplicate() -> Waveform? { let waveform = Waveform(channels: channels, size: plotSize, waveformColor: waveformColor, backgroundColor: backgroundColor) var data = FloatChannelData(repeating: [], count: plots.count) if let value = plots.first?.table { data[0] = value } if let value = plots.last?.table { data[1] = value } waveform.fill(with: data) waveform.updateLayer() return waveform } /// Remove all plots from view public func dispose() { for plot in plots { plot.removeFromSuperlayer() plot.dispose() } plots.removeAll() removeFromSuperlayer() } }
mit
eb68c37cd8cecdf2bac8ced0b4e57d77
29.399317
100
0.557539
4.929164
false
false
false
false
siriuscn/Alamofire-iOS8
dist/Source/SessionManager.swift
1
33600
// // SessionManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. open class SessionManager { // MARK: - Helper Types /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as /// associated values. /// /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with /// streaming information. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding /// error. public enum MultipartFormDataEncodingResult { case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) case failure(Error) } // MARK: - Properties /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use /// directly for any ad hoc requests. open static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. open static let defaultHTTPHeaders: HTTPHeaders = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` let userAgent: String = { if let info = Bundle.main.infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() let alamofireVersion: String = { guard let afInfo = Bundle(for: SessionManager.self).infoDictionary, let build = afInfo["CFBundleShortVersionString"] else { return "Unknown" } return "Alamofire/\(build)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() /// Default memory threshold used when encoding `MultipartFormData` in bytes. open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 /// The underlying session. open let session: URLSession /// The session delegate handling all the task and session delegate callbacks. open let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. open var startRequestsImmediately: Bool = true /// The request adapter called each time a new request is created. open var adapter: RequestAdapter? /// The request retrier called each time a request encounters an error to determine whether to retry the request. open var retrier: RequestRetrier? { get { return delegate.retrier } set { delegate.retrier = newValue } } /// The background completion handler closure provided by the UIApplicationDelegate /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation /// will automatically call the handler. /// /// If you need to handle your own events before the handler is called, then you need to override the /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. /// /// `nil` by default. open var backgroundCompletionHandler: (() -> Void)? let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) // MARK: - Lifecycle /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter configuration: The configuration used to construct the managed session. /// `URLSessionConfiguration.default` by default. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by /// default. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance. public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter session: The URL session. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionManager = self delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Data Request /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` /// and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult open func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return request(encodedURLRequest) } catch { return request(failedWith: error) } } /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request. /// /// - returns: The created `DataRequest`. open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { do { let originalRequest = try urlRequest.asURLRequest() let originalTask = DataRequest.Requestable(urlRequest: originalRequest) let task = try originalTask.task(session: session, adapter: adapter, queue: queue) let request = DataRequest(session: session, requestTask: .data(originalTask, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return request(failedWith: error) } } // MARK: Private - Request Implementation private func request(failedWith error: Error) -> DataRequest { let request = DataRequest(session: session, requestTask: .data(nil, nil), error: error) if startRequestsImmediately { request.resume() } return request } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, /// `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return download(encodedURLRequest, to: destination) } catch { return download(failedWith: error) } } /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save /// them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try urlRequest.asURLRequest() return download(.request(urlRequest), to: destination) } catch { return download(failedWith: error) } } // MARK: Resume Data /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve /// the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for /// additional information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return download(.resumeData(resumeData), to: destination) } // MARK: Private - Download Implementation private func download( _ downloadable: DownloadRequest.Downloadable, to destination: DownloadRequest.DownloadFileDestination?) -> DownloadRequest { do { let task = try downloadable.task(session: session, adapter: adapter, queue: queue) let request = DownloadRequest(session: session, requestTask: .download(downloadable, task)) request.downloadDelegate.destination = destination delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return download(failedWith: error) } } private func download(failedWith error: Error) -> DownloadRequest { let download = DownloadRequest(session: session, requestTask: .download(nil, nil), error: error) if startRequestsImmediately { download.resume() } return download } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(fileURL, with: urlRequest) } catch { return upload(failedWith: error) } } /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.file(fileURL, urlRequest)) } catch { return upload(failedWith: error) } } // MARK: Data /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(data, with: urlRequest) } catch { return upload(failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.data(data, urlRequest)) } catch { return upload(failedWith: error) } } // MARK: InputStream /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(stream, with: urlRequest) } catch { return upload(failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.stream(stream, urlRequest)) } catch { return upload(failedWith: error) } } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } catch { DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { DispatchQueue.global(qos: .utility).async { let formData = MultipartFormData() multipartFormData(formData) do { var urlRequestWithContentType = try urlRequest.asURLRequest() urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(data, with: urlRequestWithContentType), streamingFromDisk: false, streamFileURL: nil ) DispatchQueue.main.async { encodingCompletion?(encodingResult) } } else { let fileManager = FileManager.default let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) var directoryError: Error? // Create directory inside serial queue to ensure two threads don't do this in parallel self.queue.sync { do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { directoryError = error } } if let directoryError = directoryError { throw directoryError } try formData.writeEncodedData(to: fileURL) DispatchQueue.main.async { let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(fileURL, with: urlRequestWithContentType), streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } } catch { DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } } // MARK: Private - Upload Implementation private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { do { let task = try uploadable.task(session: session, adapter: adapter, queue: queue) let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) if case let .stream(inputStream, _) = uploadable { upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } } delegate[task] = upload if startRequestsImmediately { upload.resume() } return upload } catch { return upload(failedWith: error) } } private func upload(failedWith error: Error) -> UploadRequest { let upload = UploadRequest(session: session, requestTask: .upload(nil, nil), error: error) if startRequestsImmediately { upload.resume() } return upload } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @available(iOS 9.0, *) @discardableResult open func stream(withHostName hostName: String, port: Int) -> StreamRequest { return stream(.stream(hostName: hostName, port: port)) } // MARK: NetService /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @available(iOS 9.0, *) @discardableResult open func stream(with netService: NetService) -> StreamRequest { return stream(.netService(netService)) } // MARK: Private - Stream Implementation @available(iOS 9.0, *) private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { do { let task = try streamable.task(session: session, adapter: adapter, queue: queue) let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return stream(failedWith: error) } } @available(iOS 9.0, *) private func stream(failedWith error: Error) -> StreamRequest { let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) if startRequestsImmediately { stream.resume() } return stream } #endif // MARK: - Internal - Retry Request func retry(_ request: Request) -> Bool { guard let originalTask = request.originalTask else { return false } do { let task = try originalTask.task(session: session, adapter: adapter, queue: queue) request.delegate.task = task // resets all task delegate data request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error return false } } }
mit
c201b2d0bd2600a21c551d56c153f534
42.076923
129
0.630714
5.372562
false
false
false
false
mozilla/Base32
Base32/Base16.swift
1
3409
// // Base16.swift // Base32 // // Created by 野村 憲男 on 2/7/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation // MARK: - Base16 NSData <-> String public func base16Encode(data: NSData, uppercase: Bool = true) -> String { return base16encode(data.bytes, length: data.length, uppercase: uppercase) } public func base16DecodeToData(string: String) -> NSData? { if let array = base16decode(string) { return NSData(bytes: array, length: array.count) } else { return nil } } // MARK: - Base16 [UInt8] <-> String public func base16Encode(array: [UInt8], uppercase: Bool = true) -> String { return base16encode(array, length: array.count, uppercase: uppercase) } public func base16Decode(string: String) -> [UInt8]? { return base16decode(string) } // MARK: extensions extension String { // base16 public var base16DecodedData: NSData? { return base16DecodeToData(self) } public var base16EncodedString: String { return nulTerminatedUTF8.withUnsafeBufferPointer { return base16encode($0.baseAddress, length: $0.count - 1) } } public func base16DecodedString(encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { if let data = self.base16DecodedData { return NSString(data: data, encoding: NSUTF8StringEncoding) as? String } else { return nil } } } extension NSData { // base16 public var base16EncodedString: String { return base16Encode(self) } public var base16EncodedData: NSData { return base16EncodedString.dataUsingUTF8StringEncoding } public var base16DecodedData: NSData? { if let string = NSString(data: self, encoding: NSUTF8StringEncoding) as? String { return base16DecodeToData(string) } else { return nil } } } // MARK: encode private func base16encode(data: UnsafePointer<Void>, length: Int, uppercase: Bool = true) -> String { let array = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data), count: length) return array.map { String(format: uppercase ? "%02X" : "%02x", $0) }.reduce("", combine: +) } // MARK: decode extension UnicodeScalar { private var hexToUInt8: UInt8? { switch self { case "0"..."9": return UInt8(value - UnicodeScalar("0").value) case "a"..."f": return UInt8(value - UnicodeScalar("a").value + 0xa) case "A"..."F": return UInt8(value - UnicodeScalar("A").value + 0xa) default: print("base16decode: Invalid hex character \(self)") return nil } } } private func base16decode(string: String) -> [UInt8]? { // validate length let lenght = string.nulTerminatedUTF8.count - 1 if lenght % 2 != 0 { print("base16decode: String must contain even number of characters") return nil } var g = string.unicodeScalars.generate() var buffer = Array<UInt8>(count: lenght / 2, repeatedValue: 0) var index = 0 while let msn = g.next() { if let msn = msn.hexToUInt8 { if let lsn = g.next()?.hexToUInt8 { buffer[index] = msn << 4 | lsn } else { return nil } } else { return nil } index++ } return buffer }
mit
e62342a870fe2df3d079d0f12034cda3
27.341667
101
0.613643
3.950058
false
false
false
false
Johnykutty/SwiftLint
Source/swiftlint/Helpers/Benchmark.swift
1
1715
// // Benchmark.swift // SwiftLint // // Created by JP Simard on 1/25/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework struct BenchmarkEntry { let id: String // swiftlint:disable:this variable_name let time: Double } struct Benchmark { private let name: String private var entries = [BenchmarkEntry]() init(name: String) { self.name = name } // swiftlint:disable:next variable_name mutating func record(id: String, time: Double) { entries.append(BenchmarkEntry(id: id, time: time)) } mutating func record(file: File, from start: Date) { record(id: file.path ?? "<nopath>", time: -start.timeIntervalSinceNow) } func save() { let string = entries .reduce([String: Double]()) { accu, idAndTime in var accu = accu accu[idAndTime.id] = (accu[idAndTime.id] ?? 0) + idAndTime.time return accu } .sorted { $0.1 < $1.1 } .map { "\(numberFormatter.string(from: NSNumber(value: $0.1))!): \($0.0)" } .joined(separator: "\n") let data = (string + "\n").data(using: .utf8) let url = URL(fileURLWithPath: "benchmark_\(name)_\(timestamp).txt") try? data?.write(to: url, options: [.atomic]) } } private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 3 return formatter }() private let timestamp: String = { let formatter = DateFormatter() formatter.dateFormat = "yyyy_MM_dd_HH_mm_ss" return formatter.string(from: Date()) }()
mit
6d8c046d9f33635713a44b418b259764
27.098361
87
0.607351
3.949309
false
false
false
false
rtocd/NotificationObservers
NotificationObservers/Source/UIWindow/Keyboard.swift
1
1168
// // Keyboard.swift // NotificationObservers // // Created by rtocd on 8/27/17. // Copyright © 2017 RTOCD. All rights reserved. // import Foundation protocol KeyboardNotification { static var name: Notification.Name { get } } /// Handles all the UIKeyboard notifications that are declared in [UIWindow](https://developer.apple.com/documentation/uikit/uiwindow) public struct Keyboard { public struct WillShow: KeyboardNotification { static let name = Notification.Name.UIKeyboardWillShow } public struct WillChangeFrame: KeyboardNotification { static let name = Notification.Name.UIKeyboardWillChangeFrame } public struct WillHide: KeyboardNotification { static let name = Notification.Name.UIKeyboardWillHide } public struct DidShow: KeyboardNotification { static let name = Notification.Name.UIKeyboardDidShow } public struct DidChangeFrame: KeyboardNotification { static let name = Notification.Name.UIKeyboardDidChangeFrame } public struct DidHide: KeyboardNotification { static let name = Notification.Name.UIKeyboardDidHide } }
mit
a0aa27568da0a975f635b7685d23d29a
28.175
134
0.718937
5.140969
false
false
false
false
PiXeL16/RevealingSplashView
RevealingSplashView/RevealingSplashView.swift
1
5278
// // RevealingSplashView.swift // RevealingSplashView // // Created by Chris Jimenez on 2/25/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation import UIKit /// SplashView that reveals its content and animate, like twitter open class RevealingSplashView: UIView, SplashAnimatable{ /// The icon image to show and reveal with open var iconImage: UIImage? { didSet{ if let iconImage = self.iconImage{ imageView?.image = iconImage } } } ///The icon color of the image, defaults to white open var iconColor: UIColor = UIColor.white{ didSet{ imageView?.tintColor = iconColor } } open var useCustomIconColor: Bool = false{ didSet{ if(useCustomIconColor == true){ if let iconImage = self.iconImage { imageView?.image = iconImage.withRenderingMode(UIImage.RenderingMode.alwaysTemplate) } } else{ if let iconImage = self.iconImage { imageView?.image = iconImage.withRenderingMode(UIImage.RenderingMode.alwaysOriginal) } } } } ///The initial size of the icon. Ideally it has to match with the size of the icon in your LaunchScreen Splash view open var iconInitialSize: CGSize = CGSize(width: 60, height: 60) { didSet{ imageView?.frame = CGRect(x: 0, y: 0, width: iconInitialSize.width, height: iconInitialSize.height) } } /// The image view containing the background Image open var backgroundImageView: UIImageView? /// THe image view containing the icon Image open var imageView: UIImageView? /// The type of animation to use for the. Defaults to the twitter default animation open var animationType: SplashAnimationType = SplashAnimationType.twitter /// The duration of the animation, default to 1.5 seconds. In the case of heartBeat animation recommended value is 3 open var duration: Double = 1.5 /// The delay of the animation, default to 0.5 seconds open var delay: Double = 0.5 /// The boolean to stop the heart beat animation, default to false (continuous beat) open var heartAttack: Bool = false /// The repeat counter for heart beat animation, default to 1 open var minimumBeats: Int = 1 /** Default constructor of the class - parameter iconImage: The Icon image to show the animation - parameter iconInitialSize: The initial size of the icon image - parameter backgroundColor: The background color of the image, ideally this should match your Splash view - returns: The created RevealingSplashViewObject */ public init(iconImage: UIImage, iconInitialSize:CGSize, backgroundColor: UIColor) { //Sets the initial values of the image view and icon view self.imageView = UIImageView() self.iconImage = iconImage self.iconInitialSize = iconInitialSize //Inits the view to the size of the screen super.init(frame: (UIScreen.main.bounds)) imageView?.image = iconImage imageView?.tintColor = iconColor //Set the initial size and position imageView?.frame = CGRect(x: 0, y: 0, width: iconInitialSize.width, height: iconInitialSize.height) //Sets the content mode and set it to be centered imageView?.contentMode = UIView.ContentMode.scaleAspectFit imageView?.center = self.center //Adds the icon to the view self.addSubview(imageView!) //Sets the background color self.backgroundColor = backgroundColor } public init(iconImage: UIImage, iconInitialSize:CGSize, backgroundImage: UIImage) { //Sets the initial values of the image view and icon view self.imageView = UIImageView() self.iconImage = iconImage self.iconInitialSize = iconInitialSize //Inits the view to the size of the screen super.init(frame: (UIScreen.main.bounds)) imageView?.image = iconImage imageView?.tintColor = iconColor //Set the initial size and position imageView?.frame = CGRect(x: 0, y: 0, width: iconInitialSize.width, height: iconInitialSize.height) //Sets the content mode and set it to be centered imageView?.contentMode = UIView.ContentMode.scaleAspectFit imageView?.center = self.center //Sets the background image self.backgroundImageView = UIImageView() backgroundImageView?.image = backgroundImage backgroundImageView?.frame = UIScreen.main.bounds backgroundImageView?.contentMode = UIView.ContentMode.scaleAspectFill self.addSubview(backgroundImageView!) //Adds the icon to the view self.addSubview(imageView!) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b7223d10621a9d1b400ad7cb0fb8d55f
33.045161
120
0.628008
5.240318
false
false
false
false
MangoMade/MMSegmentedControl
Source/Const.swift
1
714
// // Const.swift // MMSegmentedControl // // Created by Aqua on 2017/4/12. // Copyright © 2017年 Aqua. All rights reserved. // import UIKit internal struct Const { static let defaultFont: UIFont = UIFont.systemFont(ofSize: 15) static let defaultSelectedFont: UIFont = UIFont.systemFont(ofSize: 18) static let defaultTextColor = UIColor.black static let defaultSelectedTextColor = UIColor(hex: 0xff4f53) static let onePx = 1 / UIScreen.main.scale static let tagsWidth: CGFloat = 72 static let tagsHeight: CGFloat = 40 static let animationDuration: Double = 0.25 } internal extension UIFont { static let defaultFont = UIFont.systemFont(ofSize: 14) }
mit
8fcee98056259414be4ccd6dd5ee0f2b
24.392857
74
0.703235
4.039773
false
false
false
false
ifau/SEPageViewWithNavigationBar
SEPageViewWithNavigationBar.swift
1
14858
// // SEPageViewWithNavigationBar.swift // PageViewWithNavigationBar // // https://github.com/ifau/SEPageViewWithNavigationBar // // Created by Seliverstov Evgeney on 15/08/15. // Copyright (c) 2015 Seliverstov Evgeney. All rights reserved. // import UIKit let SEStoryboardSegueIdentifier = "SEPage" let SESegueDoneNotification = "kSESegueDoneNotification" class SEPageViewWithNavigationBar: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate { @IBInspectable var pageIndicatorTintColor : UIColor = UIColor(white: 1.0, alpha: 0.4) { didSet { if titleView != nil { titleView.pageControl.pageIndicatorTintColor = pageIndicatorTintColor } } } @IBInspectable var currentPageIndicatorTintColor : UIColor = UIColor.whiteColor() { didSet { if titleView != nil { titleView.pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor } } } var titleLabelFont : UIFont = UIFont.systemFontOfSize(16) { didSet { if titleView != nil { titleView.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forRow: currentPage, inSection: 0)]) } } } @IBInspectable var titleLabelTextColor : UIColor = UIColor.whiteColor() { didSet { if titleView != nil { titleView.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forRow: currentPage, inSection: 0)]) } } } @IBInspectable var bounceEnabled : Bool = true var viewControllers : [UIViewController] = [] private var currentPage : Int = 0 private var pageViewController : UIPageViewController! private var titleView : SENavigationBarView! private var customTitleCell : ((titleCell: UICollectionViewCell, pageIndex: Int) -> (UICollectionViewCell))? private var customTitleCellClass: AnyClass? // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "segueDone:", name: SESegueDoneNotification, object: nil) if viewControllerCanPerformSegue(self, segueIdentifier: SEStoryboardSegueIdentifier) { self.performSegueWithIdentifier(SEStoryboardSegueIdentifier, sender: self) } else { initialize() } } func segueDone(notification: NSNotification) { let segue = notification.object as! SEPageViewSegue viewControllers.append(segue.destinationViewController) if viewControllerCanPerformSegue(segue.destinationViewController, segueIdentifier: SEStoryboardSegueIdentifier) { segue.performNextSegue() } else { initialize() } } private func initialize() { NSNotificationCenter.defaultCenter().removeObserver(self, name: SESegueDoneNotification, object: nil) if viewControllers.count > 0 { pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) pageViewController.dataSource = self pageViewController.delegate = self pageViewController.setViewControllers([viewControllers[0]], direction: .Forward, animated: false, completion: nil) // self.addChildViewController(pageViewController) self.view.addSubview(pageViewController.view) // pageViewController.didMoveToParentViewController(self) for view in pageViewController.view.subviews { if let scrollView = view as? UIScrollView { scrollView.delegate = self } } if self.navigationController != nil { let barframe = self.navigationController!.navigationBar.frame let titleframe = CGRect(x: 0, y: 0, width: barframe.size.width - 88, height: barframe.size.height) titleView = SENavigationBarView(frame: titleframe) titleView.pageControl.numberOfPages = viewControllers.count titleView.pageControl.currentPage = 0 titleView.pageControl.pageIndicatorTintColor = pageIndicatorTintColor titleView.pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor titleView.collectionView.delegate = self titleView.collectionView.dataSource = self self.navigationItem.titleView = titleView if customTitleCell != nil && customTitleCellClass != nil { titleView.collectionView.registerClass(customTitleCellClass!, forCellWithReuseIdentifier: "customHeaderCell") } } } } // MARK: - UIPageViewController delegate func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { if let index = viewControllers.indexOf(viewController) { return index + 1 == viewControllers.count ? nil : viewControllers[(index + 1)] } return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { if let index = viewControllers.indexOf(viewController) { return index - 1 < 0 ? nil : viewControllers[(index - 1)] } return nil } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { let currentViewController = pageViewController.viewControllers!.last! if let currentIndex = viewControllers.indexOf(currentViewController) { currentPage = currentIndex titleView.pageControl.currentPage = currentIndex } } // MARK: - UIScrollView delegate func scrollViewDidScroll(scrollView: UIScrollView) { if !(scrollView is UICollectionView) && !bounceEnabled { preventBounceForScrollView(scrollView) } if !(scrollView is UICollectionView) && titleView != nil { let allScrollViewContentSize = CGFloat(viewControllers.count) * self.view.frame.size.width let currentScrollViewContentOffset = (CGFloat(currentPage) * self.view.frame.size.width) + (scrollView.contentOffset.x - self.view.frame.size.width) let scrollPercent = currentScrollViewContentOffset * 100 / allScrollViewContentSize titleView.collectionView.contentOffset = CGPoint(x: titleView.collectionView.contentSize.width * scrollPercent / 100, y: 0.0) } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if !(scrollView is UICollectionView) && !bounceEnabled { preventBounceForScrollView(scrollView) } } // MARK: - UICollectionView delegate func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if customTitleCell != nil { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("customHeaderCell", forIndexPath: indexPath) return customTitleCell!(titleCell: cell, pageIndex: indexPath.row) } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("headerCell", forIndexPath: indexPath) as! SENavigationBarTitleCell let viewController = viewControllers[indexPath.row] cell.label.text = viewController.title == nil ? "" : viewController.title cell.label.font = titleLabelFont cell.label.textColor = titleLabelTextColor return cell } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return collectionView.frame.size } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewControllers.count } // MARK: - Other func setCustomTitle(cellClass cellClass: AnyClass, delegateCallback: ((titleCell: UICollectionViewCell, currentPage: Int) -> (UICollectionViewCell))) { customTitleCellClass = cellClass customTitleCell = delegateCallback } func preventBounceForScrollView(scrollView: UIScrollView) { if (currentPage == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width) { scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0) } if (currentPage == viewControllers.count - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width) { scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0) } } override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { if let _titleView = self.navigationItem.titleView { let barframe = self.navigationController!.navigationBar.frame let titleframe = CGRect(x: 0, y: 0, width: barframe.size.width - 88, height: barframe.size.height) _titleView.frame = titleframe } } func viewControllerCanPerformSegue(viewController: UIViewController, segueIdentifier: String) -> Bool { let templates : NSArray? = viewController.valueForKey("storyboardSegueTemplates") as? NSArray let predicate : NSPredicate = NSPredicate(format: "identifier=%@", segueIdentifier) let filteredtemplates = templates?.filteredArrayUsingPredicate(predicate) return filteredtemplates?.count > 0 } } private class SENavigationBarView: UIView { var collectionView : UICollectionView! var pageControl : UIPageControl! var fadeMask : CAGradientLayer! override init(frame: CGRect) { super.init(frame: frame) initialization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialization() } private func initialization() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Horizontal layout.minimumInteritemSpacing = 0.0 layout.minimumLineSpacing = 0.0 collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.registerClass(SENavigationBarTitleCell.self, forCellWithReuseIdentifier: "headerCell") collectionView.backgroundColor = UIColor.clearColor() collectionView.scrollEnabled = false self.addSubview(collectionView) pageControl = UIPageControl() pageControl.translatesAutoresizingMaskIntoConstraints = false self.addSubview(pageControl) let views = ["collectionView" : collectionView, "pageControl": pageControl] self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions.DirectionLeftToRight, metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pageControl]-0-|", options: NSLayoutFormatOptions.DirectionLeftToRight, metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[pageControl(==8)]-2-|", options: NSLayoutFormatOptions.DirectionLeftToRight, metrics: nil, views: views)) fadeMask = CAGradientLayer() fadeMask.colors = [UIColor(white: 1.0, alpha: 0.0).CGColor, UIColor(white: 1.0, alpha: 1.0).CGColor, UIColor(white: 1.0, alpha: 1.0).CGColor, UIColor(white: 1.0, alpha: 0.0).CGColor]; fadeMask.locations = [0.0, 0.2, 0.8, 1.0] fadeMask.startPoint = CGPoint(x: 0, y: 0) fadeMask.endPoint = CGPoint(x: 1, y: 0) self.layer.mask = fadeMask } override func layoutSubviews() { let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.invalidateLayout() super.layoutSubviews() let offset = CGFloat(pageControl.currentPage) * collectionView.frame.size.width collectionView.contentOffset = CGPoint(x: offset, y: 0.0) fadeMask.frame = self.bounds } } private class SENavigationBarTitleCell: UICollectionViewCell { var label : UILabel! override init(frame: CGRect) { super.init(frame: frame) label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .Center self.contentView.addSubview(label) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[label]-0-|", options: NSLayoutFormatOptions.DirectionLeftToRight, metrics: nil, views: ["label" : label])) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[label]-0-|", options: NSLayoutFormatOptions.DirectionLeftToRight, metrics: nil, views: ["label" : label])) } convenience init() { self.init(frame:CGRectZero) } required init?(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } } class SEPageViewSegue : UIStoryboardSegue { override func perform() { NSNotificationCenter.defaultCenter().postNotificationName(SESegueDoneNotification, object: self); } func performNextSegue() { destinationViewController.performSegueWithIdentifier(SEStoryboardSegueIdentifier, sender: sourceViewController) } }
mit
a929c2aed56f04e11b0acca165e87065
37.002558
207
0.660654
5.835821
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEProtocol/NKE_Protocol.swift
1
10758
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. 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 class NKE_Protocol: NSObject, NKScriptExport { static var registeredSchemes: Dictionary<String, NKScriptValue> = Dictionary<String, NKScriptValue>() static var activeRequests: Dictionary<Int, NKE_ProtocolCustom> = Dictionary<Int, NKE_ProtocolCustom>() static var registeredSchemeTypes: Dictionary<String, NKScriptValue> = Dictionary<String, NKScriptValue>() class func attachTo(context: NKScriptContext) { context.loadPlugin(NKE_Protocol(), namespace: "io.nodekit.electro.protocol", options: [String:AnyObject]()) } func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": return NKStorage.getPluginWithStub(stub, "lib-electro.nkar/lib-electro/protocol.js", NKElectro.self) default: return stub } } override init() {} func registerCustomProtocol(scheme: String, handler: NKScriptValue, completion: NKScriptValue?) -> Void { let scheme = scheme.lowercaseString NKE_Protocol.registeredSchemes[scheme] = handler NKE_ProtocolCustom.registeredSchemes.insert(scheme) completion?.callWithArguments([], completionHandler: nil) } func unregisterCustomProtocol(scheme: String, completion: NKScriptValue?) -> Void { let scheme = scheme.lowercaseString if (NKE_Protocol.registeredSchemes[scheme] != nil) { NKE_Protocol.registeredSchemes.removeValueForKey(scheme) } NKE_ProtocolCustom.registeredSchemes.remove(scheme) completion?.callWithArguments([], completionHandler: nil) } class func _emitRequest(req: Dictionary<String, AnyObject>, nativeRequest: NKE_ProtocolCustom) -> Void { let scheme = req["scheme"] as! String let id = nativeRequest.id let handler = NKE_Protocol.registeredSchemes[scheme] NKE_Protocol.activeRequests[id] = nativeRequest handler?.callWithArguments([req], completionHandler: nil) } class func _cancelRequest(nativeRequest: NKE_ProtocolCustom) -> Void { let id = nativeRequest.id if (NKE_Protocol.activeRequests[id] != nil) { NKE_Protocol.activeRequests.removeValueForKey(id) } } func callbackWriteData(id: Int, res: Dictionary<String, AnyObject>) -> Void { guard let nativeRequest = NKE_Protocol.activeRequests[id] else {return;} nativeRequest.callbackWriteData(res) } func callbackEnd(id: Int, res: Dictionary<String, AnyObject>) -> Void { guard let nativeRequest = NKE_Protocol.activeRequests[id] else {return;} NKE_Protocol.activeRequests.removeValueForKey(id) nativeRequest.callbackEnd(res) } func isProtocolHandled(scheme: String, callback: NKScriptValue) -> Void { let isHandled: Bool = (NKE_Protocol.registeredSchemes[scheme] != nil) callback.callWithArguments([isHandled], completionHandler: nil) } } class NKE_ProtocolCustom: NSURLProtocol { static var registeredSchemes: Set<String> = Set<String>() private class var sequenceNumber: Int { struct sequence { static var number: Int = 0 } let temp = sequence.number sequence.number += 1 return temp } var isLoading: Bool = false var isCancelled: Bool = false var headersWritten: Bool = false var id: Int = NKE_ProtocolCustom.sequenceNumber override class func canInitWithRequest(request: NSURLRequest) -> Bool { guard let host = request.URL?.host?.lowercaseString else {return false;} guard let scheme = request.URL?.scheme?.lowercaseString else {return false;} return (NKE_ProtocolCustom.registeredSchemes.contains(scheme) || NKE_ProtocolCustom.registeredSchemes.contains(host)) } override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest { return request } override class func requestIsCacheEquivalent(a: NSURLRequest?, toRequest: NSURLRequest?) -> Bool { return false } override func startLoading() { let request = self.request var req: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() req["id"] = self.id guard let host = request.URL?.host?.lowercaseString else {return;} guard let scheme = request.URL?.scheme?.lowercaseString else {return;} req["host"] = host if (!NKE_ProtocolCustom.registeredSchemes.contains(scheme) && NKE_ProtocolCustom.registeredSchemes.contains(host)) { req["scheme"] = host } else { req["scheme"] = scheme } var path = request.URL!.relativePath ?? "" let query = request.URL!.query ?? "" if (path == "") { path = "/" } let pathWithQuery: String if (query != "") { pathWithQuery = path + "?" + query } else { pathWithQuery = path } req["url"] = pathWithQuery req["method"] = request.HTTPMethod req["headers"] = request.allHTTPHeaderFields if (request.HTTPMethod == "POST") { let body = NSString(data:request.HTTPBody!, encoding: NSUTF8StringEncoding)! req["body"] = body req["length"] = body.length.description } isLoading = true headersWritten = false NKE_Protocol._emitRequest(req, nativeRequest: self) } override func stopLoading() { if (self.isLoading) { NKE_Protocol._cancelRequest(self) self.isCancelled = true NKLogging.log("+Custom Url Protocol Request Cancelled") } } func callbackWriteData(res: Dictionary<String, AnyObject>) -> Void { guard let chunk = res["_chunk"] as? String else {return;} let data: NSData? = NSData(base64EncodedString: chunk, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) if (!headersWritten) { _writeHeaders(res) self.client!.URLProtocol(self, didLoadData: data!) } } func callbackFile(res: Dictionary<String, AnyObject>) { if (self.isCancelled) {return} guard let path = res["path"] as? String else {return;} guard let url = NSURL(string: path) else {return;} let urlDecode = NKE_ProtocolFileDecode(url: url) if (urlDecode.exists()) { let data: NSData! = NSData(contentsOfFile: urlDecode.resourcePath! as String) if (!self.headersWritten) { _writeHeaders(res) } self.isLoading = false let response: NSURLResponse = NSURLResponse(URL: request.URL!, MIMEType: urlDecode.mimeType as String?, expectedContentLength: data.length, textEncodingName: urlDecode.textEncoding as String?) self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStoragePolicy.AllowedInMemoryOnly) self.client!.URLProtocol(self, didLoadData: data) self.client!.URLProtocolDidFinishLoading(self) } else { NKLogging.log("!Missing File \(path)") self.client!.URLProtocol(self, didFailWithError: NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist, userInfo: nil)) } } func callbackEnd(res: Dictionary<String, AnyObject>) { if (self.isCancelled) {return} if let _ = res["path"] as? String { return callbackFile(res);} guard let chunk = res["data"] as? String else {return;} let data: NSData = NSData(base64EncodedString: chunk, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)! if (!self.headersWritten) { _writeHeaders(res) } self.isLoading = false self.client!.URLProtocol(self, didLoadData: data) self.client!.URLProtocolDidFinishLoading(self) } private func _writeHeaders(res: Dictionary<String, AnyObject>) { self.headersWritten = true let headers: Dictionary<String, String> = res["headers"] as? Dictionary<String, String> ?? Dictionary<String, String>() let version: String = "HTTP/1.1" let statusCode: Int = res["statusCode"] as? Int ?? 200 if (statusCode == 302) { let location = headers["location"]! let url: NSURL = NSURL(string: location)! NKLogging.log("+Redirection location to \(url.absoluteString)") let response = NSHTTPURLResponse(URL: url, statusCode: statusCode, HTTPVersion: version, headerFields: headers)! self.client?.URLProtocol(self, wasRedirectedToRequest: NSURLRequest(URL: url), redirectResponse: response) self.isLoading = false self.client?.URLProtocolDidFinishLoading(self) } else { let response = NSHTTPURLResponse(URL: self.request.URL!, statusCode: statusCode, HTTPVersion: version, headerFields: headers)! self.client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStoragePolicy.NotAllowed) } } }
apache-2.0
0aac8505af6fca19603ae5f821172e5c
26.870466
204
0.595743
5.16963
false
false
false
false
envoyproxy/envoy
mobile/library/swift/mocks/MockStreamPrototype.swift
2
1009
import Dispatch @_implementationOnly import EnvoyEngine import Foundation /// Mock implementation of `StreamPrototype` which is used to produce `MockStream` instances. @objcMembers public final class MockStreamPrototype: StreamPrototype { private let onStart: ((MockStream) -> Void)? /// Initialize a new instance of the mock prototype. /// /// - parameter onStart: Closure that will be called each time a new stream /// is started from the prototype. init(onStart: @escaping (MockStream) -> Void) { self.onStart = onStart super.init(engine: MockEnvoyEngine()) } public override func start(queue: DispatchQueue = .main) -> Stream { let callbacks = self.createCallbacks(queue: queue) let underlyingStream = MockEnvoyHTTPStream(handle: 0, engine: 0, callbacks: callbacks, explicitFlowControl: false) let stream = MockStream(mockStream: underlyingStream) self.onStart?(stream) return stream } }
apache-2.0
6a6373fe448704c43db413303389e9e5
36.37037
93
0.68781
4.62844
false
false
false
false
AgaKhanFoundation/WCF-iOS
Pods/OAuthSwift/Sources/OAuthSwiftClient.swift
2
9587
// // OAuthSwiftClient.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public var OAuthSwiftDataEncoding: String.Encoding = .utf8 @objc public protocol OAuthSwiftRequestHandle { func cancel() } open class OAuthSwiftClient: NSObject { fileprivate(set) open var credential: OAuthSwiftCredential open var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .authorizationHeader /// Contains default URL session configuration open var sessionFactory = URLSessionFactory() static let separator: String = "\r\n" static var separatorData: Data = { return OAuthSwiftClient.separator.data(using: OAuthSwiftDataEncoding)! }() // MARK: init public init(credential: OAuthSwiftCredential) { self.credential = credential } public convenience init(consumerKey: String, consumerSecret: String, version: OAuthSwiftCredential.Version = .oauth1) { let credential = OAuthSwiftCredential(consumerKey: consumerKey, consumerSecret: consumerSecret) credential.version = version self.init(credential: credential) } public convenience init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String, version: OAuthSwiftCredential.Version) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, version: version) self.credential.oauthToken = oauthToken self.credential.oauthTokenSecret = oauthTokenSecret } // MARK: client methods @discardableResult open func get(_ url: URLConvertible, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.request(url, method: .GET, parameters: parameters, headers: headers, completionHandler: completion) } @discardableResult open func post(_ url: URLConvertible, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.request(url, method: .POST, parameters: parameters, headers: headers, body: body, completionHandler: completion) } @discardableResult open func put(_ url: URLConvertible, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.request(url, method: .PUT, parameters: parameters, headers: headers, body: body, completionHandler: completion) } @discardableResult open func delete(_ url: URLConvertible, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.request(url, method: .DELETE, parameters: parameters, headers: headers, completionHandler: completion) } @discardableResult open func patch(_ url: URLConvertible, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.request(url, method: .PATCH, parameters: parameters, headers: headers, completionHandler: completion) } @discardableResult open func request(_ url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { if checkTokenExpiration && self.credential.isTokenExpired() { completion?(.failure(.tokenExpired(error: nil))) return nil } guard url.url != nil else { completion?(.failure(.encodingError(urlString: url.string))) return nil } if let request = makeRequest(url, method: method, parameters: parameters, headers: headers, body: body) { request.start(completionHandler: completion) return request } return nil } open func makeRequest(_ request: URLRequest) -> OAuthSwiftHTTPRequest { let request = OAuthSwiftHTTPRequest(request: request, paramsLocation: self.paramsLocation, sessionFactory: self.sessionFactory) request.config.updateRequest(credential: self.credential) return request } open func makeRequest(_ url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil) -> OAuthSwiftHTTPRequest? { guard let url = url.url else { return nil // XXX failure not thrown here } let request = OAuthSwiftHTTPRequest(url: url, method: method, parameters: parameters, paramsLocation: self.paramsLocation, httpBody: body, headers: headers ?? [:], sessionFactory: self.sessionFactory) request.config.updateRequest(credential: self.credential) return request } @discardableResult public func postImage(_ url: URLConvertible, parameters: OAuthSwift.Parameters, image: Data, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { return self.multiPartRequest(url: url, method: .POST, parameters: parameters, image: image, completionHandler: completion) } open func makeMultiPartRequest(_ url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], multiparts: [OAuthSwiftMultipartData] = [], headers: OAuthSwift.Headers? = nil) -> OAuthSwiftHTTPRequest? { let boundary = "AS-boundary-\(arc4random())-\(arc4random())" let type = "multipart/form-data; boundary=\(boundary)" let body = self.multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) var finalHeaders = [kHTTPHeaderContentType: type] finalHeaders += headers ?? [:] return makeRequest(url, method: method, parameters: parameters, headers: finalHeaders, body: body) } func multiPartRequest(url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, image: Data, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { let multiparts = [ OAuthSwiftMultipartData(name: "media", data: image, fileName: "file", mimeType: "image/jpeg") ] guard let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts) else { return nil } request.start(completionHandler: completion) return request } open func multiPartBody(from inputParameters: OAuthSwift.Parameters, boundary: String) -> Data { var parameters = OAuthSwift.Parameters() var multiparts = [OAuthSwiftMultipartData]() for (key, value) in inputParameters { if let data = value as? Data, key == "media" { let sectionType = "image/jpeg" let sectionFilename = "file" multiparts.append(OAuthSwiftMultipartData(name: key, data: data, fileName: sectionFilename, mimeType: sectionType)) } else { parameters[key] = value } } return multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) } @discardableResult open func postMultiPartRequest(_ url: URLConvertible, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, multiparts: [OAuthSwiftMultipartData] = [], checkTokenExpiration: Bool = true, completionHandler completion: OAuthSwiftHTTPRequest.CompletionHandler?) -> OAuthSwiftRequestHandle? { if checkTokenExpiration && self.credential.isTokenExpired() { completion?(.failure(.tokenExpired(error: nil))) return nil } if let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts, headers: headers) { request.start(completionHandler: completion) return request } return nil } func multiDataFromObject(_ object: OAuthSwift.Parameters, multiparts: [OAuthSwiftMultipartData], boundary: String) -> Data { var data = Data() let prefixString = "--\(boundary)\r\n" let prefixData = prefixString.data(using: OAuthSwiftDataEncoding)! for (key, value) in object { guard let valueData = "\(value)".data(using: OAuthSwiftDataEncoding) else { continue } data.append(prefixData) let multipartData = OAuthSwiftMultipartData(name: key, data: valueData, fileName: nil, mimeType: nil) data.append(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) } for multipart in multiparts { data.append(prefixData) data.append(multipart, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) } let endingString = "--\(boundary)--\r\n" let endingData = endingString.data(using: OAuthSwiftDataEncoding)! data.append(endingData) return data } }
bsd-3-clause
ed98e4d716d2eab2679a2f51eda0589c
48.932292
347
0.705956
5.221678
false
false
false
false
rechsteiner/Parchment
Example/Examples/Calendar/CalendarViewController.swift
1
2954
import Parchment import UIKit // First thing we need to do is create our own PagingItem that will // hold our date. We need to make sure it conforms to Hashable and // Comparable, as that is required by PagingViewController. We also // cache the formatted date strings for performance. struct CalendarItem: PagingItem, Hashable, Comparable { let date: Date let dateText: String let weekdayText: String init(date: Date) { self.date = date dateText = DateFormatters.dateFormatter.string(from: date) weekdayText = DateFormatters.weekdayFormatter.string(from: date) } static func < (lhs: CalendarItem, rhs: CalendarItem) -> Bool { return lhs.date < rhs.date } } class CalendarViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let pagingViewController = PagingViewController() pagingViewController.register(CalendarPagingCell.self, for: CalendarItem.self) pagingViewController.menuItemSize = .fixed(width: 48, height: 58) pagingViewController.textColor = UIColor.gray // Add the paging view controller as a child view // controller and constrain it to all edges addChild(pagingViewController) view.addSubview(pagingViewController.view) view.constrainToEdges(pagingViewController.view) pagingViewController.didMove(toParent: self) // Set our custom data source pagingViewController.infiniteDataSource = self // Set the current date as the selected paging item pagingViewController.select(pagingItem: CalendarItem(date: Date())) } } // We need to conform to PagingViewControllerDataSource in order to // implement our custom data source. We set the initial item to be the // current date, and every time pagingItemBeforePagingItem: or // pagingItemAfterPagingItem: is called, we either subtract or append // the time interval equal to one day. This means our paging view // controller will show one menu item for each day. extension CalendarViewController: PagingViewControllerInfiniteDataSource { func pagingViewController(_: PagingViewController, itemAfter pagingItem: PagingItem) -> PagingItem? { let calendarItem = pagingItem as! CalendarItem return CalendarItem(date: calendarItem.date.addingTimeInterval(86400)) } func pagingViewController(_: PagingViewController, itemBefore pagingItem: PagingItem) -> PagingItem? { let calendarItem = pagingItem as! CalendarItem return CalendarItem(date: calendarItem.date.addingTimeInterval(-86400)) } func pagingViewController(_: PagingViewController, viewControllerFor pagingItem: PagingItem) -> UIViewController { let calendarItem = pagingItem as! CalendarItem let formattedDate = DateFormatters.shortDateFormatter.string(from: calendarItem.date) return ContentViewController(title: formattedDate) } }
mit
2738b399ef29293e354f2d7b0dd185a7
41.2
118
0.73629
5.155323
false
false
false
false
rechsteiner/Parchment
Example/Examples/Images/ImageCollectionViewCell.swift
1
707
import UIKit class ImageCollectionViewCell: UICollectionViewCell { static let reuseIdentifier: String = "ImageCellIdentifier" fileprivate lazy var imageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.contentMode = .scaleAspectFill return imageView }() override init(frame: CGRect) { super.init(frame: frame) contentView.clipsToBounds = true contentView.addSubview(imageView) contentView.constrainToEdges(imageView) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } func setImage(_ image: UIImage) { imageView.image = image } }
mit
18b1cd4c379708c4478a1cbd5f4ed244
26.192308
62
0.666195
5.198529
false
false
false
false
malaonline/iOS
mala-ios/View/Profile/InfoModifyViewWindow.swift
1
10226
// // InfoModifyViewWindow.swift // mala-ios // // Created by 王新宇 on 16/6/12. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit open class InfoModifyViewWindow: UIViewController, UITextViewDelegate { // MARK: - Property /// 姓名文字 var nameString: String? = MalaUserDefaults.studentName.value /// 自身强引用 var strongSelf: InfoModifyViewWindow? /// 遮罩层透明度 let tBakcgroundTansperancy: CGFloat = 0.7 /// 布局容器(窗口) var window = UIView() /// 内容视图 var contentView: UIView? /// 单击背景close窗口 var closeWhenTap: Bool = false // MARK: - Components /// 取消按钮.[取消] private lazy var cancelButton: UIButton = { let button = UIButton() button.setTitle(L10n.cancel, for: UIControlState()) // cancelButton.setTitleColor(UIColor(named: .ThemeBlue), forState: .Normal) button.setTitleColor(UIColor(named: .DescGray), for: UIControlState()) button.setBackgroundImage(UIImage.withColor(UIColor(named: .WhiteTranslucent9)), for: UIControlState()) button.setBackgroundImage(UIImage.withColor(UIColor(named: .HighlightGray)), for: .highlighted) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.addTarget(self, action: #selector(InfoModifyViewWindow.cancelButtonDidTap), for: .touchUpInside) return button }() /// 确认按钮.[去评价] private lazy var saveButton: UIButton = { let button = UIButton() button.setTitle("保存", for: UIControlState()) button.setTitleColor(UIColor(named: .ThemeBlue), for: UIControlState()) button.setTitleColor(UIColor(named: .DescGray), for: .highlighted) button.setTitleColor(UIColor(named: .DescGray), for: .disabled) button.setBackgroundImage(UIImage.withColor(UIColor(named: .WhiteTranslucent9)), for: UIControlState()) button.setBackgroundImage(UIImage.withColor(UIColor(named: .HighlightGray)), for: .highlighted) button.setBackgroundImage(UIImage.withColor(UIColor(named: .HighlightGray)), for: .disabled) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.addTarget(self, action: #selector(InfoModifyViewWindow.saveButtonDidTap), for: .touchUpInside) return button }() private lazy var contentContainer: UIView = { let contentContainer = UIView() return contentContainer }() /// 按钮顶部装饰线 private lazy var buttonTopLine: UIView = { let buttonTopLine = UIView(UIColor(named: .ThemeBlue)) return buttonTopLine }() /// 按钮间隔装饰线 private lazy var buttonSeparatorLine: UIView = { let buttonSeparatorLine = UIView(UIColor(named: .ThemeBlue)) return buttonSeparatorLine }() /// 姓名文本框 private lazy var nameLabel: UITextField = { let textField = UITextField() textField.textAlignment = .center textField.textColor = UIColor(named: .ArticleText) textField.tintColor = UIColor(named: .ThemeBlue) textField.text = self.nameString textField.font = UIFont.systemFont(ofSize: 14) textField.addTarget(self, action: #selector(InfoModifyViewWindow.inputFieldDidChange), for: .editingChanged) return textField }() /// 姓名底部装饰线 private lazy var nameLine: UIView = { let view = UIView(UIColor(named: .ThemeBlue)) return view }() /// 提示文字标签 private lazy var warningLabel: UILabel = { let label = UILabel( text: "* 请输入2-4位中文字符", fontSize: 11, textColor: UIColor(named: .ThemeRed) ) return label }() // MARK: - Constructed init() { super.init(nibName: nil, bundle: nil) view.frame = UIScreen.main.bounds setupUserInterface() // 持有自己强引用,使自己在外界没有强引用时依然存在。 strongSelf = self } convenience init(contentView: UIView) { self.init() view.alpha = 0 // 显示Window let window: UIWindow = UIApplication.shared.keyWindow! window.addSubview(view) window.bringSubview(toFront: view) view.frame = window.bounds } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Life Cycle override open func viewDidLoad() { super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - API open func show() { animateAlert() } open func close() { closeAlert(0) } // MARK: - Private Method private func setupUserInterface() { // Style view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: tBakcgroundTansperancy) view.addTapEvent(target: self, action: #selector(InfoModifyViewWindow.backgroundDidTap)) window.backgroundColor = UIColor.white // SubViews view.addSubview(window) window.addSubview(contentContainer) window.addSubview(nameLine) window.addSubview(nameLabel) window.addSubview(warningLabel) window.addSubview(cancelButton) window.addSubview(saveButton) window.addSubview(buttonTopLine) window.addSubview(buttonSeparatorLine) // Autolayout window.snp.makeConstraints { (maker) -> Void in maker.center.equalTo(view) maker.width.equalTo(MalaLayout_CoursePopupWindowWidth) maker.height.equalTo(MalaLayout_CoursePopupWindowWidth*0.588) } contentContainer.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(window) maker.left.equalTo(window) maker.right.equalTo(window) maker.bottom.equalTo(buttonTopLine.snp.top) } nameLine.snp.makeConstraints { (maker) -> Void in maker.height.equalTo(2) maker.centerX.equalTo(contentContainer) maker.centerY.equalTo(contentContainer.snp.bottom).multipliedBy(0.65) maker.width.equalTo(window).multipliedBy(0.8) } nameLabel.snp.makeConstraints { (maker) -> Void in maker.height.equalTo(15) maker.centerX.equalTo(contentContainer) maker.bottom.equalTo(nameLine.snp.top).offset(-15) maker.width.equalTo(100) } warningLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(nameLine.snp.bottom).offset(10) maker.right.equalTo(nameLine) } cancelButton.snp.makeConstraints { (maker) -> Void in maker.bottom.equalTo(window) maker.left.equalTo(window) maker.height.equalTo(44) maker.width.equalTo(window).multipliedBy(0.5) } saveButton.snp.makeConstraints { (maker) -> Void in maker.bottom.equalTo(window) maker.right.equalTo(window) maker.height.equalTo(44) maker.width.equalTo(window).multipliedBy(0.5) } buttonTopLine.snp.makeConstraints { (maker) -> Void in maker.bottom.equalTo(cancelButton.snp.top) maker.height.equalTo(MalaScreenOnePixel) maker.left.equalTo(window) maker.right.equalTo(window) } buttonSeparatorLine.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(cancelButton) maker.bottom.equalTo(window) maker.width.equalTo(MalaScreenOnePixel) maker.left.equalTo(cancelButton.snp.right) } } private func animateAlert() { view.alpha = 0; let originTransform = self.window.transform self.window.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.0); UIView.animate(withDuration: 0.35, animations: { () -> Void in self.view.alpha = 1.0 self.window.transform = originTransform }) } private func animateDismiss() { UIView.animate(withDuration: 0.35, animations: { () -> Void in self.view.alpha = 0 self.window.transform = CGAffineTransform() }, completion: { (bool) -> Void in self.closeAlert(0) }) } private func closeAlert(_ buttonIndex: Int) { self.view.removeFromSuperview() // 释放自身强引用 self.strongSelf = nil } /// 保存学生姓名 private func saveStudentsName() { guard let name = nameLabel.text else { return } MAProvider.saveStudentName(name: name) { result in println("Save Student Name - \(result as Optional)") MalaUserDefaults.studentName.value = name NotificationCenter.default.post(name: MalaNotification_RefreshStudentName, object: nil) DispatchQueue.main.async { self.animateDismiss() } } } // MARK: - Event Response @objc private func pressed(_ sender: UIButton!) { self.closeAlert(sender.tag) } @objc open func backgroundDidTap() { if closeWhenTap { closeAlert(0) } } @objc private func cancelButtonDidTap() { close() } /// 验证姓名字符是否合规 private func validateName(_ name: String) -> Bool { let nameRegex = "^[\\u4e00-\\u9fa5]{2,4}$" let nameTest = NSPredicate(format: "SELF MATCHES %@", nameRegex) return nameTest.evaluate(with: name) } /// 用户输入事件 @objc private func inputFieldDidChange() { guard let name = nameLabel.text else { return } saveButton.isEnabled = validateName(name) } /// 保存按钮点击事件 @objc private func saveButtonDidTap() { saveStudentsName() } }
mit
595efb61becfdbcc96e6e593bf3292fd
33.301038
116
0.614849
4.447286
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Live/Controller/BaseLiveViewController.swift
1
7227
// // BaseLiveViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/2/26. // Copyright © 2016年 ming. All rights reserved. // 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles // github: https://github.com/LYM-mg import UIKit import JHPullToRefreshKit import SafariServices class BaseLiveViewController: BaseViewController { // MARK:- ViewModel lazy var baseLiveVM : BaseLiveViewModel = BaseLiveViewModel() lazy var collectionView : UICollectionView = {[weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin // layout.headerReferenceSize = CGSizeMake(kScreenW, kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.scrollsToTop = false collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // 3.注册 collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setUpMainView() // loadData() setUpRefresh() if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: self.view) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - 初始化UI extension BaseLiveViewController { override func setUpMainView() { // 0.给ContentView进行赋值 contentView = collectionView view.addSubview(collectionView) super.setUpMainView() } } extension BaseLiveViewController { fileprivate func setUpRefresh() { // MARK: - 下拉 self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in self!.baseLiveVM.offset = 0 self?.loadData() self!.collectionView.header.endRefreshing() self?.collectionView.footer.endRefreshing() }) // MARK: - 上拉 self.collectionView.footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in self!.baseLiveVM.offset += 20 self?.loadData() self!.collectionView.header.endRefreshing() self?.collectionView.footer.endRefreshing() }) self.collectionView.header.isAutoChangeAlpha = true self.collectionView.header.beginRefreshing() self.collectionView.footer.noticeNoMoreData() } // 加载数据 @objc func loadData() { } } // MARK: - UICollectionViewDataSource extension BaseLiveViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseLiveVM.liveModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell // 2.给cell设置数据 cell.anchor = baseLiveVM.liveModels[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension BaseLiveViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: kNormalItemW, height: kNormalItemH) } } // MARK: - UICollectionViewDelegate extension BaseLiveViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.取出对应的主播信息 let anchor = baseLiveVM.liveModels[indexPath.item] // 2.判断是秀场房间&普通房间 anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor) } fileprivate func presentShowRoomVc(anchor: AnchorModel) { if #available(iOS 9.0, *) { // 1.创建SFSafariViewController let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) // 2.以Modal方式弹出 present(safariVC, animated: true, completion: nil) } else { let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) present(webVC, animated: true, completion: nil) } } fileprivate func pushNormalRoomVc(anchor: AnchorModel) { // 1.创建WebViewController let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) webVC.navigationController?.setNavigationBarHidden(true, animated: true) // 2.以Push方式弹出 navigationController?.pushViewController(webVC, animated: true) } } // MARK: - UIViewControllerPreviewingDelegate extension BaseLiveViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) else { return nil } if #available(iOS 9.0, *) { previewingContext.sourceRect = cell.frame } var vc = UIViewController() let anchor = baseLiveVM.liveModels[indexPath.item] if anchor.isVertical == 0 { if #available(iOS 9, *) { vc = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) } else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } }else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } return vc } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: nil) } }
mit
89d5a1eb1caab393c8eb934ebb9ce9a5
36.52381
160
0.671461
5.401371
false
false
false
false
ScalaInc/exp-ios-sdk
ExpSwift/Classes/Runtime.swift
1
7853
// // Runtime.swift // Pods // // Created by Cesar on 9/28/15. // // import Foundation import SocketIO import Alamofire import PromiseKit import JWT open class Runtime{ var optionsRuntime:[String : Any?] = [String : Any?]() var timeout:TimeInterval = 5 // seconds var enableSocket:Bool = true // enable socket connection /** Initialize the SDK and connect to EXP. @param host,uuid,secret. @return Promise<Bool>. */ open func start(_ host: String, uuid: String, secret: String) -> Promise<Bool> { return start(["host": host, "deviceUuid": uuid, "secret": secret]) } /** Initialize the SDK and connect to EXP. @param host,user,password,organization. @return Promise<Bool>. */ open func start(_ host:String , user: String , password:String, organization:String) -> Promise<Bool> { return start(["host": host, "username": user, "password": password, "organization": organization]) } /** Initialize the SDK and connect to EXP. @param host,user,password,organization. @return Promise<Bool>. */ open func start(_ host:String , auth: Auth) -> Promise<Bool> { return start(["host": host, "auth": auth]) } /** Initialize the SDK and connect to EXP. @param options @return Promise<Bool>. */ open func start(_ options:[String:Any?]) -> Promise<Bool> { expLogging("EXP start with options \(options)") optionsRuntime = options return Promise { fulfill, reject in if let host = options["host"] { hostUrl=host as! String } if let enableEvents = options["enableEvents"]{ self.enableSocket = NSString(string: (enableEvents as? String)!).boolValue } if let user = options["username"], let password = options["password"], let organization = options["organization"] { login(options).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch {error in reject(error) } } if let uuid = options["uuid"] as? String, let secret = options["secret"] as? String { let tokenSign = JWT.encode(["uuid": uuid, "type": "device"], algorithm: .hs256(secret.data(using: .utf8)!)) login(["token":tokenSign]).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch{error in reject(error) } } if let uuid = options["deviceUuid"] as? String , let secret = options["secret"] as? String { let tokenSign = JWT.encode(["uuid": uuid, "type": "device"], algorithm: .hs256(secret.data(using: .utf8)!)) login(["token":tokenSign]).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch{error in reject(error) } } if let uuid = options["uuid"] as? String, let apiKey = options["apiKey"] as? String { let tokenSign = JWT.encode(["uuid": uuid, "type": "consumerApp"], algorithm: .hs256(apiKey.data(using: .utf8)!)) login(["token":tokenSign]).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch{error in reject(error) } } if let uuid = options["consumerAppUuid"] as? String, let apiKey = options["apiKey"] as? String{ let tokenSign = JWT.encode(["uuid": uuid, "type": "consumerApp"], algorithm: .hs256(apiKey.data(using: .utf8)!)) login(["token":tokenSign]).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch{error in reject(error) } } if let uuid = options["networkUuid"] as? String , let apiKey = options["apiKey"] as? String{ let tokenSign = JWT.encode(["uuid": uuid, "type": "consumerApp"], algorithm: .hs256(apiKey.data(using: .utf8)!)) login(["token":tokenSign]).then {(auth: Auth) -> Void in self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } }.catch{error in reject(error) } } if let auth = options["auth"] as? Auth{ startAuth(auth) self.initNetwork(auth) if self.enableSocket { socketManager.start_socket().then { (result: Bool) -> Void in if result{ fulfill(true) } } } } } } /** Init network parameters for socket connection and Api calls @param auth */ fileprivate func initNetwork(_ auth: Auth)->Void{ tokenSDK = auth.get("token") as! String let networks = auth.get("network") as! NSDictionary hostSocket = networks["host"] as! String } /** Stop socket connection. @param host,user,password,organization. @return Promise<Bool>. */ open func stop(){ socketManager.disconnect() tokenSDK = "" } /** Connection Socket @param name for connection(offline,line),callback @return void */ open func connection(_ name:String,callback:@escaping (String)->Void){ socketManager.connection(name, callback: { (resultListen) -> Void in callback(resultListen) }) } /** Socket Manager is Connected */ open func isConnected()->Bool{ var isConnected = false if(socketManager != nil){ isConnected = socketManager.isConnected() } return isConnected } }
mit
a5061d421fd352ac9d19a9fb2f1348d1
34.215247
128
0.458551
5.11263
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/Loaders/PlaylistLoader.swift
1
3912
// // PlaylistLoader.swift // iSub // // Created by Benjamin Baron on 1/16/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class PlaylistLoader: ApiLoader, PersistedItemLoader { let playlistId: Int64 var songs = [Song]() var items: [Item] { return songs } var associatedItem: Item? { return PlaylistRepository.si.playlist(playlistId: playlistId, serverId: serverId) } init(playlistId: Int64, serverId: Int64) { self.playlistId = playlistId super.init(serverId: serverId) } override func createRequest() -> URLRequest? { return URLRequest(subsonicAction: .getPlaylist, serverId: serverId, parameters: ["id": playlistId]) } override func processResponse(root: RXMLElement) -> Bool { var songsTemp = [Song]() root.iterate("playlist.entry") { song in if let aSong = Song(rxmlElement: song, serverId: self.serverId) { songsTemp.append(aSong) } } songs = songsTemp persistModels() return true } func persistModels() { // Save the new songs songs.forEach({$0.replace()}) // Update the playlist table // TODO: This will need to be rewritten to handle two way syncing if var playlist = associatedItem as? Playlist { playlist.overwriteSubItems() } // Make sure all artist and album records are created if needed var folderIds = Set<Int64>() var artistIds = Set<Int64>() var albumIds = Set<Int64>() for song in songs { func performOperation(folderId: Int64, mediaFolderId: Int64) { if !folderIds.contains(folderId) { folderIds.insert(folderId) let loader = FolderLoader(folderId: folderId, serverId: serverId, mediaFolderId: mediaFolderId) let operation = ItemLoaderOperation(loader: loader) ApiLoader.backgroundLoadingQueue.addOperation(operation) } } if let folder = song.folder, let mediaFolderId = folder.mediaFolderId, !folder.isPersisted { performOperation(folderId: folder.folderId, mediaFolderId: mediaFolderId) } else if song.folder == nil, let folderId = song.folderId, let mediaFolderId = song.mediaFolderId { performOperation(folderId: folderId, mediaFolderId: mediaFolderId) } if let artist = song.artist, !artist.isPersisted { artistIds.insert(artist.artistId) } else if song.artist == nil, let artistId = song.artistId { artistIds.insert(artistId) } if let album = song.album, !album.isPersisted { albumIds.insert(album.albumId) } else if song.album == nil, let albumId = song.albumId { albumIds.insert(albumId) } } for artistId in artistIds { let loader = ArtistLoader(artistId: artistId, serverId: serverId) let operation = ItemLoaderOperation(loader: loader) ApiLoader.backgroundLoadingQueue.addOperation(operation) } for albumId in albumIds { let loader = AlbumLoader(albumId: albumId, serverId: serverId) let operation = ItemLoaderOperation(loader: loader) ApiLoader.backgroundLoadingQueue.addOperation(operation) } } @discardableResult func loadModelsFromDatabase() -> Bool { if let playlist = associatedItem as? Playlist { playlist.loadSubItems() songs = playlist.songs return songs.count > 0 } return false } }
gpl-3.0
4fd763760a0b6d3bd5e51e53fb029092
33.610619
115
0.584761
4.963198
false
false
false
false
GetZero/Give-Me-One
MyOne/文章/Model/ArticleModel.swift
1
3700
// // ArticleDataManager.swift // MyOne // // Created by 韦曲凌 on 16/8/27. // Copyright © 2016年 Wake GetZero. All rights reserved. // import UIKit class ArticleModel: NSObject { var articleDatas: [ArticleData] = [] private var resultType: NetworkFinishType = .Default private dynamic var resultTypeString: String = "Default" var networkError: NSError? func startNetwork(day: Int) { let parameters: [String: AnyObject] = ["strDate": GetTime.getBeforeDay(day), "strRow": "1"] Networking.get(ArticleURLString, parameters: parameters, headers: nil, successAction: { (respondsToSuccessAction) in dispatch_async(dispatch_get_global_queue(0, 0), { self.dealWithData(respondsToSuccessAction["contentEntity"] as! [String: String]) }) }) { (respondsToErrorAction) in self.dealWithError(respondsToErrorAction) } } private func dealWithData(data: [String: String]) { let model: ArticleData = ArticleData(dict: data) articleDatas.append(model) resultType = NetworkFinishType.NetworkSuccess resultTypeString = resultType.rawValue } private func dealWithError(errorInfo: NSError) { debugPrint(errorInfo) resultType = NetworkFinishType.NetworkFaile resultTypeString = resultType.rawValue } func resultKeyPath() -> String { return "resultTypeString" } } struct ArticleData { var strContMarketTime: String = "暂无数据" // 时间 var strContTitle: String = "暂无数据" // 标题 var strContAuthor: String = "暂无数据" // 作者 var strContent: String = "暂无数据" // 内容 var sAuth: String = "暂无数据" // 作者简介 var sWbN: String = "暂无数据" // 艾特 var contentHeight: CGFloat = 0 var briefHeight: CGFloat = 0 init(dict: [String: String]) { strContMarketTime = dict["strContMarketTime"]! strContTitle = dict["strContTitle"]! strContAuthor = dict["strContAuthor"]! strContent = dict["strContent"]! sAuth = dict["sAuth"]! sWbN = dict["sWbN"]! self.strContent = self.strContent.stringByReplacingOccurrencesOfString("<br>", withString: "") self.contentHeight = self.calculatorContentHeight(self.strContent) briefHeight = calculatorBreifHeight(sAuth) } private func calculatorContentHeight(content: String) -> CGFloat { let string: NSString = content as NSString let para: NSMutableParagraphStyle = NSMutableParagraphStyle() para.lineBreakMode = .ByWordWrapping let contentRect: CGRect = string.boundingRectWithSize(CGSize(width: ScreenWidth - 20, height: 0), options: Utils.combine(), attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14), NSParagraphStyleAttributeName: para], context: nil) let contentHeight: CGFloat = contentRect.height return contentHeight } private func calculatorBreifHeight(content: String) -> CGFloat { let string: NSString = content as NSString let para: NSMutableParagraphStyle = NSMutableParagraphStyle() para.lineBreakMode = .ByWordWrapping let contentRect: CGRect = string.boundingRectWithSize(CGSize(width: ScreenWidth - 20, height: 0), options: Utils.combine(), attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14), NSParagraphStyleAttributeName: para], context: nil) let contentHeight: CGFloat = contentRect.height + 10 return contentHeight } }
apache-2.0
bf32550a0351d516cd739dc3b263fbc2
37.052632
246
0.653112
4.622762
false
false
false
false
nissivm/AppleWatchKeyboard
AppleWatchKeyboard WatchKit Extension/InitialScreen.swift
1
1789
// // InitialScreen.swift // AppleWatchKeyboard // // Created by Nissi Vieira Miranda on 9/26/15. // Copyright © 2015 Nissi Vieira Miranda. All rights reserved. // import WatchKit import Foundation class InitialScreen: WKInterfaceController { @IBOutlet var table: WKInterfaceTable! let avatars : [String] = ["Axl", "Nicole", "Simon", "Suzanne", "Vincent"] override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) fillAvatarsTable() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } //-------------------------------------------------------------------------// // MARK: Table //-------------------------------------------------------------------------// func fillAvatarsTable() { table.setNumberOfRows(avatars.count, withRowType: "AvatarCell") for (index, avatarName) in avatars.enumerate() { let avatarPath = NSBundle.mainBundle().pathForResource(avatarName, ofType: "png") let avatar = UIImage(contentsOfFile: avatarPath!) let row = table.rowControllerAtIndex(index) as! AvatarCell row.avatarImage.setImage(avatar) row.avatarName.setText(avatarName) } } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { let avatarName = avatars[rowIndex] self.pushControllerWithName("ChatRoom", context: avatarName) } }
mit
646e8c7239b25ce1077769f804fb14b5
28.311475
93
0.5783
5.16763
false
false
false
false
SwiftKitz/Appz
Appz/Appz/Apps/Ibooks.swift
1
998
// // Ibooks.swift // Pods // // Created by Mariam AlJamea on 1/2/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { struct Ibooks: ExternalApplication { public typealias ActionType = Applications.Ibooks.Action public let scheme = "itms-Books:" public let fallbackURL = "https://itunes.apple.com/us/app/ibooks/id364709193?mt=8" public let appStoreId = "364709193" public init() {} } } // MARK: - Actions public extension Applications.Ibooks { enum Action { case open } } extension Applications.Ibooks.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
mit
00a42540452a40ccf737f3ee3a430993
20.212766
90
0.537613
4.615741
false
false
false
false
bravelocation/yeltzland-ios
YeltzlandWidget/WidgetTimelineData.swift
1
1350
// // WidgetTimelineData.swift // YeltzlandWidgetExtension // // Created by John Pollard on 09/09/2020. // Copyright © 2020 John Pollard. All rights reserved. // import WidgetKit import SwiftUI struct WidgetTimelineData: TimelineEntry { let date: Date let first: TimelineFixture? let second: TimelineFixture? let table: LeagueTable? var relevance: TimelineEntryRelevance? { if let firstMatch = first { if firstMatch.status == .inProgress { return TimelineEntryRelevance(score: 10.0) } if firstMatch.isToday { return TimelineEntryRelevance(score: 5.0) } } return TimelineEntryRelevance(score: 1.0) } var endOfSeason: Bool { get { // If we only have one entry, it's a result from more than a day ago, it must be the end of the season if second != nil { return false } if let first = first { return first.status == .result && first.daysSinceResult > 1 } return false } } var showInProgressView: Bool { if let first = first { return first.showAsInProgress } return false } }
mit
533240c1fbce7e8923e4e1b37a843c1e
23.981481
114
0.542624
4.684028
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Discover/Controllers/StarInteractiveViewController.swift
3
3890
// // StarInteractiveViewController.swift // iOSStar // // Created by J-bb on 17/7/6. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import MJRefresh class StarInteractiveViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dataSource:[StarSortListModel]? var imageNames:[String]? let header = MJRefreshNormalHeader() override func viewDidLoad() { super.viewDidLoad() header.setRefreshingTarget(self, refreshingAction: #selector(requestStar)) self.tableView!.mj_header = header self.tableView.mj_header.beginRefreshing() tableView.register(NoDataCell.self, forCellReuseIdentifier: "NoDataCell") configImageNames() // requestStar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func configImageNames() { imageNames = [] for index in 0...10 { imageNames?.append("starList_back\(index)") } } func requestStar() { let requestModel = StarSortListRequestModel() AppAPIHelper.discoverAPI().requestStarList(requestModel: requestModel, complete: { (response) in if let models = response as? [StarSortListModel] { self.header.endRefreshing() self.dataSource = models self.tableView.reloadData() } self.header.endRefreshing() }) { (error) in self.header.endRefreshing() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if dataSource == nil || dataSource!.count == 0{ return } if let indexPath = sender as? IndexPath { let model = dataSource![indexPath.item] let vc = segue.destination if segue.identifier == "InterToIntroduce" { if let introVC = vc as? StarIntroduceViewController { introVC.starModel = model } } if segue.identifier == "StarNewsVC" { if let introVC = vc as? StarNewsVC { introVC.starModel = model } } } } } extension StarInteractiveViewController:UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.dataSource == nil ? UIScreen.main.bounds.size.height - 150 : 130 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.count ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.dataSource == nil{ let cell = tableView.dequeueReusableCell(withIdentifier: NoDataCell.className(), for: indexPath) as! NoDataCell cell.imageView?.image = UIImage.init(named: "nodata") return cell } let cell = tableView.dequeueReusableCell(withIdentifier: StarInfoCell.className(), for: indexPath) as! StarInfoCell cell.setStarModel(starModel:dataSource![indexPath.row]) cell.setBackImage(imageName: (imageNames?[indexPath.row % 10])!) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if dataSource == nil || dataSource?.count == 0{ return } if checkLogin(){ if let model: StarSortListModel = dataSource![indexPath.row] as? StarSortListModel{ ShareDataModel.share().selectStarCode = model.symbol performSegue(withIdentifier: StarNewsVC.className(), sender: indexPath) } } } }
gpl-3.0
ce7a4f0d460ccc07613a71d677ca7709
32.8
123
0.602521
5.121212
false
false
false
false
DianQK/rx-sample-code
RxDataSourcesExample/CellIdentifierTableViewController.swift
1
1107
// // CellIdentifierTableViewController.swift // RxDataSourcesExample // // Created by DianQK on 03/10/2016. // Copyright © 2016 T. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxExtensions private struct Option { let title: String let isOn: Bool init(title: String, isOn: Bool) { self.title = title self.isOn = isOn } } /// 5_1_2 class CellIdentifierTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = nil tableView.delegate = nil let items = Observable.just([ Option(title: "选项一", isOn: true), Option(title: "选项二", isOn: false), Option(title: "选项三", isOn: true), ]) items .bindTo(tableView.rx.items(cellIdentifier: "TipTableViewCell", cellType: TipTableViewCell.self)) { (row, element, cell) in cell.title = element.title cell.isOn = element.isOn } .disposed(by: rx.disposeBag) } }
mit
60173242b5a6eb16fee54ff7be163746
22.148936
134
0.60386
4.266667
false
false
false
false
KittenYang/A-GUIDE-TO-iOS-ANIMATION
Swift Version/DownloadButtonDemo-Swift/CADemos-Swift/Classes/DownloadButton.swift
1
7001
// // DownloadButton.swift // CADemos-Swift // // Created by Kitten Yang on 12/30/15. // Copyright © 2015 Kitten Yang. All rights reserved. // import UIKit let kRadiusShrinkAnim = "cornerRadiusShrinkAnim" let kRadiusExpandAnim = "radiusExpandAnimation" let kProgressBarAnimation = "progressBarAnimation" let kCheckAnimation = "checkAnimation" class DownloadButton: UIView { var progressBarHeight: CGFloat = 0.0 var progressBarWidth: CGFloat = 0.0 private var originframe: CGRect = CGRectZero private var animating: Bool = false override init(frame: CGRect) { super.init(frame: frame) setUpViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpViews() } private func setUpViews(){ let tapGes = UITapGestureRecognizer(target: self, action: "handleButtonDidTapped:") addGestureRecognizer(tapGes) } @objc private func handleButtonDidTapped(gesture: UITapGestureRecognizer){ if animating { return } animating = true originframe = frame if let subLayers = layer.sublayers{ for subLayer in subLayers{ subLayer.removeFromSuperlayer() } } backgroundColor = UIColor(red: 0.0, green: 122/255.0, blue: 255/255.0, alpha: 1.0) layer.cornerRadius = progressBarHeight / 2 let radiusShrinkAnimation = CABasicAnimation(keyPath: "cornerRadius") radiusShrinkAnimation.duration = 0.2 radiusShrinkAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) radiusShrinkAnimation.fromValue = originframe.height / 2 radiusShrinkAnimation.delegate = self layer.addAnimation(radiusShrinkAnimation, forKey: kRadiusShrinkAnim) } private func progressBarAnimation() { let progressLayer = CAShapeLayer() let path = UIBezierPath() path.moveToPoint(CGPoint(x: progressBarHeight / 2, y: self.frame.height / 2)) path.addLineToPoint(CGPointMake(bounds.size.width - progressBarHeight / 2, bounds.size.height / 2)) progressLayer.path = path.CGPath progressLayer.strokeColor = UIColor.whiteColor().CGColor progressLayer.lineWidth = progressBarHeight - 6 progressLayer.lineCap = kCALineCapRound layer.addSublayer(progressLayer) let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = 2.0 pathAnimation.fromValue = 0.0 pathAnimation.toValue = 1.0 pathAnimation.delegate = self pathAnimation.setValue(kProgressBarAnimation, forKey: "animationName") progressLayer.addAnimation(pathAnimation, forKey: nil) } private func checkAnimation() { let checkLayer = CAShapeLayer() let path = UIBezierPath() let rectInCircle = CGRectInset(self.bounds, self.bounds.size.width*(1-1/sqrt(2.0))/2, self.bounds.size.width*(1-1/sqrt(2.0))/2) path.moveToPoint(CGPoint(x: rectInCircle.origin.x + rectInCircle.size.width/9, y: rectInCircle.origin.y + rectInCircle.size.height*2/3)) path.addLineToPoint(CGPoint(x: rectInCircle.origin.x + rectInCircle.size.width/3,y: rectInCircle.origin.y + rectInCircle.size.height*9/10)) path.addLineToPoint(CGPoint(x: rectInCircle.origin.x + rectInCircle.size.width*8/10, y: rectInCircle.origin.y + rectInCircle.size.height*2/10)) checkLayer.path = path.CGPath checkLayer.fillColor = UIColor.clearColor().CGColor checkLayer.strokeColor = UIColor.whiteColor().CGColor checkLayer.lineWidth = 10.0 checkLayer.lineCap = kCALineCapRound checkLayer.lineJoin = kCALineJoinRound self.layer.addSublayer(checkLayer) let checkAnimation = CABasicAnimation(keyPath: "strokeEnd") checkAnimation.duration = 0.3; checkAnimation.fromValue = 0.0 checkAnimation.toValue = 1.0 checkAnimation.delegate = self checkAnimation.setValue(kCheckAnimation, forKey:"animationName") checkLayer.addAnimation(checkAnimation,forKey:nil) } } extension DownloadButton { // MARK : CAAnimationDelegate override func animationDidStart(anim: CAAnimation) { if anim.isEqual(self.layer.animationForKey(kRadiusShrinkAnim)) { UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in self.bounds = CGRect(x: 0, y: 0, width: self.progressBarWidth, height: self.progressBarHeight) }, completion: { (finished) -> Void in self.layer.removeAllAnimations() self.progressBarAnimation() }) }else if anim.isEqual(self.layer.animationForKey(kRadiusExpandAnim)){ UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in self.bounds = CGRect(x: 0, y: 0, width: self.originframe.width, height: self.originframe.height) self.backgroundColor = UIColor(red: 0.1803921568627451, green: 0.8, blue: 0.44313725490196076, alpha: 1.0) }, completion: { (finished) -> Void in self.layer.removeAllAnimations() self.checkAnimation() self.animating = false }) } } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if let animationName = anim.valueForKey("animationName") where animationName.isEqualToString(kProgressBarAnimation) { UIView.animateWithDuration(0.3, animations: { () -> Void in if let sublayers = self.layer.sublayers{ for subLayer in sublayers { subLayer.opacity = 0.0 } } }, completion: { (finished) -> Void in if let sublayers = self.layer.sublayers{ for sublayer in sublayers { sublayer.removeFromSuperlayer() } } self.layer.cornerRadius = self.originframe.height / 2 let radiusExpandAnimation = CABasicAnimation(keyPath: "cornerRadius") radiusExpandAnimation.duration = 0.2 radiusExpandAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) radiusExpandAnimation.fromValue = self.progressBarHeight / 2 radiusExpandAnimation.delegate = self self.layer.addAnimation(radiusExpandAnimation, forKey: kRadiusExpandAnim) }) } } }
gpl-2.0
16445a1aa8ff33c9476adcf281074319
43.303797
164
0.634286
4.837595
false
false
false
false
Drusy/auvergne-webcams-ios
Carthage/Checkouts/realm-cocoa/examples/ios/swift/Backlink/AppDelegate.swift
1
2281
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift class Dog: Object { @objc dynamic var name = "" @objc dynamic var age = 0 // Define "owners" as the inverse relationship to Person.dogs let owners = LinkingObjects(fromType: Person.self, property: "dogs") } class Person: Object { @objc dynamic var name = "" let dogs = List<Dog>() } #if !swift(>=4.2) extension UIApplication { typealias LaunchOptionsKey = UIApplicationLaunchOptionsKey } #endif @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIViewController() window?.makeKeyAndVisible() do { try FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!) } catch {} let realm = try! Realm() try! realm.write { realm.create(Person.self, value: ["John", [["Fido", 1]]]) realm.create(Person.self, value: ["Mary", [["Rex", 2]]]) } // Log all dogs and their owners using the "owners" inverse relationship let allDogs = realm.objects(Dog.self) for dog in allDogs { let ownerNames = dog.owners.map { $0.name } print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))") } return true } }
apache-2.0
22fa2045502c6f1dce11c6d738a7fdf3
32.057971
151
0.625164
4.683778
false
false
false
false
fancymax/12306ForMac
12306ForMac/Model/QueryOrderWaitTimeResult.swift
1
777
// // QueryOrderWaitTimeResult.swift // 12306ForMac // // Created by fancymax on 16/3/3. // Copyright © 2016年 fancy. All rights reserved. // import Foundation import SwiftyJSON class QueryOrderWaitTimeResult{ var queryOrderWaitTimeStatus: Bool? var count:Int? var waitTime:Int? // var requestId: var waitCount:Int? var tourFlag:String? var orderId:String? var msg:String? init(json:JSON) { queryOrderWaitTimeStatus = json["queryOrderWaitTimeStatus"].boolValue count = json["count"].intValue waitTime = json["waitTime"].intValue waitCount = json["waitCount"].intValue tourFlag = json["tourFlag"].string orderId = json["orderId"].string msg = json["msg"].string } }
mit
2a2e93301a225f8e32d6c8762ce5b7fd
23.1875
77
0.655039
3.94898
false
false
false
false
IDLabs-Gate/EyeLearn-Swift
EyeLearn/ViewController.swift
1
6352
// The MIT License (MIT) // // Copyright (c) 2016 ID Labs L.L.C. // // 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 enum PredictionState: Int { case start case learningPlus case waiting case learningMinus case predicting } class ViewController: UIViewController { @IBOutlet weak var thumbPreview: UIImageView! @IBOutlet weak var announcer: UILabel! @IBOutlet weak var learnButton: UIButton! @IBOutlet weak var learningProgressView: UIProgressView! @IBOutlet weak var learningLabel: UILabel! @IBOutlet weak var toggleCamButton: UIButton! var state = PredictionState.start var sourcePixelFormat = OSType() var clap = CGRect() var selectRect : CGRect? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black learningProgressView.isHidden = true learningLabel.isHidden = true view.addActivityIndicatorOverlay { self.setupCam(){ self.loadAllPredictors() self.resumeFrames() self.view.removeActivityIndicatorOverlay() } } } //MARK: Actions @IBAction func tapAction(_ sender: AnyObject) { let tap = sender.location(in: view) if selectRect == nil { let height = 0.4 * view.bounds.height let width = 0.4 * view.bounds.width let rect = CGRect(x: tap.x-width/2, y: tap.y-height/2, width: width, height: height).keepWithin(view.bounds) let selectLayer = self.addLayer(name: "SelectLayer", image: UIImage(named: "square2")!, toLayer: view.layer) selectLayer.frame = rect selectRect = rect } else { //deselect selectRect = nil removeLayers(name: "SelectLayer", fromLayer: view.layer) } } @IBAction func learnAction(_ sender: AnyObject) { switch state { case .start, .predicting: newPredictorAlert() case .learningPlus, .learningMinus: cancelLearning() case .waiting: startLearningMinus() } } @IBAction func predictorsAction(_ sender: UIView) { let docsDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: docsDir) guard files.count>0 else { actionSheet(title: "No Predictors", itemNames: [String](), actionHandler: nil, fromSourceView: sender, lastRed: false) return } let items = files+["Delete All"] actionSheet(title: "Predictors", itemNames: items , actionHandler: { (i, name) -> () in guard i != items.count else { self.resetPredictors() return } self.YesNoAlert(title: "Delete Predictor: "+name+" ?"){ self.deletePredictor(name) } }, fromSourceView: sender, lastRed: true) } catch let error as NSError { print("could not get contents of directory at \(docsDir)") print(error.localizedDescription) } } //MARK: Utils func addLayer(name: String, image: UIImage, toLayer parent: CALayer) -> CALayer{ //remove previous layer removeLayers(name: name, fromLayer: parent) let layer = CALayer() layer.contents = image.cgImage layer.name = name parent.addSublayer(layer) return layer } func removeLayers(name: String, fromLayer parent: CALayer){ guard let layers = parent.sublayers else { return } var rmv = [CALayer]() for l in layers { if l.name == name { rmv.append(l) } } for l in rmv { l.removeFromSuperlayer() } } //MARK: Orientation override var shouldAutorotate : Bool { return false } /* override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { orientCam() }*/ override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .landscapeRight } override var prefersStatusBarHidden : Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
76928f980536f18f25ae556bcd2aaa3d
27.742081
136
0.559037
5.355818
false
false
false
false
tripleCC/GanHuoCode
GanHuo/Util/TPCStorageUtil.swift
1
3314
// // TPCStorageUtil.swift // WKCC // // Created by tripleCC on 15/11/28. // Copyright © 2015年 tripleCC. All rights reserved. // import Foundation class TPCStorageUtil { let fileManager = NSFileManager.defaultManager() static let shareInstance = TPCStorageUtil() func removeFileAtPath(path: String ,predicateClosure predicate: ((fileName: String) -> Bool)? = nil) { let fileEnumerator = fileManager.enumeratorAtPath(path) if let fileEnumerator = fileEnumerator { for fileName in fileEnumerator { if predicate == nil || predicate!(fileName: fileName as! String) { let filePath = path + "/\(fileName)" do { try fileManager.removeItemAtPath(filePath) } catch { } } } } } func clearFileCache(completion: (() -> ())? = nil) { func clearFile() { removeFileAtPath(TPCStorageUtil.shareInstance.directoryForTechnicalDictionary) } if completion == nil { clearFile() } else { dispatchGlobal({ () -> () in clearFile() dispatchSMain({ () -> () in completion!() }) }) } } func sizeOfFileAtPath(path: String, predicateClosure predicate: ((fileName: String) -> Bool)? = nil) -> UInt64 { var fileSize : UInt64 = 0 let fileEnumerator = fileManager.enumeratorAtPath(path) if let fileEnumerator = fileEnumerator { for fileName in fileEnumerator { if predicate == nil || predicate!(fileName: fileName as! String) { let filePath = path + "/\(fileName)" if let attr = try? NSFileManager.defaultManager().attributesOfItemAtPath(filePath) as NSDictionary { fileSize += attr.fileSize(); } } } } return fileSize } static func setObject(value: AnyObject?, forKey defaultName: String, suiteName name: String? = nil) { if name != nil { NSUserDefaults(suiteName: name)?.setObject(value, forKey: defaultName) } else { NSUserDefaults.standardUserDefaults().setObject(value, forKey: defaultName) } } static func objectForKey(defaultName: String, suiteName name: String? = nil) -> AnyObject? { guard name != nil else { return NSUserDefaults.standardUserDefaults().objectForKey(defaultName) } return NSUserDefaults(suiteName: name)?.objectForKey(defaultName) } static func setFloat(value: Float, forKey defaultName: String) { NSUserDefaults.standardUserDefaults().setFloat(value, forKey: defaultName) } static func floatForKey(defaultName: String) -> Float { return NSUserDefaults.standardUserDefaults().floatForKey(defaultName) } static func setBool(value: Bool, forKey defaultName: String) { NSUserDefaults.standardUserDefaults().setBool(value, forKey: defaultName) } static func boolForKey(defaultName: String) -> Bool { return NSUserDefaults.standardUserDefaults().boolForKey(defaultName) } }
mit
4a334641acc2aa009d9b380cc28772a2
34.98913
120
0.58653
5.401305
false
false
false
false
google/swift-structural
Sources/StructuralBenchmarks/MyEncodeJSONBenchmarks.swift
1
2031
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Benchmark import Foundation import StructuralCore import StructuralExamples let myEncodeJSONBenchmarks = BenchmarkSuite(name: "MyEncodeJSON") { suite in suite.benchmark("Point1") { stringSink = toJSONString(p1_1) } suite.benchmark("Point2") { stringSink = toJSONString(p2_1) } suite.benchmark("Point3") { stringSink = toJSONString(p3_1) } suite.benchmark("Point4") { stringSink = toJSONString(p4_1) } suite.benchmark("Point5") { stringSink = toJSONString(p5_1) } suite.benchmark("Point6") { stringSink = toJSONString(p6_1) } suite.benchmark("Point7") { stringSink = toJSONString(p7_1) } suite.benchmark("Point8") { stringSink = toJSONString(p8_1) } suite.benchmark("Point9") { stringSink = toJSONString(p9_1) } suite.benchmark("Point10") { stringSink = toJSONString(p10_1) } suite.benchmark("Point11") { stringSink = toJSONString(p11_1) } suite.benchmark("Point12") { stringSink = toJSONString(p12_1) } suite.benchmark("Point13") { stringSink = toJSONString(p13_1) } suite.benchmark("Point14") { stringSink = toJSONString(p14_1) } suite.benchmark("Point15") { stringSink = toJSONString(p15_1) } suite.benchmark("Point16") { stringSink = toJSONString(p16_1) } }
apache-2.0
92c0182e0a669b9010b53693ff9f2800
22.616279
76
0.64451
3.846591
false
false
false
false
Cin316/X-Schedule
XScheduleKit/XScheduleDownloader.swift
1
3962
// // XScheduleDownloader.swift // X Schedule // // Created by Nicholas Reichert on 2/17/15. // Copyright (c) 2015 Nicholas Reichert. // import Foundation open class XScheduleDownloader: ScheduleDownloader { private static var scheduleCalenderID: String = "27" private static var scheduleURL: URL = URL(string: "https://www.stxavier.org/cf_calendar/export.cfm")! open override class func downloadSchedule(_ date: Date, completionHandler: @escaping (String) -> Void, errorHandler: @escaping (String) -> Void) -> URLSessionTask { //Download today's schedule from the St. X website. NSLog("[XScheduleDownloader] Sending new schedule download request to stxavier.org for date \(date)") //Create objects for network request. let postData: Data = requestDataForDate(date) let request: URLRequest = scheduleWebRequest() let session: URLSession = scheduleSession() //Create NSURLSessionUploadTask out of desired objects. let postSession: URLSessionTask = session.uploadTask(with: request, from: postData, completionHandler: { ( data: Data?, response: URLResponse?, error: Error?) -> Void in //Convert output to a string. var output: String if let data = data { output = String(data: data, encoding: String.Encoding.utf8)! } else { output = "" } if (error == nil) { //Call completion handler with string. completionHandler(output) } else { // If there is an error... if ( self.errorShouldBeHandled(error!) ) { errorHandler(error!.localizedDescription) } } } ) //Start POST request. postSession.resume() return postSession } private class func scheduleWebRequest() -> URLRequest { //Create a new NSURLRequest with the correct parameters to download schedule from St. X Website. let request = NSMutableURLRequest(url: scheduleURL) request.httpMethod = "POST" request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") return request as URLRequest } private class func scheduleSession() -> URLSession { //Create a new NSURLSession with default settings. let config = URLSessionConfiguration.default let session = URLSession(configuration: config) return session } private class func requestDataForDate(_ date: Date) -> Data { //Create NSData object to send in body of POST request. let escapedDate = uploadStringForDate(date) let postString: NSString = "export_format=xml&start=\(escapedDate)&end=\(escapedDate)&calendarId=\(scheduleCalenderID)" as NSString let postData: Data = postString.data(using: String.Encoding.utf8.rawValue)! return postData } private class func uploadStringForDate(_ date: Date) -> String { //Returns a correctly formatted string to upload in as a POST parameter. let dateFormat: DateFormatter = DateFormatter() dateFormat.dateFormat = "MM/dd/yyyy" dateFormat.locale = Locale(identifier: "en_US_POSIX") let formattedDate: String = dateFormat.string(from: date) let escapedDate: String = formattedDate.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! return escapedDate } private class func errorShouldBeHandled(_ error: Error) -> Bool { let nsError: NSError = error as NSError var ignoredError: Bool = false ignoredError = ignoredError || (nsError.domain==NSURLErrorDomain && nsError.code==NSURLErrorCancelled) return !ignoredError } }
mit
6cd23014f581b339c1b09cc683db4a58
41.602151
168
0.625189
5.145455
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/URLSession/ftp/FTPURLProtocol.swift
1
5189
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif import CoreFoundation import Dispatch internal class _FTPURLProtocol: _NativeProtocol { public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(task: task, cachedResponse: cachedResponse, client: client) } public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(request: request, cachedResponse: cachedResponse, client: client) } override class func canInit(with request: URLRequest) -> Bool { // TODO: Implement sftp and ftps guard request.url?.scheme == "ftp" else { return false } return true } override func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action { guard case .transferInProgress(let ts) = internalState else { fatalError("Received body data, but no transfer in progress.") } guard let task = task else { fatalError("Received header data but no task available.") } task.countOfBytesExpectedToReceive = contentLength > 0 ? contentLength : NSURLSessionTransferSizeUnknown do { let newTS = try ts.byAppendingFTP(headerLine: data, expectedContentLength: contentLength) internalState = .transferInProgress(newTS) let didCompleteHeader = !ts.isHeaderComplete && newTS.isHeaderComplete if didCompleteHeader { // The header is now complete, but wasn't before. didReceiveResponse() } return .proceed } catch { return .abort } } override func configureEasyHandle(for request: URLRequest) { easyHandle.set(verboseModeOn: enableLibcurlDebugOutput) easyHandle.set(debugOutputOn: enableLibcurlDebugOutput, task: task!) easyHandle.set(skipAllSignalHandling: true) guard let url = request.url else { fatalError("No URL in request.") } easyHandle.set(url: url) easyHandle.set(preferredReceiveBufferSize: Int.max) do { switch (task?.body, try task?.body.getBodyLength()) { case (.some(URLSessionTask._Body.none), _): set(requestBodyLength: .noBody) case (_, .some(let length)): set(requestBodyLength: .length(length)) task!.countOfBytesExpectedToSend = Int64(length) case (_, .none): set(requestBodyLength: .unknown) } } catch let e { // Fail the request here. // TODO: We have multiple options: // NSURLErrorNoPermissionsToReadFile // NSURLErrorFileDoesNotExist self.internalState = .transferFailed let error = NSError(domain: NSURLErrorDomain, code: errorCode(fileSystemError: e), userInfo: [NSLocalizedDescriptionKey: "File system error"]) failWith(error: error, request: request) return } let timeoutHandler = DispatchWorkItem { [weak self] in guard let _ = self?.task else { fatalError("Timeout on a task that doesn't exist") } //this guard must always pass self?.internalState = .transferFailed let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)) self?.completeTask(withError: urlError) self?.client?.urlProtocol(self!, didFailWithError: urlError) } guard let task = self.task else { fatalError() } easyHandle.timeoutTimer = _TimeoutSource(queue: task.workQueue, milliseconds: Int(request.timeoutInterval) * 1000, handler: timeoutHandler) easyHandle.set(automaticBodyDecompression: true) } } /// Response processing internal extension _FTPURLProtocol { /// Whenever we receive a response (i.e. a complete header) from libcurl, /// this method gets called. func didReceiveResponse() { guard let _ = task as? URLSessionDataTask else { return } guard case .transferInProgress(let ts) = self.internalState else { fatalError("Transfer not in progress.") } guard let response = ts.response else { fatalError("Header complete, but not URL response.") } guard let session = task?.session as? URLSession else { fatalError() } switch session.behaviour(for: self.task!) { case .noDelegate: break case .taskDelegate: self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) case .dataCompletionHandler: break case .downloadCompletionHandler: break } } }
apache-2.0
02c93c15bfc287a4150f2091489534cd
43.732759
147
0.650992
5.082272
false
false
false
false
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter11-SwiftUI-concurrency-with-async-await/05-Implementing-infinite-scrolling-with-async-await/CoolGifList/CoolGifList/ContentView.swift
1
2194
// // ContentView.swift // CoolGifList // // Created by Giordano Scalzo on 12/10/2021. // import SwiftUI import NukeUI struct Gif: Identifiable, Codable, Equatable { static func == (lhs: Gif, rhs: Gif) -> Bool { lhs.id == rhs.id } let id: String let title: String var url: String { images.downsized.url } let images: Images } struct Images: Codable { let downsized: Image } struct Image: Codable { let url: String } struct Response: Codable { let data: [Gif] } struct Service { private let apiKey = <INSERT YOUR KEY> private let pageSize = 10 private let query = "cat" private let decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder }() func fetchGifs(page: Int) async -> [Gif] { let offset = page * pageSize guard let url = URL(string: "https://api.giphy.com/v1/gifs/search?api_key=\(apiKey)&q=\(query)&limit=\(pageSize)&offset=\(offset)") else { return [] } do { let (data, _) = try await URLSession .shared .data(from: url) let response = try decoder.decode(Response.self, from: data) return response.data } catch { print(error) return [] } } } struct ContentView: View { let service = Service() @State var gifs: [Gif] = [] @State var page = 0 var body: some View { List(gifs) { gif in VStack { LazyImage(source: gif.url) .aspectRatio(contentMode: .fit) Text(gif.title) } .task { if gif == gifs.last { page += 1 gifs += await service.fetchGifs(page: page) } } } .listStyle(.plain) .task { gifs = await service.fetchGifs(page: page) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
9caf8345392cdbe116efce7e01ec2148
21.618557
135
0.516408
4.22736
false
false
false
false
jalehman/twitter-clone
TwitterClient/Tweet.swift
1
2356
// // Tweet.swift // TwitterClient // // Created by Josh Lehman on 2/19/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import Foundation class Tweet: NSObject { // TODO: Make createdAt lazy // TODO: Static date formatter? var user: User? var text: String? var createdAtString: String? var createdAt: NSDate? var favoriteCount: Int? var retweetCount: Int? var retweetedBy: User? = nil var tweetId: Int? var retweeted: Bool = false var favorited: Bool = false var inReplyToStatusId: Int? var dictionary: NSDictionary? init(text: String, inReplyToStatusId: Int? = nil) { self.text = text self.user = User.currentUser self.createdAt = NSDate() self.createdAtString = DateService.sharedInstance.formatter.stringFromDate(self.createdAt!) self.inReplyToStatusId = inReplyToStatusId super.init() } init(dictionary: NSDictionary) { if let retweet = dictionary["retweeted_status"] as? NSDictionary { self.retweetedBy = User(dictionary: dictionary["user"] as! NSDictionary) self.user = User(dictionary: retweet["user"] as! NSDictionary) self.text = retweet["text"] as? String self.createdAtString = retweet["created_at"] as? String self.favoriteCount = retweet["favorite_count"] as? Int self.retweetCount = retweet["retweet_count"] as? Int } else { self.user = User(dictionary: dictionary["user"] as! NSDictionary) self.text = dictionary["text"] as? String self.createdAtString = dictionary["created_at"] as? String self.favoriteCount = dictionary["favorite_count"] as? Int self.retweetCount = dictionary["retweet_count"] as? Int } self.retweeted = dictionary["retweeted"] as! Bool self.favorited = dictionary["favorited"] as! Bool self.tweetId = dictionary["id"] as? Int self.dictionary = dictionary let dateService = DateService.sharedInstance createdAt = dateService.formatter.dateFromString(self.createdAtString!) super.init() } class func tweetsWithArray(array: [NSDictionary]) -> [Tweet] { return array.map { Tweet(dictionary: $0) } } }
gpl-2.0
da0b20b4da810723f0b7ad128b6ef80f
34.179104
99
0.627334
4.50478
false
false
false
false
samodom/TestableCoreLocation
TestableCoreLocation/MutableHeading.swift
1
3903
// // MutableHeading.swift // TestableCoreLocation // // Created by Sam Odom on 3/6/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import CoreLocation /// Mutable subclass of `CLHeading` to be used for testing purposes. open class MutableHeading: CLHeading { /// Mutable magnetic heading of a heading. private final var _magneticHeading: CLLocationDirection = 0 open override var magneticHeading: CLLocationDirection { get { return _magneticHeading } set { _magneticHeading = newValue } } /// Mutable true heading of a heading. private final var _trueHeading: CLLocationDirection = 0 open override var trueHeading: CLLocationDirection { get { return _trueHeading } set { _trueHeading = newValue } } /// Mutable heading accuracy of a heading. private final var _headingAccuracy: CLLocationDirection = .infinity open override var headingAccuracy: CLLocationDirection { get { return _headingAccuracy } set { _headingAccuracy = newValue } } /// Mutable timestamp of a heading. private final var _timestamp = Date() open override var timestamp: Date { get { return _timestamp } set { _timestamp = newValue } } /// Mutable x heading component of a heading. private final var _x: CLHeadingComponentValue = 0 open override var x: CLHeadingComponentValue { get { return _x } set { _x = newValue } } /// Mutable y heading component of a heading. private final var _y: CLHeadingComponentValue = 0 open override var y: CLHeadingComponentValue { get { return _y } set { _y = newValue } } /// Mutable z heading component of a heading. private final var _z: CLHeadingComponentValue = 0 open override var z: CLHeadingComponentValue { get { return _z } set { _z = newValue } } public override init() { super.init() } private enum MutableHeadingEncodingKeys { static let magneticHeading = "magneticHeading" static let trueHeading = "trueHeading" static let headingAccuracy = "headingAccuracy" static let timestamp = "timestamp" static let x = "x" static let y = "y" static let z = "z" } required public init?(coder: NSCoder) { _magneticHeading = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.magneticHeading) _trueHeading = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.trueHeading) _headingAccuracy = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.headingAccuracy) if let time = coder.decodeObject(forKey: MutableHeadingEncodingKeys.timestamp) as? Date { _timestamp = time } _x = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.x) _y = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.y) _z = coder.decodeDouble(forKey: MutableHeadingEncodingKeys.z) super.init(coder: coder) } open override func encode(with coder: NSCoder) { coder.encode(magneticHeading, forKey: MutableHeadingEncodingKeys.magneticHeading) coder.encode(trueHeading, forKey: MutableHeadingEncodingKeys.trueHeading) coder.encode(headingAccuracy, forKey: MutableHeadingEncodingKeys.headingAccuracy) coder.encode(timestamp, forKey: MutableHeadingEncodingKeys.timestamp) coder.encode(x, forKey: MutableHeadingEncodingKeys.x) coder.encode(y, forKey: MutableHeadingEncodingKeys.y) coder.encode(z, forKey: MutableHeadingEncodingKeys.z) } }
mit
fbddd77ed26215b8a14a15f6229cc6f9
26.871429
97
0.628908
4.752741
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/URL+WMFLinkParsing.swift
1
6110
import Foundation extension CharacterSet { public static var wmf_articleTitlePathComponentAllowed: CharacterSet { return NSCharacterSet.wmf_URLArticleTitlePathComponentAllowed() } static let urlQueryComponentAllowed: CharacterSet = { var characterSet = CharacterSet.urlQueryAllowed characterSet.remove(charactersIn: "+&=") return characterSet }() } extension URL { /// Returns a new URL with the existing scheme replaced with the wikipedia:// scheme public var replacingSchemeWithWikipediaScheme: URL? { var components = URLComponents(url: self, resolvingAgainstBaseURL: false) components?.scheme = "wikipedia" return components?.url } public var wmf_percentEscapedTitle: String? { return wmf_titleWithUnderscores?.addingPercentEncoding(withAllowedCharacters: .wmf_articleTitlePathComponentAllowed) } public var wmf_language: String? { return (self as NSURL).wmf_language } public var wmf_title: String? { return (self as NSURL).wmf_title } public var wmf_titleWithUnderscores: String? { return (self as NSURL).wmf_titleWithUnderscores } public var wmf_databaseKey: String? { return (self as NSURL).wmf_databaseKey } public var wmf_site: URL? { return (self as NSURL).wmf_site } public func wmf_URL(withTitle title: String) -> URL? { return (self as NSURL).wmf_URL(withTitle: title) } public func wmf_URL(withFragment fragment: String) -> URL? { return (self as NSURL).wmf_URL(withFragment: fragment) } public func wmf_URL(withPath path: String, isMobile: Bool) -> URL? { return (self as NSURL).wmf_URL(withPath: path, isMobile: isMobile) } public var wmf_isNonStandardURL: Bool { return (self as NSURL).wmf_isNonStandardURL } public var wmf_wiki: String? { return wmf_language?.replacingOccurrences(of: "-", with: "_").appending("wiki") } fileprivate func wmf_URLForSharing(with wprov: String) -> URL { let queryItems = [URLQueryItem(name: "wprov", value: wprov)] var components = URLComponents(url: self, resolvingAgainstBaseURL: false) components?.queryItems = queryItems return components?.url ?? self } // URL for sharing text only public var wmf_URLForTextSharing: URL { return wmf_URLForSharing(with: "sfti1") } // URL for sharing that includes an image (for example, Share-a-fact) public var wmf_URLForImageSharing: URL { return wmf_URLForSharing(with: "sfii1") } public var canonical: URL { return (self as NSURL).wmf_canonical ?? self } public var wikiResourcePath: String? { return path.wikiResourcePath } public var wResourcePath: String? { return path.wResourcePath } public var namespace: PageNamespace? { guard let language = wmf_language else { return nil } return wikiResourcePath?.namespaceOfWikiResourcePath(with: language) } public var namespaceAndTitle: (namespace: PageNamespace, title: String)? { guard let language = wmf_language else { return nil } return wikiResourcePath?.namespaceAndTitleOfWikiResourcePath(with: language) } } extension NSRegularExpression { func firstMatch(in string: String) -> NSTextCheckingResult? { return firstMatch(in: string, options: [], range: string.fullRange) } func firstReplacementString(in string: String, template: String = "$1") -> String? { guard let result = firstMatch(in: string) else { return nil } return replacementString(for: result, in: string, offset: 0, template: template) } } extension String { static let namespaceRegex = try! NSRegularExpression(pattern: "^(.+?)_*:_*(.*)$") // Assumes the input is the remainder of a /wiki/ path func namespaceOfWikiResourcePath(with language: String) -> PageNamespace { guard let namespaceString = String.namespaceRegex.firstReplacementString(in: self) else { return .main } return WikipediaURLTranslations.commonNamespace(for: namespaceString, in: language) ?? .main } func namespaceAndTitleOfWikiResourcePath(with language: String) -> (namespace: PageNamespace, title: String) { guard let result = String.namespaceRegex.firstMatch(in: self) else { return (.main, self) } let namespaceString = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$1") guard let namespace = WikipediaURLTranslations.commonNamespace(for: namespaceString, in: language) else { return (.main, self) } let title = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$2") return (namespace, title) } static let wikiResourceRegex = try! NSRegularExpression(pattern: "^/wiki/(.+)$", options: .caseInsensitive) var wikiResourcePath: String? { return String.wikiResourceRegex.firstReplacementString(in: self) } static let wResourceRegex = try! NSRegularExpression(pattern: "^/w/(.+)$", options: .caseInsensitive) public var wResourcePath: String? { return String.wResourceRegex.firstReplacementString(in: self) } public var fullRange: NSRange { return NSRange(startIndex..<endIndex, in: self) } } @objc extension NSURL { // deprecated - use namespace methods @objc var wmf_isWikiResource: Bool { return (self as URL).wikiResourcePath != nil } } @objc extension NSString { // deprecated - use namespace methods @objc var wmf_isWikiResource: Bool { return (self as String).wikiResourcePath != nil } // deprecated - use swift methods @objc var wmf_pathWithoutWikiPrefix: String? { return (self as String).wikiResourcePath } }
mit
1c602128d2f886d942cd75dbd63faded
32.571429
124
0.65401
4.536006
false
false
false
false
daikiueda/simple-speaking-agent
simple-speaking-agent/src/model/SpeakingAction.swift
1
3121
// // SpeakingActionSetting.swift // simple-speaking-agent // // Created by うえでー on 2016/04/24. // Copyright © 2016年 Daiki UEDA. All rights reserved. // import Foundation import AVFoundation class SpeakingAction: NSObject, NSCoding { var title: String? = "みせってい" var isActive: Bool = false var actionType: ActionType? var targetKey: String? var soundType: SoundType? var speaker: Speakable? init(title: String?) { if let title = title { self.title = title } self.actionType = SpeakingAction.ActionType.Touch self.soundType = SpeakingAction.SoundType.Synthe self.isActive = true } required init(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObjectForKey("title") as? String self.isActive = aDecoder.decodeBoolForKey("isActive") self.actionType = ActionType(rawValue: aDecoder.decodeInt32ForKey("actionType")) self.targetKey = aDecoder.decodeObjectForKey("targetKey") as? String self.soundType = SoundType(rawValue: aDecoder.decodeInt32ForKey("soundType")) } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.title, forKey: "title") aCoder.encodeBool(self.isActive, forKey: "isActive") if let actionType = self.actionType { aCoder.encodeInt(actionType.rawValue, forKey: "actionType") } if let targetKey = self.targetKey { aCoder.encodeObject(targetKey, forKey: "targetKey") } if let soundType = self.soundType { aCoder.encodeInt32(soundType.rawValue, forKey: "soundType") } } func prepareSpeaker() { guard let title = self.title, soundType = self.soundType else { return } var speaker:Speakable? switch soundType { case .Media: break case .Synthe: speaker = AppleSyntheSpeaker() try! speaker!.prepare(title) } self.speaker = speaker } func speak() { guard let speaker = self.speaker else { return } speaker.speak() } enum ActionType: Int32 { case Touch = 1 case Swipe = 2 case Key = 3 func getCaption() -> String { switch self { case .Touch: return "タッチ" case .Swipe: return "スワイプ" case .Key: return "キー" } } static func cases() -> [ActionType] { return [.Touch, .Swipe, .Key] } } enum SoundType: Int32 { case Media = 1 case Synthe = 2 func getCaption() -> String { switch self { case .Media: return "音声ファイル" case .Synthe: return "合成音声" } } static func cases() -> [SoundType] { return [.Synthe, .Media] } } }
mit
3f4ebb50de0db5dfddfd94327ceb255b
24.739496
88
0.543436
4.536296
false
false
false
false