hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
f9437e0d6ffe54d9e97a57bd2fceed1d6c8def7d | 3,669 | //
// NewAdminTableViewCell.swift
// ZeroMessger
//
// Created by Sandeep Mukherjee on 3/29/20.
// Copyright © 2020 Sandeep Mukherjee. All rights reserved.
//
import UIKit
class NewAdminTableViewCell: UITableViewCell {
weak var selectNewAdminTableViewController: SelectNewAdminTableViewController!
var gestureReconizer:UITapGestureRecognizer!
var icon: UIImageView = {
var icon = UIImageView()
icon.translatesAutoresizingMaskIntoConstraints = false
icon.contentMode = .scaleAspectFill
icon.layer.cornerRadius = 22
icon.layer.masksToBounds = true
icon.image = UIImage(named: "UserpicIcon")
return icon
}()
var title: UILabel = {
var title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
title.textColor = ThemeManager.currentTheme().generalTitleColor
return title
}()
var subtitle: UILabel = {
var subtitle = UILabel()
subtitle.translatesAutoresizingMaskIntoConstraints = false
subtitle.font = UIFont.systemFont(ofSize: 13)
subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor
return subtitle
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
gestureReconizer = UITapGestureRecognizer(target: self, action: #selector(cellTapped))
addGestureRecognizer(gestureReconizer)
backgroundColor = .clear
title.backgroundColor = backgroundColor
icon.backgroundColor = backgroundColor
contentView.addSubview(icon)
icon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
icon.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
icon.widthAnchor.constraint(equalToConstant: 46).isActive = true
icon.heightAnchor.constraint(equalToConstant: 46).isActive = true
contentView.addSubview(title)
title.topAnchor.constraint(equalTo: icon.topAnchor, constant: 0).isActive = true
title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true
title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
title.heightAnchor.constraint(equalToConstant: 23).isActive = true
contentView.addSubview(subtitle)
subtitle.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 0).isActive = true
subtitle.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true
subtitle.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
subtitle.heightAnchor.constraint(equalToConstant: 23).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func cellTapped() {
guard let indexPath = selectNewAdminTableViewController.tableView.indexPathForView(self) else { return }
selectNewAdminTableViewController.deselectAll(indexPath: indexPath)
selectNewAdminTableViewController.didSelectUser(at: indexPath)
isSelected = true
}
override func prepareForReuse() {
super.prepareForReuse()
icon.image = UIImage(named: "UserpicIcon")
title.text = ""
subtitle.text = ""
title.textColor = ThemeManager.currentTheme().generalTitleColor
subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 36.69 | 108 | 0.748433 |
01bf90bcc4a2a01f3065d3a4cebe8a51fd846df3 | 10,038 | //
// ExtensionsTests.swift
// ExtensionsTests
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import XCTest
class ExtensionsArrayTests: XCTestCase {
var array: Array<Int> = []
var people: Person[] = []
class Person {
let name: String, age: Int, id: String
init(_ name: String, _ age: Int, _ id: String){
self.name = name
self.age = age
self.id = id
}
}
override func setUp() {
super.setUp()
array = [1, 2, 3, 4, 5]
people = [
Person("bob", 25, "P1"),
Person("frank", 45, "P2"),
Person("ian", 35, "P3")
]
}
func testSortBy () {
var sourceArray = [2,3,6,5]
var sortedArray = sourceArray.sortBy {$0 < $1}
// check that the source array as not been mutated
XCTAssertEqualObjects(sourceArray, [2, 3, 6, 5])
// check that the destination has been sorted
XCTAssertEqualObjects(sortedArray, [2, 3, 5, 6])
}
func testReject () {
var odd = array.reject({
return $0 % 2 == 0
})
XCTAssertEqualObjects(odd, [1, 3, 5])
}
func testToDictionary () {
var dictionary = people.toDictionary { $0.id }
XCTAssertEqualObjects(Array(dictionary.keys), ["P3", "P1", "P2"])
XCTAssertEqualObjects(dictionary["P1"]?.name, "bob")
XCTAssertEqualObjects(dictionary["P2"]?.name, "frank")
XCTAssertEqualObjects(dictionary["P3"]?.name, "ian")
}
func testEach() {
var result = Array<Int>()
array.each({
result.append($0)
})
XCTAssertEqualObjects(result, array)
result.removeAll(keepCapacity: true)
array.each({
(index: Int, item: Int) in
result.append(index)
})
XCTAssertEqualObjects(result, array.map({ return $0 - 1 }) as Int[])
}
func testEachRight() {
var result = Int[]()
array.eachRight { (index: Int, value: Int) -> Void in
result += value
}
XCTAssertEqualObjects(result.first(), array.last())
XCTAssertEqualObjects(result.last(), array.first())
}
func testRange() {
XCTAssertEqualObjects(Array<Int>.range(0..2), [0, 1])
XCTAssertEqualObjects(Array<Int>.range(0...2), [0, 1, 2])
}
func testContains() {
XCTAssertFalse(array.contains("A"))
XCTAssertFalse(array.contains(6))
XCTAssertTrue(array.contains(5))
XCTAssertTrue(array.contains(3, 4) )
}
func testFirst() {
XCTAssertEqual(1, array.first()!)
}
func testLast() {
XCTAssertEqual(5, array.last()!)
}
func testDifference() {
XCTAssertEqualObjects(array.difference([3, 4]), [1, 2, 5])
XCTAssertEqualObjects(array - [3, 4], [1, 2, 5])
XCTAssertEqualObjects(array.difference([3], [5]), [1, 2, 4])
}
func testIndexOf() {
XCTAssertEqual(0, array.indexOf(1)!)
XCTAssertEqual(3, array.indexOf(4)!)
XCTAssertNil(array.indexOf(6))
}
func testIntersection() {
XCTAssertEqualObjects(array.intersection([]), [])
XCTAssertEqualObjects(array.intersection([1]), [1])
XCTAssertEqualObjects(array.intersection([1, 2], [1, 2], [1, 3]), [1])
}
func testUnion() {
XCTAssertEqualObjects(array.union([1]), array)
XCTAssertEqualObjects(array.union(Int[]()), array)
XCTAssertEqualObjects(array.union([6]), [1, 2, 3, 4, 5, 6])
}
func testZip() {
var zip1 = [1, 2].zip(["A", "B"])
var a = zip1[0][0] as Int
var b = zip1[0][1] as String
XCTAssertEqual(1, a)
XCTAssertEqual("A", b)
a = zip1[1][0] as Int
b = zip1[1][1] as String
XCTAssertEqual(2, a)
XCTAssertEqual("B", b)
}
func testPartition() {
XCTAssertEqualObjects(array.partition(2), [[1, 2], [3, 4]])
XCTAssertEqualObjects(array.partition(2, step: 1), [[1, 2], [2, 3], [3, 4], [4, 5]])
XCTAssertEqualObjects(array.partition(2, step: 1, pad: nil), [[1, 2], [2, 3], [3, 4], [4, 5], [5]])
XCTAssertEqualObjects(array.partition(4, step: 1, pad: nil), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5]])
XCTAssertEqualObjects(array.partition(2, step: 1, pad: [6,7,8]), [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
XCTAssertEqualObjects(array.partition(4, step: 3, pad: [6]), [[1, 2, 3, 4], [4, 5, 6]])
XCTAssertEqualObjects(array.partition(2, pad: [6]), [[1, 2], [3, 4], [5, 6]])
XCTAssertEqualObjects([1, 2, 3, 4, 5, 6].partition(2, step: 4), [[1, 2], [5, 6]])
XCTAssertEqualObjects(array.partition(10), [[]])
}
func testPartitionAll() {
XCTAssertEqualObjects(array.partitionAll(2, step: 1), [[1, 2], [2, 3], [3, 4], [4, 5], [5]])
XCTAssertEqualObjects(array.partitionAll(2), [[1, 2], [3, 4], [5]])
XCTAssertEqualObjects(array.partitionAll(4, step: 1), [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5], [4, 5], [5]])
}
func testPartitionBy() {
XCTAssertEqualObjects(array.partitionBy { $0 > 10 }, [[1, 2, 3, 4, 5]])
XCTAssertEqualObjects([1, 2, 4, 3, 5, 6].partitionBy { $0 % 2 == 0 }, [[1], [2, 4], [3, 5], [6]])
XCTAssertEqualObjects([1, 7, 3, 6, 10, 12].partitionBy { $0 % 3 }, [[1, 7], [3, 6], [10], [12]])
}
func testSample() {
XCTAssertEqual(1, array.sample().count)
XCTAssertEqual(2, array.sample(size: 2).count)
XCTAssertEqualObjects(array.sample(size: array.count), array)
}
func testSubscriptRange() {
XCTAssertEqualObjects(array[0..0], [])
XCTAssertEqualObjects(array[0..1], [1])
XCTAssertEqualObjects(array[0..2], [1, 2])
}
func testShuffled() {
let shuffled = array.shuffled()
XCTAssertEqualObjects(shuffled.difference(array), [])
}
func testShuffle() {
var toShuffle = array.copy()
toShuffle.shuffle()
XCTAssertEqualObjects(toShuffle.difference(array), [])
}
func testMax() {
XCTAssertEqual(5, array.max() as Int)
}
func testMin() {
XCTAssertEqual(1, array.min() as Int)
}
func testTake() {
XCTAssertEqualObjects(array.take(3), [1, 2, 3])
XCTAssertEqualObjects(array.take(0), [])
}
func testTakeWhile() {
XCTAssertEqualObjects(array.takeWhile { $0 < 3 }, [1 , 2])
XCTAssertEqualObjects([1, 2, 3, 2, 1].takeWhile { $0 < 3 }, [1, 2])
XCTAssertEqualObjects(array.takeWhile { $0.isEven() }, [])
}
func testSkip() {
XCTAssertEqualObjects(array.skip(3), [4, 5])
XCTAssertEqualObjects(array.skip(0), array)
}
func testSkipWhile() {
XCTAssertEqualObjects(array.skipWhile { $0 < 3 }, [3, 4, 5])
XCTAssertEqualObjects([1, 2, 3, 2, 1].skipWhile { $0 < 3 }, [3, 2, 1])
XCTAssertEqualObjects(array.skipWhile { $0.isEven() }, array)
}
func testTail () {
XCTAssertEqualObjects(array.tail(3), [3, 4, 5])
XCTAssertEqualObjects(array.tail(0), [])
}
func testPop() {
XCTAssertEqual(5, array.pop())
XCTAssertEqualObjects(array, [1, 2, 3, 4])
}
func testPush() {
array.push(6)
XCTAssertEqual(6, array.last()!)
}
func testShift() {
XCTAssertEqual(1, array.shift())
XCTAssertEqualObjects(array, [2, 3, 4, 5])
}
func testUnshift() {
array.unshift(0)
XCTAssertEqual(0, array.first()!)
}
func testRemove() {
array.append(array.last()!)
array.remove(array.last()!)
XCTAssertEqualObjects((array - 1), [2, 3, 4])
XCTAssertEqualObjects(array, [1, 2, 3, 4])
}
func testUnique() {
let arr = [1, 1, 1, 2, 3]
XCTAssertEqualObjects(arr.unique() as Int[], [1, 2, 3])
}
func testGroupBy() {
let group = array.groupBy(groupingFunction: {
(value: Int) -> Bool in
return value > 3
})
XCTAssertEqualObjects(Array(group.keys), [false, true])
XCTAssertEqualObjects(Array(group[true]!), [4, 5])
XCTAssertEqualObjects(Array(group[false]!), [1, 2, 3])
}
func testCountBy() {
let group = array.countBy(groupingFunction: {
(value: Int) -> Bool in
return value > 3
})
XCTAssertEqualObjects(group, [true: 2, false: 3])
}
func testReduceRight () {
let list = [[1, 1], [2, 3], [4, 5]]
let flat = list.reduceRight(Array<Int>(), { return $0 + $1 })
XCTAssertEqualObjects(flat, [4, 5, 2, 3, 1, 1])
XCTAssertEqual(4 + 5 + 2 + 3 + 1 + 1, flat.reduce(+))
XCTAssertEqualObjects(["A", "B", "C"].reduceRight(+), "CBA")
}
func testImplode () {
let array = ["A", "B", "C"]
let imploded = array.implode("A")
XCTAssertEqualObjects(imploded!, "AABAC")
XCTAssertEqualObjects(array * ",", "A,B,C")
}
func testAt () {
XCTAssertEqualObjects(array.at(0, 2), [1, 3])
XCTAssertEqualObjects(array[0, 2, 1] as Int[], [1, 3, 2])
}
func testFlatten () {
let array = [5, [6, [7]], 8]
XCTAssertEqualObjects(array.flatten() as Int[], [5, 6, 7, 8])
}
func testGet () {
XCTAssertEqual(1, array.get(0)!)
XCTAssertEqual(array.get(-1)!, array.last()!)
XCTAssertEqual(array.get(array.count)!, array.first()!)
}
func testDuplicationOperator () {
XCTAssertEqualObjects(array * 3, (array + array + array))
}
func testLastIndexOf () {
let array = [5, 1, 2, 3, 2, 1]
XCTAssertEqual(array.count - 2, array.lastIndexOf(2)!)
XCTAssertEqual(array.count - 1, array.lastIndexOf(1)!)
XCTAssertEqual(0, array.lastIndexOf(5)!)
XCTAssertNil(array.lastIndexOf(20))
}
}
| 30.23494 | 115 | 0.54483 |
4aee30c11c5361a4939ea3da6c826c0f2426bb5c | 1,286 | //
// DetailIconSchemeHandler.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 11/7/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import WebKit
import Articles
class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler {
var currentArticle: Article?
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
guard let responseURL = urlSchemeTask.request.url, let iconImage = self.currentArticle?.iconImage() else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist))
return
}
let iconView = IconView(frame: CGRect(x: 0, y: 0, width: 48, height: 48))
iconView.iconImage = iconImage
let renderedImage = iconView.asImage()
guard let data = renderedImage.dataRepresentation() else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist))
return
}
let headerFields = ["Cache-Control": "no-cache"]
if let response = HTTPURLResponse(url: responseURL, statusCode: 200, httpVersion: nil, headerFields: headerFields) {
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
urlSchemeTask.didFailWithError(URLError(.unknown))
}
}
| 27.361702 | 118 | 0.750389 |
2298ba9227ab580600adbd58bab8428b4b4ff6ac | 9,652 | //
// BSConsultingController.swift
// ben_son
//
// Created by ZS on 2018/10/16.
// Copyright © 2018年 ZS. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class BSConsultingController: BSBaseController {
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
}
override func setupUI() {
super.setupUI()
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: buttonClose)
navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: buttonPhone)
view.addSubview(scrollerMain)
scrollerMain.addSubview(labelName)
scrollerMain.addSubview(labelDesc)
scrollerMain.addSubview(labelPhone)
scrollerMain.addSubview(btnCall)
scrollerMain.addSubview(labelTime)
scrollerMain.addSubview(btnOtherPhone)
scrollerMain.layer.addSublayer(line)
scrollerMain.addSubview(labelWheat)
scrollerMain.addSubview(labelWheaden)
scrollerMain.addSubview(btnWechat)
scrollerMain.addSubview(labelWheatNumber)
scrollerMain.addSubview(labelWheatintroduce)
buttonPhone.rx.tap.subscribe(onNext: { [weak self] in
let detailVc = RSCommonWebController()
detailVc.requestUrl = "http://p.qiao.baidu.com/cps2/chatIndex?reqParam=%7B%22from%22%3A0%2C%22sessionid%22%3A%22%22%2C%22siteId%22%3A%226109277%22%2C%22tid%22%3A%22-1%22%2C%22userId%22%3A%225643636%22%2C%22ttype%22%3A1%2C%22siteConfig%22%3A%7B%22eid%22%3A%225643636%22%2C%22queuing%22%3A%22%22%2C%22session%22%3A%7B%22displayName%22%3A%221**6%22%2C%22headUrl%22%3A%22https%3A%2F%2Fss0.bdstatic.com%2F7Ls0a8Sm1A5BphGlnYG%2Fsys%2Fportraitn%2Fitem%2F15881097.jpg%22%2C%22status%22%3A0%2C%22uid%22%3A0%2C%22uname%22%3A%22%22%7D%2C%22siteId%22%3A%226109277%22%2C%22online%22%3A%22true%22%2C%22webRoot%22%3A%22%2F%2Fp.qiao.baidu.com%2Fcps2%2F%22%2C%22bid%22%3A%222534443029061092770%22%2C%22userId%22%3A%225643636%22%2C%22invited%22%3A0%7D%2C%22config%22%3A%7B%22themeColor%22%3A%22000000%22%7D%7D&from=singlemessage&isappinstalled=0"
self?.navigationController?.pushViewController(detailVc, animated: true)
}).disposed(by: disposeBag)
buttonClose.rx.tap.subscribe(onNext: { [weak self] in
self?.navigationController?.dismiss(animated: true, completion: nil)
}).disposed(by: disposeBag)
btnCall.rx.tap.subscribe(onNext: {
BSTool.callPhone(phone: ben_son_number)
}).disposed(by: disposeBag)
btnOtherPhone.rx.tap.subscribe(onNext: { [weak self] in
let phoneListVc = BSPhoneListController()
self?.navigationController?.pushViewController(phoneListVc, animated: true)
}).disposed(by: disposeBag)
}
private lazy var scrollerMain: UIScrollView = {
let scroller = UIScrollView()
scroller.origin = CGPoint(x: 0, y: 0)
scroller.size = CGSize(width: kScreenWidth, height: UIDevice.current.contentNoTabBarHeight())
scroller.alwaysBounceVertical = true
scroller.backgroundColor = kMainBackBgColor
return scroller
}()
private lazy var labelName: UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWidthHexString(hex: "D9D9D9")
label.text = "客服热线"
label.left = kSpacing
label.size = CGSize(width: 100, height: 24)
label.top = 20
label.font = UIFont.init(name: "PingFangSC-Semibold", size: 18)
return label
}()
private lazy var labelDesc: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.colorWidthHexString(hex: "383838")
label.text = "Customer service telephone"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 20)
label.top = labelName.bottom + 4
return label
}()
private lazy var labelPhone: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 18)
label.textColor = UIColor.colorWidthHexString(hex: "A98054")
label.text = "400-645-8911(上海总部)"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 20)
label.top = labelDesc.bottom + kSpacing
return label
}()
private lazy var btnCall: UIButton = {
let btn = UIButton(type: UIButton.ButtonType.custom)
btn.size = CGSize(width: 30, height: 30)
btn.top = labelPhone.top - 5
btn.left = kScreenWidth - 45
btn.setImage(UIImage(named: "consulting_phone"), for: UIControl.State.normal)
btn.setImage(UIImage(named: "consulting_phone"), for: UIControl.State.highlighted)
return btn
}()
private lazy var labelTime: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.colorWidthHexString(hex: "53402F")
label.text = "服务时间 0:00-24:00"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 18)
label.top = labelPhone.bottom + 4.0
return label
}()
private lazy var btnOtherPhone: UIButton = {
let btn = UIButton(type: UIButton.ButtonType.custom)
btn.size = CGSize(width: kContentWidth, height: 30)
btn.top = labelTime.bottom + 15
btn.left = kSpacing
btn.contentHorizontalAlignment = .left
btn.setTitle("查看全国其他门店客服电话 ▶", for: UIControl.State.normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.setTitleColor(UIColor.colorWidthHexString(hex: "5C5C5C"), for: UIControl.State.normal)
return btn
}()
private lazy var line: CALayer = {
let l = CALayer()
l.backgroundColor = UIColor.colorWidthHexString(hex: "383838").cgColor
l.frameSize = CGSize(width: kContentWidth, height: 0.5)
l.origin = CGPoint(x: kSpacing, y: btnOtherPhone.bottom + 15)
return l
}()
private lazy var labelWheat: UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWidthHexString(hex: "D9D9D9")
label.text = "微信客服"
label.left = kSpacing
label.size = CGSize(width: 100, height: 24)
label.top = line.bottom + 20
label.font = UIFont.init(name: "PingFangSC-Semibold", size: 18)
return label
}()
private lazy var labelWheaden: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.colorWidthHexString(hex: "383838")
label.text = "Customer service telephone"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 20)
label.top = labelWheat.bottom + 4
return label
}()
private lazy var btnWechat: UIImageView = {
let btn = UIImageView()
btn.size = CGSize(width: 120, height: 120)
btn.top = labelWheaden.bottom + 30
btn.left = (kScreenWidth - 120) * 0.5
btn.image = UIImage(named: "image_qrcode")
btn.isUserInteractionEnabled = true
let longTap = UILongPressGestureRecognizer()
// longTap.minimumPressDuration = 2
btn.addGestureRecognizer(longTap)
longTap.rx.event.subscribe(onNext: {[weak self] (recognizer) in
if recognizer.state != UIGestureRecognizer.State.began {
return
}
self?.saveImage()
}).disposed(by: disposeBag)
return btn
}()
private lazy var labelWheatNumber: UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWidthHexString(hex: "BFBFBF")
label.text = "微信公众号:BensonSupercarClub"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 24)
label.top = btnWechat.bottom + 15
label.font = UIFont.systemFont(ofSize: 15)
label.textAlignment = .center
return label
}()
private lazy var labelWheatintroduce: UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWidthHexString(hex: "5C5C5C")
label.text = "可长按图片,保存到相册后再扫描"
label.left = kSpacing
label.size = CGSize(width: kContentWidth, height: 16)
label.top = labelWheatNumber.bottom + 5
label.font = UIFont.systemFont(ofSize: 13)
label.textAlignment = .center
return label
}()
private lazy var buttonPhone: UIButton = {
let btn = UIButton(type: UIButton.ButtonType.custom)
btn.setImage(UIImage(named: "consulting_icon_chat"), for: UIControl.State.normal)
btn.setImage(UIImage(named: "consulting_icon_chat"), for: UIControl.State.highlighted)
btn.size = CGSize(width: 90, height: 30)
btn.setTitle(" 在线咨询", for: UIControl.State.normal)
btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
return btn
}()
private lazy var buttonClose: UIButton = {
let btn = UIButton(type: UIButton.ButtonType.custom)
btn.setImage(UIImage(named: "common_close"), for: UIControl.State.normal)
btn.setImage(UIImage(named: "common_close"), for: UIControl.State.highlighted)
btn.size = CGSize(width: 30, height: 30)
return btn
}()
}
extension BSConsultingController {
private func saveImage() {
BSTool.showAlertView(title: "保存图片", message: nil, image: btnWechat.image, vc: self)
}
}
| 41.247863 | 840 | 0.649503 |
9b0a18cd3416ff49f19559fd7d071d51a70bdcb2 | 5,875 | import NIO
extension PostgresMessage {
/// First message sent from the frontend during startup.
public struct Error: PostgresMessageType, CustomStringConvertible {
public static var identifier: PostgresMessage.Identifier {
return .error
}
/// Parses an instance of this message type from a byte buffer.
public static func parse(from buffer: inout ByteBuffer) throws -> Error {
var fields: [Field: String] = [:]
while let field = buffer.readInteger(as: Field.self) {
guard let string = buffer.readNullTerminatedString() else {
throw PostgresError.protocol("Could not read error response string.")
}
fields[field] = string
}
return .init(fields: fields)
}
public enum Field: UInt8, Hashable {
/// Severity: the field contents are ERROR, FATAL, or PANIC (in an error message),
/// or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a
//// localized translation of one of these. Always present.
case localizedSeverity = 0x53 /// S
/// Severity: the field contents are ERROR, FATAL, or PANIC (in an error message),
/// or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message).
/// This is identical to the S field except that the contents are never localized.
/// This is present only in messages generated by PostgreSQL versions 9.6 and later.
case severity = 0x56 /// V
/// Code: the SQLSTATE code for the error (see Appendix A). Not localizable. Always present.
case sqlState = 0x43 /// C
/// Message: the primary human-readable error message. This should be accurate but terse (typically one line).
/// Always present.
case message = 0x4D /// M
/// Detail: an optional secondary error message carrying more detail about the problem.
/// Might run to multiple lines.
case detail = 0x44 /// D
/// Hint: an optional suggestion what to do about the problem.
/// This is intended to differ from Detail in that it offers advice (potentially inappropriate)
/// rather than hard facts. Might run to multiple lines.
case hint = 0x48 /// H
/// Position: the field value is a decimal ASCII integer, indicating an error cursor
/// position as an index into the original query string. The first character has index 1,
/// and positions are measured in characters not bytes.
case position = 0x50 /// P
/// Internal position: this is defined the same as the P field, but it is used when the
/// cursor position refers to an internally generated command rather than the one submitted by the client.
/// The q field will always appear when this field appears.
case internalPosition = 0x70 /// p
/// Internal query: the text of a failed internally-generated command.
/// This could be, for example, a SQL query issued by a PL/pgSQL function.
case internalQuery = 0x71 /// q
/// Where: an indication of the context in which the error occurred.
/// Presently this includes a call stack traceback of active procedural language functions and
/// internally-generated queries. The trace is one entry per line, most recent first.
case locationContext = 0x57 /// W
/// Schema name: if the error was associated with a specific database object, the name of
/// the schema containing that object, if any.
case schemaName = 0x73 /// s
/// Table name: if the error was associated with a specific table, the name of the table.
/// (Refer to the schema name field for the name of the table's schema.)
case tableName = 0x74 /// t
/// Column name: if the error was associated with a specific table column, the name of the column.
/// (Refer to the schema and table name fields to identify the table.)
case columnName = 0x63 /// c
/// Data type name: if the error was associated with a specific data type, the name of the data type.
/// (Refer to the schema name field for the name of the data type's schema.)
case dataTypeName = 0x64 /// d
/// Constraint name: if the error was associated with a specific constraint, the name of the constraint.
/// Refer to fields listed above for the associated table or domain. (For this purpose, indexes are
/// treated as constraints, even if they weren't created with constraint syntax.)
case constraintName = 0x6E /// n
/// File: the file name of the source-code location where the error was reported.
case file = 0x46 /// F
/// Line: the line number of the source-code location where the error was reported.
case line = 0x4C /// L
/// Routine: the name of the source-code routine reporting the error.
case routine = 0x52 /// R
}
/// The diagnostic messages.
public var fields: [Field: String]
/// See `CustomStringConvertible`.
public var description: String {
let unique = self.fields[.routine] ?? self.fields[.sqlState] ?? "unknown"
let message = self.fields[.message] ?? "Unknown"
return "\(message) (\(unique))"
}
}
}
| 52.927928 | 122 | 0.586553 |
7adb5c09eae50afaa98d1dc78a0c96cd4fa13c86 | 3,374 | //
// SupportedStoryboard.blackboard.swift
//
// This file is automatically generated; do not modify.
//
import UIKit
private let sharedStoryboardInstance = UIStoryboard(name: "Supported", bundle: nil)
extension EmptyCollectionViewController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyCollectionViewController: EmptyCollectionViewController) -> Void)? = nil) -> EmptyCollectionViewController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyCollectionViewController", initialize)
}
// Collection View Cells
enum CollectionViewCellIdentifier: String {
case cell = "Cell"
}
final func dequeueCell(from collectionView: UICollectionView, for indexPath: IndexPath, initialize: ((_ cell: UICollectionViewCell) -> Void)? = nil) -> UICollectionViewCell {
collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCellIdentifier.cell.rawValue, for: indexPath, initialize)
}
}
extension EmptyNavigationController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyNavigationController: EmptyNavigationController) -> Void)? = nil) -> EmptyNavigationController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyNavigationController", initialize)
}
}
extension EmptyPageViewController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyPageViewController: EmptyPageViewController) -> Void)? = nil) -> EmptyPageViewController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyPageViewController", initialize)
}
}
extension EmptyTabBarController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyTabBarController: EmptyTabBarController) -> Void)? = nil) -> EmptyTabBarController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyTabBarController", initialize)
}
}
extension EmptyTableViewController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyTableViewController: EmptyTableViewController) -> Void)? = nil) -> EmptyTableViewController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyTableViewController", initialize)
}
// Table View Cells
enum TableViewCellIdentifier: String {
case cell = "Cell"
}
final func dequeueCell(from tableView: UITableView, for indexPath: IndexPath, initialize: ((_ cell: UITableViewCell) -> Void)? = nil) -> UITableViewCell {
tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifier.cell.rawValue, for: indexPath, initialize)
}
}
extension EmptyViewController {
final class func instantiateFromStoryboard(_ initialize: ((_ emptyViewController: EmptyViewController) -> Void)? = nil) -> EmptyViewController {
instantiateViewController(from: sharedStoryboardInstance, identifier: "EmptyViewController", initialize)
}
final class func instantiateNavigationControllerFromStoryboard(_ initialize: ((_ emptyViewController: EmptyViewController) -> Void)? = nil) -> UINavigationController {
instantiateNavigationController(from: sharedStoryboardInstance, identifier: "EmptyNavigationController", initialize)
}
}
| 41.146341 | 178 | 0.752223 |
ff82b57a2d36da5b405873214e754ab3d4e757e2 | 6,395 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Dispatch
import Foundation
import TSCBasic
public typealias CancellationHandler = (DispatchTime) throws -> Void
public class Cancellator: Cancellable {
public typealias RegistrationKey = String
private let observabilityScope: ObservabilityScope?
private let registry = ThreadSafeKeyValueStore<String, (name: String, handler: CancellationHandler)>()
private let cancelationQueue = DispatchQueue(label: "org.swift.swiftpm.cancellator", qos: .userInteractive, attributes: .concurrent)
private let cancelling = ThreadSafeBox<Bool>(false)
public init(observabilityScope: ObservabilityScope?) {
self.observabilityScope = observabilityScope
}
@discardableResult
public func register(name: String, handler: @escaping CancellationHandler) -> RegistrationKey? {
if self.cancelling.get(default: false) {
self.observabilityScope?.emit(debug: "not registering '\(name)' with terminator, termination in progress")
return .none
}
let key = UUID().uuidString
self.observabilityScope?.emit(debug: "registering '\(name)' with terminator")
self.registry[key] = (name: name, handler: handler)
return key
}
@discardableResult
public func register(name: String, handler: Cancellable) -> RegistrationKey? {
self.register(name: name, handler: handler.cancel(deadline:))
}
@discardableResult
public func register(name: String, handler: @escaping () throws -> Void) -> RegistrationKey? {
self.register(name: name, handler: { _ in try handler() })
}
public func register(_ process: TSCBasic.Process) -> RegistrationKey? {
self.register(name: "\(process.arguments.joined(separator: " "))", handler: process.terminate)
}
#if !os(iOS) && !os(watchOS) && !os(tvOS)
public func register(_ process: Foundation.Process) -> RegistrationKey? {
self.register(name: "\(process.description)", handler: process.terminate(timeout:))
}
#endif
public func deregister(_ key: RegistrationKey) {
self.registry[key] = nil
}
public func cancel(deadline: DispatchTime) throws -> Void {
self._cancel(deadline: deadline)
}
// marked internal for testing
@discardableResult
internal func _cancel(deadline: DispatchTime? = .none)-> Int {
self.cancelling.put(true)
self.observabilityScope?.emit(info: "starting cancellation cycle with \(self.registry.count) cancellation handlers registered")
let deadline = deadline ?? .now() + .seconds(30)
// deadline for individual handlers set slightly before overall deadline
let delta: DispatchTimeInterval = .nanoseconds(abs(deadline.distance(to: .now()).nanoseconds() ?? 0) / 5)
let handlersDeadline = deadline - delta
let cancellationHandlers = self.registry.get()
let cancelled = ThreadSafeArrayStore<String>()
let group = DispatchGroup()
for (_, (name, handler)) in cancellationHandlers {
self.cancelationQueue.async(group: group) {
do {
self.observabilityScope?.emit(debug: "cancelling '\(name)'")
try handler(handlersDeadline)
cancelled.append(name)
} catch {
self.observabilityScope?.emit(warning: "failed cancelling '\(name)': \(error)")
}
}
}
if case .timedOut = group.wait(timeout: deadline) {
self.observabilityScope?.emit(warning: "timeout waiting for cancellation with \(cancellationHandlers.count - cancelled.count) cancellation handlers remaining")
} else {
self.observabilityScope?.emit(info: "cancellation cycle completed successfully")
}
self.cancelling.put(false)
return cancelled.count
}
}
public protocol Cancellable {
func cancel(deadline: DispatchTime) throws -> Void
}
public struct CancellationError: Error, CustomStringConvertible {
public let description = "Operation cancelled"
public init() {}
}
extension TSCBasic.Process {
fileprivate func terminate(timeout: DispatchTime) {
// send graceful shutdown signal
self.signal(SIGINT)
// start a thread to see if we need to terminate more forcibly
let forceKillSemaphore = DispatchSemaphore(value: 0)
let forceKillThread = TSCBasic.Thread {
if case .timedOut = forceKillSemaphore.wait(timeout: timeout) {
// send a force-kill signal
#if os(Windows)
self.signal(SIGTERM)
#else
self.signal(SIGKILL)
#endif
}
}
forceKillThread.start()
_ = try? self.waitUntilExit()
forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more
// join the force-kill thread thread so we don't exit before everything terminates
forceKillThread.join()
}
}
#if !os(iOS) && !os(watchOS) && !os(tvOS)
extension Foundation.Process {
fileprivate func terminate(timeout: DispatchTime) {
// send graceful shutdown signal (SIGINT)
self.interrupt()
// start a thread to see if we need to terminate more forcibly
let forceKillSemaphore = DispatchSemaphore(value: 0)
let forceKillThread = TSCBasic.Thread {
if case .timedOut = forceKillSemaphore.wait(timeout: timeout) {
// force kill (SIGTERM)
self.terminate()
}
}
forceKillThread.start()
self.waitUntilExit()
forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more
// join the force-kill thread thread so we don't exit before everything terminates
forceKillThread.join()
}
}
#endif
| 38.293413 | 171 | 0.636904 |
ef4619f93ea99378360068f00f1b9ea50b138de5 | 6,984 | /**
Copyright (c) 2017 Uber Technologies, Inc.
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
protocol SignatureBezierProviderDelegate: class {
/**
Provides the temporary signature bezier.
This can be displayed to represent the most recent points of the signature,
to give the feeling of real-time drawing but should not be permanently
drawn, as it will change as more points are added.
*/
func updatedTemporaryBezier(_ bezier: UIBezierPath?)
/**
Provides the finalized signature bezier.
When enough points are added to form a full bezier curve, this will be
returned as the finalized bezier and the temporary will reset.
*/
func generatedFinalizedBezier(_ bezier: UIBezierPath)
}
/**
Provides signature styled beziers using delegate callbacks as points are added.
Temporary signature will change every time a point is added, occasionally a
finalized bezier will be generated, which should be cached, as the temporary
will then reset.
Forms one continuous signature line. Call reset() to start generating a new line.
*/
class SignatureBezierProvider {
/// The weight of a signature-styled dot.
static let dotWeight: CGFloat = 3
/// If a new point is added without being at least this distance from the previous point, it will be ignored.
static let touchDistanceThreshold: CGFloat = 2
/**
Adds apoint to the signature line.
The weight of the signature is based on the distance between these points,
further apart making the line thinner.
The delegate will receive callbacks when this function is used.
*/
func addPointToSignature(_ point: CGPoint) {
if isFirstPoint {
startNewLine(from: WeightedPoint(point: point, weight: SignatureBezierProvider.dotWeight))
} else {
let previousPoint = points[nextPointIndex - 1].point
guard previousPoint.distance(to: point) >= SignatureBezierProvider.touchDistanceThreshold else {
return
}
if isStartOfNextLine {
finalizeBezier(nextLineStartPoint: point)
startNewLine(from: points[3])
}
let weightedPoint = WeightedPoint(point: point, weight: SignatureBezierProvider.signatureWeightForLine(between: previousPoint, and: point))
addPoint(point: weightedPoint)
}
let newBezier = generateBezierPath(withPointIndex: nextPointIndex - 1)
delegate?.updatedTemporaryBezier(newBezier)
}
/// Resets the provider - addPointToSignature() will start a new line after.
func reset() {
nextPointIndex = 0
delegate?.updatedTemporaryBezier(nil)
}
/// Delegate for callbacks
weak var delegate: SignatureBezierProviderDelegate?
// MARK: Private
private static let pointsPerLine: Int = 4
private var nextPointIndex: Int = 0
private var points = [WeightedPoint](repeating: WeightedPoint.zero, count: SignatureBezierProvider.pointsPerLine)
private var isFirstPoint: Bool {
return nextPointIndex == 0
}
private var isStartOfNextLine: Bool {
return nextPointIndex >= SignatureBezierProvider.pointsPerLine
}
private func startNewLine(from weightedPoint: WeightedPoint) {
points[0] = weightedPoint
nextPointIndex = 1
}
private func addPoint(point: WeightedPoint) {
points[nextPointIndex] = point
nextPointIndex += 1
}
private func finalizeBezier(nextLineStartPoint: CGPoint) {
/*
Smooth the join between beziers by modifying the last point of the current bezier
to equal the average of the points either side of it.
*/
let touchPoint2 = points[2].point
let newTouchPoint3 = touchPoint2.average(with: nextLineStartPoint)
points[3] = WeightedPoint(point: newTouchPoint3, weight: SignatureBezierProvider.signatureWeightForLine(between: touchPoint2, and: newTouchPoint3))
guard let bezier = generateBezierPath(withPointIndex: 3) else {
return
}
delegate?.generatedFinalizedBezier(bezier)
}
private func generateBezierPath(withPointIndex index: Int) -> UIBezierPath? {
switch index {
case 0:
return UIBezierPath.dot(with: points[0])
case 1:
return UIBezierPath.line(withWeightedPointA: points[0], pointB: points[1])
case 2:
return UIBezierPath.quadCurve(withWeightedPointA: points[0], pointB: points[1], pointC: points[2])
case 3:
return UIBezierPath.bezierCurve(withWeightedPointA: points[0], pointB: points[1], pointC: points[2], pointD: points[3])
default:
return nil
}
}
// MARK: Helpers
private class func signatureWeightForLine(between pointA: CGPoint, and pointB: CGPoint) -> CGFloat {
let length = pointA.distance(to: pointB)
/**
The is the maximum length that will vary weight. Anything higher will return the same weight.
*/
let maxLengthRange: CGFloat = 50
/*
These are based on having a minimum line thickness of 2.0 and maximum of 7, linearly over line lengths 0-maxLengthRange. They fit into a typical linear equation: y = mx + c
Note: Only the points of the two parallel bezier curves will be at least as thick as the constant. The bezier curves themselves could still be drawn with sharp angles, meaning there is no true 'minimum thickness' of the signature.
*/
let gradient: CGFloat = 0.1
let constant: CGFloat = 2
var inversedLength = maxLengthRange - length
if inversedLength < 0 {
inversedLength = 0
}
return (inversedLength * gradient) + constant
}
}
| 39.457627 | 239 | 0.680126 |
6ae0167d5cf019624f490a1a628b46491dc2c603 | 467 | //
// QuoteEntity+CoreDataProperties.swift
// FavQuotes
//
// Created by Jeffery Wang on 10/5/20.
// Copyright © 2020 eagersoft.io. All rights reserved.
//
//
import Foundation
import CoreData
extension QuoteEntity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<QuoteEntity> {
return NSFetchRequest<QuoteEntity>(entityName: "QuoteEntity")
}
@NSManaged public var quote: String?
@NSManaged public var author: String?
}
| 19.458333 | 78 | 0.708779 |
e89905c7d1e7e24b2422482be952a40c6287d308 | 1,101 | //
// RepositoryCellViewModel.swift
// GithubRepoExample
//
// Created by Javier Cancio on 21/1/17.
// Copyright © 2017 Javier Cancio. All rights reserved.
//
import Foundation
import RxSwift
class RepositoryCellViewModel {
// Output
var repositoryName = Variable("")
var repositoryOrganization = Variable("")
var repositoryStars = Variable("")
var repositoryForks = Variable("")
var repositoryImage: Observable<UIImage?>
private var service: ServiceType
private let repository: Repository
init(repository: Repository, service: ServiceType) {
self.repository = repository
self.service = service
self.repositoryName.value = repository.name
self.repositoryOrganization.value = repository.organization
self.repositoryStars.value = "✭ \(repository.stars)"
self.repositoryForks.value = "⑂ \(repository.forks)"
let url = URL(string: self.repository.avatar)
if let url = url {
self.repositoryImage = service.downloadImage(from: url)
} else {
self.repositoryImage = Observable.just(UIImage())
}
}
}
| 23.934783 | 63 | 0.698456 |
3920499328d5c007fe24543bf1963195c7cb8504 | 475 | //
// UIView+AddBottmLine.swift
// BYLSwiftCommonHelper
//
// Created by Ben Liu on 16/9/19.
// Copyright © 2019 Flyingbits. All rights reserved.
//
import Foundation
extension UIView {
func addBottmLine() {
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0.0, y: self.frame.height - 1, width: self.frame.width, height: 1.0)
bottomLine.backgroundColor = UIColor.white.cgColor
self.layer.addSublayer(bottomLine)
}
}
| 22.619048 | 105 | 0.661053 |
0ab3cee5c8c5197e6f53518b7df1549bcd39f303 | 1,003 | //
// CVImageBuffer.swift
// QKMRZScanner
//
// Created by Matej Dorcak on 10/07/2019.
//
import Foundation
import CoreVideo
extension CVImageBuffer {
var cgImage: CGImage? {
CVPixelBufferLockBaseAddress(self, .readOnly)
let baseAddress = CVPixelBufferGetBaseAddress(self)
let bytesPerRow = CVPixelBufferGetBytesPerRow(self)
let (width, height) = (CVPixelBufferGetWidth(self), CVPixelBufferGetHeight(self))
let bitmapInfo = CGBitmapInfo(rawValue: (CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue))
let context = CGContext.init(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue)
guard let cgImage = context?.makeImage() else {
return nil
}
CVPixelBufferUnlockBaseAddress(self, .readOnly)
return cgImage
}
}
| 32.354839 | 203 | 0.692921 |
d54762ce317c081e2cce0da0efc8ddfd8df9749d | 19,052 | //
// DateExtension.swift
// Supership
//
// Created by Mac on 8/9/18.
// Copyright © 2018 Padi. All rights reserved.
//
import Foundation
extension ISO8601DateFormatter {
convenience init(_ formatOptions: Options, timeZone: TimeZone = TimeZone(secondsFromGMT: 0)!) {
self.init()
self.formatOptions = formatOptions
self.timeZone = timeZone
}
}
extension Formatter {
static let iso8601withFractionalSeconds = ISO8601DateFormatter([.withInternetDateTime, .withFractionalSeconds])
}
extension Date {
var iso8601withFractionalSeconds: String { return Formatter.iso8601withFractionalSeconds.string(from: self) }
}
extension String {
var iso8601withFractionalSeconds: Date? { return Formatter.iso8601withFractionalSeconds.date(from: self) }
}
extension String{
var getTimeHHmm: String{
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let fullDate = fmt.date(from: self){
let calendar = Calendar.current
let hour = calendar.component(.hour, from: fullDate)
let minutes = calendar.component(.minute, from: fullDate)
var hourString = "\(hour)"
if hour < 10 { hourString = "0\(hour)" }
var minString = "\(minutes)"
if minutes < 10 { minString = "0\(minutes)" }
return "\(hourString):\(minString)"
}else{
return ""
}
}
// var toDate: Date? {
// let fmt = DateFormatter()
// fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
// if let fullDate = fmt.date(from: self){
// return fullDate
// }
// }
}
extension Date {
static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate,
.withTime,
.withDashSeparatorInDate,
.withColonSeparatorInTime]
return formatter
}()
var calendar: Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = .current
calendar.locale = .current
return calendar
}
var toApiDateFormatString: String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
// fmt.locale = Locale(identifier: "en_US_POSIX")
// fmt.timeZone = TimeZone(abbreviation: "JST")
return fmt.string(from: self)
}
var toApiDateFormat: Date {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(abbreviation: "JST")
return fmt.date(from: fmt.string(from: self)) ?? self
}
var toApiYearMonthFormat: String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM"
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(abbreviation: "JST")
return fmt.string(from: self)
}
var toApiDateTimeFormat: String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(abbreviation: "JST")
return fmt.string(from: self)
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 9月27日(金)
var toHourMinSec : String {
let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss"
let fullDateString = fmt.string(from: self)
return "\(fullDateString)"
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 2020年9月
var toJpYearDate: String {
let fmt = DateFormatter()
fmt.dateFormat = "MM/yyyy"
let fullDateString = fmt.string(from: self)
return fullDateString
}
var toHourMinUTC7 : String {
// *** create calendar object ***
var calendar = Calendar.current
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone.current
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: self)
let minutes = calendar.component(.minute, from: self)
return "\(hour > 9 ? "\(hour)" : "0\(hour)"):\(minutes > 9 ? "\(minutes)" : "0\(minutes)")"
}
var toHourMinSecUTC7 : String {
// *** create calendar object ***
var calendar = Calendar.current
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone.current
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: self)
let minutes = calendar.component(.minute, from: self)
let sec = calendar.component(.second, from: self)
return "\(hour > 9 ? "\(hour)" : "0\(hour)"):\(minutes > 9 ? "\(minutes)" : "0\(minutes)"):\(sec > 9 ? "\(sec)" : "0\(sec)")"
}
var toHourMinUTC : String {
// *** create calendar object ***
var calendar = Calendar.current
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: self)
let minutes = calendar.component(.minute, from: self)
return "\(hour > 9 ? "\(hour)" : "0\(hour)"):\(minutes > 9 ? "\(minutes)" : "0\(minutes)")"
}
var toFullDateUTC : String {
// *** create calendar object ***
var calendar = Calendar.current
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: self)
let minutes = calendar.component(.minute, from: self)
let sec = calendar.component(.second, from: self)
let year = calendar.component(.year, from: self)
let month = calendar.component(.month, from: self)
let day = calendar.component(.day, from: self)
return "\(hour > 9 ? "\(hour)" : "0\(hour)"):\(minutes > 9 ? "\(minutes)" : "0\(minutes)"):\(sec > 9 ? "\(sec)" : "0\(sec)") \(day > 9 ? "\(day)" : "0\(day)")/\(month > 9 ? "\(month)" : "0\(month)")/\(year)"
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 2020年
var toJpYear: String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy年"
let fullDateString = fmt.string(from: self)
return fullDateString
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 09月
var toJpMonth: String {
let fmt = DateFormatter()
fmt.dateFormat = "MM月"
let fullDateString = fmt.string(from: self)
return fullDateString
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 15日
var toDay: String {
let fmt = DateFormatter()
fmt.dateFormat = "dd"
let fullDateString = fmt.string(from: self)
return fullDateString
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 15日
var toJpDay: String {
let fmt = DateFormatter()
fmt.dateFormat = "dd日"
let fullDateString = fmt.string(from: self)
return fullDateString
}
/// Convert Date to String
/// - Parameter
/// - Returns: example 2020年9月
var toYearMonthDay: String {
let fmt = DateFormatter()
fmt.dateFormat = "dd/MM/yyyy"
let fullDateString = fmt.string(from: self)
return fullDateString
}
var fullTimeString: String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let fullDateString = fmt.string(from: self)
return fullDateString
}
var toJSTDateTimeFormat: Date {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(abbreviation: "JST")
let string = fmt.string(from: self)
return fmt.date(from: string) ?? Date()
}
func getDayOfWeek(_ today: String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .japanese)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}
var gregorianYear: Int {
let com = self.calendar.dateComponents([.year], from: self)
return com.year!
}
var gregorianMonth: Int {
let com = self.calendar.dateComponents([.month], from: self)
return com.month!
}
var gregorianDay: Int {
let com = self.calendar.dateComponents([.day], from: self)
return com.day!
}
func getGregorianDate(year: Int = 1990, month: Int = 1, day: Int = 1, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date {
let calendar = self.calendar
var com = DateComponents()
com.year = year
com.month = month
com.day = day
com.hour = hour
com.minute = minute
com.second = second
return calendar.date(from: com)!
}
func getLast6Month() -> Date? {
return self.calendar.date(byAdding: .month, value: -6, to: self)
}
func getLast3Month() -> Date? {
return self.calendar.date(byAdding: .month, value: -3, to: self)
}
func getYesterday() -> Date? {
return self.calendar.date(byAdding: .day, value: -1, to: self)
}
func getTomorrow() -> Date? {
return self.calendar.date(byAdding: .day, value: 1, to: self)
}
func getLast7Day() -> Date? {
return self.calendar.date(byAdding: .day, value: -7, to: self)
}
func getLastAnyDay(value: Int) -> Date? {
return self.calendar.date(byAdding: .day, value: value, to: self)
}
func getLast30Day() -> Date? {
return self.calendar.date(byAdding: .day, value: -30, to: self)
}
func getPreviousMonth() -> Date? {
return self.calendar.date(byAdding: .month, value: -1, to: self)
}
// This week start
func getThisWeekStart() -> Date? {
let calendar = self.calendar
let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
let firstDayOfWeek = calendar.date(from: components)
return firstDayOfWeek
}
func getThisWeekEnd() -> Date? {
guard let thisWeekStartDate = self.getThisWeekStart() else {
return nil
}
let calender = self.calendar
return calender.date(byAdding: .day, value: 6, to: thisWeekStartDate)
}
func getPreviousWeekStart() -> Date? {
guard let thisWeekStartDate = self.getThisWeekStart() else {
return nil
}
let calender = self.calendar
return calender.date(byAdding: .day, value: -7, to: thisWeekStartDate)
}
func getNextWeekStart() -> Date? {
guard let thisWeekStartDate = self.getThisWeekStart() else {
return nil
}
let calender = self.calendar
return calender.date(byAdding: .day, value: 7, to: thisWeekStartDate)
}
// This Month Start
func getDaysInMonth() -> Int {
let calendar = self.calendar
let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
return numDays
}
func getThisMonthStart() -> Date? {
let components = self.calendar.dateComponents([.year, .month], from: self)
return self.calendar.date(from: components)!
}
func getThisMonthEnd() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.month += 1
components.day = 1
components.day -= 1
return Calendar.current.date(from: components as DateComponents)!
}
// Last Month Start
func getLastMonthStart() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.month -= 1
return self.calendar.date(from: components as DateComponents)!
}
// Last Month End
func getLastMonthEnd() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.day = 1
components.day -= 1
return self.calendar.date(from: components as DateComponents)!
}
// Next Month Start
func getNextMonthStart() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.month += 1
return self.calendar.date(from: components as DateComponents)!
}
// Next Month End
func getNextThirdMonthEnd() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.month += 4
components.day = 1
components.day -= 1
return self.calendar.date(from: components as DateComponents)!
}
// Next Next Month Start
func getNextNextMonthStart() -> Date? {
let components: NSDateComponents = self.calendar.dateComponents([.year, .month], from: self) as NSDateComponents
components.month += 2
return self.calendar.date(from: components as DateComponents)!
}
func getSecondOrFourthSundayInMonth() -> Date? {
let weekday = self.calendar.component(.weekday, from: self)
let nextWeekend = self.calendar.date(byAdding: .day, value: 8 - weekday, to: self) ?? Date()
let weekOfMonth = self.calendar.dateComponents([.weekOfMonth], from: nextWeekend).weekOfMonth
if weekOfMonth == 1 || weekOfMonth == 3 {
return self.calendar.date(byAdding: .day, value: 7, to: nextWeekend)
} else if weekOfMonth == 2 || weekOfMonth == 4 {
return nextWeekend
} else {
return self.calendar.date(byAdding: .day, value: 14, to: nextWeekend)
}
}
// func toString(_ format: String) -> String {
// PAppManager.shared.dateFormater.dateFormat = format
// return PAppManager.shared.dateFormater.string(from: self)
// }
func freeFormat(_ format: String) -> String {
let fmt = DateFormatter()
fmt.dateFormat = format
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(abbreviation: "JST")
return fmt.string(from: self)
}
// func fromString(dateString: String, format: String? = "yyyy-MM-dd HH:mm:ss") -> Date? {
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = format
// return dateFormatter.date(from: dateString)
// }
}
extension Date {
/// Returns the amount of years from another date
func years(from date: Date) -> Int {
return self.calendar.dateComponents([.year], from: date, to: self).year ?? 0
}
/// Returns the amount of months from another date
func months(from date: Date) -> Int {
return self.calendar.dateComponents([.month], from: date, to: self).month ?? 0
}
/// Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
return self.calendar.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
/// Returns the amount of days from another date
func days(from date: Date) -> Int {
return self.calendar.dateComponents([.day], from: date, to: self).day ?? 0
}
/// Returns the day of week from another date
func dayOfWeek(from date: Date) -> Int {
return self.calendar.dateComponents([.weekday], from: date, to: self).weekday ?? 0
}
/// Returns the amount of hours from another date
func hours(from date: Date) -> Int {
return self.calendar.dateComponents([.hour], from: date, to: self).hour ?? 0
}
/// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return self.calendar.dateComponents([.minute], from: date, to: self).minute ?? 0
}
/// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return self.calendar.dateComponents([.second], from: date, to: self).second ?? 0
}
/// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
if self.years(from: date) > 0 { return "\(self.years(from: date))y" }
if self.months(from: date) > 0 { return "\(self.months(from: date))M" }
if self.weeks(from: date) > 0 { return "\(self.weeks(from: date))w" }
if self.days(from: date) > 0 { return "\(self.days(from: date))d" }
if self.hours(from: date) > 0 { return "\(self.hours(from: date))h" }
if self.minutes(from: date) > 0 { return "\(self.minutes(from: date))m" }
if self.seconds(from: date) > 0 { return "\(self.seconds(from: date))s" }
return ""
}
}
extension TimeInterval {
func stringFromTimeInterval(interval: TimeInterval) -> String {
let time = NSInteger(interval)
let ms = Int(self.truncatingRemainder(dividingBy: 1) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d", hours, minutes, seconds, ms)
}
}
extension Date {
var convertedDate: Date {
return self
//
// let dateFormatter = DateFormatter();
// let formattedDate = dateFormatter.string(from: self);
// dateFormatter.dateStyle = .full
// dateFormatter.timeStyle = .full
// dateFormatter.locale = Locale(identifier: "en_US_POSIX");
// let sourceDate = dateFormatter.date(from: formattedDate as String);
//
// return sourceDate!;
}
}
| 35.281481 | 225 | 0.58503 |
22ebd63f1829a1d8e21c89041bfbb788d8c30617 | 955 | //
// CoreKitTests.swift
// CoreKitTests
//
// Created by AMIT on 07/07/17.
// Copyright © 2017 acme. All rights reserved.
//
import XCTest
@testable import CoreKit
class CoreKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.810811 | 111 | 0.628272 |
8f41dc9eaace42dae5f75ae0baafcae91bce690a | 845 | //
// CGRequestParam.swift
// rider
//
// Created by Đinh Anh Huy on 10/14/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
import ObjectMapper
//
//class CGLocation: Mappable {
// var long: Double?
// var lat: Double?
//
// init() {
//
// }
//
// required init?(map: Map) {
//
// }
//
// func mapping(map: Map) {
// long <- map["long"]
// lat <- map["lat"]
// }
//}
class CGRequestParam: Mappable {
var id: String?
var pickupLocation: CGLocation?
var destination: CGLocation?
init() {
}
required init?(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
pickupLocation <- map["pickupLocation"]
destination <- map["destination"]
}
}
| 17.244898 | 55 | 0.494675 |
d930769e1b1549a7df42b428e50e461597a106c4 | 2,548 | //
// LoginViewController.swift
// Shirtist
//
// Created by Ravi Shankar Jha on 10/12/15.
// Copyright © 2015 Ravi Shankar Jha. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginTapped(sender: UIButton) {
let userEmail = userEmailTextField.text
let userPassword = passwordTextField.text
let userEmailStored = NSUserDefaults.standardUserDefaults().objectForKey("userEmail") as! String
let userPasswordStored = NSUserDefaults.standardUserDefaults().objectForKey("userPassword") as! String
print (userEmail)
print (userEmailStored)
print (userPassword)
print (userPasswordStored)
if ((userEmail! == userEmailStored) && (userPassword! == userPasswordStored))
{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
let vc : AnyObject! = self.storyboard!.instantiateViewControllerWithIdentifier("featuredProduct")
self.showViewController(vc as! UIViewController, sender: vc)
} else
{
let myAlert = UIAlertController(title: "Alert", message: "Check Email and Password", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion: nil)
}
}
/*
// 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.
}
*/
}
| 31.073171 | 120 | 0.625196 |
efa1a6d1235367527d7028807bf8ad4be578c85e | 138 |
import Foundation
public struct Reusing {
public static func sayHello(with name: String) {
print("\(name)님 안녕하세요.")
}
}
| 15.333333 | 52 | 0.637681 |
727bd068b63f47e7044abbe06d6858b49e2b5584 | 5,781 | //
// KeychainOptions.swift
// SwiftKeychainWrapper
//
// Created by James Blair on 4/24/16.
// Copyright © 2016 Jason Rendel. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
protocol KeychainAttrRepresentable {
var keychainAttrValue: CFString { get }
}
// MARK: - KeychainItemAccessibility
public enum KeychainItemAccessibility {
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
*/
@available(iOS 4, *)
case afterFirstUnlock
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
@available(iOS 4, *)
case afterFirstUnlockThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
*/
@available(iOS 4, *)
case always
/**
The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
*/
@available(iOS 8, *)
case whenPasscodeSetThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
@available(iOS 4, *)
case alwaysThisDeviceOnly
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
This is the default value for keychain items added without explicitly setting an accessibility constant.
*/
@available(iOS 4, *)
case whenUnlocked
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
@available(iOS 4, *)
case whenUnlockedThisDeviceOnly
static func accessibilityForAttributeValue(_ keychainAttrValue: CFString) -> KeychainItemAccessibility? {
for (key, value) in keychainItemAccessibilityLookup {
if value == keychainAttrValue {
return key
}
}
return nil
}
}
private let keychainItemAccessibilityLookup: [KeychainItemAccessibility: CFString] = {
var lookup: [KeychainItemAccessibility: CFString] = [
.afterFirstUnlock: kSecAttrAccessibleAfterFirstUnlock,
.afterFirstUnlockThisDeviceOnly: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
.always: kSecAttrAccessibleAlways,
.whenPasscodeSetThisDeviceOnly: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.alwaysThisDeviceOnly: kSecAttrAccessibleAlwaysThisDeviceOnly,
.whenUnlocked: kSecAttrAccessibleWhenUnlocked,
.whenUnlockedThisDeviceOnly: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]
return lookup
}()
extension KeychainItemAccessibility: KeychainAttrRepresentable {
internal var keychainAttrValue: CFString {
return keychainItemAccessibilityLookup[self]!
}
}
| 46.620968 | 380 | 0.734994 |
de7e236a594e346a9b659da26bd9a7e3bdb5a223 | 471 | //
// Aletheias
//
// Created by Stephen Chen on 16/2/2017.
// Copyright © 2018 fcloud. All rights reserved.
//
import UIKit
extension NSObject: AletheiaCompatible { }
extension AletheiaWrapper where Base: NSObject {
/// Get the name of class
///
/// ```swift
///
/// MyClass.al.className //=> "MyClass"
///
/// ```
/// - Return: CGFloat
public var getClassName: String {
return String(describing: self)
}
}
| 16.821429 | 49 | 0.581741 |
3337b0972c34ff550db12ce9e65526349127c869 | 751 | import XCTest
import WBImageCropper
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.896552 | 111 | 0.603196 |
08551389bc1ac466e93b7846293cac4291d546b6 | 1,207 | //
// SCNVector3+Distance.swift
// faceIT
//
// Created by Michael Ruhl on 17.08.17.
// Copyright © 2017 NovaTec GmbH. All rights reserved.
//
import Foundation
import ARKit
public extension SCNVector3 {
/**
Calculates vector length based on Pythagoras theorem
*/
var length:Float {
get {
return sqrtf(x*x + y*y + z*z)
}
}
func distance(toVector: SCNVector3) -> Float {
return (self - toVector).length
}
static func positionFromTransform(_ transform: matrix_float4x4) -> SCNVector3 {
return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
}
static func -(left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
}
static func center(_ vectors: [SCNVector3]) -> SCNVector3 {
var x: Float = 0
var y: Float = 0
var z: Float = 0
let size = Float(vectors.count)
vectors.forEach {
x += $0.x
y += $0.y
z += $0.z
}
return SCNVector3Make(x / size, y / size, z / size)
}
}
| 23.666667 | 98 | 0.56918 |
e9f68a4043d29ac3d2057df25750e03c83965542 | 4,906 | //
// APIClient.swift
// Player
//
// Created by Victor Nouvellet on 10/12/17.
// Copyright © 2017 Victor Nouvellet. All rights reserved.
//
import Foundation
typealias APIClientCompletion = (NSError?, Any?)->()
typealias SessionCompletion = (Data?, URLResponse?, Error?)->()
class APIClient: NSObject {
// MARK: - Configuration
fileprivate let kItunesAPIErrorDomain = "iTunesAPI"
fileprivate let kAPIBaseURL = URL(string:"https://itunes.apple.com/")!
// MARK: - Public var
// APIClient singleton
static let shared = APIClient()
// MARK: - Private vars
fileprivate let session: URLSession
// MARK: - Parents methods
override init() {
let configuration = URLSessionConfiguration.default
self.session = URLSession(configuration: configuration)
}
// MARK: Private methods
/// # First level JSON request handler constructor
/// Return a handler to analyze request's response
func handler(completion: ((NSError?, Any?)->())?, apiErrorDomain: String) -> SessionCompletion {
return { (data: Data?, response:URLResponse?, error:Error?)->() in
guard let safeCompletion = completion else {
return
}
guard let safeData = data
else {
let noDataError = NSError(domain: apiErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "no data"])
DispatchQueue.main.async {
safeCompletion(noDataError, nil)
}
return
}
do {
let jsonResponse = try JSONSerialization.jsonObject(with: safeData, options: [])
if let jsonDictionary = jsonResponse as? Dictionary<String, Any>,
let jsonError = jsonDictionary["error"] as? Dictionary<String, Any>,
let code = jsonError["code"] as? Int {
let error = NSError(domain: apiErrorDomain, code: code, userInfo: [NSLocalizedDescriptionKey: jsonError["message"] as? String ?? ""])
DispatchQueue.main.async {
safeCompletion(error, nil)
}
} else {
// If everything went well
DispatchQueue.main.async {
safeCompletion(nil, jsonResponse)
}
}
} catch let error {
let jsonParsingError = NSError(domain: apiErrorDomain, code: 2, userInfo: [NSLocalizedDescriptionKey: error])
DispatchQueue.main.async {
safeCompletion(jsonParsingError, nil)
}
}
}
}
private func queryWithParams(params: Dictionary<String, Any>) -> String {
var components: Array<String> = []
if params.count > 0 {
for (key, value) in params {
components += ["\(key)=\((value as AnyObject).description.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!)"]
}
}
return components.joined(separator: "&")
}
private func iTunesRSSURL(path: String, params: Dictionary<String, Any>?) -> URL {
let mutableParams: Dictionary<String, Any> = params ?? [:]
// TODO: Add affiliate token here
var relativePath: String = "\(path)\(mutableParams.count > 0 ? "?" : "")"
relativePath += self.queryWithParams(params: mutableParams)
return URL(string: relativePath, relativeTo: kAPIBaseURL)!
}
/// Get iTunes URL giving the URL and a callback to call when the request is terminated.
private func getITURL(URL: URL, completion: @escaping APIClientCompletion) {
self.session.dataTask(with: URL, completionHandler: self.handler(completion: completion, apiErrorDomain: self.kItunesAPIErrorDomain)).resume()
}
// MARK: - Top 100 methods
/// Creates the URL to get the top songs list of phone's country.
private func iTunesRSSTopSongPath(limit: Int) -> String? {
guard let countryCode = Locale.current.regionCode else {
log.error("Error: Could not get phone's region code")
return nil
}
let dataType = "json"
let path: String = "\(countryCode)/rss/topsongs/limit=\(limit)/\(dataType)"
return path
}
/// Fetch top 100 songs on iTunes
func top100Songs(completion: @escaping APIClientCompletion) {
guard let path = iTunesRSSTopSongPath(limit: 100) else {
completion(nil, nil)
return
}
let url: URL = self.iTunesRSSURL(path: path, params: nil)
self.getITURL(URL: url, completion: completion)
}
}
| 38.031008 | 153 | 0.574806 |
11ee500d130e30150a82bc0753059f034c0354c3 | 10,418 | //
// GenericDispatchData.swift
// RTP Test
//
// Created by Jonathan Wight on 6/30/15.
//
// Copyright © 2016, Jonathan Wight
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
// MARK: GenericDispatchData
// TODO: Swift3
//public struct GenericDispatchData <Element> {
//
// public let data: DispatchData
//
// public var count: Int {
// return length / elementSize
// }
//
// public static var elementSize: Int {
// return max(sizeof(Element), 1)
// }
//
// public var elementSize: Int {
// return GenericDispatchData <Element>.elementSize
// }
//
// public var length: Int {
// return data.count
// }
//
// public var startIndex: Int {
// return 0
// }
//
// public var endIndex: Int {
// return count
// }
//
// // MARK: -
//
// public init(data: DispatchData) {
// self.data = data
// assert(count * elementSize == length)
// }
//
// public init() {
// self.init(data: DispatchData())
// }
//
// public init(buffer: UnsafeBufferPointer <Element>) {
// self.init(data: DispatchData(bytesNoCopy: buffer.baseAddress, deallocator: nil))
// }
//
// public init(start: UnsafePointer <Element>, count: Int) {
// self.init(data: DispatchData(bytesNoCopy: start, deallocator: nil))
// }
//
// // MARK: Mapping data.
//
// // TODO: Rename to "with", "withUnsafeBufferPointer", "withDataAndUnsafeBufferPointer"
//
// // IMPORTANT: If you need to keep the buffer beyond the scope of block you must hold on to data GenericDispatchData instance too. The GenericDispatchData and the buffer share the same life time.
// public func createMap <R> ( block: (GenericDispatchData <Element>, UnsafeBufferPointer <Element>) throws -> R) rethrows -> R {
// var pointer: UnsafeRawPointer? = nil
// var size: Int = 0
// let mappedData = data.withUnsafeBytes(body: &pointer)
// let buffer = UnsafeBufferPointer <Element> (start: UnsafePointer <Element> (pointer), count: size)
// return try block(GenericDispatchData <Element> (data: mappedData), buffer)
// }
//
// // MARK: -
//
// /// Non-throwing version of apply
// public func apply(_ applier: (CountableRange<Int>, UnsafeBufferPointer <Element>) -> Bool) {
// data.enumerateBytes {
// (region: DispatchData!, offset: Int, buffer: UnsafeRawPointer, size: Int) -> Bool in
// let buffer = UnsafeBufferPointer <Element> (start: UnsafePointer <Element> (buffer), count: size / self.elementSize)
// return applier(offset..<offset + size, buffer)
// }
// }
//
// /// Throwing version of apply
// public func apply(_ applier: (CountableRange<Int>, UnsafeBufferPointer <Element>) throws -> Bool) throws {
// var savedError: ErrorProtocol? = nil
// data.enumerateBytes {
// (region: DispatchData!, offset: Int, buffer: UnsafeRawPointer, size: Int) -> Bool in
// let buffer = UnsafeBufferPointer <Element> (start: UnsafePointer <Element> (buffer), count: size / self.elementSize)
// do {
// return try applier(offset..<offset + size, buffer)
// }
// catch let error {
// savedError = error
// return false
// }
// }
// if let savedError = savedError {
// throw savedError
// }
// }
//
// public func convert <U> () -> GenericDispatchData <U> {
// return GenericDispatchData <U> (data: data)
// }
//}
//
//// MARK: Equatable
//
//extension GenericDispatchData: Equatable {
//}
//
///**
// Equality operator.
//
// Warning. This can copy zero, one or both Data buffers. This can be extremely slow.
//*/
//public func == <Element> (lhs: GenericDispatchData <Element>, rhs: GenericDispatchData <Element>) -> Bool {
//
// // If we're backed by the same dispatch_data then yes, we're equal.
// if lhs.data === rhs.data {
// return true
// }
//
// // If counts are different then no, we're not equal.
// guard lhs.count == rhs.count else {
// return false
// }
//
// // Otherwise let's map both the data and memcmp. This can alloc _and_ copy _both_ functions and can therefore be extremely slow.
// return lhs.createMap() {
// (lhsData, lhsBuffer) -> Bool in
//
// return rhs.createMap() {
// (rhsData, rhsBuffer) -> Bool in
//
// let result = memcmp(lhsBuffer.baseAddress, rhsBuffer.baseAddress, lhsBuffer.length)
// return result == 0
// }
// }
//}
//
//// MARK: CustomStringConvertible
//
//extension GenericDispatchData: CustomStringConvertible {
// public var description: String {
// var chunkCount = 0
// apply() {
// (range, pointer) in
// chunkCount += 1
// return true
// }
// return "GenericDispatchData(count: \(count), length: \(length), chunk count: \(chunkCount), data: \(data))"
// }
//}
//
//// MARK: subscript
//
//public extension GenericDispatchData {
// public subscript (range: Range <Int>) -> GenericDispatchData <Element> {
// do {
// return try subBuffer(range)
// }
// catch let error {
// fatalError(String(error))
// }
// }
//}
//
//// MARK: Concot.
//
//public func + <Element> (lhs: GenericDispatchData <Element>, rhs: GenericDispatchData <Element>) -> GenericDispatchData <Element> {
// let data = lhs.data.append(other: rhs.data)
// return GenericDispatchData <Element> (data: data)
//}
//
//
//// MARK: Manipulation
//
///// Do not really like these function names but they're very useful.
//public extension GenericDispatchData {
//
// public func subBuffer(_ range: Range <Int>) throws -> GenericDispatchData <Element> {
// guard range.startIndex >= startIndex && range.startIndex <= endIndex else {
// throw Error.generic("Index out of range")
// }
// guard range.endIndex >= startIndex && range.endIndex <= endIndex else {
// throw Error.generic("Index out of range")
// }
// guard range.startIndex <= range.endIndex else {
// throw Error.generic("Index out of range")
// }
// return GenericDispatchData <Element> (data: data.subdata(in: range.startIndex * elementSize ..< (range.endIndex - range.startIndex) * elementSize))
// }
//
// public func subBuffer(startIndex: Int, count: Int) throws -> GenericDispatchData <Element> {
// return try subBuffer(startIndex..<startIndex + count)
// }
//
// public func inset(startInset: Int = 0, endInset: Int = 0) throws -> GenericDispatchData <Element> {
// return try subBuffer(startIndex: startInset, count: count - (startInset + endInset))
// }
//
// public func split(_ startIndex: Int) throws -> (GenericDispatchData <Element>, GenericDispatchData <Element>) {
// let lhs = try subBuffer(startIndex: 0, count: startIndex)
// let rhs = try subBuffer(startIndex: startIndex, count: count - startIndex)
// return (lhs, rhs)
// }
//
// func split <T> () throws -> (T, GenericDispatchData) {
// let (left, right) = try split(sizeof(T))
// let value = left.createMap() {
// (data, buffer) in
// return (buffer.toUnsafeBufferPointer() as UnsafeBufferPointer <T>)[0]
// }
// return (value, right)
// }
//
//}
//
//// MARK: -
//
//public extension GenericDispatchData {
// init <U: Integer> (value: U) {
// var copy = value
// self = withUnsafePointer(to: ©) {
// let buffer = UnsafeBufferPointer <U> (start: $0, count: 1)
// return GenericDispatchData <U> (buffer: buffer).convert()
// }
// }
//}
//
//// MARK: -
//
//public extension GenericDispatchData {
//
// // TODO: This is a bit dangerous (not anything can/should be convertable to a GenericDispatchData). Investigate deprecating? No more dangerous than & operator though?
// init <U> (value: U) {
// var copy = value
// let data: DispatchData = withUnsafePointer(to: ©) {
// let buffer = UnsafeBufferPointer <U> (start: $0, count: 1)
// return DispatchData(bytesNoCopy: buffer.baseAddress, deallocator: nil)
// }
// self.init(data: data)
// }
//}
//
//// MARK: -
//
//public extension GenericDispatchData {
//
// init(_ data: Data) {
// self = GenericDispatchData(buffer: data.toUnsafeBufferPointer())
// }
//
// func toNSData() -> Data {
// guard let data = data as? Data else {
// fatalError("dispatch_data_t not convertable to NSData")
// }
// return data
// }
//}
//
//// MARK: -
//
//public extension GenericDispatchData {
//
// init(_ string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
// guard let data = string.data(using: encoding) else {
// throw Error.generic("Could not encoding string.")
// }
// self = GenericDispatchData(buffer: data.toUnsafeBufferPointer())
// }
//
//}
| 34.726667 | 200 | 0.617873 |
891848ca64025dd2251217df70e8fa9228007bee | 4,123 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
extension UISearchBar {
open var textField: UITextField? {
firstSubview(withClass: UITextField.self)
}
@objc dynamic open var searchFieldBackgroundColor: UIColor? {
get {
switch searchBarStyle {
case .minimal:
return textField?.layer.backgroundColor?.uiColor
default:
return textField?.backgroundColor
}
}
set {
guard let newValue = newValue else { return }
switch searchBarStyle {
case .minimal:
textField?.layer.backgroundColor = newValue.cgColor
textField?.clipsToBounds = true
textField?.layer.cornerRadius = 8
default:
textField?.backgroundColor = newValue
}
}
}
}
extension UISearchBar {
private struct AssociatedKey {
static var placeholderTextColor = "placeholderTextColor"
static var initialPlaceholderText = "initialPlaceholderText"
static var didSetInitialPlaceholderText = "didSetInitialPlaceholderText"
}
/// The default value is `nil`. Uses `UISearchBar` default gray color.
@objc dynamic open var placeholderTextColor: UIColor? {
/// Unfortunately, when the `searchBarStyle == .minimal` then
/// `textField?.placeholderLabel?.textColor` doesn't work. Hence, this workaround.
get { associatedObject(&AssociatedKey.placeholderTextColor) }
set {
setAssociatedObject(&AssociatedKey.placeholderTextColor, value: newValue)
// Redraw placeholder text on color change
let placeholderText = placeholder
placeholder = placeholderText
}
}
private var didSetInitialPlaceholderText: Bool {
get { associatedObject(&AssociatedKey.didSetInitialPlaceholderText, default: false) }
set { setAssociatedObject(&AssociatedKey.didSetInitialPlaceholderText, value: newValue) }
}
private var initialPlaceholderText: String? {
get { associatedObject(&AssociatedKey.initialPlaceholderText) }
set { setAssociatedObject(&AssociatedKey.initialPlaceholderText, value: newValue) }
}
@objc private var swizzled_placeholder: String? {
get { textField?.attributedPlaceholder?.string }
set {
if superview == nil, let newValue = newValue {
initialPlaceholderText = newValue
return
}
guard let textField = textField else {
return
}
guard let newValue = newValue else {
textField.attributedPlaceholder = nil
return
}
if let placeholderTextColor = placeholderTextColor {
textField.attributedPlaceholder = NSAttributedString(string: newValue, attributes: [
.foregroundColor: placeholderTextColor
])
} else {
textField.attributedPlaceholder = NSAttributedString(string: newValue)
}
}
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
guard superview != nil, !didSetInitialPlaceholderText else { return }
if let placeholderText = initialPlaceholderText {
placeholder = placeholderText
initialPlaceholderText = nil
}
didSetInitialPlaceholderText = true
}
}
// MARK: Swizzle
extension UISearchBar {
static func runOnceSwapSelectors() {
swizzle(
UISearchBar.self,
originalSelector: #selector(getter: UISearchBar.placeholder),
swizzledSelector: #selector(getter: UISearchBar.swizzled_placeholder)
)
swizzle(
UISearchBar.self,
originalSelector: #selector(setter: UISearchBar.placeholder),
swizzledSelector: #selector(setter: UISearchBar.swizzled_placeholder)
)
}
}
| 32.722222 | 100 | 0.615329 |
d9d5c796764d7bcb4447139e66e6863bce3740e9 | 99 |
import Foundation
extension Double {
func squared() -> Double {
pow(self, 2)
}
}
| 11 | 30 | 0.565657 |
2301803c31c4d8a7b699eb0db6369dc228971903 | 277 | //
// OES_standard_derivatives.swift
// CanvasNative
//
// Created by Osei Fortune on 4/27/20.
//
import Foundation
import OpenGLES
@objcMembers
@objc(Canvas_OES_standard_derivatives)
public class Canvas_OES_standard_derivatives: NSObject {
public override init() {}
}
| 18.466667 | 56 | 0.765343 |
e6916a9e45c2415ce93cab4e560200e89ee022d2 | 3,848 | //
// PaymentSearchCollectionViewCell.swift
// MercadoPagoSDK
//
// Created by Demian Tejo on 10/25/16.
// Copyright © 2016 MercadoPago. All rights reserved.
//
import UIKit
class PaymentSearchCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleSearch: UILabel!
@IBOutlet weak var subtitleSearch: UILabel!
@IBOutlet weak var paymentOptionImageContainer: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
for subview in paymentOptionImageContainer.subviews {
subview.removeFromSuperview()
}
}
public func fillCell(image: UIImage?, title: String? = "", subtitle: String? = "") {
titleSearch.text = title
titleSearch.font = Utils.getFont(size: titleSearch.font.pointSize)
subtitleSearch.text = subtitle
subtitleSearch.font = Utils.getFont(size: subtitleSearch.font.pointSize)
addPaymentOptionIconComponent(image: image)
backgroundColor = .white
titleSearch.textColor = UIColor.black
layoutIfNeeded()
}
func getConstraintFor(label: UILabel) -> NSLayoutConstraint {
return NSLayoutConstraint(item: self.subtitleSearch, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: label.requiredHeight())
}
func totalHeight() -> CGFloat {
return titleSearch.requiredHeight() + subtitleSearch.requiredHeight() + 112
}
func fillCell(drawablePaymentOption: PaymentOptionDrawable) {
let image = drawablePaymentOption.getImage()
self.fillCell(image: image, title: drawablePaymentOption.getTitle(), subtitle: drawablePaymentOption.getSubtitle())
}
func fillCell(optionText: String) {
self.fillCell(image: nil, title: optionText, subtitle: nil)
}
static func totalHeight(drawablePaymentOption: PaymentOptionDrawable) -> CGFloat {
return PaymentSearchCollectionViewCell.totalHeight(title: drawablePaymentOption.getTitle(), subtitle: drawablePaymentOption.getSubtitle())
}
static func totalHeight(title: String?, subtitle: String?) -> CGFloat {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let availableWidth = screenWidth - (screenWidth * 0.3)
let widthPerItem = availableWidth / 2
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: widthPerItem, height: 0))
titleLabel.font = UIFont.systemFont(ofSize: 16)
titleLabel.text = title
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: widthPerItem, height: 0))
subtitleLabel.font = UIFont.systemFont(ofSize: 15)
subtitleLabel.text = subtitle
let altura1 = titleLabel.requiredHeight()
let altura2 = subtitleLabel.requiredHeight()
return altura1 + altura2 + 112
}
}
extension PaymentSearchCollectionViewCell {
fileprivate func addPaymentOptionIconComponent(image: UIImage?) {
let paymentMethodIconComponent = PXPaymentMethodIconComponent(props: PXPaymentMethodIconProps(paymentMethodIcon: image)).render()
paymentMethodIconComponent.layer.cornerRadius = paymentOptionImageContainer.frame.width/2
paymentMethodIconComponent.removeFromSuperview()
paymentOptionImageContainer.insertSubview(paymentMethodIconComponent, at: 0)
PXLayout.centerHorizontally(view: paymentMethodIconComponent).isActive = true
PXLayout.setHeight(owner: paymentMethodIconComponent, height: paymentOptionImageContainer.frame.width).isActive = true
PXLayout.setWidth(owner: paymentMethodIconComponent, width: paymentOptionImageContainer.frame.width).isActive = true
PXLayout.pinTop(view: paymentMethodIconComponent, withMargin: 0).isActive = true
}
}
| 38.868687 | 191 | 0.719854 |
1df734c771247508095c031ee0a4a28adeab435d | 459 | //
// ViewController.swift
// Initialiser
//
// Created by Kunal Kumar on 04/11/18.
// Copyright © 2018 Kunal Kumar. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 16.392857 | 58 | 0.623094 |
e9fb644c36f1b9b2c5c480815936139ad122cf22 | 2,165 | //
// AppDelegate.swift
// TipCalculator
//
// Created by szarif on 8/2/17.
// Copyright © 2017 szarif. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.06383 | 285 | 0.755196 |
0e6bd7b5c4ea2e56204df75862dd4de1fd01a0db | 8,443 | //
// GeneralTab.swift
// MeetingBar
//
// Created by Andrii Leitsius on 13.01.2021.
// Copyright © 2021 Andrii Leitsius. All rights reserved.
//
import SwiftUI
import Defaults
import KeyboardShortcuts
struct GeneralTab: View {
@Default(.launchAtLogin) var launchAtLogin
var body: some View {
VStack(alignment: .leading, spacing: 15) {
Spacer()
Section {
Toggle("preferences_general_option_login_launch".loco(), isOn: $launchAtLogin)
}
PreferredLanguageSection()
Divider()
Section {
JoinEventNotificationPicker()
}
Divider()
ShortcutsSection()
Spacer()
Divider()
PatronageAppSection()
}.padding()
}
}
struct PreferredLanguageSection: View {
@Default(.preferredLanguage) var preferredLanguage
var body: some View {
HStack {
Picker("preferences_general_option_preferred_language_title".loco(), selection: $preferredLanguage) {
Text("preferences_general_option_preferred_language_system_value".loco()).tag(AppLanguage.system)
Text("preferences_general_option_preferred_language_english_value".loco()).tag(AppLanguage.english)
Text("preferences_general_option_preferred_language_russian_value".loco()).tag(AppLanguage.russian)
Text("preferences_general_option_preferred_language_chinese_simple_value".loco()).tag(AppLanguage.chinese_simple)
Text("preferences_general_option_preferred_language_chinese_traditional_value".loco()).tag(AppLanguage.chinese_traditional)
}
Text("preferences_general_option_preferred_language_tip".loco()).foregroundColor(Color.gray).font(.system(size: 12))
}
}
}
struct ShortcutsSection: View {
var body: some View {
HStack {
Text("preferences_general_option_shortcuts".loco()).font(.headline).bold()
Spacer()
VStack {
Text("preferences_general_shortcut_open_menu".loco())
KeyboardShortcuts.Recorder(for: .openMenuShortcut)
}
VStack {
Text("preferences_general_shortcut_create_meeting".loco())
KeyboardShortcuts.Recorder(for: .createMeetingShortcut)
}
VStack {
Text("preferences_general_shortcut_join_next".loco())
KeyboardShortcuts.Recorder(for: .joinEventShortcut)
}
VStack {
Text("preferences_general_shortcut_join_from_clipboard".loco())
KeyboardShortcuts.Recorder(for: .openClipboardShortcut)
}
}
}
}
struct PatronageAppSection: View {
@State var showingPatronageModal = false
@State var showingContactModal = false
@Default(.isInstalledFromAppStore) var isInstalledFromAppStore
var body: some View {
VStack(alignment: .leading, spacing: 15) {
VStack(alignment: .center) {
Spacer()
HStack {
VStack(alignment: .center) {
Image(nsImage: NSImage(named: "appIconForAbout")!).resizable().frame(width: 120.0, height: 120.0)
Text("MeetingBar").font(.system(size: 20)).bold()
if Bundle.main.infoDictionary != nil {
Text("Version \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown")").foregroundColor(.gray)
}
}.lineLimit(1).minimumScaleFactor(0.5).frame(minWidth: 0, maxWidth: .infinity)
VStack {
Spacer()
Text("preferences_general_meeting_bar_description".loco()).multilineTextAlignment(.center)
Spacer()
HStack {
Spacer()
Button(action: clickPatronage) {
Text("preferences_general_external_patronage".loco())
}.sheet(isPresented: $showingPatronageModal) {
PatronageModal()
}
Spacer()
Button(action: { Links.github.openInDefaultBrowser() }) {
Text("preferences_general_external_gitHub".loco())
}
Spacer()
Button(action: { self.showingContactModal.toggle() }) {
Text("preferences_general_external_contact".loco())
}.sheet(isPresented: $showingContactModal) {
ContactModal()
}
Spacer()
}
Spacer()
}.frame(minWidth: 360, maxWidth: .infinity)
}
Spacer()
}
}
}
func clickPatronage() {
if isInstalledFromAppStore {
self.showingPatronageModal.toggle()
} else {
Links.patreon.openInDefaultBrowser()
}
}
}
struct PatronageModal: View {
@Environment(\.presentationMode) var presentationMode
@State var products: [String] = []
@Default(.patronageDuration) var patronageDuration
var body: some View {
VStack {
Spacer()
HStack {
VStack(alignment: .leading) {
HStack {
Text("preferences_general_patron_title".loco()).bold()
}
}.frame(width: 120)
Spacer()
VStack(alignment: .leading) {
Button(action: { purchasePatronage(patronageProducts.threeMonth) }) {
Text("preferences_general_patron_three_months".loco()).frame(width: 150)
}
Button(action: { purchasePatronage(patronageProducts.sixMonth) }) {
Text("preferences_general_patron_six_months".loco()).frame(width: 150)
}
Button(action: { purchasePatronage(patronageProducts.twelveMonth) }) {
Text("preferences_general_patron_twelve_months".loco()).frame(width: 150)
}
Text("preferences_general_patron_description".loco()).font(.system(size: 10))
}.frame(maxWidth: .infinity)
}
if patronageDuration > 0 {
Divider()
Spacer()
Text("preferences_general_patron_thank_for_purchase".loco(patronageDuration))
}
Spacer()
Divider()
HStack {
Button(action: restorePatronagePurchases) {
Text("preferences_general_patron_restore_purchases".loco())
}
Spacer()
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("general_close".loco())
}
}
}.padding().frame(width: 400, height: 300)
}
}
struct ContactModal: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Spacer()
Text("preferences_general_feedback_title".loco())
Spacer()
Button(action: { Links.emailMe.openInDefaultBrowser() }) {
Text("preferences_general_feedback_email".loco()).frame(width: 80)
}
Button(action: { Links.twitter.openInDefaultBrowser() }) {
Text("preferences_general_feedback_twitter".loco()).frame(width: 80)
}
Button(action: { Links.telegram.openInDefaultBrowser() }) {
Text("preferences_general_feedback_telegram".loco()).frame(width: 80)
}
Spacer()
Divider()
HStack {
Spacer()
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("general_close".loco())
}
}
}.padding().frame(width: 300, height: 220)
}
}
| 38.377273 | 151 | 0.533341 |
e5ba9a916e962d2cfd1ee50ce735595dd6bf7f61 | 2,673 | //
// MirroringViewController.swift
// HiResMirroring
//
// Created by Watanabe Toshinori on 4/5/19.
// Copyright © 2019 Watanabe Toshinori. All rights reserved.
//
import UIKit
class MirroringViewController: UIViewController {
@IBOutlet weak var mirroringView: UIView!
@IBOutlet weak var mirroringViewHeight: NSLayoutConstraint!
@IBOutlet weak var mirroringViewWidth: NSLayoutConstraint!
private var displayLink: CADisplayLink?
private weak var window: UIWindow?
var rate: CGFloat!
// MARK: - Instantiate ViewController
class func instantiate(with window: UIWindow) -> MirroringViewController {
let bundle = Bundle(for: MirroringViewController.self)
guard let viewController = UIStoryboard(name: "MirroringViewController", bundle: bundle).instantiateInitialViewController() as? MirroringViewController else {
fatalError("Invalid Storyboard")
}
viewController.window = window
return viewController
}
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = window?.screen.bounds ?? .zero
let viewSize = view.bounds
let rateX = viewSize.width / max(viewSize.width, screenSize.width)
let rateY = viewSize.height / max(viewSize.height, screenSize.height)
rate = min(rateX, rateY)
mirroringViewWidth.constant = screenSize.width * rate
mirroringViewHeight.constant = screenSize.height * rate
mirroringView.layer.borderWidth = 0.5
mirroringView.layer.borderColor = UIColor.lightGray.cgColor
}
// MARK: - Start and Stop Mirroring
func startMirroring() {
displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink?.add(to: .main, forMode: .default)
}
func stopMirroring() {
displayLink?.invalidate()
displayLink = nil
}
// MARK: - Update
@objc private func update() {
guard let window = window else {
return
}
mirroringView.subviews.forEach({ $0.removeFromSuperview() })
let snapshotView = window.screen.snapshotView(afterScreenUpdates: false)
mirroringView.addSubview(snapshotView)
snapshotView.layer.anchorPoint = .zero
let scale = rate ?? 1.0
let xPadding = 1 / scale * -0.5 * snapshotView.bounds.width
let yPadding = 1 / scale * -0.5 * snapshotView.bounds.height
snapshotView.transform = CGAffineTransform(scaleX: scale, y: scale).translatedBy(x: xPadding, y: yPadding)
}
}
| 30.724138 | 166 | 0.658062 |
2163037bc51b6f34714d6deaa67e176c7f6fda54 | 15,626 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case failedToCreateWithAddress(sockaddr, Int32)
case failedToCreateWithHostname(String, Int32)
case unableToSetCallback(Int32)
case unableToSetDispatchQueue(Int32)
case unableToGetFlags(Int32)
}
@available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
public extension Notification.Name {
static let reachabilityChanged = Notification.Name("reachabilityChanged")
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
@available(*, unavailable, renamed: "Connection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
@available(*, deprecated, renamed: "unavailable")
case none
case unavailable, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .unavailable: return "No Connection"
case .none: return "unavailable"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
@available(*, deprecated, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
@available(*, deprecated, renamed: "connection.description")
public var currentReachabilityString: String {
return "\(connection)"
}
@available(*, unavailable, renamed: "connection")
public var currentReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
if flags == nil {
try? setReachabilityFlags()
}
switch flags?.connection {
case .unavailable?, nil: return .unavailable
case .none?: return .unavailable
case .cellular?: return allowsCellularConnection ? .cellular : .unavailable
case .wifi?: return .wifi
}
}
fileprivate var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
fileprivate(set) var notifierRunning = false
fileprivate let reachabilityRef: SCNetworkReachability
fileprivate let reachabilitySerialQueue: DispatchQueue
fileprivate let notificationQueue: DispatchQueue?
fileprivate(set) var flags: SCNetworkReachabilityFlags? {
didSet {
guard flags != oldValue else { return }
notifyReachabilityChanged()
}
}
required public init(reachabilityRef: SCNetworkReachability,
queueQoS: DispatchQoS = .default,
targetQueue: DispatchQueue? = nil,
notificationQueue: DispatchQueue? = .main) {
self.allowsCellularConnection = true
self.reachabilityRef = reachabilityRef
self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue)
self.notificationQueue = notificationQueue
}
public convenience init(hostname: String,
queueQoS: DispatchQoS = .default,
targetQueue: DispatchQueue? = nil,
notificationQueue: DispatchQueue? = .main) throws {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else {
throw ReachabilityError.failedToCreateWithHostname(hostname, SCError())
}
self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue)
}
public convenience init(queueQoS: DispatchQoS = .default,
targetQueue: DispatchQueue? = nil,
notificationQueue: DispatchQueue? = .main) throws {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else {
throw ReachabilityError.failedToCreateWithAddress(zeroAddress, SCError())
}
self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue)
}
deinit {
stopNotifier()
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in
guard let info = info else { return }
// `weakifiedReachability` is guaranteed to exist by virtue of our
// retain/release callbacks which we provided to the `SCNetworkReachabilityContext`.
let weakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info).takeUnretainedValue()
// The weak `reachability` _may_ no longer exist if the `Reachability`
// object has since been deallocated but a callback was already in flight.
weakifiedReachability.reachability?.flags = flags
}
let weakifiedReachability = ReachabilityWeakifier(reachability: self)
let opaqueWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.passUnretained(weakifiedReachability).toOpaque()
var context = SCNetworkReachabilityContext(
version: 0,
info: UnsafeMutableRawPointer(opaqueWeakifiedReachability),
retain: { (info: UnsafeRawPointer) -> UnsafeRawPointer in
let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
_ = unmanagedWeakifiedReachability.retain()
return UnsafeRawPointer(unmanagedWeakifiedReachability.toOpaque())
},
release: { (info: UnsafeRawPointer) -> Void in
let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
unmanagedWeakifiedReachability.release()
},
copyDescription: { (info: UnsafeRawPointer) -> Unmanaged<CFString> in
let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
let weakifiedReachability = unmanagedWeakifiedReachability.takeUnretainedValue()
let description = weakifiedReachability.reachability?.description ?? "nil"
return Unmanaged.passRetained(description as CFString)
}
)
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.unableToSetCallback(SCError())
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.unableToSetDispatchQueue(SCError())
}
// Perform an initial check
try setReachabilityFlags()
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
@available(*, deprecated, message: "Please use `connection != .none`")
var isReachable: Bool {
return connection != .unavailable
}
@available(*, deprecated, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return connection == .cellular
}
@available(*, deprecated, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
return connection == .wifi
}
var description: String {
return flags?.description ?? "unavailable flags"
}
}
fileprivate extension Reachability {
func setReachabilityFlags() throws {
try reachabilitySerialQueue.sync { [unowned self] in
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) {
self.stopNotifier()
throw ReachabilityError.unableToGetFlags(SCError())
}
self.flags = flags
}
}
func notifyReachabilityChanged() {
let notify = { [weak self] in
guard let self = self else { return }
self.connection != .unavailable ? self.whenReachable?(self) : self.whenUnreachable?(self)
self.notificationCenter.post(name: .reachabilityChanged, object: self)
}
// notify on the configured `notificationQueue`, or the caller's (i.e. `reachabilitySerialQueue`)
notificationQueue?.async(execute: notify) ?? notify()
}
}
extension SCNetworkReachabilityFlags {
typealias Connection = Reachability.Connection
var connection: Connection {
guard isReachableFlagSet else { return .unavailable }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
#if targetEnvironment(simulator)
return .wifi
#else
var connection = Connection.unavailable
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
connection = .cellular
}
return connection
#endif
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var description: String {
let W = isOnWWANFlagSet ? "W" : "-"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
/**
`ReachabilityWeakifier` weakly wraps the `Reachability` class
in order to break retain cycles when interacting with CoreFoundation.
CoreFoundation callbacks expect a pair of retain/release whenever an
opaque `info` parameter is provided. These callbacks exist to guard
against memory management race conditions when invoking the callbacks.
#### Race Condition
If we passed `SCNetworkReachabilitySetCallback` a direct reference to our
`Reachability` class without also providing corresponding retain/release
callbacks, then a race condition can lead to crashes when:
- `Reachability` is deallocated on thread X
- A `SCNetworkReachability` callback(s) is already in flight on thread Y
#### Retain Cycle
If we pass `Reachability` to CoreFoundtion while also providing retain/
release callbacks, we would create a retain cycle once CoreFoundation
retains our `Reachability` class. This fixes the crashes and his how
CoreFoundation expects the API to be used, but doesn't play nicely with
Swift/ARC. This cycle would only be broken after manually calling
`stopNotifier()` — `deinit` would never be called.
#### ReachabilityWeakifier
By providing both retain/release callbacks and wrapping `Reachability` in
a weak wrapper, we:
- interact correctly with CoreFoundation, thereby avoiding a crash.
See "Memory Management Programming Guide for Core Foundation".
- don't alter the public API of `Reachability.swift` in any way
- still allow for automatic stopping of the notifier on `deinit`.
*/
private class ReachabilityWeakifier {
weak var reachability: Reachability?
init(reachability: Reachability) {
self.reachability = reachability
}
}
| 38.39312 | 129 | 0.666389 |
764a4cbe0130f09f9fe8f25f967673fc52850335 | 5,370 | import Foundation
extension Operation {
/// A parameter that can be sent with an operation
public enum Parameter: Decodable, Equatable {
/// A parameter that filter the data in the response
case filter(name: String, type: ParameterValueType, required: Bool, documentation: String)
/// A parameter that checks for existance of a property
case exists(name: String, type: ParameterValueType, documentation: String)
/// A parameter that lists the desired fields in the response
case fields(name: String, type: ParameterValueType, deprecated: Bool, documentation: String)
/// A parameter that sorts the data in the response
case sort(type: ParameterValueType, documentation: String)
/// A parameter that limits the number of elements in the response
case limit(name: String, documentation: String, maximum: Int)
/// A parameter that indicates which related types shoudl be included in the response
case include(type: ParameterValueType)
private enum CodingKeys: String, CodingKey {
case name, description, required, deprecated, schema
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let documentation = try container.decode(String.self, forKey: .description)
if name.starts(with: "filter") {
let type = try container.decode(ParameterValueType.self, forKey: .schema)
let required = try container.decodeIfPresent(Bool.self, forKey: .required) ?? false
self = .filter(name: Self.getAttribute(forName: name), type: type, required: required, documentation: documentation)
} else if name.starts(with: "exists") {
let type = ParameterValueType.simple(type: .boolean)
self = .exists(name: Self.getAttribute(forName: name), type: type, documentation: documentation)
} else if name.starts(with: "fields") {
let type = try container.decode(ParameterValueType.self, forKey: .schema)
let deprecated = try container.decodeIfPresent(Bool.self, forKey: .deprecated) ?? false
self = .fields(name: Self.getAttribute(forName: name), type: type, deprecated: deprecated, documentation: documentation)
} else if name.starts(with: "sort") {
let type = try container.decode(ParameterValueType.self, forKey: .schema)
self = .sort(type: type, documentation: documentation)
} else if name.starts(with: "limit") {
let limitParameter = try container.decode(LimitParameter.self, forKey: .schema)
self = .limit(name: Self.getAttribute(forName: name), documentation: documentation, maximum: limitParameter.maximum)
} else if name.starts(with: "include") {
let type = try container.decode(ParameterValueType.self, forKey: .schema)
self = .include(type: type)
} else {
throw DecodingError.dataCorruptedError(forKey: .name, in: container, debugDescription: "Parameter type not known")
}
}
private static func getAttribute(forName name: String) -> String {
let components = name.components(separatedBy: "[")
guard components.count == 2 else { return name }
return components[1].replacingOccurrences(of: "]", with: "")
}
private struct LimitParameter: Decodable {
let maximum: Int
enum CodingKeys: String, CodingKey {
case maximum
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
maximum = try container.decode(Int.self, forKey: .maximum)
}
}
/// The type of value of a parameter
public enum ParameterValueType: Decodable, Equatable {
/// A simple value type
case simple(type: SimplePropertyType)
/// An enum value type
case `enum`(type: String, values: [String])
enum CodingKeys: String, CodingKey {
case items, type, `enum`
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
if type == "array" {
let itemsContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .items)
let itemType = try itemsContainer.decode(String.self, forKey: .type)
if let values = try itemsContainer.decodeIfPresent([String].self, forKey: .enum) {
self = .enum(type: itemType.capitalizingFirstLetter(), values: values)
} else {
self = .simple(type: .init(type: itemType))
}
} else {
self = .simple(type: .init(type: type))
}
}
}
}
}
| 53.7 | 136 | 0.596648 |
f7a1fa9838a3552383e3ef682aeaaed0ab9b564b | 1,926 | /**
* Copyright IBM Corporation 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.
**/
import Foundation
import RestKit
/** A model containing information about a specific Solr cluster. */
public struct SolrCluster: JSONDecodable {
/// The unique identifier for this cluster.
public let solrClusterID: String
/// The name that identifies this cluster.
public let solrClusterName: String
/// The size of the cluster. Ranges from 1 to 7.
public let solrClusterSize: Int?
/// The state of the cluster.
public let solrClusterStatus: SolrClusterStatus
/// Used internally to initialize a `SolrCluster` model from JSON.
public init(json: JSON) throws {
solrClusterID = try json.getString(at: "solr_cluster_id")
solrClusterName = try json.getString(at: "cluster_name")
solrClusterSize = try Int(json.getString(at: "cluster_size"))
guard let status = SolrClusterStatus(rawValue: try json.getString(at: "solr_cluster_status")) else {
throw JSON.Error.valueNotConvertible(value: json, to: SolrCluster.self)
}
solrClusterStatus = status
}
}
/** An enum describing the current state of the cluster. */
public enum SolrClusterStatus: String {
/// The cluster is ready.
case ready = "READY"
/// The cluster is not available.
case notAvailable = "NOT_AVAILABLE"
}
| 33.789474 | 108 | 0.696781 |
870e18cbaddd4cc25cec84a6f39db4c54e889194 | 1,094 | //
// InterstitialAd.swift
// Core
//
// Created by hbkim on 2021/01/30.
//
import SwiftUI
import UIKit
import Logging
import GoogleMobileAds
public final class Interstitial: NSObject, GADInterstitialDelegate {
var adUnitId: String
var interstitial: GADInterstitial!
var endAction: (() -> Void)?
public init(adUnitId: String) {
self.adUnitId = adUnitId
super.init()
interstitial = createAndLoadInterstitial()
}
func createAndLoadInterstitial() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: adUnitId)
interstitial.delegate = self
interstitial.load(GADRequest())
return interstitial
}
public func showAd(action: @escaping () -> Void) {
if interstitial.isReady {
self.endAction = action
let root = UIApplication.shared.windows.first?.rootViewController
interstitial.present(fromRootViewController: root!)
} else {
log.info("Ad is not ready")
}
}
public func interstitialDidDismissScreen(_ ad: GADInterstitial) {
interstitial = createAndLoadInterstitial()
endAction?()
}
}
| 22.791667 | 71 | 0.70841 |
26ce27dcc2a6f1841d2a23eb10017aac682cbfcc | 1,327 | //
// ThemeHelper.swift
// Water My Plant
//
// Created by Elizabeth Thomas on 3/2/20.
// Copyright © 2020 Breena Greek. All rights reserved.
//
import Foundation
class ThemeHelper {
private let themePreferenceKey = "themePreference"
func setThemePreferenceToDark() {
UserDefaults.standard.set("Dark", forKey: themePreferenceKey)
}
func setThemePreferenceToLight() {
UserDefaults.standard.set("Light", forKey: themePreferenceKey)
}
func setThemePreferenceToBlue() {
UserDefaults.standard.set("Blue", forKey: themePreferenceKey)
}
func setThemePreferenceToGreen() {
UserDefaults.standard.set("Green", forKey: themePreferenceKey)
}
func setThemePreferenceToPink() {
UserDefaults.standard.set("Pink", forKey: themePreferenceKey)
}
func setThemePreferenceToOrange() {
UserDefaults.standard.set("Orange", forKey: themePreferenceKey)
}
func setThemePreferenceToRose() {
UserDefaults.standard.set("Plant", forKey: themePreferenceKey)
}
var themePreference: String? {
return UserDefaults.standard.string(forKey: themePreferenceKey)
}
init() {
if themePreference == nil {
setThemePreferenceToLight()
}
}
}
| 24.127273 | 71 | 0.651846 |
75efe5522b0c45c7e456c1da37ea5c98e1737905 | 1,215 | //
// SystemModel.swift
// WeatherAppv2
//
// Created by Alejandro Fernández Ruiz on 28/07/2019.
// Copyright © 2019 Alejandro Fernández Ruiz. All rights reserved.
//
import Foundation
struct SystemModel {
// let type: Int?
// let id : Int
let message : Double
let country : String
let sunrise : Int
let sunset : Int
}
extension SystemModel: Decodable {
private enum SystemModelResponseCodingKeys: String, CodingKey {
// case type = "type"
// case id = "id"
case message = "message"
case country = "country"
case sunrise = "sunrise"
case sunset = "sunset"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SystemModelResponseCodingKeys.self)
// type = try container.decode(Int.self, forKey: .type)
// id = try container.decode(Int.self, forKey: .id)
message = try container.decode(Double.self, forKey: .message)
country = try container.decode(String.self, forKey: .country)
sunrise = try container.decode(Int.self, forKey: .sunrise)
sunset = try container.decode(Int.self, forKey: .sunset)
}
}
| 25.851064 | 90 | 0.625514 |
3370474ca7d9a7f1ca1e3530991e0069650b20ff | 604 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "Base58Swift",
products: [
.library(
name: "Base58Swift",
targets: ["Base58Swift"])
],
dependencies: [
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0")
],
targets: [
.target(
name: "Base58Swift",
dependencies: ["BigInt"],
path: "Base58Swift"),
.testTarget(
name: "base58swiftTests",
dependencies: ["Base58Swift"],
path: "Base58SwiftTests")
]
)
| 24.16 | 77 | 0.52649 |
e6296ebd597fdd125ab9d074cbc93734c793bfec | 2,726 | //
// Date+ISO8601.swift
// r2-shared-swift
//
// Created by Alexandre Camilleri, Mickaël Menu on 3/22/17.
//
// Copyright 2018 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
public extension Date {
var iso8601: String {
return DateFormatter.iso8601.string(from: self)
}
}
public extension DateFormatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
static func iso8601Formatter(for string: String) -> DateFormatter {
// On iOS 10 and later, this API should be treated withFullTime or withTimeZone for different cases.
// Otherwise it will accept bad format, for exmaple 2018-04-24XXXXXXXXX
// Because it will only test the part you asssigned, date, time, timezone.
// But we should also cover the optional cases. So there is not too much benefit.
// if #available(iOS 10.0, *) {
// let formatter = ISO8601DateFormatter()
// formatter.formatOptions = [.withFullDate]
// return formatter
// }
// https://developer.apple.com/documentation/foundation/dateformatter
// Doesn't support millisecond or uncompleted part for date, time, timezone offset.
let formats = [
10: "yyyy-MM-dd",
11: "yyyy-MM-ddZ",
16: "yyyy-MM-ddZZZZZ",
19: "yyyy-MM-dd'T'HH:mm:ss",
25: "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
]
let defaultFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let format = formats[string.count] ?? defaultFormat
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = format
return formatter
}
}
public extension String {
var dateFromISO8601: Date? {
// Removing .SSSS precision if found.
var string = self
let regexp = "[.][0-9]+"
if let range = string.range(of: regexp, options: .regularExpression) {
string.replaceSubrange(range, with: "")
}
return DateFormatter.iso8601Formatter(for: string).date(from: string)
}
}
| 33.654321 | 108 | 0.630594 |
67b89a83e64507f785ac2deaebb6f462ef8558e2 | 1,340 | //
// DemoAppConfig.swift
// ZcashLightClientSample
//
// Created by Francisco Gindre on 10/31/19.
// Copyright © 2019 Electric Coin Company. All rights reserved.
//
import Foundation
import ZcashLightClientKit
import MnemonicSwift
struct DemoAppConfig {
static var host = "light.virtualsoundnw.com"
static var port: Int = 9077
static var birthdayHeight: BlockHeight = 0
static var network = ZcashSDK.isMainnet ? ZcashNetwork.mainNet : ZcashNetwork.testNet
static var seed = ZcashSDK.isMainnet ? try! Mnemonic.deterministicSeedBytes(from: "still champion voice habit trend flight survey between bitter process artefact blind carbon truly provide dizzy crush flush breeze blouse charge solid fish spread") : Array("testreferencealicetestreferencealice".utf8)
static var address: String {
"\(host):\(port)"
}
static var processorConfig: CompactBlockProcessor.Configuration {
var config = CompactBlockProcessor.Configuration(cacheDb: try! __cacheDbURL(), dataDb: try! __dataDbURL(), network: "VRSC")
config.walletBirthday = self.birthdayHeight
return config
}
static var endpoint: LightWalletEndpoint {
return LightWalletEndpoint(address: self.host, port: self.port, secure: true)
}
}
enum ZcashNetwork {
case mainNet
case testNet
}
| 34.358974 | 304 | 0.732836 |
5d87651204321f9f8ed6b6927447cc372f663939 | 11,998 | //
// Blueprint.swift
// Representor
//
// Created by Kyle Fuller on 06/01/2015.
// Copyright (c) 2015 Apiary. All rights reserved.
//
import Foundation
// MARK: Models
public typealias Metadata = (name:String, value:String)
/// A structure representing an API Blueprint AST
public struct Blueprint {
/// Name of the API
public let name:String
/// Top-level description of the API in Markdown (.raw) or HTML (.html)
public let description:String?
/// The collection of resource groups
public let resourceGroups:[ResourceGroup]
public let metadata:[Metadata]
public init(name:String, description:String?, resourceGroups:[ResourceGroup]) {
self.metadata = []
self.name = name
self.description = description
self.resourceGroups = resourceGroups
}
public init(ast:[String:AnyObject]) {
metadata = parseMetadata(ast["metadata"] as? [[String:String]])
name = ast["name"] as? String ?? ""
description = ast["description"] as? String
resourceGroups = parseBlueprintResourceGroups(ast)
}
public init?(named:String, bundle:NSBundle? = nil) {
func loadFile(named:String, bundle:NSBundle) -> [String:AnyObject]? {
if let url = bundle.URLForResource(named, withExtension: nil) {
if let data = NSData(contentsOfURL: url) {
let object: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
return object as? [String:AnyObject]
}
}
return nil
}
let ast = loadFile(named, bundle: bundle ?? NSBundle.mainBundle())
if let ast = ast {
self.init(ast: ast)
} else {
return nil
}
}
}
/// Logical group of resources.
public struct ResourceGroup {
/// Name of the Resource Group
public let name:String
/// Description of the Resource Group (.raw or .html)
public let description:String?
/// Array of the respective resources belonging to the Resource Group
public let resources:[Resource]
public init(name:String, description:String?, resources:[Resource]) {
self.name = name
self.description = description
self.resources = resources
}
}
/// Description of one resource, or a cluster of resources defined by its URI template
public struct Resource {
/// Name of the Resource
public let name:String
/// Description of the Resource (.raw or .html)
public let description:String?
/// URI Template as defined in RFC6570
// TODO, make this a URITemplate object
public let uriTemplate:String
/// Array of URI parameters
public let parameters:[Parameter]
/// Array of actions available on the resource each defining at least one complete HTTP transaction
public let actions:[Action]
public let content:[[String:AnyObject]]
public init(name:String, description:String?, uriTemplate:String, parameters:[Parameter], actions:[Action], content:[[String:AnyObject]]? = nil) {
self.name = name
self.description = description
self.uriTemplate = uriTemplate
self.actions = actions
self.parameters = parameters
self.content = content ?? []
}
}
/// Description of one URI template parameter
public struct Parameter {
/// Name of the parameter
public let name:String
/// Description of the Parameter (.raw or .html)
public let description:String?
/// An arbitrary type of the parameter (a string)
public let type:String?
/// Boolean flag denoting whether the parameter is required (true) or not (false)
public let required:Bool
/// A default value of the parameter (a value assumed when the parameter is not specified)
public let defaultValue:String?
/// An example value of the parameter
public let example:String?
/// An array enumerating possible parameter values
public let values:[String]?
public init(name:String, description:String?, type:String?, required:Bool, defaultValue:String?, example:String?, values:[String]?) {
self.name = name
self.description = description
self.type = type
self.required = required
self.defaultValue = defaultValue
self.example = example
self.values = values
}
}
// An HTTP transaction (a request-response transaction). Actions are specified by an HTTP request method within a resource
public struct Action {
/// Name of the Action
public let name:String
/// Description of the Action (.raw or .html)
public let description:String?
/// HTTP request method defining the action
public let method:String
/// Array of URI parameters
public let parameters:[Parameter]
/// URI Template for the action, if it differs from the resource's URI
public let uriTemplate:String?
/// Link relation identifier of the action
public let relation:String?
/// HTTP transaction examples for the relevant HTTP request method
public let examples:[TransactionExample]
public let content:[[String:AnyObject]]
public init(name:String, description:String?, method:String, parameters:[Parameter], uriTemplate:String? = nil, relation:String? = nil, examples:[TransactionExample]? = nil, content:[[String:AnyObject]]? = nil) {
self.name = name
self.description = description
self.method = method
self.parameters = parameters
self.uriTemplate = uriTemplate
self.relation = relation
self.examples = examples ?? []
self.content = content ?? []
}
}
/// An HTTP transaction example with expected HTTP message request and response payload
public struct TransactionExample {
/// Name of the Transaction Example
public let name:String
/// Description of the Transaction Example (.raw or .html)
public let description:String?
/// Example transaction request payloads
public let requests:[Payload]
/// Example transaction response payloads
public let responses:[Payload]
public init(name:String, description:String? = nil, requests:[Payload]? = nil, responses:[Payload]? = nil) {
self.name = name
self.description = description
self.requests = requests ?? []
self.responses = responses ?? []
}
}
/// An API Blueprint payload.
public struct Payload {
public typealias Header = (name:String, value:String)
/// Name of the payload
public let name:String
/// Description of the Payload (.raw or .html)
public let description:String?
/// HTTP headers that are expected to be transferred with HTTP message represented by this payload
public let headers:[Header]
/// An entity body to be transferred with HTTP message represented by this payload
public let body:NSData?
public let content:[[String:AnyObject]]
public init(name:String, description:String? = nil, headers:[Header]? = nil, body:NSData? = nil, content:[[String:AnyObject]]? = nil) {
self.name = name
self.description = description
self.headers = headers ?? []
self.body = body
self.content = content ?? []
}
}
// MARK: AST Parsing
func compactMap<C : CollectionType, T>(source: C, transform: (C.Generator.Element) -> T?) -> [T] {
var collection = [T]()
for element in source {
if let item = transform(element) {
collection.append(item)
}
}
return collection
}
func parseMetadata(source:[[String:String]]?) -> [Metadata] {
if let source = source {
return compactMap(source) { item in
if let name = item["name"] {
if let value = item["value"] {
return (name: name, value: value)
}
}
return nil
}
}
return []
}
func parseParameter(source:[[String:AnyObject]]?) -> [Parameter] {
if let source = source {
return source.map { item in
let name = item["name"] as? String ?? ""
let description = item["description"] as? String
let type = item["type"] as? String
let required = item["required"] as? Bool
let defaultValue = item["default"] as? String
let example = item["example"] as? String
let values = item["values"] as? [String]
return Parameter(name: name, description: description, type: type, required: required ?? true, defaultValue: defaultValue, example: example, values: values)
}
}
return []
}
func parseActions(source:[[String:AnyObject]]?) -> [Action] {
if let source = source {
return compactMap(source) { item in
let name = item["name"] as? String
let description = item["description"] as? String
let method = item["method"] as? String
let parameters = parseParameter(item["parameters"] as? [[String:AnyObject]])
let attributes = item["attributes"] as? [String:String]
let uriTemplate = attributes?["uriTemplate"]
let relation = attributes?["relation"]
let examples = parseExamples(item["examples"] as? [[String:AnyObject]])
let content = item["content"] as? [[String:AnyObject]]
if let name = name {
if let method = method {
return Action(name: name, description: description, method: method, parameters: parameters, uriTemplate:uriTemplate, relation:relation, examples:examples, content:content)
}
}
return nil
}
}
return []
}
func parseExamples(source:[[String:AnyObject]]?) -> [TransactionExample] {
if let source = source {
return compactMap(source) { item in
let name = item["name"] as? String
let description = item["description"] as? String
let requests = parsePayloads(item["requests"] as? [[String:AnyObject]])
let responses = parsePayloads(item["responses"] as? [[String:AnyObject]])
if let name = name {
return TransactionExample(name: name, description: description, requests: requests, responses: responses)
}
return nil
}
}
return []
}
func parsePayloads(source:[[String:AnyObject]]?) -> [Payload] {
if let source = source {
return compactMap(source) { item in
let name = item["name"] as? String
let description = item["description"] as? String
let headers = parseHeaders(item["headers"] as? [[String:String]])
let bodyString = item["body"] as? String
let body = bodyString?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let content = item["content"] as? [[String:AnyObject]]
if let name = name {
return Payload(name: name, description: description, headers: headers, body: body, content: content)
}
return nil
}
}
return []
}
func parseHeaders(source:[[String:String]]?) -> [Payload.Header] {
if let source = source {
return compactMap(source) { item in
if let name = item["name"] {
if let value = item["value"] {
return (name, value)
}
}
return nil
}
}
return []
}
func parseResources(source:[[String:AnyObject]]?) -> [Resource] {
if let source = source {
return compactMap(source) { item in
let name = item["name"] as? String
let description = item["description"] as? String
let uriTemplate = item["uriTemplate"] as? String
let actions = parseActions(item["actions"] as? [[String:AnyObject]])
let parameters = parseParameter(item["parameters"] as? [[String:AnyObject]])
let content = item["content"] as? [[String:AnyObject]]
if let name = name {
if let uriTemplate = uriTemplate {
return Resource(name: name, description: description, uriTemplate: uriTemplate, parameters: parameters, actions: actions, content: content)
}
}
return nil
}
}
return []
}
private func parseBlueprintResourceGroups(blueprint:[String:AnyObject]) -> [ResourceGroup] {
if let resourceGroups = blueprint["resourceGroups"] as? [[String:AnyObject]] {
return compactMap(resourceGroups) { dictionary in
if let name = dictionary["name"] as? String {
let resources = parseResources(dictionary["resources"] as? [[String:AnyObject]])
let description = dictionary["description"] as? String
return ResourceGroup(name: name, description: description, resources: resources)
}
return nil
}
}
return []
}
| 29.995 | 214 | 0.675613 |
ed49c6d320bcc568c6189c7af5d2b3b3907c369f | 11,703 | //
// HTTPRequest.swift
// SwitcheoSwift
//
// Created by Rataphon Chitnorm on 8/16/18.
// Copyright © 2018 O3 Labs Inc. All rights reserved.
//
import Foundation
import Neoutils
public class Switcheo {
var baseURL = "https://test-api.switcheo.network"
public enum Net: String {
case Test = "https://test-api.switcheo.network"
case Main = "https://api.switcheo.network"
}
var apiVersion = "/v2/"
enum HTTPMethod: String {
case GET
case POST
}
public init?(net: Net) {
self.baseURL = net.rawValue
}
public typealias JSONDictionary = [String: Any]
public struct O3Error {
public var message: String
}
public enum SWTHResult<T> {
case success(T)
case failure(String)
}
func log(_ errorMessage: String, functionName: String = #function) ->String {
return "\(functionName): \(errorMessage)"
}
public enum SWTHError: Error {
case invalidBodyRequest, invalidData, invalidRequest, noInternet, switcheoError, switcheoDataError, serverError
var localizedDescription: String {
switch self {
case .invalidBodyRequest:
return "Invalid body Request"
case .invalidData:
return "Invalid response data"
case .invalidRequest:
return "Invalid server request"
case .noInternet:
return "No Internet connection"
case .switcheoError:
return "Swticheo API error"
case .switcheoDataError:
return "Swticheo data error"
case .serverError:
return "Internal server error"
}
}
}
func sendRequest<T>(ofType _: T.Type,_ endpointURL: String, method: HTTPMethod, data: JSONDictionary, completion: @escaping (SWTHResult<T>) -> Void){
let url = URL(string: baseURL + apiVersion + endpointURL)!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("o3", forHTTPHeaderField: "User-Agent")
request.httpMethod = method.rawValue
request.cachePolicy = .reloadIgnoringLocalCacheData
if data.count > 0 {
guard let body = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.sortedKeys) else {
completion(.failure(self.log("JSONSerialization Error")))
return
}
request.httpBody = body
}
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, err) in
if err != nil {
completion(.failure(self.log(err.debugDescription)))
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
#if DEBUG
print(response as Any)
guard let errorUnwrapped = data,
let jsonError = (try? JSONSerialization.jsonObject(with: errorUnwrapped, options: [])) as? JSONDictionary else {
completion(.failure(self.log("JSONSerialization Error")))
return
}
print(endpointURL,jsonError,"________ERROR_________")
#endif
completion(.failure(self.log(jsonError.toString())))
return
}
guard let dataUnwrapped = data,
let json = (try? JSONSerialization.jsonObject(with: dataUnwrapped, options: [])) as? T else {
completion(.failure(self.log("JSONSerialization Error")))
return
}
let result = SWTHResult.success(json)
completion(result)
}
task.resume()
}
public func tickersCandlesticks(request: RequestCandlesticks,
completion: @escaping (SWTHResult<[Candlestick]>) -> Void){
sendRequest(ofType:[JSONDictionary].self,
"tickers/candlesticks",
method: .GET,
data: request.dictionary,
completion: { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let responseData = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let result = try? decoder.decode([Candlestick].self, from: responseData!)
if (result == nil) {
completion(.failure(self.log("Invalid Data")))
return
}
let w = SWTHResult.success(result!)
completion(w)
}
})
}
public func tickersLast24hours(completion: @escaping (SWTHResult<[Last24hour]>) -> Void){
sendRequest(ofType: [JSONDictionary].self,
"tickers/last_24_hours",
method: .GET,
data: [:]) { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let responseData = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let result = try? decoder.decode([Last24hour].self, from: responseData!)
if (result == nil) {
completion(.failure(self.log("Invalid Data")))
return
}
let w = SWTHResult.success(result!)
completion(w)
}
}
}
public func tickersLastPrice(symbols: [String], completion: @escaping (SWTHResult<JSONDictionary>) -> Void){
sendRequest(ofType:JSONDictionary.self,
"tickers/last_price",
method: .GET,
data: ["symbols":symbols],
completion: completion)
}
public func offers(request: RequestOffer,
completion: @escaping (SWTHResult<[Offer]>) -> Void){
sendRequest(ofType:[JSONDictionary].self,
"offers",
method: .GET,
data: request.dictionary,
completion: { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let responseData = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let result = try? decoder.decode([Offer].self, from: responseData!)
if (result == nil) {
completion(.failure(self.log("Invalid Data")))
return
}
let w = SWTHResult.success(result!)
completion(w)
}
})
}
public func trades(request: RequestTrade,
completion: @escaping (SWTHResult<[Trade]>) -> Void){
sendRequest(ofType:[JSONDictionary].self,
"trades",
method: .GET,
data: request.dictionary,
completion: { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let responseData = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let result = try? decoder.decode([Trade].self, from: responseData!)
if (result == nil) {
completion(.failure(self.log("Invalid Data")))
return
}
let w = SWTHResult.success(result!)
completion(w)
}
})
}
public func balances(addresses: [String],contractHashs: [String],completion: @escaping (SWTHResult<JSONDictionary>) -> Void){
let data = ["addresses": addresses, "contract_hashes": contractHashs] as JSONDictionary
self.sendRequest(ofType:JSONDictionary.self,
"balances",
method: .GET,
data: data,
completion: completion)
}
public func contracts(completion: @escaping (SWTHResult<JSONDictionary>) -> Void){
sendRequest(ofType:JSONDictionary.self,
"contracts",
method: .GET,
data: [:],
completion: completion)
}
public func exchangeTimestamp(completion: @escaping (SWTHResult<JSONDictionary>) -> Void){
sendRequest(ofType:JSONDictionary.self,
"exchange/timestamp",
method: .GET,
data: [:],
completion: completion)
}
public func exchangePairs(bases :[String], completion: @escaping (SWTHResult<[String]>) -> Void){
sendRequest(ofType: [String].self,
"exchange/pairs",
method: .GET,
data: ["bases":bases],
completion: completion)
}
public func exchangeTokens(completion: @escaping (SWTHResult<JSONDictionary>) -> Void){
let cache = NSCache<NSString, AnyObject>()
if let cached = cache.object(forKey: "SWTH_SUPPORTED_TOKEN") {
// use the cached version
let response = cached as! JSONDictionary
let w = SWTHResult.success(response)
completion(w)
return
} else {
sendRequest(ofType: JSONDictionary.self,
"exchange/tokens",
method: .GET,
data: [:],
completion: { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
// create it from scratch then store in the cache
cache.setObject(response as AnyObject, forKey: "SWTH_SUPPORTED_TOKEN")
let w = SWTHResult.success(response)
completion(w)
}
})
}
}
}
| 40.91958 | 153 | 0.484064 |
4a5171048695a484497dbd8dac9c317e126ef88f | 4,105 | /**
* Copyright (c) 2017 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.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import SceneKit
import SpriteKit
class ViewController: UIViewController {
let game = GameHelper.sharedInstance
var scnView: SCNView!
var gameScene: SCNScene!
var splashScene: SCNScene!
var pigNode: SCNNode!
var cameraNode: SCNNode!
var cameraFollowNode: SCNNode!
var lightFollowNode: SCNNode!
override func viewDidLoad() {
super.viewDidLoad()
setupScenes()
setupNodes()
setupActions()
setupTraffic()
setupGestures()
setupSounds()
game.state = .tapToPlay
}
func setupScenes() {
scnView = SCNView(frame: self.view.frame)
self.view.addSubview(scnView)
gameScene = SCNScene(named: "/MrPig.scnassets/GameScene.scn")
splashScene = SCNScene(named: "/MrPig.scnassets/SplashScene.scn")
scnView.scene = splashScene
}
func setupNodes() {
pigNode = gameScene.rootNode.childNode(withName: "MrPig", recursively: true)!
cameraNode = gameScene.rootNode.childNode(withName: "camera", recursively: true)!
cameraNode.addChildNode(game.hudNode)
cameraFollowNode = gameScene.rootNode.childNode(withName: "FollowCamera", recursively: true)!
lightFollowNode = gameScene.rootNode.childNode(withName: "FollowLight", recursively: true)!
}
func setupActions() {
}
func setupTraffic() {
}
func setupGestures() {
}
func setupSounds() {
}
func startSplash() {
gameScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(splashScene, with: transition, incomingPointOfView: nil, completionHandler: {
self.game.state = .tapToPlay
self.setupSounds()
self.splashScene.isPaused = false
})
}
func startGame() {
splashScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(gameScene, with: transition, incomingPointOfView: nil, completionHandler: {
self.game.state = .playing
self.setupSounds()
self.gameScene.isPaused = false
})
}
func stopGame() {
game.state = .gameOver
game.reset()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if game.state == .tapToPlay {
startGame()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden : Bool { return true }
override var shouldAutorotate : Bool { return false }
}
| 32.322835 | 97 | 0.722046 |
61a5b1729409e552b9f14585c370d677805d2da1 | 692 | //
// Nodes.swift
// ofx-ledger-sync
//
// Created by Horner, Stefan (LDN-ARC) on 06/10/2016.
// Copyright © 2016 tedslittlerobot. All rights reserved.
//
import Foundation
class Node {
var tag : String
var parentNode : Node?
var children : [Node] = []
init(name : String, parent : Node?) {
tag = name
parentNode = parent
}
}
class ObjectNode : Node {}
class RootNode : ObjectNode {
init() {
super.init(name: "root", parent: nil)
}
}
class TextNode : Node {
var content : String
init(name : String, parent : Node , contents : String) {
content = contents
super.init(name: name, parent: parent)
}
}
| 16.878049 | 60 | 0.589595 |
5dbf398f5251589f33dc1bd13e8a370cdff6aefc | 1,672 | //
// UrlUtils.swift
// TeamupKit
//
// Created by Merrick Sapsford on 14/06/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import Foundation
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map{ parameter -> String in
let percentEscapedKey = (parameter.key as! String).addingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (parameter.value as? String ?? String(describing: parameter.value)).addingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
extension String {
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func addingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
}
| 35.574468 | 146 | 0.680024 |
b911ff8d3674afd30171089bd5c637a87495d7e2 | 527 | import Foundation
import ArgumentParser
import KrakenAPI
struct SelfTest: ParsableCommand {
public static let configuration = CommandConfiguration(
abstract: "Performs various tests against the public Kraken API"
)
func run() throws {
exitOnCtrlC()
let configuration = Configuration(
environment: .production,
access: .public)
let wsapi = WebSocketAPI(
configuration: configuration)
wsapi.connect()
RunLoop.main.run()
}
func exitOnCtrlC() {
signal(SIGINT) { _ in SelfTest.exit() }
}
}
| 18.172414 | 66 | 0.72296 |
037d5a76c2390f4c972d91ce22948380bd835e36 | 4,286 | //
// SplashVC.swift
// PathFinder
//
// Created by Fury on 26/07/2019.
// Copyright © 2019 Fury. All rights reserved.
//
import UIKit
import Firebase
import GoogleMaps
class SplashVC: UIViewController {
private let shared = DataProvider.shared
private var timer: Timer!
private let mainView: UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let circleView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.appColor(.moongCherColor)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let titleText: UILabel = {
let label = UILabel()
label.text = "moongcher"
label.font = UIFont.systemFont(ofSize: 48, weight: .bold)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let subText: UILabel = {
let label = UILabel()
label.textColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1)
label.text = "긴급 상황 발생 시 화면을 터치하세요"
label.font = UIFont.systemFont(ofSize: 18, weight: .medium)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.appColor(.moongCherColor)
setupProperties()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(startSplash), userInfo: nil, repeats: false)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
circleView.layer.cornerRadius = circleView.frame.width / 2
}
@objc private func startSplash() {
getCrimeDatas()
}
private func getCrimeDatas() {
let db = Firestore.firestore()
db.collection("Crime").getDocuments { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
self.shared.crimeDocument.append(document.documentID)
let data = CrimeModel(
postion: document["position"] as! [CGFloat],
location: document["location"] as! String,
type: document["type"] as! String,
date: document["date"] as! String,
state: document["state"] as! String,
caseNumber: document["caseNumber"] as! String,
districtPliceStation: document["districtPliceStation"] as! [String],
reward: document["reward"] as! [Int]
)
self.shared.crimeData.append(data)
}
let mainVC = MainVC()
self.present(mainVC, animated: false)
}
}
}
private func setupProperties() {
let guide = view.safeAreaLayoutGuide
let margin: CGFloat = 10
view.addSubview(mainView)
mainView.topAnchor.constraint(equalTo: guide.topAnchor, constant: margin * 3).isActive = true
mainView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
mainView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
mainView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -margin * 3).isActive = true
view.addSubview(circleView)
circleView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
circleView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
circleView.widthAnchor.constraint(equalToConstant: view.frame.width / 2).isActive = true
circleView.heightAnchor.constraint(equalTo: circleView.widthAnchor).isActive = true
view.addSubview(titleText)
titleText.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
titleText.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
view.addSubview(subText)
subText.topAnchor.constraint(equalTo: titleText.bottomAnchor).isActive = true
subText.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
subText.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
}
| 34.015873 | 130 | 0.692254 |
d96e8a17e96edc3d68c9c9d5e3dd5dea4e82b84b | 3,291 | import Foundation
/// Type holding information about weather alerts such as thunderstorms
public struct Alert: Codable, Equatable {
///A brief description of the alert
public let title: String
///The time at which the alert was issues
public let timeStamp: Date
///The UNIX time at which the alert will expire.
public let expires: Date
///A detailed description of the alert.
public let description: String
///A URL that one may refer to for detailed information about the alert.
public let url: URL
///An array of strings representing the names of the regions covered by this weather alert.
public let affectedRegions: [String]
///The severity of the weather alert
public let severity: AlertSeverity
public var isExpired: Bool {
return expires.timeIntervalSinceNow < 0.00
}
private enum CodingKeys: String, CodingKey {
case title
case timeStamp = "time"
case expires
case description
case url = "uri"
case affectedRegions = "regions"
case severity
}
}
/// Enum specifying the severity of a weather alert
public enum AlertSeverity: String, Codable, Equatable {
///An individual should be aware of potentially severe weather
case advisory
///An individual should prepare for potentially severe weather
case watch
///An individual should take immediate action to protect themselves and others from potentially severe weather
case warning
public static func severity(for dangerLevel: Int) -> AlertSeverity? {
guard (1...3).contains(dangerLevel) else {
return nil
}
switch dangerLevel {
case 1:
return .advisory
case 2:
return .watch
case 3:
return .warning
default:
return nil
}
}
public var dangerLevel: Int {
switch self {
case .advisory:
return 1
case .watch:
return 2
case .warning:
return 3
}
}
}
#if os(iOS) || os(tvOS)
import UIKit
@available(iOS 13, tvOS 13, *)
public extension AlertSeverity {
///Returns a filled icon from the SF Symbols library
@available(iOS 13, tvOS 13, *)
func filledIcon(compatibleWith traitCollection: UITraitCollection?) -> UIImage {
return makeIcon(filled: true, compatibleWith: traitCollection)
}
///Returns a hollow/line icon from the SF Symbols library
@available(iOS 13, tvOS 13, *)
func hollowIcon(compatibleWith traitCollection: UITraitCollection?) -> UIImage {
return makeIcon(filled: false, compatibleWith: traitCollection)
}
@available(iOS 13, tvOS 13, *)
private func makeIcon(filled: Bool, compatibleWith traitCollection: UITraitCollection?) -> UIImage {
let iconName: String
switch self {
case .advisory:
iconName = "info.circle"
case .watch:
iconName = "eye"
case .warning:
iconName = "exclamationmark.triangle"
}
return filled
? UIImage(systemName: iconName + ".fill", compatibleWith: traitCollection)!
: UIImage(systemName: iconName, compatibleWith: traitCollection)!
}
}
#endif
| 30.192661 | 114 | 0.642054 |
ff7ae5a4b1b1e2c87cfb19730ab865150c5a1f57 | 2,735 | //
// Created by Eugene Kazaev on 2018-09-17.
//
import Foundation
import UIKit
/// A wrapper for the general steps that can be applied to any `UIViewController`
public struct GeneralStep {
struct RootViewControllerStep: RoutingStep, PerformableStep {
let windowProvider: WindowProvider
/// Constructor
init(windowProvider: WindowProvider = KeyWindowProvider()) {
self.windowProvider = windowProvider
}
func perform(with context: Any?) throws -> PerformableStepResult {
guard let viewController = windowProvider.window?.rootViewController else {
throw RoutingError.generic(.init("Root view controller was not found."))
}
return .success(viewController)
}
}
struct CurrentViewControllerStep: RoutingStep, PerformableStep {
let windowProvider: WindowProvider
/// Constructor
init(windowProvider: WindowProvider = KeyWindowProvider()) {
self.windowProvider = windowProvider
}
func perform(with context: Any?) throws -> PerformableStepResult {
guard let viewController = windowProvider.window?.topmostViewController else {
throw RoutingError.generic(.init("Topmost view controller was not found."))
}
return .success(viewController)
}
}
struct FinderStep: RoutingStep, PerformableStep {
let finder: AnyFinder?
init<F: Finder>(finder: F) {
self.finder = FinderBox(finder)
}
func perform(with context: Any?) throws -> PerformableStepResult {
guard let viewController = try finder?.findViewController(with: context) else {
throw RoutingError.generic(.init("A view controller of \(String(describing: finder)) was not found."))
}
return .success(viewController)
}
}
/// Returns the root view controller of the key window.
public static func root<C>(windowProvider: WindowProvider = KeyWindowProvider()) -> DestinationStep<UIViewController, C> {
return DestinationStep(RootViewControllerStep(windowProvider: windowProvider))
}
/// Returns the topmost presented view controller.
public static func current<C>(windowProvider: WindowProvider = KeyWindowProvider()) -> DestinationStep<UIViewController, C> {
return DestinationStep(CurrentViewControllerStep(windowProvider: windowProvider))
}
/// Returns the resulting view controller of the finder provided.
public static func custom<F: Finder>(using finder: F) -> DestinationStep<F.ViewController, F.Context> {
return DestinationStep(FinderStep(finder: finder))
}
}
| 34.620253 | 129 | 0.66947 |
de1a9cefc7233d2c16dbf2cc3d818afeb83ec1b2 | 826 | //
// Sheets_FetcherApp.swift
// Sheets-Fetcher
//
// Created by Samuel Ivarsson on 2020-09-19.
//
import SwiftUI
import WidgetKit
@main
struct Sheets_FetcherApp: App {
var body: some Scene {
WindowGroup {
ContentView().onOpenURL { url in
if url.scheme == "com.samuelivarsson.Sheets-Fetcher" || url.scheme == "sheets-fetcher" {
WidgetCenter.shared.reloadAllTimelines()
UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
// UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// exit(0)
// }
}
}
}
}
}
| 28.482759 | 113 | 0.548426 |
16aeba2602aebf67dc38b2efe649fa666acad030 | 24,784 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// TestECDH.swift
//
// Created by Michael Scott on 02/07/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
import Foundation
import amcl // comment out for Xcode
import ed25519
import nist256
import goldilocks
import bn254
import bls383
import bls24
import bls48
import rsa2048
public func TimeRSA_2048(_ rng: inout RAND)
{
let RFS=RSA.RFS
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
var pub=rsa_public_key(Int(CONFIG_FF.FFLEN))
var priv=rsa_private_key(Int(CONFIG_FF.HFLEN))
var M=[UInt8](repeating: 0,count: RFS)
var C=[UInt8](repeating: 0,count: RFS)
var P=[UInt8](repeating: 0,count: RFS)
print("\nTiming/Testing 2048-bit RSA")
print("Generating public/private key pair")
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.KEY_PAIR(&rng,65537,&priv,&pub)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA gen - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
for i in 0..<RFS {M[i]=UInt8(i%128)}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.ENCRYPT(pub,M,&C)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA enc - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
RSA.DECRYPT(priv,C,&P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "RSA dec - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var cmp=true
for i in 0..<RFS {
if P[i] != M[i] {cmp=false}
}
if !cmp {
print("FAILURE - RSA decryption")
fail=true;
}
if !fail {
print("All tests pass")
}
}
public func TimeECDH_ed25519(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing ED25519 ECC")
if ed25519.CONFIG_CURVE.CURVETYPE==ed25519.CONFIG_CURVE.WEIERSTRASS {
print("Weierstrass parameterisation")
}
if ed25519.CONFIG_CURVE.CURVETYPE==ed25519.CONFIG_CURVE.EDWARDS {
print("Edwards parameterisation")
}
if ed25519.CONFIG_CURVE.CURVETYPE==ed25519.CONFIG_CURVE.MONTGOMERY {
print("Montgomery representation")
}
if ed25519.CONFIG_FIELD.MODTYPE==ed25519.CONFIG_FIELD.PSEUDO_MERSENNE {
print("Pseudo-Mersenne Modulus")
}
if ed25519.CONFIG_FIELD.MODTYPE==ed25519.CONFIG_FIELD.MONTGOMERY_FRIENDLY {
print("Montgomery Friendly Modulus")
}
if ed25519.CONFIG_FIELD.MODTYPE==ed25519.CONFIG_FIELD.GENERALISED_MERSENNE {
print("Generalised-Mersenne Modulus")
}
if ed25519.CONFIG_FIELD.MODTYPE==ed25519.CONFIG_FIELD.NOT_SPECIAL {
print("Not special Modulus")
}
print("Modulus size \(ed25519.CONFIG_FIELD.MODBITS) bits")
print("\(ed25519.CONFIG_BIG.CHUNK) bit build")
var s:ed25519.BIG
let G=ed25519.ECP.generator();
let r=ed25519.BIG(ed25519.ROM.CURVE_Order)
s=ed25519.BIG.randomnum(r,&rng)
var W=G.mul(r)
if !W.is_infinity() {
print("FAILURE - rG!=O")
fail=true;
}
let start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=G.mul(s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "EC mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
if !fail {
print("All tests pass")
}
}
public func TimeECDH_nist256(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing NIST256 ECC")
if nist256.CONFIG_CURVE.CURVETYPE==nist256.CONFIG_CURVE.WEIERSTRASS {
print("Weierstrass parameterisation")
}
if nist256.CONFIG_CURVE.CURVETYPE==nist256.CONFIG_CURVE.EDWARDS {
print("Edwards parameterisation")
}
if nist256.CONFIG_CURVE.CURVETYPE==nist256.CONFIG_CURVE.MONTGOMERY {
print("Montgomery representation")
}
if nist256.CONFIG_FIELD.MODTYPE==nist256.CONFIG_FIELD.PSEUDO_MERSENNE {
print("Pseudo-Mersenne Modulus")
}
if nist256.CONFIG_FIELD.MODTYPE==nist256.CONFIG_FIELD.MONTGOMERY_FRIENDLY {
print("Montgomery Friendly Modulus")
}
if nist256.CONFIG_FIELD.MODTYPE==nist256.CONFIG_FIELD.GENERALISED_MERSENNE {
print("Generalised-Mersenne Modulus")
}
if nist256.CONFIG_FIELD.MODTYPE==nist256.CONFIG_FIELD.NOT_SPECIAL {
print("Not special Modulus")
}
print("Modulus size \(nist256.CONFIG_FIELD.MODBITS) bits")
print("\(nist256.CONFIG_BIG.CHUNK) bit build")
var s:nist256.BIG
let G=nist256.ECP.generator();
let r=nist256.BIG(nist256.ROM.CURVE_Order)
s=nist256.BIG.randomnum(r,&rng)
var W=G.mul(r)
if !W.is_infinity() {
print("FAILURE - rG!=O")
fail=true;
}
let start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=G.mul(s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "EC mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
if !fail {
print("All tests pass")
}
}
public func TimeECDH_goldilocks(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing GOLDILOCKS ECC")
if goldilocks.CONFIG_CURVE.CURVETYPE==goldilocks.CONFIG_CURVE.WEIERSTRASS {
print("Weierstrass parameterisation")
}
if goldilocks.CONFIG_CURVE.CURVETYPE==goldilocks.CONFIG_CURVE.EDWARDS {
print("Edwards parameterisation")
}
if goldilocks.CONFIG_CURVE.CURVETYPE==goldilocks.CONFIG_CURVE.MONTGOMERY {
print("Montgomery representation")
}
if goldilocks.CONFIG_FIELD.MODTYPE==goldilocks.CONFIG_FIELD.PSEUDO_MERSENNE {
print("Pseudo-Mersenne Modulus")
}
if goldilocks.CONFIG_FIELD.MODTYPE==goldilocks.CONFIG_FIELD.MONTGOMERY_FRIENDLY {
print("Montgomery Friendly Modulus")
}
if goldilocks.CONFIG_FIELD.MODTYPE==goldilocks.CONFIG_FIELD.GENERALISED_MERSENNE {
print("Generalised-Mersenne Modulus")
}
if goldilocks.CONFIG_FIELD.MODTYPE==goldilocks.CONFIG_FIELD.NOT_SPECIAL {
print("Not special Modulus")
}
print("Modulus size \(goldilocks.CONFIG_FIELD.MODBITS) bits")
print("\(goldilocks.CONFIG_BIG.CHUNK) bit build")
var s:goldilocks.BIG
let G=goldilocks.ECP.generator();
let r=goldilocks.BIG(goldilocks.ROM.CURVE_Order)
s=goldilocks.BIG.randomnum(r,&rng)
var W=G.mul(r)
if !W.is_infinity() {
print("FAILURE - rG!=O")
fail=true;
}
let start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=G.mul(s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "EC mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
if !fail {
print("All tests pass")
}
}
public func TimeMPIN_bn254(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing BN254 Pairings")
if bn254.CONFIG_CURVE.CURVE_PAIRING_TYPE==bn254.CONFIG_CURVE.BN {
print("BN Pairing-Friendly Curve")
}
if bn254.CONFIG_CURVE.CURVE_PAIRING_TYPE==bn254.CONFIG_CURVE.BLS {
print("BLS Pairing-Friendly Curve")
}
print("Modulus size \(bn254.CONFIG_FIELD.MODBITS) bits")
print("\(bn254.CONFIG_BIG.CHUNK) bit build")
let G=bn254.ECP.generator();
let r=bn254.BIG(bn254.ROM.CURVE_Order)
let s=bn254.BIG.randomnum(r,&rng)
var P=bn254.PAIR.G1mul(G,r);
if !P.is_infinity() {
print("FAILURE - rP!=O")
fail=true
}
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
P=bn254.PAIR.G1mul(G,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G1 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var Q=bn254.ECP2.generator();
var W=bn254.PAIR.G2mul(Q,r)
if !W.is_infinity() {
print("FAILURE - rQ!=O")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=bn254.PAIR.G2mul(Q,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G2 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var w=bn254.PAIR.ate(Q,P)
w=bn254.PAIR.fexp(w)
var g=bn254.PAIR.GTpow(w,r)
if !g.isunity() {
print("FAILURE - g^r!=1")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=bn254.PAIR.GTpow(w,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
g.copy(w)
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
_=g.compow(s,r)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow (compressed) - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
w=bn254.PAIR.ate(Q,P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing ATE - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=bn254.PAIR.fexp(w)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing FEXP - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
P.copy(G)
Q.copy(W)
P=bn254.PAIR.G1mul(P,s)
g=bn254.PAIR.ate(Q,P)
g=bn254.PAIR.fexp(g)
P.copy(G)
Q=bn254.PAIR.G2mul(Q,s)
w=bn254.PAIR.ate(Q,P)
w=bn254.PAIR.fexp(w)
if !g.equals(w) {
print("FAILURE - e(sQ,P)!=e(Q,sP)")
fail=true
}
if !fail {
print("All tests pass")
}
}
public func TimeMPIN_bls383(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing BLS383 Pairings")
if bls383.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls383.CONFIG_CURVE.BN {
print("BN Pairing-Friendly Curve")
}
if bls383.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls383.CONFIG_CURVE.BLS {
print("BLS Pairing-Friendly Curve")
}
print("Modulus size \(bls383.CONFIG_FIELD.MODBITS) bits")
print("\(bls383.CONFIG_BIG.CHUNK) bit build")
let G=bls383.ECP.generator();
let r=bls383.BIG(bls383.ROM.CURVE_Order)
let s=bls383.BIG.randomnum(r,&rng)
var P=bls383.PAIR.G1mul(G,r);
if !P.is_infinity() {
print("FAILURE - rP!=O")
fail=true
}
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
P=bls383.PAIR.G1mul(G,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G1 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var Q=bls383.ECP2.generator();
var W=bls383.PAIR.G2mul(Q,r)
if !W.is_infinity() {
print("FAILURE - rQ!=O")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=bls383.PAIR.G2mul(Q,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G2 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var w=bls383.PAIR.ate(Q,P)
w=bls383.PAIR.fexp(w)
var g=bls383.PAIR.GTpow(w,r)
if !g.isunity() {
print("FAILURE - g^r!=1")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=bls383.PAIR.GTpow(w,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
g.copy(w)
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
_=g.compow(s,r)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow (compressed) - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
w=bls383.PAIR.ate(Q,P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing ATE - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=bls383.PAIR.fexp(w)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing FEXP - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
P.copy(G)
Q.copy(W)
P=bls383.PAIR.G1mul(P,s)
g=bls383.PAIR.ate(Q,P)
g=bls383.PAIR.fexp(g)
P.copy(G)
Q=bls383.PAIR.G2mul(Q,s)
w=bls383.PAIR.ate(Q,P)
w=bls383.PAIR.fexp(w)
if !g.equals(w) {
print("FAILURE - e(sQ,P)!=e(Q,sP)")
fail=true
}
if !fail {
print("All tests pass")
}
}
public func TimeMPIN_bls24(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing BLS24 Pairings")
if bls24.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls24.CONFIG_CURVE.BN {
print("BN Pairing-Friendly Curve")
}
if bls24.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls24.CONFIG_CURVE.BLS {
print("BLS24 Pairing-Friendly Curve")
}
print("Modulus size \(bls24.CONFIG_FIELD.MODBITS) bits")
print("\(bls24.CONFIG_BIG.CHUNK) bit build")
let G=bls24.ECP.generator();
let r=bls24.BIG(bls24.ROM.CURVE_Order)
let s=bls24.BIG.randomnum(r,&rng)
var P=PAIR192.G1mul(G,r);
if !P.is_infinity() {
print("FAILURE - rP!=O")
fail=true
}
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
P=PAIR192.G1mul(G,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G1 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var Q=ECP4.generator();
var W=PAIR192.G2mul(Q,r)
if !W.is_infinity() {
print("FAILURE - rQ!=O")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=PAIR192.G2mul(Q,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G2 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var w=PAIR192.ate(Q,P)
w=PAIR192.fexp(w)
var g=PAIR192.GTpow(w,r)
if !g.isunity() {
print("FAILURE - g^r!=1")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=PAIR192.GTpow(w,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
g.copy(w)
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
_=g.compow(s,r)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow (compressed) - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
w=PAIR192.ate(Q,P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing ATE - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=PAIR192.fexp(w)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing FEXP - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
P.copy(G)
Q.copy(W)
P=PAIR192.G1mul(P,s)
g=PAIR192.ate(Q,P)
g=PAIR192.fexp(g)
P.copy(G)
Q=PAIR192.G2mul(Q,s)
w=PAIR192.ate(Q,P)
w=PAIR192.fexp(w)
if !g.equals(w) {
print("FAILURE - e(sQ,P)!=e(Q,sP)")
fail=true
}
if !fail {
print("All tests pass")
}
}
public func TimeMPIN_bls48(_ rng: inout RAND)
{
let MIN_TIME=10.0
let MIN_ITERS=10
var fail=false;
print("\nTiming/Testing BLS48 Pairings")
if bls48.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls48.CONFIG_CURVE.BN {
print("BN Pairing-Friendly Curve")
}
if bls48.CONFIG_CURVE.CURVE_PAIRING_TYPE==bls48.CONFIG_CURVE.BLS {
print("BLS48 Pairing-Friendly Curve")
}
print("Modulus size \(bls48.CONFIG_FIELD.MODBITS) bits")
print("\(bls48.CONFIG_BIG.CHUNK) bit build")
let G=bls48.ECP.generator();
let r=bls48.BIG(bls48.ROM.CURVE_Order)
let s=bls48.BIG.randomnum(r,&rng)
var P=PAIR256.G1mul(G,r);
if !P.is_infinity() {
print("FAILURE - rP!=O")
fail=true
}
var start=Date()
var iterations=0
var elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
P=PAIR256.G1mul(G,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G1 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var Q=ECP8.generator();
var W=PAIR256.G2mul(Q,r)
if !W.is_infinity() {
print("FAILURE - rQ!=O")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
W=PAIR256.G2mul(Q,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "G2 mul - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
var w=PAIR256.ate(Q,P)
w=PAIR256.fexp(w)
var g=PAIR256.GTpow(w,r)
if !g.isunity() {
print("FAILURE - g^r!=1")
fail=true
}
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=PAIR256.GTpow(w,s)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
g.copy(w)
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
_=g.compow(s,r)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "GT pow (compressed) - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
w=PAIR256.ate(Q,P)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing ATE - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
start=Date()
iterations=0
elapsed=0.0
while elapsed<MIN_TIME || iterations<MIN_ITERS {
g=PAIR256.fexp(w)
iterations+=1
elapsed = -start.timeIntervalSinceNow
}
elapsed=1000.0*elapsed/Double(iterations)
print(String(format: "PAIRing FEXP - %d iterations",iterations),terminator: "");
print(String(format: " %.2f ms per iteration",elapsed))
P.copy(G)
Q.copy(W)
P=PAIR256.G1mul(P,s)
g=PAIR256.ate(Q,P)
g=PAIR256.fexp(g)
P.copy(G)
Q=PAIR256.G2mul(Q,s)
w=PAIR256.ate(Q,P)
w=PAIR256.fexp(w)
if !g.equals(w) {
print("FAILURE - e(sQ,P)!=e(Q,sP)")
fail=true
}
if !fail {
print("All tests pass")
}
}
var RAW=[UInt8](repeating: 0,count: 100)
var rng=RAND()
rng.clean();
for i in 0 ..< 100 {RAW[i]=UInt8(i&0xff)}
rng.seed(100,RAW)
TimeECDH_ed25519(&rng)
TimeECDH_nist256(&rng)
TimeECDH_goldilocks(&rng)
TimeRSA_2048(&rng)
TimeMPIN_bn254(&rng)
TimeMPIN_bls383(&rng)
TimeMPIN_bls24(&rng)
TimeMPIN_bls48(&rng)
| 27.90991 | 92 | 0.627582 |
3ac644db6fe735ec33d7f78e89822d481227a5f2 | 3,364 | //
// CollectionViewController.swift
// GoOut Restauracje
//
// Created by Michal Szymaniak on 18/09/16.
// Copyright © 2016 Codelabs. All rights reserved.
//
import UIKit
import Kingfisher
protocol CollectionViewControllerDelegate
{
func collectionController(_ collectionController:CollectionViewController, scrolledToCellAtIndexPath indexPath:IndexPath);
}
class CollectionViewController: NSObject, UICollectionViewDelegate, UICollectionViewDataSource
{
var parentCollectionView:UICollectionView?
var collectionDelegate:CollectionViewControllerDelegate! = nil
var parentViewController:UIViewController?
var dataArray = NSArray()
//MARK:TableView delegate dataSource
func setupCollectionView()
{
parentCollectionView?.delegate = self;
parentCollectionView?.dataSource = self;
}
func reloadCollectionView()
{
self.parentCollectionView?.reloadData()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cellIdentifier = "CollectionViewCell"
let collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
let imageView = UIImageView()
imageView.frame.size.width = (parentCollectionView?.frame.size.width)!
imageView.frame.size.height = (parentCollectionView?.frame.size.height)!
collectionCell.addSubview(imageView)
let url = URL(string: RestConstants.imagesBaseLink + (dataArray[(indexPath as NSIndexPath).row] as! String))
imageView.kf.setImage(with: url!)
imageView.contentMode = .scaleAspectFill
return collectionCell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return dataArray.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize
{
return CGSize(width: (parentCollectionView?.frame)!.width, height: (parentCollectionView?.frame)!.height);
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat
{
return 1;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
{
return 1;
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
{
let collectionOrigin = parentCollectionView!.bounds.origin
let collectionWidth = parentCollectionView!.bounds.width
var centerPoint: CGPoint!
var newX: CGFloat!
if collectionOrigin.x > 0 {
newX = collectionOrigin.x + collectionWidth / 2
centerPoint = CGPoint(x: newX, y: collectionOrigin.y)
} else {
newX = collectionWidth / 2
centerPoint = CGPoint(x: newX, y: collectionOrigin.y)
}
let indexPath:IndexPath = parentCollectionView!.indexPathForItem(at: centerPoint)!
collectionDelegate.collectionController(self, scrolledToCellAtIndexPath: indexPath)
}
}
| 36.565217 | 178 | 0.721165 |
de63df036073e24199d43dee70414aad8738850e | 6,438 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
@available(SwiftStdlib 5.7, *)
extension Regex {
/// The result of matching a regex against a string.
///
/// A `Match` forwards API to the `Output` generic parameter,
/// providing direct access to captures.
@dynamicMemberLookup
public struct Match {
let anyRegexOutput: AnyRegexOutput
/// The range of the overall match.
public let range: Range<String.Index>
}
}
@available(SwiftStdlib 5.7, *)
extension Regex.Match {
var input: String {
anyRegexOutput.input
}
/// The output produced from the match operation.
public var output: Output {
if Output.self == AnyRegexOutput.self {
return anyRegexOutput as! Output
}
let typeErasedMatch = anyRegexOutput.existentialOutput(
from: anyRegexOutput.input
)
return typeErasedMatch as! Output
}
/// Accesses a capture by its name or number.
public subscript<T>(dynamicMember keyPath: KeyPath<Output, T>) -> T {
// Note: We should be able to get the element offset from the key path
// itself even at compile time. We need a better way of doing this.
guard let outputTupleOffset = MemoryLayout.tupleElementIndex(
of: keyPath, elementTypes: anyRegexOutput.map(\.type)
) else {
return output[keyPath: keyPath]
}
return anyRegexOutput[outputTupleOffset].value as! T
}
/// Accesses a capture using the `.0` syntax, even when the match isn't a tuple.
@_disfavoredOverload
public subscript(
dynamicMember keyPath: KeyPath<(Output, _doNotUse: ()), Output>
) -> Output {
output
}
@_spi(RegexBuilder)
public subscript<Capture>(_ id: ReferenceID) -> Capture {
guard let element = anyRegexOutput.first(
where: { $0.representation.referenceID == id }
) else {
preconditionFailure("Reference did not capture any match in the regex")
}
return element.existentialOutputComponent(
from: input
) as! Capture
}
}
@available(SwiftStdlib 5.7, *)
extension Regex {
/// Matches a string in its entirety.
///
/// - Parameter s: The string to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func wholeMatch(in s: String) throws -> Regex<Output>.Match? {
try _match(s, in: s.startIndex..<s.endIndex, mode: .wholeString)
}
/// Matches part of a string, starting at its beginning.
///
/// - Parameter s: The string to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func prefixMatch(in s: String) throws -> Regex<Output>.Match? {
try _match(s, in: s.startIndex..<s.endIndex, mode: .partialFromFront)
}
/// Finds the first match in a string.
///
/// - Parameter s: The string to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func firstMatch(in s: String) throws -> Regex<Output>.Match? {
try _firstMatch(s, in: s.startIndex..<s.endIndex)
}
/// Matches a substring in its entirety.
///
/// - Parameter s: The substring to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func wholeMatch(in s: Substring) throws -> Regex<Output>.Match? {
try _match(s.base, in: s.startIndex..<s.endIndex, mode: .wholeString)
}
/// Matches part of a substring, starting at its beginning.
///
/// - Parameter s: The substring to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func prefixMatch(in s: Substring) throws -> Regex<Output>.Match? {
try _match(s.base, in: s.startIndex..<s.endIndex, mode: .partialFromFront)
}
/// Finds the first match in a substring.
///
/// - Parameter s: The substring to match this regular expression against.
/// - Returns: The match, or `nil` if no match was found.
public func firstMatch(in s: Substring) throws -> Regex<Output>.Match? {
try _firstMatch(s.base, in: s.startIndex..<s.endIndex)
}
func _match(
_ input: String,
in subjectBounds: Range<String.Index>,
mode: MatchMode = .wholeString
) throws -> Regex<Output>.Match? {
let executor = Executor(program: regex.program.loweredProgram)
return try executor.match(input, in: subjectBounds, mode)
}
func _firstMatch(
_ input: String,
in subjectBounds: Range<String.Index>
) throws -> Regex<Output>.Match? {
try _firstMatch(input, subjectBounds: subjectBounds, searchBounds: subjectBounds)
}
func _firstMatch(
_ input: String,
subjectBounds: Range<String.Index>,
searchBounds: Range<String.Index>
) throws -> Regex<Output>.Match? {
let executor = Executor(program: regex.program.loweredProgram)
let graphemeSemantic = regex.initialOptions.semanticLevel == .graphemeCluster
return try executor.firstMatch(
input,
subjectBounds: subjectBounds,
searchBounds: searchBounds,
graphemeSemantic: graphemeSemantic)
}
}
@available(SwiftStdlib 5.7, *)
extension BidirectionalCollection where SubSequence == Substring {
/// Checks for a match against the string in its entirety.
///
/// - Parameter r: The regular expression being matched.
/// - Returns: The match, or `nil` if no match was found.
public func wholeMatch<R: RegexComponent>(
of r: R
) -> Regex<R.RegexOutput>.Match? {
try? r.regex.wholeMatch(in: self[...])
}
/// Checks for a match against the string, starting at its beginning.
///
/// - Parameter r: The regular expression being matched.
/// - Returns: The match, or `nil` if no match was found.
public func prefixMatch<R: RegexComponent>(
of r: R
) -> Regex<R.RegexOutput>.Match? {
try? r.regex.prefixMatch(in: self[...])
}
}
@available(SwiftStdlib 5.7, *)
extension RegexComponent {
public static func ~=(regex: Self, input: String) -> Bool {
input.wholeMatch(of: regex) != nil
}
public static func ~=(regex: Self, input: Substring) -> Bool {
input.wholeMatch(of: regex) != nil
}
}
| 33.706806 | 85 | 0.66589 |
dec7052cc456274df7b15dc65d2f81d31a166eae | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( [ {
if true {
{
}
class A {
let a {
class
case ,
| 16.923077 | 87 | 0.709091 |
db852003348f3a2014443ae20860e51ff61ad418 | 511 | //
// AppDelegate.swift
// TypographizerDemo
//
// Created by Frank Rausch on 2017-03-15.
// Copyright © 2017 Frank Rausch. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 23.227273 | 71 | 0.72407 |
eff98fdebfb56b1da3861060b71049f9c597a5a1 | 640 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
class B<T where T: T>
struct c
typealias e = ")
typealias e : d = c<T, g = g<T.e = c<T.Element == B<T>
struct c<T.Element == "\() { }
class B<T, U, g = c
typealias e = c<T>(e : B
struct c<T: B<T where T where T.Element == c
class B<T where T where T where T>
class B<T.e = c<T where T>() { }
protocol A : A"\(e = [Void>
let a {
func b<T where T.B == 0
class B<e
protocol P {
func b<D> Void>() -> Void>() -> Void>
protocol A : NSObject {
typealias e = c
class B<T
| 25.6 | 87 | 0.634375 |
f7b85dd677cb92b245ecd9452b13eb51dba62368 | 1,517 | //
// ProfileViewController.swift
// LiveU
//
// Created by Eric Sharkey on 9/10/18.
// Copyright © 2018 Eric Sharkey. All rights reserved.
//
import UIKit
import CoreLocation
class ProfileViewController: UIViewController {
var currentUser: User!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
tabBarItem.image = #imageLiteral(resourceName: "ProfileIcon")
}
override func viewWillDisappear(_ animated: Bool) {
tabBarItem.image = #imageLiteral(resourceName: "ProfileIconSelected")
}
func setup(){
currentUser = UserDefaults.standard.currentUser(forKey: "currentUser")
if let user = currentUser{
if user.artist == "true"{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let artistPro = storyboard.instantiateViewController(withIdentifier: "artistProfile")
self.addChild(artistPro)
self.view.addSubview(artistPro.view)
} else if user.venue == "true"{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let venuePro = storyboard.instantiateViewController(withIdentifier: "venueProfile")
self.addChild(venuePro)
self.view.addSubview(venuePro.view)
}
}
}
}
| 29.745098 | 101 | 0.618985 |
331b30f67421ae3cca1c007ab0a7e9b927496933 | 1,282 | //
// DefaultContentShareController.swift
// AmazonChimeSDK
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
import AmazonChimeSDKMedia
import Foundation
@objcMembers public class DefaultContentShareController: NSObject, ContentShareController {
private let contentShareVideoClientController: ContentShareVideoClientController
public init(contentShareVideoClientController: ContentShareVideoClientController) {
self.contentShareVideoClientController = contentShareVideoClientController
super.init()
}
public func startContentShare(source: ContentShareSource) {
if let videoSource = source.videoSource {
contentShareVideoClientController.startVideoShare(source: videoSource)
}
}
public func stopContentShare() {
contentShareVideoClientController.stopVideoShare()
}
public func addContentShareObserver(observer: ContentShareObserver) {
contentShareVideoClientController.subscribeToVideoClientStateChange(observer: observer)
}
public func removeContentShareObserver(observer: ContentShareObserver) {
contentShareVideoClientController.unsubscribeFromVideoClientStateChange(observer: observer)
}
}
| 33.736842 | 99 | 0.778471 |
90c2ae6c8c67e663df4925364eddd950d06adf72 | 1,158 | // Copyright 2018-2019 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// HTTP1ServerResponseComponents.swift
// SmokeHTTP1
//
import Foundation
/// The parsed components that specify a request.
public struct HTTP1ServerResponseComponents {
/// any additional response headers.
public let additionalHeaders: [(String, String)]
/// The body data of the response.
public let body: (contentType: String, data: Data)?
public init(additionalHeaders: [(String, String)],
body: (contentType: String, data: Data)?) {
self.additionalHeaders = additionalHeaders
self.body = body
}
}
| 35.090909 | 79 | 0.710708 |
09f5f6f0c6efb0d8b83237466318352aec7e59af | 1,332 | //
// ResponseMock.swift
// stellarsdkTests
//
// Created by Rogobete Christian on 19.02.18.
// Copyright © 2018 Soneso. All rights reserved.
//
import Foundation
import stellarsdk
class ResponsesMock {
init() {
ServerMock.add(mock: requestMock())
}
deinit {
ServerMock.removeAll()
}
/// override this
func requestMock() -> RequestMock {
let handler: MockHandler = { [weak self] mock, request in
mock.statusCode = 404
return self?.resourceMissingResponse()
}
return RequestMock(host: "horizon-testnet.stellar.org",
path: "/path/${variable}",
httpMethod: "GET",
mockHandler: handler)
}
func resourceMissingResponse() -> String {
return """
{
"type": "https://stellar.org/horizon-errors/not_found",
"title": "Resource Missing",
"status": 404,
"detail": "The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our databas could be found with the parameters provided.",
"instance": "horizon-testnet-001/6VNfUsVQkZ-28076890"
}
"""
}
}
| 27.75 | 225 | 0.560811 |
e6cffc69349fefbd08be5ce5501c7a177e238a72 | 2,087 | //
// BaseTalkMessageWindowNodeChackCanTalk.swift
// DQ3
//
// Created by aship on 2021/04/22.
//
import SpriteKit
extension BaseTalkMessageWindowNode {
internal func initializeTalk() {
let headNode = DataManager.adventureLog.partyCharacterNodes.first!
// 1歩先にNPC がいるか判定
// いるなら、そのNPC の会話を始める
self.name = checkWhoToTalkTo(positionX: headNode.positionX,
positionY: headNode.positionY,
direction: headNode.direction)
if self.name == nil {
showDefaultTalkMessage()
return
}
// head の方を向きたい
for characterNpcNode in self.characterNpcNodes {
if characterNpcNode.name == self.name {
if characterNpcNode.dqCharacter == .none {
continue
}
let direction = headNode.direction
let reverseDirection = getReverseDirection(direction: direction)
// isPaused してる状態なので setTexture を行う
characterNpcNode.setTexture(direction: reverseDirection)
characterNpcNode.changeDirection(direction: reverseDirection)
}
}
}
private func checkWhoToTalkTo(positionX: Int,
positionY: Int,
direction: Direction) -> String? {
let headNode = DataManager.adventureLog.partyCharacterNodes.first!
let diffs = getDiffXY(direction: headNode.direction)
let diffX = diffs.0
let diffY = diffs.1
let newPositionX = headNode.positionX + diffX
let newPositionY = headNode.positionY + diffY
for characterNode in self.characterNpcNodes {
if characterNode.positionX == newPositionX &&
characterNode.positionY == newPositionY {
return characterNode.name!
}
}
return nil
}
}
| 31.621212 | 80 | 0.54528 |
09ea327af085505a1ce5dcbb7ee5c78db37a5d4e | 2,078 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "FioriSwiftUI",
defaultLocalization: "en",
platforms: [.iOS(.v13), .watchOS(.v6)],
products: [
.library(
name: "FioriSwiftUI",
type: .dynamic,
targets: ["FioriSwiftUI"]
),
.library(
name: "FioriCharts",
type: .dynamic,
targets: ["FioriCharts"]
),
.library(
name: "FioriIntegrationCards",
type: .dynamic,
targets: ["FioriIntegrationCards"]
)
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/Flight-School/AnyCodable.git", from: "0.2.3"),
.package(name: "ObservableArray", url: "https://github.com/sstadelman/observable-array.git", from: "1.2.0"),
.package(url: "https://github.com/marmelroy/Zip.git", from: "2.0.0")
],
targets: [
.target(
name: "FioriSwiftUI",
dependencies: ["FioriSwiftUICore", "FioriIntegrationCards"]
),
.target(
name: "FioriIntegrationCards",
dependencies: ["AnyCodable", "ObservableArray", "FioriCharts", "Zip", "FioriThemeManager"]
),
.target(
name: "FioriCharts",
dependencies: ["FioriThemeManager"],
exclude: ["TestCases/SF_EnergyBenchmarking.csv"]
),
.target(
name: "FioriSwiftUICore",
dependencies: ["FioriThemeManager", "FioriCharts"],
resources: [.process("FioriSwiftUICore.strings")]
),
.target(
name: "FioriThemeManager",
dependencies: [],
resources: [
.process("72-Fonts/Resources")
]
),
.testTarget(
name: "FioriSwiftUITests",
dependencies: ["FioriSwiftUI"]
)
]
)
| 31.969231 | 116 | 0.54283 |
67c725c8855a350a752107e6c142b494ed4d06e8 | 644 | import Foundation
import SwiftyJSON
@objcMembers final class Artist: NSObject, JSONAbleType {
let id: String
dynamic var name: String
let sortableID: String?
var blurb: String?
init(id: String, name: String, sortableID: String?) {
self.id = id
self.name = name
self.sortableID = sortableID
}
static func fromJSON(_ json:[String: Any]) -> Artist {
let json = JSON(json)
let id = json["id"].stringValue
let name = json["name"].stringValue
let sortableID = json["sortable_id"].string
return Artist(id: id, name:name, sortableID:sortableID)
}
}
| 23 | 63 | 0.627329 |
d9db58a9d241ac3df29e726e7fb26274f6572c2f | 151 | //
// Created by Rene Dohan on 9/23/19.
//
import Foundation
public extension URL {
init(_ url: String) {
self.init(string: url)!
}
} | 13.727273 | 36 | 0.596026 |
112110581de4da065ec2964a4215e2ace56caf33 | 446 | //
// FirebaseService.swift
// CloudService
//
// Created by hummer98 on 2019/09/03.
//
import UIKit
import FirebaseCore
open class FirebaseService: NSObject, UIApplicationDelegate {}
extension FirebaseService {
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
| 22.3 | 158 | 0.721973 |
fba9599d473718e6458f50e1eb3718c00173042f | 2,610 | //
// UICollectionView+RDAExtension.swift
// RXCDiffArrayExample
//
// Created by ruixingchen on 9/15/19.
// Copyright © 2019 ruixingchen. All rights reserved.
//
import UIKit
extension UICollectionView {
///根据一个二维的改变来更新数据
public func reload<Element>(with differences:[RDADifference<Element>], reloadDataSource:@escaping([Element])->Void, completion:((Bool)->Void)?) {
guard self.window != .none else {
if let data = differences.last?.dataAfterChange {
reloadDataSource(data)
}
self.reloadData()
completion?(true)
return
}
let group = DispatchGroup()
//由于DifferenceKit是分阶段进行的, 这里也必须要分阶段进行
for difference in differences {
let updateClosure:()->Void = {
if let data = difference.dataAfterChange {
reloadDataSource(data)
}
for change in difference.changes {
switch change {
case .sectionRemove(offset: let offset):
self.deleteSections(IndexSet(integer: offset))
case .sectionInsert(offset: let offset):
self.insertSections(IndexSet(integer: offset))
case .sectionUpdate(offset: let offset):
self.reloadSections(IndexSet(integer: offset))
case .sectionMove(fromOffset: let from, toOffset: let to):
self.moveSection(from, toSection: to)
case .elementRemove(offset: let row, section: let section):
self.deleteItems(at: [IndexPath(row: row, section: section)])
case .elementInsert(offset: let row, section: let section):
self.insertItems(at: [IndexPath(row: row, section: section)])
case .elementUpdate(offset: let row, section: let section):
self.reloadItems(at: [IndexPath(row: row, section: section)])
case .elementMove(fromOffset: let fromRow, fromSection: let fromSection, toOffset: let toRow, toSection: let toSection):
self.moveItem(at: IndexPath(row: fromRow, section: fromSection), to: IndexPath(row: toRow, section: toSection))
}
}
}
group.enter()
self.performBatchUpdates(updateClosure) { (_) in
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
completion?(true)
}
}
}
| 40.78125 | 149 | 0.553257 |
225727d26a3dc561b954b3de7ab30287c2e779d4 | 968 | //: Creational Pattern
/*
- Prototype
- Factory method
- Abstract factory
- Singleton
- Builder
*/
//: Prototype Pattern
/*
This pattern will help you create new object by duplicating and cloning capability.
*/
//: Implementation
class SmartPhonePrototype {
var name: String
var price: Int
var brand: String
init(name: String, price: Int, brand: String) {
self.name = name
self.price = price
self.brand = brand
}
func clone() -> SmartPhonePrototype {
return SmartPhonePrototype(name: self.name, price: self.price, brand: self.brand)
}
}
class SmartPhone: SmartPhonePrototype {
override init(name: String, price: Int, brand: String) {
super.init(name: name, price: price, brand: brand)
}
}
//: Usage
let iPhone6 = SmartPhone(name: "iPhone 6", price: 649, brand: "Apple")
let aaaiPhone6 = iPhone6.clone()
aaaiPhone6.name
aaaiPhone6.price
aaaiPhone6.brand
| 20.166667 | 89 | 0.653926 |
1a4e1aaa6741e8126e93e6543995ca0f717cc2da | 512 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
enum b{class b{struct a{struct B<S where f=A{class B<b{enum S{class A{}enum A{}struct A{enum S<T{{}struct B{var _=A<T b
| 51.2 | 119 | 0.738281 |
62b66bd666515f46e88af19de3ad03ca80250af3 | 2,317 | //
// URLSessionFactory.swift
// DownloadStack-Example
//
// Created by William Boles on 13/12/2019.
// Copyright © 2019 William Boles. All rights reserved.
//
import Foundation
protocol URLSessionFactoryType {
func defaultSession(delegate: URLSessionDelegate?, delegateQueue queue: OperationQueue?) -> URLSessionType
}
extension URLSessionFactoryType {
func defaultSession(delegate: URLSessionDelegate? = nil, delegateQueue queue: OperationQueue? = nil) -> URLSessionType {
return defaultSession(delegate: delegate, delegateQueue: queue)
}
}
protocol URLSessionType {
func downloadTask(with url: URL, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTaskType
func downloadTask(withResumeData resumeData: Data, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTaskType
}
extension URLSession: URLSessionType {
func downloadTask(with url: URL, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTaskType {
return downloadTask(with: url, completionHandler: completionHandler) as URLSessionDownloadTask
}
func downloadTask(withResumeData resumeData: Data, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTaskType {
return downloadTask(withResumeData: resumeData, completionHandler: completionHandler) as URLSessionDownloadTask
}
}
protocol URLSessionDownloadTaskType {
var progress: Progress { get }
func resume()
func cancel()
func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void)
}
extension URLSessionDownloadTask: URLSessionDownloadTaskType {}
class URLSessionFactory: URLSessionFactoryType {
// MARK: - Default
func defaultSession(delegate: URLSessionDelegate? = nil, delegateQueue queue: OperationQueue? = nil) -> URLSessionType {
let configuration = URLSessionConfiguration.default
//For demonstration purposes disable caching
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.urlCache = nil
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: queue)
return session
}
}
| 37.370968 | 153 | 0.738455 |
eb0c7ec2297910ae9f7e7a4792f629e7a5f403ce | 521 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// CalculateBaselineResponseProtocol is the response to a calcualte baseline call.
public protocol CalculateBaselineResponseProtocol : Codable {
var type: String { get set }
var timestamps: [Date]? { get set }
var baseline: [BaselineProtocol] { get set }
}
| 43.416667 | 96 | 0.737044 |
72eba729eea2dce2dfdce9643c5cfe3b5d3665ec | 1,583 | //
// ViewController.swift
// LimitDrag
//
// Created by Don Mag on 4/3/18.
// Copyright © 2018 DonMag. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var canvas: UIView!
@IBOutlet var textViewCenterXConstraint: NSLayoutConstraint!
@IBOutlet var textViewCenterYConstraint: NSLayoutConstraint!
var currentCenterXConstant: CGFloat = 0.0
var currentCenterYConstant: CGFloat = 0.0
@IBAction func handleDragOfCaption(_ sender: UIPanGestureRecognizer) {
guard let senderView = sender.view else { return }
guard let parentView = senderView.superview else { return }
// get the current pan movement - relative to the view (the text view, in this case)
let translation = sender.translation(in: canvas)
switch sender.state {
case .began:
// save the current Center X and Y constants
currentCenterXConstant = textViewCenterXConstraint.constant
currentCenterYConstant = textViewCenterYConstraint.constant
break
case .changed:
// update the Center X and Y constants
textViewCenterXConstraint.constant = currentCenterXConstant + translation.x
textViewCenterYConstraint.constant = currentCenterYConstant + translation.y
break
case .ended, .cancelled:
// update the Center X and Y constants based on the final position of the dragged view
textViewCenterXConstraint.constant = senderView.center.x - parentView.frame.size.width / 2.0
textViewCenterYConstraint.constant = senderView.center.y - parentView.frame.size.height / 2.0
break
default:
break
}
}
}
| 27.77193 | 96 | 0.74921 |
1c73611391fe505b4cc8641a15873709f99e47b7 | 2,127 | //
// Voice.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2018 Alejandro Alonso. All rights reserved.
//
// Voice namespace
public enum Voice {}
extension Voice {
public struct Region: Codable {
public let id: ID
public let isCustom: Bool
public let isDeprecated: Bool
public let isOptimal: Bool
public let isVip: Bool
public let name: String
enum CodingKeys: String, CodingKey {
case id
case isCustom = "custom"
case isDeprecated = "deprecated"
case isOptimal = "optimal"
case isVip = "vip"
case name
}
}
public struct State: Codable, _SwordChild {
public internal(set) weak var sword: Sword?
public let channelId: Snowflake?
public var guild: Guild? {
guard let guildId = guildId else {
return nil
}
return sword?.guilds[guildId]
}
public let guildId: Snowflake?
public let isDeafened: Bool
public let isMuted: Bool
public let isSelfDeafened: Bool
public let isSelfMuted: Bool
public let isSuppressed: Bool
public let sessionId: String
public let userId: Snowflake
enum CodingKeys: String, CodingKey {
case channelId = "channel_id"
case guildId = "guild_id"
case isDeafened = "deaf"
case isMuted = "mute"
case isSelfDeafened = "self_deaf"
case isSelfMuted = "self_mute"
case isSuppressed = "suppress"
case sessionId = "session_id"
case userId = "user_id"
}
}
}
extension Voice.Region {
public enum ID: String, Codable {
case amsterdam
case brazil
case euCentral = "eu-central"
case euWest = "eu-west"
case frankfurt
case hongkong
case japan
case london
case russia
case singapore
case sydney
case usCentral = "us-central"
case usEast = "us-east"
case usSouth = "us-south"
case usWest = "us-west"
case vipUSEast = "vip-us-east"
case vipUSWest = "vip-us-west"
case vipAmsterdam = "vip-amsterdam"
public var isVip: Bool {
return rawValue.hasPrefix("vip")
}
}
}
| 22.870968 | 59 | 0.632346 |
9c33f7d304ff9fcf145311a735594e2f6bd5d804 | 16,897 |
//
// ViewController.swift
// Neon-Ios
//
// Created by Akhilendra Singh on 1/16/19.
// Copyright © 2019 Girnar. All rights reserved.
//
import UIKit
import Photos
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//IBOutlets
@IBOutlet weak var tagListView: UITextView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var submitButton: UIButton!
//Reference Variables
private var locArr = [CLLocation]()
private var imagePicker = UIImagePickerController()
private let imageCache = NSCache<NSString, UIImage>()
private var finalDict = [[String : Any]]()
//Value type Variables
private var selctedIndex = 0
private var tags: String = "Mandatory Tags\n\n"
private let itemsPerRow: CGFloat = 2
private let sectionInsets = UIEdgeInsets(top: 50.0,
left: 20.0,
bottom: 50.0,
right: 20.0)
//MARK: - ViewLife cycle methods
var asset = [PHAsset]()
override func viewDidLoad() {
super.viewDidLoad()
// self.setupAllTheThings()
}
override func viewDidAppear(_ animated: Bool) {
print("asset and singlton count on display", self.asset.count,NeonImagesHandler.singleonInstance.imagesCollection.count )
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setupAllTheThings()
}
// MARK: - Private Class Instance methods
private func setupAllTheThings() {
imagePicker.delegate = self
self.addCustomObjectInArray()
self.setupCollectionView(isCollectionViewHidden: NeonImagesHandler.singleonInstance.imagesCollection.count <= 0)
}
private func addCustomObjectInArray() {
self.tagListView.text = NeonImagesHandler.singleonInstance.addCustomObjectInArray()
}
private func setupCollectionView(isCollectionViewHidden: Bool) {
DispatchQueue.main.async {
self.tagListView.isHidden = !isCollectionViewHidden
self.collectionView.isHidden = isCollectionViewHidden
self.submitButton.isHidden = isCollectionViewHidden
self.collectionView.reloadData()
}
}
private func checkAllValidationOnSubmitButtonAction(message: String, arrayTagModel: [ImageTagModel], isMendatory: Bool) -> Bool {
for tagModel in arrayTagModel {
let arr = NeonImagesHandler.singleonInstance.imagesCollection.filter {
$0.getFileTag()?.getTagName() == tagModel.getTagName()
}
if tagModel.getNumberOfPhotos() > arr.count {
var messageUpdate = message
if isMendatory {
messageUpdate = message + "\(tagModel.getTagName())"
}
if isMendatory == true {
self.showCommonAlert(title: "Message", message: messageUpdate)
return false
} else {
return true
}
}
}
return true
}
private func showCommonAlert(title: String, message: String) {
let ac = UIAlertController(title: "Message", message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
private func makeJsonToSendDataAfterAllChecks() {
//Fetch all mendatory tag
//check images are filled
let mendatoryArray = NeonImagesHandler.singleonInstance.imageTagArray.filter { $0.isMandatory() == true}
if mendatoryArray.count > 0 {
if !self.checkAllValidationOnSubmitButtonAction(message: "Set images for Mandatory ", arrayTagModel: mendatoryArray, isMendatory: true) {
return
}
}
//Fetch all non-mendatory tag
//check images are filled
let nonMendatoryArray = NeonImagesHandler.singleonInstance.imageTagArray.filter { $0.isMandatory() == false}
if nonMendatoryArray.count > 0 {
if !self.checkAllValidationOnSubmitButtonAction(message: "Please delete all the images without tag or give them tag.", arrayTagModel: nonMendatoryArray, isMendatory: false) {
return
}
}
//Fetch all non-tagged images
//check images are filled
let arr = NeonImagesHandler.singleonInstance.getImagesCollection().filter {
$0.getFileTag() == nil
}
if arr.count > 0 {
self.showCommonAlert(title: "Message", message: "Please delete all the images without tag.")
return
}
//When All requirements are done.
self.showCommonAlert(title: "Message", message: "Perfect")
}
@objc private func deletePicture(sender:UIButton) {
DispatchQueue.main.async {
let i : Int = Int(sender.tag)
self.asset.remove(at: i)
NeonImagesHandler.singleonInstance.imagesCollection.remove(at: i)
self.setupCollectionView(isCollectionViewHidden: NeonImagesHandler.singleonInstance.imagesCollection.count <= 0)
}
}
private func convertDateToString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let convertedDate = dateFormatter.string(from: date)
return convertedDate
}
//MARK: - IBAction methods
@IBAction func cameraButtonAction(_ sender: Any) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "CameraViewController") as! CameraViewController
viewController.delegate = self
self.navigationController?.pushViewController(viewController, animated: true)
}
@IBAction func openGalleryTap(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
let imagePicker = OpalImagePickerController()
imagePicker.imagePickerDelegate = self
imagePicker.maximumSelectionsAllowed = 0
imagePicker.selectedAsset = self.asset
//NeonImagesHandler.singleonInstance.getNumberOfPhotosCollected()
present(imagePicker, animated: true, completion: nil)
}
}
@IBAction func submitButtonAction(_ sender: Any) {
self.makeJsonToSendDataAfterAllChecks()
}
// MARK: - Segue methods
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "showImage"){
print("In segue")
let showImageController = segue.destination as! ShowImageViewController
showImageController.navigateIndex = self.selctedIndex
}
}
}
//MARK: - CollectionView
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! MyImageCell
let fileinfo = NeonImagesHandler.singleonInstance.imagesCollection[indexPath.row]
DispatchQueue.main.async {
if let filePath = fileinfo.getFilePath(), filePath != "" {
cell.imageView.isHidden = false
if let image = NeonImagesHandler.singleonInstance.imageLocalPathSaved.object(forKey: filePath as NSString) {
cell.imageView.image = image
} else {
DispatchQueue.main.async {
cell.imageView.image = UIImage(contentsOfFile: filePath)
NeonImagesHandler.singleonInstance.imageLocalPathSaved.setObject(cell.imageView.image!, forKey: filePath as NSString)
}
}
} else {
cell.imageView.isHidden = true
}
}
cell.deleteButton?.tag = indexPath.row
cell.deleteButton?.addTarget(self, action: #selector(deletePicture(sender:)), for: .touchUpInside)
guard let imageTageModel = fileinfo.getFileTag(), imageTageModel.getIsSelected() == true
else {
cell.tagName.text = "Select Tag"
return cell
}
cell.tagName.text = imageTageModel.getTagName()
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selctedIndex = indexPath.row
self.performSegue(withIdentifier: "showImage", sender: self)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("NeonImagesHandler.singleonInstance.imagesCollection.count ",NeonImagesHandler.singleonInstance.imagesCollection.count )
return NeonImagesHandler.singleonInstance.imagesCollection.count
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * (itemsPerRow) - 10
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: widthPerItem)
}
}
//MARK: - ImagePicker
extension ViewController: OpalImagePickerControllerDelegate {
func imagePicker(_ picker: OpalImagePickerController, didFinishPickingImages images: [UIImage]) {
presentedViewController?.dismiss(animated: true, completion: nil)
}
func imagePickerNumberOfExternalItems(_ picker: OpalImagePickerController) -> Int {
return 0
}
func imagePickerTitleForExternalItems(_ picker: OpalImagePickerController) -> String {
return NSLocalizedString("External", comment: "External (title for UISegmentedControl)")
}
// func imagePicker(_ picker: OpalImagePickerController, imageURLforExternalItemAtIndex index: Int) -> URL? {
// return URL(string: "https://placeimg.com/500/500/nature")
// }
func imagePicker(_ picker: OpalImagePickerController, didFinishPickingAssets assets: [PHAsset]) {
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.isSynchronous = false
//NeonImagesHandler.singleonInstance.imagesCollection.removeAll()
self.asset = assets
var imagesCollectionArray = [FileInfo]()
if assets.count > 0 {
for i in 0...assets.count-1 {
let asset = assets[i]
manager.requestImageData(for: asset, options: options,
resultHandler: { (imagedata, dataUTI, orientation, info) in
if let info = info {
if info.keys.contains(NSString(string: "PHImageFileURLKey")) {
if let filePath = info[NSString(string: "PHImageFileURLKey")] as? URL {
print(filePath)
let absoluteString = filePath.absoluteString
//FileInfo()
let fileInfo = FileInfo()
//Set File path
fileInfo.setFilePath(filePath: absoluteString.replacingOccurrences(of: "file:///", with: ""))
//Set File Name
fileInfo.setFileName(fileName: filePath.lastPathComponent)
//Set Source
fileInfo.setSource(source: SOURCE.PHONE_GALLERY)
//Set Date TIme
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
fileInfo.setDateTimeTaken(dateTimeTaken: self.convertDateToString(date: asset.creationDate!))
//Set Time Stamp
fileInfo.setTimestamp(timestamp: self.convertDateToString(date: asset.creationDate!))
//Set Latitude and Longitude
if let locationInfo = asset.location {
fileInfo.setLatitude(latitude: String(locationInfo.coordinate.latitude))
fileInfo.setLongitude(longitude: String(locationInfo.coordinate.longitude))
}
//Save FileInfo in array
// NeonImagesHandler.singleonInstance.imagesCollection.append(fileInfo)
let taggedImageObject = NeonImagesHandler.singleonInstance.imagesCollection.filter {
$0.getFilePath() == fileInfo.getFilePath()
}
if taggedImageObject.count > 0 {
imagesCollectionArray.append(taggedImageObject[0])
} else {
imagesCollectionArray.append(fileInfo)
}
// NeonImagesHandler.singleonInstance.imagesCollection = imagesCollectionArray
if i == assets.count - 1 {
NeonImagesHandler.singleonInstance.imagesCollection = imagesCollectionArray
DispatchQueue.main.async {
self.setupCollectionView(isCollectionViewHidden: NeonImagesHandler.singleonInstance.imagesCollection.count <= 0)
}
}
}
}
}
})
}
} else {
DispatchQueue.main.async {
NeonImagesHandler.singleonInstance.imagesCollection.removeAll()
self.setupCollectionView(isCollectionViewHidden: NeonImagesHandler.singleonInstance.imagesCollection.count <= 0)
}
}
}
}
extension ViewController: CameraViewControllerProtocol {
//Images are getting from camera.
func receiveFileInfoFromCameraAndSetupView(imageArray: [FileInfo]) {
self.setupCollectionView(isCollectionViewHidden: NeonImagesHandler.singleonInstance.imagesCollection.count <= 0)
}
func setImageLoc(location: [CLLocation]){
self.locArr = location
}
}
//MARK: - UIImage
extension UIImage {
func toString() -> String? {
let data: Data? = self.pngData()
return data?.base64EncodedString(options: .endLineWithLineFeed)
}
}
| 47.597183 | 189 | 0.544594 |
1efdbbd7c2d217c3f70ccd0070bc890d191bcab7 | 2,488 | import Foundation
extension Faker {
public class Generator {
// swiftlint:disable nesting
public struct Constants {
public static let uppercaseLetters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
public static let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
public static let numbers = Array("0123456789")
}
let parser: Parser
let dateFormatter: DateFormatter
public required init(parser: Parser) {
self.parser = parser
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
}
public func generate(_ key: String) -> String {
return parser.fetch(key)
}
// MARK: - Filling
public func numerify(_ string: String) -> String {
let count = UInt32(Constants.numbers.count)
return String(string.enumerated().map { (index, item) in
#if swift(>=4.2)
let numberIndex = index == 0 ? UInt32.random(in: 0..<(count - 1)) : UInt32.random(in: 0..<count)
#else
let numberIndex = index == 0 ? arc4random_uniform(count - 1) : arc4random_uniform(count)
#endif
let char = Constants.numbers[Int(numberIndex)]
return String(item) == "#" ? char : item
})
}
public func letterify(_ string: String) -> String {
return String(string.enumerated().map { _, item in
#if swift(>=4.2)
let char = Constants.uppercaseLetters.randomElement() ?? Character("")
#else
let count = UInt32(Constants.uppercaseLetters.count)
let char = Constants.uppercaseLetters[Int(arc4random_uniform(count))]
#endif
return String(item) == "?" ? char : item
})
}
public func bothify(_ string: String) -> String {
return letterify(numerify(string))
}
public func alphaNumerify(_ string: String) -> String {
return string.replacingOccurrences(of: "[^A-Za-z0-9_]",
with: "",
options: .regularExpression,
range: nil)
}
public func randomWordsFromKey(_ key: String) -> String {
var string = ""
var list = [String]()
if let wordsList = parser.fetchRaw(key) as? [[String]] {
for words in wordsList {
if let item = words.random() {
list.append(item)
}
}
string = list.joined(separator: " ")
}
return string
}
}
}
| 30.341463 | 104 | 0.586013 |
229a281b8e648aac5378ab2766e178d6c13a1c34 | 4,262 | import Foundation
import RxSwift
import RxRelay
import RxCocoa
class RestoreMnemonicViewModel {
private let service: RestoreMnemonicService
private let disposeBag = DisposeBag()
private let invalidRangesRelay = BehaviorRelay<[NSRange]>(value: [])
private let proceedRelay = PublishRelay<AccountType>()
private let showErrorRelay = PublishRelay<String>()
private let passphraseCautionRelay = BehaviorRelay<Caution?>(value: nil)
private let clearInputsRelay = PublishRelay<Void>()
private let regex = try! NSRegularExpression(pattern: "\\S+")
private var state = State(allItems: [], invalidItems: [])
init(service: RestoreMnemonicService) {
self.service = service
}
private func wordItems(text: String) -> [WordItem] {
let matches = regex.matches(in: text, range: NSRange(location: 0, length: text.count))
return matches.compactMap { match in
guard let range = Range(match.range, in: text) else {
return nil
}
let word = String(text[range]).lowercased()
return WordItem(word: word, range: match.range)
}
}
private func syncState(text: String) {
let allItems = wordItems(text: text)
let invalidItems = allItems.filter { item in
!service.doesWordExist(word: item.word)
}
state = State(allItems: allItems, invalidItems: invalidItems)
}
private func clearInputs() {
clearInputsRelay.accept(())
clearCautions()
service.passphrase = ""
}
private func clearCautions() {
if passphraseCautionRelay.value != nil {
passphraseCautionRelay.accept(nil)
}
}
func validatePassphrase(text: String?) -> Bool {
let validated = service.validate(text: text)
if !validated {
passphraseCautionRelay.accept(Caution(text: "create_wallet.error.forbidden_symbols".localized, type: .warning))
}
return validated
}
}
extension RestoreMnemonicViewModel {
var invalidRangesDriver: Driver<[NSRange]> {
invalidRangesRelay.asDriver()
}
var proceedSignal: Signal<AccountType> {
proceedRelay.asSignal()
}
var inputsVisibleDriver: Driver<Bool> {
service.passphraseEnabledObservable.asDriver(onErrorJustReturn: false)
}
var passphraseCautionDriver: Driver<Caution?> {
passphraseCautionRelay.asDriver()
}
var clearInputsSignal: Signal<Void> {
clearInputsRelay.asSignal()
}
func onChange(text: String, cursorOffset: Int) {
syncState(text: text)
let nonCursorInvalidItems = state.invalidItems.filter { item in
let hasCursor = cursorOffset >= item.range.lowerBound && cursorOffset <= item.range.upperBound
return !hasCursor || !service.doesWordPartiallyExist(word: item.word)
}
invalidRangesRelay.accept(nonCursorInvalidItems.map { $0.range })
}
func onTogglePassphrase(isOn: Bool) {
service.set(passphraseEnabled: isOn)
clearInputs()
}
func onChange(passphrase: String) {
service.passphrase = passphrase
clearCautions()
}
func onTapProceed() {
passphraseCautionRelay.accept(nil)
guard state.invalidItems.isEmpty else {
invalidRangesRelay.accept(state.invalidItems.map { $0.range })
return
}
do {
let accountType = try service.accountType(words: state.allItems.map { $0.word })
proceedRelay.accept(accountType)
} catch {
if case RestoreMnemonicService.RestoreError.emptyPassphrase = error {
passphraseCautionRelay.accept(Caution(text: "restore.error.empty_passphrase".localized, type: .error))
} else {
showErrorRelay.accept(error.convertedError.smartDescription)
}
}
}
var showErrorSignal: Signal<String> {
showErrorRelay.asSignal()
}
}
extension RestoreMnemonicViewModel {
private struct WordItem {
let word: String
let range: NSRange
}
private struct State {
let allItems: [WordItem]
let invalidItems: [WordItem]
}
}
| 27.675325 | 123 | 0.641483 |
9c4f1c4bf0794b5c8fad9ca8c3a24c1a807c1505 | 15,276 | //
// SettingsController.swift
// DXOSwift
//
// Created by ruixingchen on 23/10/2017.
// Copyright © 2017 ruixingchen. All rights reserved.
//
import UIKit
import Kingfisher
class SettingsController: RXTableViewController {
var sectionTitles:[String] = []
var rowTitles:[[String]] = []
var cachedImageSize:UInt?
var clearCacheCellIndexPath:IndexPath?
override func initFunction() {
super.initFunction()
self.title = LocalizedString.title_settings
sectionTitles.append(Define.section_common)
sectionTitles.append(Define.section_cache)
#if DEBUG || debug
sectionTitles.append(Define.section_debug)
#endif
for i in sectionTitles {
var rowTitle:[String] = []
switch i {
case Define.section_common:
rowTitle.append(Define.row_common_hd_image_in_database)
rowTitle.append(Define.row_common_mobile_review_language)
case Define.section_cache:
rowTitle.append(Define.row_cache_clear_cahce)
case Define.section_debug:
#if DEBUG || debug
rowTitle.append(Define.row_debug_ignore_cache)
rowTitle.append(Define.row_debug_log_request)
#endif
default:
break
}
rowTitles.append(rowTitle)
}
}
override func initTableView() -> UITableView {
return UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func firstViewDidAppear(_ animated: Bool) {
super.firstViewDidAppear(animated)
KingfisherManager.shared.cache.calculateDiskCacheSize {[weak self] (size) in
//async after one second, I want the user to notice the transition
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1)) {
log.verbose("image cache size: \(size)")
self?.cachedImageSize = size
if self?.clearCacheCellIndexPath == nil {
self?.tableView.reloadData()
}else{
self?.tableView.reloadRows(at: [self!.clearCacheCellIndexPath!], with: UITableViewRowAnimation.automatic)
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return rowTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowTitles.safeGet(at: section)?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let sectionTitle:String = sectionTitles.safeGet(at: section) else {
return nil
}
var localizedTitle:String?
switch sectionTitle {
case Define.section_common:
break
case Define.section_cache:
break
case Define.section_debug:
#if DEBUG || debug
localizedTitle = "DEBUG"
#else
break
#endif
default:
break
}
return localizedTitle
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let sectionTitle:String = sectionTitles.safeGet(at: section) else {
return nil
}
var localizedTitle:String?
switch sectionTitle {
case Define.section_common:
break
case Define.section_cache:
break
case Define.section_debug:
#if DEBUG || debug
localizedTitle = nil
#else
break
#endif
default:
break
}
return localizedTitle
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let sectionTitle:String = sectionTitles.safeGet(at: indexPath.section) else {
let cell = RXBlankTableViewCell(reuseIdentifier: nil)
#if DEBUG || debug
cell.infoLabel.text = "can not get section title"
#endif
return cell
}
guard let rowTitle:String = rowTitles.safeGet(at: indexPath.section)?.safeGet(at: indexPath.row) else {
let cell = RXBlankTableViewCell(reuseIdentifier: nil)
#if DEBUG || debug
cell.infoLabel.text = "can not get row title"
#endif
return cell
}
var titleText:String?
var detailText:String?
var accessoryType:UITableViewCellAccessoryType = UITableViewCellAccessoryType.disclosureIndicator
var accessoryView:UIView?
var selectionStyle:UITableViewCellSelectionStyle = UITableViewCellSelectionStyle.default
if sectionTitle == Define.section_common {
if rowTitle == Define.row_common_hd_image_in_database {
titleText = LocalizedString.settings_row_database_hd_image
let switcher:IndexPathSwitch = IndexPathSwitch()
switcher.addTarget(self, action: #selector(switchValueChanged(sender:)), for: UIControlEvents.valueChanged)
switcher.indexPath = indexPath
switcher.isOn = SettingsManager.databaseHDImage
accessoryView = switcher
selectionStyle = UITableViewCellSelectionStyle.none
}else if rowTitle == Define.row_common_mobile_review_language {
titleText = LocalizedString.settings_row_mobile_review_language
switch SettingsManager.mobilePreviewLanguage {
case 1:
detailText = LocalizedString.settings_row_mobile_review_language_follow_system
case 2:
detailText = LocalizedString.title_english
case 3:
detailText = LocalizedString.title_chinese
default:
break
}
accessoryType = .disclosureIndicator
}
}else if sectionTitle == Define.section_cache {
if rowTitle == Define.row_cache_clear_cahce {
clearCacheCellIndexPath = indexPath
titleText = LocalizedString.settings_row_clear_cache
if self.cachedImageSize == nil {
//show indicator
let indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
indicator.startAnimating()
accessoryView = indicator
}else {
//show detail text
if cachedImageSize! < 1024 {
detailText = LocalizedString.settings_no_cached_image
}else {
detailText = String.dataSizeAbstract(size: UInt64(cachedImageSize!), decimal: 2)
}
}
}
}else if sectionTitle == Define.section_debug {
#if DEBUG || debug
if rowTitle == Define.row_debug_ignore_cache {
titleText = "Ignore Cache"
let switcher:IndexPathSwitch = IndexPathSwitch()
switcher.addTarget(self, action: #selector(switchValueChanged(sender:)), for: UIControlEvents.valueChanged)
switcher.indexPath = indexPath
switcher.isOn = SettingsManager.debug_ignore_cache
accessoryView = switcher
selectionStyle = UITableViewCellSelectionStyle.none
}else if rowTitle == Define.row_debug_log_request {
titleText = "Log All Requests"
let switcher:IndexPathSwitch = IndexPathSwitch()
switcher.addTarget(self, action: #selector(switchValueChanged(sender:)), for: UIControlEvents.valueChanged)
switcher.indexPath = indexPath
switcher.isOn = SettingsManager.debug_log_request
accessoryView = switcher
selectionStyle = UITableViewCellSelectionStyle.none
}
#endif
}
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "normal_cell")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "normal_cell")
}
cell?.textLabel?.text = titleText
cell?.detailTextLabel?.text = detailText
if accessoryView == nil {
cell?.accessoryView = nil
cell?.accessoryType = accessoryType
}else {
cell?.accessoryView = accessoryView
}
cell?.selectionStyle = selectionStyle
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let sectionTitle:String = sectionTitles.safeGet(at: indexPath.section) else {
log.error("can not get section title, indexPath:\(indexPath), titles:\(sectionTitles.count)")
return
}
guard let rowTitle:String = rowTitles.safeGet(at: indexPath.section)?.safeGet(at: indexPath.row) else {
log.error("can not get row title, indexPath:\(indexPath), titles:\(rowTitles)")
return
}
if sectionTitle == Define.section_common {
if rowTitle == Define.row_common_mobile_review_language {
self.tableView(tableView, didSelectAlertRowAt: indexPath, sectionTitle: sectionTitle, rowTitle: rowTitle)
}
}else if sectionTitle == Define.section_cache {
if rowTitle == Define.row_cache_clear_cahce {
self.tableView(tableView, didSelectAlertRowAt: indexPath, sectionTitle: sectionTitle, rowTitle: rowTitle)
}
}else if sectionTitle == Define.section_debug {
}
}
func tableView(_ tableView: UITableView, didSelectAlertRowAt indexPath: IndexPath, sectionTitle:String, rowTitle:String) {
var actions:[UIAlertAction] = []
var title:String?
var message:String?
var style:UIAlertControllerStyle = UIAlertControllerStyle.alert
if sectionTitle == Define.section_common {
if rowTitle == Define.row_common_mobile_review_language {
let systemAction:UIAlertAction = UIAlertAction(title: LocalizedString.settings_row_mobile_review_language_follow_system, style: UIAlertActionStyle.default, handler: { (action) in
SettingsManager.mobilePreviewLanguage = 1
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
let englishAction:UIAlertAction = UIAlertAction(title: LocalizedString.title_english, style: UIAlertActionStyle.default, handler: { (action) in
SettingsManager.mobilePreviewLanguage = 2
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
let chineseAction:UIAlertAction = UIAlertAction(title: LocalizedString.title_chinese, style: UIAlertActionStyle.default, handler: { (action) in
SettingsManager.mobilePreviewLanguage = 3
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
actions.append(systemAction)
actions.append(englishAction)
actions.append(chineseAction)
title = nil
style = UIAlertControllerStyle.actionSheet
}
}else if sectionTitle == Define.section_cache {
if rowTitle == Define.row_cache_clear_cahce {
guard let size = cachedImageSize, size > 1024 else{
return
}
let confirmAction:UIAlertAction = UIAlertAction(title: LocalizedString.settings_confirm_clear_cache, style: UIAlertActionStyle.destructive, handler: {[weak self] (action) in
KingfisherManager.shared.cache.clearDiskCache(completion: {
DispatchQueue.main.async {
self?.cachedImageSize = 0
self?.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
})
})
actions.append(confirmAction)
title = nil
message = LocalizedString.settings_clear_cache_warning_message
style = UIAlertControllerStyle.actionSheet
}
}else if sectionTitle == Define.section_debug {
#if DEBUG || debug
#endif
}
if actions.isEmpty {
return
}
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
for i in actions {
alert.addAction(i)
}
alert.addAction(UIAlertAction(title: LocalizedString.title_cancel, style: UIAlertActionStyle.cancel, handler: nil))
let idiom:UIUserInterfaceIdiom = UIDevice.current.userInterfaceIdiom
if idiom == UIUserInterfaceIdiom.phone {
self.present(alert, animated: true, completion: nil)
}else if idiom == UIUserInterfaceIdiom.pad {
}
}
@objc func switchValueChanged(sender:IndexPathSwitch){
guard let indexPath:IndexPath = sender.indexPath else {
return
}
guard let sectionTitle:String = sectionTitles.safeGet(at: indexPath.section) else {
return
}
guard let rowTitle:String = rowTitles.safeGet(at: indexPath.section)?.safeGet(at: indexPath.row) else {
return
}
if sectionTitle == Define.section_common {
if rowTitle == Define.row_common_hd_image_in_database {
SettingsManager.databaseHDImage = sender.isOn
}
}else if sectionTitle == Define.section_debug {
#if DEBUG || debug
if rowTitle == Define.row_debug_ignore_cache {
SettingsManager.debug_ignore_cache = sender.isOn
}else if rowTitle == Define.row_debug_log_request {
SettingsManager.debug_log_request = sender.isOn
}
#endif
}
}
}
extension SettingsController {
struct Define {
static let section_common:String = "section_common"
static let row_common_hd_image_in_database:String = "row_common_database_hd_image"
static let row_common_mobile_review_language:String = "row_common_mobile_review_language"
static let section_cache:String = "section_cache"
static let row_cache_clear_cahce:String = "row_clear_cache"
static let section_debug:String = "section_debug"
static let row_debug_ignore_cache:String = "row_debug_ignore_cache"
static let row_debug_log_request:String = "row_debug_log_request"
}
}
| 41.737705 | 194 | 0.610107 |
6a2ce1de76006ea19ac83fd23fc733aab522396c | 322 | //
// ReusableView+Ext.swift
// BoilerPlate
//
// Created by Raul Marques de Oliveira on 10/05/18.
// Copyright © 2018 Raul Marques de Oliveira. All rights reserved.
//
import UIKit
extension ReusableView where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
| 18.941176 | 67 | 0.692547 |
7205e8cd26dc2acfbfc8dbff8067430db5c97656 | 1,728 | //
// Datasource.swift
// ReTwitter
//
// Created by Leonardo Domingues on 12/12/18.
// Copyright © 2018 Leonardo Domingues. All rights reserved.
//
import LBTAComponents
import TRON
import SwiftyJSON
extension Collection where Element == JSON {
func decode<T: JSONDecodable>() throws -> [T] {
return try map{ try T(json: $0) }
}
}
class HomeDatasource: Datasource, JSONDecodable {
var users: [User] = []
var tweets: [Tweet] = []
required init(json: JSON) throws {
super.init()
guard let usersResponse = json["users"].array, let tweetsResponse = json["tweets"].array else {
throw NSError(domain: "com.retwitter", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error while parsing JSON"])
}
self.users = try usersResponse.decode()
self.tweets = try tweetsResponse.decode()
}
override func numberOfItems(_ section: Int) -> Int {
return section == 0 ? users.count : tweets.count
}
override func numberOfSections() -> Int {
return 2 // users and tweets collections
}
override func item(_ indexPath: IndexPath) -> Any? {
switch indexPath.section {
case 0:
return users[indexPath.item]
case 1:
return tweets[indexPath.item]
default:
return []
}
}
override func cellClasses() -> [DatasourceCell.Type] {
return [UserCell.self, TweetCell.self]
}
override func headerClasses() -> [DatasourceCell.Type]? {
return [HeaderCell.self]
}
override func footerClasses() -> [DatasourceCell.Type]? {
return [FooterCell.self]
}
}
| 25.791045 | 126 | 0.597222 |
5da4eb7e2ce6b74c6e8d84864f213f4f26c18f6e | 1,377 | //
// CalculatorBrain.swift
// BMI Calculator
//
// Created by pamarori mac on 07/07/20.
// Copyright © 2020 Angela Yu. All rights reserved.
//
import UIKit
struct CalculatorBrain {
var bmi: BMI?
mutating func calculateBMI(height: Float, weight: Float) {
let bmiValue = weight / pow(height, 2)
if height == 0.0 {
bmi = BMI(value: 0.0, advice: "", color: #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1))
} else if bmiValue < 18.5 {
bmi = BMI(value: bmiValue, advice: "Underweight!", color: #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))
} else if bmiValue < 24.9 {
bmi = BMI(value: bmiValue, advice: "Fit!", color: #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1))
} else {
bmi = BMI(value: bmiValue, advice: "Overweight!", color: #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1))
}
}
func getBMIValue() -> String {
let bmi1 = String(format: "%.1f", bmi?.value ?? 0.0)
return bmi1
}
func getAdvice() -> String {
return bmi?.advice ?? "No Advice"
}
func getColor() -> UIColor {
return bmi?.color ?? UIColor.white
}
}
| 30.6 | 154 | 0.580247 |
ac49ffcb3bee53b8e1b1402f8b764179735a3796 | 1,384 | // RUN: %swift -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s4main5ValueVyAA7IntegerVGMf"
struct Value<First : Equatable> {
let first: First
}
struct Integer : Equatable {
let value: Int
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
func doit() {
consume( Value(first: Integer(value: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_CONFORMANCE:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_CONFORMANCE]], i8* undef, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, i32 }>* @"$s4main5ValueVMn" to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| 38.444444 | 367 | 0.648121 |
bf57a846e9ed1b26f73e9ca10ee3b01dcc7afa1a | 701 | //
// MyTableViewCell.swift
// SecondSprintApp
//
// Created by Svetlana Timofeeva on 12/11/2019.
// Copyright © 2019 jorge. All rights reserved.
//
import UIKit
class MyTableViewCell: UITableViewCell {
public static let reuseId = "dkjsf"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
textLabel!.center = self.contentView.center
textLabel!.textAlignment = .center
textLabel!.font = .systemFont(ofSize: 20)
textLabel!.numberOfLines = 0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 25.035714 | 79 | 0.673324 |
d94257d53b089f7a352003a0d19d5ae99b6343b8 | 2,628 | //
// iGolaIndexType.swift
// iGolaIndexSortView
//
// Created by guan_xiang on 2019/7/23.
// Copyright © 2019 iGola_iOS. All rights reserved.
//
import UIKit
struct iGolaIndexStyle{
/// 常量
private struct iGolaIndexStyleConst {
static let textColor = UIColor.init(red: 35/255.0, green: 135/255.0, blue: 135/255.0, alpha: 1)
static let selectedBgColor = UIColor.init(red: 54/255.0, green: 129/255.0, blue: 228/255.0, alpha: 1)
static let indicatorFrame = CGRect(x: -60, y: 0, width: 50, height: 50)
static let sectionHeight: CGFloat = 16.0
static let textFont: UIFont = UIFont.systemFont(ofSize: 14)
static let indicatorFont: UIFont = UIFont.boldSystemFont(ofSize: 18)
static let textMargin: CGFloat = 5.0
}
/// 排序字母行高, label.layer.cornerRadius = sectionHeight * 0.5
var sectionHeight: CGFloat = iGolaIndexStyleConst.sectionHeight
/// 排序字母上下间距
var margin: CGFloat = iGolaIndexStyleConst.textMargin
/// 字体
var textFont: UIFont = iGolaIndexStyleConst.textFont
/// 文字颜色
var textColor: UIColor = iGolaIndexStyleConst.textColor
/// 文字选中颜色
var selectedColor: UIColor = UIColor.white
/// 选中背景颜色
var selectedBgColor: UIColor = iGolaIndexStyleConst.selectedBgColor
/// 指示器frame
var indicatorFrame: CGRect = iGolaIndexStyleConst.indicatorFrame
/// 指示器背景色
var indicatorBgColor: UIColor = UIColor.lightGray
/// 指示器字体
var indicatorFont: UIFont = iGolaIndexStyleConst.indicatorFont
/// 指示器文字颜色
var indicatorTextColor: UIColor = UIColor.white
init(){}
init(sectionHeight: CGFloat = iGolaIndexStyleConst.sectionHeight,
textFont: UIFont = iGolaIndexStyleConst.textFont,
textColor: UIColor = iGolaIndexStyleConst.textColor,
selectedColor: UIColor = UIColor.white,
selectedBgColor: UIColor = iGolaIndexStyleConst.selectedBgColor,
indicatorFrame: CGRect = iGolaIndexStyleConst.indicatorFrame,
indicatorBgColor: UIColor = UIColor.lightGray,
indicatorFont: UIFont = iGolaIndexStyleConst.indicatorFont,
indicatorTextColor: UIColor = UIColor.white) {
self.sectionHeight = sectionHeight
self.textFont = textFont
self.textColor = textColor
self.selectedColor = selectedColor
self.selectedBgColor = selectedBgColor
self.indicatorFrame = indicatorFrame
self.indicatorBgColor = indicatorBgColor
self.indicatorFont = indicatorFont
self.indicatorTextColor = indicatorTextColor
}
}
| 34.578947 | 109 | 0.683029 |
6769c71e260632551cf2828f6565242aca60cd15 | 1,656 | //
// NewConversationVC.swift
// ConversationsApp
//
// Created by Ilia Kolomeitsev on 21.07.2021.
// Copyright © 2021 Twilio, Inc. All rights reserved.
//
import UIKit
class NewConversationVC: UIViewController {
@IBOutlet weak var convoInputView: ConvoInputView!
@IBOutlet weak var errorLabel: UILabel!
var conversationListViewModel: ConversationListViewModel!
override func viewDidLoad() {
super.viewDidLoad()
convoInputView.title = NSLocalizedString("Conversation name", comment: "Conversation name input title")
convoInputView.placeholder = NSLocalizedString("Conversation name", comment: "Conversation name placeholder")
errorLabel.text = nil
}
@IBAction func onCreateConversation(_ sender: Any) {
guard let conversationName = convoInputView.text, !conversationName.isEmpty else {
view.layoutIfNeeded()
errorLabel.text = NSLocalizedString("Add a conversation title to create a conversation.",
comment: "Conversation name is empty error")
convoInputView.inputState = .error
UIView.animate(withDuration: 0.2) {
self.view.layoutIfNeeded()
}
return
}
conversationListViewModel.createAndJoinConversation(friendlyName: conversationName) { error in
if let error = error {
self.errorLabel.text = error.localizedDescription
} else {
self.dismiss(animated: true)
}
}
}
@IBAction func onClose(_ sender: Any) {
dismiss(animated: true)
}
}
| 33.12 | 117 | 0.640097 |
ccd86557eba9806011feb66a1fbae30cef19a861 | 9,883 | //
// AddressTableViewController.swift
// restaurant
//
// Created by love on 6/23/19.
// Copyright © 2019 love. All rights reserved.
//
import UIKit
class AddressTableViewController: UITableViewController {
var preparationTime: Int?
var addresses: [Address] = []
var editButton: UIButton!
var proceedButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.setNavBarStyle()
self.tableView.allowsSelectionDuringEditing = true;
self.setBarButtons()
// 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.
NotificationCenter.default.addObserver(self, selector: #selector(self.updateUI), name: MenuService.addressesUpdatedNotification, object: nil)
self.updateUI()
}
@objc func updateUI() {
self.addresses = MenuService.shared.getAddresses()
let hasDefaultAddress = self.addresses.filter{
(address) -> Bool in
return address.isDefault
}
if self.addresses.count > 0 && hasDefaultAddress.count > 0 {
self.proceedButton.isEnabled = true
} else {
self.proceedButton.isEnabled = false
}
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.addresses.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddressIdentifier", for: indexPath)
let index = indexPath.row
let address = self.addresses[index]
cell.textLabel?.text = address.title
cell.detailTextLabel?.text = address.address
if address.isDefault {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
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: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let address = self.addresses[indexPath.row]
MenuService.shared.removeAddress(address)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: false)
let address = self.addresses[indexPath.row]
MenuService.shared.setDefaultAddress(for: address)
}
/*
// 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?) {
if segue.identifier == "OrderConfirmationSegue" {
let orderConfirmationViewController = segue.destination as! OrderConfirmationTableViewController
let order = MenuService.shared.getLatestOrder()!
let defaultAddress = self.addresses.filter{
(address) -> Bool in
return address.isDefault
}.first
MenuService.shared.setAddressForOrder(defaultAddress!)
orderConfirmationViewController.order = order
orderConfirmationViewController.preparationTime = self.preparationTime!
}
else if segue.identifier == "EditAddressSegue" {
let addressViewController = segue.destination as! ShipmentTableViewController
let index = self.tableView.indexPathForSelectedRow?.row
let address = self.addresses[index!]
addressViewController.address = address
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "EditAddressSegue" && !tableView.isEditing {
return false
}
return true
}
@IBAction func submitOrderButtonTapped(_ sender: Any) {
guard let order = MenuService.shared.getLatestOrder() else {
NotificationCenter.default.post(name: AlertService.infoAlertNotification, object: nil, userInfo: ["title": Messages.cartIsEmptyErrorTitle, "message": Messages.cartIsEmptyErrorMessage])
return
}
let orderTotalPrice = order.items.reduce(0.0) {
(result, item) -> Double in
return result + (item.menuItem?.price)!
}
let formattedOrderPrice = String(format: "$%.2f", orderTotalPrice)
let title = "Confirm Order"
let message = "You are about to submit your order with a total of \(formattedOrderPrice)"
let alert = AlertService.getAlertControllerWithAction(title: title, message: message, actionTitle: "Submit") { [weak self] in
self?.submitOrder()
}
present(alert, animated: true, completion: nil)
}
func submitOrder() {
guard let order = MenuService.shared.getLatestOrder() else {return}
let menuIDs = Array(order.items.map {($0.menuItem?.id)!})
MenuService.shared.sumitOrderWith(menuIDs: menuIDs) {
(min: Int?) in
if let preparationTime = min {
DispatchQueue.main.async {
self.preparationTime = preparationTime
self.performSegue(withIdentifier: "OrderConfirmationSegue", sender: self.tableView)
}
}
}
}
func setBarButtons() {
self.setRightBarButton()
self.setLeftBarButton()
}
func setRightBarButton() {
self.proceedButton = UIButton(type: .system)
self.proceedButton.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 18.0)!
self.proceedButton.setTitle("\u{f30b}", for: .normal)
self.proceedButton.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
self.proceedButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -10.0)
self.proceedButton.addTarget(self, action: #selector(self.submitOrderButtonTapped(_:)), for: .touchUpInside)
let addAddressButton = UIButton(type: .system)
addAddressButton.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 18.0)!
addAddressButton.setTitle("\u{f067}", for: .normal)
addAddressButton.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
addAddressButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -10.0)
addAddressButton.addTarget(self, action: #selector(self.addAddressButtonTapped(_:)), for: .touchUpInside)
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.proceedButton), UIBarButtonItem(customView: addAddressButton)]
}
func setLeftBarButton() {
let backButton = UIButton(type: .system)
backButton.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 18.0)!
backButton.setTitle("\u{f30a}", for: .normal)
backButton.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10.0, bottom: 0, right: 0)
backButton.addTarget(self, action: #selector(self.backButtonTapped(_:)), for: .touchUpInside)
self.editButton = UIButton(type: .system)
self.editButton.titleLabel?.font = UIFont(name: "Font Awesome 5 Free", size: 18.0)!
self.editButton.setTitle("\u{f044}", for: .normal)
self.editButton.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
self.editButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10.0, bottom: 0, right: 0)
self.editButton.addTarget(self, action: #selector(self.editButtonTapped(_:)), for: .touchUpInside)
navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton), UIBarButtonItem(customView: self.editButton)]
}
@IBAction func editButtonTapped(_ sender: UIBarButtonItem) {
self.tableView.setEditing(!self.tableView.isEditing, animated: true)
if self.tableView.isEditing {
self.editButton.setTitle("\u{f058}", for: .normal)
} else {
self.editButton.setTitle("\u{f044}", for: .normal)
}
}
@IBAction func addAddressButtonTapped(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "AddAddressSegue", sender: nil)
}
@IBAction func backButtonTapped(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
}
| 39.690763 | 196 | 0.647071 |
e55d5596e114a46bd5ffe8fc0e23970942f994be | 70,866 | //
// Session.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common
/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response
/// cache handling.
open class Session {
/// Shared singleton instance used by all `AF.request` APIs. Cannot be modified.
public static let `default` = Session()
/// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's
/// `delegate` handles `URLSessionDelegate` callbacks.
///
/// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will
/// break internal Alamofire logic that tracks those tasks.
///
public let session: URLSession
/// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction.
public let delegate: SessionDelegate
/// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue.
public let rootQueue: DispatchQueue
/// Value determining whether this instance automatically calls `resume()` on all created `Request`s.
public let startRequestsImmediately: Bool
/// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its
/// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile
/// and test before introducing an additional queue.
public let requestQueue: DispatchQueue
/// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this
/// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined
/// to be a bottleneck. Always profile and test before introducing an additional queue.
public let serializationQueue: DispatchQueue
/// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a
/// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value.
public let interceptor: RequestInterceptor?
/// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning.
public let serverTrustManager: ServerTrustManager?
/// `RedirectHandler` instance used to provide customization for request redirection.
public let redirectHandler: RedirectHandler?
/// `CachedResponseHandler` instance used to provide customization of cached response handling.
public let cachedResponseHandler: CachedResponseHandler?
/// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s.
public let eventMonitor: CompositeEventMonitor
/// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default.
public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()]
/// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them.
var requestTaskMap = RequestTaskMap()
/// `Set` of currently active `Request`s.
var activeRequests: Set<Request> = []
/// Completion events awaiting `URLSessionTaskMetrics`.
var waitingCompletions: [URLSessionTask: () -> Void] = [:]
/// Creates a `Session` from a `URLSession` and other parameters.
///
/// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and
/// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer.
///
/// - Parameters:
/// - session: Underlying `URLSession` for this instance.
/// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
/// interaction.
/// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
/// serial queue.
/// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
/// by default. If set to `false`, all `Request`s created must have `.resume()` called.
/// on them for them to start.
/// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
/// will use the `rootQueue` as its `target`. A separate queue can be used if it's
/// determined request creation is a bottleneck, but that should only be done after
/// careful testing and profiling. `nil` by default.
/// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
/// queue will use the `rootQueue` as its `target`. A separate queue can be used if
/// it's determined response serialization is a bottleneck, but that should only be
/// done after careful testing and profiling. `nil` by default.
/// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
/// by default.
/// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
/// by default.
/// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
/// default.
/// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
/// `nil` by default.
/// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
/// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
public init(session: URLSession,
delegate: SessionDelegate,
rootQueue: DispatchQueue,
startRequestsImmediately: Bool = true,
requestQueue: DispatchQueue? = nil,
serializationQueue: DispatchQueue? = nil,
interceptor: RequestInterceptor? = nil,
serverTrustManager: ServerTrustManager? = nil,
redirectHandler: RedirectHandler? = nil,
cachedResponseHandler: CachedResponseHandler? = nil,
eventMonitors: [EventMonitor] = []) {
precondition(session.configuration.identifier == nil,
"Alamofire does not support background URLSessionConfigurations.")
precondition(session.delegateQueue.underlyingQueue === rootQueue,
"Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.")
self.session = session
self.delegate = delegate
self.rootQueue = rootQueue
self.startRequestsImmediately = startRequestsImmediately
self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue)
self.interceptor = interceptor
self.serverTrustManager = serverTrustManager
self.redirectHandler = redirectHandler
self.cachedResponseHandler = cachedResponseHandler
eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
delegate.eventMonitor = eventMonitor
delegate.stateProvider = self
}
/// Creates a `Session` from a `URLSessionConfiguration`.
///
/// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its
/// `delegateQueue`, and is the recommended initializer for most uses.
///
/// - Parameters:
/// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes
/// to this value after being passed to this initializer will have no effect.
/// `URLSessionConfiguration.af.default` by default.
/// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
/// interaction. `SessionDelegate()` by default.
/// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
/// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default.
/// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
/// by default. If set to `false`, all `Request`s created must have `.resume()` called.
/// on them for them to start.
/// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
/// will use the `rootQueue` as its `target`. A separate queue can be used if it's
/// determined request creation is a bottleneck, but that should only be done after
/// careful testing and profiling. `nil` by default.
/// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
/// queue will use the `rootQueue` as its `target`. A separate queue can be used if
/// it's determined response serialization is a bottleneck, but that should only be
/// done after careful testing and profiling. `nil` by default.
/// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
/// by default.
/// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
/// by default.
/// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
/// default.
/// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
/// `nil` by default.
/// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
/// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
delegate: SessionDelegate = SessionDelegate(),
rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
startRequestsImmediately: Bool = true,
requestQueue: DispatchQueue? = nil,
serializationQueue: DispatchQueue? = nil,
interceptor: RequestInterceptor? = nil,
serverTrustManager: ServerTrustManager? = nil,
redirectHandler: RedirectHandler? = nil,
cachedResponseHandler: CachedResponseHandler? = nil,
eventMonitors: [EventMonitor] = []) {
precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.")
let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue")
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
self.init(session: session,
delegate: delegate,
rootQueue: rootQueue,
startRequestsImmediately: startRequestsImmediately,
requestQueue: requestQueue,
serializationQueue: serializationQueue,
interceptor: interceptor,
serverTrustManager: serverTrustManager,
redirectHandler: redirectHandler,
cachedResponseHandler: cachedResponseHandler,
eventMonitors: eventMonitors)
}
deinit {
finishRequestsForDeinit()
session.invalidateAndCancel()
}
// MARK: - All Requests API
/// Perform an action on all active `Request`s.
///
/// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and
/// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`,
/// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any
/// additional work should be performed on another queue.
///
/// - Parameters:
/// - action: Closure to perform with all `Request`s.
public func withAllRequests(perform action: @escaping (Set<Request>) -> Void) {
rootQueue.async {
action(self.activeRequests)
}
}
/// Cancel all active `Request`s, optionally calling a completion handler when complete.
///
/// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled
/// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to
/// completion when cancelled.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default.
/// - completion: Closure to be called when all `Request`s have been cancelled.
public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) {
withAllRequests { requests in
requests.forEach { $0.cancel() }
queue.async {
completion?()
}
}
}
// MARK: - DataRequest
/// Closure which provides a `URLRequest` for mutation.
public typealias RequestModifier = (inout URLRequest) throws -> Void
struct RequestConvertible: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let parameters: Parameters?
let encoding: ParameterEncoding
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return try encoding.encode(request, with: parameters)
}
}
/// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
/// default.
/// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
/// `URLEncoding.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
let convertible = RequestConvertible(url: convertible,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
requestModifier: requestModifier)
print("private host Alamofire")
return request(convertible, interceptor: interceptor)
}
struct RequestEncodableConvertible<Parameters: Encodable>: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let parameters: Parameters?
let encoder: ParameterEncoder
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return try parameters.map { try encoder.encode($0, into: request) } ?? request
}
}
/// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a
/// `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
/// `URLEncodedFormParameterEncoder.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return request(convertible, interceptor: interceptor)
}
/// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
let request = DataRequest(convertible: convertible,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self)
perform(request)
return request
}
// MARK: - DataStreamRequest
/// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the
/// `URLRequest`.
/// `URLEncodedFormParameterEncoder.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
/// the provided parameters. `nil` by default.
///
/// - Returns: The created `DataStream` request.
open func streamRequest<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataStreamRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return streamRequest(convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor)
}
/// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
/// the provided parameters. `nil` by default.
///
/// - Returns: The created `DataStream` request.
open func streamRequest(_ convertible: URLConvertible,
method: HTTPMethod = .get,
headers: HTTPHeaders? = nil,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataStreamRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: Optional<Empty>.none,
encoder: URLEncodedFormParameterEncoder.default,
headers: headers,
requestModifier: requestModifier)
return streamRequest(convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor)
}
/// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
///
/// - Returns: The created `DataStreamRequest`.
open func streamRequest(_ convertible: URLRequestConvertible,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
let request = DataStreamRequest(convertible: convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self)
perform(request)
return request
}
// MARK: - DownloadRequest
/// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
/// `Destination`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
/// default.
/// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
/// Defaults to `URLEncoding.default`.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let convertible = RequestConvertible(url: convertible,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
requestModifier: requestModifier)
return download(convertible, interceptor: interceptor, to: destination)
}
/// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
/// a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
/// Defaults to `URLEncodedFormParameterEncoder.default`.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return download(convertible, interceptor: interceptor, to: destination)
}
/// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(_ convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let request = DownloadRequest(downloadable: .request(convertible),
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self,
destination: destination ?? DownloadRequest.defaultDestination)
perform(request)
return request
}
/// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
/// well as a `RequestInterceptor`, and a `Destination`.
///
/// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
/// Alamofire. The file will not be deleted until the system purges the temporary files.
///
/// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1),
/// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
/// generation logic where the data is written incorrectly and will always fail to resume the download. For more
/// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
///
/// - Parameters:
/// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(resumingWith data: Data,
interceptor: RequestInterceptor? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let request = DownloadRequest(downloadable: .resumeData(data),
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self,
destination: destination ?? DownloadRequest.defaultDestination)
perform(request)
return request
}
// MARK: - UploadRequest
struct ParameterlessRequestConvertible: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return request
}
}
struct Upload: UploadConvertible {
let request: URLRequestConvertible
let uploadable: UploadableConvertible
func createUploadable() throws -> UploadRequest.Uploadable {
try uploadable.createUploadable()
}
func asURLRequest() throws -> URLRequest {
try request.asURLRequest()
}
}
// MARK: Data
/// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
///
/// - Parameters:
/// - data: The `Data` to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ data: Data,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
///
/// - Parameters:
/// - data: The `Data` to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ data: Data,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: File
/// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
/// components and `RequestInterceptor`.
///
/// - Parameters:
/// - fileURL: The `URL` of the file to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ fileURL: URL,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - fileURL: The `URL` of the file to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ fileURL: URL,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: InputStream
/// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - stream: The `InputStream` that provides the data to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ stream: InputStream,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - stream: The `InputStream` that provides the data to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ stream: InputStream,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: MultipartFormData
/// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
/// `URLRequest` components and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` building closure.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
/// provided parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: url,
method: method,
headers: headers,
requestModifier: requestModifier)
let formData = MultipartFormData(fileManager: fileManager)
multipartFormData(formData)
return upload(multipartFormData: formData,
with: convertible,
usingThreshold: encodingMemoryThreshold,
interceptor: interceptor,
fileManager: fileManager)
}
/// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
/// value, and a `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` building closure.
/// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
with request: URLRequestConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
let formData = MultipartFormData(fileManager: fileManager)
multipartFormData(formData)
return upload(multipartFormData: formData,
with: request,
usingThreshold: encodingMemoryThreshold,
interceptor: interceptor,
fileManager: fileManager)
}
/// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
/// and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` instance to upload.
/// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
/// provided parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: MultipartFormData,
to url: URLConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: url,
method: method,
headers: headers,
requestModifier: requestModifier)
let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
request: convertible,
multipartFormData: multipartFormData)
return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
/// value and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` instance to upload.
/// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: MultipartFormData,
with request: URLRequestConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
request: request,
multipartFormData: multipartFormData)
return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
}
// MARK: - Internal API
// MARK: Uploadable
func upload(_ uploadable: UploadRequest.Uploadable,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor?,
fileManager: FileManager) -> UploadRequest {
let uploadable = Upload(request: convertible, uploadable: uploadable)
return upload(uploadable, interceptor: interceptor, fileManager: fileManager)
}
func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest {
let request = UploadRequest(convertible: upload,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
fileManager: fileManager,
delegate: self)
perform(request)
return request
}
// MARK: Perform
/// Starts performing the provided `Request`.
///
/// - Parameter request: The `Request` to perform.
func perform(_ request: Request) {
rootQueue.async {
guard !request.isCancelled else { return }
self.activeRequests.insert(request)
self.requestQueue.async {
// Leaf types must come first, otherwise they will cast as their superclass.
switch request {
case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship.
case let r as DataRequest: self.performDataRequest(r)
case let r as DownloadRequest: self.performDownloadRequest(r)
case let r as DataStreamRequest: self.performDataStreamRequest(r)
default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))")
}
}
}
}
func performDataRequest(_ request: DataRequest) {
dispatchPrecondition(condition: .onQueue(requestQueue))
performSetupOperations(for: request, convertible: request.convertible)
}
func performDataStreamRequest(_ request: DataStreamRequest) {
dispatchPrecondition(condition: .onQueue(requestQueue))
performSetupOperations(for: request, convertible: request.convertible)
}
func performUploadRequest(_ request: UploadRequest) {
dispatchPrecondition(condition: .onQueue(requestQueue))
do {
let uploadable = try request.upload.createUploadable()
rootQueue.async { request.didCreateUploadable(uploadable) }
performSetupOperations(for: request, convertible: request.convertible)
} catch {
rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) }
}
}
func performDownloadRequest(_ request: DownloadRequest) {
dispatchPrecondition(condition: .onQueue(requestQueue))
switch request.downloadable {
case let .request(convertible):
performSetupOperations(for: request, convertible: convertible)
case let .resumeData(resumeData):
rootQueue.async { self.didReceiveResumeData(resumeData, for: request) }
}
}
func performSetupOperations(for request: Request, convertible: URLRequestConvertible) {
dispatchPrecondition(condition: .onQueue(requestQueue))
let initialRequest: URLRequest
do {
initialRequest = try convertible.asURLRequest()
try initialRequest.validate()
} catch {
rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) }
return
}
rootQueue.async { request.didCreateInitialURLRequest(initialRequest) }
guard !request.isCancelled else { return }
guard let adapter = adapter(for: request) else {
rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) }
return
}
adapter.adapt(initialRequest, for: self) { result in
do {
let adaptedRequest = try result.get()
try adaptedRequest.validate()
self.rootQueue.async {
request.didAdaptInitialRequest(initialRequest, to: adaptedRequest)
self.didCreateURLRequest(adaptedRequest, for: request)
}
} catch {
self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) }
}
}
}
// MARK: - Task Handling
func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
dispatchPrecondition(condition: .onQueue(rootQueue))
request.didCreateURLRequest(urlRequest)
guard !request.isCancelled else { return }
let task = request.task(for: urlRequest, using: session)
requestTaskMap[request] = task
request.didCreateTask(task)
updateStatesForTask(task, request: request)
}
func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
dispatchPrecondition(condition: .onQueue(rootQueue))
guard !request.isCancelled else { return }
let task = request.task(forResumeData: data, using: session)
requestTaskMap[request] = task
request.didCreateTask(task)
updateStatesForTask(task, request: request)
}
func updateStatesForTask(_ task: URLSessionTask, request: Request) {
dispatchPrecondition(condition: .onQueue(rootQueue))
request.withState { state in
switch state {
case .initialized, .finished:
// Do nothing.
break
case .resumed:
task.resume()
rootQueue.async { request.didResumeTask(task) }
case .suspended:
task.suspend()
rootQueue.async { request.didSuspendTask(task) }
case .cancelled:
// Resume to ensure metrics are gathered.
task.resume()
task.cancel()
rootQueue.async { request.didCancelTask(task) }
}
}
}
// MARK: - Adapters and Retriers
func adapter(for request: Request) -> RequestAdapter? {
if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
} else {
return request.interceptor ?? interceptor
}
}
func retrier(for request: Request) -> RequestRetrier? {
if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
} else {
return request.interceptor ?? interceptor
}
}
// MARK: - Invalidation
func finishRequestsForDeinit() {
requestTaskMap.requests.forEach { request in
rootQueue.async {
request.finish(error: AFError.sessionDeinitialized)
}
}
}
}
// MARK: - RequestDelegate
extension Session: RequestDelegate {
public var sessionConfiguration: URLSessionConfiguration {
session.configuration
}
public var startImmediately: Bool { startRequestsImmediately }
public func cleanup(after request: Request) {
activeRequests.remove(request)
}
public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) {
guard let retrier = retrier(for: request) else {
rootQueue.async { completion(.doNotRetry) }
return
}
retrier.retry(request, for: self, dueTo: error) { retryResult in
self.rootQueue.async {
guard let retryResultError = retryResult.error else { completion(retryResult); return }
let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
completion(.doNotRetryWithError(retryError))
}
}
}
public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
rootQueue.async {
let retry: () -> Void = {
guard !request.isCancelled else { return }
request.prepareForRetry()
self.perform(request)
}
if let retryDelay = timeDelay {
self.rootQueue.after(retryDelay) { retry() }
} else {
retry()
}
}
}
}
// MARK: - SessionStateProvider
extension Session: SessionStateProvider {
func request(for task: URLSessionTask) -> Request? {
dispatchPrecondition(condition: .onQueue(rootQueue))
return requestTaskMap[task]
}
func didGatherMetricsForTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(rootQueue))
let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
if didDisassociate {
waitingCompletions[task]?()
waitingCompletions[task] = nil
}
}
func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) {
dispatchPrecondition(condition: .onQueue(rootQueue))
let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
if didDisassociate {
completion()
} else {
waitingCompletions[task] = completion
}
}
func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
dispatchPrecondition(condition: .onQueue(rootQueue))
return requestTaskMap[task]?.credential ??
session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
}
func cancelRequestsForSessionInvalidation(with error: Error?) {
dispatchPrecondition(condition: .onQueue(rootQueue))
requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
}
}
| 56.602236 | 154 | 0.594756 |
1c8c8c29b50a15feaead5bb466dc08b4d3c8eaa8 | 862 | //: Playground - noun: a place where people can play
import UIKit
// HelloWorld
var str:String = "Hello, playground"
str + "s"
let c:Character = "t"
str.append(c)
str.appendContentsOf("sdfasdfas")
str
let str2:String = "hello"
str2 + "s"
str2
// Dictionary
var dic:Dictionary<String, String> = ["s":"1", "r":"2"]
for (key, value) in dic {
print("key:\(key), value:\(value)")
}
// Array
var array:Array<String> = ["s", "t", "u"]
var num = 1
for i in 0..<array.count {
print("value:\(array[i])")
num++
}
for i in 0...100 {
num++
}
// Tuple
var tuple = (404, "Not Found")
tuple.0
tuple.1
var tuple2 = (s1:"value", s2:"hello")
tuple2.s1
// Optional
var opStr:String? = "Hello"
print("this is \(opStr)")
var count:Int? = 99
var i:Int = count!
if let validCount = count {
validCount
} else {
count
}
| 10.775 | 55 | 0.589327 |
230e852b5f242b7779debb6a5760534d8e781cfd | 486 | //
// ViewController.swift
// RickAndMortyFlexx
//
// Created by Даниил on 16.03.2021.
//
import UIKit
class ViewController: UIViewController {
let apiClient = APIClient()
override func viewDidLoad() {
super.viewDidLoad()
apiClient.getAllCharacters() { result in
switch result {
case .success(let models):
models.forEach { (model) in
print(model.id)
}
case .failure(let error):
print(error)
}
}
}
}
| 16.2 | 44 | 0.602881 |
abdf3274c6b1e8ea0eaa5f96eb484314a27034e2 | 7,490 | //
// String+extTests.swift
// Quelbo
//
// Created by Chris Sessions on 3/9/22.
//
import CustomDump
import XCTest
@testable import quelbo
final class StringExtTests: QuelboTests {
func testConvertToMultiline() {
XCTAssertEqual(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
""".convertToMultiline(),
#"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed \
do eiusmod tempor incididunt ut labore et dolore magna \
aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
ullamco laboris nisi ut aliquip ex ea commodo consequat. \
Duis aute irure dolor in reprehenderit in voluptate velit \
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
occaecat cupidatat non proident, sunt in culpa qui officia \
deserunt mollit anim id est laborum.
"""#
)
}
func testConvertToMultilineShortString() {
XCTAssertEqual("hello".convertToMultiline(), "hello")
}
func testConvertToMultilineAlreadyMultiline() {
XCTAssertEqual(
"""
I'm already
multiline!
""".convertToMultiline(),
"""
I'm already
multiline!
"""
)
}
func testConvertToMultilineCustomLimit() {
XCTAssertEqual(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""".convertToMultiline(limit: 20),
#"""
Lorem ipsum dolor \
sit amet, \
consectetur \
adipiscing elit, sed \
do eiusmod tempor \
incididunt ut labore \
et dolore magna \
aliqua.
"""#
)
}
func testConvertToMultilineHandleTooLongWord() {
XCTAssertEqual(
"""
Lorem ipsum dolor sit amet, LoremIpsumDolorSitAmetConsecteturAdipiscingElit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""".convertToMultiline(limit: 20),
#"""
Lorem ipsum dolor \
sit amet, \
LoremIpsumDolorSitAmetConsecteturAdipiscingElit, \
sed do eiusmod \
tempor incididunt ut \
labore et dolore \
magna aliqua.
"""#
)
}
func testIndented() {
XCTAssertEqual("hello".indented, " hello")
XCTAssertEqual(
"""
Hello
world
""".indented,
"""
Hello
world
"""
)
}
func testLowerCamelCase() {
XCTAssertEqual("OPEN-CLOSE".lowerCamelCase, "openClose")
XCTAssertEqual("GRANITE-WALL-F".lowerCamelCase, "graniteWallFunc")
XCTAssertEqual("EQUAL?".lowerCamelCase, "isEqual")
}
func testQuoted() {
let string = " A secret path leads southwest into the forest."
XCTAssertEqual(
string.quoted,
#"""
" A secret path leads southwest into the forest."
"""#
)
}
func testQuotedMultiline() {
let string = """
"WELCOME TO ZORK!
ZORK is a game of adventure, danger, and low cunning. In it you \
will explore some of the most amazing territory ever seen by mortals. \
No computer should be without one!"
"""
XCTAssertNoDifference(
string.quoted,
#"""
"""
"WELCOME TO ZORK!
ZORK is a game of adventure, danger, and low cunning. In it \
you will explore some of the most amazing territory ever \
seen by mortals. No computer should be without one!"
"""
"""#
)
}
func testTranslateMultiline() {
let string = """
You are outside a large gateway, on which is inscribed||
Abandon every hope
all ye who enter here!||
The gate is open; through it you can see a desolation, with a pile of
mangled bodies in one corner. Thousands of voices, lamenting some
hideous fate, can be heard.
"""
XCTAssertNoDifference(string.translateMultiline, """
You are outside a large gateway, on which is inscribed
Abandon every hope all ye who enter here!
The gate is open; through it you can see a desolation, with \
a pile of mangled bodies in one corner. Thousands of voices, \
lamenting some hideous fate, can be heard.
"""
)
}
func testTranslateMultilineNestedQuotes() {
let string = """
!!!!FROBOZZ MAGIC BOAT COMPANY!!!!|
|
Hello, Sailor!|
|
Instructions for use:|
|
To get into a body of water, say \"Launch\".|
To get to shore, say \"Land\" or the direction in which you want
to maneuver the boat.|
|
Warranty:|
|
This boat is guaranteed against all defects for a period of 76
milliseconds from date of purchase or until first used, whichever comes first.|
|
Warning:|
This boat is made of thin plastic.|
Good Luck!
"""
XCTAssertNoDifference(string.translateMultiline, """
!!!!FROBOZZ MAGIC BOAT COMPANY!!!!
Hello, Sailor!
Instructions for use:
To get into a body of water, say "Launch".
To get to shore, say "Land" or the direction in which you want \
to maneuver the boat.
Warranty:
This boat is guaranteed against all defects for a period of \
76 milliseconds from date of purchase or until first used, \
whichever comes first.
Warning:
This boat is made of thin plastic.
Good Luck!
"""
)
}
func testTranslateMultilineQuoted() {
let string = """
Cloak of Darkness|
A basic IF demonstration.|
Original game by Roger Firth|
ZIL conversion by Jesse McGrew, Jayson Smith, and Josh Lawrence
"""
XCTAssertNoDifference(string.translateMultiline.quoted, #"""
"""
Cloak of Darkness
A basic IF demonstration.
Original game by Roger Firth
ZIL conversion by Jesse McGrew, Jayson Smith, and Josh \
Lawrence
"""
"""#
)
}
func testUpperCamelCase() {
XCTAssertEqual("OPEN-CLOSE".upperCamelCase, "OpenClose")
XCTAssertEqual("GRANITE-WALL-F".upperCamelCase, "GraniteWallFunc")
XCTAssertEqual("EQUAL?".upperCamelCase, "IsEqual")
}
}
| 32.145923 | 457 | 0.554206 |
09b48eb79eb8e8f8c98523c4cebb58b7feef082a | 271 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A{class A:a}class a{protocol a{enum S<T where H:c
| 38.714286 | 87 | 0.752768 |
38991e5d98bbd39d333ee1093d7d61cd70fd3da0 | 437 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{func b<T :T.a{
{
n}if{{enum b{func a{
| 36.416667 | 79 | 0.736842 |
f7992cc9d4693818e939bcf2ced511b5ee0689c8 | 449 | //
// Tree.swift
// Tree
//
// Created by Henry on 2019/06/21.
// Copyright © 2019 Eonil. All rights reserved.
//
import Foundation
public struct Tree<Value>: MutableTreeProtocol {
public typealias Index = TreeIndex<Tree>
public typealias Path = TreePath<Array<Tree>.Index>
public typealias Subtree = Tree
public var value: Value
public init(_ v: Value) {
value = v
}
public var subtrees = Array<Tree>()
}
| 20.409091 | 55 | 0.659243 |
e5265ad7613380d68fedf1934fc72833447f8670 | 1,174 | // Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio
import SwiftUI
struct StateWithTextField: View {
@State var name = "Mariana"
var body: some View {
VStack(spacing: 20) {
HeaderView("State", subtitle: "Two-way Binding", desc: "Add a dollar sign ($) before the variable name to create a two-way binding between a control and a state variable.", back: .blue, textColor: .white)
Spacer()
TextField("Enter name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
Text("Name:")
Text("\(name)")
.font(.largeTitle)
.fontWeight(.black)
Spacer()
DescView("A two-way binding means when the state variable is updated, the control gets updated. And when the control updates the value, the state variable gets updated.", back: .blue, textColor: .white)
}
.font(.title)
}
}
struct StateWithTextField_Previews: PreviewProvider {
static var previews: some View {
StateWithTextField()
}
}
| 34.529412 | 216 | 0.591141 |
56db716a1bfe34a9910214f2c2b666067dd00827 | 5,224 | //
// MasterViewModel.swift
// Whitelabel
//
// Created by Martin Eberl on 27.02.17.
// Copyright © 2017 Martin Eberl. All rights reserved.
//
import Foundation
import AlamofireObjectMapper
import CoreLocation
import ObjectMapper
class MasterViewModel: MasterViewModelProtocol {
internal func load() {}
private let loader: ContentLoader?
fileprivate let locationProvider: LocationProvider?
let title = "Master"
private(set) var content: [Time]?
private(set) var sections: [Section]?
private(set) var isLoading: Bool = false
private var timer: Timer?
private let timeStore: TimeStore
weak var delegate: MasterViewModelDelegate?
init(loader: ContentLoader? = nil, locationProvider: LocationProvider? = nil, timeStore: TimeStore) {
self.loader = loader
self.locationProvider = locationProvider
self.timeStore = timeStore
content = timeStore.models()?.value
timeStore.models()?.onValueChanged {[weak self] (models: [Time]) in
self?.content = models
self?.delegate?.signalUpdate()
}
setupContent()
if LocationProvider.authorizationStatus == .authorizedWhenInUse {
locationProvider?.delegate = self
}
}
init(content: [Any], timeStore: TimeStore) {
self.content = nil
self.loader = nil
self.locationProvider = nil
self.timeStore = timeStore
}
// func load() {
// guard let loader = loader else { return }
//
// locationProvider?.startLocationUpdate()
//
// isLoading = true
// delegate?.signalUpdate()
//
// loader.load(contentResponse: {[weak self] response in
// self?.isLoading = false
// switch response {
// case .success(let content):
// self?.content = content
// self?.setupContent()
// break
// case .fail(let error):
// self?.content = nil
// self?.setupContent()
// break
// }
// self?.delegate?.signalUpdate()
// })
// }
var numberOfItems: Int? {
guard let sections = sections else {
return nil
}
return sections.count
}
func nuberOfCellItems(at index: Int) -> Int {
guard let section = section(at: index) else {
return 0
}
return section.content?.count ?? 0
}
func sectionViewModel(at index: Int) -> OverviewHeaderView.ViewModel? {
guard
let section = section(at: index),
let title = section.title else {
return nil
}
return OverviewHeaderView.ViewModel(title: title, buttonTitle: section.action)
}
func numberOfCells(at index: Int) -> Int? {
guard let section = section(at: index) else {
return nil
}
return section.content?.count
}
func cellViewModel(at indexPath: IndexPath) -> ViewCell.ViewModel? {
guard let section = section(at: indexPath.section),
let contents = section.content,
contents.indices.contains(indexPath.row) else {
return nil
}
let content = contents[indexPath.row]
return ViewCell.ViewModel(
imageUrl: nil,
title: "",
description: "",
distance: nil)
}
func did(change searchText: String) {
//TODO: filter text by search text
delegate?.signalUpdate()
}
func didCloseSearch() {
setupContent()
delegate?.signalUpdate()
}
func add() {
guard let time: Time = timeStore.new() else {
return
}
time.value = NSDate()
timeStore.add(model: time)
}
//MARK: - Private Methods
private func section(at index: Int) -> Section? {
guard let sections = sections,
sections.indices.contains(index) else {
return nil
}
return sections[index]
}
private func setupContent() {
sections = [
Section(title: "Section 1", action: "Show more", content: timeStore.models()?.value)
]
}
private func stopLocationUpdates() {
locationProvider?.endLocationUpdate()
}
fileprivate func stopLocationUpdates(after seconds: TimeInterval) {
guard timer == nil else {
return
}
timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: {[weak self] _ in
self?.timer = nil
self?.stopLocationUpdates()
})
}
}
extension MasterViewModel: OverviewHeaderViewDelegate {
func didPressButton(overview: OverviewHeaderView) {
}
}
extension MasterViewModel: LocationProviderDelegate {
func didUpdate(authorizationStatus: CLAuthorizationStatus) {}
func didUpdate(location: CLLocation) {
delegate?.signalUpdate()
stopLocationUpdates(after: 10)
}
}
| 27.350785 | 105 | 0.566041 |
fb211f077af5c268a272b5ee564fb9d65d8e979d | 1,080 | //
// Alert.swift
// AlertBuilder
//
// Created by Bradley Hilton on 2/23/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
public struct Alert : AlertBuilder {
public var configuration = AlertControllerConfiguration()
public init(title: String? = nil, message: String? = nil, cancelable: Bool = true) {
initialize(title: title, message: message, style: .alert, cancelable: cancelable)
}
public func textField(_ placeholder: String, configure: TextFieldConfiguration? = nil) -> Alert {
return modify { (config: inout AlertControllerConfiguration) in
config.textFields.append((placeholder, TextField(configuration: configure)))
}
}
public func observeTextField(_ placeholder: String, observer: @escaping TextFieldHandler) -> Alert {
return modify { (config: inout AlertControllerConfiguration) in
if let (_, textField) = config.textFields.find(predicate: { $0.0 == placeholder }) {
textField.observer = observer
}
}
}
}
| 33.75 | 104 | 0.649074 |
79fc06305365b0a6efc4df9994fa15131dc8d81e | 599 | //
// BaseSafariViewController.swift
// Potatso
//
// Created by LEI on 12/30/15.
// Copyright © 2015 TouchingApp. All rights reserved.
//
import Foundation
import SafariServices
class BaseSafariViewController: SFSafariViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action:nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barStyle = .default
}
}
| 23.96 | 109 | 0.694491 |
23fe4f7dc242e5375ccd7d577aa73010449e2430 | 4,236 | import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class DatabaseQueueTests: GRDBTestCase {
// Until SPM tests can load resources, disable this test for SPM.
#if !SWIFT_PACKAGE
func testInvalidFileFormat() throws {
do {
let testBundle = Bundle(for: type(of: self))
let url = testBundle.url(forResource: "Betty", withExtension: "jpeg")!
guard (try? Data(contentsOf: url)) != nil else {
XCTFail("Missing file")
return
}
_ = try DatabaseQueue(path: url.path)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssert([
"file is encrypted or is not a database",
"file is not a database"].contains(error.message!))
XCTAssertTrue(error.sql == nil)
XCTAssert([
"SQLite error 26: file is encrypted or is not a database",
"SQLite error 26: file is not a database"].contains(error.description))
}
}
#endif
func testAddRemoveFunction() throws {
// Adding a function and then removing it should succeed
let dbQueue = try makeDatabaseQueue()
let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
guard let int = Int.fromDatabaseValue(dbValues[0]) else {
return nil
}
return int + 1
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT succ(1)"), 2) // 2
}
dbQueue.remove(function: fn)
do {
try dbQueue.inDatabase { db in
try db.execute("SELECT succ(1)")
XCTFail("Expected Error")
}
XCTFail("Expected Error")
}
catch let error as DatabaseError {
// expected error
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!.lowercased(), "no such function: succ") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.sql!, "SELECT succ(1)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 1 with statement `select succ(1)`: no such function: succ")
}
}
func testAddRemoveCollation() throws {
// Adding a collation and then removing it should succeed
let dbQueue = try makeDatabaseQueue()
let collation = DatabaseCollation("test_collation_foo") { (string1, string2) in
return (string1 as NSString).localizedStandardCompare(string2)
}
dbQueue.add(collation: collation)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE files (name TEXT COLLATE TEST_COLLATION_FOO)")
}
dbQueue.remove(collation: collation)
do {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE files_fail (name TEXT COLLATE TEST_COLLATION_FOO)")
XCTFail("Expected Error")
}
XCTFail("Expected Error")
}
catch let error as DatabaseError {
// expected error
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!.lowercased(), "no such collation sequence: test_collation_foo") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.sql!, "CREATE TABLE files_fail (name TEXT COLLATE TEST_COLLATION_FOO)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 1 with statement `create table files_fail (name text collate test_collation_foo)`: no such collation sequence: test_collation_foo")
}
}
func testAllowsUnsafeTransactions() throws {
dbConfiguration.allowsUnsafeTransactions = true
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.beginTransaction()
}
try dbQueue.inDatabase { db in
try db.commit()
}
}
}
| 39.588785 | 204 | 0.604344 |
0e7a826b0a2c301ae171b7e9884499db1f4e8ffd | 698 | // 1260. Shift 2D Grid
// https://leetcode.com/problems/shift-2d-grid/
// Runtime: 192 ms, faster than 100.00% of Swift online submissions for Shift 2D Grid.
// Memory Usage: 14.7 MB, less than 30.77% of Swift online submissions for Shift 2D Grid.
class Solution {
func shiftGrid(_ grid: [[Int]], _ k: Int) -> [[Int]] {
if k == 0 {
return grid
}
let m = grid.count
let n = grid[0].count
var ans = grid
for i in 0..<m {
for j in 0..<n {
let i1 = (i + (j + k) / n) % m
let j1 = (j + k) % n
ans[i1][j1] = grid[i][j]
}
}
return ans
}
} | 27.92 | 89 | 0.472779 |
2f4c8d2d6ee989cc5a96cc2626a5838086486d40 | 33,846 | //
// RangeSeekSlider.swift
// RangeSeekSlider
//
// Created by Keisuke Shoji on 2017/03/09.
//
//
import UIKit
@IBDesignable open class RangeSeekSlider: UIControl {
// MARK: - initializers
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public required override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public convenience init(frame: CGRect = .zero, completion: ((RangeSeekSlider) -> Void)? = nil) {
self.init(frame: frame)
completion?(self)
}
// MARK: - open stored properties
open weak var delegate: RangeSeekSliderDelegate?
/// The minimum possible value to select in the range
@IBInspectable open var minValue: CGFloat = 0.0 {
didSet {
refresh()
}
}
/// The maximum possible value to select in the range
@IBInspectable open var maxValue: CGFloat = 100.0 {
didSet {
refresh()
}
}
/// The preselected minumum value
/// (note: This should be less than the selectedMaxValue)
@IBInspectable open var selectedMinValue: CGFloat = 0.0 {
didSet {
if selectedMinValue < minValue {
selectedMinValue = minValue
}
}
}
/// The preselected maximum value
/// (note: This should be greater than the selectedMinValue)
@IBInspectable open var selectedMaxValue: CGFloat = 100.0 {
didSet {
if selectedMaxValue > maxValue {
selectedMaxValue = maxValue
}
}
}
/// The font of the minimum value text label. If not set, the default is system font size 12.0.
open var minLabelFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
minLabel.font = minLabelFont as CFTypeRef
minLabel.fontSize = minLabelFont.pointSize
}
}
/// The font of the maximum value text label. If not set, the default is system font size 12.0.
open var maxLabelFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
maxLabel.font = maxLabelFont as CFTypeRef
maxLabel.fontSize = maxLabelFont.pointSize
}
}
/// Each handle in the slider has a label above it showing the current selected value. By default, this is displayed as a decimal format.
/// You can update this default here by updating properties of NumberFormatter. For example, you could supply a currency style, or a prefix or suffix.
open var numberFormatter: NumberFormatter = {
let formatter: NumberFormatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0
return formatter
}()
/// Hides the labels above the slider controls. true = labels will be hidden. false = labels will be shown. Default is false.
@IBInspectable open var hideLabels: Bool = false {
didSet {
minLabel.isHidden = hideLabels
maxLabel.isHidden = hideLabels
}
}
/// fixes the labels above the slider controls. true: labels will be fixed to both ends. false: labels will move with the handles. Default is false.
@IBInspectable open var labelsFixed: Bool = false
/// The minimum distance the two selected slider values must be apart. Default is 0.
@IBInspectable open var minDistance: CGFloat = 0.0 {
didSet {
if minDistance < 0.0 {
minDistance = 0.0
}
}
}
/// The maximum distance the two selected slider values must be apart. Default is CGFloat.greatestFiniteMagnitude.
@IBInspectable open var maxDistance: CGFloat = .greatestFiniteMagnitude {
didSet {
if maxDistance < 0.0 {
maxDistance = .greatestFiniteMagnitude
}
}
}
/// The color of the minimum value text label. If not set, the default is the tintColor.
@IBInspectable open var minLabelColor: UIColor?
/// The color of the maximum value text label. If not set, the default is the tintColor.
@IBInspectable open var maxLabelColor: UIColor?
/// Handle slider with custom color, you can set custom color for your handle
@IBInspectable open var handleColor: UIColor?
/// Handle slider with custom border color, you can set custom border color for your handle
@IBInspectable open var handleBorderColor: UIColor?
/// Set slider line tint color between handles
@IBInspectable open var colorBeforeLeftHandle: UIColor?
@IBInspectable open var colorBetweenHandles: UIColor?
@IBInspectable open var colorAfterRightHandle: UIColor?
/// The color of the entire slider when the handle is set to the minimum value and the maximum value. Default is nil.
@IBInspectable open var initialColor: UIColor?
/// If true, the control will mimic a normal slider and have only one handle rather than a range.
/// In this case, the selectedMinValue will be not functional anymore. Use selectedMaxValue instead to determine the value the user has selected.
@IBInspectable open var disableRange: Bool = false {
didSet {
leftHandle.isHidden = disableRange
minLabel.isHidden = disableRange
}
}
/// If true the control will snap to point at each step between minValue and maxValue. Default is false.
@IBInspectable open var enableStep: Bool = false
/// The step value, this control the value of each step. If not set the default is 0.0.
/// (note: this is ignored if <= 0.0)
@IBInspectable open var step: CGFloat = 0.0
/// The smallest value the left handle of the slider could be dragged to. Default is 0.
@IBInspectable open var minTrackingValue: CGFloat = 0.0
/// The largest value the right handle of the slider could be dragged to. Default is 0.
@IBInspectable open var maxTrackingValue: CGFloat = 0.0
/// Handle slider with custom image, you can set custom image for your handle
@IBInspectable open var handleImage: UIImage? {
didSet {
guard let image = handleImage else {
return
}
var handleFrame = CGRect.zero
handleFrame.size = image.size
leftHandle.frame = handleFrame
leftHandle.contents = image.cgImage
rightHandle.frame = handleFrame
rightHandle.contents = image.cgImage
}
}
/// Handle diameter (default 28.0)
@IBInspectable open var handleDiameter: CGFloat = 28.0 {
didSet {
leftHandle.cornerRadius = handleDiameter / 2.0
rightHandle.cornerRadius = handleDiameter / 2.0
leftHandle.frame = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
rightHandle.frame = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
}
}
/// Selected handle diameter multiplier (default 1.7)
@IBInspectable open var selectedHandleDiameterMultiplier: CGFloat = 1.7
/// Set the slider line height (default 1.0)
@IBInspectable open var lineHeight: CGFloat = 1.0 {
didSet {
updateLineHeight()
}
}
/// Handle border width (default 0.0)
@IBInspectable open var handleBorderWidth: CGFloat = 0.0 {
didSet {
leftHandle.borderWidth = handleBorderWidth
rightHandle.borderWidth = handleBorderWidth
}
}
/// Set padding between label and handle (default 8.0)
@IBInspectable open var labelPadding: CGFloat = 8.0 {
didSet {
updateLabelPositions()
}
}
/// The label displayed in accessibility mode for minimum value handler. If not set, the default is empty String.
@IBInspectable open var minLabelAccessibilityLabel: String?
/// The label displayed in accessibility mode for maximum value handler. If not set, the default is empty String.
@IBInspectable open var maxLabelAccessibilityLabel: String?
/// The brief description displayed in accessibility mode for minimum value handler. If not set, the default is empty String.
@IBInspectable open var minLabelAccessibilityHint: String?
/// The brief description displayed in accessibility mode for maximum value handler. If not set, the default is empty String.
@IBInspectable open var maxLabelAccessibilityHint: String?
// MARK: - private stored properties
private enum HandleTracking { case none, left, right }
private var handleTracking: HandleTracking = .none
private let sliderLine: CALayer = CALayer()
private let sliderLineBeforeLeftHandle: CALayer = CALayer()
private let sliderLineBetweenHandles: CALayer = CALayer()
private let sliderLineAfterRightHandle: CALayer = CALayer()
private let leftHandle: CAShapeLayer = CAShapeLayer()
private let rightHandle: CAShapeLayer = CAShapeLayer()
fileprivate let minLabel: CATextLayer = CATextLayer()
fileprivate let maxLabel: CATextLayer = CATextLayer()
private var minLabelTextSize: CGSize = .zero
private var maxLabelTextSize: CGSize = .zero
// UIFeedbackGenerator
private var previousStepMinValue: CGFloat?
private var previousStepMaxValue: CGFloat?
// strong reference needed for UIAccessibilityContainer
// see http://stackoverflow.com/questions/13462046/custom-uiview-not-showing-accessibility-on-voice-over
private var accessibleElements: [UIAccessibilityElement] = []
// MARK: - private computed properties
private var leftHandleAccessibilityElement: UIAccessibilityElement {
let element: RangeSeekSliderLeftElement = RangeSeekSliderLeftElement(accessibilityContainer: self)
element.isAccessibilityElement = true
element.accessibilityLabel = minLabelAccessibilityLabel
element.accessibilityHint = minLabelAccessibilityHint
element.accessibilityValue = minLabel.string as? String
element.accessibilityFrame = convert(leftHandle.frame, to: nil)
element.accessibilityTraits = UIAccessibilityTraitAdjustable
return element
}
private var rightHandleAccessibilityElement: UIAccessibilityElement {
let element: RangeSeekSliderRightElement = RangeSeekSliderRightElement(accessibilityContainer: self)
element.isAccessibilityElement = true
element.accessibilityLabel = maxLabelAccessibilityLabel
element.accessibilityHint = maxLabelAccessibilityHint
element.accessibilityValue = maxLabel.string as? String
element.accessibilityFrame = convert(rightHandle.frame, to: nil)
element.accessibilityTraits = UIAccessibilityTraitAdjustable
return element
}
// MARK: - UIView
open override func layoutSubviews() {
super.layoutSubviews()
if handleTracking == .none {
updateLineHeight()
updateLabelValues()
updateColors()
updateHandlePositions()
updateLabelPositions()
}
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: 65.0)
}
// MARK: - UIControl
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let touchLocation: CGPoint = touch.location(in: self)
let insetExpansion: CGFloat = -30.0
let isTouchingLeftHandle: Bool = leftHandle.frame.insetBy(dx: insetExpansion, dy: insetExpansion).contains(touchLocation)
let isTouchingRightHandle: Bool = rightHandle.frame.insetBy(dx: insetExpansion, dy: insetExpansion).contains(touchLocation)
guard isTouchingLeftHandle || isTouchingRightHandle else { return false }
// the touch was inside one of the handles so we're definitely going to start movign one of them. But the handles might be quite close to each other, so now we need to find out which handle the touch was closest too, and activate that one.
let distanceFromLeftHandle: CGFloat = touchLocation.distance(to: leftHandle.frame.center)
let distanceFromRightHandle: CGFloat = touchLocation.distance(to: rightHandle.frame.center)
if distanceFromLeftHandle < distanceFromRightHandle && !disableRange {
handleTracking = .left
} else if selectedMaxValue == maxValue && leftHandle.frame.midX == rightHandle.frame.midX {
handleTracking = .left
} else {
handleTracking = .right
}
// let handle = (handleTracking == .left) ? leftHandle : rightHandle
// animate(handle: handle, selected: true)
delegate?.didStartTouches(in: self)
return true
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
guard handleTracking != .none else { return false }
let location: CGPoint = touch.location(in: self)
// find out the percentage along the line we are in x coordinate terms (subtracting half the frames width to account for moving the middle of the handle, not the left hand side)
let percentage: CGFloat = (location.x - sliderLine.frame.minX - handleDiameter / 2.0) / (sliderLine.frame.maxX - sliderLine.frame.minX)
// multiply that percentage by self.maxValue to get the new selected minimum value
let selectedValue: CGFloat = percentage * (maxValue - minValue) + minValue
switch handleTracking {
case .left:
let newMinValue = min(selectedValue, selectedMaxValue)
selectedMinValue = max(newMinValue, minTrackingValue)
case .right:
// don't let the dots cross over, (unless range is disabled, in which case just dont let the dot fall off the end of the screen)
if disableRange && selectedValue >= minValue {
selectedMaxValue = selectedValue
} else {
let newMaxValue = max(selectedValue, selectedMinValue)
selectedMaxValue = maxTrackingValue > 0 ? min(newMaxValue, maxTrackingValue) : newMaxValue
}
case .none:
// no need to refresh the view because it is done as a side-effect of setting the property
break
}
refresh()
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
// let handle = (handleTracking == .left) ? leftHandle : rightHandle
// animate(handle: handle, selected: false)
handleTracking = .none
delegate?.didEndTouches(in: self)
}
// MARK: - UIAccessibility
open override func accessibilityElementCount() -> Int {
return accessibleElements.count
}
open override func accessibilityElement(at index: Int) -> Any? {
return accessibleElements[index]
}
open override func index(ofAccessibilityElement element: Any) -> Int {
guard let element = element as? UIAccessibilityElement else { return 0 }
return accessibleElements.index(of: element) ?? 0
}
// MARK: - open methods
/// When subclassing **RangeSeekSlider** and setting each item in **setupStyle()**, the design is reflected in Interface Builder as well.
open func setupStyle() {}
// MARK: - private methods
private func setup() {
isAccessibilityElement = false
accessibleElements = [leftHandleAccessibilityElement, rightHandleAccessibilityElement]
leftHandle.path = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter), cornerRadius: (handleDiameter / 2.0)).cgPath
leftHandle.fillColor = UIColor.white.cgColor
// leftHandle.shadowColor = UIColor.lightGray.cgColor
leftHandle.shadowPath = leftHandle.path
leftHandle.shadowOffset = CGSize(width: 0.0, height: 4.0)
leftHandle.shadowOpacity = 0.5
leftHandle.shadowRadius = 3.0
rightHandle.path = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter), cornerRadius: (handleDiameter / 2.0)).cgPath
rightHandle.fillColor = UIColor.white.cgColor
// rightHandle.shadowColor = UIColor.lightGray.cgColor
rightHandle.shadowPath = rightHandle.path
rightHandle.shadowOffset = CGSize(width: 0.0, height: 4.0)
rightHandle.shadowOpacity = 0.5
rightHandle.shadowRadius = 3.0
// draw the slider line
layer.addSublayer(sliderLine)
// draw the track distline
layer.addSublayer(sliderLineBeforeLeftHandle)
layer.addSublayer(sliderLineBetweenHandles)
layer.addSublayer(sliderLineAfterRightHandle)
// draw the minimum slider handle
leftHandle.cornerRadius = handleDiameter / 2.0
leftHandle.borderWidth = handleBorderWidth
layer.addSublayer(leftHandle)
// draw the maximum slider handle
rightHandle.cornerRadius = handleDiameter / 2.0
rightHandle.borderWidth = handleBorderWidth
layer.addSublayer(rightHandle)
let handleFrame: CGRect = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
leftHandle.frame = handleFrame
rightHandle.frame = handleFrame
// draw the text labels
let labelFontSize: CGFloat = 12.0
let labelFrame: CGRect = CGRect(x: 0.0, y: 0.0, width: 75.0, height: 14.0)
minLabelFont = UIFont.systemFont(ofSize: labelFontSize)
minLabel.alignmentMode = kCAAlignmentCenter
minLabel.frame = labelFrame
minLabel.contentsScale = UIScreen.main.scale
layer.addSublayer(minLabel)
maxLabelFont = UIFont.systemFont(ofSize: labelFontSize)
maxLabel.alignmentMode = kCAAlignmentCenter
maxLabel.frame = labelFrame
maxLabel.contentsScale = UIScreen.main.scale
layer.addSublayer(maxLabel)
setupStyle()
refresh()
}
private func percentageAlongLine(for value: CGFloat) -> CGFloat {
// stops divide by zero errors where maxMinDif would be zero. If the min and max are the same the percentage has no point.
guard minValue < maxValue else { return 0.0 }
// get the difference between the maximum and minimum values (e.g if max was 100, and min was 50, difference is 50)
let maxMinDif: CGFloat = maxValue - minValue
// now subtract value from the minValue (e.g if value is 75, then 75-50 = 25)
let valueSubtracted: CGFloat = value - minValue
// now divide valueSubtracted by maxMinDif to get the percentage (e.g 25/50 = 0.5)
return valueSubtracted / maxMinDif
}
private func xPositionAlongLine(for value: CGFloat) -> CGFloat {
// first get the percentage along the line for the value
let percentage: CGFloat = percentageAlongLine(for: value)
// get the difference between the maximum and minimum coordinate position x values (e.g if max was x = 310, and min was x=10, difference is 300)
let maxMinDif: CGFloat = sliderLine.frame.maxX - sliderLine.frame.minX
// now multiply the percentage by the minMaxDif to see how far along the line the point should be, and add it onto the minimum x position.
let offset: CGFloat = percentage * maxMinDif
return sliderLine.frame.minX + offset
}
private func updateLineHeight() {
let barSidePadding: CGFloat = 2.0
let yMiddle: CGFloat = frame.height / 2.0
let lineLeftSide: CGPoint = CGPoint(x: barSidePadding, y: yMiddle)
let lineRightSide: CGPoint = CGPoint(x: frame.width - barSidePadding,
y: yMiddle)
sliderLine.frame = CGRect(x: lineLeftSide.x,
y: lineLeftSide.y,
width: lineRightSide.x - lineLeftSide.x,
height: lineHeight)
sliderLine.cornerRadius = lineHeight / 2.0
sliderLineBeforeLeftHandle.cornerRadius = sliderLine.cornerRadius
sliderLineBetweenHandles.cornerRadius = sliderLine.cornerRadius
sliderLineAfterRightHandle.cornerRadius = sliderLine.cornerRadius
}
private func updateLabelValues() {
minLabel.isHidden = hideLabels || disableRange
maxLabel.isHidden = hideLabels
if let replacedString = delegate?.rangeSeekSlider(self, stringForMinValue: selectedMinValue) {
minLabel.string = replacedString
} else {
minLabel.string = numberFormatter.string(from: selectedMinValue as NSNumber)
}
if let replacedString = delegate?.rangeSeekSlider(self, stringForMaxValue: selectedMaxValue) {
maxLabel.string = replacedString
} else {
maxLabel.string = numberFormatter.string(from: selectedMaxValue as NSNumber)
}
if let nsstring = minLabel.string as? NSString {
minLabelTextSize = nsstring.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: minLabelFont])
}
if let nsstring = maxLabel.string as? NSString {
maxLabelTextSize = nsstring.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: maxLabelFont])
}
}
private func updateColors() {
let isInitial: Bool = selectedMinValue == minValue && selectedMaxValue == maxValue
if let initialColor = initialColor?.cgColor, isInitial {
minLabel.foregroundColor = initialColor
maxLabel.foregroundColor = initialColor
sliderLineBeforeLeftHandle.backgroundColor = initialColor
sliderLineBetweenHandles.backgroundColor = initialColor
sliderLineAfterRightHandle.backgroundColor = initialColor
sliderLine.backgroundColor = initialColor
let color: CGColor = (handleImage == nil) ? initialColor : UIColor.clear.cgColor
leftHandle.backgroundColor = color
leftHandle.borderColor = color
rightHandle.backgroundColor = color
rightHandle.borderColor = color
} else {
let tintCGColor: CGColor = tintColor.cgColor
minLabel.foregroundColor = minLabelColor?.cgColor ?? tintCGColor
maxLabel.foregroundColor = maxLabelColor?.cgColor ?? tintCGColor
sliderLineBeforeLeftHandle.backgroundColor = colorBeforeLeftHandle?.cgColor ?? tintCGColor
sliderLineBetweenHandles.backgroundColor = colorBetweenHandles?.cgColor ?? tintCGColor
sliderLineAfterRightHandle.backgroundColor = colorAfterRightHandle?.cgColor ?? tintCGColor
sliderLine.backgroundColor = tintCGColor
let color: CGColor
if let _ = handleImage {
color = UIColor.clear.cgColor
} else {
color = handleColor?.cgColor ?? tintCGColor
}
leftHandle.fillColor = color
leftHandle.borderColor = handleBorderColor.map { $0.cgColor }
rightHandle.fillColor = color
rightHandle.borderColor = handleBorderColor.map { $0.cgColor }
}
}
private func updateAccessibilityElements() {
accessibleElements = [leftHandleAccessibilityElement, rightHandleAccessibilityElement]
}
private func updateHandlePositions() {
leftHandle.position = CGPoint(x: xPositionAlongLine(for: selectedMinValue),
y: sliderLine.frame.midY)
rightHandle.position = CGPoint(x: xPositionAlongLine(for: selectedMaxValue),
y: sliderLine.frame.midY)
// positioning for the dist slider line
sliderLineBeforeLeftHandle.frame = CGRect(x: sliderLine.frame.minX,
y: sliderLine.frame.minY,
width: leftHandle.position.x,
height: lineHeight)
sliderLineBetweenHandles.frame = CGRect(x: leftHandle.position.x,
y: sliderLine.frame.minY,
width: rightHandle.position.x - leftHandle.position.x,
height: lineHeight)
sliderLineAfterRightHandle.frame = CGRect(x: rightHandle.position.x,
y: sliderLine.frame.minY,
width: sliderLine.frame.maxX - rightHandle.position.x,
height: lineHeight)
}
private func updateLabelPositions() {
// the center points for the labels are X = the same x position as the relevant handle. Y = the y position of the handle minus half the height of the text label, minus some padding.
minLabel.frame.size = minLabelTextSize
maxLabel.frame.size = maxLabelTextSize
if labelsFixed {
updateFixedLabelPositions()
return
}
let minSpacingBetweenLabels: CGFloat = 8.0
let newMinLabelCenter: CGPoint = CGPoint(x: leftHandle.frame.midX,
y: leftHandle.frame.minY - (minLabelTextSize.height / 2.0) - labelPadding)
let newMaxLabelCenter: CGPoint = CGPoint(x: rightHandle.frame.midX,
y: rightHandle.frame.minY - (maxLabelTextSize.height / 2.0) - labelPadding)
let newLeftMostXInMaxLabel: CGFloat = newMaxLabelCenter.x - maxLabelTextSize.width / 2.0
let newRightMostXInMinLabel: CGFloat = newMinLabelCenter.x + minLabelTextSize.width / 2.0
let newSpacingBetweenTextLabels: CGFloat = newLeftMostXInMaxLabel - newRightMostXInMinLabel
if disableRange || newSpacingBetweenTextLabels > minSpacingBetweenLabels {
minLabel.position = newMinLabelCenter
maxLabel.position = newMaxLabelCenter
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
}
} else {
let increaseAmount: CGFloat = minSpacingBetweenLabels - newSpacingBetweenTextLabels
minLabel.position = CGPoint(x: newMinLabelCenter.x - increaseAmount / 2.0, y: newMinLabelCenter.y)
maxLabel.position = CGPoint(x: newMaxLabelCenter.x + increaseAmount / 2.0, y: newMaxLabelCenter.y)
// Update x if they are still in the original position
if minLabel.position.x == maxLabel.position.x {
minLabel.position.x = leftHandle.frame.midX
maxLabel.position.x = leftHandle.frame.midX + minLabel.frame.width / 2.0 + minSpacingBetweenLabels + maxLabel.frame.width / 2.0
}
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
maxLabel.frame.origin.x = minSpacingBetweenLabels + minLabel.frame.width
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
minLabel.frame.origin.x = maxLabel.frame.origin.x - minSpacingBetweenLabels - minLabel.frame.width
}
}
}
private func updateFixedLabelPositions() {
minLabel.position = CGPoint(x: xPositionAlongLine(for: minValue),
y: sliderLine.frame.minY - (minLabelTextSize.height / 2.0) - (handleDiameter / 2.0) - labelPadding)
maxLabel.position = CGPoint(x: xPositionAlongLine(for: maxValue),
y: sliderLine.frame.minY - (maxLabelTextSize.height / 2.0) - (handleDiameter / 2.0) - labelPadding)
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
}
}
fileprivate func refresh() {
if enableStep && step > 0.0 {
selectedMinValue = CGFloat(roundf(Float(selectedMinValue / step))) * step
if let previousStepMinValue = previousStepMinValue, previousStepMinValue != selectedMinValue {
TapticEngine.selection.feedback()
}
previousStepMinValue = selectedMinValue
selectedMaxValue = CGFloat(roundf(Float(selectedMaxValue / step))) * step
if let previousStepMaxValue = previousStepMaxValue, previousStepMaxValue != selectedMaxValue {
TapticEngine.selection.feedback()
}
previousStepMaxValue = selectedMaxValue
}
let diff: CGFloat = selectedMaxValue - selectedMinValue
if diff < minDistance {
switch handleTracking {
case .left:
selectedMinValue = selectedMaxValue - minDistance
case .right:
selectedMaxValue = selectedMinValue + minDistance
case .none:
break
}
} else if diff > maxDistance {
switch handleTracking {
case .left:
selectedMinValue = selectedMaxValue - maxDistance
case .right:
selectedMaxValue = selectedMinValue + maxDistance
case .none:
break
}
}
// ensure the minimum and maximum selected values are within range. Access the values directly so we don't cause this refresh method to be called again (otherwise changing the properties causes a refresh)
if selectedMinValue < minValue {
selectedMinValue = minValue
}
if selectedMaxValue > maxValue {
selectedMaxValue = maxValue
}
// update the frames in a transaction so that the tracking doesn't continue until the frame has moved.
CATransaction.begin()
CATransaction.setDisableActions(true)
updateHandlePositions()
updateLabelPositions()
CATransaction.commit()
updateLabelValues()
updateColors()
updateAccessibilityElements()
// update the delegate
if let delegate = delegate, handleTracking != .none {
delegate.rangeSeekSlider(self, didChange: selectedMinValue, maxValue: selectedMaxValue)
}
}
private func animate(handle: CAShapeLayer, selected: Bool) {
let transform: CATransform3D
if selected {
transform = CATransform3DMakeScale(selectedHandleDiameterMultiplier, selectedHandleDiameterMultiplier, 1.0)
} else {
transform = CATransform3DIdentity
}
CATransaction.begin()
CATransaction.setAnimationDuration(0.3)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
handle.transform = transform
// the label above the handle will need to move too if the handle changes size
updateLabelPositions()
CATransaction.commit()
}
}
// MARK: - RangeSeekSliderLeftElement
private final class RangeSeekSliderLeftElement: UIAccessibilityElement {
override func accessibilityIncrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMinValue += slider.step
accessibilityValue = slider.minLabel.string as? String
}
override func accessibilityDecrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMinValue -= slider.step
accessibilityValue = slider.minLabel.string as? String
}
}
// MARK: - RangeSeekSliderRightElement
private final class RangeSeekSliderRightElement: UIAccessibilityElement {
override func accessibilityIncrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMaxValue += slider.step
slider.refresh()
accessibilityValue = slider.maxLabel.string as? String
}
override func accessibilityDecrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMaxValue -= slider.step
slider.refresh()
accessibilityValue = slider.maxLabel.string as? String
}
}
// MARK: - CGRect
private extension CGRect {
var center: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
// MARK: - CGPoint
private extension CGPoint {
func distance(to: CGPoint) -> CGFloat {
let distX: CGFloat = to.x - x
let distY: CGFloat = to.y - y
return sqrt(distX * distX + distY * distY)
}
}
| 41.477941 | 247 | 0.633339 |
7696a1cd45d8f83aef52dcdba7ae7802577311cb | 4,359 | //
// ListViewController.swift
// WeatherApp
//
// Created by Alex Severyanov on 6/12/19.
// Copyright © 2019 Alex Severyanov. All rights reserved.
//
import UIKit
class ListViewController: UITableViewController, UITableViewDataSourcePrefetching {
let viewModel = ListViewModel()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupHandlers()
loadData()
}
func loadData() {
viewModel.startLoading { [weak self] in
self?.handleError($0)
if $0 == nil, self?.refreshControl == nil {
self?.addRefreshControl()
}
if self?.refreshControl?.isRefreshing == true {
self?.refreshControl?.endRefreshing()
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch viewModel.items[indexPath.row] {
case .loading(let viewModel):
let cell = tableView.dequeueCell(for: indexPath, type: LoadingTableViewCell.self)
cell.viewModel = viewModel
cell.retryHandler = { [weak self] in self?.loadData() }
return cell
case .weather(let viewModel):
let cell = tableView.dequeueCell(for: indexPath, type: WeatherTableViewCell.self)
cell.viewModel = viewModel
viewModel.imageViewModel.startLoading()
return cell
case .myLocation(let viewModel):
let cell = tableView.dequeueCell(for: indexPath, type: MyLocationTableViewCell.self)
cell.viewModel = viewModel
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch viewModel.items[indexPath.row] {
case .weather(let weatherViewModel):
viewModel.perform(transition: .details(weatherViewModel))
case .myLocation(let locationViewModel):
if case .success(let weatherViewModel) = locationViewModel.state {
viewModel.perform(transition: .details(weatherViewModel))
}
default:
break
}
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
indexPaths.forEach {
if case .weather(let vm) = viewModel.items[$0.row] {
vm.imageViewModel.startLoading()
}
}
}
func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
indexPaths.forEach {
if case .weather(let vm) = viewModel.items[$0.row] {
vm.imageViewModel.cancelLoading()
}
}
}
}
extension ListViewController {
private func setupUI() {
tableView.rowHeight = 90
tableView.tableFooterView = UIView()
tableView.prefetchDataSource = self
tableView.register(WeatherTableViewCell.self)
tableView.register(LoadingTableViewCell.self)
tableView.register(MyLocationTableViewCell.self)
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refreshControlAction), for: .valueChanged)
}
private func setupHandlers() {
viewModel.viewActionHandler = { [weak self] in
switch $0 {
case .reload:
self?.tableView.reloadData()
}
}
}
private func handleError(_ error: Error?) {
guard let error = error else { return }
let alert = UIAlertController(title: L10n.General.error, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: L10n.General.Button.ok, style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
@objc func refreshControlAction(_ sender: UIRefreshControl) {
loadData()
}
}
private extension UITableView {
func register(_ cellClass: UITableViewCell.Type) {
register(cellClass, forCellReuseIdentifier: String(describing: cellClass))
}
func dequeueCell<T: UITableViewCell>(for indexPath: IndexPath, type: T.Type = T.self) -> T {
return dequeueReusableCell(withIdentifier: String(describing: type), for: indexPath) as! T
}
}
| 30.062069 | 123 | 0.664602 |
7ae2db4daec52ca11bbcb5e6bb7b3400d875ef9f | 1,169 | //
// OutputDataMessage.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
/** The output data message contains payload plus metadata for a payload received from a device. */
public struct OutputDataMessage: Codable {
public var type: OutputDataMessageOutputMessageType?
public var device: Device?
public var payload: Data?
/** Received time for message. Value is ms since epoch. */
public var received: String?
public var transport: String?
public var udpMetaData: UDPMetadata?
public var coapMetaData: CoAPMetadata?
public var messageId: String?
public init(type: OutputDataMessageOutputMessageType? = nil, device: Device? = nil, payload: Data? = nil, received: String? = nil, transport: String? = nil, udpMetaData: UDPMetadata? = nil, coapMetaData: CoAPMetadata? = nil, messageId: String? = nil) {
self.type = type
self.device = device
self.payload = payload
self.received = received
self.transport = transport
self.udpMetaData = udpMetaData
self.coapMetaData = coapMetaData
self.messageId = messageId
}
}
| 33.4 | 256 | 0.698033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.