repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
daniel-beard/SwiftAndObjCAlgorithms
Algorithms/SwiftTest.swift
1
1953
// // SwiftTest.swift // Algorithms // // Created by Daniel Beard on 11/16/14. // Copyright (c) 2014 Daniel Beard. All rights reserved. // import Foundation @objc public class SwiftTest: NSObject { public func start() { let array = [5, 2, 3, 1, 7] let stringArray = ["c", "a", "z", "b", "t"] // Bubble Sort print("BubbleSort Sorted Int array: \(BubbleSort(array))") print("BubbleSort Sorted string array: \(BubbleSort(stringArray))") // Insertion Sort print("Insertion Sort Sorted Int array: \(InsertionSort(array))") print("Insertion Sort Sorted string array: \(InsertionSort(stringArray))") // Selection Sort print("Selection Sort Sorted Int array: \(SelectionSort(array))") print("Selection Sort Sorted string array: \(SelectionSort(stringArray))") print("Array: \(array)") print("Shuffled array: \(array.shuffle())") var stack = DBStack<String>() stack.push("a") stack.push("b") print("Pop: \(stack.pop())") print("Pop: \(stack.pop())") print("Pop: \(stack.pop())") var queue = DBQueue<Int>() for i in 0..<4 { queue.enqueue(i) } for _ in 0..<4 { print("Dequeue: \(queue.dequeue())") } var shuffleArray = [1, 2, 3, 4, 5, 6] shuffleArray.fisherYatesShuffle() print("Fisher-Yates shuffled array: \(shuffleArray)") var tree = Tree<Int>() tree = tree.insert(3) tree = tree.insert(2) tree = tree.insert(7) tree = tree.insert(1) tree = tree.insert(5) tree = tree.insert(6) tree = tree.insert(9) tree = tree.insert(7) print("Tree contains 2? \(tree.contains(2))") tree.inOrderTraversal() tree.inOrderPrettyPrint(tree) } }
mit
1af407e8134614dca00e698e23528656
29.061538
82
0.536098
4.128964
false
false
false
false
tjw/swift
benchmark/single-source/DataBenchmarks.swift
1
14440
//===--- DataBenchmarks.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Foundation public let DataBenchmarks = [ BenchmarkInfo(name: "DataSubscript", runFunction: run_Subscript, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataCount", runFunction: run_Count, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataSetCount", runFunction: run_SetCount, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAccessBytes", runFunction: run_AccessBytes, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataMutateBytes", runFunction: run_MutateBytes, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataCopyBytes", runFunction: run_CopyBytes, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendBytes", runFunction: run_AppendBytes, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendArray", runFunction: run_AppendArray, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReset", runFunction: run_Reset, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceSmall", runFunction: run_ReplaceSmall, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceMedium", runFunction: run_ReplaceMedium, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceLarge", runFunction: run_ReplaceLarge, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceSmallBuffer", runFunction: run_ReplaceSmallBuffer, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceMediumBuffer", runFunction: run_ReplaceMediumBuffer, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataReplaceLargeBuffer", runFunction: run_ReplaceLargeBuffer, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendSequence", runFunction: run_AppendSequence, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataSmallToSmall", runFunction: run_AppendDataSmallToSmall, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataSmallToMedium", runFunction: run_AppendDataSmallToMedium, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataSmallToLarge", runFunction: run_AppendDataSmallToLarge, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataMediumToSmall", runFunction: run_AppendDataMediumToSmall, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataMediumToMedium", runFunction: run_AppendDataMediumToMedium, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataMediumToLarge", runFunction: run_AppendDataMediumToLarge, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataLargeToSmall", runFunction: run_AppendDataLargeToSmall, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataLargeToMedium", runFunction: run_AppendDataLargeToMedium, tags: [.validation, .api, .Data]), BenchmarkInfo(name: "DataAppendDataLargeToLarge", runFunction: run_AppendDataLargeToLarge, tags: [.validation, .api, .Data]), ] enum SampleKind { case small case medium case large case veryLarge case string case immutableBacking } func sampleData(size: Int) -> Data { var data = Data(count: size) data.withUnsafeMutableBytes { arc4random_buf($0, size) } return data } func sampleString() -> Data { let bytes: [UInt8] = [ 0x4c,0x6f,0x72,0x65, 0x6d,0x20,0x69,0x70, 0x73,0x75,0x6d,0x20, 0x64,0x6f,0x6c,0x6f, 0x72,0x20,0x73,0x69, 0x74,0x20,0x61,0x6d, 0x65,0x74,0x2c,0x20, 0x63,0x6f,0x6e,0x73, 0x65,0x63,0x74,0x65, 0x74,0x75,0x72,0x20, 0x61,0x64,0x69,0x70, 0x69,0x73,0x69,0x63, 0x69,0x6e,0x67,0x20, 0x65,0x6c,0x69,0x74, 0x2c,0x20,0x73,0x65, 0x64,0x20,0x64,0x6f, 0x20,0x65,0x69,0x75, 0x73,0x6d,0x6f,0x64, 0x0a,0x74,0x65,0x6d, 0x70,0x6f,0x72,0x20, 0x69,0x6e,0x63,0x69, 0x64,0x69,0x64,0x75, 0x6e,0x74,0x20,0x75, 0x74,0x20,0x6c,0x61, 0x62,0x6f,0x72,0x65, 0x20,0x65,0x74,0x20, 0x64,0x6f,0x6c,0x6f, 0x72,0x65,0x20,0x6d, 0x61,0x67,0x6e,0x61, 0x20,0x61,0x6c,0x69, 0x71,0x75,0x61,0x2e, 0x20,0x55,0x74,0x20, 0x65,0x6e,0x69,0x6d, 0x20,0x61,0x64,0x20, 0x6d,0x69,0x6e,0x69, 0x6d,0x20,0x76,0x65, 0x6e,0x69,0x61,0x6d, 0x2c,0x0a,0x71,0x75, 0x69,0x73,0x20,0x6e, 0x6f,0x73,0x74,0x72, 0x75,0x64,0x20,0x65, 0x78,0x65,0x72,0x63, 0x69,0x74,0x61,0x74, 0x69,0x6f,0x6e,0x20, 0x75,0x6c,0x6c,0x61, 0x6d,0x63,0x6f,0x20, 0x6c,0x61,0x62,0x6f, 0x72,0x69,0x73,0x20, 0x6e,0x69,0x73,0x69, 0x20,0x75,0x74,0x20, 0x61,0x6c,0x69,0x71, 0x75,0x69,0x70,0x20, 0x65,0x78,0x20,0x65, 0x61,0x20,0x63,0x6f, 0x6d,0x6d,0x6f,0x64, 0x6f,0x0a,0x63,0x6f, 0x6e,0x73,0x65,0x71, 0x75,0x61,0x74,0x2e, 0x20,0x44,0x75,0x69, 0x73,0x20,0x61,0x75, 0x74,0x65,0x20,0x69, 0x72,0x75,0x72,0x65, 0x20,0x64,0x6f,0x6c, 0x6f,0x72,0x20,0x69, 0x6e,0x20,0x72,0x65, 0x70,0x72,0x65,0x68, 0x65,0x6e,0x64,0x65, 0x72,0x69,0x74,0x20, 0x69,0x6e,0x20,0x76, 0x6f,0x6c,0x75,0x70, 0x74,0x61,0x74,0x65, 0x20,0x76,0x65,0x6c, 0x69,0x74,0x20,0x65, 0x73,0x73,0x65,0x0a, 0x63,0x69,0x6c,0x6c, 0x75,0x6d,0x20,0x64, 0x6f,0x6c,0x6f,0x72, 0x65,0x20,0x65,0x75, 0x20,0x66,0x75,0x67, 0x69,0x61,0x74,0x20, 0x6e,0x75,0x6c,0x6c, 0x61,0x20,0x70,0x61, 0x72,0x69,0x61,0x74, 0x75,0x72,0x2e,0x20, 0x45,0x78,0x63,0x65, 0x70,0x74,0x65,0x75, 0x72,0x20,0x73,0x69, 0x6e,0x74,0x20,0x6f, 0x63,0x63,0x61,0x65, 0x63,0x61,0x74,0x20, 0x63,0x75,0x70,0x69, 0x64,0x61,0x74,0x61, 0x74,0x20,0x6e,0x6f, 0x6e,0x0a,0x70,0x72, 0x6f,0x69,0x64,0x65, 0x6e,0x74,0x2c,0x20, 0x73,0x75,0x6e,0x74, 0x20,0x69,0x6e,0x20, 0x63,0x75,0x6c,0x70, 0x61,0x20,0x71,0x75, 0x69,0x20,0x6f,0x66, 0x66,0x69,0x63,0x69, 0x61,0x20,0x64,0x65, 0x73,0x65,0x72,0x75, 0x6e,0x74,0x20,0x6d, 0x6f,0x6c,0x6c,0x69, 0x74,0x20,0x61,0x6e, 0x69,0x6d,0x20,0x69, 0x64,0x20,0x65,0x73, 0x74,0x20,0x6c,0x61, 0x62,0x6f,0x72,0x75, 0x6d,0x2e,0x0a,0x00] return Data(bytes: bytes) } func sampleBridgedNSData() -> Data { let count = 1033 var bytes = [UInt8](repeating: 0, count: count) bytes.withUnsafeMutableBufferPointer { arc4random_buf($0.baseAddress, $0.count) } let data = NSData(bytes: bytes, length: count) return Data(referencing: data) } func sampleData(_ type: SampleKind) -> Data { switch type { case .small: return sampleData(size: 11) case .medium: return sampleData(size: 1033) case .large: return sampleData(size: 40980) case .veryLarge: return sampleData(size: 1024 * 1024 * 1024 + 128) case .string: return sampleString() case .immutableBacking: return sampleBridgedNSData() } } func benchmark_AccessBytes(_ N: Int, _ data: Data) { for _ in 1...10000*N { data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) in // Ensure that the compiler does not optimize away this call blackHole(ptr.pointee) } } } func benchmark_MutateBytes(_ N: Int, _ data_: Data) { for _ in 1...10000*N { var data = data_ data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in // Mutate a byte ptr.pointee = 42 } } } func benchmark_CopyBytes(_ N: Int, _ data: Data) { let amount = data.count var buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: amount) defer { buffer.deallocate() } for _ in 1...10000*N { data.copyBytes(to: buffer, count: amount) } } func benchmark_AppendBytes(_ N: Int, _ count: Int, _ data_: Data) { let bytes = malloc(count).assumingMemoryBound(to: UInt8.self) defer { free(bytes) } for _ in 1...10000*N { var data = data_ data.append(bytes, count: count) } } func benchmark_AppendArray(_ N: Int, _ count: Int, _ data_: Data) { var bytes = [UInt8](repeating: 0, count: count) bytes.withUnsafeMutableBufferPointer { arc4random_buf($0.baseAddress, $0.count) } for _ in 1...10000*N { var data = data_ data.append(contentsOf: bytes) } } func benchmark_AppendSequence(_ N: Int, _ count: Int, _ data_: Data) { let bytes = repeatElement(UInt8(0xA0), count: count) for _ in 1...10000*N { var data = data_ data.append(contentsOf: bytes) } } func benchmark_Reset(_ N: Int, _ range: Range<Data.Index>, _ data_: Data) { for _ in 1...10000*N { var data = data_ data.resetBytes(in: range) } } func benchmark_Replace(_ N: Int, _ range: Range<Data.Index>, _ data_: Data, _ replacement: Data) { for _ in 1...10000*N { var data = data_ data.replaceSubrange(range, with: replacement) } } func benchmark_ReplaceBuffer(_ N: Int, _ range: Range<Data.Index>, _ data_: Data, _ replacement: UnsafeBufferPointer<UInt8>) { for _ in 1...10000*N { var data = data_ data.replaceSubrange(range, with: replacement) } } func benchmark_AppendData(_ N: Int, _ lhs: Data, _ rhs: Data) { var data = lhs for _ in 1...10000*N { data = lhs data.append(rhs) } } @inline(never) public func run_Subscript(_ N: Int) { let data = sampleData(.medium) let index = 521 for _ in 1...10000*N { // Ensure that the compiler does not optimize away this call blackHole(data[index]) } } @inline(never) public func run_Count(_ N: Int) { let data = sampleData(.medium) for _ in 1...10000*N { // Ensure that the compiler does not optimize away this call blackHole(data.count) } } @inline(never) public func run_SetCount(_ N: Int) { let data = sampleData(.medium) let count = data.count + 100 var otherData = data let orig = data.count for _ in 1...10000*N { otherData.count = count otherData.count = orig } } @inline(never) public func run_AccessBytes(_ N: Int) { let data = sampleData(.medium) benchmark_AccessBytes(N, data) } @inline(never) public func run_MutateBytes(_ N: Int) { let data = sampleData(.medium) benchmark_MutateBytes(N, data) } @inline(never) public func run_CopyBytes(_ N: Int) { let data = sampleData(.medium) benchmark_CopyBytes(N, data) } @inline(never) public func run_AppendBytes(_ N: Int) { let data = sampleData(.medium) benchmark_AppendBytes(N, 809, data) } @inline(never) public func run_AppendArray(_ N: Int) { let data = sampleData(.medium) benchmark_AppendArray(N, 809, data) } @inline(never) public func run_Reset(_ N: Int) { let data = sampleData(.medium) benchmark_Reset(N, 431..<809, data) } @inline(never) public func run_ReplaceSmall(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.small) benchmark_Replace(N, 431..<809, data, replacement) } @inline(never) public func run_ReplaceMedium(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.medium) benchmark_Replace(N, 431..<809, data, replacement) } @inline(never) public func run_ReplaceLarge(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.large) benchmark_Replace(N, 431..<809, data, replacement) } @inline(never) public func run_ReplaceSmallBuffer(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.small) let sz = replacement.count replacement.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) in benchmark_ReplaceBuffer(N, 431..<809, data, UnsafeBufferPointer(start: ptr, count: sz)) } } @inline(never) public func run_ReplaceMediumBuffer(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.medium) let sz = replacement.count replacement.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) in benchmark_ReplaceBuffer(N, 431..<809, data, UnsafeBufferPointer(start: ptr, count: sz)) } } @inline(never) public func run_ReplaceLargeBuffer(_ N: Int) { let data = sampleData(.medium) let replacement = sampleData(.large) let sz = replacement.count replacement.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) in benchmark_ReplaceBuffer(N, 431..<809, data, UnsafeBufferPointer(start: ptr, count: sz)) } } @inline(never) public func run_AppendSequence(_ N: Int) { let data = sampleData(.medium) benchmark_AppendSequence(N, 809, data) } @inline(never) public func run_AppendDataSmallToSmall(_ N: Int) { let data = sampleData(.small) let other = sampleData(.small) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataSmallToMedium(_ N: Int) { let data = sampleData(.medium) let other = sampleData(.small) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataSmallToLarge(_ N: Int) { let data = sampleData(.large) let other = sampleData(.small) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataMediumToSmall(_ N: Int) { let data = sampleData(.small) let other = sampleData(.medium) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataMediumToMedium(_ N: Int) { let data = sampleData(.medium) let other = sampleData(.medium) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataMediumToLarge(_ N: Int) { let data = sampleData(.large) let other = sampleData(.medium) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataLargeToSmall(_ N: Int) { let data = sampleData(.small) let other = sampleData(.large) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataLargeToMedium(_ N: Int) { let data = sampleData(.medium) let other = sampleData(.large) benchmark_AppendData(N, data, other) } @inline(never) public func run_AppendDataLargeToLarge(_ N: Int) { let data = sampleData(.large) let other = sampleData(.large) benchmark_AppendData(N, data, other) }
apache-2.0
37ce2a1e832d1ed6a1dd25520aa7a5eb
36.604167
133
0.671676
2.801707
false
false
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/View/Option/Controller/SLOptionViewController.swift
1
14106
// // SLOptionViewController.swift // ShiftLibra // // Created by LUO on 2017/7/30. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit import TPKeyboardAvoiding enum SLOptionCurrencyType : Int { case from = 1001 case to } class SLOptionViewController: UIViewController { var currency : SLCurrency? { didSet { labInfo.text = "? → \(currency?.code ?? "")" } } lazy var optionViewModel : SLOptionViewModel = SLOptionViewModel() var searchList : [SLCurrency]? var closure : ((SLCurrency)->())? var optionType : SLOptionCurrencyType = .to { didSet { switch optionType { case .from: tableViewBackgroundColor = top_left_bgColor themeTextColor = top_left_textColor tableCellViewBackgroundColor = bottom_left_bgColor textFiledColor = RGB(R: 4, G: 3, B: 7, alpha: 1) case .to: tableViewBackgroundColor = RGB(R: 55, G: 71, B: 73, alpha: 1) themeTextColor = top_right_textColor tableCellViewBackgroundColor = RGB(R: 84, G: 101, B: 102, alpha: 1) textFiledColor = RGB(R: 24, G: 41, B: 43, alpha: 1) } } } fileprivate var tableViewBackgroundColor : UIColor? fileprivate var themeTextColor : UIColor? fileprivate var tableCellViewBackgroundColor : UIColor? fileprivate let currencyID = "currencyID" fileprivate let currencyTypeID = "currencyTypeID" fileprivate var textFiled : UITextField? fileprivate var textFiledColor : UIColor? override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = tableViewBackgroundColor tableView.register(SLOptionTableViewCell.self, forCellReuseIdentifier: currencyID) tableView.register(SLOptionTableHeaderView.self, forHeaderFooterViewReuseIdentifier: currencyTypeID) tableView.rowHeight = homeDetailTableViewCellHight tableView.separatorInset = .zero tableView.separatorStyle = .none tableView.sectionHeaderHeight = 25 tableView.sectionIndexBackgroundColor = tableViewBackgroundColor tableView.sectionIndexColor = themeTextColor view.addSubview(headerView) headerView.backgroundColor = tableViewBackgroundColor headerView.backgroundColor = tableViewBackgroundColor headerView.addSubview(labInfo) labInfo.textColor = themeTextColor headerView.addSubview(searchBar) searchBar.tintColor = themeTextColor for subView in searchBar.subviews { if subView.isKind(of: UIView.self) { subView.subviews[0].removeFromSuperview() if subView.subviews[0].isKind(of: UITextField.self) { let textFiled : UITextField = subView.subviews[0] as! UITextField self.textFiled = textFiled textFiled.backgroundColor = textFiledColor textFiled.textColor = themeTextColor } } } searchBar.delegate = self headerView.addSubview(btnCancel) btnCancel.setTitleColor(self.themeTextColor, for: .normal) btnCancel.addTarget(self, action: #selector(btnCancelClick), for: .touchUpInside) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textFiled?.becomeFirstResponder() } override func viewWillLayoutSubviews() { headerView.snp.makeConstraints { (make) in make.top.equalTo(view).offset(20) make.left.right.equalTo(view) make.height.equalTo(homeHeaderHight) } tableView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.top.equalTo(headerView.snp.bottom) make.height.equalTo(SCREENH - 20 - homeHeaderHight) make.width.equalTo(SCREENW) } labInfo.snp.makeConstraints { (make) in make.centerX.equalTo(headerView) make.centerY.equalTo(headerView.snp.centerY).multipliedBy(0.5) } searchBar.snp.makeConstraints { (make) in make.left.equalTo(headerView).offset(8) make.right.equalTo(headerView).offset(-58) make.centerY.equalTo(headerView.snp.centerY).multipliedBy(1.5) } btnCancel.snp.makeConstraints { (make) in make.left.equalTo(searchBar.snp.right).offset(0) make.right.equalTo(headerView).offset(-8) make.centerY.equalTo(headerView.snp.centerY).multipliedBy(1.5) } } fileprivate lazy var scrollerView : TPKeyboardAvoidingScrollView = { let scrollerView = TPKeyboardAvoidingScrollView() return scrollerView }() fileprivate lazy var headerView: UIView = { let view = UIView() return view }() fileprivate lazy var labInfo : UILabel = { let lab = UILabel() lab.text = "? → USD" lab.font = UIFont.systemFont(ofSize: smallFontSize) lab.sizeToFit() return lab }() fileprivate lazy var searchBar : UISearchBar = { let searchBar = UISearchBar() searchBar.keyboardAppearance = .dark searchBar.barTintColor = UIColor.clear return searchBar }() fileprivate lazy var btnCancel : UIButton = { let btn = UIButton() btn.setTitle(btnCancelText, for: UIControlState.normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: smallFontSize) btn.sizeToFit() return btn }() fileprivate lazy var tableView : TPKeyboardAvoidingTableView = { let view = TPKeyboardAvoidingTableView(frame: CGRect(), style: .plain) return view }() } extension SLOptionViewController { @objc fileprivate func btnCancelClick() -> () { searchBar.endEditing(true) self.isEditing = false self.dismiss(animated: true) { } } } extension SLOptionViewController : UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if searchList != nil { return 1 } return (optionViewModel.currencyList?.count)! } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchList != nil { return (searchList?.count)! } let keys = optionViewModel.currencyTyeList let count = optionViewModel.currencyList![(keys?[section])!]?.count return count ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: currencyID, for: indexPath) as! SLOptionTableViewCell cell.backgroundColor = tableCellViewBackgroundColor cell.selectionStyle = .none cell.optionType = self.optionType if searchList != nil { cell.currency = searchList?[indexPath.row] return cell } let keys = optionViewModel.currencyTyeList let currency = optionViewModel.currencyList![(keys?[indexPath.section])!]?[indexPath.row] cell.currency = currency cell.closure = { tableView.isEditing = true } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: currencyTypeID) as! SLOptionTableHeaderView headerView.label.textColor = self.themeTextColor headerView.contentView.backgroundColor = tableViewBackgroundColor var str = optionViewModel.currencyTyeList?[section] ?? "" if str == "query" { str = indexHotText } if str == "customize" { str = indexcustomExchangeText } if searchList != nil { str = searchResultsText } headerView.label.text = str return headerView } func sectionIndexTitles(for tableView: UITableView) -> [String]? { if searchList != nil { return nil } var arr : [String] = NSMutableArray.init(array: optionViewModel.currencyTyeList!, copyItems: true) as! [String] if arr[0] == "customize" { arr.remove(at: 0) arr.remove(at: 0) arr.insert("☆", at: 0) arr.insert("★", at: 0) } else { arr.remove(at: 0) arr.insert("☆", at: 0) } return arr } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var model : SLCurrency if searchList != nil { model = (searchList?[indexPath.row])! } else { let keys = optionViewModel.currencyTyeList model = (optionViewModel.currencyList![(keys?[indexPath.section])!]?[indexPath.item])! } if model.query == "expire" && model.exchange != 0 { let alertVC = UIAlertController(title: alertVCTitle, message: alertVCMessage, preferredStyle: .alert) let confirm = UIAlertAction(title: confirmTitle, style: .default, handler: { [weak self] (_) in self?.closure?(model) self?.searchBar.resignFirstResponder() self?.dismiss(animated: true, completion: { }) }) let confirmCancel = UIAlertAction(title: btnCancelText, style: .default, handler: { (_) in return }) alertVC.addAction(confirm) alertVC.addAction(confirmCancel) self.present(alertVC, animated: true, completion: nil) return } //处理津巴布韦元 if model.exchange == 0 { let alertVC = UIAlertController(title: alertVCTitle, message: alertVCZWDMessage, preferredStyle: .alert) let confirm = UIAlertAction(title: confirmTitle, style: .default, handler: { (_) in return }) alertVC.addAction(confirm) self.present(alertVC, animated: true, completion: nil) return } closure?(model) searchBar.resignFirstResponder() self.dismiss(animated: true, completion: { }) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if (optionViewModel.customizeList?.count) ?? 0 > 0, indexPath.section == 0 { return true } return false } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { optionViewModel.deleteCustomize(index: indexPath.row) tableView.reloadData() } } extension SLOptionViewController : UISearchBarDelegate,UITextFieldDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { let str = searchBar.text ?? "" if country == "China" { searchList = SLSQLManager.shared.selectSQL(sql: "SELECT * FROM T_Currency WHERE name LIKE '%\(str)%' OR code LIKE '%\(str)%' ORDER BY code ASC;") } else { searchList = SLSQLManager.shared.selectSQL(sql: "SELECT * FROM T_Currency WHERE name LIKE '%\(str)%' OR code LIKE '%\(str)%' OR name_English LIKE '%\(str)%' ORDER BY code ASC;") } tableView.reloadData() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchList != nil, searchText == "" { searchList = nil tableView.reloadData() } } }
mit
20f7bd3c98386ac24d7dabf0cc7727ca
26.127168
190
0.521486
5.88341
false
false
false
false
dn-m/PitchSpellingTools
PitchSpellingTools/PitchSpelling+Resolution.swift
1
1232
// // PitchSpelling+Resolution.swift // PitchSpellingTools // // Created by James Bean on 5/3/16. // // import Foundation extension PitchSpelling { /** Resolution of a `PitchSpelling`. */ public enum Resolution: Float { // chromatic case halfStep = 0 // quartertone case quarterStep = 0.5 // eighth-tone case eighthStep = 0.25 } /// `Resolution` (e.g., halfstep (chromatic), quarter-step, or eighth-step) public var resolution: Resolution { return eighthStep != .none ? .eighthStep : quarterStep.resolution == .quarterStep ? .quarterStep : .halfStep } /** - returns: A `PitchSpelling` object that is quantized to the given `resolution`. */ public func quantized(to resolution: Resolution) -> PitchSpelling { switch resolution { case .quarterStep: return PitchSpelling(letterName, quarterStep, .none) case .halfStep where quarterStep.resolution == .quarterStep: return PitchSpelling(letterName, quarterStep.quantizedToHalfStep, .none) default: return self } } }
mit
b8f05fc1e9e061ef51e5bd0fef11c0b1
24.142857
85
0.582792
4.529412
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
Short Daily Devotions/Views/Cells/Info/SocialCell.swift
1
4077
// // SocialCell.swift // Short Daily Devotions // // Created by Matt Bush on 12/21/16. // Copyright © 2016 Matt Bush. All rights reserved. // import UIKit import PureLayout class SocialCell: UITableViewCell { var viewModel: MoreInfoViewModel static let kReuseIdentifier = "SocialCell" let kButtonHeight: CGFloat = 60 let wrapperView = UIView() init(viewModel: MoreInfoViewModel) { self.viewModel = viewModel super.init(style: .default, reuseIdentifier: SocialCell.kReuseIdentifier) setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupView() { backgroundColor = Style.grayLight selectionStyle = .none setupWrapperView() addSocialButtons() } private func setupWrapperView() { addSubview(wrapperView) wrapperView.autoSetDimension(.width, toSize: 240) wrapperView.autoSetDimension(.height, toSize: kButtonHeight) wrapperView.autoCenterInSuperview() } private func addSocialButtons() { addFacebookButton() addTwitterButton() addInstagramButton() } private func addFacebookButton() { guard let url = viewModel.kFacebookURL else { return } let button = socialButton(withImage: #imageLiteral(resourceName: "Facebook"), url: url) wrapperView.addSubview(button) button.autoSetDimension(.height, toSize: kButtonHeight) button.autoSetDimension(.width, toSize: kButtonHeight) button.autoAlignAxis(.horizontal, toSameAxisOf: wrapperView) button.autoPinEdge(.leading, to: .leading, of: wrapperView) makeCircle(forButton: button) button.addTarget(self, action: #selector(openFacebookURL), for: .touchUpInside) } private func addTwitterButton() { guard let url = viewModel.kTwitterURL else { return } let button = socialButton(withImage: #imageLiteral(resourceName: "Twitter"), url: url) wrapperView.addSubview(button) button.autoSetDimension(.height, toSize: kButtonHeight) button.autoSetDimension(.width, toSize: kButtonHeight) button.autoCenterInSuperview() makeCircle(forButton: button) button.addTarget(self, action: #selector(openTwitterURL), for: .touchUpInside) } private func addInstagramButton() { guard let url = viewModel.kInstagramURL else { return } let button = socialButton(withImage: #imageLiteral(resourceName: "Instagram"), url: url) wrapperView.addSubview(button) button.autoSetDimension(.height, toSize: kButtonHeight) button.autoSetDimension(.width, toSize: kButtonHeight) button.autoAlignAxis(.horizontal, toSameAxisOf: wrapperView) button.autoPinEdge(.trailing, to: .trailing, of: wrapperView) makeCircle(forButton: button) button.addTarget(self, action: #selector(openInstagramURL), for: .touchUpInside) } private func socialButton(withImage image: UIImage, url: URL) -> UIButton { let button = UIButton() button.backgroundColor = Style.pink button.clipsToBounds = true button.setImage(image, for: .normal) return button } private func makeCircle(forButton button: UIButton) { button.layer.cornerRadius = ceil(kButtonHeight / 2.0) button.layer.rasterizationScale = UIScreen.main.scale button.layer.shouldRasterize = true } @objc private func openFacebookURL() { guard let url = viewModel.kFacebookURL else { return }; UIApplication.shared.open(url, options: [:], completionHandler: nil) } @objc private func openTwitterURL() { guard let url = viewModel.kTwitterURL else { return }; UIApplication.shared.open(url, options: [:], completionHandler: nil) } @objc private func openInstagramURL() { guard let url = viewModel.kInstagramURL else { return }; UIApplication.shared.open(url, options: [:], completionHandler: nil) } }
mit
e99d88010b2621fbda3ec3b83114e0f4
38.572816
171
0.681796
4.840855
false
false
false
false
IngmarStein/swift
test/stdlib/UnicodeScalarDiagnostics.swift
4
3312
// RUN: %target-parse-verify-swift func isString(_ s: inout String) {} func test_UnicodeScalarDoesNotImplementArithmetic(_ us: UnicodeScalar, i: Int) { var a1 = "a" + "b" // OK isString(&a1) let a2 = "a" - "b" // expected-error {{binary operator '-' cannot be applied to two 'String' operands}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}} let a3 = "a" * "b" // expected-error {{binary operator '*' cannot be applied to two 'String' operands}} // expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}} let a4 = "a" / "b" // expected-error {{binary operator '/' cannot be applied to two 'String' operands}} // expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}} let b1 = us + us // expected-error {{binary operator '+' cannot be applied to two 'UnicodeScalar' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} let b2 = us - us // expected-error {{binary operator '-' cannot be applied to two 'UnicodeScalar' operands}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}} let b3 = us * us // expected-error {{binary operator '*' cannot be applied to two 'UnicodeScalar' operands}} // expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}} let b4 = us / us // expected-error {{binary operator '/' cannot be applied to two 'UnicodeScalar' operands}} // expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}} let c1 = us + i // expected-error {{binary operator '+' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}} let c2 = us - i // expected-error {{binary operator '-' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '-' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} let c3 = us * i // expected-error {{binary operator '*' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}} let c4 = us / i // expected-error {{binary operator '/' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}} let d1 = i + us // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}} let d2 = i - us // expected-error {{binary operator '-' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}} let d3 = i * us // expected-error {{binary operator '*' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}} let d4 = i / us // expected-error {{binary operator '/' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note {{expected an argument list of type '(Int, Int)'}} }
apache-2.0
acd9ab4cc659dc6ed60de0db2fa54495
96.411765
291
0.698068
4.290155
false
false
false
false
crazypoo/PTools
PooToolsSource/Permission/PTPermissionCell.swift
1
11032
// // SMZDTPermissionCell.swift // SMZDT // // Created by jax on 2022/9/3. // Copyright © 2022 Respect. All rights reserved. // import UIKit import SwifterSwift import SnapKit import SJAttributesStringMaker #if canImport(Permission) import Permission #endif #if canImport(HealthKit) import HealthKit #endif #if canImport(HealthPermission) import HealthPermission #endif #if canImport(SpeechPermission) import SpeechPermission #endif #if canImport(FaceIDPermission) import FaceIDPermission #endif #if canImport(LocationWhenInUsePermission) import LocationWhenInUsePermission #endif #if canImport(NotificationPermission) import NotificationPermission #endif #if canImport(RemindersPermission) import RemindersPermission #endif #if canImport(CalendarPermission) import CalendarPermission #endif #if canImport(PhotoLibraryPermission) import PhotoLibraryPermission #endif #if canImport(CameraPermission) import CameraPermission #endif #if canImport(TrackingPermission) import TrackingPermission #endif class PTPermissionCell: PTBaseNormalCell { static let ID = "PTPermissionCell" #if canImport(Permission) var cellStatus:Permission.Status? = .notDetermined var cellButtonTapBlock:((_ type:Permission.Kind)->Void)? #endif var cellModel:PTPermissionModel? { didSet{ #if canImport(Permission) switch cellModel!.type { case .tracking: #if canImport(TrackingPermission) if #available(iOS 14.5, *) { self.cellStatus = Permission.tracking.status } #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .camera: #if canImport(CameraPermission) self.cellStatus = Permission.camera.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .photoLibrary: #if canImport(PhotoLibraryPermission) self.cellStatus = Permission.photoLibrary.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .calendar: #if canImport(CalendarPermission) self.cellStatus = Permission.calendar.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .reminders: #if canImport(RemindersPermission) self.cellStatus = Permission.reminders.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .notification: #if canImport(NotificationPermission) self.cellStatus = Permission.notification.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .locationWhenInUse: #if canImport(LocationWhenInUsePermission) self.cellStatus = Permission.locationWhenInUse.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .faceID: #if canImport(FaceIDPermission) self.cellStatus = Permission.faceID.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .speech: #if canImport(SpeechPermission) self.cellStatus = Permission.speech.status #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif case .health: #if canImport(HealthKit) && canImport(HealthPermission) self.cellStatus = HealthPermission.status(for: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!) #else #if canImport(Permission) self.cellStatus = .notSupported #endif #endif default:break } #endif self.setButtonStatus() } } func setButtonStatus() { var permissionName = "" #if canImport(Permission) switch self.cellModel!.type { case .tracking: permissionName = "用户数据追踪" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_tracking") case .camera: permissionName = "照相机" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_camera") case .photoLibrary: permissionName = "相册" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_photoLibrary") case .calendar: permissionName = "日历" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_calendar") case .reminders: permissionName = "提醒" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_reminders") case .notification: permissionName = "通知推送" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_notification") case .locationWhenInUse: permissionName = "定位" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_location") case .speech: permissionName = "语音识别" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_speech") case .health: permissionName = "健康" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_health") case .faceID: permissionName = "FaceID" self.cellIcon.image = Bundle.imageWithName(imageName: "icon_permission_faceid") default:break } #endif self.cellTitle.attributedText = NSMutableAttributedString.sj.makeText({ make in make.append(permissionName).font(PTAppBaseConfig.share.permissionCellTitleFont).alignment(.left).textColor(PTAppBaseConfig.share.permissionCellTitleTextColor).lineSpacing(CGFloat.ScaleW(w: 3)) if !(self.cellModel?.desc ?? "").stringIsEmpty() { make.append("\n\(self.cellModel!.desc)").font(PTAppBaseConfig.share.permissionCellSubtitleFont).alignment(.left).textColor(PTAppBaseConfig.share.permissionCellSubtitleTextColor) } }) #if canImport(Permission) switch self.cellStatus { case .authorized: self.authorizedButton.isSelected = true self.authorizedButton.isUserInteractionEnabled = false self.authorizedButton.setTitle("已授权", for: .selected) case .denied: self.authorizedButton.isSelected = true self.authorizedButton.isUserInteractionEnabled = true self.authorizedButton.setTitleColor(PTAppBaseConfig.share.permissionDeniedColor, for: .selected) self.authorizedButton.setTitle("已拒绝", for: .selected) self.authorizedButton.addActionHandlers(handler: { sender in switch self.cellModel!.type { case .tracking: #if canImport(TrackingPermission) if #available(iOS 14.5, *) { Permission.tracking.openSettingPage() } #endif case .camera: #if canImport(CameraPermission) Permission.camera.openSettingPage() #endif case .photoLibrary: #if canImport(PhotoLibraryPermission) Permission.photoLibrary.openSettingPage() #endif case .calendar: #if canImport(CalendarPermission) Permission.calendar.openSettingPage() #endif case .reminders: #if canImport(RemindersPermission) Permission.reminders.openSettingPage() #endif case .notification: #if canImport(NotificationPermission) Permission.notification.openSettingPage() #endif case .locationWhenInUse: #if canImport(LocationWhenInUsePermission) Permission.locationWhenInUse.openSettingPage() #endif default:break } }) case .notDetermined: self.authorizedButton.isSelected = false self.authorizedButton.isUserInteractionEnabled = true self.authorizedButton.setTitle("询问授权", for: .normal) self.authorizedButton.addActionHandlers(handler: { sender in if self.cellButtonTapBlock != nil { self.cellButtonTapBlock!(self.cellModel!.type) } }) case .notSupported: self.authorizedButton.setTitle("不支持", for: .selected) self.authorizedButton.setTitleColor(PTAppBaseConfig.share.permissionDeniedColor, for: .selected) self.authorizedButton.isSelected = true self.authorizedButton.isUserInteractionEnabled = false default: break } #endif } fileprivate lazy var authorizedButton:UIButton = { let view = UIButton.init(type: .custom) view.titleLabel?.font = PTAppBaseConfig.share.permissionAuthorizedButtonFont view.setTitleColor(.systemBlue, for: .normal) view.setTitle("询问授权", for: .normal) view.setTitleColor(.systemBlue, for: .selected) view.setTitle("已授权", for: .selected) return view }() fileprivate lazy var cellTitle = self.pt_createLabel(text: "",bgColor: .clear) fileprivate lazy var cellIcon:UIImageView = { let view = UIImageView() view.contentMode = .scaleAspectFit return view }() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.contentView.addSubviews([self.authorizedButton,self.cellIcon,self.cellTitle]) self.authorizedButton.snp.makeConstraints { make in make.top.bottom.equalToSuperview().inset(CGFloat.ScaleW(w: 7.5)) make.right.equalToSuperview().inset(PTAppBaseConfig.share.defaultViewSpace) make.width.equalTo(PTUtils.sizeFor(string: "询问授权", font: self.authorizedButton.titleLabel!.font!, height: 24, width: CGFloat(MAXFLOAT)).width + CGFloat.ScaleW(w: 10)) } self.cellIcon.snp.makeConstraints { make in make.left.equalToSuperview().inset(PTAppBaseConfig.share.defaultViewSpace) make.top.bottom.equalToSuperview().inset(CGFloat.ScaleW(w: 5)) make.width.equalTo(self.cellIcon.snp.height) } self.cellTitle.snp.makeConstraints { make in make.left.equalTo(self.cellIcon.snp.right).offset(PTAppBaseConfig.share.defaultViewSpace) make.top.bottom.equalToSuperview() make.right.equalTo(self.authorizedButton.snp.left).offset(-PTAppBaseConfig.share.defaultViewSpace) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
48877606417ea13c06360b356ab5a11c
33.476341
204
0.649556
4.67251
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/CS_BigInt/String Conversion.swift
2
8802
// // String Conversion.swift // CS.BigInt // // Created by Károly Lőrentey on 2016-01-03. // Copyright © 2016-2017 Károly Lőrentey. // extension CS.BigUInt { //MARK: String Conversion /// Calculates the number of numerals in a given radix that fit inside a single `Word`. /// /// - Returns: (chars, power) where `chars` is highest that satisfy `radix^chars <= 2^Word.bitWidth`. `power` is zero /// if radix is a power of two; otherwise `power == radix^chars`. fileprivate static func charsPerWord(forRadix radix: Int) -> (chars: Int, power: Word) { var power: Word = 1 var overflow = false var count = 0 while !overflow { let (high,low) = power.multipliedFullWidth(by: Word(radix)) if high > 0 { overflow = true } if !overflow || (high == 1 && low == 0) { count += 1 power = low } } return (count, power) } /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by /// letters from the English alphabet. /// /// - Requires: `radix > 1 && radix < 36` /// - Parameter `text`: A string consisting of characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. public init?<S: StringProtocol>(_ text: S, radix: Int = 10) { precondition(radix > 1 && radix < 36) guard !text.isEmpty else { return nil } let (charsPerWord, power) = CS.BigUInt.charsPerWord(forRadix: radix) var words: [Word] = [] var end = text.endIndex var start = end var count = 0 while start != text.startIndex { start = text.index(before: start) count += 1 if count == charsPerWord { guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } words.append(d) end = start count = 0 } } if start != end { guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } words.append(d) } if power == 0 { self.init(words: words) } else { self.init() for d in words.reversed() { self.multiply(byWord: power) self.addWord(d) } } } } extension CS.BigInt { /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by /// letters from the English alphabet. /// /// - Requires: `radix > 1 && radix < 36` /// - Parameter `text`: A string optionally starting with "-" or "+" followed by characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. public init?<S: StringProtocol>(_ text: S, radix: Int = 10) { var magnitude: CS.BigUInt? var sign: Sign = .plus if text.first == "-" { sign = .minus let text = text.dropFirst() magnitude = CS.BigUInt(text, radix: radix) } else if text.first == "+" { let text = text.dropFirst() magnitude = CS.BigUInt(text, radix: radix) } else { magnitude = CS.BigUInt(text, radix: radix) } guard let m = magnitude else { return nil } self.magnitude = m self.sign = m.isZero ? .plus : sign } } extension String { /// Initialize a new string with the base-10 representation of an unsigned big integer. /// /// - Complexity: O(v.count^2) public init(_ v: CS.BigUInt) { self.init(v, radix: 10, uppercase: false) } /// Initialize a new string representing an unsigned big integer in the given radix (base). /// /// Numerals greater than 9 are represented as letters from the English alphabet, /// starting with `a` if `uppercase` is false or `A` otherwise. /// /// - Requires: radix > 1 && radix <= 36 /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). public init(_ v: CS.BigUInt, radix: Int, uppercase: Bool = false) { precondition(radix > 1) let (charsPerWord, power) = CS.BigUInt.charsPerWord(forRadix: radix) guard !v.isZero else { self = "0"; return } var parts: [String] if power == 0 { parts = v.words.map { String($0, radix: radix, uppercase: uppercase) } } else { parts = [] var rest = v while !rest.isZero { let mod = rest.divide(byWord: power) parts.append(String(mod, radix: radix, uppercase: uppercase)) } } assert(!parts.isEmpty) self = "" var first = true for part in parts.reversed() { let zeroes = charsPerWord - part.count assert(zeroes >= 0) if !first && zeroes > 0 { // Insert leading zeroes for mid-Words self += String(repeating: "0", count: zeroes) } first = false self += part } } /// Initialize a new string representing a signed big integer in the given radix (base). /// /// Numerals greater than 9 are represented as letters from the English alphabet, /// starting with `a` if `uppercase` is false or `A` otherwise. /// /// - Requires: radix > 1 && radix <= 36 /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). public init(_ value: CS.BigInt, radix: Int = 10, uppercase: Bool = false) { self = String(value.magnitude, radix: radix, uppercase: uppercase) if value.sign == .minus { self = "-" + self } } } extension CS.BigUInt: ExpressibleByStringLiteral { /// Initialize a new big integer from a Unicode scalar. /// The scalar must represent a decimal digit. public init(unicodeScalarLiteral value: UnicodeScalar) { self = CS.BigUInt(String(value), radix: 10)! } /// Initialize a new big integer from an extended grapheme cluster. /// The cluster must consist of a decimal digit. public init(extendedGraphemeClusterLiteral value: String) { self = CS.BigUInt(value, radix: 10)! } /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. /// The string must contain only decimal digits. public init(stringLiteral value: StringLiteralType) { self = CS.BigUInt(value, radix: 10)! } } extension CS.BigInt: ExpressibleByStringLiteral { /// Initialize a new big integer from a Unicode scalar. /// The scalar must represent a decimal digit. public init(unicodeScalarLiteral value: UnicodeScalar) { self = CS.BigInt(String(value), radix: 10)! } /// Initialize a new big integer from an extended grapheme cluster. /// The cluster must consist of a decimal digit. public init(extendedGraphemeClusterLiteral value: String) { self = CS.BigInt(value, radix: 10)! } /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. /// The string must contain only decimal digits. public init(stringLiteral value: StringLiteralType) { self = CS.BigInt(value, radix: 10)! } } extension CS.BigUInt: CustomStringConvertible { /// Return the decimal representation of this integer. public var description: String { return String(self, radix: 10) } } extension CS.BigInt: CustomStringConvertible { /// Return the decimal representation of this integer. public var description: String { return String(self, radix: 10) } } extension CS.BigUInt: CustomPlaygroundDisplayConvertible { /// Return the playground quick look representation of this integer. public var playgroundDescription: Any { let text = String(self) return text + " (\(self.bitWidth) bits)" } } extension CS.BigInt: CustomPlaygroundDisplayConvertible { /// Return the playground quick look representation of this integer. public var playgroundDescription: Any { let text = String(self) return text + " (\(self.magnitude.bitWidth) bits)" } }
mit
f42f7139c791f14b9fe3f5350817d0bb
35.654167
157
0.595885
4.380976
false
false
false
false
soapyigu/LeetCode_Swift
DP/EditDistance.swift
1
1110
/** * Question Link: https://leetcode.com/problems/edit-distance/ * Primary idea: 2D Dynamic Programming, find minimum step from * inserting, deleting, or replacing a character * Time Complexity: O(mn), Space Complexity: O(mn) */ class EditDistance { func minDistance(word1: String, _ word2: String) -> Int { let aChars = [Character](word1.characters) let bChars = [Character](word2.characters) let aLen = aChars.count let bLen = bChars.count var dp = Array(count: aLen + 1, repeatedValue:(Array(count: bLen + 1, repeatedValue: 0))) for i in 0...aLen { for j in 0...bLen { if i == 0 { dp[i][j] = j } else if j == 0 { dp[i][j] = i } else if aChars[i - 1] == bChars[j - 1] { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1 } } } return dp[aLen][bLen] } }
mit
ac3e104e13dd0aee178052c04b18a2b8
32.666667
97
0.461261
3.627451
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/Classes/Renderers/BarChartRenderer.swift
3
23738
// // BarChartRenderer.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 BarChartRenderer: ChartDataRendererBase { public weak var dataProvider: BarChartDataProvider? public init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let dataProvider = dataProvider, barData = dataProvider.barData else { return } for (var i = 0; i < barData.dataSetCount; i++) { guard let set = barData.getDataSetByIndex(i) else { continue } if set.isVisible && set.entryCount > 0 { if !(set is IBarChartDataSet) { fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset") } drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i) } } } public func drawDataSet(context context: CGContext, dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } CGContextSaveGState(context) let trans = dataProvider.getTransformer(dataSet.axisDependency) let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled let dataSetOffset = (barData.dataSetCount - 1) let groupSpace = barData.groupSpace let groupSpaceHalf = groupSpace / 2.0 let barSpace = dataSet.barSpace let barSpaceHalf = barSpace / 2.0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(dataSet.axisDependency) let barWidth: CGFloat = 0.5 let 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++) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } // calculate the x-position, depending on datasetcount let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(e.xIndex) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= 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 = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight 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 { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= 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 = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight 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) } let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top: CGFloat, bottom: CGFloat if isInverted { bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart) top = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { top = y >= yStart ? CGFloat(y) : CGFloat(yStart) bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor) CGContextFillRect(context, barRect) } } } CGContextRestoreGState(context) } /// Prepares a bar for being highlighted. public func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 let left = x - barWidth + barspacehalf let right = x + barWidth - barspacehalf let top = CGFloat(y1) let bottom = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0) } public override func drawValues(context context: CGContext) { // if values are drawn if (passesCheck()) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } var dataSets = barData.dataSets let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled var posOffset: CGFloat var negOffset: CGFloat for (var dataSetIndex = 0, count = barData.dataSetCount; dataSetIndex < count; dataSetIndex++) { guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue } if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let isInverted = dataProvider.isInverted(dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueOffsetPlus: CGFloat = 4.5 let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if (isInverted) { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } let valueTextColor = dataSet.valueTextColor guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let dataSetCount = barData.dataSetCount let groupSpace = barData.groupSpace // if only single values are drawn (sum) if (!dataSet.isStacked) { for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let valuePoint = trans.getTransformedValueBarChart( entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace ) if (!viewPortHandler.isInBoundsRight(valuePoint.x)) { break } if (!viewPortHandler.isInBoundsY(valuePoint.y) || !viewPortHandler.isInBoundsLeft(valuePoint.x)) { continue } let val = e.value drawValue(context: context, value: formatter.stringFromNumber(val)!, xPos: valuePoint.x, yPos: valuePoint.y + (val >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } } else { // if we have stacks for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let values = e.values let valuePoint = trans.getTransformedValueBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace) // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsRight(valuePoint.x)) { break } if (!viewPortHandler.isInBoundsY(valuePoint.y) || !viewPortHandler.isInBoundsLeft(valuePoint.x)) { continue } drawValue(context: context, value: formatter.stringFromNumber(e.value)!, xPos: valuePoint.x, yPos: valuePoint.y + (e.value >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } else { // draw stack values 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: 0.0, y: CGFloat(y) * animator.phaseY)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { let x = valuePoint.x let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset) if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)) { continue } drawValue(context: context, value: formatter.stringFromNumber(vals[k])!, xPos: x, yPos: y, font: valueFont, align: .Center, color: valueTextColor) } } } } } } } /// Draws a value at the specified x and y position. public func drawValue(context context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]) } public override func drawExtras(context context: CGContext) { } private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint()) public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } CGContextSaveGState(context) let setCount = barData.dataSetCount let drawHighlightArrowEnabled = dataProvider.isDrawHighlightArrowEnabled var barRect = CGRect() for (var i = 0; i < indices.count; i++) { let h = indices[i] let index = h.xIndex let dataSetIndex = h.dataSetIndex guard let set = barData.getDataSetByIndex(dataSetIndex) as? IBarChartDataSet else { continue } if (!set.isHighlightEnabled) { continue } let barspaceHalf = set.barSpace / 2.0 let trans = dataProvider.getTransformer(set.axisDependency) CGContextSetFillColorWithColor(context, set.highlightColor.CGColor) CGContextSetAlpha(context, set.highlightAlpha) // check outofbounds if (CGFloat(index) < (CGFloat(dataProvider.chartXMax) * animator.phaseX) / CGFloat(setCount)) { let e = set.entryForXIndex(index) as! BarChartDataEntry! if (e === nil || e.xIndex != index) { continue } let groupspace = barData.groupSpace let isStack = h.stackIndex < 0 ? false : true // calculate the correct x-position let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index) let y1: Double let y2: Double if (isStack) { y1 = h.range?.from ?? 0.0 y2 = h.range?.to ?? 0.0 } else { y1 = e.value y2 = 0.0 } prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect) CGContextFillRect(context, barRect) if (drawHighlightArrowEnabled) { CGContextSetAlpha(context, 1.0) // distance between highlight arrow and bar let offsetY = animator.phaseY * 0.07 CGContextSaveGState(context) let pixelToValueMatrix = trans.pixelToValueMatrix let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c)) let arrowWidth = set.barSpace / 2.0 let arrowHeight = arrowWidth * xToYRel let yArrow = (y1 > -y2 ? y1 : y1) * Double(animator.phaseY) _highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4 _highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY _highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight _highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight trans.pointValuesToPixel(&_highlightArrowPtsBuffer) CGContextBeginPath(context) CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y) CGContextClosePath(context) CGContextFillPath(context) CGContextRestoreGState(context) } } } CGContextRestoreGState(context) } internal func passesCheck() -> Bool { guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false } return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX } }
mit
3abef68b0b49c5e0b376c1edd8ccda47
40.142114
232
0.442834
6.542999
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/BlogListTableViewController.swift
1
8633
// // BlogListTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/05/19. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class BlogList: ItemList { override func toModel(json: JSON)->BaseObject { return Blog(json: json) } override func fetch(offset: Int, success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) { if working {return} self.working = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo let success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in LOG("\(result)") if self.refresh { self.items = [] } self.totalCount = total self.parseItems(result) for item in self.items as! [Blog] { item.endpoint = authInfo.endpoint item.loadSettings() item.adjustUploadDestination() } success(items: result, total: total) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } let failure: (JSON!-> Void) = { (error: JSON!)-> Void in LOG("failure:\(error.description)") failure(error) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } api.authenticationV2(authInfo.username, password: authInfo.password, remember: true, success:{_ in var params = ["limit":"20"] params["fields"] = "id,name,url,parent,allowToChangeAtUpload,uploadDestination" if !self.refresh { params["offset"] = "\(self.items.count)" } if !self.searchText.isEmpty { params["search"] = self.searchText params["searchFields"] = "name" } api.listBlogsForUser("me", options: params, success: success, failure: failure) }, failure: failure ) } } //MARK: - class BlogListTableViewController: BaseTableViewController, UISearchBarDelegate { var list: BlogList = BlogList() var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = NSLocalizedString("System", comment: "System") searchBar = UISearchBar() searchBar.frame = CGRectMake(0.0, 0.0, self.tableView.frame.size.width, 44.0) searchBar.barTintColor = Color.tableBg searchBar.placeholder = NSLocalizedString("Search", comment: "Search") searchBar.delegate = self let textField = Utils.getTextFieldFromView(searchBar) if textField != nil { textField!.enablesReturnKeyAutomatically = false } self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_setting"), left: true, target: self, action: "settingButtonPushed:") // self.tableView.estimatedRowHeight = 44.0 // self.tableView.rowHeight = UITableViewAutomaticDimension self.fetch() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Refresh @IBAction func refresh(sender:UIRefreshControl) { self.fetch() } // MARK: - fetch func fetch() { SVProgressHUD.showWithStatus(NSLocalizedString("Fetch sites...", comment: "Fetch sites...")) let success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in SVProgressHUD.dismiss() self.tableView.reloadData() self.refreshControl!.endRefreshing() } let failure: (JSON!-> Void) = { (error: JSON!)-> Void in SVProgressHUD.showErrorWithStatus(NSLocalizedString("Fetch sites failured.", comment: "Fetch sites failured.")) self.refreshControl!.endRefreshing() } list.refresh(success, failure: failure) } func more() { let success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in self.tableView.reloadData() self.refreshControl!.endRefreshing() } let failure: (JSON!-> Void) = { (error: JSON!)-> Void in self.refreshControl!.endRefreshing() } list.more(success, failure: failure) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.list.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BlogCell", forIndexPath: indexPath) self.adjustCellLayoutMargins(cell) // Configure the cell... cell.textLabel?.textColor = Color.cellText cell.textLabel?.font = UIFont.systemFontOfSize(21.0) cell.detailTextLabel?.font = UIFont.systemFontOfSize(15.0) let blog = self.list[indexPath.row] as! Blog cell.textLabel?.text = blog.name cell.detailTextLabel?.text = blog.parentName return cell } // MARK: - Table view delegte override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let storyboard: UIStoryboard = UIStoryboard(name: "Blog", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! BlogTableViewController let blog = self.list[indexPath.row] as! Blog vc.blog = blog self.navigationController?.pushViewController(vc, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 74.0 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return searchBar } //MARK: - override func scrollViewDidScroll(scrollView: UIScrollView) { if (self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height)) { if self.list.working {return} if self.list.isFinished() {return} self.more() } } //MARK: - func settingButtonPushed(sender: UIBarButtonItem) { let storyboard: UIStoryboard = UIStoryboard(name: "Setting", bundle: nil) let vc = storyboard.instantiateInitialViewController() self.presentViewController(vc!, animated: true, completion: nil) } // MARK: -- func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() self.list.searchText = searchBar.text! if self.list.count > 0 { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) } self.fetch() } }
mit
a655af962d6b18bf0958b70c34773048
34.813278
159
0.612444
5.196267
false
false
false
false
saeta/penguin
Tests/PenguinTablesTests/StringParsibleTests.swift
1
3445
// Copyright 2020 Penguin Authors // // 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 XCTest @testable import PenguinTables final class StringParsibleTests: XCTestCase { func testInt() { assertParses(expected: 3, source: " 3") assertParses(expected: 3, source: " 3 ") assertParses(expected: -100, source: " -100 ") assertParses(expected: 0, source: " 0 ") assertParseFailure(a: Int.self, from: "NaN") } func testFloat() { assertParses(expected: Float(3.14159), source: " 3.14159 ") assertParses(expected: Float(-6.28318), source: " -6.28318") assertParses(expected: -Float.infinity, source: " -Inf ") XCTAssert(Float(parsing: " NaN ")!.isNaN) // NaN's don't compare equal XCTAssert(Float(parsing: " nan ")!.isNaN) // NaN's don't compare equal assertParseFailure(a: Float.self, from: " asdf") } func testDouble() { assertParses(expected: 3.14159, source: " 3.14159 ") assertParses(expected: -6.28318, source: " -6.28318") assertParses(expected: -Double.infinity, source: " -Inf ") XCTAssert(Double(parsing: " NaN ")!.isNaN) // NaN's don't compare equal XCTAssert(Double(parsing: " nan ")!.isNaN) // NaN's don't compare equal assertParseFailure(a: Double.self, from: " asdf") } func testBool() { assertParses(expected: true, source: "t") assertParses(expected: true, source: " t ") assertParses(expected: true, source: " T ") assertParses(expected: true, source: " TrUe ") assertParses(expected: true, source: " 1 ") assertParses(expected: false, source: "f") assertParses(expected: false, source: " F ") assertParses(expected: false, source: " F ") assertParses(expected: false, source: " FaLsE ") assertParses(expected: false, source: " 0 ") assertParseFailure(a: Bool.self, from: "3") assertParseFailure(a: Bool.self, from: "asdf") assertParseFailure(a: Bool.self, from: " NaN ") } static var allTests = [ ("testInt", testInt), ("testFloat", testFloat), ("testDouble", testDouble), ("testBool", testBool), ] } fileprivate func assertParses<T: PStringParsible & Equatable>( expected: T, source: String, file: StaticString = #file, line: UInt = #line ) { let result = T(parsing: source) XCTAssertEqual(expected, result, file: file, line: line) } fileprivate func assertParseFailure<T: PStringParsible>( a type: T.Type, from source: String, reason: String? = nil, file: StaticString = #file, line: UInt = #line ) { do { let unexpected = try T(parseOrThrow: source) XCTFail( "\"\(source)\" parsed as \(type) unexpectedly as \(unexpected).", file: file, line: line) } catch { let msg = String(describing: error) if let reason = reason { XCTAssert( msg.contains(reason), "Error message \"\(msg)\" did not contain expected string \"\(reason)\".", file: file, line: line) } } }
apache-2.0
cc7d5c508d0b6c568c5f39446069c6b5
34.153061
95
0.662119
3.696352
false
true
false
false
jadnohra/learn
learn/GameScene.swift
1
38065
// // AppDelegate.swift // learn // // Created by Jad Nohra on 13/09/15. // Copyright (c) 2015 Jad Nohra. All rights reserved. // import SpriteKit // func randf() -> Float { return Float(arc4random()) / Float(UInt32.max) } func randf2(low:Float, up:Float) -> Float { return low+2.0*randf()*(up-low) } class PreRelInfo { var to: String = "" var resolved: Bool = false } class RelInfo: Equatable { var id : Int = 0 var from :LrnEntity = LrnEntity() var to :LrnEntity = LrnEntity() var node :SKShapeNode = SKShapeNode() } func ==(lhs: RelInfo, rhs: RelInfo) -> Bool { return lhs.id == rhs.id } class LrnEntity: Equatable { var id : Int = 0 var fn : String = "" var fp : String = "" var node : SKNode = SKNode() var sel_node : SKShapeNode = SKShapeNode() var type : String = "" var load_rel_to = Array<PreRelInfo>() var rel = Array<RelInfo>() var ocr : String = "" var modif : NSDate = NSDate() var scl : CGFloat = 1.0 var node_scl_add : CGFloat = 0.0 var text : String = "" var fntName : String = "PilGI" var fntSize: CGFloat = 14.0 var fntColName : String = "black" var fntCol: NSColor = NSColor.blackColor() } func ==(lhs: LrnEntity, rhs: LrnEntity) -> Bool { return lhs.id == rhs.id } class GameScene: SKScene { var dirPath = "" var sdirPath = "" let fntNames = ["PilGI", "Arial", "Deutsche Zierschrift"] let colNames = ["black":NSColor.blackColor(), "red":NSColor.redColor(), "magenta":NSColor.magentaColor(), "green":NSColor.greenColor(), "blue":NSColor.blueColor()] var id_gen :Int = 1 var rel_id_gen: Int = 1 var rroot : SKNode = SKNode() var root : SKNode = SKNode() var sel : SKNode = SKNode() var sel_ent : LrnEntity? var drag_sel : SKNode = SKNode() var entities = Array<LrnEntity>() var sel_entities = Array<LrnEntity>() var entities_by_fn = Dictionary<String, LrnEntity>() var state : String = "" var auto_note_index = 1 var auto_paste_index = 1 var last_mouse_evt = NSEvent() var time : CFTimeInterval = CFTimeInterval() var last_evt_time : CFTimeInterval = CFTimeInterval() var fcs_cpy : SKNode = SKNode() var fcs_cpy_orig : SKNode = SKNode() var drag_rect : SKShapeNode = SKShapeNode() var deferred = [""] var is_sel_dragging = false; var is_sel_moving = false; var sel_drag_from : NSPoint = NSPoint(); var sel_drag_to : NSPoint = NSPoint(); var sel_move_from : NSPoint = NSPoint(); var started_sel_moving = false; func write() { let dp = sdirPath for ent in entities { var cfg = "" cfg = cfg + String(format: "pos.x\n%f\n", Float(ent.node.position.x)) cfg = cfg + String(format: "pos.y\n%f\n", Float(ent.node.position.y)) cfg = cfg + String(format: "scl\n%f\n", Float(ent.scl)) cfg = cfg + String(format: "fntSize\n%f\n", Float(ent.fntSize)) cfg = cfg + "fntName\n" + ent.fntName + "\n" cfg = cfg + "fntCol\n" + ent.fntColName + "\n" for rel in ent.rel { if rel.from.fn == ent.fn { cfg = cfg + "rel_to\n" + rel.to.fn + "\n" } } let fp = (dp as NSString).stringByAppendingPathComponent("_" + ent.fn + ".lrn") do { try cfg.writeToFile(fp, atomically: false, encoding: NSUTF8StringEncoding) } catch _ { } } if (true) { var cfg = "" cfg = cfg + String(format: "pos.x\n%f\n", Float(root.position.x)) cfg = cfg + String(format: "pos.y\n%f\n", Float(root.position.y)) cfg = cfg + String(format: "scl\n%f\n", Float(root.xScale)) let fp = (dp as NSString).stringByAppendingPathComponent("state_root.lrn") do { try cfg.writeToFile(fp, atomically: false, encoding: NSUTF8StringEncoding) } catch _ { }; } } func createTextTexture(_text: NSString, fntName: String, fntSize: CGFloat = 14.0, fntCol: NSColor = NSColor.blackColor()) -> SKTexture{ let font = NSFont(name: fntName, size: fntSize) let textAttributes: [String: AnyObject] = [ NSForegroundColorAttributeName : fntCol as AnyObject, NSFontAttributeName : font as! AnyObject ] let text = " " + _text.stringByReplacingOccurrencesOfString("\n", withString: " \n ") + " " let sz = text.sizeWithAttributes(textAttributes) let nsi:NSImage = NSImage(size: sz) nsi.lockFocus() NSColor.whiteColor().setFill() //NSBezierPath.fillRect(NSRect(x: 0,y: 0,width: sz.width,height: sz.height)) NSBezierPath.strokeRect(NSRect(x: 0,y: 0,width: sz.width,height: sz.height)) text.drawInRect(NSRect(x: 0,y: 0,width: sz.width,height: sz.height), withAttributes:textAttributes) nsi.unlockFocus() return SKTexture(image:nsi) } func createLrnNote(text: String, prefix : String = "note_") -> String { var fn = String(format: prefix + "%d.txt", auto_note_index) while NSFileManager.defaultManager().fileExistsAtPath((dirPath as NSString).stringByAppendingPathComponent(fn)) { auto_note_index = auto_note_index+1 fn = String(format: prefix + "%d.txt", auto_note_index) } do { try text.writeToFile((dirPath as NSString).stringByAppendingPathComponent(fn), atomically: false, encoding: NSUTF8StringEncoding) } catch _ { }; return fn } func isLrnEntityFile(fn:String) -> Bool { if fn.hasSuffix("png") || fn.hasSuffix("jpg") || fn.hasSuffix("jpeg") { return true } else if fn.hasSuffix("txt") && (fn.rangeOfString("ocr") == nil) { return true } return false } func deleteEntityFile(ent: LrnEntity) { do { try NSFileManager.defaultManager().removeItemAtPath(ent.fp) } catch _ { } } func updateLrnEntityNote(ent: LrnEntity) { if ent.type == "text" { let tex = createTextTexture(ent.text, fntName:ent.fntName, fntSize: ent.fntSize, fntCol: ent.fntCol) ent.node.setScale(ent.scl) (ent.node as! SKSpriteNode).size = NSSize(width: tex.size().width*ent.scl, height: tex.size().height*ent.scl) (ent.node as! SKSpriteNode).texture = tex } } func fixText(txt: String) -> String { if txt.hasSuffix("\n") { return String(txt.characters.dropLast()) } return txt } func updateLrnEntityFromFile(fn: String, ent: LrnEntity) { if ent.type == "image" { let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) let img = NSImage(contentsOfFile: fp) let tex = SKTexture(image: img!) (ent.node as! SKSpriteNode).size = tex.size() (ent.node as! SKSpriteNode).texture = tex } else { let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) let txt = fixText((try! NSString(contentsOfFile: fp, encoding: NSUTF8StringEncoding)) as String) ent.text = txt let tex = createTextTexture(ent.text, fntName: ent.fntName, fntSize: ent.fntSize, fntCol: ent.fntCol) (ent.node as! SKSpriteNode).size = tex.size() (ent.node as! SKSpriteNode).texture = tex } } func addLrnEntityFromFile(fn: String, center: CGPoint, i:Int) -> Bool { let ent = LrnEntity() var pos = CGPoint(x:(center.x + CGFloat(i)*40.0), y:(center.y + CGFloat(i)*40.0)) if (true) { let dp = (dirPath as NSString).stringByAppendingPathComponent("state") let fp = (dp as NSString).stringByAppendingPathComponent("_" + fn + ".lrn") if NSFileManager.defaultManager().fileExistsAtPath(fp) { let cfg = (try! NSString(contentsOfFile: fp, encoding: NSUTF8StringEncoding)) as String let lines = cfg.componentsSeparatedByString("\n") var li = 0 var key = "" for line in lines { if (li % 2 == 0) { key = line } else { if (key == "pos.x") { pos.x = CGFloat((line as NSString).floatValue) } else if (key == "pos.y") { pos.y = CGFloat((line as NSString).floatValue) } else if (key == "scl") { ent.scl = CGFloat((line as NSString).floatValue) } else if (key == "fntSize") { ent.fntSize = CGFloat((line as NSString).floatValue) } else if (key == "fntName") { ent.fntName = line } else if (key == "fntCol") { if let colVal = self.colNames[line] { ent.fntColName = line ent.fntCol = self.colNames[ent.fntColName]! } else { ent.fntColName = line ent.fntCol = self.colNames["black"]! } } else if (key == "rel_to") { let pri = PreRelInfo(); pri.to = line; pri.resolved = false; ent.load_rel_to.append(pri) } } li++ } } } if fn.hasSuffix("png") || fn.hasSuffix("jpg") || fn.hasSuffix("jpeg") { let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) let img = NSImage(contentsOfFile: fp) let tex = SKTexture(image: img!) let sprite = SKSpriteNode(texture: tex) ent.fn = fn; ent.fp = fp; ent.node = sprite; ent.type = "image"; if (fn.hasPrefix("paste_")) { let num = Int(fn.componentsSeparatedByString("_")[1].componentsSeparatedByString(".")[0]) if num >= self.auto_paste_index { self.auto_paste_index = num! + 1} } } else if fn.hasSuffix("txt") && (fn.rangeOfString("ocr") == nil) { let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) let txt = (try! NSString(contentsOfFile: fp, encoding: NSUTF8StringEncoding)) as String ent.text = fixText(txt); let sprite = SKSpriteNode(texture: createTextTexture(ent.text, fntName: ent.fntName, fntSize: ent.fntSize, fntCol: ent.fntCol)) ent.fn = fn; ent.fp = fp; ent.node = sprite; ent.type = "text"; if (fn.hasPrefix("auto_note")) { let num = Int(fn.componentsSeparatedByString("_")[2].componentsSeparatedByString(".")[0]) if num >= self.auto_note_index { self.auto_note_index = num! + 1} } ent.scl = 1.0 // We use font size for this } if (ent.fn != "") { let attrs = (try! NSFileManager.defaultManager().attributesOfItemAtPath(ent.fp)) ent.modif = attrs[NSFileModificationDate] as! NSDate ent.id = id_gen; id_gen++; ent.node.position = pos ent.node.setScale(ent.scl) //ent.node.zRotation = CGFloat(randf2(-0.01, 0.01)) ent.node.name = ent.fn let bbr : CGFloat = 12.0 let bb = SKPhysicsBody(circleOfRadius: bbr); bb.affectedByGravity = false; bb.mass = 0; ent.node.physicsBody = bb ent.sel_node = createCircleNode( CGPoint(x: 0,y: 0), rad: bbr, name: "^_sel_" + ent.node.name!, zPos: 1.5) ent.sel_node.fillColor = SKColor.redColor(); //ent.node.addChild(ent.sel_node) self.entities.append(ent) self.entities_by_fn[ent.fn] = ent self.root.addChild(ent.node) return true } return false } func refresh() { let fileManager = NSFileManager.defaultManager() let contents = try? fileManager.contentsOfDirectoryAtPath(dirPath) if contents != nil { var newi = 0 let files = contents for fn in files! { if (isLrnEntityFile(fn)) { let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) let attrs = (try! fileManager.attributesOfItemAtPath(fp)) let modif = attrs[NSFileModificationDate] as! NSDate let ent = entities_by_fn[fn] if (ent != nil) { if (ent!.modif != modif) { updateLrnEntityFromFile(fn, ent:ent!) } } else { addLrnEntityFromFile(fn, center:last_mouse_evt.locationInNode(self.root), i:newi) newi++ } } } } } func paste() -> Bool { var did_paste = false let pasteboard = NSPasteboard.generalPasteboard() if let nofElements = pasteboard.pasteboardItems?.count { if nofElements > 0 { var strArr: Array<String> = [] for element in pasteboard.pasteboardItems! { if let str = element.stringForType("public.utf8-plain-text") { strArr.append(str) } } if strArr.count != 0 { for str in strArr { createLrnNote(str) did_paste = true } } else { let img = NSImage(pasteboard: NSPasteboard.generalPasteboard()) if (img != nil) { var img_rep = NSImageRep() for rep in img!.representations { if rep is NSBitmapImageRep { img_rep = rep } } if img_rep is NSBitmapImageRep { let data = (img_rep as! NSBitmapImageRep).representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) as NSData? /* let df = NSDateFormatter() df.dateStyle = .ShortStyle df.timeStyle = .ShortStyle let date = NSDate() let date_str = df.stringFromDate(date).stringByReplacingOccurrencesOfString("/", withString: "-").stringByReplacingOccurrencesOfString(":", withString: ".") let fp = dirPath.stringByAppendingPathComponent("paste_" + date_str + ".png") */ let prefix = "paste_" var fn = String(format: prefix + "%d.png", auto_paste_index) while NSFileManager.defaultManager().fileExistsAtPath((dirPath as NSString).stringByAppendingPathComponent(fn)) { auto_paste_index = auto_paste_index+1 fn = String(format: prefix + "%d.png", auto_note_index) } let fp = (dirPath as NSString).stringByAppendingPathComponent(fn) data?.writeToFile(fp, atomically: true) did_paste = true } } } } } return did_paste } func createRel(from:LrnEntity, to:LrnEntity, delOnFound:Bool=false) -> Bool { for erel in from.rel { if (erel.from.fn == from.fn && erel.to.fn == to.fn) || (erel.from.fn == to.fn && erel.to.fn == from.fn) { if delOnFound { erel.node.removeFromParent() from.rel.removeAtIndex( from.rel.indexOf(erel)! ) to.rel.removeAtIndex( to.rel.indexOf(erel)! ) } return false } } let rel = RelInfo(); rel.id = self.rel_id_gen; self.rel_id_gen++; rel.from = from; rel.to = to; from.rel.append(rel); rel.to.rel.append(rel); return true } func resolveRels(ent:LrnEntity) { for pri in ent.load_rel_to { if (pri.resolved == false) { if let toEnt = self.entities_by_fn[pri.to] { createRel(ent, to: toEnt) } pri.resolved = true } } ent.load_rel_to.removeAll(keepCapacity: false) } func resolveAllRels() { for ent in self.entities { resolveRels(ent) } } func updateRelNodePath(node:SKShapeNode, from:LrnEntity, to:LrnEntity) { func chooseRelPoints(pts1:[CGPoint], pts2:[CGPoint]) -> (CGPoint, CGPoint) { func distSq(p1:CGPoint, p2:CGPoint) -> CGFloat { return (p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y) } var min_1 = 0; var min_2 = 0; var min_dist = distSq(pts1[0], p2: pts2[0]) for (i1, pt1) in pts1.enumerate() { for (i2, pt2) in pts2.enumerate() { if distSq(pt1, p2: pt2) < min_dist { min_dist = distSq(pt1, p2: pt2); min_1 = i1; min_2 = i2; } } } return (pts1[min_1], pts2[min_2]) } func getRectRot(ent: LrnEntity) -> [CGPoint] { var sz1 = (ent.node as! SKSpriteNode).size let szmul = ent.scl / (ent.scl + ent.node_scl_add) sz1.width = sz1.width*szmul; sz1.height = sz1.height*szmul; let rect1 = NSMakeRect(-sz1.width/2.0, -sz1.height/2.0, sz1.width, sz1.height) let rot1 = CGAffineTransformMakeRotation(ent.node.zRotation) var pts = [CGPoint](count:8, repeatedValue:CGPoint()) var pp = CGPoint(); pp = CGPoint(x:rect1.minX, y:rect1.minY); pts[0] = CGPointApplyAffineTransform(pp, rot1); pp = CGPoint(x:rect1.minX, y:rect1.maxY); pts[1] = CGPointApplyAffineTransform(pp, rot1); pp = CGPoint(x:rect1.maxX, y:rect1.minY); pts[2] = CGPointApplyAffineTransform(pp, rot1); pp = CGPoint(x:rect1.maxX, y:rect1.maxY); pts[3] = CGPointApplyAffineTransform(pp, rot1); pts[0] = CGPoint(x: pts[0].x + ent.node.position.x, y: pts[0].y + ent.node.position.y ) pts[1] = CGPoint(x: pts[1].x + ent.node.position.x, y: pts[1].y + ent.node.position.y ) pts[2] = CGPoint(x: pts[2].x + ent.node.position.x, y: pts[2].y + ent.node.position.y ) pts[3] = CGPoint(x: pts[3].x + ent.node.position.x, y: pts[3].y + ent.node.position.y ) pts[4] = CGPoint(x: (pts[0].x+pts[1].x)/2.0, y: (pts[0].y+pts[1].y)/2.0) pts[5] = CGPoint(x: (pts[2].x+pts[3].x)/2.0, y: (pts[2].y+pts[3].y)/2.0) pts[6] = CGPoint(x: (pts[0].x+pts[2].x)/2.0, y: (pts[0].y+pts[2].y)/2.0) pts[7] = CGPoint(x: (pts[1].x+pts[3].x)/2.0, y: (pts[1].y+pts[3].y)/2.0) return pts } let pts1 = getRectRot(from) let pts2 = getRectRot(to) var is_outer = (pts2[0].x > pts1[2].x || pts2[2].x < pts1[0].x) && (pts2[0].y > pts1[1].y || pts2[1].y < pts1[0].y) as Bool let rpts1 = (is_outer) ? pts1 : Array(pts1[Range(start:4,end:8)]) let rpts2 = (is_outer) ? pts2 : Array(pts2[Range(start:4,end:8)]) let (rel_pt1, rel_pt2) = chooseRelPoints(rpts1, pts2: rpts2) let scl = 2.0 as CGFloat let pathToDraw:CGMutablePathRef = CGPathCreateMutable() CGPathMoveToPoint(pathToDraw, nil, rel_pt1.x/scl, rel_pt1.y/scl) CGPathAddLineToPoint(pathToDraw, nil, rel_pt2.x/scl, rel_pt2.y/scl) node.path = pathToDraw node.setScale(scl) } func updateRelNodes(ent: LrnEntity) { for rel in ent.rel { if (rel.node.name == "^-") { updateRelNodePath(rel.node, from: rel.from, to: rel.to) } } } func createRelNode(from:LrnEntity, to:LrnEntity) -> SKShapeNode { let node:SKShapeNode = SKShapeNode() updateRelNodePath(node, from: from, to: to) node.strokeColor = SKColor.redColor() node.name = "^-" return node } func createNodesFroRels(ent:LrnEntity) { for rel in ent.rel { if (rel.node.name != "^-") { rel.node = createRelNode(rel.from, to: rel.to) // http://sartak.org/2014/03/skshapenode-you-are-dead-to-me.html self.root.addChild(rel.node) } } } func createAllNodesForRels() { for ent in self.entities { createNodesFroRels(ent) } } func mainLoad() { let fileManager = NSFileManager.defaultManager() sdirPath = (dirPath as NSString).stringByAppendingPathComponent("state") do { try NSFileManager.defaultManager().createDirectoryAtPath(sdirPath, withIntermediateDirectories: false, attributes: nil) } catch _ { } self.rroot.name = "^rroot" self.addChild(rroot) self.root.name = "^root" self.rroot.addChild(root) if (true) { let fp = (sdirPath as NSString).stringByAppendingPathComponent("state_root.lrn") if NSFileManager.defaultManager().fileExistsAtPath(fp) { let cfg = (try! NSString(contentsOfFile: fp, encoding: NSUTF8StringEncoding)) as String let lines = cfg.componentsSeparatedByString("\n") var li = 0 var key = "" for line in lines { if (li % 2 == 0) { key = line } else { if (key == "pos.x") { root.position.x = CGFloat((line as NSString).floatValue) } else if (key == "pos.y") { root.position.y = CGFloat((line as NSString).floatValue) } else if (key == "scl") { root.setScale( CGFloat((line as NSString).floatValue) ) } } li++ } } } let contents = try? fileManager.contentsOfDirectoryAtPath(dirPath) let center = CGPoint(x:self.size.width/2, y:self.size.height/2) var i : Int = 0 if contents != nil { let files = contents for fn in files! { if addLrnEntityFromFile(fn, center:center, i:i) { i++ } } } resolveAllRels() createAllNodesForRels() self.backgroundColor = NSColor.whiteColor() } override func didMoveToView(view: SKView) { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = true openPanel.canCreateDirectories = true openPanel.canChooseFiles = false openPanel.beginWithCompletionHandler { (result) -> Void in if result == NSFileHandlingPanelOKButton { if let url = openPanel.URL { self.dirPath = url.path! } } if NSFileManager.defaultManager().fileExistsAtPath(self.dirPath) == false { NSApplication.sharedApplication().terminate(nil) return } else { self.mainLoad() } } } override func mouseDragged(evt: NSEvent) { self.last_evt_time = self.time; checkWake(); if self.is_sel_moving == false { if (self.drag_sel.name == nil) { self.drag_sel = self.nodeAtPoint(evt.locationInNode(self)) if (self.drag_sel.name == "^rroot") { self.drag_sel = SKNode() } } let node = self.drag_sel if (evt.modifierFlags.intersect(.ShiftKeyMask) != []) { self.root.setScale(self.root.xScale * (1.0 + evt.deltaX/20.0) ) } else { if (node.name != nil && !node.name!.hasPrefix("^")) { node.position = evt.locationInNode(node.parent!) updateRelNodes(self.entities_by_fn[node.name!]!) } else { self.root.position = CGPoint(x: self.root.position.x + evt.deltaX, y: self.root.position.y - evt.deltaY) } } } else { if self.started_sel_moving == false { self.started_sel_moving = true self.sel_move_from = evt.locationInNode(self.root) } let mp = evt.locationInNode(self.root) let dd = CGPoint(x: mp.x - self.sel_move_from.x, y: mp.y - self.sel_move_from.y) for ent in sel_entities { ent.node.position = CGPoint(x: ent.node.position.x + dd.x, y: ent.node.position.y + dd.y) } self.sel_move_from = mp } } override func keyUp(evt: NSEvent) { if evt.characters == "s" { if self.is_sel_dragging == true { self.is_sel_dragging = false self.is_sel_moving = true self.drag_rect.strokeColor = SKColor.redColor(); self.started_sel_moving == false killDragRectNode() } } } override func keyDown(evt: NSEvent) { let scl_fac = 1.02 as CGFloat let fnt_scl_fac = 1.02 as CGFloat func handleRptUp(evt: NSEvent) { if let ent = self.sel_ent { if (ent.type == "text") { ent.fntSize = ent.fntSize * fnt_scl_fac self.sel.setScale( ent.scl) updateLrnEntityNote(ent) updateRelNodes(ent) } else { ent.scl = ent.scl * scl_fac self.sel.setScale( ent.scl) updateRelNodes(ent) } } } func handleRptDown(evt: NSEvent) { if let ent = self.sel_ent { if (ent.type == "text") { ent.fntSize = ent.fntSize / fnt_scl_fac self.sel.setScale( ent.scl) updateLrnEntityNote(ent) updateRelNodes(ent) } else { ent.scl = ent.scl / scl_fac self.sel.setScale( ent.scl) updateRelNodes(ent) } } } func handleLeft(evt: NSEvent) { if let ent = self.sel_ent { if (ent.type == "text") { var next = false var ki = "black" for (k, v) in self.colNames { if next { ki = k; next = false; break; } else { if ent.fntCol == v { next = true } } } if next { for (k, v) in self.colNames { ki = k; break; } } if let ccol = self.colNames[ent.fntColName] { ent.fntColName = ki } ent.fntCol = self.colNames[ki]! updateLrnEntityNote(ent) } } } func handleRight(evt: NSEvent) { if let ent = self.sel_ent { if (ent.type == "text") { var ni = 0 for (i, ff) in self.fntNames.enumerate() { if ent.fntName == ff { ni = (i + 1) % self.fntNames.count } } ent.fntName = self.fntNames[ni] updateLrnEntityNote(ent) } } } self.last_evt_time = self.time; checkWake(); if state == "note" { } else { if (evt.ARepeat) { switch(evt.keyCode) { case 126: handleRptUp(evt); case 125: handleRptDown(evt); case 124: evt; // right case 123: evt; // left default: evt; } if evt.characters == "d" { if isEntityNode(self.fcs_cpy_orig) { killFcsNode() deleteEntityFile(self.entities_by_fn[self.fcs_cpy_orig.name!]!) self.fcs_cpy_orig.removeFromParent() } } } else { if evt.characters == "n" { let fn = createLrnNote("note: ") addLrnEntityFromFile(fn, center:last_mouse_evt.locationInNode(self.root), i:0) } else if evt.characters == "p" { if (paste()) { refresh() } } else if evt.characters == "w" { write() } else if evt.characters == "r" { refresh() } else if evt.characters == "x" { self.view!.paused = true } else if evt.characters == "s" { if self.is_sel_dragging == false { self.sel_drag_from = last_mouse_evt.locationInNode(self); self.sel_drag_to = last_mouse_evt.locationInNode(self); self.is_sel_dragging = true; setDragRectNode(); } } else if evt.characters == "m" { let sceneRect = CGRectMake( -100, -100, 10000, 10000) self.physicsWorld.enumerateBodiesInRect(sceneRect) { (body: SKPhysicsBody!, stop: UnsafeMutablePointer<ObjCBool>) in print (body.node!.name) } } else { switch(evt.keyCode) { case 124: handleRight(evt) case 123: handleLeft(evt) default: evt; } } } } } override func mouseEntered(evt: NSEvent) { if self.view!.paused == true { return; } self.last_evt_time = self.time; checkWake(); self.last_mouse_evt = evt } override func mouseMoved(evt: NSEvent) { if self.view!.paused == true { return; } if (self.started_sel_moving == true) { self.is_sel_moving = false self.started_sel_moving = false for ent in sel_entities { updateRelNodes(ent) } resetSelEntities(Array<SKNode>()); } self.last_evt_time = self.time; checkWake(); self.last_mouse_evt = evt self.deferred.append("killFcsNode"); //killFcsNode() if self.is_sel_dragging == true { self.sel_drag_to = last_mouse_evt.locationInNode(self) setDragRectNode() updateDragRectNode() if (true) { let sceneRect = CGRectMake(self.sel_drag_from.x, self.sel_drag_from.y, self.sel_drag_to.x-self.sel_drag_from.x, self.sel_drag_to.y-self.sel_drag_from.y) let sceneRect2 = CGRectMake(sceneRect.minX, sceneRect.minY, sceneRect.width, sceneRect.height) var sel_nodes = Array<SKNode>() self.physicsWorld.enumerateBodiesInRect(sceneRect2) { (body: SKPhysicsBody!, stop: UnsafeMutablePointer<ObjCBool>) in sel_nodes.append(body.node!) //print (body.node!.name) } resetSelEntities(sel_nodes) } } } func isEntityNode(node: SKNode) -> Bool { return node.name != nil && node.name != "" && !node.name!.hasPrefix("^") } func setSelNode(node: SKNode) { let scl_add = CGFloat(0.0 * 0.125*1.5) if self.sel != node { if let ent = self.sel_ent { ent.node_scl_add = 0.0 self.sel.setScale( ent.scl + ent.node_scl_add) self.sel.zPosition = 1 } if isEntityNode(node) { self.sel = node self.sel_ent = self.entities_by_fn[self.sel.name!] if let ent = self.sel_ent { self.sel_ent!.node_scl_add = scl_add self.sel.setScale( ent.scl + ent.node_scl_add) self.sel.zPosition = 2 } } else { self.sel = SKNode() self.sel_ent = nil } } } func resetSelEntities(sel_nodes: Array<SKNode>) { for ent in self.sel_entities { ent.sel_node.removeFromParent() } sel_entities.removeAll(); for node in sel_nodes { if isEntityNode(node) { let sel_ent = self.entities_by_fn[node.name!]! sel_ent.node.addChild(sel_ent.sel_node) sel_entities.append(sel_ent) } } } func killFcsNode() { self.fcs_cpy.removeFromParent() self.fcs_cpy = SKNode() } func setFcsNode(node: SKNode) { killFcsNode() self.fcs_cpy_orig = node self.fcs_cpy = node.copy() as! SKNode self.fcs_cpy.name = "^focus" self.fcs_cpy.position = CGPoint(x:self.size.width/2, y:self.size.height/2) self.fcs_cpy.setScale(1.0) self.fcs_cpy.zRotation = 0.0 self.fcs_cpy.zPosition = 3.0 self.addChild(self.fcs_cpy) } func killDragRectNode() { self.drag_rect.removeFromParent() self.drag_rect = SKShapeNode() } func createCircleNode(center: CGPoint, rad: CGFloat, name: String, zPos: CGFloat) -> SKShapeNode { let circ_node = SKShapeNode(circleOfRadius: rad) circ_node.strokeColor = SKColor.blackColor() circ_node.name = name circ_node.position = center circ_node.setScale(1.0) circ_node.zRotation = 0.0 circ_node.zPosition = zPos return circ_node } func createRectNode(from: CGPoint, to: CGPoint, name: String, zPos: CGFloat) -> SKShapeNode { let rect_node = SKShapeNode(rectOfSize: CGSize(width: 1.0 * (to.x - from.x), height: 1.0*(to.y - from.y))) rect_node.strokeColor = SKColor.blackColor() rect_node.name = name rect_node.position = CGPoint( x: 0.5*(from.x+to.x), y: 0.5*(from.y+to.y)) rect_node.setScale(1.0) rect_node.zRotation = 0.0 rect_node.zPosition = zPos return rect_node } func setDragRectNode() { killDragRectNode() self.drag_rect = createRectNode(self.sel_drag_from, to: self.sel_drag_to, name: "^drag_rect", zPos: 2.0) self.drag_rect.lineWidth = 2.0 self.addChild(self.drag_rect) } func updateDragRectNode() { if (self.is_sel_dragging) { setDragRectNode() } else { if (self.drag_rect.name == "^drag_rect") { killDragRectNode() } } } override func mouseDown(evt: NSEvent) { self.last_evt_time = self.time; checkWake(); //self.mouse_is_down = true; if (evt.clickCount == 2) { killFcsNode() let dbl_sel = self.nodeAtPoint(evt.locationInNode(self)) if isEntityNode(dbl_sel) { setFcsNode(dbl_sel) } } } override func mouseUp(evt: NSEvent) { self.last_evt_time = self.time; checkWake(); //self.mouse_is_down = false; self.drag_sel = SKNode() let node = self.nodeAtPoint(evt.locationInNode(self)) if (evt.modifierFlags.intersect(.ShiftKeyMask) != []) && isEntityNode(node) && isEntityNode(self.sel) { let from = self.sel; let to = node; var found = false if let fent = self.entities_by_fn[from.name!] { if let tent = self.entities_by_fn[to.name!] { if (createRel(fent, to: tent, delOnFound: true)) { createNodesFroRels(fent) } } } } if (isEntityNode(node)) { setSelNode(node) } } //override func touchesBeganWithEvent(evt: NSEvent) { // println("touches") //} func checkWake() { //if (self.last_evt_time.distanceTo(self.time) > 0.5) { // self.view!.paused = true //} //else { self.view!.paused = false //} } override func update(currentTime: CFTimeInterval) { if (self.view!.paused == true) {return} self.time = currentTime; //checkWake(); for (i,cmd) in self.deferred.enumerate() { if (cmd == "killFcsNode") { self.killFcsNode() } } self.deferred = [] //if (self.sel.name != nil) && (isEntityNode(self.sel)) { // println(self.convertPoint(CGPoint(x: 0,y: 0), fromNode: self.sel)) //} //if (self.last_evt_time.distanceTo(self.time) > 0.5) { // self.view!.paused = true //} } }
unlicense
dd95034e3363f1bf7d725b970524d5e2
40.151351
184
0.500959
4.000946
false
false
false
false
alisidd/iOS-WeJ
Pods/M13Checkbox/Sources/Managers/M13CheckboxDotController.swift
3
10233
// // M13CheckboxDotController.swift // M13Checkbox // // Created by McQuilkin, Brandon on 4/1/16. // Copyright © 2016 Brandon McQuilkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit internal class M13CheckboxDotController: M13CheckboxController { //---------------------------- // MARK: - Properties //---------------------------- override var tintColor: UIColor { didSet { selectedBoxLayer.strokeColor = tintColor.cgColor if style == .stroke { markLayer.strokeColor = tintColor.cgColor if markType == .radio { markLayer.fillColor = tintColor.cgColor } } else { selectedBoxLayer.fillColor = tintColor.cgColor } } } override var secondaryTintColor: UIColor? { didSet { unselectedBoxLayer.strokeColor = secondaryTintColor?.cgColor } } override var secondaryCheckmarkTintColor: UIColor? { didSet { if style == .fill { markLayer.strokeColor = secondaryCheckmarkTintColor?.cgColor } } } override var hideBox: Bool { didSet { selectedBoxLayer.isHidden = hideBox unselectedBoxLayer.isHidden = hideBox } } fileprivate var style: M13Checkbox.AnimationStyle = .stroke init(style: M13Checkbox.AnimationStyle) { self.style = style super.init() sharedSetup() } override init() { super.init() sharedSetup() } fileprivate func sharedSetup() { // Disable som implicit animations. let newActions = [ "opacity": NSNull(), "strokeEnd": NSNull(), "transform": NSNull(), "fillColor": NSNull(), "path": NSNull(), "lineWidth": NSNull() ] // Setup the unselected box layer unselectedBoxLayer.lineCap = kCALineCapRound unselectedBoxLayer.rasterizationScale = UIScreen.main.scale unselectedBoxLayer.shouldRasterize = true unselectedBoxLayer.actions = newActions unselectedBoxLayer.transform = CATransform3DIdentity unselectedBoxLayer.fillColor = nil // Setup the selected box layer. selectedBoxLayer.lineCap = kCALineCapRound selectedBoxLayer.rasterizationScale = UIScreen.main.scale selectedBoxLayer.shouldRasterize = true selectedBoxLayer.actions = newActions selectedBoxLayer.fillColor = nil selectedBoxLayer.transform = CATransform3DIdentity // Setup the checkmark layer. markLayer.lineCap = kCALineCapRound markLayer.lineJoin = kCALineJoinRound markLayer.rasterizationScale = UIScreen.main.scale markLayer.shouldRasterize = true markLayer.actions = newActions markLayer.transform = CATransform3DIdentity markLayer.fillColor = nil } //---------------------------- // MARK: - Layers //---------------------------- let markLayer = CAShapeLayer() let selectedBoxLayer = CAShapeLayer() let unselectedBoxLayer = CAShapeLayer() override var layersToDisplay: [CALayer] { return [unselectedBoxLayer, selectedBoxLayer, markLayer] } //---------------------------- // MARK: - Animations //---------------------------- override func animate(_ fromState: M13Checkbox.CheckState?, toState: M13Checkbox.CheckState?, completion: (() -> Void)?) { super.animate(fromState, toState: toState) if pathGenerator.pathForMark(toState) == nil && pathGenerator.pathForMark(fromState) != nil { let scaleAnimation = animationGenerator.fillAnimation(1, amplitude: 0.18, reverse: true) let opacityAnimation = animationGenerator.opacityAnimation(true) CATransaction.begin() CATransaction.setCompletionBlock({ () -> Void in self.resetLayersForState(toState) completion?() }) if style == .stroke { unselectedBoxLayer.opacity = 0.0 let quickOpacityAnimation = animationGenerator.quickOpacityAnimation(false) quickOpacityAnimation.beginTime = CACurrentMediaTime() + scaleAnimation.duration - quickOpacityAnimation.duration unselectedBoxLayer.add(quickOpacityAnimation, forKey: "opacity") } selectedBoxLayer.add(scaleAnimation, forKey: "transform") markLayer.add(opacityAnimation, forKey: "opacity") CATransaction.commit() } else if pathGenerator.pathForMark(toState) != nil && pathGenerator.pathForMark(fromState) == nil { markLayer.path = pathGenerator.pathForMark(toState)?.cgPath let scaleAnimation = animationGenerator.fillAnimation(1, amplitude: 0.18, reverse: false) let opacityAnimation = animationGenerator.opacityAnimation(false) CATransaction.begin() CATransaction.setCompletionBlock({ () -> Void in self.resetLayersForState(toState) completion?() }) if style == .stroke { let quickOpacityAnimation = animationGenerator.quickOpacityAnimation(true) quickOpacityAnimation.beginTime = CACurrentMediaTime() unselectedBoxLayer.add(quickOpacityAnimation, forKey: "opacity") } selectedBoxLayer.add(scaleAnimation, forKey: "transform") markLayer.add(opacityAnimation, forKey: "opacity") CATransaction.commit() } else { let fromPath = pathGenerator.pathForMark(fromState) let toPath = pathGenerator.pathForMark(toState) let morphAnimation = animationGenerator.morphAnimation(fromPath, toPath: toPath) CATransaction.begin() CATransaction.setCompletionBlock({ [unowned self] () -> Void in self.resetLayersForState(self.state) completion?() }) markLayer.add(morphAnimation, forKey: "path") CATransaction.commit() } } //---------------------------- // MARK: - Layout //---------------------------- override func layoutLayers() { // Frames unselectedBoxLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) selectedBoxLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) markLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) // Paths unselectedBoxLayer.path = pathGenerator.pathForDot()?.cgPath selectedBoxLayer.path = pathGenerator.pathForBox()?.cgPath markLayer.path = pathGenerator.pathForMark(state)?.cgPath } //---------------------------- // MARK: - Display //---------------------------- override func resetLayersForState(_ state: M13Checkbox.CheckState?) { super.resetLayersForState(state) // Remove all remnant animations. They will interfere with each other if they are not removed before a new round of animations start. unselectedBoxLayer.removeAllAnimations() selectedBoxLayer.removeAllAnimations() markLayer.removeAllAnimations() // Set the properties for the final states of each necessary property of each layer. unselectedBoxLayer.strokeColor = secondaryTintColor?.cgColor unselectedBoxLayer.lineWidth = pathGenerator.boxLineWidth selectedBoxLayer.strokeColor = tintColor.cgColor selectedBoxLayer.lineWidth = pathGenerator.boxLineWidth if style == .stroke { selectedBoxLayer.fillColor = nil markLayer.strokeColor = tintColor.cgColor if markType != .radio { markLayer.fillColor = nil } else { markLayer.fillColor = tintColor.cgColor } } else { selectedBoxLayer.fillColor = tintColor.cgColor markLayer.strokeColor = secondaryCheckmarkTintColor?.cgColor } markLayer.lineWidth = pathGenerator.checkmarkLineWidth if pathGenerator.pathForMark(state) != nil { unselectedBoxLayer.opacity = 0.0 selectedBoxLayer.transform = CATransform3DIdentity markLayer.opacity = 1.0 } else { unselectedBoxLayer.opacity = 1.0 selectedBoxLayer.transform = CATransform3DMakeScale(0.0, 0.0, 0.0) markLayer.opacity = 0.0 } // Paths unselectedBoxLayer.path = pathGenerator.pathForDot()?.cgPath selectedBoxLayer.path = pathGenerator.pathForBox()?.cgPath markLayer.path = pathGenerator.pathForMark(state)?.cgPath } }
gpl-3.0
2831b53008a086b646412e4f12ff9298
39.442688
464
0.609558
5.44545
false
false
false
false
kubusma/JMWeatherApp
JMWeatherApp/Views/SimpleWeatherViewModel.swift
1
1590
// // SimpleWeatherViewModel.swift // JMWeatherApp // // Created by Jakub Matuła on 01/10/2017. // Copyright © 2017 Jakub Matuła. All rights reserved. // import Foundation struct SimpleWeatherViewModel { private let weather: Weather private let tempratureColorProvider: TemperatureColorProvider private let dateFormatter: DateFormatter init(weather: Weather, tempratureColorProvider: TemperatureColorProvider, dateFormatter: DateFormatter) { self.weather = weather self.tempratureColorProvider = tempratureColorProvider self.dateFormatter = dateFormatter } var coloredTemperature: NSAttributedString { get { let fontColor = tempratureColorProvider.fontColor(forTemperature: weather.temprature) let range = (temperature as NSString).range(of: temperatureValue) let text = NSMutableAttributedString.init(string: temperature) text.addAttribute(.foregroundColor, value: fontColor, range: range) return text } } var temperature: String { return "temp: " + temperatureValue } private var temperatureValue: String { return String(describing: weather.temprature) + " °C" } var weatherDescirption: String { return weather.weatherText } var date: String { let date = Date(timeIntervalSince1970: TimeInterval(weather.dateTime)) return dateFormatter.string(from: date) } var city: String { return weather.location.name } }
mit
0b51f8e2ffac560570c796409d858150
28.37037
109
0.667718
5.050955
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Crypto/Verification/Transactions/QRCode/MXQRCodeTransactionV2.swift
1
5287
// // Copyright 2022 The Matrix.org Foundation C.I.C // // 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 #if DEBUG import MatrixSDKCrypto /// QR transaction originating from `MatrixSDKCrypto` class MXQRCodeTransactionV2: NSObject, MXQRCodeTransaction { var state: MXQRCodeTransactionState { if qrCode.isDone { return .verified } else if qrCode.isCancelled { return .cancelled } else if qrCode.otherSideScanned || qrCode.hasBeenConfirmed { return .qrScannedByOther } else if qrCode.weStarted { return .waitingOtherConfirm } return .unknown } var qrCodeData: MXQRCodeData? { do { let data = try handler.generateQrCode(userId: otherUserId, flowId: transactionId) log.debug("Generated new QR code") return MXQRCodeDataCoder().decode(data) } catch { log.error("Cannot generate QR code", context: error) return nil } } var transactionId: String { return qrCode.flowId } let transport: MXKeyVerificationTransport var isIncoming: Bool { return !qrCode.weStarted } var otherUserId: String { return qrCode.otherUserId } var otherDeviceId: String { return qrCode.otherDeviceId } var reasonCancelCode: MXTransactionCancelCode? { guard let info = qrCode.cancelInfo else { return nil } return .init( value: info.cancelCode, humanReadable: info.reason ) } var error: Error? { return nil } var dmRoomId: String? { return qrCode.roomId } var dmEventId: String? { return qrCode.flowId } private var qrCode: QrCode private let handler: MXCryptoVerificationHandler private let log = MXNamedLog(name: "MXQRCodeTransactionV2") init(qrCode: QrCode, transport: MXKeyVerificationTransport, handler: MXCryptoVerificationHandler) { self.qrCode = qrCode self.transport = transport self.handler = handler } func userHasScannedOtherQrCodeData(_ otherQRCodeData: MXQRCodeData) { log.debug("->") let data = MXQRCodeDataCoder().encode(otherQRCodeData) Task { do { let qrCode = try await handler.scanQrCode(userId: otherUserId, flowId: transactionId, data: data) await MainActor.run { log.debug("Scanned QR code") self.qrCode = qrCode } } catch { log.error("Failed scanning QR code", context: error) } } } func otherUserScannedMyQrCode(_ otherUserScanned: Bool) { guard otherUserScanned else { log.debug("Cancelling due to mismatched keys") cancel(with: .mismatchedKeys()) return } log.debug("Confirming verification") Task { do { try await handler.confirmVerification(userId: otherUserId, flowId: transactionId) log.debug("Verification confirmed") } catch { log.error("Fail", context: error) } } } func cancel(with code: MXTransactionCancelCode) { cancel(with: code, success: {}, failure: { _ in }) } func cancel(with code: MXTransactionCancelCode, success: @escaping () -> Void, failure: @escaping (Error) -> Void) { log.debug("Cancelling transaction") Task { do { try await handler.cancelVerification(userId: otherUserId, flowId: transactionId, cancelCode: code.value) await MainActor.run { log.debug("Transaction cancelled") success() } } catch { await MainActor.run { log.error("Failed cancelling transaction", context: error) failure(error) } } } } } extension MXQRCodeTransactionV2: MXKeyVerificationTransactionV2 { func processUpdates() -> MXKeyVerificationUpdateResult { guard let verification = handler.verification(userId: otherUserId, flowId: transactionId), case .qrCodeV1(let qrCode) = verification else { log.debug("Transaction was removed") return .removed } guard self.qrCode != qrCode else { return .noUpdates } log.debug("Transaction was updated - \(qrCode)") self.qrCode = qrCode return .updated } } #endif
apache-2.0
199d9a6e0de4db9d84fb765654bedcdf
28.870056
120
0.586344
5.040038
false
false
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFramework/database/coredata/stack/HMCDStoreURL.swift
1
5710
// // HMCDStoreURL.swift // HMRequestFramework // // Created by Hai Pham on 7/24/17. // Copyright © 2017 Holmusk. All rights reserved. // import CoreData import SwiftUtilities /// Use this class to represent components to build a persistent store URL. public struct HMCDStoreURL { fileprivate var fileManager: FileManager? fileprivate var searchPath: FileManager.SearchPathDirectory? fileprivate var domainMask: FileManager.SearchPathDomainMask? fileprivate var fileName: String? fileprivate var fileExtension: String? /// Get the associated store URL. /// /// - Returns: A URL instance. /// - Throws: Exception if the URL cannot be created. public func storeURL() throws -> URL { guard let fileManager = self.fileManager, let fileName = self.fileName, let fileExtension = self.fileExtension, let searchPath = self.searchPath, let domainMask = self.domainMask, let directoryURL = fileManager.urls(for: searchPath , in: domainMask).first else { throw Exception("One or more data fields are nil") } let storeName = "\(fileName).\(fileExtension)" return directoryURL.appendingPathComponent(storeName) } } extension HMCDStoreURL: HMBuildableType { public static func builder() -> Builder { return Builder() } public final class Builder { fileprivate var storeURL: Buildable fileprivate init() { storeURL = Buildable() } /// Set the fileManager instance. /// /// - Parameter fileManager: A FileManager instance. /// - Returns: The current Builder instance. @discardableResult public func with(fileManager: FileManager?) -> Self { storeURL.fileManager = fileManager return self } /// Set the default fileManager instance. /// /// - Returns: The current Builder instance. @discardableResult public func withDefaultFileManager() -> Self { return with(fileManager: .default) } /// Set the searchPath instance. /// /// - Parameter searchPath: A SearchPathDirectory instance. /// - Returns: The current Builder instance. @discardableResult public func with(searchPath: FileManager.SearchPathDirectory?) -> Self { storeURL.searchPath = searchPath return self } /// Set the document directory. /// /// - Returns: The current Builder instance. @discardableResult public func withDocumentDirectory() -> Self { return with(searchPath: .documentDirectory) } /// Set the domainMask instance. /// /// - Parameter domainMask: A SearchPathDomainMask instance. /// - Returns: The current Builder instance. @discardableResult public func with(domainMask: FileManager.SearchPathDomainMask?) -> Self { storeURL.domainMask = domainMask return self } /// Set the userDomainMask. /// /// - Returns: The current Builder instance. @discardableResult public func withUserDomainMask() -> Self { return with(domainMask: .userDomainMask) } /// Set the file name. /// /// - Parameter fileName: A String value. /// - Returns: The current Builder instance. @discardableResult public func with(fileName: String?) -> Self { storeURL.fileName = fileName return self } /// Set the file extension. /// /// - Parameter fileExtension: A String value. /// - Returns: The current Builder instance. @discardableResult public func with(fileExtension: String?) -> Self { storeURL.fileExtension = fileExtension return self } /// Set the file extension using a StoreType /// /// - Parameter storeType: A StoreType instance. /// - Returns: The current Builder instance. @discardableResult public func with(storeType: HMCDStoreSettings.StoreType) -> Self { if let fileExtension = storeType.fileExtension() { return with(fileExtension: fileExtension) } else { return self } } } } extension HMCDStoreURL.Builder: HMBuilderType { public typealias Buildable = HMCDStoreURL /// Override this method to provide default implementation. /// /// - Parameter buildable: A Buildable instance. /// - Returns: The current Builder instance. public func with(buildable: Buildable?) -> Self { if let buildable = buildable { return self .with(fileManager: buildable.fileManager) .with(fileName: buildable.fileName) .with(searchPath: buildable.searchPath) .with(domainMask: buildable.domainMask) .with(fileExtension: buildable.fileExtension) } else { return self } } public func build() -> Buildable { return storeURL } } public extension HMCDStoreSettings.StoreType { /// Get the associated file extension. /// /// - Returns: A String value. public func fileExtension() -> String? { switch self { case .SQLite: return "sqlite" default: return nil } } }
apache-2.0
6b883d906f89285fb25724c7478343e0
30.541436
87
0.582239
5.66369
false
false
false
false
twostraws/HackingWithSwift
Classic/project29/Project29/BuildingNode.swift
1
2546
// // BuildingNode.swift // Project29 // // Created by TwoStraws on 19/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import SpriteKit import UIKit enum CollisionTypes: UInt32 { case banana = 1 case building = 2 case player = 4 } class BuildingNode: SKSpriteNode { var currentImage: UIImage! func setup() { name = "building" currentImage = drawBuilding(size: size) texture = SKTexture(image: currentImage) configurePhysics() } func configurePhysics() { physicsBody = SKPhysicsBody(texture: texture!, size: size) physicsBody!.isDynamic = false physicsBody!.categoryBitMask = CollisionTypes.building.rawValue physicsBody!.contactTestBitMask = CollisionTypes.banana.rawValue } func drawBuilding(size: CGSize) -> UIImage { // 1 let renderer = UIGraphicsImageRenderer(size: size) let img = renderer.image { ctx in // 2 let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height) var color: UIColor switch Int.random(in: 0...2) { case 0: color = UIColor(hue: 0.502, saturation: 0.98, brightness: 0.67, alpha: 1) case 1: color = UIColor(hue: 0.999, saturation: 0.99, brightness: 0.67, alpha: 1) default: color = UIColor(hue: 0, saturation: 0, brightness: 0.67, alpha: 1) } ctx.cgContext.setFillColor(color.cgColor) ctx.cgContext.addRect(rectangle) ctx.cgContext.drawPath(using: .fill) // 3 let lightOnColor = UIColor(hue: 0.190, saturation: 0.67, brightness: 0.99, alpha: 1) let lightOffColor = UIColor(hue: 0, saturation: 0, brightness: 0.34, alpha: 1) for row in stride(from: 10, to: Int(size.height - 10), by: 40) { for col in stride(from: 10, to: Int(size.width - 10), by: 40) { if Bool.random() { ctx.cgContext.setFillColor(lightOnColor.cgColor) } else { ctx.cgContext.setFillColor(lightOffColor.cgColor) } ctx.cgContext.fill(CGRect(x: col, y: row, width: 15, height: 20)) } } // 4 } return img } func hitAt(point: CGPoint) { let convertedPoint = CGPoint(x: point.x + size.width / 2.0, y: abs(point.y - (size.height / 2.0))) let renderer = UIGraphicsImageRenderer(size: size) let img = renderer.image { ctx in currentImage.draw(at: CGPoint(x: 0, y: 0)) ctx.cgContext.addEllipse(in: CGRect(x: convertedPoint.x - 32, y: convertedPoint.y - 32, width: 64, height: 64)) ctx.cgContext.setBlendMode(.clear) ctx.cgContext.drawPath(using: .fill) } texture = SKTexture(image: img) currentImage = img configurePhysics() } }
unlicense
a9c8fa7c262f29e9a1daa1adc245b0ea
25.237113
114
0.673084
3.225602
false
false
false
false
HasanEdain/NPCColorPicker
ColorPickerExample/ViewController.swift
1
4628
// // ViewController.swift // ColorPickerExample // // Created by Hasan D Edain and Andrew Bush on 12/6/15. // Copyright © 2015-2017 NPC Unlimited. All rights reserved. // import UIKit import NPCColorPicker // Step 1) Adopt the NPCColorPickerViewDelegate class ViewController: UIViewController, NPCColorPickerViewDelegate { @IBOutlet weak var colorView: UIView! @IBOutlet weak var embedView: UIView! @IBOutlet weak var horizontalSpacingSegment: UISegmentedControl! @IBOutlet weak var verticalSpacingSegment: UISegmentedControl! // Step 2) Initilze NPCColorPicker var colorPicker = NPCColorPicker() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. colorView.backgroundColor = NPCColorUtility.colorWithHex("#00ff00ff") colorView.layer.borderColor = UIColor.black.cgColor colorView.layer.borderWidth = 4.0 colorView.layer.cornerRadius = 8 colorView.layer.masksToBounds = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Step 3) place colorPicker in Embed View (see Main Storyboard for example) _ = self.colorPicker.embedColorPickerInView(self.embedView, forDelegate: self) updatePaleteSpacing() } // Step 4) implement delegate // MARK: - NPCColorPickerViewDelegate func colorChosen(_ color: UIColor) { self.colorView.backgroundColor = color } // MARK: - Actions @IBAction func pickerPressed(_ sender: AnyObject) { colorPicker.toggleVisibility() } @IBAction func shapeSelected(_ sender: AnyObject) { let shapeSegment = sender as! UISegmentedControl var shape = NPCColorPickerMask.square switch shapeSegment.selectedSegmentIndex { case 0: shape = .square break case 1: shape = .roundedRect break case 2: shape = .circle break default: shape = .square break } // You can change the shape of the touch targets for the colors self.colorPicker.changeMaskStyle(shape) } @IBAction func sizeSelected(_ sender: AnyObject) { let sizeSegment = sender as! UISegmentedControl var size: CGFloat switch sizeSegment.selectedSegmentIndex { case 0: size = 32 break case 1: size = 48 break case 2: size = 64 break default: size = 48 break } // You can set the size of the touch targets for the colors self.colorPicker.changeDiameter(size) } @IBAction func horizontalSpaceSelected(_ sender: AnyObject) { updatePaleteSpacing() } @IBAction func verticalSpaceSelected(_ sender: AnyObject) { updatePaleteSpacing() } func updatePaleteSpacing() { let horizontalSpace: CGFloat let verticalSapace:CGFloat switch horizontalSpacingSegment.selectedSegmentIndex { case 0: horizontalSpace = 0 break case 1: horizontalSpace = 8 break default: horizontalSpace = 8 break } switch verticalSpacingSegment.selectedSegmentIndex { case 0: verticalSapace = 0 break case 1: verticalSapace = 8 break default: verticalSapace = 8 break } // You can change the insets between cells self.colorPicker.changeSpaceBetweenColors(verticalSapace, columns: horizontalSpace) } @IBAction func colorsSelected(_ sender: AnyObject) { let colorSegment = sender as! UISegmentedControl switch colorSegment.selectedSegmentIndex { case 0: self.colorPicker.changeColorSet(["ffffff", "ff0000", "00ff00", "0000ff", "000000"]) break case 1: self.colorPicker.changeColorSet(["fe7923", "fd0d1b", "bf1698", "941abe", "6819bd", "1024fc", "1ec0a8", "1dbb20", "c7f131", "e8ea34", "fad931", "feb92b"]) break case 2: self.colorPicker.changeColorToGradient("ff0000", endColor: "0000ff", steps: 32) break case 3: self.colorPicker.changeColorToGradientArray(["ffffff","000000","ff0000","00ff00","0000ff"], steps: 16) break default: break } } }
mit
e27e15c42b112dc8ffc12147de677573
27.386503
165
0.60644
4.880802
false
false
false
false
brorbw/Helium
Helium/Helium/AppDelegate.swift
1
2619
// // AppDelegate.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { @IBOutlet weak var magicURLMenu: NSMenuItem! @IBOutlet weak var percentageMenu: NSMenuItem! @IBOutlet weak var fullScreenFloatMenu: NSMenuItem! func applicationWillFinishLaunching(_ notification: Notification) { NSAppleEventManager.shared().setEventHandler( self, andSelector: #selector(AppDelegate.handleURLEvent(_:withReply:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL) ) } func applicationDidFinishLaunching(_ aNotification: Notification) { magicURLMenu.state = UserDefaults.standard.bool(forKey: UserSetting.disabledMagicURLs.userDefaultsKey) ? NSOffState : NSOnState fullScreenFloatMenu.state = UserDefaults.standard.bool(forKey: UserSetting.disabledFullScreenFloat.userDefaultsKey) ? NSOffState : NSOnState if let alpha = UserDefaults.standard.object(forKey: UserSetting.opacityPercentage.userDefaultsKey) { let offset = (alpha as! Int)/10 - 1 for (index, button) in percentageMenu.submenu!.items.enumerated() { (button ).state = (offset == index) ? NSOnState : NSOffState } } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @IBAction func magicURLRedirectToggled(_ sender: NSMenuItem) { sender.state = (sender.state == NSOnState) ? NSOffState : NSOnState UserDefaults.standard.set((sender.state == NSOffState), forKey: UserSetting.disabledMagicURLs.userDefaultsKey) } //MARK: - handleURLEvent // Called when the App opened via URL. @objc func handleURLEvent(_ event: NSAppleEventDescriptor, withReply reply: NSAppleEventDescriptor) { guard let keyDirectObject = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)), let urlString = keyDirectObject.stringValue, let url : String = urlString.substring(from: urlString.characters.index(urlString.startIndex, offsetBy: 9)), let urlObject = URL(string:url) else { return print("No valid URL to handle") } NotificationCenter.default.post(name: Notification.Name(rawValue: "HeliumLoadURL"), object: urlObject) } }
mit
8011c9f94367ac40a494712b8aae2f61
38.089552
148
0.676976
5.085437
false
false
false
false
lecksfrawen/HeaderDLHamburgerMenuTest
DLHamburguerMenu/BSABaseViewController.swift
1
1997
// // BSABaseViewController.swift // DLHamburguerMenu // // Created by Hector H. De Diego Brito on 10/21/16. // Copyright © 2016 Ignacio Nieto Carvajal. All rights reserved. // import UIKit import Foundation class BSABaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("viewDidLoad desde base") UIApplication.sharedApplication().statusBarStyle = .LightContent // Do any additional setup after loading the view. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // - (UIStatusBarStyle)preferredStatusBarStyle // { // return UIStatusBarStyleLightContent; // } override func preferredStatusBarStyle() -> UIStatusBarStyle { print("SOMEBODY SAVE ME") return UIStatusBarStyle.LightContent } /* // 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. } */ } extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } }
mit
6e85d74957e050fc49d33b491e0b594e
26.342466
144
0.717435
5.131105
false
false
false
false
zype/ZypeAppleTVBase
ZypeAppleTVBase/Models/ResponseModels/ZobjectTypeModel.swift
1
2542
// // ZobjectTypeModel.swift // ZypeAppleTVBase // // Created by Ilya Sorokin on 10/22/15. // Copyright © 2015 Ilya Sorokin. All rights reserved. // import UIKit open class ZobjectTypeModel: BaseModel { fileprivate(set) open var keywords = Array<String>() fileprivate(set) open var createdAt: Date? fileprivate(set) open var updatedAt: Date? fileprivate(set) open var descriptionString = "" fileprivate(set) open var videosEnabled = true fileprivate(set) open var zobjectCount = 0 fileprivate(set) open var siteIdString = "" fileprivate(set) open var zobjectAttributes: Array<AnyObject>? init(fromJson: Dictionary<String, AnyObject>) { super.init(json: fromJson) do { let keywords = fromJson[kJSON_Keywords] if (keywords != nil) { self.keywords = keywords as! Array<String> } self.createdAt = SSUtils.stringToDate(try SSUtils.stringFromDictionary(fromJson, key: kJSONCreatedAt)) self.updatedAt = SSUtils.stringToDate(try SSUtils.stringFromDictionary(fromJson, key: kJSONUpdatedAt)) self.descriptionString = try SSUtils.stringFromDictionary(fromJson, key: kJSONDescription) self.videosEnabled = try SSUtils.boolFromDictionary(fromJson, key: kJSONVideosEnabled) self.zobjectCount = try SSUtils.intagerFromDictionary(fromJson, key: kJSONZobjectCount) self.siteIdString = try SSUtils.stringFromDictionary(fromJson, key: kJSONSiteId) self.zobjectAttributes = fromJson[kJSONZobjectAttributes] as? Array<AnyObject> } catch _ { ZypeLog.error("Exception: ZobjectTypeModel") } } open func getZobjects(_ loadedSince: Date = Date(), completion:@escaping (_ zobjects: Array<ZobjectModel>?, _ error: NSError?) -> Void) { let zobjects = self.userData["zobjects"] if zobjects != nil { if(loadedSince.compare(self.userData["zobjects_date"] as! Date) == ComparisonResult.orderedAscending) { completion(zobjects as? Array<ZobjectModel>, nil) return } } ZypeAppleTVBase.sharedInstance.getZobjects(QueryZobjectsModel(objectType: self), completion: { (objects, error) -> Void in self.userData["zobjects"] = objects as AnyObject? self.userData["zobjects_date"] = Date() as AnyObject? completion(objects, error) }) } }
mit
f853251b235d353eabdb7ba05d120dac
38.703125
139
0.644235
4.351027
false
false
false
false
ONode/actor-platform
actor-apps/app-ios/ActorCore/Providers/MixpanelProvider.swift
24
1829
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class MixpanelProvider:NSObject, ACAnalyticsProvider { var mixpanel: Mixpanel! init(token: String) { mixpanel = Mixpanel.sharedInstanceWithToken(token) } private func saveDeviceId(deviceId: String!) { mixpanel.registerSuperProperties(["deviceId": deviceId]) } func onLoggedOutWithDeviceId(deviceId: String!) { saveDeviceId(deviceId) mixpanel.identify("device:\(deviceId)") } func onLoggedInWithDeviceId(deviceId: String!, withUid uid: jint, withPhoneNumber phoneNumber: jlong, withUserName userName: String!) { saveDeviceId(deviceId) mixpanel.identify("uid:\(uid)") mixpanel.people.set("$phone", to: "\(phoneNumber)") mixpanel.people.set("$name", to: "\(userName)") } func onLoggedInPerformedWithDeviceId(deviceId: String!, withUid uid: jint, withPhoneNumber phoneNumber: jlong, withUserName userName: String!) { saveDeviceId(deviceId) mixpanel.createAlias("uid:\(uid)", forDistinctID: "device:\(deviceId)") mixpanel.identify("uid:\(uid)") mixpanel.people.set("$phone", to: "\(phoneNumber)") mixpanel.people.set("$name", to: "\(userName)") } func trackEvent(event: String!) { mixpanel.track(event) } func trackEvent(event: String!, withArgs hashMap: JavaUtilHashMap!) { var props : [NSObject: AnyObject] = [:] var keys = hashMap.keySet().toArray() for i in 0..<hashMap.size() { var key = keys.objectAtIndex(UInt(i)) as! String var value = hashMap.getWithId(key) as! String props.updateValue(key, forKey: value) } mixpanel.track(event, properties: props) } }
mit
f22414896a739b5cf422cc9a8c96d58f
33.528302
148
0.632039
4.417874
false
false
false
false
welbesw/easypost-swift
Pod/Classes/EasyPostApi.swift
1
29940
// // EasyPostApi.swift // Pods // // Created by William Welbes on 10/4/15. // // import Foundation open class EasyPostApi { //Define a shared instance method to return a singleton of the API manager public static var sharedInstance = EasyPostApi() let errorDomain = "com.technomagination.EasyPostApi" var apiToken = "" //Pass in via setCredentials var apiBaseUrl = "" //Pass in via setCredentials public var logHTTPRequestAndResponse = false public init() { //Nothing more to do here now } public init(token: String, baseUrl: String) { setCredentials(token, baseUrl: baseUrl) } //Set the credentials to use with the API open func setCredentials(_ token: String, baseUrl: String) { self.apiToken = token self.apiBaseUrl = baseUrl } func getAuthHeader() -> [String : String] { let user = self.apiToken let credentialData = "\(user):".data(using: String.Encoding.utf8)! let base64Credentials = credentialData.base64EncodedString(options: []) return ["Authorization": "Basic \(base64Credentials)", "Accept" : "application/json"] } //Use key string format for how the keys will be formed: "address[id]" should be address[%ELEMENT%] func paramtersFromAddress(_ address:EasyPostAddress, keyStringFormat:String) -> [String : String] { var parameters = [String : String]() if let id = address.id { parameters.updateValue(id, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with: "id")) } if let street1 = address.street1 { parameters.updateValue(street1, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"street1")) } if let street2 = address.street2 { parameters.updateValue(street2, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"street2")) } if let city = address.city { parameters.updateValue(city, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"city")) } if let state = address.state { parameters.updateValue(state, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"state")) } if let zip = address.zip { parameters.updateValue(zip, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"zip")) } if let country = address.country { parameters.updateValue(country, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"country")) } if let name = address.name { parameters.updateValue(name, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"name")) } if let company = address.company { parameters.updateValue(company, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"company")) } if let phone = address.phone { parameters.updateValue(phone, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"phone")) } if let email = address.email { parameters.updateValue(email, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"email")) } if let isResidentatial = address.isResidential { parameters.updateValue(isResidentatial ? "true" : "false", forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"residential")) } return parameters } func paramtersFromParcel(_ parcel:EasyPostParcel, keyStringFormat:String) -> [String : String] { var parameters = [String : String]() if let id = parcel.id { parameters.updateValue(id, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"id")) } if let length = parcel.length { parameters.updateValue(length.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"length")) } if let width = parcel.width { parameters.updateValue(width.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"width")) } if let height = parcel.height { parameters.updateValue(height.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"height")) } if let predefinedPackaged = parcel.predefinedPackage { parameters.updateValue(predefinedPackaged, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"predefined_package")) } parameters.updateValue(parcel.weight.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"weight")) return parameters } func parametersForCustomsItem(_ customsItem: EasyPostCustomsItem, keyStringFormat:String) -> [String : String] { var parameters = [String : String]() if let id = customsItem.id { parameters.updateValue(id, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"id")) } if let description = customsItem.itemDescription { parameters.updateValue(description, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"description")) } if let quantity = customsItem.quantity { parameters.updateValue(quantity.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"quantity")) } if let weight = customsItem.weight { parameters.updateValue(weight.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"weight")) } if let value = customsItem.value { parameters.updateValue(value.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"weight")) } if let hs_tariff_number = customsItem.hsTariffNumber { parameters.updateValue(hs_tariff_number.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"hs_tariff_number")) } if let origin_country = customsItem.originCountry { parameters.updateValue(origin_country, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"origin_country")) } return parameters } func parametersForCustomsInfo(_ customsInfo: EasyPostCustomsInfo, keyStringFormat:String) -> [String : String] { var parameters = [String : String]() if let id = customsInfo.id { parameters.updateValue(id, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"id")) } if let customsItems = customsInfo.customsItems { var index = 0 for customsItem in customsItems { if let customsItemId = customsItem.id { parameters.updateValue(customsItemId, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"custom_items").appending("[\(index)][id]")) } else { parameters += parametersForCustomsItem(customsItem, keyStringFormat: "customs_info[customs_items][\(index)][%ELEMENT%]") } index += 1 } } if let contentsType = customsInfo.contentsType?.rawValue { parameters.updateValue(contentsType, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"contents_type")) } if let contentsExplanation = customsInfo.contentsExplanation { parameters.updateValue(contentsExplanation, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"contents_explanation")) } if let restrictionType = customsInfo.restrictionType?.rawValue { parameters.updateValue(restrictionType, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"restriction_type")) } if let restrictionComments = customsInfo.restrictionComments { parameters.updateValue(restrictionComments, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"restriction_comments")) } if let customsCertify = customsInfo.customsCertify { parameters.updateValue(customsCertify.stringValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"customs_certify")) } if let customsSigner = customsInfo.customsSigner { parameters.updateValue(customsSigner, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"customs_signer")) } parameters.updateValue(customsInfo.nonDeliveryOption.rawValue, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"non_delivery_option")) if let eelPfc = customsInfo.eelPfc { parameters.updateValue(eelPfc, forKey: keyStringFormat.replacingOccurrences(of: "%ELEMENT%", with:"eel_pfc")) } return parameters } func parametersForShipment(_ toAddress:EasyPostAddress, fromAddress:EasyPostAddress, parcel:EasyPostParcel, customsInfo:EasyPostCustomsInfo?, carrierAccountIds:[String]?, referenecNumber:String?) -> [String : String] { var parameters = [String : String]() if let toAddressId = toAddress.id { parameters.updateValue(toAddressId, forKey: "shipment[to_address][id]") } else { parameters += paramtersFromAddress(toAddress, keyStringFormat: "shipment[to_address][%ELEMENT%]") } if let fromAddressId = fromAddress.id { parameters.updateValue(fromAddressId, forKey: "shipment[from_address][id]") } else { parameters += paramtersFromAddress(fromAddress, keyStringFormat: "shipment[from_address][%ELEMENT%]") } if let parcelId = parcel.id { parameters.updateValue(parcelId, forKey: "shipment[parcel][id]") } else { parameters += paramtersFromParcel(parcel, keyStringFormat: "shipment[parcel][%ELEMENT%]") } if let customs_info = customsInfo { if let customs_info_id = customs_info.id { parameters.updateValue(customs_info_id, forKey: "shipment[customs_info][id]") } else { parameters += parametersForCustomsInfo(customs_info, keyStringFormat: "shipment[customs_info][%ELEMENT%]") } } if let carriers = carrierAccountIds { for index in 0 ..< carriers.count { parameters.updateValue(carriers[index], forKey: "shipment[carrier_accounts][\(index)][id]") } } if let reference = referenecNumber { parameters.updateValue(reference, forKey: "shipment[reference]") } return parameters } //Post an address model and get an address object with id populated back open func postAddress(_ address:EasyPostAddress, completion: @escaping (_ result: EasyPostResult<EasyPostAddress>) -> ()) { let parameters = paramtersFromAddress(address, keyStringFormat:"address[%ELEMENT%]") guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "addresses", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let address = EasyPostAddress(jsonDictionary: resultDict) completion(EasyPostResult.success(address)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func verifyAddress(_ addressId:String, completion: @escaping (_ result: EasyPostResult<EasyPostAddress>) -> ()) { guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "addresses/\(addressId)/verify", method: .get, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { if let addressDict = resultDict["address"] as? [String: Any] { let address = EasyPostAddress(jsonDictionary: addressDict) completion(EasyPostResult.success(address)) } else { let userInfo = [NSLocalizedDescriptionKey : "address element was not found in results"] completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: userInfo))) } } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func postParcel(_ parcel:EasyPostParcel, completion: @escaping (_ result: EasyPostResult<EasyPostParcel>) -> ()) { let parameters = paramtersFromParcel(parcel, keyStringFormat: "parcel[%ELEMENT%]") guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "parcels", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let parcel = EasyPostParcel(jsonDictionary: resultDict) completion(EasyPostResult.success(parcel)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func postCustomsItem(_ customsItem: EasyPostCustomsItem, completion: @escaping (_ result: EasyPostResult<EasyPostCustomsItem>) -> ()) { let parameters = parametersForCustomsItem(customsItem, keyStringFormat: "customs_item[%ELEMENT%]") guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "customs_items", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let customItem = EasyPostCustomsItem(jsonDictionary: resultDict) completion(EasyPostResult.success(customItem)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func postCustomsInfo(_ customsInfo: EasyPostCustomsInfo, completion: @escaping (_ result: EasyPostResult<EasyPostCustomsInfo>) -> ()) { let parameters = parametersForCustomsInfo(customsInfo, keyStringFormat: "customs_info[%ELEMENT%]") guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "customs_items", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let customInfo = EasyPostCustomsInfo(jsonDictionary: resultDict) completion(EasyPostResult.success(customInfo)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } //If the shipment and parcel objects you pass in have id's defined, those will be used and the rest of the parameters will be ignored. If you pass in objects that don't have id's defined, the parameters will be used to create the objects on the back end open func postShipment(_ toAddress:EasyPostAddress, fromAddress:EasyPostAddress, parcel:EasyPostParcel, customsInfo:EasyPostCustomsInfo? = nil, completion: @escaping (_ result: EasyPostResult<EasyPostShipment>) -> ()) { postShipment(toAddress, fromAddress: fromAddress, parcel: parcel, carrierAccountIds: nil, referenceNumber: nil, customsInfo: customsInfo, completion: completion) } open func postShipment(_ toAddress:EasyPostAddress, fromAddress:EasyPostAddress, parcel:EasyPostParcel, carrierAccountIds:[String]?, referenceNumber:String?, customsInfo:EasyPostCustomsInfo? = nil, completion: @escaping (_ result: EasyPostResult<EasyPostShipment>) -> ()) { let parameters = parametersForShipment(toAddress, fromAddress: fromAddress, parcel: parcel, customsInfo: customsInfo, carrierAccountIds: carrierAccountIds, referenecNumber: referenceNumber) guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "shipments", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let shipment = EasyPostShipment(jsonDictionary: resultDict) completion(EasyPostResult.success(shipment)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func buyShipment(_ shipmentId:String, rateId:String, completion: @escaping (_ result: EasyPostResult<EasyPostBuyResponse>) -> ()) { buyShipment(shipmentId, rateId: rateId, labelFormat: nil, completion: completion) } open func buyShipment(_ shipmentId:String, rateId:String, labelFormat:String?, completion: @escaping (_ result: EasyPostResult<EasyPostBuyResponse>) -> ()) { var parameters = ["rate[id]" : rateId] if let format = labelFormat { parameters.updateValue(format, forKey: "label_format") } guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "shipments/\(shipmentId)/buy", method: .post, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let buyResponse = EasyPostBuyResponse(jsonDictionary: resultDict) completion(EasyPostResult.success(buyResponse)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func getShipments(onlyPurchased:Bool, pageSize:Int, beforeShipmentId:String?, completion: @escaping (_ result: EasyPostResult<[EasyPostShipment]>) -> ()) { var parameters:[String : String] = ["purchased" : onlyPurchased ? "true" : "false", "page_size" : String(pageSize)] if let beforeId = beforeShipmentId { parameters.updateValue(beforeId, forKey: "before_id") } guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "shipments", method: .get, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { if let shipmentsArray = resultDict["shipments"] as? NSArray { var shipments = [EasyPostShipment]() for shipmentItem in shipmentsArray { if let shipmentDict = shipmentItem as? [String: Any] { let shipment = EasyPostShipment(jsonDictionary: shipmentDict) shipments.append(shipment) } } completion(EasyPostResult.success(shipments)) } else { print("getShipments result was successful, but shipments array was not found.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 5, userInfo: nil))) } } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func labelForShipment(_ shipmentId:String, labelFormat:String, completion: @escaping (_ result: EasyPostResult<EasyPostShipment>) -> ()) { let parameters = ["file_format" : labelFormat] guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "shipments/\(shipmentId)/label", method: .get, parameters: parameters, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let shipment = EasyPostShipment(jsonDictionary: resultDict) completion(EasyPostResult.success(shipment)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func getCarrierAccounts(_ completion: @escaping (_ result: EasyPostResult<[EasyPostCarrierAccount]>) -> ()) { guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "carrier_accounts", method: .get, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultArray = json as? [Any] { var carrierAccounts = [EasyPostCarrierAccount]() for carrierItem in resultArray { if let carrierDict = carrierItem as? [String: Any] { let carrierAccount = EasyPostCarrierAccount(jsonDictionary: carrierDict) carrierAccounts.append(carrierAccount) } } completion(EasyPostResult.success(carrierAccounts)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func getCarrierTypes(_ completion: @escaping (_ result: EasyPostResult<[EasyPostCarrierType]>) -> ()) { guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "carrier_types", method: .get, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultArray = json as? [Any] { var carrierTypes = [EasyPostCarrierType]() for carrierItem in resultArray { if let carrierDict = carrierItem as? NSDictionary { let carrierType = EasyPostCarrierType(jsonDictionary: carrierDict) carrierTypes.append(carrierType) } } completion(EasyPostResult.success(carrierTypes)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func getUserApiKeys( _ completion: @escaping (_ result: EasyPostResult<EasyPostUserApiKeys>) -> ()) { guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "api_keys", method: .get, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let userApiKeys = EasyPostUserApiKeys(jsonDictionary: resultDict) completion(EasyPostResult.success(userApiKeys)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } open func requestRefund(_ shipmentId:String, completion: @escaping (_ result: EasyPostResult<EasyPostRefund>) -> ()) { guard let request = URLRequest.newRequest(urlString: apiBaseUrl + "shipments/\(shipmentId)/refund", method: .get, headers: getAuthHeader()) else { return } URLSession.newSession().apiDataTask(with: request, logRequestAndResponse: logHTTPRequestAndResponse) { (result) in switch result { case .success (let json): if let resultDict = json as? [String: Any] { let refund = EasyPostRefund(jsonDictionary: resultDict) completion(EasyPostResult.success(refund)) } else { print("Result was successful, but blank.") completion(EasyPostResult.failure(NSError(domain: self.errorDomain, code: 2, userInfo: nil))) } break case .failure (let error): print(error) completion(EasyPostResult.failure(error)) break } } } }
mit
08f139907af0a152c4ea4708dde8b203
46.298578
277
0.598764
5.043801
false
false
false
false
jaouahbi/OMShadingGradientLayer
Sources/OShadingGradientLayer/GradientBaseLayer.swift
1
13367
// // OMGradientLayer.swift // // Created by Jorge Ouahbi on 19/8/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // // // Copyright 2015 - Jorge Ouahbi // // 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 LibControl public typealias GradientColors = (UIColor,UIColor) typealias TransformContextClosure = (_ ctx:CGContext, _ startPoint:CGPoint, _ endPoint:CGPoint, _ startRadius:CGFloat, _ endRadius:CGFloat) -> (Void) public class GradientBaseLayer: CALayer, GradientLayerProtocol { // MARK: - OMColorsAndLocationsProtocol @objc open var colors: [UIColor] = [] { didSet { // if only exist one color, duplicate it. if (colors.count == 1) { let color = colors.first! colors = [color, color]; } // map monochrome colors to rgba colors colors = colors.map({ return ($0.colorSpace?.model == .monochrome) ? UIColor(red: $0.components[0], green : $0.components[0], blue : $0.components[0], alpha : $0.components[1]) : $0 }) self.setNeedsDisplay() } } @objc open var locations : [CGFloat]? = nil { didSet { if locations != nil{ locations!.sort { $0 < $1 } } self.setNeedsDisplay() } } open var isAxial : Bool { return (gradientType == .axial) } open var isRadial : Bool { return (gradientType == .radial) } // MARK: - OMAxialGradientLayerProtocol open var gradientType: GradientType = .axial { didSet { self.setNeedsDisplay(); } } @objc open var startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5) { didSet { self.setNeedsDisplay(); } } @objc open var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5) { didSet{ self.setNeedsDisplay(); } } open var extendsBeforeStart : Bool = false { didSet { self.setNeedsDisplay() } } open var extendsPastEnd : Bool = false { didSet { self.setNeedsDisplay() } } // MARK: - OMRadialGradientLayerProtocol @objc open var startRadius: CGFloat = 0 { didSet { startRadius = clamp(startRadius, lowerValue: 0, upperValue: 1.0) self.setNeedsDisplay(); } } @objc open var endRadius: CGFloat = 0 { didSet { endRadius = clamp(endRadius, lowerValue: 0, upperValue: 1.0) self.setNeedsDisplay(); } } // MARK: OMMaskeableLayerProtocol open var lineWidth : CGFloat = 1.0 { didSet { self.setNeedsDisplay() } } open var stroke : Bool = false { didSet { self.setNeedsDisplay() } } open var path: CGPath? { didSet { self.setNeedsDisplay() } } /// Transform the radial gradient /// example: oval gradient = CGAffineTransform(scaleX: 2, y: 1.0); open var radialTransform: CGAffineTransform = CGAffineTransform.identity { didSet { self.setNeedsDisplay() } } // Some predefined Gradients (from WebKit) public lazy var insetGradient:GradientColors = { return (UIColor(red:0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0 ), UIColor(red: 0 / 255.0, green:0 / 255.0,blue: 0 / 255.0,alpha: 0.2 )) }() public lazy var shineGradient:GradientColors = { return (UIColor(red:1, green:1,blue: 1,alpha: 0 ), UIColor(red: 1, green:1,blue:1,alpha: 0.8 )) }() public lazy var shadeGradient:GradientColors = { return (UIColor(red: 252 / 255.0, green: 252 / 255.0,blue: 252 / 255.0,alpha: 0.65 ), UIColor(red: 178 / 255.0, green:178 / 255.0,blue: 178 / 255.0,alpha: 0.65 )) }() public lazy var convexGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.43 ), UIColor(red:1,green:1,blue:1,alpha: 0.5 )) }() public lazy var concaveGradient:GradientColors = { return (UIColor(red:1,green:1,blue:1,alpha: 0.0 ), UIColor(red:1,green:1,blue:1,alpha: 0.46 )) }() // Here's a method that creates a view that allows 360 degree rotation of its two-colour // gradient based upon input from a slider (or anything). The incoming slider value // ("x" variable below) is between 0.0 and 1.0. // // At 0.0 the gradient is horizontal (with colour A on top, and colour B below), rotating // through 360 degrees to value 1.0 (identical to value 0.0 - or a full rotation). // // E.g. when x = 0.25, colour A is left and colour B is right. At 0.5, colour A is below // and colour B is above, 0.75 colour A is right and colour B is left. It rotates anti-clockwise // from right to left. // // It takes four arguments: frame, colourA, colourB and the input value (0-1). // // from: http://stackoverflow.com/a/29168654/6387073 public class func pointsFromNormalizedAngle(_ normalizedAngle:Double) -> (CGPoint,CGPoint) { //x is between 0 and 1, eg. from a slider, representing 0 - 360 degrees //colour A starts on top, with colour B below //rotations move anti-clockwise //create coordinates let r = 2.0 * .pi; let a = pow(sin((r*((normalizedAngle+0.75)/2))),2); let b = pow(sin((r*((normalizedAngle+0.0)/2))),2); let c = pow(sin((r*((normalizedAngle+0.25)/2))),2); let d = pow(sin((r*((normalizedAngle+0.5)/2))),2); //set the gradient direction return (CGPoint(x: a, y: b),CGPoint(x: c, y: d)) } // MARK: - Object constructors required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } convenience public init(type:GradientType) { self.init() self.gradientType = type } // MARK: - Object Overrides override public init() { super.init() self.allowsEdgeAntialiasing = true self.contentsScale = UIScreen.main.scale self.needsDisplayOnBoundsChange = true; self.drawsAsynchronously = true; } override public init(layer: Any) { super.init(layer: layer) if let other = layer as? GradientBaseLayer { // common self.colors = other.colors self.locations = other.locations self.gradientType = other.gradientType // axial gradient properties self.startPoint = other.startPoint self.endPoint = other.endPoint self.extendsBeforeStart = other.extendsBeforeStart self.extendsPastEnd = other.extendsPastEnd // radial gradient properties self.startRadius = other.startRadius self.endRadius = other.endRadius // OMMaskeableLayerProtocol self.path = other.path self.stroke = other.stroke self.lineWidth = other.lineWidth self.radialTransform = other.radialTransform } } // MARK: - Functions override open class func needsDisplay(forKey event: String) -> Bool { if (event == GradientLayerProperties.startPoint || event == GradientLayerProperties.locations || event == GradientLayerProperties.colors || event == GradientLayerProperties.endPoint || event == GradientLayerProperties.startRadius || event == GradientLayerProperties.endRadius) { return true } return super.needsDisplay(forKey: event) } override open func action(forKey event: String) -> CAAction? { if (event == GradientLayerProperties.startPoint || event == GradientLayerProperties.locations || event == GradientLayerProperties.colors || event == GradientLayerProperties.endPoint || event == GradientLayerProperties.startRadius || event == GradientLayerProperties.endRadius) { return animationActionForKey(event); } return super.action(forKey: event) } override open func draw(in ctx: CGContext) { // super.drawInContext(ctx) do nothing let clipBoundingBox = ctx.boundingBoxOfClipPath ctx.clear(clipBoundingBox); ctx.clip(to: clipBoundingBox) } func prepareContextIfNeeds(_ ctx:CGContext, scale:CGAffineTransform, closure:TransformContextClosure) { let sp = CGPoint( x: self.startPoint.x * self.bounds.size.width, y: self.startPoint.y * self.bounds.size.height) let ep = CGPoint( x: self.endPoint.x * self.bounds.size.width, y: self.endPoint.y * self.bounds.size.height) // let ep = self.endPoint * self.bounds.size let mr = minRadius(self.bounds.size) // Scaling transformation and keeping track of the inverse let invScaleT = scale.inverted(); // Extract the Sx and Sy elements from the inverse matrix (See the Quartz documentation for the math behind the matrices) let invS = CGPoint(x:invScaleT.a, y:invScaleT.d); // Transform center and radius of gradient with the inverse let startPointAffined = CGPoint(x:sp.x * invS.x, y:sp.y * invS.y); let endPointAffined = CGPoint(x:ep.x * invS.x, y:ep.y * invS.y); let startRadiusAffined = mr * startRadius * invS.x; let endRadiusAffined = mr * endRadius * invS.x; // Draw the gradient with the scale transform on the context ctx.scaleBy(x: scale.a, y: scale.d); closure(ctx, startPointAffined, endPointAffined, startRadiusAffined, endRadiusAffined) // Reset the context ctx.scaleBy(x: invS.x, y: invS.y); } func addPathAndClipIfNeeded(_ ctx:CGContext) { if (self.path != nil) { ctx.addPath(self.path!); if (self.stroke) { ctx.setLineWidth(self.lineWidth); ctx.replacePathWithStrokedPath(); } ctx.clip(); } } func isDrawable() -> Bool { if (colors.count == 0) { // nothing to do Log.print("\(self.name ?? "") Unable to do the shading without colors.") return false } if (startPoint.isZero && endPoint.isZero) { // nothing to do Log.print("\(self.name ?? "") Start point and end point are {x:0, y:0}.") return false } if (startRadius == endRadius && self.isRadial) { // nothing to do Log.print("\(self.name ?? "") Start radius and end radius are equal. \(startRadius) \(endRadius)") return false } return true; } override open var description:String { get { var currentDescription:String = "type: \((self.isAxial ? "Axial" : "Radial")) " if let locations = locations { if(locations.count == colors.count) { _ = zip(colors,locations).compactMap { currentDescription += "color: \($0.0.shortDescription) location: \($0.1) " } } else { if (locations.count > 0) { _ = locations.map({currentDescription += "\($0) "}) } if (colors.count > 0) { _ = colors.map({currentDescription += "\($0.shortDescription) "}) } } } if (self.isRadial) { currentDescription += "center from : \(startPoint) to \(endPoint), radius from : \(startRadius) to \(endRadius)" } else if (self.isAxial) { currentDescription += "from : \(startPoint) to \(endPoint)" } if (self.extendsPastEnd) { currentDescription += " draws after end location " } if (self.extendsBeforeStart) { currentDescription += " draws before start location " } return currentDescription } } }
apache-2.0
b7e057b4ea62af2951c437cbd3ec9ced
34.359788
150
0.551474
4.358005
false
false
false
false
invalidstream/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_04_PhotoEditing_Begin/CocoaConf Photo Editing/PhotoEditingViewController.swift
1
5015
// // PhotoEditingViewController.swift // CocoaConf Photo Editing // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit import Photos import PhotosUI import CoreImage class PhotoEditingViewController: UIViewController, PHContentEditingController { @IBOutlet weak var imagePreview: UIImageView! @IBOutlet weak var pixellationScaleSlider: UISlider! var pixellateFilter: CIFilter! var input: PHContentEditingInput? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. pixellateFilter = CIFilter(name: "CIPixellate") pixellateFilter.setDefaults() updateFilteredPreview() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func updateFilteredPreview() { if let cgImage = input?.displaySizeImage?.CGImage { let ciImage = CIImage(CGImage: cgImage) imagePreview.image = UIImage (CIImage: applyPixellateFilterToCIImage (ciImage)) } else { NSLog ("couldn't get CIImage") } } private func applyPixellateFilterToCIImage (ciImage: CIImage) -> CIImage { pixellateFilter.setValue(NSNumber (float: pixellationScaleSlider.value), forKey: "inputScale") pixellateFilter.setValue(ciImage, forKey: "inputImage") return pixellateFilter.outputImage ?? ciImage } @IBAction func pixellationScaleSliderValueChanged(sender: AnyObject) { updateFilteredPreview() } // MARK: - PHContentEditingController func canHandleAdjustmentData(adjustmentData: PHAdjustmentData?) -> Bool { // Inspect the adjustmentData to determine whether your extension can work with past edits. // (Typically, you use its formatIdentifier and formatVersion properties to do this.) return false } func startContentEditingWithInput(contentEditingInput: PHContentEditingInput?, placeholderImage: UIImage) { // Present content for editing, and keep the contentEditingInput for use when closing the edit session. // If you returned YES from canHandleAdjustmentData:, contentEditingInput has the original image and adjustment data. // If you returned NO, the contentEditingInput has past edits "baked in". input = contentEditingInput updateFilteredPreview() } func finishContentEditingWithCompletionHandler(completionHandler: ((PHContentEditingOutput!) -> Void)!) { // Update UI to reflect that editing has finished and output is being rendered. // Render and provide output on a background queue. dispatch_async(dispatch_get_global_queue(CLong(DISPATCH_QUEUE_PRIORITY_DEFAULT), 0)) { // Create editing output from the editing input. let output = PHContentEditingOutput(contentEditingInput: self.input!) // Provide new adjustments and render output to given location. // output.adjustmentData = <#new adjustment data#> // let renderedJPEGData = <#output JPEG#> // renderedJPEGData.writeToURL(output.renderedContentURL, atomically: true) let adjustmentDict = ["pixellateScale" : NSNumber(float: self.pixellationScaleSlider.value)] let adjustmentData = PHAdjustmentData (formatIdentifier: "CocoaConfPixellator", formatVersion: "1.0", data: NSKeyedArchiver.archivedDataWithRootObject(adjustmentDict)) output.adjustmentData = adjustmentData if let fullSizeImageURL = self.input!.fullSizeImageURL, fullCIImage = CIImage (contentsOfURL: fullSizeImageURL) { let fullFilteredImage = self.applyPixellateFilterToCIImage (fullCIImage) let myCIContext = CIContext (EAGLContext: EAGLContext (API: .OpenGLES2)) let myCGImage = myCIContext.createCGImage(fullFilteredImage, fromRect: fullFilteredImage.extent) let myUIImage = UIImage(CGImage: myCGImage) let fullFilteredJPEG = UIImageJPEGRepresentation (myUIImage, 1.0) let wrote = fullFilteredJPEG!.writeToURL(output.renderedContentURL, atomically: true) if !wrote { NSLog ("Failed to write to \(output.renderedContentURL)") } } // Call completion handler to commit edit to Photos. completionHandler?(output) NSLog ("called completion handler") // Clean up temporary files, etc. } } var shouldShowCancelConfirmation: Bool { // Determines whether a confirmation to discard changes should be shown to the user on cancel. // (Typically, this should be "true" if there are any unsaved changes.) return false } func cancelContentEditing() { // Clean up temporary files, etc. // May be called after finishContentEditingWithCompletionHandler: while you prepare output. } }
cc0-1.0
a98170af27789350a20efaa75217cba2
39.443548
125
0.699302
4.970268
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
InfiniteScroll/InfiniteScroll/Controller/HomeViewController.swift
1
14068
// // HomeViewController.swift // InfiniteScroll // // Created by Anirudh Das on 7/6/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import UIKit import SwiftSpinner import Alamofire import SDWebImage /** Presents a text field for user entry, and shows infinite list of images with current time. */ class HomeViewController: UIViewController { // MARK:- IBOutlets @IBOutlet weak var userEntryView: UIView! @IBOutlet weak var nameTxtFld: UITextField! @IBOutlet weak var startBtn: UIButton! @IBOutlet weak var userDetailView: UIView! @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var currentDateTimeLbl: UILabel! @IBOutlet weak var imagesCollectionView: UICollectionView! // MARK:- Properties weak var timer: Timer? var pixlrService: PixlrServiceProtocol! var pixlrImageArray: [PixlrImage] = [] var footerView: CustomFooterView? var isLoading:Bool = false var imageSearchRequest: DataRequest? var cellHeight: CGFloat? // MARK:- Initializers //Inject dependencies convenience init(pixlrService: PixlrServiceProtocol) { self.init() self.pixlrService = pixlrService } // MARK:- DeInitializers deinit { timer?.invalidate() } // MARK:- View Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Just incase this VC is initialized via Storyboard. if pixlrService == nil { pixlrService = PixlrService(apiURL: ServerConfiguration.apiBaseUrl) } setupView() } //Configures the view func setupView() { //Hides Scroll of Collection View imagesCollectionView.showsHorizontalScrollIndicator = false imagesCollectionView.showsVerticalScrollIndicator = false //Register FooterView imagesCollectionView.register(UINib(nibName: Constants.footerViewXibName, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: Constants.footerViewReuseIdentifier) //For cell spacing and padding. if let layout = imagesCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5) layout.minimumInteritemSpacing = 5 cellHeight = imagesCollectionView.frame.size.height / 3 if UIDevice.current.screenType == .iPhones_5_5s_5c_SE { layout.itemSize = CGSize(width: (imagesCollectionView.frame.size.width - 20) / 2.5, height: imagesCollectionView.frame.size.height / 3) } else { layout.itemSize = CGSize(width: (imagesCollectionView.frame.size.width - 20) / 2, height: imagesCollectionView.frame.size.height / 3) } } userDetailView.isHidden = true imagesCollectionView.isHidden = true nameTxtFld.addCornerRadius(radius: 5.0) startBtn.addCornerRadius(radius: 5.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. //print("Memory Warning Received") } // MARK:- IBActions @IBAction func startBtnClicked(_ sender: UIButton) { handleStartClick() } func handleStartClick() { hideKeypad() guard checkIfValidInput() else { Utility.showAlertMessage(title: Constants.alertTitle, message: Constants.alertMessage, viewController: self) return } SwiftSpinner.show(delay: 0.3, title: Constants.spinnerMessage) _ = pixlrService.fetchImagesForPage(pageNumber: 1, completionBlock: { [weak self] (pixlrImageArray) in SwiftSpinner.hide() guard let weakSelf = self, let pixlrImageArray = pixlrImageArray else { //print("No Data Found") return } weakSelf.pixlrImageArray = pixlrImageArray weakSelf.userEntryView.isHidden = true weakSelf.userDetailView.isHidden = false weakSelf.nameLbl.text = weakSelf.nameTxtFld.text weakSelf.imagesCollectionView.isHidden = false weakSelf.imagesCollectionView.reloadData() weakSelf.startTimer() }) } //Returns true if input is not empty func checkIfValidInput() -> Bool { guard let name = nameTxtFld.text, !name.isEmpty else { return false } return true } //Refreshes time on UI every 0.05 seconds func startTimer() { timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(showDateTime), userInfo: nil, repeats: true) if let timer = timer { //To avoid lag of timer during scrolling RunLoop.main.add(timer, forMode: .commonModes) } } //Shows time value on UI @objc func showDateTime() { currentDateTimeLbl.text = Date().toString(with: Constants.dateFormat) } } // MARK:- UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pixlrImageArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let imageCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.imageCellReuseIdentifier, for: indexPath) as? ImageCollectionViewCell else { return UICollectionViewCell() } imageCell.configureImageCell(pixlrImage: pixlrImageArray[indexPath.row]) imageCell.deselected() return imageCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath), let imageCell = cell as? ImageCollectionViewCell else { return } imageCell.selected() guard let downloadedImage = imageCell.downloadedImage else { return } let imageInfo = GSImageInfo(image: downloadedImage, imageMode: .aspectFit) let transitionInfo = GSTransitionInfo(fromView: imageCell.contentImgView!) let imageViewer = GSImageViewerController(imageInfo: imageInfo, transitionInfo: transitionInfo) present(imageViewer, animated: true, completion: nil) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath), let imageCell = cell as? ImageCollectionViewCell else { return } imageCell.deselected() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize.zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { if isLoading { return CGSize.zero } return CGSize(width: collectionView.bounds.size.width, height: 55) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionFooter { guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Constants.footerViewReuseIdentifier, for: indexPath) as? CustomFooterView else { return UICollectionReusableView() } self.footerView = footer self.footerView?.backgroundColor = UIColor.clear return footer } else { guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Constants.footerViewReuseIdentifier, for: indexPath) as? CustomFooterView else { return UICollectionReusableView() } return header } } func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { if elementKind == UICollectionElementKindSectionFooter { self.footerView?.prepareInitialAnimation() } } func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) { if elementKind == UICollectionElementKindSectionFooter { self.footerView?.stopAnimate() } } //compute the scroll value and play witht the threshold to get desired effect func scrollViewDidScroll(_ scrollView: UIScrollView) { let threshold = 100.0 let contentOffset = scrollView.contentOffset.y let contentHeight = scrollView.contentSize.height let diffHeight = contentHeight - contentOffset let frameHeight = scrollView.bounds.size.height var triggerThreshold = Float((diffHeight - frameHeight))/Float(threshold) triggerThreshold = min(triggerThreshold, 0.0) let pullRatio = min(fabs(triggerThreshold), 1.0) self.footerView?.setTransform(inTransform: CGAffineTransform.identity, scaleFactor: CGFloat(pullRatio)) if pullRatio >= 1 { self.footerView?.animateFinal() } //For memory managament, we free images from top if the infinite list exceeds a certain thresold. if let cellHeight = cellHeight, pixlrImageArray.count + ServerConfiguration.imagesPerPage >= Constants.maxNumberOfImagesAtATime { //let top: CGFloat = 0 let bottom: CGFloat = scrollView.contentSize.height - scrollView.frame.size.height let buffer: CGFloat = Constants.cellBuffer * cellHeight let scrollPosition = scrollView.contentOffset.y if scrollPosition > bottom - buffer { let tempImagesArray: [PixlrImage] = Array(pixlrImageArray.prefix(Constants.maxNumberOfItemsToBeFreed)) if tempImagesArray.count > 0 { //print("Reached the bottom of the collection view") pixlrImageArray.removeFirst(Constants.maxNumberOfItemsToBeFreed) // Update the CollectionView and contentOffset imagesCollectionView.reloadData() imagesCollectionView.contentOffset.y -= CGFloat(Constants.maxNumberOfItemsToBeFreed) * cellHeight removeImagesFromCache(images: tempImagesArray) { } } } /*else if scrollPosition < top + buffer { print("Reach the top of the collection view") }*/ } } func removeImagesFromCache(images: [PixlrImage], completionBlock: @escaping () -> Void) { performOperationInBackground { //print("Before Clearing: \(SDImageCache.shared().getSize())") var count = 0 for image in images { SDImageCache.shared().removeImage(forKey: image.previewURL, fromDisk: true, withCompletion: { count = count + 1 if count == images.count { //print("After Clearing: \(SDImageCache.shared().getSize())") completionBlock() } }) } } } //compute the offset and call the load method func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if (self.footerView?.isAnimatingFinal)! { //print("loading more images") self.isLoading = true self.footerView?.startAnimate() if let _ = imageSearchRequest { //print("Already Ongoing Request") return } Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { (_) in var pageNumber = 1 //Default if let lastImage = self.pixlrImageArray.last { pageNumber = lastImage.pageNumber + 1 } self.imageSearchRequest = self.pixlrService.fetchImagesForPage(pageNumber: pageNumber, completionBlock: { [weak self] (pixlrImageArray) in guard let weakSelf = self else { return } if let pixlrImageArray = pixlrImageArray { weakSelf.pixlrImageArray.append(contentsOf: pixlrImageArray) weakSelf.imagesCollectionView.reloadData() } else { //print("No data found") weakSelf.imagesCollectionView.scrollToItem(at: IndexPath(row: weakSelf.pixlrImageArray.count - 1, section: 0), at: .bottom, animated: true) } weakSelf.isLoading = false weakSelf.footerView?.stopAnimate() weakSelf.imageSearchRequest = nil }) }) } } } extension HomeViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { hideKeypad() return false } func hideKeypad() { view.endEditing(true) } }
apache-2.0
117c7f9c7676e70ababc42599b2d7a35
40.991045
219
0.644061
5.64713
false
false
false
false
rodrigoff/hackingwithswift
project14/Project14/WhackSlot.swift
1
2085
// // WhackSlot.swift // Project14 // // Created by Rodrigo F. Fernandes on 7/24/17. // Copyright © 2017 Rodrigo F. Fernandes. All rights reserved. // import SpriteKit import UIKit class WhackSlot: SKNode { var charNode: SKSpriteNode! var isVisible = false var isHit = false func configure(at position: CGPoint) { self.position = position let sprite = SKSpriteNode(imageNamed: "whackHole") addChild(sprite) let cropNode = SKCropNode() cropNode.position = CGPoint(x: 0, y: 15) cropNode.zPosition = 1 cropNode.maskNode = SKSpriteNode(imageNamed: "whackMask") charNode = SKSpriteNode(imageNamed: "penguinGood") charNode.position = CGPoint(x: 0, y: -90) charNode.name = "character" cropNode.addChild(charNode) addChild(cropNode) } func show(hideTime: Double) { if isVisible { return } charNode.xScale = 1 charNode.yScale = 1 charNode.run(SKAction.moveBy(x: 0, y: 80, duration: 0.05)) isVisible = true isHit = false if RandomInt(min: 0, max: 2) == 0 { charNode.texture = SKTexture(imageNamed: "penguinGood") charNode.name = "charFriend" } else { charNode.texture = SKTexture(imageNamed: "penguinEvil") charNode.name = "charEnemy" } DispatchQueue.main.asyncAfter(deadline: .now() + (hideTime * 3.5)) { [unowned self] in self.hide() } } func hide() { if !isVisible { return } charNode.run(SKAction.moveBy(x: 0, y:-80, duration:0.05)) isVisible = false } func hit() { isHit = true let delay = SKAction.wait(forDuration: 0.25) let hide = SKAction.moveBy(x: 0, y:-80, duration:0.5) let notVisible = SKAction.run { [unowned self] in self.isVisible = false } charNode.run(SKAction.sequence([delay, hide, notVisible])) } }
mit
8d06638b01fe9fc843f5c322e7c5a26e
26.421053
94
0.564299
4.102362
false
false
false
false
turekj/ReactiveTODO
ReactiveTODOFramework/Classes/Assemblies/CreateTODOAssembly.swift
1
2467
import Foundation import Swinject import UIKit public class CreateTODOAssembly: AssemblyType { public init() { } public func assemble(container: Container) { container.register(CreateTODONoteViewController.self) { r in let view = r.resolve(CreateTODONoteView.self)! let viewModel = r.resolve(CreateTODONoteViewModel.self)! return CreateTODONoteViewController(view: view, viewModel: viewModel) } container.register(CreateTODONoteView.self) { r in let noteTextView = r.resolve(NoteTextView.self)! let priorityPicker = r.resolve(PriorityPicker.self)! let datePicker = r.resolve(PopupDatePicker.self)! return CreateTODONoteView(noteLabel: UILabel(), noteTextView: noteTextView, priorityLabel: UILabel(), priorityPicker: priorityPicker, dateLabel: UILabel(), datePicker: datePicker) } container.register(NoteTextView.self) { r in let noteValidator = r.resolve(Validator<String?>.self)! return NoteTextView(validator: noteValidator) } container.register(PriorityPicker.self) { r in let priorityValidator = r.resolve(Validator<Priority?>.self)! let priorities = [Priority.Urgent, Priority.High, Priority.Medium, Priority.Low] return PriorityPicker(validator: priorityValidator, priorities: priorities) } container.register(PopupDatePicker.self) { r in let validator = r.resolve(Validator<NSDate?>.self)! let dateFormatter = r.resolve(DateFormatterProtocol.self, name: "relative")! return PopupDatePicker(validator: validator, dateFormatter: dateFormatter, datePicker: UIDatePicker(), triggerPickerButton: UIButton(type: .RoundedRect)) } container.register(CreateTODONoteViewModel.self) { r in let factory = r.resolve( CreateTODONoteListViewModelFactoryProtocol.self)! return factory.createViewModel() } container.register(CreateTODONoteListViewModelFactoryProtocol.self) { _ in return CreateTODONoteListViewModelFactory() } } }
mit
2c53f08560bbe6470f1e01364a849cce
34.242857
77
0.60154
5.53139
false
false
false
false
dreamsxin/swift
stdlib/public/SDK/UIKit/UIKit.swift
3
6954
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation @_exported import UIKit //===----------------------------------------------------------------------===// // UIGeometry //===----------------------------------------------------------------------===// public extension UIEdgeInsets { static var zero: UIEdgeInsets { @_transparent // @fragile get { return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) } } } public extension UIOffset { static var zero: UIOffset { @_transparent // @fragile get { return UIOffset(horizontal: 0.0, vertical: 0.0) } } } //===----------------------------------------------------------------------===// // Equatable types. //===----------------------------------------------------------------------===// @_transparent // @fragile public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool { return lhs.top == rhs.top && lhs.left == rhs.left && lhs.bottom == rhs.bottom && lhs.right == rhs.right } extension UIEdgeInsets : Equatable {} @_transparent // @fragile public func == (lhs: UIOffset, rhs: UIOffset) -> Bool { return lhs.horizontal == rhs.horizontal && lhs.vertical == rhs.vertical } extension UIOffset : Equatable {} // These are un-imported macros in UIKit. //===----------------------------------------------------------------------===// // UIDeviceOrientation //===----------------------------------------------------------------------===// #if !os(watchOS) && !os(tvOS) public extension UIDeviceOrientation { var isLandscape: Bool { return self == .landscapeLeft || self == .landscapeRight } var isPortrait: Bool { return self == .portrait || self == .portraitUpsideDown } var isFlat: Bool { return self == .faceUp || self == .faceDown } var isValidInterfaceOrientation: Bool { switch (self) { case .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight: return true default: return false } } } public func UIDeviceOrientationIsLandscape( _ orientation: UIDeviceOrientation ) -> Bool { return orientation.isLandscape } public func UIDeviceOrientationIsPortrait( _ orientation: UIDeviceOrientation ) -> Bool { return orientation.isPortrait } public func UIDeviceOrientationIsValidInterfaceOrientation( _ orientation: UIDeviceOrientation) -> Bool { return orientation.isValidInterfaceOrientation } #endif //===----------------------------------------------------------------------===// // UIInterfaceOrientation //===----------------------------------------------------------------------===// #if !os(watchOS) && !os(tvOS) public extension UIInterfaceOrientation { var isLandscape: Bool { return self == .landscapeLeft || self == .landscapeRight } var isPortrait: Bool { return self == .portrait || self == .portraitUpsideDown } } public func UIInterfaceOrientationIsPortrait( _ orientation: UIInterfaceOrientation) -> Bool { return orientation.isPortrait } public func UIInterfaceOrientationIsLandscape( _ orientation: UIInterfaceOrientation ) -> Bool { return orientation.isLandscape } #endif // Overlays for variadic initializers. #if !os(watchOS) && !os(tvOS) public extension UIActionSheet { convenience init(title: String?, delegate: UIActionSheetDelegate?, cancelButtonTitle: String?, destructiveButtonTitle: String?, // Hack around overload ambiguity with non-variadic constructor. // <rdar://problem/16704770> otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...) { self.init(title: title, delegate: delegate, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle) self.addButton(withTitle: firstButtonTitle) for buttonTitle in moreButtonTitles { self.addButton(withTitle: buttonTitle) } } } #endif #if !os(watchOS) && !os(tvOS) public extension UIAlertView { convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, // Hack around overload ambiguity with non-variadic constructor. // <rdar://problem/16704770> otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...) { self.init(title: title, message: message, delegate: delegate, cancelButtonTitle: cancelButtonTitle) self.addButton(withTitle: firstButtonTitle) for buttonTitle in moreButtonTitles { self.addButton(withTitle: buttonTitle) } } } #endif #if !os(watchOS) internal struct _UIViewQuickLookState { static var views = Set<UIView>() } extension UIView : _DefaultCustomPlaygroundQuickLookable { public var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { if _UIViewQuickLookState.views.contains(self) { return .view(UIImage()) } else { _UIViewQuickLookState.views.insert(self) // in case of an empty rectangle abort the logging if (bounds.size.width == 0) || (bounds.size.height == 0) { return .view(UIImage()) } UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) // UIKit is about to update this to be optional, so make it work // with both older and newer SDKs. (In this context it should always // be present.) let ctx: CGContext! = UIGraphicsGetCurrentContext() UIColor(white:1.0, alpha:0.0).set() ctx.fill(bounds) layer.render(in: ctx) let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() _UIViewQuickLookState.views.remove(self) return .view(image) } } } #endif extension UIColor : _ColorLiteralConvertible { @nonobjc public required convenience init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) { self.init(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha)) } } public typealias _ColorLiteralType = UIColor extension UIImage : _ImageLiteralConvertible { private convenience init!(failableImageLiteral name: String) { self.init(named: name) } public required convenience init(imageLiteralResourceName name: String) { self.init(failableImageLiteral: name) } } public typealias _ImageLiteralType = UIImage
apache-2.0
44bc1ed36a02d846a9f4f9a0df177bdc
28.591489
80
0.603681
5.174107
false
false
false
false
cenfoiOS/ImpesaiOSCourse
DefaultTableViewExample/DefaultTableViewExample/NumbersTableViewController.swift
1
2962
// // NumbersTableViewController.swift // DefaultTableViewExample // // Created by Cesar Brenes on 5/11/17. // Copyright © 2017 César Brenes Solano. All rights reserved. // import UIKit class NumbersTableViewController: UITableViewController { var array = [Int]() override func viewDidLoad() { super.viewDidLoad() array = loadDataSource() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadDataSource() -> [Int]{ var array = [Int]() for index in 200...300{ array.append(index) } return array } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let value = array[indexPath.row] cell.textLabel?.text = "\(value)" return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
07b6aa79fd3076bdf84b2c8b9057962a
28.89899
136
0.64527
5.112263
false
false
false
false
ainopara/Stage1st-Reader
Stage1st/Scene/Settings/SettingsViewController.swift
1
19288
// // SettingsViewController.swift // Stage1st // // Created by Zheng Li on 4/9/16. // Copyright © 2016 Renaissance. All rights reserved. // import UIKit import AcknowList import WebKit import CocoaLumberjack import Ainoaibo import ReactiveSwift import ReactiveCocoa import Combine import Files import SafariServices final class SettingsViewController: UITableViewController { @IBOutlet weak var usernameDetailLabel: UILabel! @IBOutlet weak var fontSizeDetailLabel: UILabel! @IBOutlet weak var displayImageSwitch: UISwitch! @IBOutlet weak var keepHistoryDetailLabel: UILabel! @IBOutlet weak var removeTailsSwitch: UISwitch! @IBOutlet weak var precacheSwitch: UISwitch! @IBOutlet weak var forcePortraitSwitch: UISwitch! @IBOutlet weak var nightModeSwitch: UISwitch! @IBOutlet weak var matchSystemDarkModeSwitch: UISwitch! @IBOutlet weak var forumOrderCell: UITableViewCell! @IBOutlet weak var fontSizeCell: UITableViewCell! @IBOutlet weak var keepHistoryCell: UITableViewCell! @IBOutlet weak var imageCacheCell: UITableViewCell! @IBOutlet weak var iCloudSyncDetailLabel: UILabel! @IBOutlet weak var versionDetailLabel: UILabel! var bag = Set<AnyCancellable>() override var preferredStatusBarStyle: UIStatusBarStyle { return AppEnvironment.current.colorManager.isDarkTheme() ? .lightContent : .default } override func viewDidLoad() { super.viewDidLoad() forumOrderCell.textLabel?.text = NSLocalizedString("SettingsViewController.Forum_Order_Custom", comment: "Forum Order") let settings = AppEnvironment.current.settings displayImageSwitch.isOn = settings.displayImage.value forcePortraitSwitch.isOn = settings.forcePortraitForPhone.value removeTailsSwitch.isOn = settings.removeTails.value precacheSwitch.isOn = settings.precacheNextPage.value versionDetailLabel.text = applicationVersion() navigationItem.title = NSLocalizedString("SettingsViewController.NavigationBar_Title", comment: "Settings") fontSizeCell.textLabel?.text = NSLocalizedString("SettingsViewController.Font_Size", comment: "Font Size") fontSizeCell.detailTextLabel?.text = settings.defaults.string(forKey: "FontSize") fontSizeCell.selectionStyle = .blue fontSizeCell.accessoryType = .disclosureIndicator keepHistoryCell.textLabel?.text = NSLocalizedString("SettingsViewController.HistoryLimit", comment: "History Limit") keepHistoryCell.detailTextLabel?.text = historyLimitString(from: settings.defaults.integer(forKey: "HistoryLimit")) keepHistoryCell.selectionStyle = .blue keepHistoryCell.accessoryType = .disclosureIndicator let prettyPrintedCacheSize = Double(totalCacheSize() / (102 * 1024)) / 10.0 imageCacheCell.detailTextLabel?.text = String(format: "%.1f MiB", prettyPrintedCacheSize) NotificationCenter.default.addObserver( self, selector: #selector(didReceivePaletteChangeNotification), name: .APPaletteDidChange, object: nil ) setupObservation() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let settings = AppEnvironment.current.settings fontSizeDetailLabel.text = settings.defaults.string(forKey: "FontSize") keepHistoryCell.detailTextLabel?.text = historyLimitString(from: settings.defaults.integer(forKey: "HistoryLimit")) didReceivePaletteChangeNotification(nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) AppEnvironment.current.eventTracker.setObjectValue("SettingsViewController", forKey: "lastViewController") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if AppEnvironment.current.settings.forcePortraitForPhone.value && UIDevice.current.userInterfaceIdiom == .phone { return .portrait } else { return super.supportedInterfaceOrientations } } @IBAction func backAction(_ sender: Any) { dismiss(animated: true, completion: nil) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { S1LogDebug("select: \(indexPath)") tableView.deselectRow(at: indexPath, animated: true) let settings = AppEnvironment.current.settings switch (indexPath.section, indexPath.row) { case (0, 1): navigationController?.pushViewController(ReorderForumViewController(), animated: true) case (0, 2): let keys: [String] = { if UIDevice.current.userInterfaceIdiom == .phone { return ["15px", "17px", "19px", "21px", "23px"] } else { return ["18px", "20px", "22px", "24px", "26px"] } }() let controller = GSSingleSelectionTableViewController(keys: keys, andSelectedKey: settings.defaults.string(forKey: "FontSize") ?? "") controller.title = NSLocalizedString("SettingsViewController.Font_Size", comment: "Font Size") controller.completionHandler = { value in settings.defaults.setValue(value, forKey: "FontSize") } navigationController?.pushViewController(controller, animated: true) case (0, 4): let selectedKey = settings.defaults.integer(forKey: "HistoryLimit") let keys = [ NSLocalizedString("SettingsViewController.HistoryLimit.3days", comment: "3 days"), NSLocalizedString("SettingsViewController.HistoryLimit.1week", comment: "1 week"), NSLocalizedString("SettingsViewController.HistoryLimit.2weeks", comment: "2 weeks"), NSLocalizedString("SettingsViewController.HistoryLimit.1month", comment: "1 month"), NSLocalizedString("SettingsViewController.HistoryLimit.3months", comment: "3 months"), NSLocalizedString("SettingsViewController.HistoryLimit.6months", comment: "6 months"), NSLocalizedString("SettingsViewController.HistoryLimit.1year", comment: "1 year"), NSLocalizedString("SettingsViewController.HistoryLimit.Forever", comment: "Forever") ] let controller = GSSingleSelectionTableViewController(keys: keys, andSelectedKey: historyLimitString(from: selectedKey)) controller.title = NSLocalizedString("SettingsViewController.HistoryLimit", comment: "HistoryLimit") controller.completionHandler = { [weak self] value in guard let strongSelf = self else { return } settings.defaults.setValue(strongSelf.parseHistoryLimitString(value), forKey: "HistoryLimit") } navigationController?.pushViewController(controller, animated: true) case (0, 0): present(LoginViewController(), animated: true, completion: nil) case (0, 10): URLCache.shared.removeAllCachedResponses() clearWebKitCache() let prettyPrintedCacheSize = Double(totalCacheSize() / (102 * 1024)) / 10.0 imageCacheCell.detailTextLabel?.text = String(format: "%.1f MiB", prettyPrintedCacheSize) case (0, 11): navigationController?.pushViewController(AdvancedSettingsViewController(), animated: true) case (1, 0): navigationController?.pushViewController(CloudKitViewController(), animated: true) case (2, 2): #if DEBUG pushLogViewer() #else let safariViewController = SFSafariViewController(url: URL(string: "https://ainopara.github.io/stage1st-reader-EULA.html")!) self.present(safariViewController, animated: true, completion: nil) #endif case (2, 3): navigationController?.pushViewController(acknowledgementListViewController(), animated: true) default: break } } override func didReceivePaletteChangeNotification(_ notification: Notification?) { let colorManager = AppEnvironment.current.colorManager displayImageSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") removeTailsSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") precacheSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") forcePortraitSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") nightModeSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") matchSystemDarkModeSwitch.onTintColor = colorManager.colorForKey("appearance.switch.tint") navigationController?.navigationBar.barStyle = colorManager.isDarkTheme() ? .black : .default navigationController?.navigationBar.barTintColor = colorManager.colorForKey("appearance.navigationbar.bartint") navigationController?.navigationBar.tintColor = colorManager.colorForKey("appearance.navigationbar.tint") navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: colorManager.colorForKey("appearance.navigationbar.title"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17.0) ] } } extension SettingsViewController { func applicationVersion() -> String { guard let shortVersionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString"), let versionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") else { return "?" } return "\(shortVersionString) (\(versionString))" } } extension SettingsViewController { @objc func pushLogViewer() { let logViewController = InMemoryLogViewController() navigationController?.pushViewController(logViewController, animated: true) } @objc func acknowledgementListViewController() -> AcknowListViewController { let acknowledgmentPlistFilePath = Bundle.main.path(forResource: "Pods-Stage1st-acknowledgements", ofType: "plist") return AcknowListViewController(acknowledgementsPlistPath: acknowledgmentPlistFilePath) } @objc func clearWebKitCache() { let websiteDataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: Date.distantPast) { S1LogInfo("WebKit disk cache cleaned.") AppEnvironment.current.settings.previousWebKitCacheCleaningDate.value = Date() } } @objc func totalCacheSize() -> UInt { var totalCacheSize = UInt(URLCache.shared.currentDiskUsage) if let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first, let libraryFolder = try? Folder(path: libraryURL.relativePath), let webKitCacheFolder = try? libraryFolder.subfolder(named: "Caches").subfolder(named: "WebKit") { for file in webKitCacheFolder.files.recursive { S1LogVerbose("\(file.name)") if let fileAttributes = try? FileManager.default.attributesOfItem(atPath: file.path), let fileSize = fileAttributes[FileAttributeKey.size] as? UInt64 { totalCacheSize += UInt(fileSize) } } } return totalCacheSize } @objc func setupObservation() { AppEnvironment.current.settings.currentUsername .map { currentUserName in return currentUserName ?? NSLocalizedString("SettingsViewController.Not_Login_State_Mark", comment: "") } .assign(to: \.text, on: usernameDetailLabel) .store(in: &bag) AppEnvironment.current.settings.manualControlInterfaceStyle .map { !$0 } .assign(to: \.isOn, on: matchSystemDarkModeSwitch) .store(in: &bag) AppEnvironment.current.settings.nightMode .assign(to: \.isOn, on: nightModeSwitch) .store(in: &bag) displayImageSwitch.publisher(for: .valueChanged) .map(\.isOn) .subscribe(AppEnvironment.current.settings.displayImage) .store(in: &bag) removeTailsSwitch.publisher(for: .valueChanged) .map(\.isOn) .subscribe(AppEnvironment.current.settings.removeTails) .store(in: &bag) precacheSwitch.publisher(for: .valueChanged) .map(\.isOn) .subscribe(AppEnvironment.current.settings.precacheNextPage) .store(in: &bag) nightModeSwitch.publisher(for: .valueChanged) .map(\.isOn) .subscribe(AppEnvironment.current.settings.nightMode) .store(in: &bag) forcePortraitSwitch.publisher(for: .valueChanged) .map(\.isOn) .subscribe(AppEnvironment.current.settings.forcePortraitForPhone) .store(in: &bag) matchSystemDarkModeSwitch.publisher(for: .valueChanged) .map(\.isOn) .map { !$0 } .subscribe(AppEnvironment.current.settings.manualControlInterfaceStyle) .store(in: &bag) NotificationCenter.default.reactive .notifications(forName: .YapDatabaseCloudKitSuspendCountChanged) .take(during: self.reactive.lifetime) .signal.observeValues { [weak self] (_) in self?.updateCloudKitStatus( state: AppEnvironment.current.cloudkitManager.state.value, enableSync: AppEnvironment.current.settings.enableCloudKitSync.value ) } NotificationCenter.default.reactive .notifications(forName: .YapDatabaseCloudKitInFlightChangeSetChanged) .take(during: self.reactive.lifetime) .signal.observeValues { [weak self] (_) in self?.updateCloudKitStatus( state: AppEnvironment.current.cloudkitManager.state.value, enableSync: AppEnvironment.current.settings.enableCloudKitSync.value ) } AppEnvironment.current.cloudkitManager.state .combineLatest(AppEnvironment.current.settings.enableCloudKitSync) .sink { [weak self] (args) in let (state, enableSync) = args self?.updateCloudKitStatus(state: state, enableSync: enableSync) } .store(in: &bag) } func updateCloudKitStatus(state: CloudKitManager.State, enableSync: Bool) { S1LogDebug("Observed CloudKit manager state changed.") DispatchQueue.main.async { guard enableSync else { self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Off", comment: "Off") return } switch state { case .waitingSetupTriggered: self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Off", comment: "Off") // self.iCloudSyncCell.detailTextLabel?.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Init", comment: "Init") case .migrating, .identifyUser, .createZone, .createZoneSubscription: self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Setup", comment: "Setup") case .fetchRecordChanges: self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Fetch", comment: "Fetch") case .readyForUpload: let suspendCount = AppEnvironment.current.databaseManager.cloudKitExtension.suspendCount let inFlightCount = AppEnvironment.current.databaseManager.cloudKitExtension.numberOfInFlightChangeSets let queuedCount = AppEnvironment.current.databaseManager.cloudKitExtension.numberOfQueuedChangeSets if suspendCount == 0 && inFlightCount == 0 && queuedCount == 0 { self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Ready", comment: "Ready") } else { self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Upload", comment: "Upload") + "(\(inFlightCount) - \(queuedCount))" } case .createZoneError, .createZoneSubscriptionError, .fetchRecordChangesError, .uploadError, .networkError: let suspendCount = AppEnvironment.current.databaseManager.cloudKitExtension.suspendCount self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Recover", comment: "Recover") + "(\(suspendCount))" case .halt: self.iCloudSyncDetailLabel.text = NSLocalizedString("SettingsViewController.CloudKit.Status.Halt", comment: "Halt") } } } } private extension SettingsViewController { func parseHistoryLimitString(_ string: String) -> Int { switch string { case NSLocalizedString("SettingsViewController.HistoryLimit.3days", comment: ""): return 259200 case NSLocalizedString("SettingsViewController.HistoryLimit.1week", comment: ""): return 604800 case NSLocalizedString("SettingsViewController.HistoryLimit.2weeks", comment: ""): return 1209600 case NSLocalizedString("SettingsViewController.HistoryLimit.1month", comment: ""): return 2592000 case NSLocalizedString("SettingsViewController.HistoryLimit.3months", comment: ""): return 7884000 case NSLocalizedString("SettingsViewController.HistoryLimit.6months", comment: ""): return 15768000 case NSLocalizedString("SettingsViewController.HistoryLimit.1year", comment: ""): return 31536000 default: return -1 } } func historyLimitString(from value: Int) -> String { switch value { case 259200: return NSLocalizedString("SettingsViewController.HistoryLimit.3days", comment: "") case 604800: return NSLocalizedString("SettingsViewController.HistoryLimit.1week", comment: "") case 1209600: return NSLocalizedString("SettingsViewController.HistoryLimit.2weeks", comment: "") case 2592000: return NSLocalizedString("SettingsViewController.HistoryLimit.1month", comment: "") case 7884000: return NSLocalizedString("SettingsViewController.HistoryLimit.3months", comment: "") case 15768000: return NSLocalizedString("SettingsViewController.HistoryLimit.6months", comment: "") case 31536000: return NSLocalizedString("SettingsViewController.HistoryLimit.1year", comment: "") default: return NSLocalizedString("SettingsViewController.HistoryLimit.Forever", comment: "") } } }
bsd-3-clause
b0b3cc0f31eb6e10fddeff8cdadeb5fe
45.813107
149
0.672526
5.345621
false
false
false
false
zszone/QRCode
QRCode/QRCode/Classes/Detector/DetectorViewController.swift
1
3058
// // DetectorViewController.swift // QRCode // // Created by zs on 16/6/20. // Copyright © 2016年 zs. All rights reserved. // import UIKit class DetectorViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var resultLabel: UILabel! // { // didSet{ // // // 1.获取当前显示的图片 // let currentImage = imageView.image! // // // 2.将UIImage转成CIImage // let ciImage = CIImage(image: currentImage)! // // // 3.创建探测器 // let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) // // // 4.弹出ciImage中所有的二维码 // let resultArray = detector.featuresInImage(ciImage) // // // 5.遍历数据,拿到所有的二维码 // for feature in resultArray { // let qrCodeFeature = feature as! CIQRCodeFeature // resultLabel!.text = qrCodeFeature.messageString // // } // // } // //} override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { //1.获取当前显示的图片 let currentImage = imageView.image! //2.将UIImage转换成CIImage let ciImage = CIImage(image: currentImage)! //3.创建探测器 let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) //4.弹出ciImage中所有的二维码 let resultArray = detector.featuresInImage(ciImage) //5.遍历数据,拿到所有的二维码 for feature in resultArray { let qrCodeFeature = feature as! CIQRCodeFeature resultLabel!.text = qrCodeFeature.messageString } } } extension DetectorViewController { @IBAction func photoPicker() { //1.判断照片源是否可用 if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { return } //2.创建图片选择控制器 let ipc = UIImagePickerController() //3.设置照片来源 ipc.sourceType = .PhotoLibrary //4.设置代理(在代理方法中拿到用户选中的照片) ipc.delegate = self //5.弹出控制器 presentViewController(ipc, animated: true, completion: nil) } } extension DetectorViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { //获取选中的图片 let image = info[UIImagePickerControllerOriginalImage] as! UIImage //将图片显示在imageView中 imageView.image = image //退出控制器 picker.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
b835085b54c760bcdfca7821ff42aa4b
25.605769
123
0.577521
4.812174
false
false
false
false
giapnh/TadiSDK
TadiSDK/Classes/Controllers/TDTabbarController.swift
1
1251
// // TDTabbarViewController.swift // TadiSDK // // Created by GiapNH on 1/9/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class TDTabbarController: UITabBarController { /// /// Tabbar item color (normal state) /// @IBInspectable var itemNormalColor: UIColor = UIColor.lightGray { didSet { UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: itemNormalColor], for:UIControlState()); let items = tabBar.items! ; for item in items { item.image = item.image!.imageWithColor(tintColor: itemNormalColor).withRenderingMode(UIImageRenderingMode.alwaysOriginal); } } } /// /// Tabbar item color (selected state) /// @IBInspectable var itemSelectedColor: UIColor = UIColor.white { didSet { UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: itemSelectedColor], for:UIControlState.selected); let items = tabBar.items! ; for item in items { item.selectedImage = item.image?.imageWithColor(tintColor: itemSelectedColor).withRenderingMode(.alwaysOriginal) } } } }
mit
756ed53f37dc0fb3ee90b0ad3093518b
31.894737
143
0.648
5.252101
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/ResourceGroupsTaggingAPI/ResourceGroupsTaggingAPI_Paginator.swift
1
12482
//===----------------------------------------------------------------------===// // // 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 SotoCore // MARK: Paginators extension ResourceGroupsTaggingAPI { /// Returns a table that shows counts of resources that are noncompliant with their tag policies. For more information on tag policies, see Tag Policies in the AWS Organizations User Guide. You can call this operation only from the organization's master account and from the us-east-1 Region. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getComplianceSummaryPaginator<Result>( _ input: GetComplianceSummaryInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetComplianceSummaryOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getComplianceSummary, tokenKey: \GetComplianceSummaryOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getComplianceSummaryPaginator( _ input: GetComplianceSummaryInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetComplianceSummaryOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getComplianceSummary, tokenKey: \GetComplianceSummaryOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Returns all the tagged or previously tagged resources that are located in the specified Region for the AWS account. Depending on what information you want returned, you can also specify the following: Filters that specify what tags and resource types you want returned. The response includes all tags that are associated with the requested resources. Information about compliance with the account's effective tag policy. For more information on tag policies, see Tag Policies in the AWS Organizations User Guide. You can check the PaginationToken response parameter to determine if a query is complete. Queries occasionally return fewer results on a page than allowed. The PaginationToken response parameter value is null only when there are no more results to display. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getResourcesPaginator<Result>( _ input: GetResourcesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetResourcesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getResources, tokenKey: \GetResourcesOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getResourcesPaginator( _ input: GetResourcesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetResourcesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getResources, tokenKey: \GetResourcesOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Returns all tag keys in the specified Region for the AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getTagKeysPaginator<Result>( _ input: GetTagKeysInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetTagKeysOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getTagKeys, tokenKey: \GetTagKeysOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getTagKeysPaginator( _ input: GetTagKeysInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetTagKeysOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getTagKeys, tokenKey: \GetTagKeysOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Returns all tag values for the specified key in the specified Region for the AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getTagValuesPaginator<Result>( _ input: GetTagValuesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetTagValuesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getTagValues, tokenKey: \GetTagValuesOutput.paginationToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getTagValuesPaginator( _ input: GetTagValuesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetTagValuesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getTagValues, tokenKey: \GetTagValuesOutput.paginationToken, on: eventLoop, onPage: onPage ) } } extension ResourceGroupsTaggingAPI.GetComplianceSummaryInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ResourceGroupsTaggingAPI.GetComplianceSummaryInput { return .init( groupBy: self.groupBy, maxResults: self.maxResults, paginationToken: token, regionFilters: self.regionFilters, resourceTypeFilters: self.resourceTypeFilters, tagKeyFilters: self.tagKeyFilters, targetIdFilters: self.targetIdFilters ) } } extension ResourceGroupsTaggingAPI.GetResourcesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ResourceGroupsTaggingAPI.GetResourcesInput { return .init( excludeCompliantResources: self.excludeCompliantResources, includeComplianceDetails: self.includeComplianceDetails, paginationToken: token, resourcesPerPage: self.resourcesPerPage, resourceTypeFilters: self.resourceTypeFilters, tagFilters: self.tagFilters, tagsPerPage: self.tagsPerPage ) } } extension ResourceGroupsTaggingAPI.GetTagKeysInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ResourceGroupsTaggingAPI.GetTagKeysInput { return .init( paginationToken: token ) } } extension ResourceGroupsTaggingAPI.GetTagValuesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ResourceGroupsTaggingAPI.GetTagValuesInput { return .init( key: self.key, paginationToken: token ) } }
apache-2.0
b82af5897ca022c498ce4d88de01690f
45.22963
787
0.655985
5.071922
false
false
false
false
xwu/swift
stdlib/public/core/UnicodeScalar.swift
1
16540
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Unicode.Scalar Type //===----------------------------------------------------------------------===// extension Unicode { /// A Unicode scalar value. /// /// The `Unicode.Scalar` type, representing a single Unicode scalar value, is /// the element type of a string's `unicodeScalars` collection. /// /// You can create a `Unicode.Scalar` instance by using a string literal that /// contains a single character representing exactly one Unicode scalar value. /// /// let letterK: Unicode.Scalar = "K" /// let kim: Unicode.Scalar = "김" /// print(letterK, kim) /// // Prints "K 김" /// /// You can also create Unicode scalar values directly from their numeric /// representation. /// /// let airplane = Unicode.Scalar(9992)! /// print(airplane) /// // Prints "✈︎" @frozen public struct Scalar: Sendable { @usableFromInline internal var _value: UInt32 @inlinable internal init(_value: UInt32) { self._value = _value } } } extension Unicode.Scalar : _ExpressibleByBuiltinUnicodeScalarLiteral, ExpressibleByUnicodeScalarLiteral { /// A numeric representation of the Unicode scalar. @inlinable public var value: UInt32 { return _value } @_transparent public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self._value = UInt32(value) } /// Creates a Unicode scalar with the specified value. /// /// Do not call this initializer directly. It may be used by the compiler /// when you use a string literal to initialize a `Unicode.Scalar` instance. /// /// let letterK: Unicode.Scalar = "K" /// print(letterK) /// // Prints "K" /// /// In this example, the assignment to the `letterK` constant is handled by /// this initializer behind the scenes. @_transparent public init(unicodeScalarLiteral value: Unicode.Scalar) { self = value } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of an emoji character: /// /// let codepoint: UInt32 = 127881 /// let emoji = Unicode.Scalar(codepoint) /// print(emoji!) /// // Prints "🎉" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value---that is, /// if `v` is in the range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is /// an invalid Unicode scalar value, the result is `nil`. @inlinable public init?(_ v: UInt32) { // Unicode 6.3.0: // // D9. Unicode codespace: A range of integers from 0 to 10FFFF. // // D76. Unicode scalar value: Any Unicode code point except // high-surrogate and low-surrogate code points. // // * As a result of this definition, the set of Unicode scalar values // consists of the ranges 0 to D7FF and E000 to 10FFFF, inclusive. if (v < 0xD800 || v > 0xDFFF) && v <= 0x10FFFF { self._value = v return } // Return nil in case of an invalid unicode scalar value. return nil } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"밥"`, the Korean word for rice: /// /// let codepoint: UInt16 = 48165 /// let bap = Unicode.Scalar(codepoint) /// print(bap!) /// // Prints "밥" /// /// In case of an invalid input value, the result is `nil`. /// /// let codepoint: UInt16 = extValue // This might be an invalid value /// if let bap = Unicode.Scalar(codepoint) { /// print(bap) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value, in the /// range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is an invalid /// unicode scalar value, the result is `nil`. @inlinable public init?(_ v: UInt16) { self.init(UInt32(v)) } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"7"`: /// /// let codepoint: UInt8 = 55 /// let seven = Unicode.Scalar(codepoint) /// print(seven) /// // Prints "7" /// /// - Parameter v: The code point to use for the scalar. @inlinable public init(_ v: UInt8) { self._value = UInt32(v) } /// Creates a duplicate of the given Unicode scalar. @inlinable public init(_ v: Unicode.Scalar) { // This constructor allows one to provide necessary type context to // disambiguate between function overloads on 'String' and 'Unicode.Scalar'. self = v } /// Returns a string representation of the Unicode scalar. /// /// Scalar values representing characters that are normally unprintable or /// that otherwise require escaping are escaped with a backslash. /// /// let tab = Unicode.Scalar(9)! /// print(tab) /// // Prints " " /// print(tab.escaped(asASCII: false)) /// // Prints "\t" /// /// When the `forceASCII` parameter is `true`, a `Unicode.Scalar` instance /// with a value greater than 127 is represented using an escaped numeric /// value; otherwise, non-ASCII characters are represented using their /// typical string value. /// /// let bap = Unicode.Scalar(48165)! /// print(bap.escaped(asASCII: false)) /// // Prints "밥" /// print(bap.escaped(asASCII: true)) /// // Prints "\u{BC25}" /// /// - Parameter forceASCII: Pass `true` if you need the result to use only /// ASCII characters; otherwise, pass `false`. /// - Returns: A string representation of the scalar. public func escaped(asASCII forceASCII: Bool) -> String { func lowNibbleAsHex(_ v: UInt32) -> String { let nibble = v & 15 if nibble < 10 { return String(Unicode.Scalar(nibble+48)!) // 48 = '0' } else { return String(Unicode.Scalar(nibble-10+65)!) // 65 = 'A' } } if self == "\\" { return "\\\\" } else if self == "\'" { return "\\\'" } else if self == "\"" { return "\\\"" } else if _isPrintableASCII { return String(self) } else if self == "\0" { return "\\0" } else if self == "\n" { return "\\n" } else if self == "\r" { return "\\r" } else if self == "\t" { return "\\t" } else if UInt32(self) < 128 { return "\\u{" + lowNibbleAsHex(UInt32(self) >> 4) + lowNibbleAsHex(UInt32(self)) + "}" } else if !forceASCII { return String(self) } else if UInt32(self) <= 0xFFFF { var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } else { // FIXME: Type checker performance prohibits this from being a // single chained "+". var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 28) result += lowNibbleAsHex(UInt32(self) >> 24) result += lowNibbleAsHex(UInt32(self) >> 20) result += lowNibbleAsHex(UInt32(self) >> 16) result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } } /// A Boolean value indicating whether the Unicode scalar is an ASCII /// character. /// /// ASCII characters have a scalar value between 0 and 127, inclusive. For /// example: /// /// let canyon = "Cañón" /// for scalar in canyon.unicodeScalars { /// print(scalar, scalar.isASCII, scalar.value) /// } /// // Prints "C true 67" /// // Prints "a true 97" /// // Prints "ñ false 241" /// // Prints "ó false 243" /// // Prints "n true 110" @inlinable public var isASCII: Bool { return value <= 127 } // FIXME: Unicode makes this interesting. internal var _isPrintableASCII: Bool { return (self >= Unicode.Scalar(0o040) && self <= Unicode.Scalar(0o176)) } } extension Unicode.Scalar: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the Unicode scalar. @inlinable public var description: String { return String(self) } /// An escaped textual representation of the Unicode scalar, suitable for /// debugging. public var debugDescription: String { return "\"\(escaped(asASCII: true))\"" } } extension Unicode.Scalar: LosslessStringConvertible { @inlinable public init?(_ description: String) { let scalars = description.unicodeScalars guard let v = scalars.first, scalars.count == 1 else { return nil } self = v } } extension Unicode.Scalar: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.value) } } extension Unicode.Scalar { /// Creates a Unicode scalar with the specified numeric value. /// /// - Parameter v: The Unicode code point to use for the scalar. `v` must be /// a valid Unicode scalar value, in the ranges `0...0xD7FF` or /// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is /// returned. /// /// For example, the following code sample creates a `Unicode.Scalar` instance /// with a value of an emoji character: /// /// let codepoint = 127881 /// let emoji = Unicode.Scalar(codepoint)! /// print(emoji) /// // Prints "🎉" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value. /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } @inlinable public init?(_ v: Int) { if let exact = UInt32(exactly: v) { self.init(exact) } else { return nil } } } extension UInt8 { /// Construct with value `v.value`. /// /// - Precondition: `v.value` can be represented as ASCII (0..<128). @inlinable public init(ascii v: Unicode.Scalar) { _precondition(v.value < 128, "Code point value does not fit into ASCII") self = UInt8(v.value) } } extension UInt32 { /// Construct with value `v.value`. @inlinable public init(_ v: Unicode.Scalar) { self = v.value } } extension UInt64 { /// Construct with value `v.value`. @inlinable public init(_ v: Unicode.Scalar) { self = UInt64(v.value) } } extension Unicode.Scalar: Equatable { @inlinable public static func == (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value == rhs.value } } extension Unicode.Scalar: Comparable { @inlinable public static func < (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value < rhs.value } } extension Unicode.Scalar { @frozen public struct UTF16View: Sendable { @usableFromInline internal var value: Unicode.Scalar @inlinable internal init(value: Unicode.Scalar) { self.value = value } } @inlinable public var utf16: UTF16View { return UTF16View(value: self) } } extension Unicode.Scalar.UTF16View: RandomAccessCollection { public typealias Indices = Range<Int> /// The position of the first code unit. @inlinable public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the collection is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { return 0 + UTF16.width(value) } /// Accesses the code unit at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. @inlinable public subscript(position: Int) -> UTF16.CodeUnit { if position == 1 { return UTF16.trailSurrogate(value) } if endIndex == 1 { return UTF16.CodeUnit(value.value) } return UTF16.leadSurrogate(value) } } extension Unicode.Scalar { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @frozen public struct UTF8View: Sendable { @usableFromInline internal var value: Unicode.Scalar @inlinable internal init(value: Unicode.Scalar) { self.value = value } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @inlinable public var utf8: UTF8View { return UTF8View(value: self) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Unicode.Scalar.UTF8View: RandomAccessCollection { public typealias Indices = Range<Int> /// The position of the first code unit. @inlinable public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the collection is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { return 0 + UTF8.width(value) } /// Accesses the code unit at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. @inlinable public subscript(position: Int) -> UTF8.CodeUnit { _precondition(position >= startIndex && position < endIndex, "Unicode.Scalar.UTF8View index is out of bounds") return value.withUTF8CodeUnits { $0[position] } } } extension Unicode.Scalar { internal static var _replacementCharacter: Unicode.Scalar { return Unicode.Scalar(_value: UTF32._replacementCodeUnit) } } extension Unicode.Scalar { /// Creates an instance of the NUL scalar value. @available(*, unavailable, message: "use 'Unicode.Scalar(0)'") public init() { Builtin.unreachable() } } // Access the underlying code units extension Unicode.Scalar { // Access the scalar as encoded in UTF-16 internal func withUTF16CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt16>) throws -> Result ) rethrows -> Result { var codeUnits: (UInt16, UInt16) = (self.utf16[0], 0) let utf16Count = self.utf16.count if utf16Count > 1 { _internalInvariant(utf16Count == 2) codeUnits.1 = self.utf16[1] } return try Swift.withUnsafePointer(to: &codeUnits) { return try $0.withMemoryRebound(to: UInt16.self, capacity: 2) { return try body(UnsafeBufferPointer(start: $0, count: utf16Count)) } } } // Access the scalar as encoded in UTF-8 @inlinable internal func withUTF8CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { let encodedScalar = UTF8.encode(self)! var (codeUnits, utf8Count) = encodedScalar._bytes // The first code unit is in the least significant byte of codeUnits. codeUnits = codeUnits.littleEndian return try Swift.withUnsafePointer(to: &codeUnits) { return try $0.withMemoryRebound(to: UInt8.self, capacity: 4) { return try body(UnsafeBufferPointer(start: $0, count: utf8Count)) } } } }
apache-2.0
74f3d2ba1197827797afb49e976e3177
29.928839
81
0.622487
3.926771
false
false
false
false
xoyip/AzureStorageApiClient
Pod/Classes/AzureStorage/Queue/Request/PutMessageRequestBase.swift
1
1895
// // PutMessagesRequestBase.swift // AzureStorageApiClient // // Created by Hiromasa Ohno on 2015/08/06. // Copyright (c) 2015 Hiromasa Ohno. All rights reserved. // import Foundation public extension AzureQueue { public class PutMessagesRequestBase: Request { public var method : String { get { return "" } } let queue : String var message : String public typealias Response = Bool public init(queue : String, message: String) { self.queue = queue self.message = message } public func path() -> String { var base = basePath() let params = parameters() if params.count == 0 { return base } return base + "?" + join("&", params) } public func additionalHeaders() -> [String:String] { return RequestUtility.headerForXmlBody(body()) } public func body() -> NSData? { let data : NSData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let encoded = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) let bodyString = "<?xml version=\"1.0\"?>\n<QueueMessage>\n <MessageText>\(encoded)\n</MessageText>\n</QueueMessage>\n" return bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } public func convertResponseObject(object: AnyObject?) -> Response? { return true } public func responseTypes() -> Set<String>? { return [""] } internal func parameters() -> [String] { return [] } internal func basePath() -> String { return "" } } }
mit
84b2a9f7c3c524b0b94b650db942023b
30.583333
132
0.561478
5.249307
false
false
false
false
danqing/2048
m2048UITests/m2048UITests.swift
1
4389
// // m2048UITests.swift // m2048UITests // // Created by Xue Qin on 1/31/18. // Copyright © 2018 Danqing. All rights reserved. // import XCTest class m2048UITests: XCTestCase { let app = XCUIApplication() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSettings() { app.buttons["Settings"].tap() let tablesQuery = app.tables // Game Type tablesQuery.staticTexts["Game Type"].tap() tablesQuery.staticTexts["Powers of 3"].tap() tablesQuery.staticTexts["Fibonacci"].tap() tablesQuery.staticTexts["Powers of 2"].tap() app.navigationBars["Game Type"].buttons["Settings"].tap() // Board Size tablesQuery.staticTexts["Board Size"].tap() tablesQuery.staticTexts["3 x 3"].tap() tablesQuery.staticTexts["5 x 5"].tap() tablesQuery.staticTexts["4 x 4"].tap() app.navigationBars["Board Size"].buttons["Back"].tap() // About tablesQuery.staticTexts["About 2048"].tap() app.navigationBars["About 2048"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() } func testThemes() { let tablesQuery = app.tables // vibrant app.buttons["Settings"].tap() tablesQuery.staticTexts["Theme"].tap() tablesQuery.staticTexts["Vibrant"].tap() app.navigationBars["Theme"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() // joyful app.buttons["Settings"].tap() tablesQuery.staticTexts["Theme"].tap() tablesQuery.staticTexts["Joyful"].tap() app.navigationBars["Theme"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() // default app.buttons["Settings"].tap() tablesQuery.staticTexts["Theme"].tap() tablesQuery.staticTexts["Default"].tap() app.navigationBars["Theme"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() } func testPlayPowerOfTwo() { app.buttons["Settings"].tap() let tablesQuery = app.tables tablesQuery.staticTexts["Game Type"].tap() tablesQuery.staticTexts["Powers of 2"].tap() app.navigationBars["Game Type"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() app.swipeUp() app.swipeLeft() app.swipeDown() app.swipeRight() app.buttons["Restart"].tap() } func testPlayPowerOfThree() { app.buttons["Settings"].tap() let tablesQuery = app.tables tablesQuery.staticTexts["Game Type"].tap() tablesQuery.staticTexts["Powers of 3"].tap() app.navigationBars["Game Type"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() app.swipeUp() app.swipeLeft() app.swipeDown() app.swipeRight() app.buttons["Restart"].tap() } func testPlayFibonacci() { app.buttons["Settings"].tap() let tablesQuery = app.tables tablesQuery.staticTexts["Game Type"].tap() tablesQuery.staticTexts["Fibonacci"].tap() app.navigationBars["Game Type"].buttons["Settings"].tap() app.navigationBars["Settings"].buttons["Done"].tap() app.swipeUp() app.swipeLeft() app.swipeDown() app.swipeRight() app.buttons["Restart"].tap() } }
mit
c7b8320b9ab37b78fa805657459a834d
33
182
0.599179
4.803943
false
true
false
false
chauhan9909/AERecord
AERecord/AERecord.swift
2
41035
// // AERecord.swift // // Copyright (c) 2014 Marko Tadić <[email protected]> http://tadija.net // // 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 CoreData let kAERecordPrintLog = true // this will soon be updated to Swift 2.0 error handling. // MARK: - AERecord (facade for shared instance of AEStack) /** This class is facade for accessing shared instance of `AEStack` (private class which is all about the Core Data Stack). */ public class AERecord { // MARK: Properties /// Managed object context for current thread. public class var defaultContext: NSManagedObjectContext { return AEStack.sharedInstance.defaultContext } /// Managed object context for main thread. public class var mainContext: NSManagedObjectContext { return AEStack.sharedInstance.mainContext } /// Managed object context for background thread. public class var backgroundContext: NSManagedObjectContext { return AEStack.sharedInstance.backgroundContext } /// Persistent Store Coordinator for current stack. public class var persistentStoreCoordinator: NSPersistentStoreCoordinator? { return AEStack.sharedInstance.persistentStoreCoordinator } // MARK: Setup Stack /** Returns the final URL in Application Documents Directory for the store with given name. :param: name Filename for the store. */ public class func storeURLForName(name: String) -> NSURL { return AEStack.storeURLForName(name) } /** Returns merged model from the bundle for given class. :param: forClass Class inside bundle with data model. */ public class func modelFromBundle(#forClass: AnyClass) -> NSManagedObjectModel { return AEStack.modelFromBundle(forClass: forClass) } /** Loads Core Data Stack *(creates new if it doesn't already exist)* with given options **(all options are optional)**. - Default option for `managedObjectModel` is `NSManagedObjectModel.mergedModelFromBundles(nil)!`. - Default option for `storeType` is `NSSQLiteStoreType`. - Default option for `storeURL` is `bundleIdentifier + ".sqlite"` inside `applicationDocumentsDirectory`. :param: managedObjectModel Managed object model for Core Data Stack. :param: storeType Store type for Persistent Store creation. :param: configuration Configuration for Persistent Store creation. :param: storeURL URL for Persistent Store creation. :param: options Options for Persistent Store creation. :returns: Optional error if something went wrong. */ public class func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = AEStack.defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = AEStack.defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { return AEStack.sharedInstance.loadCoreDataStack(managedObjectModel: managedObjectModel, storeType: storeType, configuration: configuration, storeURL: storeURL, options: options) } /** Destroys Core Data Stack for given store URL *(stop notifications, reset contexts, remove persistent store and delete .sqlite file)*. **This action can't be undone.** :param: storeURL Store URL for stack to destroy. */ public class func destroyCoreDataStack(storeURL: NSURL = AEStack.defaultURL) { AEStack.sharedInstance.destroyCoreDataStack(storeURL: storeURL) } /** Deletes all records from all entities contained in the model. :param: context If not specified, `defaultContext` will be used. */ public class func truncateAllData(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.truncateAllData(context: context) } // MARK: Context Execute /** Executes given fetch request. :param: request Fetch request to execute. :param: context If not specified, `defaultContext` will be used. */ public class func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { return AEStack.sharedInstance.executeFetchRequest(request, context: context) } // MARK: Context Save /** Saves context *(without waiting - returns immediately)*. :param: context If not specified, `defaultContext` will be used. */ public class func saveContext(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContext(context: context) } /** Saves context with waiting *(returns when context is saved)*. :param: context If not specified, `defaultContext` will be used. */ public class func saveContextAndWait(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContextAndWait(context: context) } // MARK: Context Faulting Objects /** Turns objects into faults for given Array of `NSManagedObjectID`. :param: objectIDS Array of `NSManagedObjectID` objects to turn into fault. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ public class func refreshObjects(#objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshObjects(objectIDS: objectIDS, mergeChanges: mergeChanges, context: context) } /** Turns all registered objects into faults. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ public class func refreshAllRegisteredObjects(#mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshAllRegisteredObjects(mergeChanges: mergeChanges, context: context) } } // MARK: - CoreData Stack (AERecord heart:) private class AEStack { // MARK: Shared Instance class var sharedInstance: AEStack { struct Singleton { static let instance = AEStack() } return Singleton.instance } // MARK: Default settings class var bundleIdentifier: String { return NSBundle.mainBundle().bundleIdentifier! } class var defaultURL: NSURL { return storeURLForName(bundleIdentifier) } class var defaultModel: NSManagedObjectModel { return NSManagedObjectModel.mergedModelFromBundles(nil)! } // MARK: Properties var managedObjectModel: NSManagedObjectModel? var persistentStoreCoordinator: NSPersistentStoreCoordinator? var mainContext: NSManagedObjectContext! var backgroundContext: NSManagedObjectContext! var defaultContext: NSManagedObjectContext { if NSThread.isMainThread() { return mainContext } else { return backgroundContext } } // MARK: Setup Stack class func storeURLForName(name: String) -> NSURL { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeName = "\(name).sqlite" return applicationDocumentsDirectory.URLByAppendingPathComponent(storeName) } class func modelFromBundle(#forClass: AnyClass) -> NSManagedObjectModel { let bundle = NSBundle(forClass: forClass) return NSManagedObjectModel.mergedModelFromBundles([bundle])! } func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { self.managedObjectModel = managedObjectModel // setup main and background contexts mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) // create the coordinator and store persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) if let coordinator = persistentStoreCoordinator { var error: NSError? if coordinator.addPersistentStoreWithType(storeType, configuration: configuration, URL: storeURL, options: options, error: &error) == nil { var userInfoDictionary = [NSObject : AnyObject]() userInfoDictionary[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" userInfoDictionary[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." userInfoDictionary[NSUnderlyingErrorKey] = error error = NSError(domain: AEStack.bundleIdentifier, code: 1, userInfo: userInfoDictionary) if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error } else { // everything went ok mainContext.persistentStoreCoordinator = coordinator backgroundContext.persistentStoreCoordinator = coordinator startReceivingContextNotifications() return nil } } else { return NSError(domain: AEStack.bundleIdentifier, code: 2, userInfo: [NSLocalizedDescriptionKey : "Could not create NSPersistentStoreCoordinator from given NSManagedObjectModel."]) } } func destroyCoreDataStack(storeURL: NSURL = defaultURL) -> NSError? { // must load this core data stack first loadCoreDataStack(storeURL: storeURL) // because there is no persistentStoreCoordinator if destroyCoreDataStack is called before loadCoreDataStack // also if we're in other stack currently that persistentStoreCoordinator doesn't know about this storeURL stopReceivingContextNotifications() // stop receiving notifications for these contexts // reset contexts mainContext.reset() backgroundContext.reset() // finally, remove persistent store var error: NSError? if let coordinator = persistentStoreCoordinator { if let store = coordinator.persistentStoreForURL(storeURL) { if coordinator.removePersistentStore(store, error: &error) { NSFileManager.defaultManager().removeItemAtURL(storeURL, error: &error) } } } // reset coordinator and model persistentStoreCoordinator = nil managedObjectModel = nil if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error ?? nil } func truncateAllData(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext if let mom = managedObjectModel { for entity in mom.entities as! [NSEntityDescription] { if let entityType = NSClassFromString(entity.managedObjectClassName) as? NSManagedObject.Type { entityType.deleteAll(context: moc) } } } } deinit { stopReceivingContextNotifications() if kAERecordPrintLog { println("\(NSStringFromClass(self.dynamicType)) deinitialized - function: \(__FUNCTION__) | line: \(__LINE__)\n") } } // MARK: Context Execute func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { var fetchedObjects = [NSManagedObject]() let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if let result = moc.executeFetchRequest(request, error: &error) { if let managedObjects = result as? [NSManagedObject] { fetchedObjects = managedObjects } } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return fetchedObjects } // MARK: Context Save func saveContext(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlock { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } func saveContextAndWait(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } // MARK: Context Sync func startReceivingContextNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: mainContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: backgroundContext) } func stopReceivingContextNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func contextDidSave(notification: NSNotification) { if let context = notification.object as? NSManagedObjectContext { let contextToRefresh = context == mainContext ? backgroundContext : mainContext contextToRefresh.performBlock({ () -> Void in contextToRefresh.mergeChangesFromContextDidSaveNotification(notification) }) } } // MARK: Context Faulting Objects class func refreshObjects(#objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { for objectID in objectIDS { var error: NSError? context.performBlockAndWait({ () -> Void in if let object = context.existingObjectWithID(objectID, error: &error) { if !object.fault && error == nil { // turn managed object into fault context.refreshObject(object, mergeChanges: mergeChanges) } else { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } }) } } class func refreshAllRegisteredObjects(#mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { var registeredObjectIDS = [NSManagedObjectID]() for object in context.registeredObjects { if let managedObject = object as? NSManagedObject { registeredObjectIDS.append(managedObject.objectID) } } refreshObjects(objectIDS: registeredObjectIDS, mergeChanges: mergeChanges) } } // MARK: - NSManagedObject Extension /** This extension is all about **easy querying**. All queries are called as class functions on `NSManagedObject` (or it's custom subclass), and `defaultContext` is used if you don't specify any. */ public extension NSManagedObject { // MARK: General /** This property **must return correct entity name** because it's used all across other helpers to reference custom `NSManagedObject` subclass. You may override this property in your custom `NSManagedObject` subclass if needed (but it should work out of the box generally). */ class var entityName: String { var name = NSStringFromClass(self) name = name.componentsSeparatedByString(".").last return name } /// An `NSEntityDescription` object describes an entity in Core Data. class var entity: NSEntityDescription? { return NSEntityDescription.entityForName(entityName, inManagedObjectContext: AERecord.defaultContext) } /** Creates fetch request **(for any entity type)** for given predicate and sort descriptors *(which are optional)*. :param: predicate Predicate for fetch request. :param sortDescriptors Sort Descriptors for fetch request. :returns: The created fetch request. */ class func createFetchRequest(predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> NSFetchRequest { let request = NSFetchRequest(entityName: entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors return request } private static let defaultPredicateType: NSCompoundPredicateType = .AndPredicateType /** Creates predicate for given attributes and predicate type. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :returns: The created predicate. */ class func createPredicateForAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType) -> NSPredicate { var predicates = [NSPredicate]() for (attribute, value) in attributes { predicates.append(NSPredicate(format: "%K = %@", argumentArray: [attribute, value])) } let compoundPredicate = NSCompoundPredicate(type: predicateType, subpredicates: predicates) return compoundPredicate } // MARK: Creating /** Creates new instance of entity object. :param: context If not specified, `defaultContext` will be used. :returns: New instance of `Self`. */ class func create(context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context) let object = self(entity: entityDescription!, insertIntoManagedObjectContext: context) return object } /** Creates new instance of entity object and set it with given attributes. :param: attributes Dictionary of attribute names and values. :param: context If not specified, `defaultContext` will be used. :returns: New instance of `Self` with set attributes. */ class func createWithAttributes(attributes: [NSObject : AnyObject], context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let object = create(context: context) if attributes.count > 0 { object.setValuesForKeysWithDictionary(attributes) } return object } /** Finds the first record for given attribute and value or creates new if the it does not exist. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. :returns: Instance of managed object. */ class func firstOrCreateWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { return firstOrCreateWithAttributes([attribute : value], context: context) } /** Finds the first record for given attributes or creates new if the it does not exist. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Instance of managed object. */ class func firstOrCreateWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) let request = createFetchRequest(predicate: predicate) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? createWithAttributes(attributes, context: context) } // MARK: Finding First /** Finds the first record. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func first(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } /** Finds the first record for given predicate. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } /** Finds the first record for given attribute and value. :param: attribute Attribute name. :param: value Attribute value. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return firstWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds the first record for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return firstWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds the first record ordered by given attribute. :param: name Attribute name. :param: ascending A Boolean value. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstOrderedByAttribute(name: String, ascending: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let sortDescriptors = [NSSortDescriptor(key: name, ascending: ascending)] return first(sortDescriptors: sortDescriptors, context: context) } // MARK: Finding All /** Finds all records. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func all(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } /** Finds all records for given predicate. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } /** Finds all records for given attribute and value. :param: attribute Attribute name. :param: value Attribute value. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return allWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return allWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } // MARK: Deleting /** Deletes instance of entity object. :param: context If not specified, `defaultContext` will be used. */ func delete(context: NSManagedObjectContext = AERecord.defaultContext) { context.deleteObject(self) } /** Deletes all records. :param: context If not specified, `defaultContext` will be used. */ class func deleteAll(context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.all(context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given predicate. :param: predicate Predicate. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithPredicate(predicate: NSPredicate, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithPredicate(predicate, context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given attribute name and value. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttribute(attribute, value: value, context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttributes(attributes, predicateType: predicateType, context: context) { for object in objects { context.deleteObject(object) } } } // MARK: Count /** Counts all records. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func count(context: NSManagedObjectContext = AERecord.defaultContext) -> Int { return countWithPredicate(context: context) } /** Counts all records for given predicate. :param: predicate Predicate. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithPredicate(predicate: NSPredicate? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let request = createFetchRequest(predicate: predicate) request.includesSubentities = false var error: NSError? let count = context.countForFetchRequest(request, error: &error) if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return count } /** Counts all records for given attribute name and value. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { return countWithAttributes([attribute : value], context: context) } /** Counts all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return countWithPredicate(predicate: predicate, context: context) } // MARK: Distinct /** Gets distinct values for given attribute and predicate. :param: attribute Attribute name. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional Array of `AnyObject`. */ class func distinctValuesForAttribute(attribute: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [AnyObject]? { var distinctValues = [AnyObject]() if let distinctRecords = distinctRecordsForAttributes([attribute], predicate: predicate, sortDescriptors: sortDescriptors, context: context) { for record in distinctRecords { if let value: AnyObject = record[attribute] { distinctValues.append(value) } } } return distinctValues.count > 0 ? distinctValues : nil } /** Gets distinct values for given attributes and predicate. :param: attributes Dictionary of attribute names and values. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional Array of `AnyObject`. */ class func distinctRecordsForAttributes(attributes: [String], predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [Dictionary<String, AnyObject>]? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) request.resultType = .DictionaryResultType request.propertiesToFetch = attributes request.returnsDistinctResults = true var distinctRecords: [Dictionary<String, AnyObject>]? var error: NSError? if let distinctResult = context.executeFetchRequest(request, error: &error) as? [Dictionary<String, AnyObject>] { distinctRecords = distinctResult } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return distinctRecords } // MARK: Auto Increment /** Gets next ID for given attribute name. Attribute must be of `Int` type. :param: attribute Attribute name. :param: context If not specified, `defaultContext` will be used. :returns: Auto incremented ID. */ class func autoIncrementedIntegerAttribute(attribute: String, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let sortDescriptor = NSSortDescriptor(key: attribute, ascending: false) if let object = self.first(sortDescriptors: [sortDescriptor], context: context) { if let max = object.valueForKey(attribute) as? Int { return max + 1 } else { return 0 } } else { return 0 } } // MARK: Turn Object Into Fault /** Turns object into fault. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ func refresh(mergeChanges: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) { AERecord.refreshObjects(objectIDS: [objectID], mergeChanges: mergeChanges, context: context) } // MARK: Batch Updating /** Updates data directly in persistent store **(iOS 8 and above)**. :param: predicate Predicate. :param: properties Properties to update. :param: resultType If not specified, `StatusOnlyResultType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Batch update result. */ class func batchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, resultType: NSBatchUpdateRequestResultType = .StatusOnlyResultType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSBatchUpdateResult? { // create request let request = NSBatchUpdateRequest(entityName: entityName) // set request parameters request.predicate = predicate request.propertiesToUpdate = properties request.resultType = resultType // execute request var batchResult: NSBatchUpdateResult? = nil context.performBlockAndWait { () -> Void in var error: NSError? if let result = context.executeRequest(request, error: &error) as? NSBatchUpdateResult { batchResult = result } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return batchResult } /** Updates data directly in persistent store **(iOS 8 and above)**. :param: predicate Predicate. :param: properties Properties to update. :param: context If not specified, `defaultContext` will be used. :returns: Count of updated objects. */ class func objectsCountForBatchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectsCountResultType, context: context) { if let count = result.result as? Int { return count } else { return 0 } } else { return 0 } } /** Updates data directly in persistent store **(iOS 8 and above)**. Objects are turned into faults after updating *(managed object context is refreshed)*. :param: predicate Predicate. :param: properties Properties to update. :param: context If not specified, `defaultContext` will be used. */ class func batchUpdateAndRefreshObjects(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectIDsResultType, context: context) { if let objectIDS = result.result as? [NSManagedObjectID] { AERecord.refreshObjects(objectIDS: objectIDS, mergeChanges: true, context: context) } } } }
mit
42962ff3245d235df353b8bbdcf25056
41.479296
265
0.652727
5.573757
false
false
false
false
WeirdMath/TimetableSDK
Sources/TimetableError.swift
1
2160
// // TimetableError.swift // TimetableSDK // // Created by Sergej Jaskiewicz on 24.11.2016. // // import SwiftyJSON /// Represents an error that can occure while querying the Timetable service. public enum TimetableError: Error { /// Returned when couldn't parse a JSON responce returned from Timetable or loaded from a `*.json` file. case incorrectJSONFormat(JSON, description: String) /// Returned when a networking error occures. case networkingError(Error) /// Returned when a `Timetable` object is deallocated prior to fetching. case timetableIsDeallocated /// Returned when attempting to fetch a next or previous week with the current week's /// `studentGroup` property not set. case unknownStudentGroup /// Returned when attempting to fetch a corresponding room for `Location`, but no room was found. case couldntFindRoomForLocation private static func incorrectJSONDescription<T>(for type: T.Type) -> String { return "Could not convert JSON to \(type)" } internal static func incorrectJSON<T>(_ json: JSON, whenConverting type: T.Type) -> TimetableError { return TimetableError.incorrectJSONFormat(json, description: incorrectJSONDescription(for: type)) } } extension TimetableError: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: TimetableError, rhs: TimetableError) -> Bool { switch (lhs, rhs) { case (incorrectJSONFormat(let json1, let description1), incorrectJSONFormat(let json2, let description2)): return json1 == json2 && description1 == description2 case (.networkingError, .networkingError): return true case (.timetableIsDeallocated, .timetableIsDeallocated): return true default: return false } } }
mit
f7f449966dfa7b1d723ff1b31cf2fb83
33.83871
114
0.663889
4.605544
false
false
false
false
liuwin7/meizi_app_ios
meinv/class/beauty/BeautyTableViewCell.swift
1
1366
// // BeautyTableViewCell.swift // meinv // // Created by tropsci on 16/3/14. // Copyright © 2016年 topsci. All rights reserved. // import UIKit protocol BeautyTableViewCellProtocol { func favorite(beauty: Beauty, completedBlock:(Bool) -> Void) ->Void } class BeautyTableViewCell: UITableViewCell { @IBOutlet weak var beautyImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! var favoriteDelegate: BeautyTableViewCellProtocol? var beautyModel: Beauty! { didSet { let url = NSURL(string: beautyModel.url) beautyImageView.sd_setImageWithURL(url!) self.titleLabel.text = beautyModel.name self.favoriteButton.selected = beautyModel.favorited self.setNeedsLayout() } } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .None self.titleLabel.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) } @IBAction func favoriteAction(sender: UIButton) { favoriteDelegate?.favorite(beautyModel, completedBlock: { (success) -> Void in if success { self.favoriteButton.selected = true self.setNeedsLayout() } }) } }
mit
68e51beaa25ca9e7ab3ef078e6ba0397
26.26
88
0.622891
4.683849
false
false
false
false
proversity-org/edx-app-ios
Source/ButtonStyle.swift
2
1888
// // ButtonStyle.swift // edX // // Created by Akiva Leffert on 6/3/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit public class ButtonStyle : NSObject { var textStyle : OEXTextStyle var backgroundColor : UIColor? var borderStyle : BorderStyle? var contentInsets : UIEdgeInsets var shadow: ShadowStyle? init(textStyle : OEXTextStyle, backgroundColor : UIColor?, borderStyle : BorderStyle? = nil, contentInsets : UIEdgeInsets? = nil, shadow: ShadowStyle? = nil) { self.textStyle = textStyle self.backgroundColor = backgroundColor self.borderStyle = borderStyle self.contentInsets = contentInsets ?? UIEdgeInsets.zero self.shadow = shadow } fileprivate func applyToButton(button : UIButton, withTitle text : String? = nil) { button.setAttributedTitle(textStyle.attributedString(withText: text), for: .normal) button.applyBorderStyle(style: borderStyle ?? BorderStyle.clearStyle()) // Use a background image instead of a backgroundColor so that it picks up a pressed state automatically button.setBackgroundImage(backgroundColor.map { UIImage.oex_image(with: $0) }, for: .normal) button.contentEdgeInsets = contentInsets if let shadowStyle = shadow { button.layer.shadowColor = shadowStyle.color.cgColor button.layer.shadowRadius = shadowStyle.size button.layer.shadowOpacity = Float(shadowStyle.opacity) button.layer.shadowOffset = CGSize(width: cos(CGFloat(shadowStyle.angle) / 180.0 * CGFloat(Double.pi/2)), height: sin(CGFloat(shadowStyle.angle) / 180.0 * CGFloat(Double.pi/2))) } } } extension UIButton { @objc func applyButtonStyle(style : ButtonStyle, withTitle text : String?) { style.applyToButton(button: self, withTitle: text) } }
apache-2.0
0857df6905de79cf8bb1fdaf1a029200
39.170213
189
0.693326
4.673267
false
false
false
false
dvor/Antidote
Antidote/LoginGenericCreateController.swift
1
5097
// 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 SnapKit private struct PrivateConstants { static let FieldsOffset = 20.0 static let VerticalOffset = 30.0 } class LoginGenericCreateController: LoginBaseController { fileprivate var containerView: IncompressibleView! fileprivate var containerViewTopConstraint: Constraint! var titleLabel: UILabel! var firstTextField: ExtendedTextField! var secondTextField: ExtendedTextField! var bottomButton: RoundedButton! override func loadView() { super.loadView() createGestureRecognizers() createContainerView() createTitleLabel() createExtendedTextFields() createGoButton() configureViews() installConstraints() } override func keyboardWillShowAnimated(keyboardFrame frame: CGRect) { if containerView.frame.isEmpty { return } let underFormHeight = containerView.frame.size.height - secondTextField.frame.maxY let offset = min(0.0, underFormHeight - frame.height) containerViewTopConstraint.update(offset: offset) view.layoutIfNeeded() } override func keyboardWillHideAnimated(keyboardFrame frame: CGRect) { containerViewTopConstraint.update(offset: 0.0) view.layoutIfNeeded() } func configureViews() { fatalError("override in subclass") } } extension LoginGenericCreateController { func tapOnView() { view.endEditing(true) } func bottomButtonPressed() { fatalError("override in subclass") } } extension LoginGenericCreateController: ExtendedTextFieldDelegate { func loginExtendedTextFieldReturnKeyPressed(_ field: ExtendedTextField) { if field == firstTextField { _ = secondTextField.becomeFirstResponder() } else if field == secondTextField { view.endEditing(true) bottomButtonPressed() } } } private extension LoginGenericCreateController { func createGestureRecognizers() { let tapGR = UITapGestureRecognizer(target: self, action: #selector(LoginCreateAccountController.tapOnView)) view.addGestureRecognizer(tapGR) } func createContainerView() { containerView = IncompressibleView() containerView.backgroundColor = .clear view.addSubview(containerView) } func createTitleLabel() { titleLabel = UILabel() titleLabel.textColor = theme.colorForType(.LoginButtonBackground) titleLabel.font = UIFont.antidoteFontWithSize(26.0, weight: .light) titleLabel.backgroundColor = .clear containerView.addSubview(titleLabel) } func createExtendedTextFields() { firstTextField = ExtendedTextField(theme: theme, type: .login) firstTextField.delegate = self firstTextField.returnKeyType = .next containerView.addSubview(firstTextField) secondTextField = ExtendedTextField(theme: theme, type: .login) secondTextField.delegate = self secondTextField.returnKeyType = .go containerView.addSubview(secondTextField) } func createGoButton() { bottomButton = RoundedButton(theme: theme, type: .login) bottomButton.addTarget(self, action: #selector(LoginCreateAccountController.bottomButtonPressed), for: .touchUpInside) containerView.addSubview(bottomButton) } func installConstraints() { containerView.customIntrinsicContentSize.width = CGFloat(Constants.MaxFormWidth) containerView.snp.makeConstraints { containerViewTopConstraint = $0.top.equalTo(view).constraint $0.centerX.equalTo(view) $0.width.lessThanOrEqualTo(Constants.MaxFormWidth) $0.width.lessThanOrEqualTo(view).offset(-2 * Constants.HorizontalOffset) $0.height.equalTo(view) } titleLabel.snp.makeConstraints { $0.top.equalTo(containerView).offset(PrivateConstants.VerticalOffset) $0.centerX.equalTo(containerView) } firstTextField.snp.makeConstraints { $0.top.equalTo(titleLabel.snp.bottom).offset(PrivateConstants.FieldsOffset) $0.leading.equalTo(containerView) $0.trailing.equalTo(containerView) } secondTextField.snp.makeConstraints { $0.leading.trailing.equalTo(firstTextField) if firstTextField.isHidden { $0.top.equalTo(titleLabel.snp.bottom).offset(PrivateConstants.FieldsOffset) } else { $0.top.equalTo(firstTextField.snp.bottom).offset(PrivateConstants.FieldsOffset) } } bottomButton.snp.makeConstraints { $0.top.equalTo(secondTextField.snp.bottom).offset(PrivateConstants.VerticalOffset) $0.leading.trailing.equalTo(firstTextField) } } }
mit
6bcfc2a23cb6ccebfc0baef58f511d8c
32.097403
126
0.678634
5.081755
false
false
false
false
anishathalye/skipchat
Contagged/SwiftAddressBook.swift
1
17237
//SwiftAddressBook - A strong-typed Swift Wrapper for ABAddressBook //Copyright (C) 2014 Socialbit GmbH // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see http://www.gnu.org/licenses/ . //If you would to like license this software for non-free commercial use, //please write us at [email protected] . import UIKit import AddressBook //MARK: global address book variable var swiftAddressBook : SwiftAddressBook? { get { if let instance = swiftAddressBookInstance { return instance } else { swiftAddressBookInstance = SwiftAddressBook(0) return swiftAddressBookInstance } } } //MARK: private address book store private var swiftAddressBookInstance : SwiftAddressBook? //MARK: Address Book class SwiftAddressBook { var internalAddressBook : ABAddressBook! private init?(_ dummy : Int) { var err : Unmanaged<CFError>? = nil let ab = ABAddressBookCreateWithOptions(nil, &err) if err == nil { internalAddressBook = ab.takeRetainedValue() } else { return nil } } class func authorizationStatus() -> ABAuthorizationStatus { return ABAddressBookGetAuthorizationStatus() } func requestAccessWithCompletion( completion : (Bool, CFError?) -> Void ) { ABAddressBookRequestAccessWithCompletion(internalAddressBook) {(let b : Bool, c : CFError!) -> Void in completion(b,c)} } func hasUnsavedChanges() -> Bool { return ABAddressBookHasUnsavedChanges(internalAddressBook) } func save() -> CFError? { return errorIfNoSuccess { ABAddressBookSave(self.internalAddressBook, $0)} } func revert() { ABAddressBookRevert(internalAddressBook) } func addRecord(record : SwiftAddressBookRecord) -> CFError? { return errorIfNoSuccess { ABAddressBookAddRecord(self.internalAddressBook, record.internalRecord, $0) } } func removeRecord(record : SwiftAddressBookRecord) -> CFError? { return errorIfNoSuccess { ABAddressBookRemoveRecord(self.internalAddressBook, record.internalRecord, $0) } } //MARK: person records var personCount : Int { get { return ABAddressBookGetPersonCount(internalAddressBook) } } func personWithRecordId(recordId : Int32) -> SwiftAddressBookPerson? { return SwiftAddressBookRecord(record: ABAddressBookGetPersonWithRecordID(internalAddressBook, recordId).takeUnretainedValue()).convertToPerson() } var allPeople : [SwiftAddressBookPerson]? { get { return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeople(internalAddressBook).takeRetainedValue()) } } func allPeopleInSource(source : SwiftAddressBookSource) -> [SwiftAddressBookPerson]? { return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeopleInSource(internalAddressBook, source.internalRecord).takeRetainedValue()) } func peopleWithName(name : String) -> [SwiftAddressBookPerson]? { let string : CFString = name as CFString return convertRecordsToPersons(ABAddressBookCopyPeopleWithName(internalAddressBook, string).takeRetainedValue()) } } //MARK: Wrapper for ABAddressBookRecord class SwiftAddressBookRecord { var internalRecord : ABRecord init(record : ABRecord) { internalRecord = record } func convertToSource() -> SwiftAddressBookSource? { if ABRecordGetRecordType(internalRecord) == UInt32(kABSourceType) { let source = SwiftAddressBookSource(record: internalRecord) return source } else { return nil } } func convertToGroup() -> SwiftAddressBookGroup? { if ABRecordGetRecordType(internalRecord) == UInt32(kABGroupType) { let group = SwiftAddressBookGroup(record: internalRecord) return group } else { return nil } } func convertToPerson() -> SwiftAddressBookPerson? { if ABRecordGetRecordType(internalRecord) == UInt32(kABPersonType) { let person = SwiftAddressBookPerson(record: internalRecord) return person } else { return nil } } } //MARK: Wrapper for ABAddressBookRecord of type ABSource class SwiftAddressBookSource : SwiftAddressBookRecord { var searchable : Bool { get { let sourceType : CFNumber = ABRecordCopyValue(internalRecord, kABSourceTypeProperty).takeRetainedValue() as CFNumber var rawSourceType : Int32? = nil CFNumberGetValue(sourceType, CFNumberGetType(sourceType), &rawSourceType) let andResult = kABSourceTypeSearchableMask & rawSourceType! return andResult != 0 } } var sourceName : String { return ABRecordCopyValue(internalRecord, kABSourceNameProperty).takeRetainedValue() as CFString } } //MARK: Wrapper for ABAddressBookRecord of type ABGroup class SwiftAddressBookGroup : SwiftAddressBookRecord { var name : String { get { return ABRecordCopyValue(internalRecord, kABGroupNameProperty).takeRetainedValue() as CFString } } class func create() -> SwiftAddressBookGroup { return SwiftAddressBookGroup(record: ABGroupCreate().takeRetainedValue()) } class func createInSource(source : SwiftAddressBookSource) -> SwiftAddressBookGroup { return SwiftAddressBookGroup(record: ABGroupCreateInSource(source.internalRecord).takeRetainedValue()) } var allMembers : [SwiftAddressBookPerson]? { get { return convertRecordsToPersons(ABGroupCopyArrayOfAllMembers(internalRecord).takeRetainedValue()) } } func addMember(person : SwiftAddressBookPerson) -> CFError? { return errorIfNoSuccess { ABGroupAddMember(self.internalRecord, person.internalRecord, $0) } } func removeMember(person : SwiftAddressBookPerson) -> CFError? { return errorIfNoSuccess { ABGroupRemoveMember(self.internalRecord, person.internalRecord, $0) } } var source : SwiftAddressBookSource { get { return SwiftAddressBookSource(record: ABGroupCopySource(internalRecord).takeRetainedValue()) } } } //MARK: Wrapper for ABAddressBookRecord of type ABPerson class SwiftAddressBookPerson : SwiftAddressBookRecord { class func create() -> SwiftAddressBookPerson { return SwiftAddressBookPerson(record: ABPersonCreate().takeRetainedValue()) } class func createInSource(source : SwiftAddressBookSource) -> SwiftAddressBookPerson { return SwiftAddressBookPerson(record: ABPersonCreateInSource(source.internalRecord).takeRetainedValue()) } class func createInSourceWithVCard(source : SwiftAddressBookSource, vCard : String) -> [SwiftAddressBookPerson]? { let data : NSData? = vCard.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) let abPersons : NSArray? = ABPersonCreatePeopleInSourceWithVCardRepresentation(source.internalRecord, data).takeRetainedValue() var swiftPersons = [SwiftAddressBookPerson]() if let persons = abPersons { for person : ABRecord in persons { let swiftPerson = SwiftAddressBookPerson(record: person) swiftPersons.append(swiftPerson) } } if swiftPersons.count != 0 { return swiftPersons } else { return nil } } class func createVCard(people : [SwiftAddressBookPerson]) -> String { let peopleArray : NSArray = people.map{$0.internalRecord} let data : NSData = ABPersonCreateVCardRepresentationWithPeople(peopleArray).takeRetainedValue() return NSString(data: data, encoding: NSUTF8StringEncoding)! } //MARK: Personal Information func setImage(image : UIImage) -> CFError? { let imageData : NSData = UIImagePNGRepresentation(image) return errorIfNoSuccess { ABPersonSetImageData(self.internalRecord, CFDataCreate(nil, UnsafePointer(imageData.bytes), imageData.length), $0) } } var image : UIImage? { get { return UIImage(data: ABPersonCopyImageData(internalRecord).takeRetainedValue()) } } func imageDataWithFormat(format : SwiftAddressBookPersonImageFormat) -> UIImage? { return UIImage(data: ABPersonCopyImageDataWithFormat(internalRecord, format.abPersonImageFormat).takeRetainedValue()) } func hasImageData() -> Bool { return ABPersonHasImageData(internalRecord) } func removeImage() -> CFError? { return errorIfNoSuccess { ABPersonRemoveImageData(self.internalRecord, $0) } } var allLinkedPeople : [SwiftAddressBookPerson]? { get { return convertRecordsToPersons(ABPersonCopyArrayOfAllLinkedPeople(internalRecord).takeRetainedValue() as CFArray) } } var source : SwiftAddressBookSource { get { return SwiftAddressBookSource(record: ABPersonCopySource(internalRecord).takeRetainedValue()) } } var compositeNameDelimiterForRecord : String { get { return ABPersonCopyCompositeNameDelimiterForRecord(internalRecord).takeRetainedValue() } } var firstName : String? { get { let value: AnyObject = ABRecordCopyValue(self.internalRecord, kABPersonFirstNameProperty).takeRetainedValue() ?? "" let typedval = value as? String return typedval } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonFirstNameProperty, value) } } var lastName : String? { get { let value: AnyObject = ABRecordCopyValue(self.internalRecord, kABPersonLastNameProperty).takeRetainedValue() ?? "" let typedval = value as? String return typedval } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonLastNameProperty, value) } } var middleName : String? { get { return extractProperty(kABPersonMiddleNameProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonMiddleNameProperty, value) } } var prefix : String? { get { return extractProperty(kABPersonPrefixProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonPrefixProperty, value) } } var suffix : String? { get { return extractProperty(kABPersonSuffixProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonSuffixProperty, value) } } var nickname : String? { get { return extractProperty(kABPersonNicknameProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonNicknameProperty, value) } } var firstNamePhonetic : String? { get { return extractProperty(kABPersonFirstNamePhoneticProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonFirstNamePhoneticProperty, value) } } var lastNamePhonetic : String? { get { return extractProperty(kABPersonLastNamePhoneticProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonLastNamePhoneticProperty, value) } } var middleNamePhonetic : String? { get { return extractProperty(kABPersonMiddleNamePhoneticProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonMiddleNamePhoneticProperty, value) } } var organization : String? { get { return extractProperty(kABPersonOrganizationProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonOrganizationProperty, value) } } var jobTitle : String? { get { return extractProperty(kABPersonJobTitleProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonJobTitleProperty, value) } } var department : String? { get { return extractProperty(kABPersonDepartmentProperty) } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonDepartmentProperty, value) } } var birthday : NSDate? { get { return extractProperty(kABPersonBirthdayProperty) } set { setSingleValueProperty(kABPersonBirthdayProperty, newValue) } } var note : String? { get { let value: AnyObject = ABRecordCopyValue(self.internalRecord, kABPersonNoteProperty).takeRetainedValue() ?? "" let typedval = value as? String return typedval } set { let value: AnyObject = newValue ?? "" setSingleValueProperty(kABPersonNoteProperty, value) } } var creationDate : NSDate? { get { return extractProperty(kABPersonCreationDateProperty) } set { setSingleValueProperty(kABPersonCreationDateProperty, newValue) } } var modificationDate : NSDate? { get { return extractProperty(kABPersonModificationDateProperty) } set { setSingleValueProperty(kABPersonModificationDateProperty, newValue) } } var alternateBirthday : Dictionary<String, AnyObject>? { get { return extractProperty(kABPersonAlternateBirthdayProperty) } set { let dict : NSDictionary? = newValue setSingleValueProperty(kABPersonAlternateBirthdayProperty, dict) } } //MARK: generic methods to set and get person properties private func extractProperty<T>(propertyName : ABPropertyID) -> T? { let copyval = ABRecordCopyValue(self.internalRecord, propertyName) let retval = copyval.takeRetainedValue() let typedval = retval as? T return typedval } private func setSingleValueProperty<T : AnyObject>(key : ABPropertyID,_ value : T?) { ABRecordSetValue(self.internalRecord, key, value, nil) } private func convertDictionary<T,U, V : AnyObject, W : AnyObject where V : Hashable>(d : Dictionary<T,U>?, keyConverter : (T) -> V, valueConverter : (U) -> W ) -> NSDictionary? { if let d2 = d { var dict = Dictionary<V,W>() for key in d2.keys { dict[keyConverter(key)] = valueConverter(d2[key]!) } return dict } else { return nil } } } //MARK: methods to convert arrays of ABRecords private func convertRecordsToPersons(records : [ABRecord]?) -> [SwiftAddressBookPerson]? { let swiftRecords = records?.map {(record : ABRecord) -> SwiftAddressBookPerson in return SwiftAddressBookRecord(record: record).convertToPerson()!} return swiftRecords } enum SwiftAddressBookPersonImageFormat { case thumbnail case originalSize var abPersonImageFormat : ABPersonImageFormat { switch self { case .thumbnail : return kABPersonImageFormatThumbnail case .originalSize : return kABPersonImageFormatOriginalSize } } } //MARK: some more handy methods //extension NSString { // convenience init?(string : String?) { // if string == nil { // self.init() // return nil // } // self.init(string: string!) // } //} func errorIfNoSuccess(call : (UnsafeMutablePointer<Unmanaged<CFError>?>) -> Bool) -> CFError? { var err : Unmanaged<CFError>? = nil let success : Bool = call(&err) if success { return nil } else { return err?.takeRetainedValue() } }
mit
a999afb48688240580ffb457fd673681
30.341818
182
0.63764
5.202837
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/DrinkPoint/Bartender/BartenderOnHandViewController.swift
1
3597
// // BartenderOnHandViewController.swift // DrinkPoint // // Created by Paul Kirk Adams on 7/5/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import UIKit class OnHandViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var alcoholDataSource = [Item]() var mixerDataSource = [Item]() @IBOutlet weak var alcoholTableView: UITableView! @IBOutlet weak var mixerTableView: UITableView! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = false SettingsController.firstLaunch() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) splitDataSource() self.alcoholTableView.reloadData() self.mixerTableView.reloadData() if let alertVC = SettingsController.checkOnHand() { presentViewController(alertVC, animated: true, completion: nil) } } func splitDataSource() { alcoholDataSource = [] mixerDataSource = [] for item in ItemController.sharedController.onHand { if item.alcohol { alcoholDataSource.append(item) } else { mixerDataSource.append(item) } } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == alcoholTableView{ return alcoholDataSource.count } else { return mixerDataSource.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView == alcoholTableView { let cell = tableView.dequeueReusableCellWithIdentifier("alcoholCell", forIndexPath: indexPath) as! ItemTableViewCell let item = alcoholDataSource[indexPath.row] cell.setCell(item) return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("mixersCell", forIndexPath: indexPath) as! ItemTableViewCell let item = mixerDataSource[indexPath.row] cell.setCell(item) return cell } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView == alcoholTableView { return "Alcohol" } else { return "Mixers" } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if tableView == alcoholTableView && editingStyle == .Delete { let item = self.alcoholDataSource[indexPath.row] ItemController.sharedController.removeItem(item) self.splitDataSource() self.alcoholTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if tableView == mixerTableView && editingStyle == .Delete { let item = self.mixerDataSource[indexPath.row] ItemController.sharedController.removeItem(item) self.splitDataSource() self.mixerTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
3645c2eebede867718510f1a3a824733
34.613861
148
0.646552
5.601246
false
false
false
false
wang-chuanhui/CHSDK
Add/RefreshControl/RefreshContentView.swift
1
3406
// // RefreshContentView.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import UIKit public protocol RefreshContentProtocol { var refreshState: RefreshState {get set} var pullingPercent: CGFloat {get set} init() } class RefreshContentView: UIView, RefreshContentProtocol { public var refreshState: RefreshState = .idle { didSet { if refreshState == .refreshing { activityIndicatorView.startAnimating() // progressView.isHidden = true label.text = "正在刷新数据中..." }else { activityIndicatorView.stopAnimating() // progressView.isHidden = false if refreshState == .pulling { label.text = "松开立即刷新" }else if refreshState == .idle { label.text = "拖拽刷新" }else if refreshState == .noMore { label.text = "没有更多了" }else if refreshState == .willRefresh { label.text = "即将刷新" } } } } public var pullingPercent: CGFloat = 0 { didSet { // progressView.setProgress(pullingPercent, animated: true) } } // let progressView = CUCircleProgressView(frame: CGRect.zero) let progressView = UIProgressView() let label = UILabel(frame: CGRect.zero) let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) public required init() { super.init(frame: CGRect.zero) setupSubviews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } func setupSubviews() { refreshState = .idle pullingPercent = 0 // progressView.progressTintColor = UIColor.darkGray // progressView.trackTintColor = UIColor.clear // progressView.lineWidth = 2 activityIndicatorView.hidesWhenStopped = true label.textColor = UIColor.darkText label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) // addSubview(progressView) addSubview(label) addSubview(activityIndicatorView) // progressView.translatesAutoresizingMaskIntoConstraints = false label.translatesAutoresizingMaskIntoConstraints = false activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false label.leftAnchor.constraint(equalTo: centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true activityIndicatorView.rightAnchor.constraint(equalTo: centerXAnchor, constant: -8).isActive = true activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true // progressView.rightAnchor.constraint(equalTo: centerXAnchor, constant: -8).isActive = true // progressView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true // progressView.heightAnchor.constraint(equalTo: activityIndicatorView.heightAnchor).isActive = true // progressView.widthAnchor.constraint(equalTo: activityIndicatorView.widthAnchor).isActive = true } }
mit
77ef9c024ef1374d842073e062755edb
29.081081
114
0.641809
5.455882
false
false
false
false
AgentFeeble/pgoapi
pgoapi/Classes/Networking/AuthRequest.swift
1
6246
// // AuthRequest.swift // pgoapi // // Created by Rayman Rosevear on 2016/07/25. // Copyright © 2016 MC. All rights reserved. // import Foundation import BoltsSwift private class AuthID: Synchronizable { private var id: Int = 0 let synchronizationLock: Lockable = SpinLock() private static let globalAuthId = AuthID() static func newAuthId() -> Int { return globalAuthId.newId() } private func newId() -> Int { return sync { id += 1 return id } } } public class AuthRequest { public enum AuthError: Error { case invalidResponse case clientError(String) } private let network: Network private let sessionId = "Auth Session \(AuthID.newAuthId())" public init(network: Network) { self.network = network } public func login(_ username: String, password: String) -> Task<AuthToken> { // Note: self is captured strongly to keep a strong reference to self // during the API calls let sessionId = self.sessionId let args = RequestArgs(sessionId: sessionId) return network.getJSON(EndPoint.LoginInfo, args: args) .continueOnSuccessWithTask(network.processingExecutor, continuation: { (response: NetworkResponse<Any>) in // Note strong capture to keep self alive during request return try self.getTicket(response: response, username: username, password: password) }) .continueOnSuccessWithTask(network.processingExecutor, continuation: { (ticket: String) -> Task<AuthToken> in return try self.loginViaOauth(ticket: ticket) }) .continueWithTask(continuation: { [weak self] task in self?.network.resetSessionWithID(sessionID: sessionId) return task }) } private func getTicket(response: NetworkResponse<Any>, username: String, password: String) throws -> Task<String> { guard let json = response.response as? NSDictionary, let lt = json["lt"] as? String, let execution = json["execution"] as? String else { throw AuthError.invalidResponse } let parameters: [String: Any] = [ "lt": lt, "execution": execution, "_eventId": "submit", "username": username, "password": password ] let args = RequestArgs(params: parameters, sessionId: sessionId) return network.postData(EndPoint.LoginInfo, args: args) .continueOnSuccessWith(network.processingExecutor, continuation: { (response: NetworkResponse<Data>) -> String in guard let location = response.responseHeaders?["Location"], let ticketRange = location.range(of: "?ticket=") else { throw self.getError(forInvalidTicketResponse: response) } return String(location.characters.suffix(from: ticketRange.upperBound)) }) } private func loginViaOauth(ticket: String) throws -> Task<AuthToken> { if ticket.characters.count == 0 { throw AuthError.invalidResponse } let parameters = [ "client_id": "mobile-app_pokemon-go", "redirect_uri": "https://www.nianticlabs.com/pokemongo/error", "client_secret": "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR", "grant_type": "refresh_token", "code": ticket ] return network.postString(EndPoint.LoginOAuth, args: RequestArgs(params: parameters, sessionId: sessionId)) .continueOnSuccessWith(network.processingExecutor, continuation: { (response: NetworkResponse<String>) -> AuthToken in guard let value = response.response, let regex = try? NSRegularExpression(pattern: "access_token=([A-Za-z0-9\\-.]+)&expires=([0-9]+)", options: []) else { throw AuthError.invalidResponse } let matches = regex.matches(in: value, options: [], range: NSRange(location: 0, length: value.utf16.count)) // Extract the access_token guard matches.count > 0 && matches[0].numberOfRanges >= 3, let tokenRange = matches[0].rangeAt(1).rangeForString(value) else { throw AuthError.invalidResponse } let token = value.substring(with: tokenRange) // Extract the expiry date guard let expiryRange = matches[0].rangeAt(2).rangeForString(value) else { throw AuthError.invalidResponse } let date = self.getDate(fromResponse: response) let expiryString = value.substring(with: expiryRange) guard let expiryTime = Int(expiryString) else { throw AuthError.invalidResponse } let expiryDate = date.addingTimeInterval(TimeInterval(expiryTime)) return AuthToken(token: token, expiry: expiryDate) }) } private func getDate<T>(fromResponse response: NetworkResponse<T>) -> Date { let formatter = DateFormatter() if let dateString = response.responseHeaders?["Date"], let date = formatter.date(from: dateString) { return date } return Date() } private func getError(forInvalidTicketResponse response: NetworkResponse<Data>) -> AuthError { if let responseData = response.response, let json = (try? JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions())) as? NSDictionary, let errors = json["errors"] as? [String], let error = errors.first { return AuthError.clientError(error) } return AuthError.invalidResponse } }
apache-2.0
e1f7c43d6676cee574d719b287ab3f2b
31.526042
137
0.578543
4.894201
false
false
false
false
TCA-Team/iOS
TUM Campus App/Extensions.swift
1
10486
// // Extensions.swift // TUM Campus App // // Created by Mathias Quintero on 7/21/16. // Copyright © 2016 LS1 TUM. All rights reserved. // import CoreLocation import UIKit import SafariServices import Sweeft private var locationManager: CLLocationManager = Thread.isMainThread ? CLLocationManager() : DispatchQueue.main.sync { CLLocationManager() } private func currentLocation() -> CLLocation { locationManager.startUpdatingLocation() let location = locationManager.location locationManager.stopUpdatingLocation() return location ?? DefaultCampus.value.location } extension URL { func open(sender: UIViewController? = nil) { if let sender = sender { let safariViewController = SFSafariViewController(url: self) sender.present(safariViewController, animated: true, completion: nil) } else { UIApplication.shared.open(self, options: [:], completionHandler: nil) } } } extension Date { var dayString: String { return string(using: "yyyy-MM-dd") } func numberOfDaysUntilDateTime(_ toDateTime: Date, inTimeZone timeZone: TimeZone? = nil) -> Int { var calendar = Calendar.current if let timeZone = timeZone { calendar.timeZone = timeZone } let difference = calendar.dateComponents(Set([.day]), from: self, to: toDateTime) return difference.day ?? 0 } } extension DateComponentsFormatter { static let shortTimeFormatter: DateComponentsFormatter = { let dateComponentsFormatter = DateComponentsFormatter() dateComponentsFormatter.unitsStyle = .short dateComponentsFormatter.maximumUnitCount = 1 return dateComponentsFormatter }() } extension SimpleManager { var location: CLLocation { return currentLocation() } } extension Array { func lastIndex(where criteria: (Element) throws -> Bool) rethrows -> Int? { return try enumerated().reduce(nil) { last, value in if try criteria(value.element) { return value.offset } return last } } } extension Collection { func mapped<V>() -> [V] { return compactMap { $0 as? V } } func first<V: Equatable>(where path: KeyPath<Element, V>, equals value: V) -> Element? { return first { $0[keyPath: path] == value } } func sorted(byLocation path: KeyPath<Element, CLLocation>) -> [Element] { let location = currentLocation() return self.sorted(ascending: { location.distance(from: $0[keyPath: path]) }) } func grouped<V: Hashable>(by path: KeyPath<Element, V>) -> [V : [Element]] { return reduce([:]) { dict, element in var dict = dict let key = element[keyPath: path] dict[key, default: []].append(element) return dict } } } extension Bundle { var version: String { return infoDictionary?["CFBundleShortVersionString"] as? String ?? "1" } var build: String { return infoDictionary?["CFBundleVersion"] as? String ?? "1.0" } var userAgent: String { return "TCA iOS \(version)/\(build)" } } extension Promise { func mapError(to defaultValue: T) -> Promise<T, E> { return mapResult { .value($0.value ?? defaultValue) } } } extension TimeInterval { static var oneMinute: TimeInterval { return 60 } static var oneHour: TimeInterval { return 60 * .oneMinute } static var sixHours: TimeInterval { return 6 * .oneHour } static var aboutOneDay: TimeInterval { return 24 * .oneHour } static var aboutOneWeek: TimeInterval { return 7 * .aboutOneDay } } extension UIViewController { func showError(_ title: String, _ message: String? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) present(alert, animated: true) } } extension Double { var bool: Bool { return NSNumber(value: self).boolValue } } extension UIColor { convenience init(hexString: String) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } } extension API { func removeCache(for endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty) { .global() >>> { let url = self.url(for: endpoint, arguments: arguments, queries: queries) let cacheKey = url.relativePath.replacingOccurrences(of: "/", with: "_") self.cache.delete(at: cacheKey) } } func clearCache() { cache.clear() } } extension FileCache { private var searchPathURL: URL { let urls = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) return urls[urls.count - 1].appendingPathComponent(directory) } func clear() { try? FileManager.default.removeItem(at: searchPathURL) } } extension CGContext { func addRoundedRectToPath(rect: CGRect, ovalWidth: CGFloat, ovalHeight: CGFloat) { if ovalWidth == 0 || ovalHeight == 0 { return self.addRect(rect) } saveGState() setStrokeColor(Constants.tumBlue.cgColor) translateBy(x: rect.minX, y: rect.minY) scaleBy(x: ovalWidth, y: ovalHeight) let relativeWidth = rect.width / ovalWidth let relativeHeight = rect.height / ovalHeight move(to: .init(x: relativeWidth, y: relativeHeight / 2)) addArc(tangent1End: .init(x: relativeWidth, y: relativeHeight), tangent2End: .init(x: relativeWidth / 2, y: relativeHeight), radius: 1.0) addArc(tangent1End: .init(x: 0, y: relativeHeight), tangent2End: .init(x: 0, y: relativeHeight / 2), radius: 1.0) addArc(tangent1End: .init(x: 0, y: 0), tangent2End: .init(x: relativeWidth / 2, y: 0), radius: 1.0) addArc(tangent1End: .init(x: relativeWidth, y: 0), tangent2End: .init(x: relativeWidth, y: relativeHeight / 2), radius: 1.0) restoreGState() } } extension UIImage { func resized(to newSize: CGSize, scale: CGFloat = 0.0) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, scale) self.draw(in: .init(x: 0, y: 0, width: newSize.width, height: newSize.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? self } func withRoundedCorners(radius: CGFloat, borderSize: CGFloat) -> UIImage { let scale = max(self.scale, 1.0) let scaledBorderSize = scale * borderSize let scaledRadius = scale * radius guard let cgImage = self.cgImage, let colorSpace = cgImage.colorSpace else { return self } let width = size.width * scale let height = size.height * scale let context = CGContext.init(data: nil, width: Int(width), height: Int(height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: cgImage.bytesPerRow, space: colorSpace, bitmapInfo: cgImage.bitmapInfo.rawValue) context?.setFillColor(UIColor.white.cgColor) context?.fill(.init(x: 0, y: 0, width: width, height: height)) context?.beginPath() let rect = CGRect(x: scaledBorderSize, y: scaledBorderSize, width: width - borderSize * 2, height: height - borderSize * 2) context?.addRoundedRectToPath(rect: rect, ovalWidth: scaledRadius, ovalHeight: scaledRadius) context?.closePath() context?.clip() context?.draw(cgImage, in: .init(x: 0, y: 0, width: width, height: height)) let ref = context?.makeImage() guard let image = ref.map({ UIImage(cgImage: $0, scale: scale, orientation: .up) }) else { return self } return image } func squared() -> UIImage { guard let cgImage = self.cgImage else { return self } let width = cgImage.width let height = cgImage.height let cropSize = min(width, height) let x = Double(width - cropSize) / 2.0 let y = Double(height - cropSize) / 2.0 let rect = CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(cropSize), height: CGFloat(cropSize)) let newImage = cgImage.cropping(to: rect) ?? cgImage return UIImage(cgImage: newImage, scale: 0.0, orientation: self.imageOrientation) } } extension JSON { var strings: [String] { return array ==> { $0.string } } } extension Collection { var nonEmpty: Self? { guard !isEmpty else { return nil } return self } }
gpl-3.0
749874b69d47910d3b4089c93e169a7e
28.535211
152
0.564425
4.529158
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/live/View/GifView/LYCGifView.swift
1
3010
// // LYCGifView.swift // LYCSwiftDemo // // Created by yuchen.li on 2017/6/13. // Copyright © 2017年 zsc. All rights reserved. // import UIKit private let kGifCellId = "kGifCellId" @objc protocol LYCGifViewDelegate :NSObjectProtocol { @objc optional func gitView(_ gifView : LYCGifView ,collectionView : UICollectionView , didSelectRowAtIndex indexPath : IndexPath , gifModel : LYCGifModel) } class LYCGifView: UIView { weak var deleage : LYCGifViewDelegate? fileprivate lazy var gifCollectionView : HYPageCollectionView = { let rect = CGRect(x: 0, y: 0, width: kScreenWidth, height: 280) let titles = ["礼物"] let style = HYTitleStyle() style.isShowBottomLine = true style.titleBackgroundColor = UIColor.black let layout = HYPageCollectionFlowLayout() layout.cols = 4 layout.rows = 2 layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let gifView = HYPageCollectionView(frame: rect, titles:titles , style: style, isTitleInTop: false, layout: layout) gifView.backgroundColor = UIColor.black let nib = UINib(nibName: "LYCGifViewCell", bundle: nil) gifView.register(nib: nib , identifier: kGifCellId) gifView.datasoure = self gifView.delegate = self return gifView }() fileprivate lazy var gifVM : LYCGifViewModel = LYCGifViewModel() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:-初始化UI extension LYCGifView { func setupUI(){ addSubview(gifCollectionView) } } //MARK:- 数据源方法 extension LYCGifView : HYPageCollectionViewDataSource{ func numberOfSections(pageCollectionView: HYPageCollectionView) -> Int { return 1 } func collection(_ pageCollectionView: HYPageCollectionView, numberOfItemsInSection section: Int) -> Int { return LYCGifViewModel.shareInstance.gifPackage.count } func collection(_ pageCollectionView: HYPageCollectionView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView .dequeueReusableCell(withReuseIdentifier: kGifCellId, for: indexPath) as! LYCGifViewCell let gifModel = LYCGifViewModel.shareInstance.gifPackage[indexPath.row] cell.gifModel = gifModel return cell } } //MARK:- 代理方法 extension LYCGifView : HYPageCollectionViewDelegate{ func collection(_ pageCollectionView: HYPageCollectionView, collection: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { let gifModel = LYCGifViewModel.shareInstance.gifPackage[indexPath.row] deleage?.gitView!(self, collectionView: collection, didSelectRowAtIndex: indexPath, gifModel: gifModel) } }
mit
2a3862ca4d5fb6bdb596e33f40a21aeb
33.241379
160
0.691507
4.590139
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/SSHTerminalViewController.swift
1
9296
// // SSHTerminalViewController.swift // Sublime // // Created by Eular on 3/28/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import NMSSH class SSHTerminalViewController: UIViewController, UITextViewDelegate { var server = ["host": "localhost", "port": "22", "username": "sublime", "password": "sublime"] let terminalTextView = UITextView() var sshSession: NMSSHSession! var shellPrompt: String! let promptView = UIView() var promptViewBottom: NSLayoutConstraint! var promptViewHeight: NSLayoutConstraint! let promptLines = 3 let promptLineHeight: CGFloat = 14 let promptViewTopMargin: CGFloat = 5 let promptViewBottomOffset: CGFloat = 5 override func viewDidLoad() { super.viewDidLoad() title = server["host"] view.backgroundColor = Constant.CapeCod shellPrompt = "[\(server["username"]!)@\(server["host"]!) ~] >" Global.Notifi.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) Global.Notifi.addObserver(self, selector: #selector(self.keyboardDidShow), name: UIKeyboardDidShowNotification, object: nil) Global.Notifi.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) view.addSubview(terminalTextView) view.addSubview(promptView) setTerminalTextView() setPromptView(">", lineHeight: promptLineHeight, maxLines: promptLines) SSHLog("[sublime@localhost ~] > ssh \(server["username"]!)@\(server["host"]!):\(server["port"]!)") } deinit { sshSession.disconnect() } func keyboardWillShow(noti: NSNotification) { let info = noti.userInfo! let value = info[UIKeyboardFrameBeginUserInfoKey] as! NSValue let value2 = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue let keyboardSize = value.CGRectValue() let height = keyboardSize.height var time: NSTimeInterval = 0 value2.getValue(&time) promptViewBottom.constant = -height - promptViewBottomOffset UIView.animateWithDuration(time, animations: { self.view.layoutIfNeeded() }) { (_) in self.updateTerminalTextView() } } func keyboardDidShow() { navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ssh_keyboard"), style: .Plain, target: self, action: #selector(self.dismissKeyboard)) } func keyboardWillHide(noti: NSNotification) { navigationItem.rightBarButtonItem = nil let info = noti.userInfo! let value2 = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue var time: NSTimeInterval = 0 value2.getValue(&time) promptViewBottom.constant = -promptViewBottomOffset UIView.animateWithDuration(time) { () -> Void in self.view.layoutIfNeeded() } } func dismissKeyboard() { self.view.endEditing(true) } func setTerminalTextView() { // terminalTextView.frame = view.frame terminalTextView.backgroundColor = Constant.CapeCod terminalTextView.textColor = UIColor.whiteColor() terminalTextView.textContainerInset.top = 0 terminalTextView.textContainerInset.bottom = 0 terminalTextView.editable = false terminalTextView.translatesAutoresizingMaskIntoConstraints = false view.addConstraint(NSLayoutConstraint(item: terminalTextView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: terminalTextView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: terminalTextView, attribute: .Bottom, relatedBy: .Equal, toItem: promptView, attribute: .Top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: terminalTextView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: view.width)) } func setPromptView(promptText: String, lineHeight: CGFloat, maxLines: Int){ promptView.translatesAutoresizingMaskIntoConstraints = false // Add constraints promptViewBottom = NSLayoutConstraint(item: promptView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -promptViewBottomOffset) promptViewHeight = NSLayoutConstraint(item: promptView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: lineHeight) view.addConstraint(promptViewBottom) view.addConstraint(NSLayoutConstraint(item: promptView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: promptView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: view.width)) view.addConstraint(promptViewHeight) let prompt = UILabel() prompt.text = promptText prompt.textColor = UIColor.whiteColor() prompt.font = terminalTextView.font prompt.frame = CGRectMake(5, 0, prompt.intrinsicContentSize().width, lineHeight) promptView.addSubview(prompt) let input = UITextView() input.frame = CGRectMake(0, 0, view.width, lineHeight * maxLines) input.backgroundColor = UIColor.clearColor() input.font = terminalTextView.font input.textContainer.maximumNumberOfLines = maxLines input.textContainerInset.top = 0 input.textContainerInset.bottom = 0 input.autocorrectionType = .No input.autocapitalizationType = .None input.keyboardType = .ASCIICapable input.keyboardAppearance = .Dark input.spellCheckingType = .No input.delegate = self input.tintColor = UIColor.whiteColor() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .ByCharWrapping paragraphStyle.firstLineHeadIndent = prompt.frame.width + prompt.frame.origin.x let attrs = [ NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: UIColor.whiteColor() ] input.attributedText = NSAttributedString(string: " ", attributes: attrs) input.text = nil promptView.addSubview(input) } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { let cmd = textView.text.trim() if cmd.isEmpty { SSHLog(shellPrompt) } else { SSHLog("\(shellPrompt) \(cmd)") textView.text = nil if promptViewHeight.constant != promptLineHeight { promptViewHeight.constant = promptLineHeight UIView.animateWithDuration(0.3, animations: { () -> Void in self.view.layoutIfNeeded() }) } if sshSession.authorized { do { let response = try sshSession.channel.execute(cmd) if !response.isEmpty { SSHLog(response[nil,-1]) } } catch {} } } return false } return true } func textViewDidChange(textView: UITextView) { promptViewHeight.constant = textView.contentSize.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.view.layoutIfNeeded() }) } override func viewDidAppear(animated: Bool) { let user = server["username"]! let host = server["host"]! let port = server["port"]! let passwd = server["password"]! sshSession = NMSSHSession(host: "\(host):\(port)", andUsername: user) if Network.isConnectedToNetwork() { if sshSession.connect() { SSHLog("Password: ******") if sshSession.authenticateByPassword(passwd) { SSHLog("Connect: Successful!") SSHLog("=============================") } else { SSHLog("Error: Password is wrong!") } } else { SSHLog("Error: Connect fialed!") } } else { SSHLog("Error: No network!") } } func SSHLog(msg: String) { terminalTextView.text = terminalTextView.text + "\(msg)\n" terminalTextView.setLineBreakMode(.ByCharWrapping) terminalTextView.scrollToBottom() } func updateTerminalTextView() { terminalTextView.attributedText = terminalTextView.attributedText.copy() as! NSAttributedString terminalTextView.scrollToBottom() } }
gpl-3.0
ff5c0ec65422e257dbc9c2eb48ab833a
41.058824
186
0.62894
5.204367
false
false
false
false
a7ex/SwiftDTO
SwiftDTO/Helper/HelperFunctions.swift
1
2062
// // HelperFunctions.swift // SwiftDTO // // Created by Alex da Franca on 24.05.17. // Copyright © 2017 Farbflash. All rights reserved. // import Foundation func writeToStdError(_ str: String) { let handle = FileHandle.standardError if let data = str.data(using: String.Encoding.utf8) { handle.write(data) } } func writeToStdOut(_ str: String) { let handle = FileHandle.standardOutput if let data = "\(str)\n".data(using: String.Encoding.utf8) { handle.write(data) } } func createClassNameFromType(_ nsType: String?) -> String? { guard let nsType = nsType, !nsType.isEmpty else { return nil } guard let type = nsType.components(separatedBy: ":").last else { return nil } let capType = type.capitalizedFirst switch capType { case "Error": return "DTOError" default: return capType } } func writeContent(_ content: String, toFileAtPath fpath: String?) { guard let fpath = fpath else { writeToStdError("Error creating enum file. Path for target file is nil.") return } do { try content.write(toFile: fpath, atomically: false, encoding: String.Encoding.utf8) writeToStdOut("Successfully written file to: \(fpath)\n") } catch let error as NSError { writeToStdError("error: \(error.localizedDescription)") } } func pathForClassName(_ className: String, inFolder target: String?, fileExtension: String = "swift") -> String? { guard let target = target else { return nil } let fileurl = URL(fileURLWithPath: target) let newUrl = fileurl.appendingPathComponent(className).appendingPathExtension(fileExtension) return newUrl.path } func pathForParseExtension(_ className: String, inFolder target: String?, fileExtension: String = "swift") -> String? { guard let target = target else { return nil } let fileurl = URL(fileURLWithPath: target) let newUrl = fileurl .appendingPathComponent("\(className)+Parse") .appendingPathExtension(fileExtension) return newUrl.path }
apache-2.0
cf3e4d071fdf34203f55738eaa3d8710
29.761194
119
0.679767
4.049116
false
false
false
false
erkekin/EERegression
EERegression/swix/swix/io.swift
1
3417
// // io.swift // swix // // Created by Scott Sievert on 11/7/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation // ndarray binary func write_binary(x:ndarray, filename:String, prefix:String=S2_PREFIX){ let N = x.n let data = NSData(bytes:!x, length:N*sizeof(Double)) data.writeToFile(prefix+"../"+filename, atomically: false) } func read_binary(filename:String, prefix:String=S2_PREFIX) -> ndarray{ let read = NSData(contentsOfFile: prefix+"../"+filename) let l:Int! = read?.length let sD:Int = sizeof(Double) let count = (l.double / sD.double) let y = zeros(count.int) read?.getBytes(!y, length: count.int*sizeof(Double)) return y } // matrix binary func write_binary(x:matrix, filename:String, prefix:String=S2_PREFIX){ let y = concat(array(x.shape.0.double, x.shape.1.double), y: x.flat) write_binary(y, filename:filename, prefix:prefix) } func read_binary(filename:String, prefix:String=S2_PREFIX)->matrix{ var a:ndarray = read_binary(filename, prefix:prefix) var (w, h) = (a[0], a[1]) let b = reshape(a[2..<a.n], shape: (w.int,h.int)) return b } // ndarray csv func write_csv(x:ndarray, filename:String, prefix:String=S2_PREFIX){ // write the array to CSV var seperator="," var str = "" for i in 0..<x.n{ seperator = i == x.n-1 ? "" : "," str += String(format: "\(x[i])"+seperator) } str += "\n" var error:NSError? do { try str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 } if let error=error{ Swift.print("File probably wasn't recognized \n\(error)") } } func read_csv(filename:String, prefix:String=S2_PREFIX) -> ndarray{ let x = try? String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding) var array:[Double] = [] var columns:Int = 0 var z = x!.componentsSeparatedByString(",") columns = 0 for i in 0..<z.count{ let num = z[i] array.append(num.doubleValue) columns += 1 } var done = zeros(1 * columns) done.grid = array return done } // matrix csv func read_csv(filename:String, prefix:String=S2_PREFIX) -> matrix{ let x = try? String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding) var y = x!.componentsSeparatedByString("\n") let rows = y.count-1 var array:[Double] = [] var columns:Int = 0 for i in 0..<rows{ let z = y[i].componentsSeparatedByString(",") columns = 0 for num in z{ array.append(num.doubleValue) columns += 1 } } var done = zeros((rows, columns)) done.flat.grid = array return done } func write_csv(x:matrix, filename:String, prefix:String=S2_PREFIX){ var seperator="," var str = "" for i in 0..<x.shape.0{ for j in 0..<x.shape.1{ seperator = j == x.shape.1-1 ? "" : "," str += String(format: "\(x[i, j])"+seperator) } str += "\n" } var error:NSError? do { try str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 } if let error=error{ Swift.print("File probably wasn't recognized \n\(error)") } }
gpl-2.0
f94b1f32d4b21184eae7ebf3e93ea932
27.957627
101
0.604331
3.423848
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
labs/SwiftProgramming/SwiftProgramming/Contact.swift
2
999
import Foundation enum PhoneType: String, CustomDebugStringConvertible { case Home = "Home" case Work = "Work" case Cell = "Cell" var debugDescription: String { return rawValue } } class Contact: CustomDebugStringConvertible { var firstName: String? var lastName: String? var companyName: String? var phoneNumbers: [PhoneType: String]? var fullName: String { var name = "" if let last = lastName { name += last if firstName != nil { name += ", " } } if let first = firstName { name += first } return name } var debugDescription: String { var desc = "name: \(fullName) | phone numbers: " if let phones = phoneNumbers { desc += "\(phones)" } else { desc += "none" } return desc } }
mit
502193f287f5f5588dc86643eba486ed
19
56
0.479479
5.203125
false
false
false
false
YuantongL/Cross-Train
ICrossCommander/leaderboard.swift
1
3792
// // leaderboard.swift // ICrossCommander // // Created by Lyt on 12/22/14. // Copyright (c) 2014 Lyt. All rights reserved. // //This class is for the leaderboard view import Foundation import SpriteKit class leaderboard: SKScene { var back:SKSpriteNode! var background:SKSpriteNode! var did = false override func didMoveToView(view: SKView) { if(did == false){ did = true self.scaleMode = SKSceneScaleMode.AspectFill //Background background = SKSpriteNode(texture:SKTexture(imageNamed:"background_leaderboard")) background.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) background.setScale(0.91) background.zPosition = 1 self.addChild(background) //Back button back = SKSpriteNode(texture: SKTexture(imageNamed: "back_icon")) back.position = CGPoint(x:CGRectGetMidX(self.frame) - 460, y:CGRectGetMidY(self.frame) + 235) back.zPosition = 6 back.setScale(2.6) self.addChild(back) var transit_fan:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng")) transit_fan.position = CGPoint(x:CGRectGetMidX(self.frame) + 130, y:CGRectGetMidY(self.frame)) transit_fan.zPosition = 100 transit_fan.setScale(1.0) self.addChild(transit_fan) transit_fan.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {() transit_fan.removeFromParent() }) }else{ var transit_fan:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng")) transit_fan.position = CGPoint(x:CGRectGetMidX(self.frame) + 130, y:CGRectGetMidY(self.frame)) transit_fan.zPosition = 100 transit_fan.setScale(1.0) self.addChild(transit_fan) transit_fan.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {() transit_fan.removeFromParent() }) } } //----------------------Functions of touches---------------------- override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { back.texture = SKTexture(imageNamed: "back_icon") var tnode:SKSpriteNode = self.nodeAtPoint((touches.first as! UITouch).locationInNode(self)) as! SKSpriteNode if(tnode.isEqual(back)){ //back to main var transit_zheng:SKSpriteNode = SKSpriteNode(texture: SKTexture(imageNamed: "transit_zheng")) transit_zheng.position = CGPoint(x:CGRectGetMidX(self.frame) - 1200, y:CGRectGetMidY(self.frame)) transit_zheng.zPosition = 100 transit_zheng.setScale(1.0) self.addChild(transit_zheng) transit_zheng.runAction(SKAction.moveTo(CGPoint(x:CGRectGetMidX(self.frame) + 160, y:CGRectGetMidY(self.frame)), duration: 0.5), completion: {() Bank.storeScene(self, x: 5) self.view?.presentScene(Bank.getScene(1)) transit_zheng.removeFromParent() }) } } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { var tnode:SKSpriteNode = self.nodeAtPoint((touches.first as! UITouch).locationInNode(self)) as! SKSpriteNode if(tnode.isEqual(back)){ back.texture = SKTexture(imageNamed: "back_icon_t") } } //----------------------End of touches functions---------------------- }
mit
230367ea872d71692d8bde74bb078ca5
40.681319
156
0.603112
4.574186
false
false
false
false
swiftix/swift.old
test/IDE/print_stdlib.swift
1
1509
// Check interface produced for the standard library. // // RUN: %target-swift-ide-test -print-module -module-to-print=Swift -source-filename %s -print-interface > %t.txt // RUN: FileCheck -check-prefix=CHECK-ARGC %s < %t.txt // RUN: FileCheck %s < %t.txt // RUN: FileCheck -check-prefix=CHECK-SUGAR %s < %t.txt // RUN: FileCheck -check-prefix=CHECK-MUTATING-ATTR %s < %t.txt // RUN: FileCheck -check-prefix=NO-FIXMES %s < %t.txt // RUN: FileCheck -check-prefix=CHECK-ARGC %s < %t.txt // RUN: %target-swift-ide-test -print-module -module-to-print=Swift -source-filename %s -print-interface-doc > %t-doc.txt // RUN: FileCheck %s < %t-doc.txt // CHECK-ARGC: static var argc: CInt { get } // CHECK-NOT: @rethrows // CHECK-NOT: {{^}}import // CHECK-NOT: _Double // CHECK-NOT: _StringBuffer // CHECK-NOT: _StringCore // CHECK-NOT: _ArrayBody // DONT_CHECK-NOT: {{([^I]|$)([^n]|$)([^d]|$)([^e]|$)([^x]|$)([^a]|$)([^b]|$)([^l]|$)([^e]|$)}} // CHECK-NOT: buffer: _ArrayBuffer // CHECK-NOT: func ~> // FIXME: Builtin. // FIXME: RawPointer // CHECK-NOT: extension [ // CHECK-NOT: extension {{.*}}? // CHECK-NOT: extension {{.*}}! // CHECK-NOT: addressWithOwner // CHECK-NOT: mutableAddressWithOwner // CHECK-NOT: _ColorLiteralConvertible // CHECK-NOT: _FileReferenceLiteralConvertible // CHECK-NOT: _ImageLiteralConvertible // CHECK-SUGAR: extension Array : // CHECK-SUGAR: extension ImplicitlyUnwrappedOptional : // CHECK-SUGAR: extension Optional : // CHECK-MUTATING-ATTR: mutating func // NO-FIXMES-NOT: FIXME
apache-2.0
9145aa07f9dfdad0edd1c6dddfe73168
34.928571
121
0.667329
3.238197
false
false
false
false
dobaduc/SwiftStarterKit
SwiftStarterKitTests/ClosureSyntaxTests.swift
1
4018
// // ClosureSyntaxTests.swift // SwiftStarterKit // // Created by Doba Duc on 6/29/15. // Copyright (c) 2015 Doba Duc. All rights reserved. // import XCTest class ClosureSyntaxTests: XCTestCase { func testClosureWithParameterNamesAndReturnType() { var strings = ["25", "11", "3333"] sort(&strings, { (s1: String, s2: String) -> Bool in return s1 < s2 }) XCTAssert(strings[0] == "11" && strings[1] == "25" && strings[2] == "3333", "Array sorting went wrong") } func testClosureWithoutParameterNamesAndReturnType() { var strings = ["25", "11", "3333"] sort(&strings, { s1, s2 in s1 > s2 }) XCTAssert(strings[0] == "3333" && strings[1] == "25" && strings[2] == "11", "Array sorting went wrong") } func testClosureWithShorthandParameters() { var strings = ["25", "11", "3333"] sort(&strings, { $0 > $1 }) XCTAssert(strings[0] == "3333" && strings[1] == "25" && strings[2] == "11", "Array sorting went wrong") } func testClosureWithOperatorFunction() { var strings = ["25", "11", "3333"] sort(&strings, (>)) XCTAssert(strings[0] == "3333" && strings[1] == "25" && strings[2] == "11", "Array sorting went wrong") } func testClosureWithoutReturnType() { let sum = {(left: Int, right: Int) in return left + right } XCTAssert(sum(10, 5) == 15, "10 + 5 should be 15!") } func testInoutParameters() { var leftValue = 3 var rightValue = 4 func swapValues(inout left: Int, inout right: Int) { let temporaryValue = left left = right right = temporaryValue } swapValues(&leftValue, &rightValue) XCTAssert(leftValue == 4 && rightValue == 3, "Left value should be 4, right value should be 3!") } func testInlineClosure() { let numbers: [Int] = [5, 10, 100, 15, 20, 60] // NOTE: let n = 5 -1 will generate compile error let sumOfFirstHalf: Int = { var total: Int = 0 for i in 0 ..< numbers.count / 2 { total += numbers[i] } return total }() let sumOfTheRest: Int = { var total: Int = 0 for i in numbers.count / 2 ..< numbers.count { total += numbers[i] } return total }() XCTAssert(sumOfFirstHalf == 115 && sumOfTheRest == 95, "Calculation went wrong!") } func testTrailingClosure() { let numbers: [Int] = [5, 10, 100, 15, 20, 60] let expectation = self.expectationWithDescription("Completion block must be invoked") func sum(array: [Int], completionBock: (totalValue: Int) -> Void) { var total = 0 for number in array { total += number } completionBock(totalValue: total) } sum(numbers, { (totalValue) -> Void in print(totalValue) expectation.fulfill() }) // NOTE: This is actually a good example of trailing closure waitForExpectationsWithTimeout(2) {(error) -> Void in if let error = error { XCTFail("Something went wrong") } } } func testTrailingClosureHavingNoParameters() { let numbers: [Int] = [5, 10, 100, 15, 20, 60] let expectation = self.expectationWithDescription("Dummy completion block must be invoked") func sum(array: [Int], completionBock: () -> Void) { var total = 0 for number in array { total += number } completionBock() } sum(numbers, { expectation.fulfill() }) waitForExpectationsWithTimeout(2) {(error) -> Void in if let error = error { XCTFail("Something went wrong") } } } }
mit
9ed1ed9ef5cf85c244327a2a7d749328
28.328467
111
0.525137
4.247357
false
true
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/DMCharacter.swift
1
6451
// // DMCharacter.swift // denm_view // // Created by James Bean on 9/10/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class DMCharacter: CAShapeLayer { public var x: CGFloat = 0 public var top: CGFloat = 0 public var width: CGFloat { get { return 0 } } public var height: CGFloat = 0 public var italicAngle: CGFloat = 0 public var midLine: CGFloat { get { return 0.5 * height } } public var xHeight: CGFloat { get { return 0.2 * height } } public var capHeight: CGFloat { get { return 0.0618 * height } } public var baseline: CGFloat { get { return 0.75 * height } } public var restLine: CGFloat { get { return 0.9 * height } } public class func withDMCharacterType(type: DMCharacterType, height: CGFloat) -> DMCharacter? { let dmCharacter: DMCharacter? switch type { case .F: dmCharacter = DMCharacter_f() case .P: dmCharacter = DMCharacter_p() case .M: dmCharacter = DMCharacter_m() case .O: dmCharacter = DMCharacter_o() case .Exclamation: return nil case .Paren_open: return nil case .Paren_close: return nil } dmCharacter!.height = height // still needs position set, and build() return dmCharacter! } public class func dmCharacterWithDMCharacterType( type: DMCharacterType, x: CGFloat, height: CGFloat ) -> DMCharacter? { let dmCharacter: DMCharacter? switch type { case .F: dmCharacter = DMCharacter_f() case .P: dmCharacter = DMCharacter_p() default: return nil } dmCharacter!.x = x dmCharacter!.height = height dmCharacter!.build() return dmCharacter! } internal func build() { path = makePath() setFrame() setVisualAttributes() } private func setFrame() { // get bounding box?, then -0.5 * width frame = CGRectMake(x - 0.5 * width, top, width, height) } private func makePath() -> CGPath { // make path, override in subclassesq return UIBezierPath().CGPath } private func setVisualAttributes() { strokeColor = UIColor.grayscaleColorWithDepthOfField(.MostForeground).CGColor fillColor = UIColor.clearColor().CGColor lineJoin = kCALineJoinBevel lineWidth = 0.0618 * height } } public class DMCharacter_f: DMCharacter { public override var width: CGFloat { get { return baseline - xHeight } } private var crossStroke_length: CGFloat { get { return 0.5 * width } } override func makePath() -> CGPath { let path = UIBezierPath() addDownStrokeToPath(path) addCrossStrokeToPath(path) return path.CGPath } private func addDownStrokeToPath(path: UIBezierPath) { let downStroke = UIBezierPath() downStroke.moveToPoint(CGPointMake(0, restLine)) downStroke.addLineToPoint(CGPointMake(0.236 * width, height)) downStroke.addLineToPoint(CGPointMake(0.618 * width, xHeight)) downStroke.addCurveToPoint( CGPointMake(width, capHeight), controlPoint1: CGPointMake(0.825 * width, -0.1236 * height), controlPoint2: CGPointMake(width, capHeight) ) path.appendPath(downStroke) } private func addCrossStrokeToPath(path: UIBezierPath) { let crossStroke = UIBezierPath() crossStroke.moveToPoint( CGPointMake(0.618 * width - 0.5 * crossStroke_length, xHeight) ) crossStroke.addLineToPoint( CGPointMake(0.618 * width + 0.5 * crossStroke_length, xHeight) ) path.appendPath(crossStroke) } } public class DMCharacter_p: DMCharacter { public override var width: CGFloat { get { return baseline - xHeight } } public var serif_length: CGFloat { get { return 0.382 * width } } override func makePath() -> CGPath { let path = UIBezierPath() addStemStrokeToPath(path) addBowlStrokeToPath(path) addSerifStrokeToPath(path) return path.CGPath } private func addStemStrokeToPath(path: UIBezierPath) { let stemStroke = UIBezierPath() stemStroke.moveToPoint(CGPointMake(0.5 * serif_length, restLine)) stemStroke.addLineToPoint(CGPointMake(0.618 * width, xHeight)) stemStroke.addLineToPoint(CGPointMake(0.33 * width, xHeight + 0.0618 * height)) path.appendPath(stemStroke) } private func addBowlStrokeToPath(path: UIBezierPath) { let bowlStroke = UIBezierPath( ovalInRect: CGRectMake( 0.5 * width, midLine - 0.25 * width, 0.5 * width, 0.5 * width ) ) path.appendPath(bowlStroke) } private func addSerifStrokeToPath(path: UIBezierPath) { let serifStroke = UIBezierPath() serifStroke.moveToPoint(CGPointMake(0, restLine)) serifStroke.addLineToPoint(CGPointMake(serif_length, restLine)) path.appendPath(serifStroke) } override func setVisualAttributes() { super.setVisualAttributes() fillColor = DNMColorManager.backgroundColor.CGColor } } public class DMCharacter_o: DMCharacter { public override var width: CGFloat { get { return 0.618 * (baseline - xHeight) } } override func makePath() -> CGPath { let path = UIBezierPath(ovalInRect: CGRectMake(0, midLine - 0.5 * width, width, width)) return path.CGPath } override func setVisualAttributes() { super.setVisualAttributes() fillColor = DNMColorManager.backgroundColor.CGColor } } public class DMCharacter_m: DMCharacter { public override var width: CGFloat { get { return baseline - xHeight } } override func makePath() -> CGPath { // something let path = UIBezierPath() path.moveToPoint(CGPointMake(0, baseline)) path.addLineToPoint(CGPointMake(0, xHeight)) path.addLineToPoint(CGPointMake(0.5 * width, xHeight + 0.5 * (baseline - xHeight))) path.addLineToPoint(CGPointMake(width, xHeight)) path.addLineToPoint(CGPointMake(width, baseline)) return path.CGPath } } public enum DMCharacterType { case F, P, M, O, Exclamation, Paren_open, Paren_close }
gpl-2.0
139d039ba06152ab5ea83c298c4383ae
31.094527
95
0.626357
4.36696
false
false
false
false
kthomas/KTSwiftExtensions
Source/common/services/KTS3Service.swift
1
3187
// // KTS3Service.swift // KTSwiftExtensions // // Created by Kyle Thomas on 7/4/16. // Copyright © 2016 Kyle Thomas. All rights reserved. // import Alamofire import AlamofireObjectMapper public class KTS3Service: NSObject { public class func presign(_ url: URL, filename: String, metadata: [String: String], headers: [String: String], successHandler: KTApiSuccessHandler?, failureHandler: KTApiFailureHandler?) { presign(url, bucket: nil, filename: filename, metadata: metadata, headers: headers, successHandler: successHandler, failureHandler: failureHandler) } public class func presign(_ url: URL, bucket: String?, filename: String, metadata: [String: String], headers: [String: String], successHandler: KTApiSuccessHandler?, failureHandler: KTApiFailureHandler?) { var params = ["filename": filename, "metadata": metadata.toJSONString()] params["bucket"] = bucket let request: DataRequest = Alamofire.request(url, method: .get, parameters: params, headers: headers) KTApiService.shared.execute(request, successHandler: successHandler, failureHandler: failureHandler) } public class func upload(_ presignedS3Request: KTPresignedS3Request, data: Data, withMimeType mimeType: String, successHandler: KTApiSuccessHandler?, failureHandler: KTApiFailureHandler?) { if presignedS3Request.fields != nil { let request: DataRequest = Alamofire.request(presignedS3Request.url, method: .post, headers: presignedS3Request.signedHeaders) Alamofire.upload(multipartFormData: { multipartFormData in for (name, value) in presignedS3Request.fields { let data = value.data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(data as Data, withName: name) } multipartFormData.append(data, withName: "file", fileName: "filename", mimeType: mimeType) }, with: request.request!, encodingCompletion: { encodingResult in switch encodingResult { case .success(let request, _, _): KTApiService.shared.execute(request as DataRequest, successHandler: successHandler, failureHandler: failureHandler) case .failure(let encodingError): logWarn("Multipart upload not attempted due to encoding error; \(encodingError)") } }) } else { let request: DataRequest = Alamofire.upload(data, to: presignedS3Request.url, method: .put, headers: presignedS3Request.signedHeaders) KTApiService.shared.execute(request, successHandler: successHandler, failureHandler: failureHandler) } } }
mit
ac1c03c96667b45f9ab8887e652e4cf4
49.571429
155
0.587571
5.521664
false
false
false
false
gjpc/ios-charts
Charts/Classes/Data/IndependentScatterChartData.swift
1
1506
// // ScatterChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // derived from ScatterChart by Gerard J. Cerchio // // 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 UIKit public class IndependentScatterChartData: BarLineScatterCandleBubbleChartData { public override init() { super.init() } public override init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } /// Returns the maximum shape-size across all DataSets. public func getGreatestShapeSize() -> CGFloat { var max = CGFloat(0.0) for set in _dataSets { let scatterDataSet = set as? IndependentScatterChartDataSet if (scatterDataSet == nil) { print("IndependentScatterChartData: Found a DataSet which is not a ScatterChartDataSet", terminator: "\n") } else { let size = scatterDataSet!.scatterShapeSize if (size > max) { max = size } } } return max } }
apache-2.0
41838050a5c3a003e66055af28e5c449
24.1
122
0.560425
4.842444
false
false
false
false
vapor/vapor
Sources/Vapor/Sessions/MemorySessions.swift
1
1805
/// Simple in-memory sessions implementation. public struct MemorySessions: SessionDriver { public let storage: Storage public final class Storage { public var sessions: [SessionID: SessionData] public let queue: DispatchQueue public init() { self.sessions = [:] self.queue = DispatchQueue(label: "MemorySessions.Storage") } } public init(storage: Storage) { self.storage = storage } public func createSession( _ data: SessionData, for request: Request ) -> EventLoopFuture<SessionID> { let sessionID = self.generateID() self.storage.queue.sync { self.storage.sessions[sessionID] = data } return request.eventLoop.makeSucceededFuture(sessionID) } public func readSession( _ sessionID: SessionID, for request: Request ) -> EventLoopFuture<SessionData?> { let session = self.storage.queue.sync { self.storage.sessions[sessionID] } return request.eventLoop.makeSucceededFuture(session) } public func updateSession( _ sessionID: SessionID, to data: SessionData, for request: Request ) -> EventLoopFuture<SessionID> { self.storage.queue.sync { self.storage.sessions[sessionID] = data } return request.eventLoop.makeSucceededFuture(sessionID) } public func deleteSession( _ sessionID: SessionID, for request: Request ) -> EventLoopFuture<Void> { self.storage.queue.sync { self.storage.sessions[sessionID] = nil } return request.eventLoop.makeSucceededFuture(()) } private func generateID() -> SessionID { return .init(string: [UInt8].random(count: 32).base64String()) } }
mit
d70b8f40fb98e6502a93fd56a7824439
30.666667
82
0.630471
4.878378
false
false
false
false
justinhester/hacking-with-swift
src/Project36/Project36/GameViewController.swift
1
1501
// // GameViewController.swift // Project36 // // Created by Justin Lawrence Hester on 2/26/16. // Copyright (c) 2016 Justin Lawrence Hester. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView let DEBUG = false skView.showsFPS = DEBUG skView.showsNodeCount = DEBUG skView.showsPhysics = DEBUG /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .ResizeFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
gpl-3.0
a1d9c5353ac18d72a66dcaf3cb461e5b
26.290909
94
0.603598
5.579926
false
false
false
false
NocturneZX/TTT-Pre-Internship-Exercises
Swift/CameraAppSwift/CameraAppSwift/ViewController.swift
1
3471
// // ViewController.swift // CameraAppSwift // // Created by Julio Reyes on 3/12/15. // Copyright (c) 2015 Julio Reyes. All rights reserved. // import UIKit import MobileCoreServices class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate { var pop:UIPopoverController? @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func TakePhoto(sender: AnyObject){ var imagePicker = UIImagePickerController() imagePicker.delegate = self; imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.mediaTypes = NSArray(object: kUTTypeImage); imagePicker.allowsEditing = false; if(UIDevice.currentDevice().userInterfaceIdiom == .Phone) { self.presentViewController(imagePicker, animated: true, completion: nil) }else{ pop = UIPopoverController(contentViewController: imagePicker); pop!.contentViewController = imagePicker; pop!.delegate = self pop!.contentViewController = imagePicker pop!.delegate = self; pop!.presentPopoverFromBarButtonItem(sender as UIBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true); } } //MARK - Image Pricker Delegate // The picker does not dismiss itself; the client dismisses it in these callbacks. // The delegate will receive one or the other, but not both, depending whether the user // confirms or cancels. func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){ println("i've got an image"); if(UIDevice.currentDevice().userInterfaceIdiom == .Phone) { self.imageView.image = image; self.dismissViewControllerAnimated(true, completion: nil) }else{ self.imageView.image = image; pop?.dismissPopoverAnimated(true); } // } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){ if(UIDevice.currentDevice().userInterfaceIdiom == .Phone) { self.imageView.image = (info[UIImagePickerControllerOriginalImage] as UIImage); self.dismissViewControllerAnimated(true, completion: nil) }else{ self.imageView.image = (info[UIImagePickerControllerOriginalImage] as UIImage); pop?.dismissPopoverAnimated(true); } } func imagePickerControllerDidCancel(picker: UIImagePickerController){ if(UIDevice.currentDevice().userInterfaceIdiom == .Phone) { self.dismissViewControllerAnimated(true, completion: nil) }else{ pop?.dismissPopoverAnimated(true); } } }
gpl-2.0
09345bee6b4cfb5b1e4482d8989fb008
34.783505
146
0.634976
6.089474
false
false
false
false
korrolion/smartrate
SmartRate/Classes/SMTriggerCounterType.swift
1
1428
// // SMTriggerCounterType.swift // Pods // // Created by Igor Korolev on 17.07.17. // // Should count one type of event and will fire after n times import Foundation public class SMTriggerCounterType: SMTrigger { //MARK: - Public public init(notificationName: NSNotification.Name, repeatTimes: Int, uniqName: String) { self.notificationName = notificationName self.counter = SMEventsCounter(key: uniqName) self.repeatTimes = repeatTimes super.init() startObserving() } //MARK: - Private private var notificationName: NSNotification.Name private var counter: SMEventsCounter private var observer: NSObjectProtocol? private var repeatTimes: Int deinit { if observer != nil { NotificationCenter.default.removeObserver(observer!) observer = nil } } private func startObserving() { if observer != nil { return } observer = NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: nil, using: { [weak self] (notification) in self?.handleNotification(notification) }) } private func handleNotification(_ notification: Notification) { if counter.increment() >= repeatTimes, fire() { counter.reset() } } }
mit
aff86c90835b98ae1f460313766ff0ee
24.052632
148
0.611345
5.010526
false
false
false
false
SwipeCellKit/SwipeCellKit
Source/SwipeAction.swift
10
4939
// // SwipeAction.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit /// Constants that help define the appearance of action buttons. public enum SwipeActionStyle: Int { /// Apply a style that reflects standard non-destructive actions. case `default` /// Apply a style that reflects destructive actions. case destructive } /** The `SwipeAction` object defines a single action to present when the user swipes horizontally in a table/collection item. This class lets you define one or more custom actions to display for a given item in your table/collection. Each instance of this class represents a single action to perform and includes the text, formatting information, and behavior for the corresponding button. */ public class SwipeAction: NSObject { /// An optional unique action identifier. public var identifier: String? /// The title of the action button. /// /// - note: You must specify a title or an image. public var title: String? /// The style applied to the action button. public var style: SwipeActionStyle /// The object that is notified as transitioning occurs. public var transitionDelegate: SwipeActionTransitioning? /// The font to use for the title of the action button. /// /// - note: If you do not specify a font, a 15pt system font is used. public var font: UIFont? /// The text color of the action button. /// /// - note: If you do not specify a color, white is used. public var textColor: UIColor? /// The highlighted text color of the action button. /// /// - note: If you do not specify a color, `textColor` is used. public var highlightedTextColor: UIColor? /// The image used for the action button. /// /// - note: You must specify a title or an image. public var image: UIImage? /// The highlighted image used for the action button. /// /// - note: If you do not specify a highlight image, the default `image` is used for the highlighted state. public var highlightedImage: UIImage? /// The closure to execute when the user taps the button associated with this action. public var handler: ((SwipeAction, IndexPath) -> Void)? /// The background color of the action button. /// /// - note: Use this property to specify the background color for your button. If you do not specify a value for this property, the framework assigns a default color based on the value in the style property. public var backgroundColor: UIColor? /// The highlighted background color of the action button. /// /// - note: Use this property to specify the highlighted background color for your button. public var highlightedBackgroundColor: UIColor? /// The visual effect to apply to the action button. /// /// - note: Assigning a visual effect object to this property adds that effect to the background of the action button. public var backgroundEffect: UIVisualEffect? /// A Boolean value that determines whether the actions menu is automatically hidden upon selection. /// /// - note: When set to `true`, the actions menu is automatically hidden when the action is selected. The default value is `false`. public var hidesWhenSelected = false /** Constructs a new `SwipeAction` instance. - parameter style: The style of the action button. - parameter title: The title of the action button. - parameter handler: The closure to execute when the user taps the button associated with this action. */ public init(style: SwipeActionStyle, title: String?, handler: ((SwipeAction, IndexPath) -> Void)?) { self.title = title self.style = style self.handler = handler } /** Calling this method performs the configured expansion completion animation including deletion, if necessary. Calling this method more than once has no effect. You should only call this method from the implementation of your action `handler` method. - parameter style: The desired style for completing the expansion action. */ public func fulfill(with style: ExpansionFulfillmentStyle) { completionHandler?(style) } // MARK: - Internal internal var completionHandler: ((ExpansionFulfillmentStyle) -> Void)? } /// Describes how expansion should be resolved once the action has been fulfilled. public enum ExpansionFulfillmentStyle { /// Implies the item will be deleted upon action fulfillment. case delete /// Implies the item will be reset and the actions view hidden upon action fulfillment. case reset } // MARK: - Internal internal extension SwipeAction { var hasBackgroundColor: Bool { return backgroundColor != .clear && backgroundEffect == nil } }
mit
5b233e412b98715db29756b7362356fc
36.694656
264
0.692183
4.987879
false
false
false
false
rmalabuyoc/treehouse-tracks
ios-development-with-swift/Computed-Properties.playground/Contents.swift
1
1227
//: Playground - noun: a place where people can play import UIKit class Product { var title: String var price: Double init(title: String, price: Double) { self.title = title self.price = price } func discountedPrice(percentage: Double) -> Double { return price - (price * percentage / 100) } } class Furniture: Product { // stored properties var height: Double var width: Double var length: Double // computed property; not a stored property var surfaceArea: Double { get { return length * width } set { length = sqrt(newValue) width = sqrt(newValue) } } // Designated initializer init(title: String, price: Double, height: Double, width: Double, length: Double) { self.height = height self.width = width self.length = length super.init(title: title, price: price) } } class Electronic: Product { var batteries: Bool? // Optional property } let table = Furniture(title: "Coffee Table", price: 300, height: 5, width: 10, length: 10) table.surfaceArea = 144 table.length table.width table.surfaceArea
mit
c366e3d2d64cc0d3a4809fd04f252f95
19.813559
90
0.599837
4.09
false
false
false
false
mike4aday/SwiftlySalesforce
Sources/SwiftlySalesforce/Extensions/URLRequest+OAuth.swift
1
1676
import Foundation extension URLRequest { static func refreshTokenFlow(host: String, clientID: String, refreshToken: String) throws -> Self { guard let url = URL(string: "https://\(host)/services/oauth2/token") else { throw URLError(.badURL) } var req = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData) req.httpMethod = HTTP.Method.post let params: [String: String] = [ "format" : "urlencoded", "grant_type": "refresh_token", "client_id": clientID, "refresh_token": refreshToken] guard let body = String(byPercentEncoding: params)?.data(using: .utf8) else { throw RequestError("Failed to create refresh token flow request") } req.httpBody = body req.setValue(HTTP.MIMEType.formUrlEncoded, forHTTPHeaderField: HTTP.Header.contentType) return req } static func revokeTokenFlow(host: String, token: String) throws -> Self { guard let url = URL(string: "https://\(host)/services/oauth2/revoke") else { throw URLError(.badURL) } var req = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData) req.httpMethod = HTTP.Method.post let params: [String: String] = ["token" : token] guard let body = String(byPercentEncoding: params)?.data(using: .utf8) else { throw RequestError("Failed to create revoke token flow request") } req.httpBody = body req.setValue(HTTP.MIMEType.formUrlEncoded, forHTTPHeaderField: HTTP.Header.contentType) return req } }
mit
cf588804406a8cc8db2f5c80e1649562
37.090909
103
0.614558
4.642659
false
false
false
false
jaksatomovic/Snapgram
Snapgram/editVC.swift
1
10537
// // editVC.swift // Snapgram // // Created by Jaksa Tomovic on 28/11/16. // Copyright © 2016 Jaksa Tomovic. All rights reserved. // import UIKit import Parse class editVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // UI objects @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var avaImg: UIImageView! @IBOutlet weak var fullnameTxt: UITextField! @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var webTxt: UITextField! @IBOutlet weak var bioTxt: UITextView! @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var telTxt: UITextField! @IBOutlet weak var genderTxt: UITextField! // pickerView & pickerData var genderPicker : UIPickerView! let genders = ["male","female"] // value to hold keyboard frmae size var keyboard = CGRect() // default func override func viewDidLoad() { super.viewDidLoad() // create picker genderPicker = UIPickerView() genderPicker.dataSource = self genderPicker.delegate = self genderPicker.backgroundColor = UIColor.groupTableViewBackground genderPicker.showsSelectionIndicator = true genderTxt.inputView = genderPicker // check notifications of keyboard - shown or not NotificationCenter.default.addObserver(self, selector: #selector(editVC.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(editVC.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // tap to hide keyboard let hideTap = UITapGestureRecognizer(target: self, action: #selector(editVC.hideKeyboard)) hideTap.numberOfTapsRequired = 1 self.view.isUserInteractionEnabled = true self.view.addGestureRecognizer(hideTap) // tap to choose image let avaTap = UITapGestureRecognizer(target: self, action: #selector(editVC.loadImg(_:))) avaTap.numberOfTapsRequired = 1 avaImg.isUserInteractionEnabled = true avaImg.addGestureRecognizer(avaTap) // call alignment function alignment() // call information function information() } // func to hide keyboard func hideKeyboard() { self.view.endEditing(true) } // func when keyboard is shown func keyboardWillShow(_ notification: Notification) { // define keyboard frame size keyboard = (((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue)! // move up with animation UIView.animate(withDuration: 0.4, animations: { () -> Void in self.scrollView.contentSize.height = self.view.frame.size.height + self.keyboard.height / 2 }) } // func when keyboard is hidden func keyboardWillHide(_ notification: Notification) { // move down with animation UIView.animate(withDuration: 0.4, animations: { () -> Void in self.scrollView.contentSize.height = 0 }) } // func to call UIImagePickerController func loadImg (_ recognizer : UITapGestureRecognizer) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary picker.allowsEditing = true present(picker, animated: true, completion: nil) } // method to finilize our actions with UIImagePickerController func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage self.dismiss(animated: true, completion: nil) } // alignment function func alignment() { let width = self.view.frame.size.width let height = self.view.frame.size.height scrollView.frame = CGRect(x: 0, y: 0, width: width, height: height) avaImg.frame = CGRect(x: width - 68 - 10, y: 15, width: 68, height: 68) avaImg.layer.cornerRadius = avaImg.frame.size.width / 2 avaImg.clipsToBounds = true fullnameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y, width: width - avaImg.frame.size.width - 30, height: 30) usernameTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: width - avaImg.frame.size.width - 30, height: 30) webTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: width - 20, height: 30) bioTxt.frame = CGRect(x: 10, y: webTxt.frame.origin.y + 40, width: width - 20, height: 60) bioTxt.layer.borderWidth = 1 bioTxt.layer.borderColor = UIColor(red: 230 / 255.5, green: 230 / 255.5, blue: 230 / 255.5, alpha: 1).cgColor bioTxt.layer.cornerRadius = bioTxt.frame.size.width / 50 bioTxt.clipsToBounds = true emailTxt.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 100, width: width - 20, height: 30) telTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: width - 20, height: 30) genderTxt.frame = CGRect(x: 10, y: telTxt.frame.origin.y + 40, width: width - 20, height: 30) titleLbl.frame = CGRect(x: 15, y: emailTxt.frame.origin.y - 30, width: width - 20, height: 30) } // user information function func information() { // receive profile picture let ava = PFUser.current()?.object(forKey: "ava") as! PFFile ava.getDataInBackground { (data, error) -> Void in self.avaImg.image = UIImage(data: data!) } // receive text information usernameTxt.text = PFUser.current()?.username fullnameTxt.text = PFUser.current()?.object(forKey: "fullname") as? String bioTxt.text = PFUser.current()?.object(forKey: "bio") as? String webTxt.text = PFUser.current()?.object(forKey: "web") as? String emailTxt.text = PFUser.current()?.email telTxt.text = PFUser.current()?.object(forKey: "tel") as? String genderTxt.text = PFUser.current()?.object(forKey: "gender") as? String } // regex restrictions for email textfield func validateEmail (_ email : String) -> Bool { let regex = "[A-Z0-9a-z._%+-]{4}+@[A-Za-z0-9.-]+\\.[A-Za-z]{2}" let range = email.range(of: regex, options: .regularExpression) let result = range != nil ? true : false return result } // regex restrictions for web textfield func validateWeb (_ web : String) -> Bool { let regex = "www.+[A-Z0-9a-z._%+-]+.[A-Za-z]{2}" let range = web.range(of: regex, options: .regularExpression) let result = range != nil ? true : false return result } // alert message function func alert (_ error: String, message : String) { let alert = UIAlertController(title: error, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } // clicked save button @IBAction func save_clicked(_ sender: AnyObject) { // if incorrect email according to regex if !validateEmail(emailTxt.text!) { alert("Incorrect email", message: "please provide correct email address") return } // if incorrect weblink according to regex if !validateWeb(webTxt.text!) { alert("Incorrect web-link", message: "please provide correct website") return } // save filled in information let user = PFUser.current()! user.username = usernameTxt.text?.lowercased() user.email = emailTxt.text?.lowercased() user["fullname"] = fullnameTxt.text?.lowercased() user["web"] = webTxt.text?.lowercased() user["bio"] = bioTxt.text // if "tel" is empty, send empty data, else entered data if telTxt.text!.isEmpty { user["tel"] = "" } else { user["tel"] = telTxt.text } // if "gender" is empty, send empty data, else entered data if genderTxt.text!.isEmpty { user["gender"] = "" } else { user["gender"] = genderTxt.text } // send profile picture let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5) let avaFile = PFFile(name: "ava.jpg", data: avaData!) user["ava"] = avaFile // send filled information to server user.saveInBackground (block: { (success, error) -> Void in if success{ // hide keyboard self.view.endEditing(true) // dismiss editVC self.dismiss(animated: true, completion: nil) // send notification to homeVC to be reloaded NotificationCenter.default.post(name: Notification.Name(rawValue: "reload"), object: nil) } else { print(error!.localizedDescription) } }) } // clicked cancel button @IBAction func cancel_clicked(_ sender: AnyObject) { self.view.endEditing(true) self.dismiss(animated: true, completion: nil) } // PICKER VIEW METHODS // picker comp numb func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // picker text numb func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return genders.count } // picker text config func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return genders[row] } // picker did selected some value from it func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { genderTxt.text = genders[row] self.view.endEditing(true) } }
mit
47eba6d60d741b8437a24839ef5548c0
35.206186
161
0.60839
4.672284
false
false
false
false
kzin/swift-testing
swift-testing/Pods/Mockingjay/Mockingjay/MockingjayProtocol.swift
3
5999
// // MockingjayProtocol.swift // Mockingjay // // Created by Kyle Fuller on 28/02/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation /// Structure representing a registered stub public struct Stub : Equatable { let matcher:Matcher let builder:Builder let uuid:UUID init(matcher:@escaping Matcher, builder:@escaping Builder) { self.matcher = matcher self.builder = builder uuid = UUID() } } public func ==(lhs:Stub, rhs:Stub) -> Bool { return lhs.uuid == rhs.uuid } var stubs = [Stub]() var registered: Bool = false public class MockingjayProtocol: URLProtocol { // MARK: Stubs fileprivate var enableDownloading = true fileprivate let operationQueue = OperationQueue() class func addStub(_ stub:Stub) -> Stub { stubs.append(stub) if !registered { URLProtocol.registerClass(MockingjayProtocol.self) } return stub } /// Register a matcher and a builder as a new stub @discardableResult open class func addStub(matcher: @escaping Matcher, builder: @escaping Builder) -> Stub { return addStub(Stub(matcher: matcher, builder: builder)) } /// Unregister the given stub open class func removeStub(_ stub:Stub) { if let index = stubs.index(of: stub) { stubs.remove(at: index) } } /// Remove all registered stubs open class func removeAllStubs() { stubs.removeAll(keepingCapacity: false) } /// Finds the appropriate stub for a request /// This method searches backwards though the registered requests /// to find the last registered stub that handles the request. class func stubForRequest(_ request:URLRequest) -> Stub? { for stub in stubs.reversed() { if stub.matcher(request) { return stub } } return nil } // MARK: NSURLProtocol /// Returns whether there is a registered stub handler for the given request. override open class func canInit(with request:URLRequest) -> Bool { return stubForRequest(request) != nil } override open class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override open func startLoading() { if let stub = MockingjayProtocol.stubForRequest(request) { switch stub.builder(request) { case .failure(let error): client?.urlProtocol(self, didFailWithError: error) case .success(var response, let download): let headers = self.request.allHTTPHeaderFields switch(download) { case .content(var data): applyRangeFromHTTPHeaders(headers, toData: &data, andUpdateResponse: &response) client?.urlProtocol(self, didLoad: data) client?.urlProtocolDidFinishLoading(self) case .streamContent(data: var data, inChunksOf: let bytes): applyRangeFromHTTPHeaders(headers, toData: &data, andUpdateResponse: &response) self.download(data, inChunksOfBytes: bytes) return case .noContent: client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocolDidFinishLoading(self) } } } else { let error = NSError(domain: NSExceptionName.internalInconsistencyException.rawValue, code: 0, userInfo: [ NSLocalizedDescriptionKey: "Handling request without a matching stub." ]) client?.urlProtocol(self, didFailWithError: error) } } override open func stopLoading() { self.enableDownloading = false self.operationQueue.cancelAllOperations() } // MARK: Private Methods fileprivate func download(_ data:Data?, inChunksOfBytes bytes:Int) { guard let data = data else { client?.urlProtocolDidFinishLoading(self) return } self.operationQueue.maxConcurrentOperationCount = 1 self.operationQueue.addOperation { () -> Void in self.download(data, fromOffset: 0, withMaxLength: bytes) } } fileprivate func download(_ data:Data, fromOffset offset:Int, withMaxLength maxLength:Int) { guard let queue = OperationQueue.current else { return } guard (offset < data.count) else { client?.urlProtocolDidFinishLoading(self) return } let length = min(data.count - offset, maxLength) queue.addOperation { () -> Void in guard self.enableDownloading else { self.enableDownloading = true return } let subdata = data.subdata(in: offset ..< (offset + length)) self.client?.urlProtocol(self, didLoad: subdata) Thread.sleep(forTimeInterval: 0.01) self.download(data, fromOffset: offset + length, withMaxLength: maxLength) } } fileprivate func extractRangeFromHTTPHeaders(_ headers:[String : String]?) -> Range<Int>? { guard let rangeStr = headers?["Range"] else { return nil } let range = rangeStr.components(separatedBy: "=")[1].components(separatedBy: "-").map({ (str) -> Int in Int(str)! }) let loc = range[0] let length = range[1] + 1 return loc ..< length } fileprivate func applyRangeFromHTTPHeaders( _ headers:[String : String]?, toData data:inout Data, andUpdateResponse response:inout URLResponse) { guard let range = extractRangeFromHTTPHeaders(headers) else { client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) return } let fullLength = data.count data = data.subdata(in: range) //Attach new headers to response if let r = response as? HTTPURLResponse { var header = r.allHeaderFields as! [String:String] header["Content-Length"] = String(data.count) header["Content-Range"] = "bytes \(range.lowerBound)-\(range.upperBound)/\(fullLength)" response = HTTPURLResponse(url: r.url!, statusCode: r.statusCode, httpVersion: nil, headerFields: header)! } client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } }
mit
3ae0e34a8f9e65e332bc04c9560b70c3
30.082902
185
0.669445
4.589901
false
false
false
false
byule/TravisExamples
ExampleApp/RootViewController.swift
1
4883
// // RootViewController.swift // ExampleApp // // Created by Benjamin Yule on 10/11/15. // Copyright © 2015 Spire, Inc. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds if UIDevice.currentDevice().userInterfaceIdiom == .Pad { pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0) } self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) { // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here. let currentViewController = self.pageViewController!.viewControllers![0] let viewControllers = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController var viewControllers: [UIViewController] let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController) if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) { let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController) viewControllers = [currentViewController, nextViewController!] } else { let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController) viewControllers = [previousViewController!, currentViewController] } self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) return .Mid } }
mit
c083379418a51f59289f6742eb2d02c6
51.494624
333
0.733306
5.903265
false
false
false
false
Mazy-ma/DemoBySwift
NewsFrameworkDemo/NewsFrameworkDemo/NewsFramework/TitleViewProperty.swift
1
1009
// // CustomProperty.swift // NewsFrameworkDemo // // Created by Mazy on 2017/7/26. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class TitleViewProperty { /// 是否是滚动的Title var isScrollEnable : Bool = false /// 普通Title颜色 var normalColor : UIColor = UIColor.darkGray /// 选中Title颜色 var selectedColor : UIColor = UIColor.red /// Title字体大小 var font : UIFont = UIFont.systemFont(ofSize: 14.0) /// 滚动Title的字体间距 var titleMargin : CGFloat = 20 /// title的高度 var titleHeight : CGFloat = 44 /// 是否显示底部滚动条 var isHiddenBottomLine : Bool = false /// 底部滚动条的颜色 var bottomLineColor : UIColor = UIColor.red /// 底部滚动条的高度 var bottomLineH : CGFloat = 2 /// contentView 切换动画 var contentOffsetAnimated: Bool = true /// titleView 是否需要阴影 var isNeedShadowInBottom: Bool = false }
apache-2.0
488e3b6a7f8a282be72c1c1b8574b98d
22.783784
55
0.646591
4.190476
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Core/_Extensions/_Foundation/Sequence+Utils.swift
1
4399
// // Sequence+Utils.swift // APExtensions // // Created by Anton Plebanovich on 8/4/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import Foundation // ******************************* MARK: - As public extension Sequence { /// Returns `self` as `Array`. var asArray: [Element] { if let array = self as? [Element] { return array } else { return Array(self) } } } // ******************************* MARK: - Splitting public extension Sequence { func splitBefore(separator isSeparator: (Iterator.Element) -> Bool) -> [AnySequence<Iterator.Element>] { var result: [AnySequence<Iterator.Element>] = [] var subSequence: [Iterator.Element] = [] var iterator = makeIterator() while let element = iterator.next() { if isSeparator(element) { if !subSequence.isEmpty { result.append(AnySequence(subSequence)) } subSequence = [element] } else { subSequence.append(element) } } result.append(AnySequence(subSequence)) return result } } // ******************************* MARK: - Equatable public extension Sequence where Element: Equatable { /// Returns whether collection has at least one common element with passed array. @inlinable func hasIntersection(with array: [Element]) -> Bool { return contains { array.contains($0) } } /// Returns intersection array. @inlinable func intersection(with array: [Element]) -> [Element] { return filter { array.contains($0) } } /// Helper method to filter out duplicates @inlinable func filterDuplicates() -> [Element] { return filterDuplicates { $0 == $1 } } } // ******************************* MARK: - Hashable public extension Sequence where Element: Hashable { /// Fast method to get unique values without keeping an order. /// - note: It's ~1000 times faster than `filterDuplicates()` for 10000 items sequence. @inlinable func uniqueUnordered() -> [Element] { return Array(Set(self)) } } // ******************************* MARK: - Scripting public extension Sequence { @inlinable func count(where isIncluded: (Element) throws -> Bool) rethrows -> Int { try filter(isIncluded).count } /// Helper method to filter out duplicates. Element will be filtered out if closure return true. @inlinable func filterDuplicates(_ isDuplicate: (_ lhs: Element, _ rhs: Element) throws -> Bool) rethrows -> [Element] { var results = [Element]() try forEach { element in let duplicate = try results.contains { return try isDuplicate(element, $0) } if !duplicate { results.append(element) } } return results } /// Transforms an array to a dictionary using array elements as values and transform result as keys. @inlinable func dictionaryMapKeys<T>(_ transform: (_ element: Iterator.Element) throws -> T?) rethrows -> [T: Iterator.Element] { return try self.reduce(into: [T: Iterator.Element]()) { dictionary, element in guard let key = try transform(element) else { return } dictionary[key] = element } } /// Transforms an array to a dictionary using array elements as keys and transform result as values. @inlinable func dictionaryMapValues<T>(_ transform: (_ element: Iterator.Element) throws -> T?) rethrows -> [Iterator.Element: T] { return try self.reduce(into: [Iterator.Element: T]()) { dictionary, element in guard let value = try transform(element) else { return } dictionary[element] = value } } } // ******************************* MARK: - Operations public extension Sequence where Element: BinaryFloatingPoint { /// Returns averge value of all elements in a sequence. func average() -> Element? { var i: Element = 0 var total: Element = 0 for value in self { total = total + value i += 1 } if i == 0 { return nil } else { return total / i } } }
mit
b3a43a620a92003096b53461f52201c8
30.191489
135
0.561164
4.886667
false
false
false
false
Mazy-ma/DemoBySwift
PullToRefresh/PullToRefresh/PullToRefresh/RefreshFooterView.swift
1
7114
// // RefreshFooterView.swift // PullToRefresh // // Created by Mazy on 2017/12/5. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class RefreshFooterView: RefreshBaseView { /// 保存cell的总个数 private var lastRefreshCount:Int = 0 /// 状态改变时就调用 override var State : RefreshState { willSet { oldState = self.State } didSet { switch self.State { // 普通状态 case .normal: if (oldState == .refreshing) { self.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { self.scrollView.contentInset.bottom = self.scrollViewOriginalInset.bottom }) } else { UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { self.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)); }) } let deltaH : CGFloat = self.heightForContentBreakView() let currentCount : Int = self.totalDataCountInScrollView() if (oldState == .refreshing && deltaH > 0 && currentCount != self.lastRefreshCount) { var offset:CGPoint = self.scrollView.contentOffset; offset.y = self.scrollView.contentOffset.y self.scrollView.contentOffset = offset; } // 释放加载更多 case .pulling: UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { self.arrowImage.transform = CGAffineTransform.identity }) // 正在加载更多 case .refreshing: self.lastRefreshCount = self.totalDataCountInScrollView(); UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { var bottom : CGFloat = self.height + self.scrollViewOriginalInset.bottom let deltaH : CGFloat = self.heightForContentBreakView() if deltaH < 0 { bottom = bottom - deltaH } var inset:UIEdgeInsets = self.scrollView.contentInset; inset.bottom = bottom; self.scrollView.contentInset = inset; }) case .refreshingNoData: // self.lastRefreshCount = self.totalDataCountInScrollView(); UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { var bottom : CGFloat = self.height + self.scrollViewOriginalInset.bottom let deltaH : CGFloat = self.heightForContentBreakView() if deltaH < 0 { bottom = bottom - deltaH } var inset:UIEdgeInsets = self.scrollView.contentInset; inset.bottom = bottom; self.scrollView.contentInset = inset; }) default: break; } } } override func willMove(toSuperview newSuperview: UIView!) { super.willMove(toSuperview: newSuperview) if let _superView = self.superview { _superView.removeObserver(self, forKeyPath: RefreshContentSize) } // 监听contentsize newSuperview.addObserver(self, forKeyPath: RefreshContentSize, options: NSKeyValueObservingOptions.new, context: nil) // 重新调整frame resetFrameWithContentSize() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard !self.isHidden else { return } // 这里分两种情况 1.contentSize 2.contentOffset if RefreshContentSize == keyPath { self.resetFrameWithContentSize() } else if RefreshContentOffset == keyPath { // 如果不是刷新状态 guard self.State != .refreshing else { return } let currentOffsetY : CGFloat = self.scrollView.contentOffset.y let happenOffsetY : CGFloat = self.happenOffsetX() if currentOffsetY <= happenOffsetY { return } if self.scrollView.isDragging { let normal2pullingOffsetY = happenOffsetY + self.frame.size.height if self.State == .normal && currentOffsetY > normal2pullingOffsetY { self.State = .pulling; } else if (self.State == .pulling && currentOffsetY <= normal2pullingOffsetY) { self.State = .normal; } } else if (self.State == .pulling) { self.State = .refreshing } } } /** 重新设置frame */ private func resetFrameWithContentSize() { let contentHeight:CGFloat = self.scrollView.contentSize.height let scrollHeight:CGFloat = self.scrollView.height - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom var rect:CGRect = self.frame rect.origin.y = contentHeight > scrollHeight ? contentHeight : scrollHeight self.frame = rect } private func heightForContentBreakView() -> CGFloat { let h:CGFloat = self.scrollView.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; return self.scrollView.contentSize.height - h; } private func happenOffsetX() -> CGFloat { let deltaH:CGFloat = self.heightForContentBreakView() if deltaH > 0 { return deltaH - self.scrollViewOriginalInset.top; } else { return -self.scrollViewOriginalInset.top; } } /// 获取cell的总个数 private func totalDataCountInScrollView() -> Int { var totalCount:Int = 0 if self.scrollView is UITableView { let tableView:UITableView = self.scrollView as! UITableView for i in 0 ..< tableView.numberOfSections { totalCount = totalCount + tableView.numberOfRows(inSection: i) } } else if self.scrollView is UICollectionView{ let collectionView:UICollectionView = self.scrollView as! UICollectionView for i in 0 ..< collectionView.numberOfSections { totalCount = totalCount + collectionView.numberOfItems(inSection: i) } } return totalCount } deinit { self.endRefreshing() } }
apache-2.0
064854d14750c4de337a8af14438fe06
36.778378
151
0.552869
5.627214
false
false
false
false
relayrides/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/VariantTweak.swift
1
5366
// // VariantTweak.swift // Mixpanel // // Created by Yarden Eitan on 9/28/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit class VariantTweak: NSObject, NSCoding { let name: String let encoding: String let value: AnyObject let type: String? convenience init?(JSONObject: [String: Any]?) { guard let object = JSONObject else { Logger.error(message: "variant action json object should not be nil") return nil } guard let name = object["name"] as? String else { Logger.error(message: "invalid tweak name") return nil } guard let encoding = object["encoding"] as? String else { Logger.error(message: "invalid tweak encoding") return nil } guard let type = object["type"] as? String else { Logger.error(message: "no type") return nil } guard let value = object["value"] else { Logger.error(message: "bad value") return nil } self.init(name: name, encoding: encoding, value: value as AnyObject, type: type) } init(name: String, encoding: String, value: AnyObject, type: String) { self.name = name self.encoding = encoding self.value = value self.type = type } func execute() { guard let tweak = MixpanelTweaks.defaultStore.tweakCollections["Mixpanel"]?.tweakGroups["Mixpanel"]?.tweaks[name] else { return } let currentViewData = MixpanelTweaks.defaultStore.currentViewDataForTweak(tweak) let tweakViewData = createViewDataType(value: value, viewData: currentViewData) MixpanelTweaks.defaultStore.setValue(tweakViewData, forTweak: tweak) } func createViewDataType(value: AnyObject, viewData: TweakViewData) -> TweakViewData { let (_, def, min, max) = viewData.getValueDefaultMinMax() if type == "number" { if let value = value as? Double, let def = def as? Double { return TweakViewData.doubleTweak(value: value, defaultValue: def, min: min as? Double, max: max as? Double, stepSize: 0) } else if let value = value as? CGFloat, let def = def as? CGFloat { return TweakViewData.float(value: value, defaultValue: def, min: min as? CGFloat, max: max as? CGFloat, stepSize: 0) } else if let value = value as? Int, let def = def as? Int { return TweakViewData.integer(value: value, defaultValue: def, min: min as? Int, max: max as? Int, stepSize: 0) } } else if type == "string" { if let value = value as? String, let def = def as? String { return TweakViewData.string(value: value, defaultValue: def) } } else { if let value = value as? Bool, let def = def as? Bool { return TweakViewData.boolean(value: value, defaultValue: def) } else if let value = value as? UIColor, let def = def as? UIColor { return TweakViewData.color(value: value, defaultValue: def) } } return TweakViewData.boolean(value: false, defaultValue: false) } func stop() { guard let tweak = MixpanelTweaks.defaultStore.tweakCollections["Mixpanel"]?.tweakGroups["Mixpanel"]?.tweaks[name] else { return } let currentViewData = MixpanelTweaks.defaultStore.currentViewDataForTweak(tweak) let value = currentViewData.getValueDefaultMinMax() MixpanelTweaks.defaultStore.setValue(createViewDataType(value: value.1 as AnyObject, viewData: currentViewData), forTweak: tweak) } required init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let encoding = aDecoder.decodeObject(forKey: "encoding") as? String, let type = aDecoder.decodeObject(forKey: "type") as? String, let value = aDecoder.decodeObject(forKey: "value") else { return nil } self.name = name self.encoding = encoding self.value = value as AnyObject self.type = type } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(encoding, forKey: "encoding") aCoder.encode(value, forKey: "value") aCoder.encode(type, forKey: "type") } override func isEqual(_ object: Any?) -> Bool { guard let object = object as? VariantTweak else { return false } if object === self { return true } else { return self.name == object.name } } override var hash: Int { return self.name.hash } } /// The MixpanelTweaks struct that needs to be extended to define new Tweaks for A/B testing public struct MixpanelTweaks: TweakLibraryType { /// The default store that holds the Tweaks public static var defaultStore: TweakStore = TweakStore(enabled: true) /** setTweaks needs to be called to add the defined Tweaks into the environment. - parameter tweaks: the tweaks to set */ public static func setTweaks(tweaks: [TweakClusterType]) { defaultStore.addTweaks(tweaks) } }
apache-2.0
5cb7de87e1cdf847e286aba599cfc5ee
34.296053
137
0.612488
4.444905
false
false
false
false
chien/CKImagePicker
CKImagePicker/Classes/CKImagePickerConfiguration.swift
1
2231
// // CKImagePickerConfiguration.swift // Pods // // Created by Cheng-chien Kuo on 6/5/16. // // extension UIImage { var uncompressedPNGData: NSData { return UIImagePNGRepresentation(self)! } var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! } var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)! } var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! } var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)! } var lowestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.0)! } } public class CKImagePickerConfiguration { public var font = UIFont.systemFontOfSize(16) public var textColor = UIColor.lightGrayColor() public var backgroundColor = UIColor.whiteColor() public var utilButtonBackgroundColor = UIColor.clearColor() public var tintColor = UIColor.orangeColor() public var menuButtonSize = CGFloat(30) public var menuButtonSpacing = CGFloat(2) public var imageFolderName = "default" public var cameraControlButtonSize = CGFloat(60) public var utilControlButtonSize = CGFloat(40) public var paddingSize = CGFloat(10) public var collectionViewImagePerRow = CGFloat(5) public var collectionViewLineSpacing = CGFloat(2) public var collectionViewCellSize: CGSize { let cellSize = (imageContainerSize-((collectionViewImagePerRow-1)*collectionViewLineSpacing))/CGFloat(collectionViewImagePerRow) return CGSize(width: cellSize, height: cellSize) } public var compressionRate = CGFloat(0.5) internal var menuSectionHeight: CGFloat { return menuButtonSize + 2*menuButtonSpacing } lazy internal var imageContainerSize: CGFloat = { return self.frame.width }() lazy internal var controllerContainerHeight: CGFloat = { return self.frame.height - self.imageContainerSize - self.menuSectionHeight }() internal let frame: CGRect! public enum MenuMode: Int { case Camera case Album } public init(frame: CGRect) { self.frame = frame } }
mit
6c88608cd5c569e2c3c76c7f60ff9fa0
33.859375
136
0.706858
4.777302
false
false
false
false
edx/edx-app-ios
Source/Registration Field Views/RegistrationFormFieldView.swift
1
10179
// // RegistrationFormFieldView.swift // edX // // Created by Muhammad Zeeshan Arif on 22/11/2017. // Copyright © 2017 edX. All rights reserved. // import UIKit class RegistrationFormFieldView: UIView { // MARK: - Configurations - private var textFieldHeight:CGFloat = 40.0 private var textViewHeight:CGFloat = 100.0 private var textInputViewHeight: CGFloat { return isInputTypeTextArea ? textViewHeight : textFieldHeight } // MARK: - Properties - let titleLabelStyle = OEXMutableTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBlack()) let instructionsLabelStyle = OEXMutableTextStyle(weight: .normal, size: .xxxSmall, color: OEXStyles.shared().neutralBlack()) let errorLabelStyle = OEXMutableTextStyle(weight: .normal, size: .xxxSmall, color: OEXStyles.shared().errorBase()) // This is to keep track of either user tapped out first time from the field or not // Show validation error first time on tap out and then while editing var tapout: Bool = false private var accessibilityIdPrefix: String { return "RegistrationFormFieldView:\(formField?.name ?? "")" } // MARK: - UI Properties - lazy private var textInputLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.isAccessibilityElement = false label.attributedText = self.isRequired ? self.titleLabelStyle.attributedString(withText: "\(self.formField?.label ?? "") \(Strings.asteric)") : self.titleLabelStyle.attributedString(withText: "\(self.formField?.label ?? "")") label.accessibilityIdentifier = "\(self.accessibilityIdPrefix)-text-input-label" return label }() // Used in child class @objc lazy var textInputField: LogistrationTextField = { let textField = LogistrationTextField() textField.defaultTextAttributes = OEXStyles.shared().textFieldStyle(with: .base, color: OEXStyles.shared().neutralBlack()).attributes.attributedKeyDictionary() textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.addTarget(self, action: #selector(RegistrationFormFieldView.valueDidChange), for: .editingChanged) textField.addTarget(self, action: #selector(RegistrationFormFieldView.editingDidEnd), for: .editingDidEnd) textField.accessibilityIdentifier = "\(accessibilityIdPrefix)-text-input-field" return textField }() lazy private var textInputArea: OEXPlaceholderTextView = { let textArea = OEXPlaceholderTextView() textArea.textContainer.lineFragmentPadding = 0.0 textArea.autocapitalizationType = .none textArea.applyStandardBorderStyle() textArea.backgroundColor = .clear textArea.accessibilityIdentifier = "\(self.accessibilityIdPrefix)-text-input-area" return textArea }() lazy private var errorLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.isAccessibilityElement = false label.accessibilityIdentifier = "\(self.accessibilityIdPrefix)-error-label" return label }() lazy private var instructionsLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.isAccessibilityElement = false label.attributedText = self.instructionsLabelStyle.attributedString(withText: self.formField?.instructions ?? "") label.accessibilityIdentifier = "\(self.accessibilityIdPrefix)-instructions-label" return label }() var textInputView: UIView { return isInputTypeTextArea ? textInputArea : textInputField } // Used in child class private(set) var formField: OEXRegistrationFormField? @objc var errorMessage: String? { didSet { errorLabel.attributedText = self.errorLabelStyle.attributedString(withText: errorMessage ?? "") refreshAccessibilty() } } var currentValue: String { let value = isInputTypeTextArea ? textInputArea.text : textInputField.text return value?.trimmingCharacters(in: NSCharacterSet.whitespaces) ?? "" } var isInputTypeTextArea: Bool { return formField?.fieldType ?? OEXRegistrationFieldTypeText == OEXRegistrationFieldTypeTextArea } var isRequired: Bool { return formField?.isRequired ?? false } var hasValue: Bool { return currentValue != "" } @objc var isValidInput: Bool { guard let errorMessage = validate() else { return true } self.errorMessage = errorMessage return false } // MARK: - Setup View - required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @objc init(with formField: OEXRegistrationFormField) { super.init(frame: CGRect.zero) self.formField = formField loadView() } // public method, can be inherited func loadView() { titleLabelStyle.lineBreakMode = .byWordWrapping instructionsLabelStyle.lineBreakMode = .byWordWrapping errorLabelStyle.lineBreakMode = .byWordWrapping addSubViews() refreshAccessibilty() } func refreshAccessibilty() { guard let formField = formField else { return } let errorAccessibility = errorMessage ?? "" != "" ? ",\(Strings.Accessibility.errorText), \(errorMessage ?? "")" : "" let requiredOrOptionalAccessibility = isRequired ? Strings.accessibilityRequiredInput : Strings.Accessibility.optionalInput textInputView.accessibilityLabel = formField.label textInputView.accessibilityHint = "\(requiredOrOptionalAccessibility),\(formField.instructions)\(errorAccessibility)" } func addSubViews() { // Add subviews addSubview(textInputLabel) addSubview(textInputView) addSubview(errorLabel) addSubview(instructionsLabel) setupConstraints() } func setupConstraints() { // Setup Constraints textInputLabel.snp.makeConstraints { make in make.top.equalTo(self) make.leading.equalTo(self).offset(StandardHorizontalMargin) make.trailing.equalTo(self).inset(StandardHorizontalMargin) } textInputView.snp.makeConstraints { make in make.leading.equalTo(textInputLabel) make.trailing.equalTo(textInputLabel) make.top.equalTo(textInputLabel.snp.bottom).offset(StandardVerticalMargin/2.0) make.height.equalTo(textInputViewHeight) } errorLabel.snp.makeConstraints { make in make.leading.equalTo(textInputLabel) make.trailing.equalTo(textInputLabel) make.top.equalTo(textInputView.snp.bottom).offset(StandardVerticalMargin/2.0) } instructionsLabel.snp.makeConstraints { make in make.leading.equalTo(textInputLabel) make.trailing.equalTo(textInputLabel) make.top.equalTo(errorLabel.snp.bottom).offset(StandardVerticalMargin/2.0) make.bottom.equalTo(self).inset(StandardVerticalMargin) } } override func layoutSubviews() { super.layoutSubviews() // Super View is not constraint base. Calculating superview height. let textInputLabelHeight = textInputLabel.sizeThatFits(CGSize(width: textInputView.frame.size.width, height: CGFloat.greatestFiniteMagnitude)).height let errorLabelHeight = errorLabel.sizeThatFits(CGSize(width: textInputView.frame.size.width, height: CGFloat.greatestFiniteMagnitude)).height let instructionLabelHeight = instructionsLabel.sizeThatFits(CGSize(width: textInputView.frame.size.width, height: CGFloat.greatestFiniteMagnitude)).height var height = textInputLabelHeight + errorLabelHeight + instructionLabelHeight + StandardVerticalMargin + (3.0 * StandardVerticalMargin/2.0) if let _ = formField { height += textInputViewHeight } var frame = self.frame frame.size.height = height self.frame = frame } @objc func setValue(_ value: String) { if isInputTypeTextArea { textInputArea.text = value } else { textInputField.text = value } } func clearError() { errorMessage = nil } @objc func valueDidChange(isPicker: Bool = false) { if !tapout && !isPicker { return } validateInput() } @objc private func editingDidEnd() { if tapout { return } tapout = true validateInput() } private func validateInput() { errorMessage = validate() NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: NOTIFICATION_REGISTRATION_FORM_FIELD_VALUE_DID_CHANGE))) } func validate() -> String? { guard let field = formField else { return nil } if isRequired && currentValue == "" { return field.errorMessage.required == "" ? Strings.registrationFieldEmptyError(fieldName: field.label) : field.errorMessage.required } let length = currentValue.count if length < field.restriction.minLength { return field.errorMessage.minLength == "" ? Strings.registrationFieldMinLengthError(fieldName: field.label, count: "\(field.restriction.minLength)")(field.restriction.minLength) : field.errorMessage.minLength } else if length > field.restriction.maxLength && field.restriction.maxLength != 0 { return field.errorMessage.maxLength == "" ? Strings.registrationFieldMaxLengthError(fieldName: field.label, count: "\(field.restriction.maxLength)")(field.restriction.maxLength): field.errorMessage.maxLength } switch field.fieldType { case OEXRegistrationFieldTypeEmail: if hasValue && !currentValue.isValidEmailAddress() { return Strings.ErrorMessage.invalidEmailFormat } break default: break } return nil } }
apache-2.0
afcf27f669bdeeea92ddda342d95c560
39.712
233
0.668795
5.235597
false
false
false
false
davecom/SwiftGraph
Sources/SwiftGraph/UnweightedGraph.swift
2
6378
// // UnweightedGraph.swift // SwiftGraph // // Copyright (c) 2014-2019 David Kopec // // 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. /// An implementation of Graph with some convenience methods for adding and removing UnweightedEdges. WeightedEdges may be added to an UnweightedGraph but their weights will be ignored. open class UnweightedGraph<V: Equatable & Codable>: Graph { public var vertices: [V] = [V]() public var edges: [[UnweightedEdge]] = [[UnweightedEdge]]() //adjacency lists public init() { } required public init(vertices: [V]) { for vertex in vertices { _ = self.addVertex(vertex) } } /// Add an edge to the graph. /// /// - parameter e: The edge to add. /// - parameter directed: If false, undirected edges are created. /// If true, a reversed edge is also created. /// Default is false. public func addEdge(_ e: UnweightedEdge, directed: Bool) { edges[e.u].append(e) if !directed && e.u != e.v { edges[e.v].append(e.reversed()) } } /// Add a vertex to the graph. /// /// - parameter v: The vertex to be added. /// - returns: The index where the vertex was added. public func addVertex(_ v: V) -> Int { vertices.append(v) edges.append([E]()) return vertices.count - 1 } } extension Graph where E == UnweightedEdge { /// Initialize an UnweightedGraph consisting of path. /// /// The resulting graph has the vertices in path and an edge between /// each pair of consecutive vertices in path. /// /// If path is an empty array, the resulting graph is the empty graph. /// If path is an array with a single vertex, the resulting graph has that vertex and no edges. /// /// - Parameters: /// - path: An array of vertices representing a path. /// - directed: If false, undirected edges are created. /// If true, edges are directed from vertex i to vertex i+1 in path. /// Default is false. public static func withPath(_ path: [V], directed: Bool = false) -> Self { let g = Self(vertices: path) guard path.count >= 2 else { return g } for i in 0..<path.count - 1 { g.addEdge(fromIndex: i, toIndex: i+1, directed: directed) } return g } /// Initialize an UnweightedGraph consisting of cycle. /// /// The resulting graph has the vertices in cycle and an edge between /// each pair of consecutive vertices in cycle, /// plus an edge between the last and the first vertices. /// /// If cycle is an empty array, the resulting graph is the empty graph. /// If cycle is an array with a single vertex, the resulting graph has the vertex /// and a single edge to itself if directed is true. /// If directed is false the resulting graph has the vertex and two edges to itself. /// /// - Parameters: /// - cycle: An array of vertices representing a cycle. /// - directed: If false, undirected edges are created. /// If true, edges are directed from vertex i to vertex i+1 in cycle. /// Default is false. public static func withCycle(_ cycle: [V], directed: Bool = false) -> Self { let g = Self.withPath(cycle, directed: directed) if cycle.count > 0 { g.addEdge(fromIndex: cycle.count-1, toIndex: 0, directed: directed) } return g } /// This is a convenience method that adds an unweighted edge. /// /// - parameter from: The starting vertex's index. /// - parameter to: The ending vertex's index. /// - parameter directed: Is the edge directed? (default `false`) public func addEdge(fromIndex: Int, toIndex: Int, directed: Bool = false) { addEdge(UnweightedEdge(u: fromIndex, v: toIndex, directed: directed), directed: directed) } /// This is a convenience method that adds an unweighted, undirected edge between the first occurence of two vertices. It takes O(n) time. /// /// - parameter from: The starting vertex. /// - parameter to: The ending vertex. /// - parameter directed: Is the edge directed? (default `false`) public func addEdge(from: V, to: V, directed: Bool = false) { if let u = indexOfVertex(from), let v = indexOfVertex(to) { addEdge(UnweightedEdge(u: u, v: v, directed: directed), directed: directed) } } /// Check whether there is an edge from one vertex to another vertex. /// /// - parameter from: The index of the starting vertex of the edge. /// - parameter to: The index of the ending vertex of the edge. /// - returns: True if there is an edge from the starting vertex to the ending vertex. public func edgeExists(fromIndex: Int, toIndex: Int) -> Bool { // The directed property of this fake edge is ignored, since it's not taken into account // for equality. return edgeExists(E(u: fromIndex, v: toIndex, directed: true)) } /// Check whether there is an edge from one vertex to another vertex. /// /// Note this will look at the first occurence of each vertex. /// Also returns false if either of the supplied vertices cannot be found in the graph. /// /// - parameter from: The starting vertex of the edge. /// - parameter to: The ending vertex of the edge. /// - returns: True if there is an edge from the starting vertex to the ending vertex. public func edgeExists(from: V, to: V) -> Bool { if let u = indexOfVertex(from) { if let v = indexOfVertex(to) { return edgeExists(fromIndex: u, toIndex: v) } } return false } }
apache-2.0
c70547da248cfa731194cf83470dbf4c
39.884615
185
0.623079
4.277666
false
false
false
false
OscarSwanros/swift
test/PlaygroundTransform/do-catch.swift
15
1644
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test func doSomething() throws -> Int { return 5 } do { try doSomething() } catch { print(error) } // CHECK: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit 1 try doSomething() // CHECK-LABEL: [{{.*}}] $builtin_log[='1'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] 2 try! doSomething() // CHECK-LABEL: [{{.*}}] $builtin_log[='2'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] 3 try? doSomething() // CHECK-LABEL: [{{.*}}] $builtin_log[='3'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[='Optional(5)']
apache-2.0
e070a5ea8a124e562e05fb4e9bdef1f6
34.73913
197
0.604015
3.16763
false
false
false
false
stephentyrone/swift
test/Driver/Dependencies/file-added-fine.swift
5
1386
/// other ==> main // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND-NOT: Handled // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./other.swift ./main.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD-NOT: Handled other.swift // CHECK-THIRD: Handled main.swift // CHECK-THIRD-NOT: Handled other.swift
apache-2.0
504d86093b77b2a078f2f492960d3e6a
68.3
356
0.733766
3.230769
false
false
true
false
Lyndir/STO-Planner
STO Planner/Language.swift
1
1322
// // Language.swift // STO Planner // // Created by Maarten Billemont on 2015-10-15. // Copyright © 2015 Maarten Billemont. All rights reserved. // import Foundation infix operator % { associativity left precedence 0 } func %(left: String, right: [CVarArgType]) -> String { return String( format: left, arguments: right ) } extension GeneratorType { public func at(index: Int) -> Self.Element? { var lastValue: Self.Element?, advancingSelf = self for (var current = index; current >= 0; --current) { lastValue = advancingSelf.next() if lastValue == nil { break } } return lastValue } } extension Indexable { func at(index: Index) -> Self._Element? { let fromStart = startIndex.distanceTo( index ) if fromStart < 0 { return nil } if fromStart >= startIndex.distanceTo( endIndex ) { return nil } return self[index] } } struct WeakReference<T> { private weak var _value: AnyObject? } extension WeakReference where T: AnyObject { init(_ value: T) { self.value = value } var value: T? { get { return _value as! T? } set { _value = newValue } } }
gpl-3.0
ecc4c9db739cd58572af70a263cb8207
19.640625
60
0.557154
4.089783
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Extensions/UIKit/UIScreen+CSExtension.swift
1
1577
// // UIScreen.swift // Renetik // // Created by Rene Dohan on 8/24/19. // import Foundation import UIKit public extension UIScreen { public class var size: CGSize { main.bounds.size } public class var width: CGFloat { size.width } public class var height: CGFloat { size.height } public class var maxLength: CGFloat { max(width, height) } public class var minLength: CGFloat { min(width, height) } public class var isZoomed: Bool { main.nativeScale >= main.scale } public class var isRetina: Bool { main.scale >= 2.0 } public class var orientation: UIInterfaceOrientation { delegate.window?.rootViewController?.get { $0.interfaceOrientation } ?? UIApplication.shared.statusBarOrientation } public class var isPortrait: Bool { orientation.isPortrait } public class var isLandscape: Bool { !isPortrait } public class var isThin: Bool { isPortrait && UIDevice.isPhone } public class var isUltraThin: Bool { isPortrait && UIScreen.width <= 375 } public class var isWide: Bool { !isThin } public class var isUltraWide: Bool { UIDevice.isTablet && isLandscape } public class var isShort: Bool { isLandscape && UIDevice.isPhone } public class var isUltraShort: Bool { isLandscape && isSmallPhone } public class var isTall: Bool { !isShort } // tablet || portrait public class var isUltraTall: Bool { UIDevice.isTablet || !isSmallPhone && isPortrait } public class var isSmallPhone: Bool { (UIDevice.typeIsLike == .iphone4 || UIDevice.typeIsLike == .iphone5) } }
mit
024cbf9006dc07137019b67df41080c1
42.805556
91
0.69499
4.356354
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/Logic/Request/CIOSearchQuery.swift
1
4078
// // CIOSearchQuery.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating the necessary and additional parameters required to execute a search query. */ public struct CIOSearchQuery: CIORequestData { /** The user typed query to return results for */ public let query: String /** The filters used to refine results */ public let filters: CIOQueryFilters? /** The page number of the results */ public let page: Int /** The number of results per page to return */ public let perPage: Int /** The sort method/order for results */ public let sortOption: CIOSortOption? /** The section to return results from */ public let section: String /** The list of hidden metadata fields to return */ public let hiddenFields: [String]? /** The list of hidden facet fields to return */ public let hiddenFacets: [String]? /** The variation map to use with the result set */ var variationsMap: CIOQueryVariationsMap? /** The sort method/order for groups */ public let groupsSortOption: CIOGroupsSortOption? func url(with baseURL: String) -> String { return String(format: Constants.SearchQuery.format, baseURL, query) } /** Create a Search request query object - Parameters: - query: The user typed query to return results for - filters: The filters used to refine results - page: The page number of the results - perPage: The number of results per page to return - sortOption: The sort method/order for results - section: The section to return results from - hiddenFields: The list of hidden metadata fields to return - hiddenFacets: The list of hidden facest to return - groupsSortOption: The sort method/order for groups ### Usage Example: ### ``` let facetFilters = [(key: "Nutrition", value: "Organic"), (key: "Nutrition", value: "Natural"), (key: "Brand", value: "Kraft Foods")] let searchQuery = CIOSearchQuery(query: "red", filters: CIOQueryFilters(groupFilter: nil, facetFilters: facetFilters), page: 1, perPage: 30, section: "Products", hiddenFields: ["price_CA", "currency_CA"], hiddenFacets: ["brand", "price_CA"]) ``` */ public init(query: String, filters: CIOQueryFilters? = nil, sortOption: CIOSortOption? = nil, page: Int? = nil, perPage: Int? = nil, section: String? = nil, hiddenFields: [String]? = nil, hiddenFacets: [String]? = nil, groupsSortOption: CIOGroupsSortOption? = nil, variationsMap: CIOQueryVariationsMap? = nil) { self.query = query.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)! self.filters = filters self.page = page != nil ? page! : Constants.SearchQuery.defaultPage self.perPage = perPage != nil ? perPage! : Constants.SearchQuery.defaultPerPage self.section = section != nil ? section! : Constants.SearchQuery.defaultSectionName self.sortOption = sortOption self.hiddenFields = hiddenFields self.hiddenFacets = hiddenFacets self.variationsMap = variationsMap self.groupsSortOption = groupsSortOption } func decorateRequest(requestBuilder: RequestBuilder) { requestBuilder.set(page: self.page) requestBuilder.set(perPage: self.perPage) requestBuilder.set(groupFilter: self.filters?.groupFilter) requestBuilder.set(facetFilters: self.filters?.facetFilters) requestBuilder.set(searchSection: self.section) requestBuilder.set(sortOption: self.sortOption) requestBuilder.set(hiddenFields: self.hiddenFields) requestBuilder.set(hiddenFacets: self.hiddenFacets) requestBuilder.set(variationsMap: self.variationsMap) requestBuilder.set(groupsSortOption: self.groupsSortOption) } }
mit
5e864b847a5d6150dc8ce9c7c6efbe8f
33.846154
315
0.661025
4.465498
false
false
false
false
dreamsxin/swift
test/RemoteAST/structural_types.swift
3
765
// RUN: %target-swift-remoteast-test %s | FileCheck %s @_silgen_name("printMetadataType") func printType(_: Any.Type) typealias Fn1 = () -> () printType(Fn1.self) // CHECK: found type: () -> () typealias Fn2 = (Int, Float) -> () printType(Fn2.self) // CHECK: found type: (Int, Float) -> () typealias Tuple1 = (Int, Float, Int) printType(Tuple1.self) // CHECK: found type: (Int, Float, Int) printType(Int.Type.self) // CHECK: found type: Int.Type printType(Tuple1.Type.self) // CHECK: found type: (Int, Float, Int).Type typealias Tuple2 = (Int.Type, x: Float, Int) printType(Tuple2.self) // CHECK: found type: (Int.Type, x: Float, Int) typealias Tuple3 = (x: Int, Float, y: Int.Type) printType(Tuple3.self) // CHECK: found type: (x: Int, Float, y: Int.Type)
apache-2.0
26d10a6e09f3042a6a9fb090c0ff8b0e
24.5
54
0.666667
2.741935
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/UIColorExtension.swift
1
2121
// // UIColorExtension.swift // TeacherTools // // Created by Parker Rushton on 12/1/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit import Marshal extension UIColor { class var ticketRed: UIColor { return #colorLiteral(red: 0.9882352941, green: 0.4117647059, blue: 0.4352941176, alpha: 1) } class var coolBlue: UIColor { return try! UIColor(hex: "4DA6BD") } class var appleBlue: UIColor { return try! UIColor(hex: "007AFF") } class var chalk: UIColor { return try! UIColor(hex: "FFFFDC") } convenience init(hex hexString: String) throws { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: throw MarshalError.nullValue(key: hexString) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } var hexValue: String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) let rgb = (Int)(red * 255)<<16 | (Int)(green * 255)<<8 | (Int)(blue * 255)<<0 return String(format:"#%06x", rgb) } } extension MarshaledObject { public func value(for key: KeyType) throws -> UIColor { do { let stringValue: String = try self.value(for: key) return try UIColor(hex: stringValue) } catch MarshalError.nullValue { throw MarshalError.nullValue(key: key) } } }
mit
e90924988e5eaeccac55a3c153d208c1
29.724638
127
0.550943
3.521595
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Views/NoteUndoOverlayView.swift
1
1636
import Foundation import WordPressShared /** * @class NoteUndoOverlayView * @brief This class renders a simple overlay view, with a Legend Label on its right, and an undo button on its * right side. * @details The purpose of this helper view is to act as a simple drop-in overlay, to be used by NoteTableViewCell. * By doing this, we avoid the need of having yet another UITableViewCell subclass, and thus, * we don't need to duplicate any of the mechanisms already available in NoteTableViewCell, such as * custom cell separators and Height Calculation. */ @objc public class NoteUndoOverlayView : UIView { // MARK: - NSCoder public override func awakeFromNib() { super.awakeFromNib() backgroundColor = Style.noteUndoBackgroundColor // Legend legendLabel.text = NSLocalizedString("Comment has been deleted", comment: "Displayed when a Comment is removed") legendLabel.textColor = Style.noteUndoTextColor legendLabel.font = Style.noteUndoTextFont // Button undoButton.titleLabel?.font = Style.noteUndoTextFont undoButton.setTitle(NSLocalizedString("Undo", comment: "Revert an operation"), forState: .Normal) undoButton.setTitleColor(Style.noteUndoTextColor, forState: .Normal) } // MARK: - Private Alias private typealias Style = WPStyleGuide.Notifications // MARK: - Private Outlets @IBOutlet private weak var legendLabel: UILabel! @IBOutlet private weak var undoButton: UIButton! }
gpl-2.0
e74972d515a184b1a87a78573b8e3c3b
39.9
127
0.67176
5.144654
false
false
false
false
mmcguill/StrongBox
FavIcon-Swift/DetectedIcon.swift
1
1964
// // FavIcon // Copyright © 2016 Leon Breedt // // 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; /// Enumerates the types of detected icons. @objc public enum DetectedIconType: UInt { /// A shortcut icon. case shortcut /// A classic icon (usually in the range 16x16 to 48x48). case classic /// A Google TV icon. case googleTV /// An icon used by Chrome/Android. case googleAndroidChrome /// An icon used by Safari on OS X for tabs. case appleOSXSafariTab /// An icon used iOS for Web Clips on home screen. case appleIOSWebClip /// An icon used for a pinned site in Windows. case microsoftPinnedSite /// An icon defined in a Web Application Manifest JSON file, mainly Android/Chrome. case webAppManifest /// A website image that is used for Facebook display purposes case FBImage } /// Represents a detected icon. @objc public class DetectedIcon : NSObject { /// The absolute URL for the icon file. @objc public let url: URL /// The type of the icon. @objc public let type: DetectedIconType /// The width of the icon, if known, in pixels. public let width: Int? /// The height of the icon, if known, in pixels. public let height: Int? init(url: URL, type: DetectedIconType, width: Int? = nil, height: Int? = nil) { self.url = url self.type = type self.width = width self.height = height } }
agpl-3.0
8cd8be240f016f75557e904dfde00393
32.271186
87
0.684157
4.132632
false
false
false
false
tadasz/MistikA
MistikA/Classes/LevelsViewController.swift
1
3019
// // LevelsViewController.swift // MistikA // // Created by Tadas Ziemys on 16/07/14. // Copyright (c) 2014 Tadas Ziemys. All rights reserved. // import UIKit class LevelsViewController: UIViewController, LevelCollectionViewControllerDelegate { @IBOutlet weak var imageView: UIImageView? var collectionView: LevelCollectionViewController? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView // // visualEffectView.frame = imageView.bounds // visualEffectView.alpha = 0 // if collectionView { // collectionView!.view.alpha = 0 // } // imageView.addSubview(visualEffectView) // // UIView.animateWithDuration(1.0, animations: { // visualEffectView.alpha = 1 // }, completion: { // _ in // UIView.animateWithDuration(1.0) { // self.collectionView!.view.alpha = 1 // } // }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func levelChoosen(level: Int) { switch level { case 0: performSegueWithIdentifier("show_MapRiddle", sender: self) case 1: let flappyStoryboard = UIStoryboard(name: "FlappyMain", bundle: nil) let flappyViewController = flappyStoryboard.instantiateInitialViewController() as! FlappyViewController self.presentViewController(flappyViewController, animated: true, completion: nil) case 2: performSegueWithIdentifier("showIlusions_segue", sender: self) case 3: performSegueWithIdentifier("showStereogram_segue", sender: self) case 4: performSegueWithIdentifier("showFirstLevel_segue", sender: self) case 5: performSegueWithIdentifier("showTimerView", sender: self) case 6: performSegueWithIdentifier("showFinalPuzzle_segue", sender: self) default: print("other level") } } // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "embededLevelCollection_segue" { collectionView = segue.destinationViewController as? LevelCollectionViewController collectionView!.delegate = self } } }
mit
228744125c42ddcfc04fc3166a1159a5
32.175824
115
0.625704
5.151877
false
false
false
false
nsagora/validation-toolkit
Sources/Constraints/Standard/PredicateConstraint.swift
1
4563
import Foundation /** A `Constraint` that links a `Predicate` to an `Error` that describes why the predicate evaluation has failed. ```swift let constraint = PredicateConstraint(.email, error: EmailFailure.invalid) let result = constraint.evaluate(with: "[email protected]) ``` */ public struct PredicateConstraint<T, E: Error>: Constraint { public typealias InputType = T public typealias ErrorType = E private let predicate: AnyPredicate<T> private let errorBuilder: (T) -> E /** Returns a new `PredicateConstraint` instance. ```swift let constraint = PredicateConstraint(.email, error: EmailFailure.invalid) let result = constraint.evaluate(with: "[email protected]) ``` - parameter predicate: A `Predicate` to describes the evaluation rule. - parameter error: An `Error` that describes why the evaluation has failed. */ public init<P: Predicate>(_ predicate: P, error: E) where P.InputType == InputType { self.predicate = predicate.erase() self.errorBuilder = { _ in return error } } /** Returns a new `PredicateConstraint` instance. ```swift let constraint = PredicateConstraint(.email) { EmailFailure.invalidFormat($0) } let result = constraint.evaluate(with: "[email protected]) ``` - parameter predicate: A `Predicate` to describes the evaluation rule. - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init<P: Predicate>(_ predicate: P, errorBuilder: @escaping (T) -> E) where P.InputType == T { self.predicate = predicate.erase() self.errorBuilder = errorBuilder } /** Returns a new `PredicateConstraint` instance. ```swift let constraint = PredicateConstraint(.email) { EmailFailure.invalid } let result = constraint.evaluate(with: "[email protected]) ``` - parameter predicate: A `Predicate` to describes the evaluation rule. - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init<P: Predicate>(_ predicate: P, errorBuilder: @escaping () -> E) where P.InputType == T { self.predicate = predicate.erase() self.errorBuilder = { _ in errorBuilder() } } /** Returns a new `PredicateConstraint` instance. ```swift let constraint = PredicateConstraint { .email } errorBuilder: { EmailFailure.invalidFormat($0) } let result = constraint.evaluate(with: "[email protected]) ``` - parameter predicateBuilder: A a closure that dynamically builds a `Predicate` to describes the evaluation rule. - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init<P: Predicate>(_ predicateBuilder: @escaping () -> P, errorBuilder: @escaping (T) -> E) where P.InputType == T { self.predicate = predicateBuilder().erase() self.errorBuilder = errorBuilder } /** Returns a new `PredicateConstraint` instance. ```swift let constraint = PredicateConstraint { .email } errorBuilder: { EmailFailure.invalid } let result = constraint.evaluate(with: "[email protected]) ``` - parameter predicateBuilder: A a closure that dynamically builds a `Predicate` to describes the evaluation rule. - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init<P: Predicate>(_ predicateBuilder: @escaping () -> P, errorBuilder: @escaping () -> E) where P.InputType == T { self.predicate = predicateBuilder().erase() self.errorBuilder = { _ in errorBuilder() } } /** Evaluates the input on the provided `Predicate`. - parameter input: The input to be validated. - returns: `.success` if the input is valid,`.failure` containing the `Summary` of the failing `Constraint`s otherwise. */ public func evaluate(with input: T) -> Result<Void, Summary<E>> { let result = predicate.evaluate(with: input) if result == true { return .success(()) } let error = errorBuilder(input) let summary = Summary(errors: [error]) return .failure(summary) } }
mit
6800a688496cddd637d82fc8e760634e
34.372093
127
0.638615
4.540299
false
false
false
false
magnetsystems/message-samples-ios
QuickStart/Pods/MagnetMaxCore/MagnetMax/Core/MMUser.swift
1
12037
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import Foundation @objc public protocol MMUserDelegate { static func overrideCompletion(completion:((error: NSError?) -> Void), error:NSError?, context:String) } public extension MMUser { /// The currently logged-in user or nil. static private var currentlyLoggedInUser: MMUser? @nonobjc static public var delegate : MMUserDelegate.Type? /** Registers a new user. - Parameters: - success: A block object to be executed when the registration finishes successfully. This block has no return value and takes one argument: the newly created user. - failure: A block object to be executed when the registration finishes with an error. This block has no return value and takes one argument: the error object. */ public func register(success: ((user: MMUser) -> Void)?, failure: ((error: NSError) -> Void)?) { assert(!userName.isEmpty && !password.isEmpty, "userName or password cannot be empty") MMCoreConfiguration.serviceAdapter.registerUser(self, success: { user in success?(user: user) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Logs in as an user. - Parameters: - credential: A credential object containing the user's userName and password. - success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object. */ static public func login(credential: NSURLCredential, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { login(credential, rememberMe: false, success: success, failure: failure) } /** Logs in as an user. - Parameters: - credential: A credential object containing the user's userName and password. - rememberMe: A boolean indicating if the user should stay logged in across app restarts. - success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object. */ static public func login(credential: NSURLCredential, rememberMe: Bool, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { let loginClosure : () -> Void = { () in MMCoreConfiguration.serviceAdapter.loginWithUsername(credential.user, password: credential.password, rememberMe: rememberMe, success: { _ in // Get current user now MMCoreConfiguration.serviceAdapter.getCurrentUserWithSuccess({ user -> Void in // Reset the state userTokenExpired(nil) currentlyLoggedInUser = user let userInfo = ["userID": user.userID, "deviceID": MMServiceAdapter.deviceUUID(), "token": MMCoreConfiguration.serviceAdapter.HATToken] NSNotificationCenter.defaultCenter().postNotificationName(MMServiceAdapterDidReceiveHATTokenNotification, object: self, userInfo: userInfo) // Register for token expired notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "userTokenExpired:", name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil) if let _ = self.delegate { handleCompletion(success, failure: failure, error : nil, context: "com.magnet.login.succeeded") } else { success?() } }, failure: { error in if let _ = self.delegate { handleCompletion(success, failure: failure, error : error, context: "com.magnet.login.failed") } else { failure?(error: error) } }).executeInBackground(nil) }) { error in if let _ = self.delegate { handleCompletion(success, failure: failure, error : error, context: "com.magnet.login.failed") } else { failure?(error: error) } }.executeInBackground(nil) } //begin login if currentlyLoggedInUser != nil { MMUser.logout({ () in loginClosure() }) { error in failure?(error : error); } } else { loginClosure() } } static private func handleCompletion(success: (() -> Void)?, failure: ((error: NSError) -> Void)?, error: NSError?, context : String) { delegate?.overrideCompletion({ (error) -> Void in if let error = error { failure?(error: error) } else { success?() } }, error: error, context: context) } /** Acts as the userToken expired event receiver. - Parameters: - notification: The notification that was received. */ @objc static private func userTokenExpired(notification: NSNotification?) { currentlyLoggedInUser = nil // Unregister for token expired notification NSNotificationCenter.defaultCenter().removeObserver(self, name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil) } /** Logs out a currently logged-in user. */ static public func logout() { logout(nil, failure: nil) } /** Logs out a currently logged-in user. - Parameters: - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func logout(success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { if currentUser() == nil { success?() return } userTokenExpired(nil) MMCoreConfiguration.serviceAdapter.logoutWithSuccess({ _ in success?() }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get the currently logged-in user. - Returns: The currently logged-in user or nil. */ static public func currentUser() -> MMUser? { return currentlyLoggedInUser } /** Search for users based on some criteria. - Parameters: - query: The DSL can be found here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax - limit: The number of records to retrieve. - offset: The offset to start from. - sort: The sort criteria. - success: A block object to be executed when the call finishes successfully. This block has no return value and takes one argument: the list of users that match the specified criteria. - failure: A block object to be executed when the call finishes with an error. This block has no return value and takes one argument: the error object. */ static public func searchUsers(query: String, limit take: Int, offset skip: Int, sort: String, success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.searchUsers(query, take: Int32(take), skip: Int32(skip), sort: sort, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get users with userNames. - Parameters: - userNames: A list of userNames to fetch users for. - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userNames. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func usersWithUserNames(userNames:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.getUsersByUserNames(userNames, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get users with userIDs. - Parameters: - userNames: A list of userIDs to fetch users for. - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userIDs. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func usersWithUserIDs(userIDs:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.getUsersByUserIds(userIDs, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Update the currently logged-in user's profile. - Parameters: - updateProfileRequest: A profile update request. - success: A block object to be executed when the update finishes successfully. This block has no return value and takes one argument: the updated user. - failure: A block object to be executed when the registration finishes with an error. This block has no return value and takes one argument: the error object. */ static public func updateProfile(updateProfileRequest: MMUpdateProfileRequest, success: ((user: MMUser) -> Void)?, failure: ((error: NSError) -> Void)?) { guard let _ = currentUser() else { // FIXME: Use a different domain failure?(error: NSError(domain: "MMXErrorDomain", code: 401, userInfo: nil)) return } let userService = MMUserService() userService.updateProfile(updateProfileRequest, success: { user in success?(user: user) }) { error in failure?(error: error) }.executeInBackground(nil) } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? MMUser { return userID != nil && userID == rhs.userID } return false } override var hash: Int { return userID != nil ? userID.hashValue : ObjectIdentifier(self).hashValue } }
apache-2.0
2c98ba67dfcecdc07cacdc572e1b4c40
43.253676
197
0.614023
5.111253
false
false
false
false
strike65/SwiftyStats
SwiftyStats/CommonSource/ProbDist/ProbDist-Uniform.swift
1
5545
// // Created by VT on 20.07.18. // Copyright © 2018 strike65. All rights reserved. /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif extension SSProbDist { /// Uniform distribution public enum Uniform { /// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Uniform distribution. /// - Parameter a: Lower bound /// - Parameter b: Upper bound /// - Throws: SSSwiftyStatsError if a >= b public static func para<FPT: SSFloatingPoint & Codable>(lowerBound a: FPT, upperBound b: FPT) throws -> SSProbDistParams<FPT> { if (a >= b) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lower bound a is expected to be greater than upper bound b", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>() result.mean = (a + b) / 2 let ex1: FPT = FPT.one / Helpers.makeFP(12.0) let ex2: FPT = b - a result.variance = ex1 * (ex2 * ex2) // 1 / 12 * (b - a) * (b - a) result.kurtosis = Helpers.makeFP(1.8) result.skewness = 0 return result } /// Returns the pdf of the Uniform distribution. /// - Parameter x: x /// - Parameter a: Lower bound /// - Parameter b: Upper bound /// - Throws: SSSwiftyStatsError if a >= b public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, lowerBound a: FPT, upperBound b: FPT) throws -> FPT { if (a >= b) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lower bound a is expected to be greater than upper bound b", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if x < a || x > b { return 0 } else { return 1 / (b - a) } } /// Returns the cdf of the Uniform distribution. /// - Parameter x: x /// - Parameter a: Lower bound /// - Parameter b: Upper bound /// - Throws: SSSwiftyStatsError if a >= b public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, lowerBound a: FPT, upperBound b: FPT) throws -> FPT { if (a >= b) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lower bound a is expected to be greater than upper bound b", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if x < a { return 0 } else if x > b { return 1 } else { return (x - a) / (b - a) } } /// Returns the cdf of the Uniform distribution. /// - Parameter x: x /// - Parameter a: Lower bound /// - Parameter b: Upper bound /// - Throws: SSSwiftyStatsError if a >= b public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, lowerBound a: FPT, upperBound b: FPT) throws -> FPT { if (a >= b) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lower bound a is expected to be greater than upper bound b", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if p < 0 || p > 1 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("p is expected to be >= 0 and <= 1 ", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } return a + (b - a) * p } } }
gpl-3.0
fa26bb977dbdb7f1c96aa825ccb30cb6
37.234483
135
0.510281
4.489069
false
false
false
false
HarrisLee/Utils
MySampleCode-master/CustomTransition/CustomTransition-Swift/CustomTransition-Swift/ViewController.swift
1
3419
// // ViewController.swift // CustomTransition-Swift // // Created by 张星宇 on 16/2/7. // Copyright © 2016年 zxy. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { lazy var tableView: UITableView = { let tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: .Plain) tableView.delegate = self tableView.dataSource = self tableView.bounces = true tableView.tableFooterView = UIView(frame: CGRectZero) return tableView }() let headetTitleArray = ["Presentation Transitions"] let cellTitleArray = ["淡入淡出", "滑动", "自定义Presentation"] let cellSubtitleArray = ["一种淡入淡出的动画", "一种交互式切换","使用presentation controller改变被展示的ViewController的布局"] override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "自定义页面跳转动画" view.addSubview(tableView) tableView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 实现UITableViewDelegate协议 extension ViewController { func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let nav: UINavigationController switch indexPath.row { case 0: nav = UINavigationController(rootViewController: CrossDissolveFirstViewController()) case 1: nav = UINavigationController(rootViewController: InteractivityFirstViewController()) case 2: nav = UINavigationController(rootViewController: CustomPresentationFirstViewController()) default: nav = UINavigationController() break } // http://stackoverflow.com/questions/22585416/slow-performance-for-presentviewcontroller-depends-on-complexity-of-presenting dispatch_async(dispatch_get_main_queue()) { self.presentViewController(nav, animated: true, completion: nil) } } } // MARK: - 实现UITableViewDataSource协议 extension ViewController { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return headetTitleArray.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellTitleArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let tableViewCell = UITableViewCell(style: .Subtitle, reuseIdentifier: String(UITableViewCell)) tableViewCell.textLabel?.text = cellTitleArray[indexPath.row] tableViewCell.detailTextLabel?.text = cellSubtitleArray[indexPath.row] tableViewCell.selectionStyle = .None return tableViewCell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return headetTitleArray[section] } }
mit
7e5f41052af34fe9e0ce3ba1d9956475
34.526882
133
0.690375
5.186813
false
false
false
false
nifty-swift/Nifty
Sources/eye.swift
2
1906
/*************************************************************************************************** * eye.swift * * This file provides functionality for obtaining an identity matrix. * * Author: Philip Erickson * Creation Date: 1 May 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ // TODO: remove the optional column... maybe a vector wants an eye function? /// Create a matrix with ones on the main diagonal and zeros elsewhere. /// /// - Parameters: /// - rows: number of rows; or edge length in square matrix if columns is nil /// - columns: number of columns; if nil, return square identity matrix /// - Returns: identity matrix of specified size public func eye(_ rows: Int, _ columns: Int? = nil) -> Matrix<Double> { let cols = columns ?? rows precondition(rows > 0 && cols > 0, "Invalid matrix dimensions: \([rows, cols])") var M = zeros(rows, cols) for d in 0..<rows { M[d,d] = 1 } return M } public func eye(_ size: [Int]) -> Matrix<Double> { precondition(size.count == 2, "Matrix size must be 2 dimensional") return eye(size[0], size[1]) } /// Return the scalar multiplicative identity. /// /// - Returns: the scalar 1 public func eye() -> Double { return 1.0 }
apache-2.0
adbf4e8ecf3c6ba951a236612852a1e1
32.45614
101
0.604407
4.263982
false
false
false
false
richardpiazza/SOSwift
Sources/SOSwift/TypeAndQuantityNode.swift
1
2664
import Foundation /// A structured value indicating the quantity, unit of measurement, and business /// function of goods included in a bundle offer. public class TypeAndQuantityNode: StructuredValue { /// The quantity of the goods included in the offer. public var amountOfThisGood: Number? /// The business function (e.g. sell, lease, repair, dispose) /// of the offer or component of a bundle (TypeAndQuantityNode). /// The default is [http://purl.org/goodrelations/v1#Sell](http://purl.org/goodrelations/v1#Sell). public var businessFunction: BusinessFunction? /// The product that this structured value is referring to. public var typeOfGood: ProductOrService? /// The unit of measurement given using the UN/CEFACT Common /// Code (3 characters) or a URL. Other codes than the UN/CEFACT /// Common Code may be used with a prefix followed by a colon. public var unitCode: URLOrText? /// A string or text indicating the unit of measurement. Useful if you /// cannot provide a standard unit code for unitCode. public var unitText: String? internal enum TypeAndQuantityNodeCodingKeys: String, CodingKey { case amountOfThisGood case businessFunction case typeOfGood case unitCode case unitText } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: TypeAndQuantityNodeCodingKeys.self) amountOfThisGood = try container.decodeIfPresent(Number.self, forKey: .amountOfThisGood) businessFunction = try container.decodeIfPresent(BusinessFunction.self, forKey: .businessFunction) typeOfGood = try container.decodeIfPresent(ProductOrService.self, forKey: .typeOfGood) unitCode = try container.decodeIfPresent(URLOrText.self, forKey: .unitCode) unitText = try container.decodeIfPresent(String.self, forKey: .unitText) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TypeAndQuantityNodeCodingKeys.self) try container.encodeIfPresent(amountOfThisGood, forKey: .amountOfThisGood) try container.encodeIfPresent(businessFunction, forKey: .businessFunction) try container.encodeIfPresent(typeOfGood, forKey: .typeOfGood) try container.encodeIfPresent(unitCode, forKey: .unitCode) try container.encodeIfPresent(unitText, forKey: .unitText) try super.encode(to: encoder) } }
mit
8efbb25b757c7368893c449111fd500e
41.967742
106
0.702327
4.608997
false
false
false
false
jie-cao/SwiftImage
SwiftImageDemo/SwiftImageDemo/ImageTableViewController.swift
1
3778
// // ImageTableViewController.swift // CJImageUtilsDemo // // Created by Jie Cao on 11/20/15. // Copyright © 2015 JieCao. All rights reserved. // import UIKit class ImageTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { private let reuseIdentifier = "ImageCell" @IBOutlet weak var tableView: UITableView! var dataSource = [] override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.dataSource = [["text":"cat", "url":"http://www.fndvisions.org/img/cutecat.jpg"], ["text":"cat", "url":"http://www.mycatnames.com/wp-content/uploads/2015/09/Great-Ideas-for-cute-cat-names-2.jpg"], ["text":"cat", "url":"http://cdn.cutestpaw.com/wp-content/uploads/2011/11/cute-cat.jpg"], ["text":"cat", "url":"http://buzzneacom.c.presscdn.com/wp-content/uploads/2015/02/cute-cat-l.jpg"], ["text":"cat", "url":"http://images.fanpop.com/images/image_uploads/CUTE-CAT-cats-625629_689_700.jpg"], ["text":"cat", "url":"http://cl.jroo.me/z3/m/a/z/e/a.baa-Very-cute-cat-.jpg"], ["text":"cat", "url":"http://www.cancats.net/wp-content/uploads/2014/10/cute-cat-pictures-the-cutest-cat-ever.jpg"], ["text":"cat", "url":"https://catloves9.files.wordpress.com/2012/05/cute-cat-20.jpg"], ["text":"cat", "url":"https://s-media-cache-ak0.pinimg.com/736x/8c/99/e3/8c99e3483387df6395da674a6b5dee4c.jpg"], ["text":"cat", "url":"http://youne.com/wp-content/uploads/2013/09/cute-cat.jpg"], ["text":"cat", "url":"http://www.lovefotos.com/wp-content/uploads/2011/06/cute-cat1.jpg"], ["text":"cat", "url":"http://cutecatsrightmeow.com/wp-content/uploads/2015/10/heres-looking-at-you-kid.jpg"]] // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return self.dataSource.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let data = self.dataSource[indexPath.row] as! [String :String] let cell = self.tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ImageTableViewCell cell.contentLabel?.text = data["text"] let placeholderImage = UIImage(named: "placeholder.jpg") if let imageUrl = NSURL(string: data["url"]!){ cell.photoView?.imageWithURL(imageUrl, placeholderImage: placeholderImage) cell.photoView?.contentMode = .ScaleAspectFit } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100.0 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
af86a3c9d75ee87d4d7695b4f75b7e9b
46.2125
132
0.660577
4.022364
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/GestureVC.swift
1
1899
// // GestureVC.swift // UIScrollViewDemo // // Created by xiAo_Ju on 2019/3/13. // Copyright © 2019 伯驹 黄. All rights reserved. // import UIKit class GestureView: UIView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("GestureView touchesBegan") } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { print("GestureView touchesCancelled") } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("GestureView touchesEnded") } } class GestureVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() let gestureView = GestureView() gestureView.backgroundColor = .red view.addSubview(gestureView) gestureView.translatesAutoresizingMaskIntoConstraints = false gestureView.widthAnchor.constraint(equalToConstant: 100).isActive = true gestureView.heightAnchor.constraint(equalToConstant: 100).isActive = true gestureView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true gestureView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true view.backgroundColor = .white let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap)) tapGesture.cancelsTouchesInView = false tapGesture.delaysTouchesEnded = false tapGesture.numberOfTapsRequired = 2 gestureView.addGestureRecognizer(tapGesture) } @objc func tap(_ sender: UITapGestureRecognizer) { print("tap") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("touchesBegan") } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { print("touchesCancelled") } }
mit
9aade98bd19aafa47412730ae8bec71c
29.516129
89
0.67759
5.072386
false
false
false
false
DomBlack/mal
swift3/Sources/step6_file/main.swift
6
4958
import Foundation // read func READ(_ str: String) throws -> MalVal { return try read_str(str) } // eval func eval_ast(_ ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalSymbol: return try env.get(ast) case MalVal.MalList(let lst, _): return list(try lst.map { try EVAL($0, env) }) case MalVal.MalVector(let lst, _): return vector(try lst.map { try EVAL($0, env) }) case MalVal.MalHashMap(let dict, _): var new_dict = Dictionary<String,MalVal>() for (k,v) in dict { new_dict[k] = try EVAL(v, env) } return hash_map(new_dict) default: return ast } } func EVAL(_ orig_ast: MalVal, _ orig_env: Env) throws -> MalVal { var ast = orig_ast, env = orig_env while true { switch ast { case MalVal.MalList(let lst, _): if lst.count == 0 { return ast } default: return try eval_ast(ast, env) } switch ast { case MalVal.MalList(let lst, _): switch lst[0] { case MalVal.MalSymbol("def!"): return try env.set(lst[1], try EVAL(lst[2], env)) case MalVal.MalSymbol("let*"): let let_env = try Env(env) var binds = Array<MalVal>() switch lst[1] { case MalVal.MalList(let l, _): binds = l case MalVal.MalVector(let l, _): binds = l default: throw MalError.General(msg: "Invalid let* bindings") } var idx = binds.startIndex while idx < binds.endIndex { let v = try EVAL(binds[binds.index(after: idx)], let_env) try let_env.set(binds[idx], v) idx = binds.index(idx, offsetBy: 2) } env = let_env ast = lst[2] // TCO case MalVal.MalSymbol("do"): let slc = lst[1..<lst.index(before: lst.endIndex)] try _ = eval_ast(list(Array(slc)), env) ast = lst[lst.index(before: lst.endIndex)] // TCO case MalVal.MalSymbol("if"): switch try EVAL(lst[1], env) { case MalVal.MalFalse, MalVal.MalNil: if lst.count > 3 { ast = lst[3] // TCO } else { return MalVal.MalNil } default: ast = lst[2] // TCO } case MalVal.MalSymbol("fn*"): return malfunc( { return try EVAL(lst[2], Env(env, binds: lst[1], exprs: list($0))) }, ast:[lst[2]], env:env, params:[lst[1]]) default: switch try eval_ast(ast, env) { case MalVal.MalList(let elst, _): switch elst[0] { case MalVal.MalFunc(let fn, nil, _, _, _, _): let args = Array(elst[1..<elst.count]) return try fn(args) case MalVal.MalFunc(_, let a, let e, let p, _, _): let args = Array(elst[1..<elst.count]) env = try Env(e, binds: p![0], exprs: list(args)) // TCO ast = a![0] // TCO default: throw MalError.General(msg: "Cannot apply on '\(elst[0])'") } default: throw MalError.General(msg: "Invalid apply") } } default: throw MalError.General(msg: "Invalid apply") } } } // print func PRINT(_ exp: MalVal) -> String { return pr_str(exp, true) } // repl @discardableResult func rep(_ str:String) throws -> String { return PRINT(try EVAL(try READ(str), repl_env)) } var repl_env: Env = try Env() // core.swift: defined using Swift for (k, fn) in core_ns { try repl_env.set(MalVal.MalSymbol(k), malfunc(fn)) } try repl_env.set(MalVal.MalSymbol("eval"), malfunc({ try EVAL($0[0], repl_env) })) let pargs = CommandLine.arguments.map { MalVal.MalString($0) } // TODO: weird way to get empty list, fix this var args = pargs[pargs.startIndex..<pargs.startIndex] if pargs.index(pargs.startIndex, offsetBy:2) < pargs.endIndex { args = pargs[pargs.index(pargs.startIndex, offsetBy:2)..<pargs.endIndex] } try repl_env.set(MalVal.MalSymbol("*ARGV*"), list(Array(args))) // core.mal: defined using the language itself try rep("(def! not (fn* (a) (if a false true)))") try rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") if CommandLine.arguments.count > 1 { try rep("(load-file \"" + CommandLine.arguments[1] + "\")") exit(0) } while true { print("user> ", terminator: "") let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } catch (MalError.General(let msg)) { print("Error: \(msg)") } }
mpl-2.0
882caced240ba8ea18e7ed067365751c
31.834437
89
0.520976
3.764617
false
false
false
false
jphacks/TK_08
iOS/AirMeet/AirMeet/MyMenuTableViewController.swift
1
4847
// // MyMenuTableViewController.swift // AirMeet // // Created by koooootake on 2015/12/01. // Copyright © 2015年 koooootake. All rights reserved. // import UIKit class MyMenuTableViewController: UITableViewController { var selectedMenuItem : Int = 0 override func viewDidLoad() { super.viewDidLoad() // Customize apperance of table view tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) // tableView.separatorStyle = .None tableView.backgroundColor = UIColor(red: 128.0/255.0, green: 204.0/255.0, blue: 223.0/255.0, alpha: 1)//水色 tableView.scrollsToTop = false // Preserve selection between presentations self.clearsSelectionOnViewWillAppear = false tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedMenuItem, inSection: 0), animated: false, scrollPosition: .Middle) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return 4 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("CELL") if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CELL") cell!.backgroundColor = UIColor.clearColor() cell!.textLabel?.textColor = UIColor.whiteColor() let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height)) selectedBackgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2) cell!.selectedBackgroundView = selectedBackgroundView } switch (indexPath.row) { case 0: cell!.textLabel?.text = "HOME" break case 1: cell!.textLabel?.text = "Meeted Book" break case 2: cell!.textLabel?.text = "Make AirMeet" break case 3: cell!.textLabel?.text = "Profile Setting" break default: break } return cell! } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row == selectedMenuItem) { //return } selectedMenuItem = indexPath.row //Present new view controller let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil) var destViewController : UIViewController switch (indexPath.row) { case 0: destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("Main") break case 1: let storyboard: UIStoryboard = UIStoryboard(name: "Meet", bundle: NSBundle.mainBundle()) destViewController = storyboard.instantiateInitialViewController() as! MeetListViewController break case 2: let storyboard: UIStoryboard = UIStoryboard(name: "Parent", bundle: NSBundle.mainBundle()) destViewController = storyboard.instantiateInitialViewController() as! MakeAirMeetViewController break case 3: let storyboard: UIStoryboard = UIStoryboard(name: "Profile", bundle: NSBundle.mainBundle()) destViewController = storyboard.instantiateInitialViewController() as! ProfileSettingViewController break default: destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("Main") break } sideMenuController()?.setContentViewController(destViewController) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
8eaa2b42141d8e8a7f5fc421d1974bc3
34.072464
133
0.62624
5.796407
false
false
false
false
simonbs/bemyeyes-ios
BeMyEyes/Source/Views/BlueShadowGradientView.swift
3
2356
// // BlueShadowGradientView.swift // BeMyEyes // // Created by Tobias Due Munk on 28/10/14. // Copyright (c) 2014 Be My Eyes. All rights reserved. // import UIKit class LightBlueShadowView: GradientView { override func setup() { super.setup() let color = UIColor.lightBlueColor() colors = [color.colorWithAlphaComponent(0), color.colorWithAlphaComponent(0.3)] startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 0, y: 1) } } class LightBlueShadowViewReverse: LightBlueShadowView { override func setup() { super.setup() startPoint = CGPoint(x: 0, y: 1) endPoint = CGPoint(x: 0, y: 0) } } class DarkBlueShadowView: GradientView { override func setup() { super.setup() let color = UIColor.darkBlueColor() colors = [color.colorWithAlphaComponent(0), color.colorWithAlphaComponent(0.3)] startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 0, y: 1) } } class DarkBlueShadowViewReverse: DarkBlueShadowView { override func setup() { super.setup() startPoint = CGPoint(x: 0, y: 1) endPoint = CGPoint(x: 0, y: 0) } } class LightBlueOverlayView: GradientView { override func setup() { super.setup() let color = UIColor.lightBlueColor() colors = [color.colorWithAlphaComponent(0), color.colorWithAlphaComponent(1)] startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 0, y: 1) } } class LightBlueOverlayViewReverse: LightBlueOverlayView { override func setup() { super.setup() startPoint = CGPoint(x: 0, y: 1) endPoint = CGPoint(x: 0, y: 0) } } class DarkBlueOverlayView: GradientView { override func setup() { super.setup() let color = UIColor.darkBlueColor() colors = [color.colorWithAlphaComponent(0), color.colorWithAlphaComponent(1)] startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 0, y: 1) } } class DarkBlueOverlayViewReverse: DarkBlueOverlayView { override func setup() { super.setup() startPoint = CGPoint(x: 0, y: 1) endPoint = CGPoint(x: 0, y: 0) } }
mit
9f3650b5b955d2147952745e228a4a72
22.098039
57
0.580221
4.090278
false
false
false
false
btanner/Eureka
Example/Example/Helpers/FloatLabelTextField.swift
4
4943
// // FloatLabelTextField.swift // FloatLabelFields // // Created by Fahim Farook on 28/11/14. // Copyright (c) 2014 RookSoft Ltd. All rights reserved. // // Original Concept by Matt D. Smith // http://dribbble.com/shots/1254439--GIF-Mobile-Form-Interaction?list=users // // Objective-C version by Jared Verdi // https://github.com/jverdi/JVFloatLabeledTextField // import UIKit @IBDesignable public class FloatLabelTextField: UITextField { let animationDuration = 0.3 var title = UILabel() // MARK:- Properties override public var accessibilityLabel:String! { get { if text?.isEmpty ?? true { return title.text } else { return text } } set { self.accessibilityLabel = newValue } } override public var placeholder:String? { didSet { title.text = placeholder title.sizeToFit() } } override public var attributedPlaceholder:NSAttributedString? { didSet { title.text = attributedPlaceholder?.string title.sizeToFit() } } var titleFont: UIFont = .systemFont(ofSize: 12.0) { didSet { title.font = titleFont title.sizeToFit() } } @IBInspectable var hintYPadding:CGFloat = 0.0 @IBInspectable var titleYPadding:CGFloat = 0.0 { didSet { var r = title.frame r.origin.y = titleYPadding title.frame = r } } @IBInspectable var titleTextColour:UIColor = .gray { didSet { if !isFirstResponder { title.textColor = titleTextColour } } } @IBInspectable var titleActiveTextColour:UIColor! { didSet { if isFirstResponder { title.textColor = titleActiveTextColour } } } // MARK:- Init required public init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) setup() } override init(frame:CGRect) { super.init(frame:frame) setup() } // MARK:- Overrides override public func layoutSubviews() { super.layoutSubviews() setTitlePositionForTextAlignment() let isResp = isFirstResponder if isResp && !(text?.isEmpty ?? true) { title.textColor = titleActiveTextColour } else { title.textColor = titleTextColour } // Should we show or hide the title label? if text?.isEmpty ?? true { // Hide hideTitle(isResp) } else { // Show showTitle(isResp) } } override public func textRect(forBounds bounds:CGRect) -> CGRect { var r = super.textRect(forBounds: bounds) if !(text?.isEmpty ?? true){ var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0)) } return r.integral } override public func editingRect(forBounds bounds:CGRect) -> CGRect { var r = super.editingRect(forBounds: bounds) if !(text?.isEmpty ?? true) { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0)) } return r.integral } override public func clearButtonRect(forBounds bounds:CGRect) -> CGRect { var r = super.clearButtonRect(forBounds: bounds) if !(text?.isEmpty ?? true) { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = CGRect(x:r.origin.x, y:r.origin.y + (top * 0.5), width:r.size.width, height:r.size.height) } return r.integral } // MARK:- Public Methods // MARK:- Private Methods private func setup() { borderStyle = .none titleActiveTextColour = tintColor // Set up title label title.alpha = 0.0 title.font = titleFont title.textColor = titleTextColour if let str = placeholder, !str.isEmpty { title.text = str title.sizeToFit() } self.addSubview(title) } private func maxTopInset()->CGFloat { return max(0, floor(bounds.size.height - (font?.lineHeight ?? 0) - 4.0)) } private func setTitlePositionForTextAlignment() { let r = textRect(forBounds: bounds) var x = r.origin.x if textAlignment == .center { x = r.origin.x + (r.size.width * 0.5) - title.frame.size.width } else if textAlignment == .right { x = r.origin.x + r.size.width - title.frame.size.width } title.frame = CGRect(x:x, y:title.frame.origin.y, width:title.frame.size.width, height:title.frame.size.height) } private func showTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: [.beginFromCurrentState, .curveEaseOut], animations:{ // Animation self.title.alpha = 1.0 var r = self.title.frame r.origin.y = self.titleYPadding self.title.frame = r }) } private func hideTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: [.beginFromCurrentState, .curveEaseIn], animations:{ // Animation self.title.alpha = 0.0 var r = self.title.frame r.origin.y = self.title.font.lineHeight + self.hintYPadding self.title.frame = r }) } }
mit
9d4de76af1ea3fbcbd4f0605cc996768
24.219388
113
0.672062
3.284385
false
false
false
false
GiorgioNatili/CryptoMessages
CryptoMessages/authentication/routing/AuthenticationRouting.swift
1
953
// // AuthenticationRouting.swift // CryptoMessages // // Created by Giorgio Natili on 5/7/17. // Copyright © 2017 Giorgio Natili. All rights reserved. // import Foundation import UIKit class AuthenticationRouter: AuthenticationRouting { var window: UIWindow? enum SegueIdentifiers: String { case MesseagesList = "MesseagesList" } init() { self.window = UIApplication.shared.delegate!.window! } func presentMessages() { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let navigationController = UINavigationController() let view = mainStoryboard.instantiateViewController(withIdentifier: SegueIdentifiers.MesseagesList.rawValue) as! MessagesViewController navigationController.pushViewController(view, animated: false) window?.rootViewController = navigationController } }
unlicense
2ffb15c387666017d0a38343e044cb52
25.444444
143
0.678571
5.145946
false
false
false
false
hdimessi/ThreeRingControl
ThreeRingControl/RingTip.swift
8
3654
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class RingTip : CALayer { //MARK:- Constituent Layers fileprivate lazy var tipLayer : CAShapeLayer = { let layer = CAShapeLayer() layer.lineCap = kCALineCapRound layer.lineWidth = self.ringWidth return layer }() fileprivate lazy var shadowLayer : CAShapeLayer = { let layer = CAShapeLayer() layer.lineCap = kCALineCapRound layer.strokeColor = UIColor.black.cgColor layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = .zero layer.shadowRadius = 12.0 layer.shadowOpacity = 1.0 layer.mask = self.shadowMaskLayer return layer }() fileprivate lazy var shadowMaskLayer : CAShapeLayer = { let layer = CAShapeLayer() layer.strokeColor = UIColor.black.cgColor layer.lineCap = kCALineCapButt return layer }() //MARK:- Utility Properties fileprivate var radius : CGFloat { return (min(bounds.width, bounds.height) - ringWidth) / 2.0 } fileprivate var tipPath : CGPath { return UIBezierPath(arcCenter: center, radius: radius, startAngle: -0.01, endAngle: 0, clockwise: true).cgPath } fileprivate var shadowMaskPath : CGPath { return UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI_2), clockwise: true).cgPath } //MARK:- API Properties var color: CGColor = UIColor.red.cgColor { didSet { tipLayer.strokeColor = color } } var ringWidth: CGFloat = 40.0 { didSet { tipLayer.lineWidth = ringWidth shadowLayer.lineWidth = ringWidth shadowMaskLayer.lineWidth = ringWidth preparePaths() } } //MARK:- Initialisation override init() { super.init() sharedInitialisation() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInitialisation() } override init(layer: Any) { super.init(layer: layer) if let layer = layer as? RingTip { color = layer.color ringWidth = layer.ringWidth } } fileprivate func sharedInitialisation() { addSublayer(shadowLayer) addSublayer(tipLayer) color = UIColor.red.cgColor preparePaths() } //MARK:- Lifecycle Overrides override func layoutSublayers() { for layer in [tipLayer, shadowLayer, shadowMaskLayer] { layer.bounds = bounds layer.position = center } preparePaths() } //MARK:- Utility methods fileprivate func preparePaths() { tipLayer.path = tipPath shadowLayer.path = tipPath shadowMaskLayer.path = shadowMaskPath } }
mit
e85732e57edcc36f9f270ba078e0dfd7
28.232
124
0.701423
4.47246
false
false
false
false