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
|
---|---|---|---|---|---|
29cf2f6d059f233ae48653ac3e04585272428983 | 330 | //
// Codable.swift
// oracli
//
// Created by Anika Morris on 2/23/20.
// Copyright © 2020 Anika Morris. All rights reserved.
//
import Foundation
struct Login:Codable {
let email: String
let password: String
}
struct Update:Codable {
let token: String
let fieldToUpdate: String
let update: String
}
| 14.347826 | 55 | 0.669697 |
796f7004d76d5f6528888d9fa7ba2d2300d1a75c | 1,551 | //
// SettingsViewController.swift
// iTip
//
// Created by Brian Kaplan on 12/9/15.
// Copyright © 2015 Brian Kaplan. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipSegment: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Load the saved tip setting
let defaults = NSUserDefaults.standardUserDefaults()
let defaultTipIndex = defaults.integerForKey("defaultTip")
defaultTipSegment.selectedSegmentIndex = defaultTipIndex
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func settingChanged(sender: AnyObject){
print(defaultTipSegment.selectedSegmentIndex)
// Save the index for the default segment
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(defaultTipSegment.selectedSegmentIndex, forKey: "defaultTip")
defaults.synchronize()
}
/*
// 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.
}
*/
}
| 29.264151 | 106 | 0.685364 |
91c4fdc7e4705122aff9cb9decb67a94eb12767c | 1,842 | //
// MainVIewController.swift
// Bankey
//
// Created by Taiki on 4/01/6.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupTabBar()
}
private func setupViews() {
let summaryVC = AccountSummaryViewController()
summaryVC.setTabBarImage(imageName: "list.dash.header.rectangle", title: "Summary")
let summaryNC = UINavigationController(rootViewController: summaryVC)
summaryNC.navigationBar.barTintColor = appColor
hideNavigationBarLine(summaryNC.navigationBar)
let moneyVC = MoveMoneyViewController()
moneyVC.setTabBarImage(imageName: "arrow.left.arrow.right", title: "Move Money")
let moneyNC = UINavigationController(rootViewController: moneyVC)
let moreVC = MoreViewController()
moreVC.setTabBarImage(imageName: "ellipsis.circle", title: "More")
let moreNC = UINavigationController(rootViewController: moreVC)
let tabBarList = [summaryNC, moneyNC, moreNC]
viewControllers = tabBarList
}
private func hideNavigationBarLine(_ navigationBar: UINavigationBar) {
let img = UIImage()
navigationBar.shadowImage = img
navigationBar.setBackgroundImage(img, for: .default)
navigationBar.isTranslucent = false
}
private func setupTabBar() {
tabBar.tintColor = appColor
tabBar.isTranslucent = false
}
}
class MoveMoneyViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .systemOrange
}
}
class MoreViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .systemPurple
}
}
| 27.909091 | 91 | 0.661238 |
69108c6ff827a7d2ed33e495d6488134534eceac | 416 | //
// Binding+Bool.swift
//
//
// Created by Christopher Weems on 7/2/20.
//
#if canImport(SwiftUI)
import Foundation
import SwiftUI
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@available(*, deprecated, message: "Moved to `unstandard-ui` package")
public extension Binding where Value == Bool {
prefix static func !(_ binding: Self) -> Bool {
!binding.wrappedValue
}
}
#endif
| 19.809524 | 70 | 0.668269 |
e9312a626f18c7fdb29add6916b00c06dcac09c1 | 4,427 | //
// ViewController.swift
// TestPromiss
//
// Created by IOS3 on 2019/5/9.
// Copyright © 2019 IOS3. All rights reserved.
//
import UIKit
import PromiseKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "PromiseKit_01"
// testPromise_02()
testRace()
}
}
fileprivate typealias Doc = ViewController
extension Doc {
/*
- fulfill 方法吧 promise 的状态置为完成状态(fulfilled), 这是then 方法就能捕捉到, 并执行成功情况的回调
- reject 方法把 promise 的状态置为失败(rejected), 这时就能进到 catch 方法
- finally 方法, 不管成功失败, 都会进入finally 方法
- then 方法, 要求传入一个promise, 返回一个promise
- map() 是根据先前的promise结果, 然后返回一个新的对象或值类型
- compactMap(), 与map类似, 其返回Optional, 如果我们返回nil, 则整个链会产生 PMKError.compactMap 错误
- 如果想要在链路中获取值用于其他操作,比如输出调试。那么可以使用 get()、tap() 这两个方法,它们都不会影响到原有链路逻辑
- when 方法提供了并行执行异步操作的能力,并且只有在所有异步操作执行完后才执行回调。 和其他的 promise 链一样,when 方法中任一异步操作发生错误,都会进入到下一个 catch 方法中。
- race 的用法与 when 一样,如果有一个方法执行完成就会立即返回.
- Guarantee 是 Promise 的变种、或者补充,其用法和 Promise 一样,大多情况下二者可以互相替换使用。 与 Promise 状态可以是成功或者失败不同,Guarantee 要确保永不失败,因此语法也更简单些。
- after() PromiseKit 封装的延迟方法
let g = Guarantee<String> { seal in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
print("洗碗完毕!")
seal("干净的碗筷")
}
}
*/
}
fileprivate typealias Test = ViewController
fileprivate extension Test {
func testPromise_01() -> () {
_ = cook()
.then({ data -> Promise<String> in
return self.eat(data: data)
})
.then({ (data) -> Promise<String> in
return self.wash(data: data)
})
.done({ (data) in
print(data)
})
}
func testPromise_02() -> () {
_ = cook()
.map{ $0 + "配上一碗汤" }
.then(eat)
.get{ print("deubg: then(eat): data=\($0) 😂")}
.then(wash)
.tap{ print("dubg: then(wash): \($0) 😂") }
.done({ (data) in
print(data)
})
.catch({ (error) in
print(error.localizedDescription + "没法吃")
})
.finally {
print("出门上班")
}
}
func testWhen() -> Void {
_ = when(fulfilled: cutup(), boil())
.done { print("结果: \($0) \($1)")}
}
func testRace() -> Void {
_ = race(cutup(), boil())
.done{ print("data: \($0) ")}
}
}
fileprivate typealias TestPromiss = ViewController
fileprivate extension TestPromiss {
func cook() -> Promise<String> {
print("开始做饭")
let p = Promise<String> { (reslover) in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
print("做饭完毕")
reslover.fulfill("鸡蛋炒饭")
// let error = NSError(domain: "cook.error", code: 2333, userInfo: [NSLocalizedDescriptionKey : "米饭烧焦了"])
// reslover.reject(error)
})
}
return p
}
func eat(data: String) -> Promise<String> {
print("j开始吃饭" + data)
let p = Promise<String> { resolver in
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
print("吃饭完毕")
resolver.fulfill("一个碗和一双筷子")
})
}
return p
}
func wash(data: String) -> Promise<String> {
print("开始洗碗: \(data)")
let p = Promise<String> { resolver in
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
print("洗碗完毕")
resolver.fulfill("f干净的碗")
})
}
return p
}
// 切菜
func cutup() -> Promise<String> {
print("开始切菜")
let p = Promise<String> { resolver in
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
print("切菜完毕")
resolver.fulfill("切好的菜")
})
}
return p
}
// 烧水
func boil() -> Promise<String> {
print("开始烧水")
let p = Promise<String> { resolver in
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
print("烧水完毕")
resolver.fulfill("烧好的水")
})
}
return p
}
}
| 28.378205 | 121 | 0.522476 |
09c214c66d155a64e56ac21b97b7dff29eb0954a | 120 | import XCTest
import xcsettingTests
var tests = [XCTestCaseEntry]()
tests += xcsettingTests.allTests()
XCTMain(tests)
| 15 | 34 | 0.783333 |
e2ce2f6ca6c6d5153cfe8f42efa38488568ba2a4 | 5,958 | //
// ViewController.swift
// Tip Calculator
//
// Created by Max Skeen on 11/12/20.
//
import UIKit
class ViewController: UIViewController {
//Declare variables
var tipPercent = 0.0
let tipPercentages = [15, 20, 25]
//Declare Elements
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipField: UITextField!
@IBOutlet weak var totalField: UITextField!
@IBOutlet weak var billLabel: UILabel!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var darkModeLabel: UILabel!
@IBOutlet weak var rateLabel: UILabel!
@IBOutlet weak var rateField: UITextField!
@IBOutlet weak var tipSlider: UISlider!
@IBOutlet weak var darkModeSwitch: UISwitch!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet var background: UIView!
@IBOutlet weak var dollarSign: UILabel!
@IBOutlet weak var totalLabel: UILabel!
// let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tipSlider.value = Float(tipPercentages[tipControl.selectedSegmentIndex])
billField.becomeFirstResponder()
rateField.text = String(UserDefaults.standard.integer(forKey: "Rate")) + "%"
tipField.text = "$" + String(format: "%.2f", UserDefaults.standard.double(forKey: "Tip"))
billField.text = String(format: "%.2f", UserDefaults.standard.double(forKey: "Bill"))
// if UserDefaults.standard.double(forKey: "Bill") == 0.0 {
// billField.text = String(format: "%.2f", UserDefaults.standard.double(forKey: "Bill"))
// }
// else {
// billField.text = String(UserDefaults.standard.double(forKey: "Bill"))
// }
totalField.text = "$" + String(format: "%.2f", UserDefaults.standard.double(forKey: "Total"))
tipSlider.value = UserDefaults.standard.float(forKey: "Slider Value")
tipControl.selectedSegmentIndex = UserDefaults.standard.integer(forKey: "Tip Control Index")
if UserDefaults.standard.bool(forKey: "DarkMode on") {
darkModeSwitch.setOn(UserDefaults.standard.bool(forKey: "DarkMode on"), animated: true)
if darkModeSwitch.isOn {
background.backgroundColor = UIColor.darkGray
changeTextColor(color: UIColor.white)
UserDefaults.standard.set(true, forKey: "DarkMode on")
}
else {
background.backgroundColor = UIColor.white
changeTextColor(color: UIColor.black)
UserDefaults.standard.set(false, forKey: "DarkMode on")
}
}
}
func changeTextColor(color: UIColor)
{
billLabel.textColor = color
tipLabel.textColor = color
totalLabel.textColor = color
billField.textColor = color
tipField.textColor = color
totalField.textColor = color
dollarSign.textColor = color
rateField.textColor = color
rateLabel.textColor = color
}
@IBAction func darkModeClicked(_ sender: Any) {
if darkModeSwitch.isOn {
background.backgroundColor = UIColor.darkGray
changeTextColor(color: UIColor.white)
UserDefaults.standard.set(true, forKey: "DarkMode on")
}
else {
background.backgroundColor = UIColor.white
changeTextColor(color: UIColor.black)
UserDefaults.standard.set(false, forKey: "DarkMode on")
}
}
@IBAction func tipSlid(_ sender: Any) {
tipSlider.value = round(tipSlider.value)
rateField.text = String(Int(round(tipSlider.value))) + "%"
tipPercent = Double(tipSlider.value)
UserDefaults.standard.set(tipSlider.value, forKey: "Slider Value")
print("Default \(String(tipSlider.value))")
}
@IBAction func tipSelected(_ sender: Any) {
rateField.text = String(tipPercentages[tipControl.selectedSegmentIndex]) + "%"
tipSlider.value = Float(tipPercentages[tipControl.selectedSegmentIndex])
tipPercent = Double(tipPercentages[tipControl.selectedSegmentIndex])
//Get the Bill Amount
let bill = Double(billField.text!) ?? 0
//Calculate the tip and total
let tip = tipPercent/100 * bill
let total = bill + tip
//Update the tip and total labels
tipField.text = String(format: "$%.2f", tip)
totalField.text = String(format: "$%.2f", total)
UserDefaults.standard.set(tip, forKey: "Tip")
UserDefaults.standard.set(tipPercent, forKey: "Rate")
UserDefaults.standard.set(bill, forKey: "Bill")
UserDefaults.standard.set(total, forKey: "Total")
UserDefaults.standard.set(tipControl.selectedSegmentIndex, forKey: "Tip Control Index")
UserDefaults.standard.set(tipSlider.value, forKey: "Slider Value")
}
@IBAction func calculateTip(_ sender: Any) {
//Get the Bill Amount
let bill = Double(billField.text!) ?? 0
//Calculate the tip and total
let tip = tipPercent/100 * bill
let total = bill + tip
//Update the tip and total labels
tipField.text = String(format: "$%.2f", tip)
totalField.text = String(format: "$%.2f", total)
UserDefaults.standard.set(tip, forKey: "Tip")
UserDefaults.standard.set(tipPercent, forKey: "Rate")
UserDefaults.standard.set(bill, forKey: "Bill")
UserDefaults.standard.set(total, forKey: "Total")
}
}
| 34.045714 | 101 | 0.599027 |
5015a642484e280c81f6c671e43520bbf6d6084a | 1,366 | import Foundation
/// Graph, Topological-Sort
class Solution {
var visited = [Bool]()
var result = [Int]()
var graph = Dictionary<Int,[Int]>()
var possible = true
/// Solution not working: Needs analysis
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
//diagnostic is right if no suceeding statements present
visited = Array.init(repeating: false, count: numCourses)
for element in prerequisites { // form graph
if var adjList = graph[element[0]] {
adjList.append(element[1])
graph.updateValue(adjList, forKey: element[0])
} else {
graph.updateValue([element[1]], forKey: element[0])
}
}
for i in 0..<numCourses {
if !visited[i] {
topologicalSort(i)
} else {
possible = false
}
}
return possible ? result : []
}
func topologicalSort(_ v: Int) {
visited[v] = true
if let adjNodes = graph[v] {
for node in adjNodes {
if !visited[node] {
topologicalSort(node)
}
}
}
result.append(v)
}
}
func testFindOrder() {
print(Solution.init().findOrder(4, [[1,0],[2,0],[3,1],[3,2]]))
}
testFindOrder() | 31.045455 | 74 | 0.516105 |
906637de80bbdda1092026f1b1744a46ad02d59a | 897 | //
// chatTimeTests.swift
// chatTimeTests
//
// Created by 陈静 on 14-9-21.
// Copyright (c) 2014年 Team chatTime. All rights reserved.
//
import UIKit
import XCTest
class chatTimeTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.243243 | 111 | 0.613155 |
dea063f1b30eaae306e0c1d1ca0839d8340d1e99 | 1,371 | //
// SuperheroeResource.swift
// SuperHeroes
//
// Created by Oscar on 16/5/18.
// Copyright © 2018 Oscar García. All rights reserved.
//
import Foundation
import Result
enum SuperheroesResource {
case all
}
extension SuperheroesResource: Resource {
var method: Method {
switch self {
case .all:
return .GET
}
}
var path: String {
switch self {
case .all:
return ""
}
}
var parameters: [String: String] {
switch self {
case .all:
return [:]
}
}
var body: Data? {
switch self {
case .all:
return nil
}
}
}
extension URL {
static func superheroeURL() -> URL {
guard let baseURL = URL(string: AppURL.domainsAPI) else {
fatalError("API URL is needed")
}
return baseURL.appendingPathComponent("bvyob")
}
}
extension APIClient {
static func superheroesAPIClient() -> APIClient {
return APIClient(baseURL: URL.superheroeURL())
}
func superheroes(completion: @escaping (Result<Superheroes, APIClientError>) -> Void) {
let resource = SuperheroesResource.all
object(resource) { (result: Result<Superheroes, APIClientError>) in
completion(result)
}
}
}
| 19.585714 | 91 | 0.556528 |
08539a195c296ece82ea881145cdff23e27ff984 | 13,199 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 XCTest
import Chatto
@testable import ChattoAdditions
class ChatInputBarTests: XCTestCase {
private var bar: ChatInputBar!
private var presenter: FakeChatInputBarPresenter!
private var delegateStrong: FakeChatInputBarDelegate!
override func setUp() {
super.setUp()
self.bar = ChatInputBar.loadNib()
}
private func setupPresenter() {
self.presenter = FakeChatInputBarPresenter(chatInputBar: self.bar)
}
private func setupDelegate() {
self.delegateStrong = FakeChatInputBarDelegate()
self.bar.delegate = self.delegateStrong
}
private func createItemView(inputItem: ChatInputItemProtocol) -> ChatInputItemView {
let itemView = ChatInputItemView()
itemView.inputItem = inputItem
return itemView
}
private func simulateTapOnTextViewForDelegate(_ textViewDelegate: UITextViewDelegate) {
let dummyTextView = UITextView()
let shouldBeginEditing = textViewDelegate.textViewShouldBeginEditing?(dummyTextView) ?? true
guard shouldBeginEditing else { return }
textViewDelegate.textViewDidBeginEditing?(dummyTextView)
}
func testThat_WhenInputTextChanged_BarEnablesSendButton() {
self.bar.sendButton.isEnabled = false
self.bar.inputText = "!"
XCTAssertTrue(self.bar.sendButton.isEnabled)
}
func testThat_WhenInputTextBecomesEmpty_BarDisablesSendButton() {
self.bar.sendButton.isEnabled = true
self.bar.inputText = ""
XCTAssertFalse(self.bar.sendButton.isEnabled)
}
// MARK: - Presenter tests
func testThat_WhenItemViewTapped_ItNotifiesPresenterThatNewItemReceivedFocus() {
self.setupPresenter()
let item = MockInputItem()
self.bar.inputItemViewTapped(createItemView(inputItem: item))
XCTAssertTrue(self.presenter.onDidReceiveFocusOnItemCalled)
XCTAssertTrue(self.presenter.itemThatReceivedFocus === item)
}
func testThat_WhenTextViewDidBeginEditing_ItNotifiesPresenter() {
self.setupPresenter()
self.bar.textViewDidBeginEditing(self.bar.textView)
XCTAssertTrue(self.presenter.onDidBeginEditingCalled)
}
func testThat_WhenTextViewDidEndEditing_ItNotifiesPresenter() {
self.setupPresenter()
self.bar.textViewDidEndEditing(self.bar.textView)
XCTAssertTrue(self.presenter.onDidEndEditingCalled)
}
func testThat_GivenTextViewHasNoText_WhenTextViewDidChange_ItDisablesSendButton() {
self.bar.sendButton.isEnabled = true
self.bar.textView.text = ""
self.bar.textViewDidChange(self.bar.textView)
XCTAssertFalse(self.bar.sendButton.isEnabled)
}
func testThat_WhenTextViewDidChange_ItEnablesSendButton() {
self.bar.sendButton.isEnabled = false
self.bar.textView.text = "!"
self.bar.textViewDidChange(self.bar.textView)
XCTAssertTrue(self.bar.sendButton.isEnabled)
}
func testThat_WhenSendButtonTapped_ItNotifiesPresenter() {
self.setupPresenter()
self.bar.buttonTapped(self.bar)
XCTAssertTrue(self.presenter.onSendButtonPressedCalled)
}
// MARK: Delegation Tests
func testThat_WhenItemViewTapped_ItNotifiesDelegateThatNewItemReceivedFocus() {
self.setupDelegate()
let item = MockInputItem()
self.bar.inputItemViewTapped(createItemView(inputItem: item))
XCTAssertTrue(self.delegateStrong.inputBarDidReceiveFocusOnItemCalled)
XCTAssertTrue(self.delegateStrong.focusedItem === item)
}
func testThat_WhenTextViewDidBeginEditing_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.textViewDidBeginEditing(self.bar.textView)
XCTAssertTrue(self.delegateStrong.inputBarDidBeginEditingCalled)
}
func testThat_WhenTextViewDidEndEditing_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.textViewDidEndEditing(self.bar.textView)
XCTAssertTrue(self.delegateStrong.inputBarDidEndEditingCalled)
}
func testThat_WhenTextViewDidChangeText_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.inputText = "text"
self.bar.textViewDidChange(self.bar.textView)
XCTAssertTrue(self.delegateStrong.inputBarDidChangeTextCalled)
}
func testThat_WhenExpandableTextViewPlaceholderIsShown_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.expandableTextViewDidShowPlaceholder(self.bar.textView)
XCTAssertTrue(self.delegateStrong.inputBarDidShowPlaceholderCalled)
}
func testThat_WhenExpandableTextViewPlaceholderIsHidden_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.expandableTextViewDidHidePlaceholder(self.bar.textView)
XCTAssertTrue(self.delegateStrong.inputBarDidHidePlaceholderCalled)
}
func testThat_WhenSendButtonTapped_ItNotifiesDelegate() {
self.setupDelegate()
self.bar.buttonTapped(self.bar)
XCTAssertTrue(self.delegateStrong.inputBarSendButtonPressedCalled)
}
func testThat_WhenInputTextChangedAndCustomStateUpdateClosureProvided_BarUpdatesSendButtonStateAccordingly() {
var closureCalled = false
self.bar.shouldEnableSendButton = { (_) in
closureCalled = true
return false
}
self.bar.inputText = " "
self.bar.textViewDidChange(self.bar.textView)
XCTAssertTrue(closureCalled)
XCTAssertFalse(self.bar.sendButton.isEnabled)
}
func testThat_WhenItemViewTapped_ItReceivesFocuesByDefault() {
self.setupPresenter()
let item = MockInputItem()
self.bar.inputItemViewTapped(createItemView(inputItem: item))
XCTAssertTrue(self.presenter.onDidReceiveFocusOnItemCalled)
XCTAssertTrue(self.presenter.itemThatReceivedFocus === item)
}
func testThat_WhenItemViewTappedAndDelegateAllowsFocusing_ItWillFocusTheItem() {
self.setupDelegate()
self.delegateStrong.inputBarShouldFocusOnItemResult = true
let item = MockInputItem()
self.bar.inputItemViewTapped(createItemView(inputItem: item))
XCTAssertTrue(self.delegateStrong.inputBarShouldFocusOnItemCalled)
XCTAssertTrue(self.delegateStrong.inputBarDidReceiveFocusOnItemCalled)
XCTAssertTrue(self.delegateStrong.focusedItem === item)
}
func testThat_GivenFocusedItemIsNil_WhenFocusOnItem_InputBarDidLoseFocusIsNotCalled() {
self.setupDelegate()
self.setupPresenter()
self.delegateStrong.inputBarShouldFocusOnItemResult = true
let item = MockInputItem()
self.presenter.focusedItem = nil
self.bar.focusOnInputItem(item)
XCTAssertFalse(self.delegateStrong.inputBarDidLoseFocusOnItemCalled)
XCTAssertTrue(self.delegateStrong.inputBarDidReceiveFocusOnItemCalled)
}
func testThat_GivenFocusedItemIsItem1_WhenFocusOnItem2_InputBarDidLoseFocusIsCalled() {
self.setupDelegate()
self.setupPresenter()
self.delegateStrong.inputBarShouldFocusOnItemResult = true
let item1 = MockInputItem()
let item2 = MockInputItem()
self.presenter.focusedItem = item1
self.bar.focusOnInputItem(item2)
XCTAssertTrue(self.delegateStrong.inputBarDidLoseFocusOnItemCalled)
XCTAssertTrue(self.delegateStrong.inputBarDidReceiveFocusOnItemCalled)
}
func testThat_WhenItemViewTappedAndDelegateDisallowsFocusing_ItWontFocusTheItem() {
self.setupDelegate()
self.delegateStrong.inputBarShouldFocusOnItemResult = false
let item = MockInputItem()
self.bar.inputItemViewTapped(createItemView(inputItem: item))
XCTAssertTrue(self.delegateStrong.inputBarShouldFocusOnItemCalled)
XCTAssertFalse(self.delegateStrong.inputBarDidReceiveFocusOnItemCalled)
}
func testThat_WhenTextViewGoingToBecomeEditable_ItBecomesEditableByDefault() {
self.setupPresenter()
self.simulateTapOnTextViewForDelegate(self.bar)
XCTAssertTrue(self.presenter.onDidBeginEditingCalled)
}
func testThat_WhenTextViewGoingToBecomeEditableAndDelegateAllowsIt_ItWillBeEditable() {
self.setupDelegate()
self.delegateStrong.inputBarShouldBeginTextEditingResult = true
self.simulateTapOnTextViewForDelegate(self.bar)
XCTAssertTrue(self.delegateStrong.inputBarShouldBeginTextEditingCalled)
XCTAssertTrue(self.delegateStrong.inputBarDidBeginEditingCalled)
}
func testThat_WhenTextViewGoingToBecomeEditableAndDelegateDisallowsIt_ItWontBeEditable() {
self.setupDelegate()
self.delegateStrong.inputBarShouldBeginTextEditingResult = false
self.simulateTapOnTextViewForDelegate(self.bar)
XCTAssertTrue(self.delegateStrong.inputBarShouldBeginTextEditingCalled)
XCTAssertFalse(self.delegateStrong.inputBarDidBeginEditingCalled)
}
}
class FakeChatInputBarPresenter: ChatInputBarPresenter {
var focusedItem: ChatInputItemProtocol?
weak var viewController: ChatInputBarPresentingController?
let chatInputBar: ChatInputBar
init(chatInputBar: ChatInputBar) {
self.chatInputBar = chatInputBar
self.chatInputBar.presenter = self
}
var onDidBeginEditingCalled = false
func onDidBeginEditing() {
self.onDidBeginEditingCalled = true
}
var onDidEndEditingCalled = false
func onDidEndEditing() {
self.onDidEndEditingCalled = true
}
var onSendButtonPressedCalled = false
func onSendButtonPressed() {
self.onSendButtonPressedCalled = true
}
var onDidReceiveFocusOnItemCalled = false
var itemThatReceivedFocus: ChatInputItemProtocol?
func onDidReceiveFocusOnItem(_ item: ChatInputItemProtocol) {
self.onDidReceiveFocusOnItemCalled = true
self.itemThatReceivedFocus = item
}
func onViewDidUpdate() {}
}
class FakeChatInputBarDelegate: ChatInputBarDelegate {
var inputBarShouldBeginTextEditingCalled = false
var inputBarShouldBeginTextEditingResult = true
func inputBarShouldBeginTextEditing(_ inputBar: ChatInputBar) -> Bool {
self.inputBarShouldBeginTextEditingCalled = true
return self.inputBarShouldBeginTextEditingResult
}
var inputBarDidBeginEditingCalled = false
func inputBarDidBeginEditing(_ inputBar: ChatInputBar) {
self.inputBarDidBeginEditingCalled = true
}
var inputBarDidEndEditingCalled = false
func inputBarDidEndEditing(_ inputBar: ChatInputBar) {
self.inputBarDidEndEditingCalled = true
}
var inputBarDidChangeTextCalled = false
func inputBarDidChangeText(_ inputBar: ChatInputBar) {
self.inputBarDidChangeTextCalled = true
}
var inputBarSendButtonPressedCalled = false
func inputBarSendButtonPressed(_ inputBar: ChatInputBar) {
self.inputBarSendButtonPressedCalled = true
}
var inputBarShouldFocusOnItemCalled = false
var inputBarShouldFocusOnItemResult = true
func inputBar(_ inputBar: ChatInputBar, shouldFocusOnItem item: ChatInputItemProtocol) -> Bool {
self.inputBarShouldFocusOnItemCalled = true
return self.inputBarShouldFocusOnItemResult
}
var inputBarDidLoseFocusOnItemCalled = false
func inputBar(_ inputBar: ChatInputBar, didLoseFocusOnItem item: ChatInputItemProtocol) {
self.inputBarDidLoseFocusOnItemCalled = true
}
var inputBarDidReceiveFocusOnItemCalled = false
var focusedItem: ChatInputItemProtocol?
func inputBar(_ inputBar: ChatInputBar, didReceiveFocusOnItem item: ChatInputItemProtocol) {
self.inputBarDidReceiveFocusOnItemCalled = true
self.focusedItem = item
}
var inputBarDidShowPlaceholderCalled = false
func inputBarDidShowPlaceholder(_ inputBar: ChatInputBar) {
self.inputBarDidShowPlaceholderCalled = true
}
var inputBarDidHidePlaceholderCalled = false
func inputBarDidHidePlaceholder(_ inputBar: ChatInputBar) {
self.inputBarDidHidePlaceholderCalled = true
}
}
| 37.497159 | 114 | 0.748163 |
21db4a1d3b116eb171dc1beabf996fc7ecc684a4 | 316 | //
// Person+Convenience.swift
// Pair
//
// Created by Tiffany Sakaguchi on 5/21/21.
//
import CoreData
extension Person {
@discardableResult convenience init(name: String, context: NSManagedObjectContext = CoreDataStack.context) {
self.init(context: context)
self.name = name
}
}
| 18.588235 | 112 | 0.670886 |
87ba5c2b3e065eca31db4cc134eaaf5d243d61a8 | 198 | // RUN: %target-parse-verify-swift
struct S {
init(a:Bool) {
return
}
init(b:Bool) {
return 1 // expected-error {{'nil' is the only return value permitted in an initializer}}
}
}
| 15.230769 | 93 | 0.621212 |
ed4ef99f2e305ca794ebebca4efbe057941da907 | 5,191 | //
// LineChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet
{
public var valueLabelOffset: CGPoint = CGPoint(x: 0, y: 0)
public var lineGradient: CGGradient?
@objc(LineChartMode)
public enum Mode: Int
{
case linear
case stepped
case cubicBezier
case horizontalBezier
}
private func initialize()
{
// default color
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
public required init()
{
super.init()
initialize()
}
public override init(entries: [ChartDataEntry]?, label: String?)
{
super.init(entries: entries, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The drawing mode for this line dataset
///
/// **default**: Linear
open var mode: Mode = Mode.linear
private var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
open var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue.clamped(to: 0.05...1)
}
}
/// The radius of the drawn circles.
open var circleRadius = CGFloat(8.0)
/// The hole radius of the drawn circles
open var circleHoleRadius = CGFloat(4.0)
open var circleColors = [NSUIColor]()
/// - Returns: The color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
open func getCircleColor(atIndex index: Int) -> NSUIColor?
{
let size = circleColors.count
let index = index % size
if index >= size
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
open func setCircleColor(_ color: NSUIColor)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(color)
}
open func setCircleColors(_ colors: NSUIColor...)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(contentsOf: colors)
}
/// Resets the circle-colors array and creates a new one
open func resetCircleColors(_ index: Int)
{
circleColors.removeAll(keepingCapacity: false)
}
/// If true, drawing circles is enabled
open var drawCirclesEnabled = true
/// `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var isDrawCirclesEnabled: Bool { return drawCirclesEnabled }
/// The color of the inner circle (the circle-hole).
open var circleHoleColor: NSUIColor? = NSUIColor.white
/// `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var drawCircleHoleEnabled = true
/// `true` if drawing the circle-holes is enabled, `false` ifnot.
open var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled }
/// This is how much (in pixels) into the dash pattern are we starting from.
open var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var lineDashLengths: [CGFloat]?
/// Line cap type, default is CGLineCap.Butt
open var lineCapType = CGLineCap.butt
/// formatter for customizing the position of the fill-line
private var _fillFormatter: IFillFormatter = DefaultFillFormatter()
/// Sets a custom IFillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
open var fillFormatter: IFillFormatter?
{
get
{
return _fillFormatter
}
set
{
_fillFormatter = newValue ?? DefaultFillFormatter()
}
}
// MARK: NSCopying
open override func copy(with zone: NSZone? = nil) -> Any
{
let copy = super.copy(with: zone) as! LineChartDataSet
copy.circleColors = circleColors
copy.circleHoleColor = circleHoleColor
copy.circleRadius = circleRadius
copy.circleHoleRadius = circleHoleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.lineCapType = lineCapType
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCircleHoleEnabled = drawCircleHoleEnabled
copy.mode = mode
copy._fillFormatter = _fillFormatter
return copy
}
}
| 29.327684 | 155 | 0.624735 |
62455f204fcc23a2bb71508ec7a326c56b97b7a3 | 2,799 | /// Copyright (c) 2018 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 Foundation
import Firebase
struct Names { //let this be DB of names (list too). Gets initialized to app when launched.
//Maybe we won't move db reference to larger class.
let ref: DatabaseReference?
let key: String
let name: String
let addedByUser: String
init(name: String, addedByUser: String, key: String = "") {
self.ref = nil
self.key = key
self.name = name
self.addedByUser = addedByUser
//have points too.
//Maybe bio as well. or add this info into groceryitme modle.
}
init?(snapshot: DataSnapshot) {
guard
let value = snapshot.value as? [String: AnyObject],
let name = value["name"] as? String,
let addedByUser = value["addedByUser"] as? String
else {
return nil
}
self.ref = snapshot.ref
self.key = snapshot.key
self.name = name
self.addedByUser = addedByUser
}
func toAnyObject() -> Any {
return [
"name": name,
"addedByUser": addedByUser
]
}
}
| 39.422535 | 91 | 0.676313 |
3aba89d3af4ecab408dfb854110b9ac286883945 | 928 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//771. Jewels and Stones
//You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
//The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
//Example 1:
//Input: J = "aA", S = "aAAbbbb"
//Output: 3
//Example 2:
//Input: J = "z", S = "ZZ"
//Output: 0
//Note:
//S and J will consist of letters and have length at most 50.
//The characters in J are distinct.
//class Solution {
// func numJewelsInStones(_ J: String, _ S: String) -> Int {
// }
//}
// Time Is Money | 40.347826 | 231 | 0.71444 |
67904163a6abb6675727b44c094b74dcb20bc14e | 1,515 | //
// Library.swift
// CoreImageVideo
//
// Created by Chris Eidhof on 03/04/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import Foundation
import AVFoundation
import GLKit
let pixelBufferDict: [String:AnyObject] =
[kCVPixelBufferPixelFormatTypeKey as String: NSNumber(unsignedInt: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)]
class VideoSampleBufferSource: NSObject {
lazy var displayLink: CADisplayLink =
CADisplayLink(target: self, selector: "displayLinkDidRefresh:")
let videoOutput: AVPlayerItemVideoOutput
let consumer: CVPixelBuffer -> ()
let player: AVPlayer
init?(url: NSURL, consumer callback: CVPixelBuffer -> ()) {
player = AVPlayer(URL: url)
consumer = callback
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: pixelBufferDict)
player.currentItem!.addOutput(videoOutput)
super.init()
start()
player.play()
}
func start() {
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
func displayLinkDidRefresh(link: CADisplayLink) {
let itemTime = videoOutput.itemTimeForHostTime(CACurrentMediaTime())
if videoOutput.hasNewPixelBufferForItemTime(itemTime) {
var presentationItemTime = kCMTimeZero
let pixelBuffer = videoOutput.copyPixelBufferForItemTime(itemTime, itemTimeForDisplay: &presentationItemTime)
consumer(pixelBuffer!)
}
}
} | 29.705882 | 121 | 0.69835 |
697b09b5074241d71d75c4967fe536a6479973b2 | 297 | //
// ExtensionDeclSyntax+Extensions.swift
// SwiftSyntax
//
// Created by Luciano Almeida on 28/03/19.
//
import SwiftSyntax
extension ExtensionDeclSyntax {
var isPublicExtension: Bool {
return modifiers?.contains(where: { $0.name.tokenKind == .publicKeyword }) ?? false
}
}
| 19.8 | 91 | 0.690236 |
d564372ee57af88bec7f9903dcbefaaa352fb3a4 | 2,856 | //
// QuestionsTableViewController.swift
// OCRApp
//
// Created by Zhanibek Lukpanov on 08.06.2020.
// Copyright © 2020 Zhanibek Lukpanov. All rights reserved.
//
import UIKit
final class QuestionsTableViewController: UITableViewController, ExpandableHeaderViewDelegate {
var secitonsArray = [
Section(title: "Questions", items: ["Item","Item","Item","Item","Item"], expanded: false),
Section(title: "FAQ", items: ["Item","Item","Item","Item","Item"], expanded: false),
Section(title: "Contacts", items: ["Item","Item","Item","Item","Item"], expanded: true)
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return secitonsArray.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return secitonsArray[section].items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = secitonsArray[indexPath.section].items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 57
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if secitonsArray[indexPath.section].expanded {
return 44
}
return 0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 3
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = ExpandableHeaderView()
header.setup(with: secitonsArray[section].title, section: section, delegate: self)
return header
}
// MARK: - Methods
func toggleSection(section: Int) {
secitonsArray[section].expanded = !secitonsArray[section].expanded
tableView.beginUpdates()
for row in 0..<secitonsArray[section].items.count {
tableView.reloadRows(at: [IndexPath(row: row, section: section)], with: .automatic)
}
tableView.endUpdates()
}
}
| 34.409639 | 109 | 0.661064 |
fc567b560e36248c34f72f1d5abc29390ad41513 | 5,601 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
public class EPA_FdV_AUTHZ_GLIST_PQ : EPA_FdV_AUTHZ_ANY
{
/**
* This is the start-value of the generated list.
*/
var head:EPA_FdV_AUTHZ_PQ=EPA_FdV_AUTHZ_PQ()
/**
* The difference between one value and its previous
* different value. For example, to generate the sequence
* (1; 4; 7; 10; 13; ...) the increment is 3; likewise to
* generate the sequence (1; 1; 4; 4; 7; 7; 10; 10; 13;
* 13; ...) the increment is also 3.
*/
var increment:EPA_FdV_AUTHZ_PQ=EPA_FdV_AUTHZ_PQ()
/**
* If non-NULL, specifies that the sequence alternates,
* i.e., after this many increments, the sequence item
* values roll over to start from the initial sequence
* item value. For example, the sequence (1; 2; 3; 1; 2;
* 3; 1; 2; 3; ...) has period 3; also the sequence
* (1; 1; 2; 2; 3; 3; 1; 1; 2; 2; 3; 3; ...) has period
* 3 too.
*/
var period:NSNumber?
/**
* The integer by which the index for the sequence is
* divided, effectively the number of times the sequence
* generates the same sequence item value before
* incrementing to the next sequence item value. For
* example, to generate the sequence (1; 1; 1; 2; 2; 2; 3; 3;
* 3; ...) the denominator is 3.
*/
var denominator:NSNumber?
public required init()
{
super.init()
}
public override func loadWithXml(__node: DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler)
{
super.loadWithXml(__node:__node, __request: __request)
if EPA_FdV_AUTHZ_Helper.hasAttribute(node: __node, name:"period", url:"")
{
self.period = EPA_FdV_AUTHZ_Helper.getNumber(stringNumber: EPA_FdV_AUTHZ_Helper.getAttribute(node: __node, name:"period", url:"")!.stringValue, isDecimal:false)!
}
if EPA_FdV_AUTHZ_Helper.hasAttribute(node: __node, name:"denominator", url:"")
{
self.denominator = EPA_FdV_AUTHZ_Helper.getNumber(stringNumber: EPA_FdV_AUTHZ_Helper.getAttribute(node: __node, name:"denominator", url:"")!.stringValue, isDecimal:false)!
}
}
public override func serialize(__parent:DDXMLElement, __request:EPA_FdV_AUTHZ_RequestResultHandler)
{
super.serialize(__parent:__parent, __request:__request)
let __headItemElement=__request.writeElement(obj: head, type:EPA_FdV_AUTHZ_PQ.self, name:"head", URI:"urn:hl7-org:v3", parent:__parent, skipNullProperty:false)
if __headItemElement != nil
{
self.head.serialize(__parent: __headItemElement!, __request: __request);
}
let __incrementItemElement=__request.writeElement(obj: increment, type:EPA_FdV_AUTHZ_PQ.self, name:"increment", URI:"urn:hl7-org:v3", parent:__parent, skipNullProperty:false)
if __incrementItemElement != nil
{
self.increment.serialize(__parent: __incrementItemElement!, __request: __request);
}
if self.period != nil
{
let __periodItemElement=__request.addAttribute(name: "period", URI:"", stringValue:"", element:__parent)
__periodItemElement.stringValue = EPA_FdV_AUTHZ_Helper.getStringFromNumber(number: self.period!);
}
if self.denominator != nil
{
let __denominatorItemElement=__request.addAttribute(name: "denominator", URI:"", stringValue:"", element:__parent)
__denominatorItemElement.stringValue = EPA_FdV_AUTHZ_Helper.getStringFromNumber(number: self.denominator!);
}
}
public override func loadProperty(__node: DDXMLElement, __request: EPA_FdV_AUTHZ_RequestResultHandler ) -> Bool
{
if __node.localName=="head"
{
if EPA_FdV_AUTHZ_Helper.isValue(node:__node, name: "head")
{
self.head = try! __request.createObject(node: __node, type:EPA_FdV_AUTHZ_PQ.self) as! EPA_FdV_AUTHZ_PQ
}
return true;
}
if __node.localName=="increment"
{
if EPA_FdV_AUTHZ_Helper.isValue(node:__node, name: "increment")
{
self.increment = try! __request.createObject(node: __node, type:EPA_FdV_AUTHZ_PQ.self) as! EPA_FdV_AUTHZ_PQ
}
return true;
}
if __node.localName=="period"
{
if EPA_FdV_AUTHZ_Helper.isValue(node:__node, name: "period")
{
self.period = EPA_FdV_AUTHZ_Helper.getNumber(stringNumber: __node.stringValue, isDecimal:false)!
}
return true;
}
if __node.localName=="denominator"
{
if EPA_FdV_AUTHZ_Helper.isValue(node:__node, name: "denominator")
{
self.denominator = EPA_FdV_AUTHZ_Helper.getNumber(stringNumber: __node.stringValue, isDecimal:false)!
}
return true;
}
return super.loadProperty(__node:__node, __request:__request)
}
} | 41.183824 | 184 | 0.581325 |
b9fc24aae3f6ff93898188724efddde8afec7352 | 427 | import PackageDescription
let package = Package(
name: "People",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 5),
.Package(url: "https://github.com/vapor/postgresql-provider", majorVersion: 1, minor: 0)
],
exclude: [
"Config",
"Database",
"Localization",
"Public",
"Resources",
"Tests",
]
)
| 23.722222 | 96 | 0.557377 |
1e9aa57aedd77cccc51fad8c4df7b8f8743fd748 | 3,756 | func tokenize(_ stream: String) throws -> [Token] {
var tokens: [Token] = []
var currentIndex = stream.startIndex
while currentIndex != stream.endIndex {
// Process new lines as a special case to merge repeated new lines.
if stream[currentIndex].isNewline {
tokens.append(Token(kind: .newline, value: stream[currentIndex ... currentIndex]))
let skipCount = stream
.suffix(from: currentIndex)
.prefix(while: { $0.isNewline })
.count
currentIndex = stream.index(currentIndex, offsetBy: skipCount)
continue
}
// Skip other whitespace characters.
if stream[currentIndex].isWhitespace {
currentIndex = stream.index(after: currentIndex)
continue
}
// Skip comments.
if stream.suffix(from: currentIndex).starts(with: "//") {
let skipCount = stream
.suffix(from: currentIndex)
.prefix(while: { !$0.isNewline })
.count
currentIndex = stream.index(currentIndex, offsetBy: skipCount)
continue
}
// Process keywords and identifiers.
if stream[currentIndex].isIdentifier {
let substring = stream
.suffix(from: currentIndex)
.prefix(while: { $0.isIdentifier })
let token: Token
switch substring {
case "type": token = Token(kind: .type, value: substring)
case "init": token = Token(kind: ._init, value: substring)
case "decl": token = Token(kind: .decl, value: substring)
case "rule": token = Token(kind: .rule, value: substring)
default : token = Token(kind: .identifier, value: substring)
}
tokens.append(token)
currentIndex = stream.index(currentIndex, offsetBy: substring.count)
continue
}
// Process variable identifiers.
if stream[currentIndex] == "$" {
let tokenCharacterCount = 1 + stream
.suffix(from: stream.index(after: currentIndex))
.prefix(while: { $0.isIdentifier })
.count
let nextIndex = stream.index(currentIndex, offsetBy: tokenCharacterCount)
tokens.append(Token(kind: .variableIdentifier, value: stream[currentIndex ..< nextIndex]))
currentIndex = nextIndex
continue
}
// Process 2-characters tokens.
if stream.distance(from: currentIndex, to: stream.endIndex) >= 2 {
let substring = stream[currentIndex ..< stream.index(currentIndex, offsetBy: 2)]
var token: Token? = nil
switch substring {
case "=>": token = Token(kind: .thickArrow, value: substring)
case "->": token = Token(kind: .arrow, value: substring)
case "::": token = Token(kind: .doubleColon, value: substring)
default : break
}
if token != nil {
tokens.append(token!)
currentIndex = stream.index(currentIndex, offsetBy: 2)
continue
}
}
// Process 1-character tokens.
let substring = stream[currentIndex ... currentIndex]
let token: Token
switch stream[currentIndex] {
case ",": token = Token(kind: .comma, value: substring)
case ";": token = Token(kind: .semicolon, value: substring)
case "(": token = Token(kind: .leftParen, value: substring)
case ")": token = Token(kind: .rightParen, value: substring)
case "=": token = Token(kind: .equal, value: substring)
case "|": token = Token(kind: .pipe, value: substring)
case ":": token = Token(kind: .colon, value: substring)
default : token = Token(kind: .error, value: substring)
}
tokens.append(token)
currentIndex = stream.index(after: currentIndex)
}
return tokens + [Token(kind: .eof, value: stream[stream.endIndex ..< stream.endIndex])]
}
extension Character {
var isIdentifier: Bool { self == "_" || self.isLetter || self.isNumber }
}
| 32.947368 | 96 | 0.636848 |
56acfa2cc149fa91e7c784f1c1e3bdf14bf7e136 | 6,368 | //
// NewDiskViewController.swift
// MacMulator
//
// Created by Vale on 23/02/21.
//
import Cocoa
class NewDiskViewController: NSViewController, NSTextFieldDelegate {
enum Mode {
case ADD
case EDIT
}
@IBOutlet weak var titleField: NSTextField!
@IBOutlet weak var diskSizeTextField: NSTextField!
@IBOutlet weak var diskSizeStepper: NSStepper!
@IBOutlet weak var diskSizeSlider: NSSlider!
@IBOutlet weak var minDiskSizeLabel: NSTextField!
@IBOutlet weak var maxDiskSizeLabel: NSTextField!
@IBOutlet weak var useCow: NSButton!
@IBOutlet weak var okButton: NSButton!
var oldVirtualDrive: VirtualDrive?
var newVirtualDrive: VirtualDrive?
var parentController: EditVMViewControllerHardware?;
var isVisible: Bool = false;
var mode: Mode = Mode.ADD;
func setVirtualDrive(_ virtualDrive: VirtualDrive) {
self.newVirtualDrive = virtualDrive;
self.oldVirtualDrive = virtualDrive.clone();
}
func setMode(_ mode: Mode) {
self.mode = mode;
}
func setparentController(_ parentController: EditVMViewControllerHardware) {
self.parentController = parentController;
}
fileprivate func updateView() {
if let parentController = self.parentController {
if let virtualMachine = parentController.virtualMachine {
if let newVirtualDrive = self.newVirtualDrive {
diskSizeSlider.intValue = newVirtualDrive.size;
diskSizeStepper.intValue = newVirtualDrive.size;
diskSizeTextField.intValue = newVirtualDrive.size
if (newVirtualDrive.format == QemuConstants.FORMAT_QCOW2) {
useCow.intValue = 1;
} else {
useCow.intValue = 0;
}
if (mode == Mode.ADD) {
titleField.stringValue = "Create new disk";
} else {
titleField.stringValue = "Edit " + newVirtualDrive.name;
}
let minDiskSize = Utils.getMinDiskSizeForSubType(virtualMachine.os, virtualMachine.subtype);
let maxDiskSize = Utils.getMaxDiskSizeForSubType(virtualMachine.os, virtualMachine.subtype);
minDiskSizeLabel.stringValue = Utils.formatDisk(Int32(minDiskSize));
maxDiskSizeLabel.stringValue = Utils.formatDisk(Int32(maxDiskSize));
diskSizeStepper.minValue = Double(minDiskSize);
diskSizeStepper.maxValue = Double(maxDiskSize);
diskSizeSlider.minValue = Double(minDiskSize);
diskSizeSlider.maxValue = Double(maxDiskSize);
}
}
}
}
@IBAction func cowCheckboxChanged(_ sender: Any) {
if useCow.intValue == 1 {
newVirtualDrive?.format = QemuConstants.FORMAT_QCOW2;
} else {
newVirtualDrive?.format = QemuConstants.FORMAT_RAW;
}
}
@IBAction func cancelButtonPressed(_ sender: Any) {
self.dismiss(self);
}
@IBAction func sliderChanged(_ sender: Any) {
if (sender as? NSObject == diskSizeSlider) {
if let newVirtualDrive = self.newVirtualDrive {
newVirtualDrive.size = diskSizeSlider.intValue;
diskSizeTextField.intValue = diskSizeSlider.intValue;
diskSizeStepper.intValue = diskSizeSlider.intValue;
}
}
}
@IBAction func stepperChanged(_ sender: Any) {
if (sender as? NSObject == diskSizeStepper) {
if let newVirtualDrive = self.newVirtualDrive {
newVirtualDrive.size = diskSizeStepper.intValue
diskSizeTextField.intValue = diskSizeStepper.intValue;
diskSizeSlider.intValue = diskSizeStepper.intValue;
}
}
}
override func viewWillAppear() {
updateView();
}
override func viewDidAppear() {
isVisible = true;
}
override func viewDidDisappear() {
isVisible = false;
}
func controlTextDidEndEditing(_ notification: Notification) {
if (notification.object as! NSTextField) == diskSizeTextField && self.isVisible {
if let newVirtualDrive = self.newVirtualDrive {
let size = diskSizeTextField.intValue;
newVirtualDrive.size = size;
diskSizeStepper.intValue = size;
diskSizeSlider.intValue = size;
if let parentController = self.parentController {
if let virtualMachine = parentController.virtualMachine {
if size < Utils.getMinDiskSizeForSubType(virtualMachine.os, virtualMachine.subtype) || size > Utils.getMaxDiskSizeForSubType(virtualMachine.os, virtualMachine.subtype) {
diskSizeStepper.isEnabled = false;
diskSizeSlider.isEnabled = false;
} else {
diskSizeStepper.isEnabled = true;
diskSizeSlider.isEnabled = true;
}
}
}
}
}
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if (segue.identifier == MacMulatorConstants.CREATE_DISK_FILE_SEGUE) {
if let newVirtualDrive = self.newVirtualDrive {
let destinationController = segue.destinationController as! CreateDiskFileViewController;
destinationController.setNewVirtualDrive(newVirtualDrive);
destinationController.setOldVirtualDrive((mode == Mode.EDIT) ? oldVirtualDrive : nil);
destinationController.setParentController(self);
}
}
}
func diskCreated() {
if let newVirtualDrive = self.newVirtualDrive {
if mode == Mode.ADD {
parentController?.addVirtualDrive(newVirtualDrive);
}
else {
parentController?.reloadDrives();
}
}
self.dismiss(self);
}
}
| 37.239766 | 193 | 0.582443 |
fb63a9573d7aed0e088e8e0226c05d326164f34e | 759 | //
// main.swift
// firstUniqChar
//
// Created by wangwei on 2021/6/23.
//
import Foundation
/*
剑指 Offer 50. 第一个只出现一次的字符
https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/submissions/
可以使用数组存储个数节省空间。两次遍历字符串。
*/
class Solution {
func firstUniqChar(_ s: String) -> Character {
var dict: [String.Element: Int] = Dictionary()
for char in s {
let count = dict[char]
dict[char] = (count ?? 0) + 1
}
for char in s {
let count = dict[char]
if count == 1 {
return Character(extendedGraphemeClusterLiteral: char)
}
}
return Character(" ")
}
}
let sol = Solution()
print(sol.firstUniqChar("abaccdeff"))
| 23 | 88 | 0.571805 |
f553dd9ebbad7a9b2b078f284716ba5b1f2af2e9 | 23,355 | //
// INIParser.swift
// INISerialization
//
// Created by Gwynne Raskind on 12/5/17.
//
import Foundation
internal class INIParser {
typealias Lex = () throws -> ParsedToken?
let options: INISerialization.ReadingOptions
let tokenizer: Lex
// - MARK: "External" interface
static func parse(_ text: String, options: INISerialization.ReadingOptions = []) throws -> INIUnorderedObject {
var tokenizer = INITokenizer(text)
return try INIParser(options: options) { try tokenizer.nextToken() }.parse()
}
// - MARK: Guts
private init(options: INISerialization.ReadingOptions, lexer: @escaping Lex) {
self.options = options
self.tokenizer = lexer
}
enum State: Equatable {
case inSection(name: String?) // A section header was read and we're looking for keys, or top level
case readingSectionHeader // Saw a [ but nothing else
case finishingSectionHeader(name: String) // Saw a section name after [, waiting for ]
case awaitingSectionStart(name: String?) // Got ], waiting for comment or eol
case readingKey(key: String) // Read a key but no separator
case readingValue(key: String, valueSoFar: [Token]) // Read a separator and are gathering value fragments
case readingComment(tokens: [Token]) // Read a comment marker in a valid place and are waiting for newline
static func ==(lhs: State, rhs: State) -> Bool {
switch (lhs, rhs) {
case (.readingSectionHeader, .readingSectionHeader): return true
case (.finishingSectionHeader(let l), .finishingSectionHeader(let r)): return l == r
case (.awaitingSectionStart(let l), .awaitingSectionStart(let r)): return l == r
case (.inSection(let l), .inSection(let r)): return l == r
case (.readingKey(let l), .readingKey(let r)): return l == r
case (.readingComment(let l), .readingComment(let r)): return l == r
case (.readingValue(let k1, let v1), .readingValue(let k2, let v2)): return k1 == k2 && v1 == v2
default: return false
}
}
func `is`(rhs: State) -> Bool {
switch (self, rhs) {
case (.readingSectionHeader, .readingSectionHeader),
(.finishingSectionHeader, .finishingSectionHeader),
(.awaitingSectionStart, .awaitingSectionStart),
(.inSection, .inSection),
(.readingKey, .readingKey),
(.readingValue, .readingValue),
(.readingComment, .readingComment):
return true
default:
return false
}
}
}
func parse() throws -> INIUnorderedObject {
var lastLoc: String.Index = String.Index(encodedOffset: 0)
var lastLine: UInt = 0
while let tok = try tokenizer() {
lastLoc = tok.position
lastLine = tok.line
switch tok.data {
case .commentMarker: try handleCommentMarker(tok)
case .newline: try handleNewline(tok)
case .sectionOpen: try handleSectionOpen(tok)
case .sectionClose: try handleSectionClose(tok)
case .separator: try handleSeparator(tok)
case .quotedString: try handleQuotedString(tok)
case .signedInteger, .unsignedInteger: try handleInteger(tok)
case .decimal: try handleDecimal(tok)
case .bareTrue, .bareFalse: try handleBoolean(tok)
case .whitespace: try handleWhitespace(tok)
case .identifier(let str): try handleIdentifier(tok, String(str))
case .text: try handleText(tok)
}
// print("Token: \(tok.data)\nStack: " + stack.map { $0.debugDescription }.joined(separator: ", "))
}
// Implicit newline at the end of input to pop anything still on the stack
try handleNewline(.init(position: lastLoc, line: lastLine, data: .newline))
return result
}
var stack: [State] = [.inSection(name: nil)]
var line: UInt = 1
var result: INIUnorderedObject = [:]
var topState: State { return stack.last! }
func popState() { _ = stack.popLast() }
func pushState(_ newState: State) { stack.append(newState) }
func replaceState(with newState: State) {
popState()
pushState(newState)
}
func addStateToken(_ token: ParsedToken) {
switch topState {
case .readingValue(let key, let valuesSoFar): replaceState(with: .readingValue(key: key, valueSoFar: valuesSoFar + [token.data]))
case .readingComment(let tokens): replaceState(with: .readingComment(tokens: tokens + [token.data]))
default: fatalError("Can only add tokens to values or comments")
}
}
func setTrueValue(_ value: Any, forKey key: String) {
guard case .inSection(let maybeSect) = stack.first! else { fatalError("base state is not a section state") }
let finalKey = options.contains(.lowercaseKeys) ? key.lowercased() : (options.contains(.uppercaseKeys) ? key.uppercased() : key)
if let sect = maybeSect {
let finalSect = options.contains(.lowercaseKeys) ? sect.lowercased() : (options.contains(.uppercaseKeys) ? sect.uppercased() : sect)
if var existing = result[finalSect] as? INIUnorderedObject {
existing[finalKey] = value
result[finalSect] = existing
} else {
result[finalSect] = [finalKey: value]
}
} else {
result[finalKey] = value
}
}
func recordKeyAndValue(key: String, value: [Token]?) throws {
if let values = value {
// This is a not-terribly-efficient trim()
func dropWhite(_ tok: Token) -> Bool { if case .whitespace = tok { return true } else { return false } }
let filteredValues = values.drop(while: dropWhite).reversed().drop(while: dropWhite).reversed()
if filteredValues.count == 0 {
setTrueValue("", forKey: key)
} else if filteredValues.count == 1 {
switch filteredValues.first! {
case .commentMarker(let content): setTrueValue(String(content), forKey: key)
case .newline: fatalError("newline token should never appear in value token list")
case .sectionOpen: setTrueValue("[", forKey: key)
case .sectionClose: setTrueValue("]", forKey: key)
case .separator: setTrueValue("=", forKey: key)
case .quotedString(let str, _): setTrueValue(String(str), forKey: key)
case .signedInteger(let str): setTrueValue(options.contains(.detectNumericValues) ? Int(str)! : String(str), forKey: key)
case .unsignedInteger(let str): setTrueValue(options.contains(.detectNumericValues) ? UInt(str)! : String(str), forKey: key)
case .decimal(let str): setTrueValue(options.contains(.detectNumericValues) ? Double(str)! : String(str), forKey: key)
case .bareFalse(let str): setTrueValue(options.contains(.detectBooleanValues) ? false : String(str), forKey: key)
case .bareTrue(let str): setTrueValue(options.contains(.detectBooleanValues) ? true : String(str), forKey: key)
case .whitespace: fatalError("sole whitespace token should have been filtered out")
case .identifier(let str): setTrueValue(String(str), forKey: key)
case .text(let str): setTrueValue(String(str), forKey: key)
}
} else {
var intermediate = ""
for token in filteredValues {
switch token {
case .commentMarker(let content): intermediate += content
case .newline: fatalError("newline token should never appear in value token list")
case .sectionOpen: intermediate += "["
case .sectionClose: intermediate += "]"
case .separator: intermediate += "="
case .quotedString(let str, let isDouble): // When a quoted string appears in a set of value tokens, the quotes lose their magic
intermediate += (isDouble ? "\"" : "'") + str + (isDouble ? "\"" : "'")
case .signedInteger(let str): intermediate += str
case .unsignedInteger(let str): intermediate += str
case .decimal(let str): intermediate += str
case .bareFalse(let str): intermediate += str
case .bareTrue(let str): intermediate += str
case .whitespace(let str): intermediate += str
case .identifier(let str): intermediate += str
case .text(let str): intermediate += str
}
}
setTrueValue(intermediate, forKey: key)
}
} else {
setTrueValue("", forKey: key)
}
// print("KEY: \(key)\nVALUE: \(value ?? [.text("MISSING")])")
}
func handleCommentMarker(_ tok: ParsedToken) throws {
// inSection -> readingComment
// readingSectionHeader -> ERROR
// finishingSectionHeader -> ERROR
// awaitingSectionStart -> readingComment
// readingKey -> ERROR, ^readingComment
// readingValue -> readingValue, ^readingComment
// readingComment -> readingComment
guard case .commentMarker(let marker) = tok.data else { fatalError("not a comment marker") }
if marker == "#" && !options.contains(.allowHashComments) {
try handleText(tok) // If we're not allowing hash comments, a hash marker is treated as a text node
return
}
switch topState {
case .inSection: // Comment marker at top level starts a comment
pushState(.readingComment(tokens: [tok.data]))
case .readingSectionHeader, .finishingSectionHeader:
throw INISerialization.SerializationError.commentInSectionHeader(line: tok.line)
case .awaitingSectionStart:
if !options.contains(.allowTrailingComments) {
throw INISerialization.SerializationError.commentInSectionHeader(line: tok.line)
}
replaceState(with: .readingComment(tokens: [tok.data]))
case .readingKey(let key):
if !options.contains(.allowTrailingComments) {
throw INISerialization.SerializationError.commentInterruptedKey(line: tok.line)
}
if !options.contains(.allowMissingValues) {
throw INISerialization.SerializationError.incompleteKey(line: tok.line)
}
try recordKeyAndValue(key: key, value: nil)
case .readingValue(let key, let value):
if !options.contains(.allowTrailingComments) {
addStateToken(tok)
} else {
try recordKeyAndValue(key: key, value: value)
replaceState(with: .readingComment(tokens: [tok.data]))
}
case .readingComment:
addStateToken(tok)
}
}
func handleNewline(_ tok: ParsedToken) throws {
// inSection -> inSection
// readingSectionHeader -> ERROR
// finishingSectionHeader -> ERROR
// awaitingSectionStart -> ^inSection
// readingKey -> ERROR, ^
// readingValue -> ERROR, ^
// readingComment -> ^
switch topState {
case .inSection: // Newlines always valid at top level
break
case .readingSectionHeader, .finishingSectionHeader: // Newline never valid while reading section name or closer
throw INISerialization.SerializationError.incompleteSectionHeader(line: tok.line)
case .awaitingSectionStart(let name): // Newline is valid when about to start a section
popState() // remove the await
replaceState(with: .inSection(name: name)) // Replace top level state with current
case .readingKey(let key):
if !options.contains(.allowMissingValues) { // To accept EOL here, must be allowing missing values
throw INISerialization.SerializationError.incompleteKey(line: tok.line)
}
try recordKeyAndValue(key: key, value: nil)
popState() // Pop the .ReadingKey state
case .readingValue(let key, let value):
try recordKeyAndValue(key: key, value: value) // Ended the value
popState() // Pop the .ReadingValue state
case .readingComment: // Ends the comment
// We don't do anything with comments, so just pop it into nowhere
popState()
}
}
func handleSectionOpen(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, readingKey -> ERROR
// inSection -> ^readingSectionHeader
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .inSection: // Section open at top level may be valid
if !options.contains(.detectSections) { // .detectSections must be set to use sections
throw INISerialization.SerializationError.sectionsNotAllowed(line: tok.line) // hard error at top level
}
pushState(.readingSectionHeader)
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .readingKey: // If already reading/read a section header or key, syntax error
throw INISerialization.SerializationError.tooManyBrackets(line: tok.line)
case .readingValue, .readingComment: // Section header start while reading value or comment becomes part of the token list
addStateToken(tok)
}
}
func handleSectionClose(_ tok: ParsedToken) throws {
// awaitingSectionStart, inSection, readingKey -> ERROR
// readingSectionHeader -> ERROR, ^awaitingSectionStart
// finishingSectionHeader -> ^awaitingSectionStart
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader: // Section close with no section name may be valid
if !options.contains(.allowSectionReset) { // .allowSectionReset must be set to reset section name
throw INISerialization.SerializationError.tooManyBrackets(line: tok.line)
}
replaceState(with: .awaitingSectionStart(name: nil)) // Add the await so comments can be processed and no more syntax happens
case .finishingSectionHeader(let name): // Section close with section name starts new section
replaceState(with: .awaitingSectionStart(name: name)) // Go to waiting for comment/newline
case .awaitingSectionStart, .inSection, .readingKey: // Section closer when awaiting, at section level, or reading key is syntax error
throw INISerialization.SerializationError.tooManyBrackets(line: tok.line)
case .readingValue, .readingComment: // Section header closer while reading value or comment becomes part of the token list
addStateToken(tok)
}
}
func handleSeparator(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection -> ERROR
// readingKey -> ^readingValue
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .inSection: // Separator at top or section header is syntax error
throw INISerialization.SerializationError.noKeyAvailable(line: tok.line)
case .readingKey(let key): // Separator while reading key starts value read
replaceState(with: .readingValue(key: key, valueSoFar: [])) // Push an empty value state
case .readingValue, .readingComment: // Separator while reading value or comment becomes part of the token list
addStateToken(tok)
}
}
func handleQuotedString(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .inSection, .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .readingKey: // In top, section, header, key is error
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Quoted string while reading value or comment is valid
addStateToken(tok)
}
}
func handleInteger(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .inSection, .readingKey: // Syntax error if not reading value
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Integer while reading value or comment is valid
addStateToken(tok)
}
}
func handleDecimal(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .inSection, .readingKey: // Syntax error if not reading value
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Decimal while reading value or comment is valid
addStateToken(tok)
}
}
func handleBoolean(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .inSection, .readingKey: // Syntax error if not reading value
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Boolean while reading value or comment is valid
addStateToken(tok)
}
}
func handleWhitespace(_ tok: ParsedToken) throws {
// readingSectionHeader, finishingSectionHeader, awaitingSectionStart, inSection, readingKey ->
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart, .inSection, .readingKey: // Whitespace is ignored most places
break
case .readingValue, .readingComment: // Whitespace while reading value or comment is significant
addStateToken(tok)
}
}
func handleIdentifier(_ tok: ParsedToken, _ str: String) throws {
// inSection -> readingKey
// readingSectionHeader -> ^finishingSectionHeader
// finishingSectionHeader, awaitingSectionStart, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .inSection: // Identifier at top level starts a key
pushState(.readingKey(key: str)) // do NOT pop top-level state
case .readingSectionHeader: // Identifier in section header sets section name
replaceState(with: .finishingSectionHeader(name: str))
case .finishingSectionHeader, .awaitingSectionStart: // Identifier after section header is syntax error
throw INISerialization.SerializationError.invalidSectionName(line: tok.line)
case .readingKey: // Identifier while waiting for separator is syntax error
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Identifier while reading value or comment is valid
addStateToken(tok)
}
}
func handleText(_ tok: ParsedToken) throws {
// inSection, readingSectionHeader, finishingSectionHeader, awaitingSectionStart, readingKey -> ERROR
// readingValue -> readingValue
// readingComment -> readingComment
switch topState {
case .inSection: // Text at top level is syntax error
throw INISerialization.SerializationError.invalidKeyName(line: tok.line)
case .readingSectionHeader, .finishingSectionHeader, .awaitingSectionStart: // Text in or after section header is syntax error
throw INISerialization.SerializationError.invalidSectionName(line: tok.line)
case .readingKey: // Text while waiting for separator is syntax error
throw INISerialization.SerializationError.missingSeparator(line: tok.line)
case .readingValue, .readingComment: // Text while reading value or comment is valid
addStateToken(tok)
}
}
}
extension INIParser.State: CustomDebugStringConvertible {
var debugDescription: String {
switch (self) {
case .readingSectionHeader: return "readingSectionHeader"
case .finishingSectionHeader(let name): return "finishingSectionHeader(\(name))"
case .awaitingSectionStart(let name): return "awaitingSectionStart(\(name ?? "RESET"))"
case .inSection(let name): return "inSection(\(name ?? "(NONE)"))"
case .readingKey(let key): return "readingKey(\(key))"
case .readingValue(let key, let value): return "readingValue(\(key), " + value.map { $0.debugDescription }.joined(separator: ",") + ")"
case .readingComment(let tokens): return "readingComment(" + tokens.map { $0.debugDescription }.joined(separator: ",") + ")"
}
}
}
| 54.187935 | 165 | 0.611989 |
b94a3e266afcea98bbd913bf8abfabc3859e947e | 1,768 | //
// TestHelper.swift
// albumsTests
//
// Created by Rodrigo Gonzalez on 26/02/2018.
// Copyright © 2018 Rodrigo Gonzalez. All rights reserved.
//
import Foundation
@testable import albums
struct TestHelper {
static let urlEndpoint = "https://itunes.apple.com/lookup?id=909253&entity=album"
static var provider: GetAlbumProvider {
get {
return GetAlbumNetworkProvider(endpointURL: TestHelper.urlEndpoint)
}
}
static var parser: GetAlbumParser {
get {
return GetAlbumParserImp()
}
}
private static var mockProvider: GetAlbumProvider {
get {
return MockAlbumProvider()
}
}
static var interactor: GetAlbumInteractor {
get {
let provider = TestHelper.mockProvider
let parser = TestHelper.parser
return GetAlbumInteractorImp(parser: parser, provider: provider)
}
}
static var presenter: GetAlbumPresenter {
get {
let interactor = TestHelper.interactor
return GetAlbumPresenterImp(interactor: interactor)
}
}
static var mockPresenter: GetAlbumPresenter {
get {
return GetAlbumPresenterFailableMock()
}
}
static let albumInformation: [String : Any] = [
"resultCount": 1,
"results": [[
"wrapperType":"artist",
"artistType":"Artist",
"artistName":"Jack Johnson",
"artistLinkUrl":"https://itunes.apple.com/us/artist/jack-johnson/909253?uo=4",
"artistId":909253,
"amgArtistId":468749,
"primaryGenreName":"Rock",
"primaryGenreId":21
]]
]
}
| 25.623188 | 90 | 0.579186 |
2123aee9d05d9fa1745a4eea85ac3935e1c0966e | 925 | //
// Thors_ThursdayTests.swift
// Thors ThursdayTests
//
// Created by Mounika Ankam on 1/29/15.
// Copyright (c) 2015 Mounika Ankam. All rights reserved.
//
import UIKit
import XCTest
class Thors_ThursdayTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25 | 111 | 0.622703 |
e548db7f7766aad88839927400a91f51adbd8618 | 4,474 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import NIO
//MARK: Paginators
extension IoTAnalytics {
/// Retrieves a list of channels.
public func listChannelsPaginator(
_ input: ListChannelsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListChannelsResponse,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listChannels, tokenKey: \ListChannelsResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Lists information about data set contents that have been created.
public func listDatasetContentsPaginator(
_ input: ListDatasetContentsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDatasetContentsResponse,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listDatasetContents, tokenKey: \ListDatasetContentsResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Retrieves information about data sets.
public func listDatasetsPaginator(
_ input: ListDatasetsRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDatasetsResponse,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listDatasets, tokenKey: \ListDatasetsResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Retrieves a list of data stores.
public func listDatastoresPaginator(
_ input: ListDatastoresRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDatastoresResponse,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listDatastores, tokenKey: \ListDatastoresResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Retrieves a list of pipelines.
public func listPipelinesPaginator(
_ input: ListPipelinesRequest,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListPipelinesResponse,
EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listPipelines, tokenKey: \ListPipelinesResponse.nextToken, on: eventLoop, onPage: onPage)
}
}
extension IoTAnalytics.ListChannelsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> IoTAnalytics.ListChannelsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension IoTAnalytics.ListDatasetContentsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> IoTAnalytics.ListDatasetContentsRequest {
return .init(
datasetName: self.datasetName,
maxResults: self.maxResults,
nextToken: token,
scheduledBefore: self.scheduledBefore,
scheduledOnOrAfter: self.scheduledOnOrAfter
)
}
}
extension IoTAnalytics.ListDatasetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> IoTAnalytics.ListDatasetsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension IoTAnalytics.ListDatastoresRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> IoTAnalytics.ListDatastoresRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension IoTAnalytics.ListPipelinesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> IoTAnalytics.ListPipelinesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| 34.682171 | 158 | 0.666294 |
4ac1b615106532e495ed606abc8cf1fd1fcfef8d | 539 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Panasonic {
public struct LUMIXDMCLX100: CameraModel {
public init() {}
public let name = "Panasonic LUMIX DMC-LX100"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Panasonic.self
}
}
public typealias PanasonicLUMIXDMCLX100 = Cameras.Manufacturers.Panasonic.LUMIXDMCLX100
| 29.944444 | 99 | 0.749536 |
f421e13053bc8b0ffcdfa5673c4dfb409e72a3c5 | 2,269 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class LayoutConstraint: NSLayoutConstraint {
public var label: String? {
get {
identifier
}
set {
identifier = newValue
}
}
internal weak var constraint: Constraint?
}
internal func == (lhs: LayoutConstraint, rhs: LayoutConstraint) -> Bool {
// If firstItem or secondItem on either constraint has a dangling pointer
// this comparison can cause a crash. The solution for this is to ensure
// your layout code hold strong references to things like Views, LayoutGuides
// and LayoutAnchors as SnapKit will not keep strong references to any of these.
guard lhs.firstAttribute == rhs.firstAttribute,
lhs.secondAttribute == rhs.secondAttribute,
lhs.relation == rhs.relation,
lhs.priority == rhs.priority,
lhs.multiplier == rhs.multiplier,
lhs.secondItem === rhs.secondItem,
lhs.firstItem === rhs.firstItem
else {
return false
}
return true
}
| 37.816667 | 84 | 0.697223 |
5ddc3491562fe7d52b9ebd9afe91eaee2442a793 | 1,099 | //
// ViewController+Problem2.swift
// Day26
//
// Created by Manish Rathi on 08/01/2022.
//
import Foundation
import dsa_reusable
/*
https://www.geeksforgeeks.org/reverse-number-using-stack/
Reverse a number using stack
Given a number , write a program to reverse this number using stack.
Examples:
Input : 365
Output : 563
Input : 6899
Output : 9986
*/
extension ViewController {
func reverse(inputNumber: Int) {
print("Input: \(inputNumber)")
let stack = Stack<Int>()
// Insert digits into Stack
var currentNumber = inputNumber
while currentNumber != 0 {
let digit = currentNumber % 10
stack.push(data: digit)
currentNumber /= 10
}
// reverse
let outputNumber = stack.reverse
print("Output: \(outputNumber)")
}
}
extension Stack where T == Int {
var reverse: Int {
var output = 0
var index = 1
while isEmpty == false {
output += index * pop()!
index = index * 10
}
return output
}
}
| 18.627119 | 69 | 0.582348 |
16b14deecc720f1494637763a360ac68289f970a | 1,151 | //
// JSON.swift
// WebAuthnKit
//
// Created by Lyo Kato on 2018/11/20.
// Copyright © 2018 Lyo Kato. All rights reserved.
//
import Foundation
public class JSONHelper<T: Codable> {
public static func decode(_ json: String) -> Optional<T> {
if let data: Data = json.data(using: .utf8) {
do {
return try JSONDecoder().decode(T.self, from: data)
} catch let error {
WAKLogger.debug("<JSONHelper> failed to decode: \(error)")
return nil
}
} else {
WAKLogger.debug("<JSONHelper> invalid UTF-8 string")
return nil
}
}
public static func encode(_ obj: T) -> Optional<String> {
do {
let data = try JSONEncoder().encode(obj)
if let str = String(data: data, encoding: .utf8) {
return str
} else {
WAKLogger.debug("<JSONHelper> invalid UTF-8 string")
return nil
}
} catch let error {
WAKLogger.debug("<JSONHelper> failed to encode: \(error)")
return nil
}
}
}
| 27.404762 | 74 | 0.516942 |
d5f8ef28836e5fd5d6d7ea3a34a125ba2b6cbdda | 41,666 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import Foundation
import SotoCore
extension IoTDeviceAdvisor {
// MARK: Enums
public enum Status: String, CustomStringConvertible, Codable, _SotoSendable {
case canceled = "CANCELED"
case error = "ERROR"
case fail = "FAIL"
case pass = "PASS"
case passWithWarnings = "PASS_WITH_WARNINGS"
case pending = "PENDING"
case running = "RUNNING"
case stopped = "STOPPED"
case stopping = "STOPPING"
public var description: String { return self.rawValue }
}
public enum SuiteRunStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case canceled = "CANCELED"
case error = "ERROR"
case fail = "FAIL"
case pass = "PASS"
case passWithWarnings = "PASS_WITH_WARNINGS"
case pending = "PENDING"
case running = "RUNNING"
case stopped = "STOPPED"
case stopping = "STOPPING"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct CreateSuiteDefinitionRequest: AWSEncodableShape {
/// Creates a Device Advisor test suite with suite definition configuration.
public let suiteDefinitionConfiguration: SuiteDefinitionConfiguration?
/// The tags to be attached to the suite definition.
public let tags: [String: String]?
public init(suiteDefinitionConfiguration: SuiteDefinitionConfiguration? = nil, tags: [String: String]? = nil) {
self.suiteDefinitionConfiguration = suiteDefinitionConfiguration
self.tags = tags
}
public func validate(name: String) throws {
try self.suiteDefinitionConfiguration?.validate(name: "\(name).suiteDefinitionConfiguration")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, min: 1)
}
try self.validate(self.tags, name: "tags", parent: name, max: 50)
}
private enum CodingKeys: String, CodingKey {
case suiteDefinitionConfiguration
case tags
}
}
public struct CreateSuiteDefinitionResponse: AWSDecodableShape {
/// Creates a Device Advisor test suite with TimeStamp of when it was created.
public let createdAt: Date?
/// Creates a Device Advisor test suite with Amazon Resource Name (ARN).
public let suiteDefinitionArn: String?
/// Creates a Device Advisor test suite with suite UUID.
public let suiteDefinitionId: String?
/// Creates a Device Advisor test suite with suite definition name.
public let suiteDefinitionName: String?
public init(createdAt: Date? = nil, suiteDefinitionArn: String? = nil, suiteDefinitionId: String? = nil, suiteDefinitionName: String? = nil) {
self.createdAt = createdAt
self.suiteDefinitionArn = suiteDefinitionArn
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionName = suiteDefinitionName
}
private enum CodingKeys: String, CodingKey {
case createdAt
case suiteDefinitionArn
case suiteDefinitionId
case suiteDefinitionName
}
}
public struct DeleteSuiteDefinitionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId"))
]
/// Suite definition ID of the test suite to be deleted.
public let suiteDefinitionId: String
public init(suiteDefinitionId: String) {
self.suiteDefinitionId = suiteDefinitionId
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteSuiteDefinitionResponse: AWSDecodableShape {
public init() {}
}
public struct DeviceUnderTest: AWSEncodableShape & AWSDecodableShape {
/// Lists devices certificate ARN.
public let certificateArn: String?
/// Lists devices thing ARN.
public let thingArn: String?
public init(certificateArn: String? = nil, thingArn: String? = nil) {
self.certificateArn = certificateArn
self.thingArn = thingArn
}
public func validate(name: String) throws {
try self.validate(self.certificateArn, name: "certificateArn", parent: name, max: 2048)
try self.validate(self.certificateArn, name: "certificateArn", parent: name, min: 20)
try self.validate(self.thingArn, name: "thingArn", parent: name, max: 2048)
try self.validate(self.thingArn, name: "thingArn", parent: name, min: 20)
}
private enum CodingKeys: String, CodingKey {
case certificateArn
case thingArn
}
}
public struct GetEndpointRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "certificateArn", location: .querystring("certificateArn")),
AWSMemberEncoding(label: "thingArn", location: .querystring("thingArn"))
]
/// The certificate ARN of the device. This is an optional parameter.
public let certificateArn: String?
/// The thing ARN of the device. This is an optional parameter.
public let thingArn: String?
public init(certificateArn: String? = nil, thingArn: String? = nil) {
self.certificateArn = certificateArn
self.thingArn = thingArn
}
public func validate(name: String) throws {
try self.validate(self.certificateArn, name: "certificateArn", parent: name, max: 2048)
try self.validate(self.certificateArn, name: "certificateArn", parent: name, min: 20)
try self.validate(self.thingArn, name: "thingArn", parent: name, max: 2048)
try self.validate(self.thingArn, name: "thingArn", parent: name, min: 20)
}
private enum CodingKeys: CodingKey {}
}
public struct GetEndpointResponse: AWSDecodableShape {
/// The response of an Device Advisor endpoint.
public let endpoint: String?
public init(endpoint: String? = nil) {
self.endpoint = endpoint
}
private enum CodingKeys: String, CodingKey {
case endpoint
}
}
public struct GetSuiteDefinitionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId")),
AWSMemberEncoding(label: "suiteDefinitionVersion", location: .querystring("suiteDefinitionVersion"))
]
/// Suite definition ID of the test suite to get.
public let suiteDefinitionId: String
/// Suite definition version of the test suite to get.
public let suiteDefinitionVersion: String?
public init(suiteDefinitionId: String, suiteDefinitionVersion: String? = nil) {
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionVersion = suiteDefinitionVersion
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, max: 255)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, min: 2)
}
private enum CodingKeys: CodingKey {}
}
public struct GetSuiteDefinitionResponse: AWSDecodableShape {
/// Date (in Unix epoch time) when the suite definition was created.
public let createdAt: Date?
/// Date (in Unix epoch time) when the suite definition was last modified.
public let lastModifiedAt: Date?
/// Latest suite definition version of the suite definition.
public let latestVersion: String?
/// The ARN of the suite definition.
public let suiteDefinitionArn: String?
/// Suite configuration of the suite definition.
public let suiteDefinitionConfiguration: SuiteDefinitionConfiguration?
/// Suite definition ID of the suite definition.
public let suiteDefinitionId: String?
/// Suite definition version of the suite definition.
public let suiteDefinitionVersion: String?
/// Tags attached to the suite definition.
public let tags: [String: String]?
public init(createdAt: Date? = nil, lastModifiedAt: Date? = nil, latestVersion: String? = nil, suiteDefinitionArn: String? = nil, suiteDefinitionConfiguration: SuiteDefinitionConfiguration? = nil, suiteDefinitionId: String? = nil, suiteDefinitionVersion: String? = nil, tags: [String: String]? = nil) {
self.createdAt = createdAt
self.lastModifiedAt = lastModifiedAt
self.latestVersion = latestVersion
self.suiteDefinitionArn = suiteDefinitionArn
self.suiteDefinitionConfiguration = suiteDefinitionConfiguration
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionVersion = suiteDefinitionVersion
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case createdAt
case lastModifiedAt
case latestVersion
case suiteDefinitionArn
case suiteDefinitionConfiguration
case suiteDefinitionId
case suiteDefinitionVersion
case tags
}
}
public struct GetSuiteRunReportRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId")),
AWSMemberEncoding(label: "suiteRunId", location: .uri("suiteRunId"))
]
/// Suite definition ID of the test suite.
public let suiteDefinitionId: String
/// Suite run ID of the test suite run.
public let suiteRunId: String
public init(suiteDefinitionId: String, suiteRunId: String) {
self.suiteDefinitionId = suiteDefinitionId
self.suiteRunId = suiteRunId
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, max: 36)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, min: 12)
}
private enum CodingKeys: CodingKey {}
}
public struct GetSuiteRunReportResponse: AWSDecodableShape {
/// Download URL of the qualification report.
public let qualificationReportDownloadUrl: String?
public init(qualificationReportDownloadUrl: String? = nil) {
self.qualificationReportDownloadUrl = qualificationReportDownloadUrl
}
private enum CodingKeys: String, CodingKey {
case qualificationReportDownloadUrl
}
}
public struct GetSuiteRunRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId")),
AWSMemberEncoding(label: "suiteRunId", location: .uri("suiteRunId"))
]
/// Suite definition ID for the test suite run.
public let suiteDefinitionId: String
/// Suite run ID for the test suite run.
public let suiteRunId: String
public init(suiteDefinitionId: String, suiteRunId: String) {
self.suiteDefinitionId = suiteDefinitionId
self.suiteRunId = suiteRunId
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, max: 36)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, min: 12)
}
private enum CodingKeys: CodingKey {}
}
public struct GetSuiteRunResponse: AWSDecodableShape {
/// Date (in Unix epoch time) when the test suite run ended.
public let endTime: Date?
/// Error reason for any test suite run failure.
public let errorReason: String?
/// Date (in Unix epoch time) when the test suite run started.
public let startTime: Date?
/// Status for the test suite run.
public let status: SuiteRunStatus?
/// Suite definition ID for the test suite run.
public let suiteDefinitionId: String?
/// Suite definition version for the test suite run.
public let suiteDefinitionVersion: String?
/// The ARN of the suite run.
public let suiteRunArn: String?
/// Suite run configuration for the test suite run.
public let suiteRunConfiguration: SuiteRunConfiguration?
/// Suite run ID for the test suite run.
public let suiteRunId: String?
/// The tags attached to the suite run.
public let tags: [String: String]?
/// Test results for the test suite run.
public let testResult: TestResult?
public init(endTime: Date? = nil, errorReason: String? = nil, startTime: Date? = nil, status: SuiteRunStatus? = nil, suiteDefinitionId: String? = nil, suiteDefinitionVersion: String? = nil, suiteRunArn: String? = nil, suiteRunConfiguration: SuiteRunConfiguration? = nil, suiteRunId: String? = nil, tags: [String: String]? = nil, testResult: TestResult? = nil) {
self.endTime = endTime
self.errorReason = errorReason
self.startTime = startTime
self.status = status
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionVersion = suiteDefinitionVersion
self.suiteRunArn = suiteRunArn
self.suiteRunConfiguration = suiteRunConfiguration
self.suiteRunId = suiteRunId
self.tags = tags
self.testResult = testResult
}
private enum CodingKeys: String, CodingKey {
case endTime
case errorReason
case startTime
case status
case suiteDefinitionId
case suiteDefinitionVersion
case suiteRunArn
case suiteRunConfiguration
case suiteRunId
case tags
case testResult
}
}
public struct GroupResult: AWSDecodableShape {
/// Group result ID.
public let groupId: String?
/// Group Result Name.
public let groupName: String?
/// Tests under Group Result.
public let tests: [TestCaseRun]?
public init(groupId: String? = nil, groupName: String? = nil, tests: [TestCaseRun]? = nil) {
self.groupId = groupId
self.groupName = groupName
self.tests = tests
}
private enum CodingKeys: String, CodingKey {
case groupId
case groupName
case tests
}
}
public struct ListSuiteDefinitionsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken"))
]
/// The maximum number of results to return at once.
public let maxResults: Int?
/// A token used to get the next set of results.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
}
private enum CodingKeys: CodingKey {}
}
public struct ListSuiteDefinitionsResponse: AWSDecodableShape {
/// A token used to get the next set of results.
public let nextToken: String?
/// An array of objects that provide summaries of information about the suite definitions in the list.
public let suiteDefinitionInformationList: [SuiteDefinitionInformation]?
public init(nextToken: String? = nil, suiteDefinitionInformationList: [SuiteDefinitionInformation]? = nil) {
self.nextToken = nextToken
self.suiteDefinitionInformationList = suiteDefinitionInformationList
}
private enum CodingKeys: String, CodingKey {
case nextToken
case suiteDefinitionInformationList
}
}
public struct ListSuiteRunsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken")),
AWSMemberEncoding(label: "suiteDefinitionId", location: .querystring("suiteDefinitionId")),
AWSMemberEncoding(label: "suiteDefinitionVersion", location: .querystring("suiteDefinitionVersion"))
]
/// The maximum number of results to return at once.
public let maxResults: Int?
/// A token to retrieve the next set of results.
public let nextToken: String?
/// Lists the test suite runs of the specified test suite based on suite definition ID.
public let suiteDefinitionId: String?
/// Must be passed along with suiteDefinitionId. Lists the test suite runs of the specified test suite based on suite definition version.
public let suiteDefinitionVersion: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, suiteDefinitionId: String? = nil, suiteDefinitionVersion: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionVersion = suiteDefinitionVersion
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2000)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, max: 255)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, min: 2)
}
private enum CodingKeys: CodingKey {}
}
public struct ListSuiteRunsResponse: AWSDecodableShape {
/// A token to retrieve the next set of results.
public let nextToken: String?
/// An array of objects that provide summaries of information about the suite runs in the list.
public let suiteRunsList: [SuiteRunInformation]?
public init(nextToken: String? = nil, suiteRunsList: [SuiteRunInformation]? = nil) {
self.nextToken = nextToken
self.suiteRunsList = suiteRunsList
}
private enum CodingKeys: String, CodingKey {
case nextToken
case suiteRunsList
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("resourceArn"))
]
/// The ARN of the IoT Device Advisor resource.
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 20)
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// The tags attached to the IoT Device Advisor resource.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct StartSuiteRunRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId"))
]
/// Suite definition ID of the test suite.
public let suiteDefinitionId: String
/// Suite definition version of the test suite.
public let suiteDefinitionVersion: String?
/// Suite run configuration.
public let suiteRunConfiguration: SuiteRunConfiguration?
/// The tags to be attached to the suite run.
public let tags: [String: String]?
public init(suiteDefinitionId: String, suiteDefinitionVersion: String? = nil, suiteRunConfiguration: SuiteRunConfiguration? = nil, tags: [String: String]? = nil) {
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionVersion = suiteDefinitionVersion
self.suiteRunConfiguration = suiteRunConfiguration
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, max: 255)
try self.validate(self.suiteDefinitionVersion, name: "suiteDefinitionVersion", parent: name, min: 2)
try self.suiteRunConfiguration?.validate(name: "\(name).suiteRunConfiguration")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, min: 1)
}
try self.validate(self.tags, name: "tags", parent: name, max: 50)
}
private enum CodingKeys: String, CodingKey {
case suiteDefinitionVersion
case suiteRunConfiguration
case tags
}
}
public struct StartSuiteRunResponse: AWSDecodableShape {
/// Starts a Device Advisor test suite run based on suite create time.
public let createdAt: Date?
/// Amazon Resource Name (ARN) of the started suite run.
public let suiteRunArn: String?
/// Suite Run ID of the started suite run.
public let suiteRunId: String?
public init(createdAt: Date? = nil, suiteRunArn: String? = nil, suiteRunId: String? = nil) {
self.createdAt = createdAt
self.suiteRunArn = suiteRunArn
self.suiteRunId = suiteRunId
}
private enum CodingKeys: String, CodingKey {
case createdAt
case suiteRunArn
case suiteRunId
}
}
public struct StopSuiteRunRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId")),
AWSMemberEncoding(label: "suiteRunId", location: .uri("suiteRunId"))
]
/// Suite definition ID of the test suite run to be stopped.
public let suiteDefinitionId: String
/// Suite run ID of the test suite run to be stopped.
public let suiteRunId: String
public init(suiteDefinitionId: String, suiteRunId: String) {
self.suiteDefinitionId = suiteDefinitionId
self.suiteRunId = suiteRunId
}
public func validate(name: String) throws {
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, max: 36)
try self.validate(self.suiteRunId, name: "suiteRunId", parent: name, min: 12)
}
private enum CodingKeys: CodingKey {}
}
public struct StopSuiteRunResponse: AWSDecodableShape {
public init() {}
}
public struct SuiteDefinitionConfiguration: AWSEncodableShape & AWSDecodableShape {
/// Gets the device permission ARN.
public let devicePermissionRoleArn: String?
/// Gets the devices configured.
public let devices: [DeviceUnderTest]?
/// Gets the tests intended for qualification in a suite.
public let intendedForQualification: Bool?
/// Gets test suite root group.
public let rootGroup: String?
/// Gets Suite Definition Configuration name.
public let suiteDefinitionName: String?
public init(devicePermissionRoleArn: String? = nil, devices: [DeviceUnderTest]? = nil, intendedForQualification: Bool? = nil, rootGroup: String? = nil, suiteDefinitionName: String? = nil) {
self.devicePermissionRoleArn = devicePermissionRoleArn
self.devices = devices
self.intendedForQualification = intendedForQualification
self.rootGroup = rootGroup
self.suiteDefinitionName = suiteDefinitionName
}
public func validate(name: String) throws {
try self.validate(self.devicePermissionRoleArn, name: "devicePermissionRoleArn", parent: name, max: 2048)
try self.validate(self.devicePermissionRoleArn, name: "devicePermissionRoleArn", parent: name, min: 20)
try self.devices?.forEach {
try $0.validate(name: "\(name).devices[]")
}
try self.validate(self.devices, name: "devices", parent: name, max: 2)
try self.validate(self.rootGroup, name: "rootGroup", parent: name, max: 2048)
try self.validate(self.rootGroup, name: "rootGroup", parent: name, min: 1)
try self.validate(self.suiteDefinitionName, name: "suiteDefinitionName", parent: name, max: 256)
try self.validate(self.suiteDefinitionName, name: "suiteDefinitionName", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case devicePermissionRoleArn
case devices
case intendedForQualification
case rootGroup
case suiteDefinitionName
}
}
public struct SuiteDefinitionInformation: AWSDecodableShape {
/// Date (in Unix epoch time) when the test suite was created.
public let createdAt: Date?
/// Specifies the devices that are under test for the test suite.
public let defaultDevices: [DeviceUnderTest]?
/// Specifies if the test suite is intended for qualification.
public let intendedForQualification: Bool?
/// Suite definition ID of the test suite.
public let suiteDefinitionId: String?
/// Suite name of the test suite.
public let suiteDefinitionName: String?
public init(createdAt: Date? = nil, defaultDevices: [DeviceUnderTest]? = nil, intendedForQualification: Bool? = nil, suiteDefinitionId: String? = nil, suiteDefinitionName: String? = nil) {
self.createdAt = createdAt
self.defaultDevices = defaultDevices
self.intendedForQualification = intendedForQualification
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionName = suiteDefinitionName
}
private enum CodingKeys: String, CodingKey {
case createdAt
case defaultDevices
case intendedForQualification
case suiteDefinitionId
case suiteDefinitionName
}
}
public struct SuiteRunConfiguration: AWSEncodableShape & AWSDecodableShape {
/// TRUE if multiple test suites run in parallel.
public let parallelRun: Bool?
/// Gets the primary device for suite run.
public let primaryDevice: DeviceUnderTest?
/// Gets test case list.
public let selectedTestList: [String]?
public init(parallelRun: Bool? = nil, primaryDevice: DeviceUnderTest? = nil, selectedTestList: [String]? = nil) {
self.parallelRun = parallelRun
self.primaryDevice = primaryDevice
self.selectedTestList = selectedTestList
}
public func validate(name: String) throws {
try self.primaryDevice?.validate(name: "\(name).primaryDevice")
try self.selectedTestList?.forEach {
try validate($0, name: "selectedTestList[]", parent: name, max: 36)
try validate($0, name: "selectedTestList[]", parent: name, min: 12)
}
try self.validate(self.selectedTestList, name: "selectedTestList", parent: name, max: 100)
}
private enum CodingKeys: String, CodingKey {
case parallelRun
case primaryDevice
case selectedTestList
}
}
public struct SuiteRunInformation: AWSDecodableShape {
/// Date (in Unix epoch time) when the suite run was created.
public let createdAt: Date?
/// Date (in Unix epoch time) when the suite run ended.
public let endAt: Date?
/// Number of test cases that failed in the suite run.
public let failed: Int?
/// Number of test cases that passed in the suite run.
public let passed: Int?
/// Date (in Unix epoch time) when the suite run was started.
public let startedAt: Date?
/// Status of the suite run.
public let status: SuiteRunStatus?
/// Suite definition ID of the suite run.
public let suiteDefinitionId: String?
/// Suite definition name of the suite run.
public let suiteDefinitionName: String?
/// Suite definition version of the suite run.
public let suiteDefinitionVersion: String?
/// Suite run ID of the suite run.
public let suiteRunId: String?
public init(createdAt: Date? = nil, endAt: Date? = nil, failed: Int? = nil, passed: Int? = nil, startedAt: Date? = nil, status: SuiteRunStatus? = nil, suiteDefinitionId: String? = nil, suiteDefinitionName: String? = nil, suiteDefinitionVersion: String? = nil, suiteRunId: String? = nil) {
self.createdAt = createdAt
self.endAt = endAt
self.failed = failed
self.passed = passed
self.startedAt = startedAt
self.status = status
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionName = suiteDefinitionName
self.suiteDefinitionVersion = suiteDefinitionVersion
self.suiteRunId = suiteRunId
}
private enum CodingKeys: String, CodingKey {
case createdAt
case endAt
case failed
case passed
case startedAt
case status
case suiteDefinitionId
case suiteDefinitionName
case suiteDefinitionVersion
case suiteRunId
}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("resourceArn"))
]
/// The resource ARN of an IoT Device Advisor resource.
public let resourceArn: String
/// The tags to be attached to the IoT Device Advisor resource.
public let tags: [String: String]
public init(resourceArn: String, tags: [String: String]) {
self.resourceArn = resourceArn
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 20)
try self.tags.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, min: 1)
}
try self.validate(self.tags, name: "tags", parent: name, max: 50)
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct TagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct TestCaseRun: AWSDecodableShape {
/// Provides test case run end time.
public let endTime: Date?
/// Provides test case run failure result.
public let failure: String?
/// Provides test case run log URL.
public let logUrl: String?
/// Provides test case run start time.
public let startTime: Date?
/// Provides the test case run status. Status is one of the following: PASS: Test passed. FAIL: Test failed. PENDING: Test has not started running but is scheduled. RUNNING: Test is running. STOPPING: Test is performing cleanup steps. You will see this status only if you stop a suite run. STOPPED Test is stopped. You will see this status only if you stop a suite run. PASS_WITH_WARNINGS: Test passed with warnings. ERORR: Test faced an error when running due to an internal issue.
public let status: Status?
/// Provides the test case run definition ID.
public let testCaseDefinitionId: String?
/// Provides the test case run definition name.
public let testCaseDefinitionName: String?
/// Provides the test case run ID.
public let testCaseRunId: String?
/// Provides test case run warnings.
public let warnings: String?
public init(endTime: Date? = nil, failure: String? = nil, logUrl: String? = nil, startTime: Date? = nil, status: Status? = nil, testCaseDefinitionId: String? = nil, testCaseDefinitionName: String? = nil, testCaseRunId: String? = nil, warnings: String? = nil) {
self.endTime = endTime
self.failure = failure
self.logUrl = logUrl
self.startTime = startTime
self.status = status
self.testCaseDefinitionId = testCaseDefinitionId
self.testCaseDefinitionName = testCaseDefinitionName
self.testCaseRunId = testCaseRunId
self.warnings = warnings
}
private enum CodingKeys: String, CodingKey {
case endTime
case failure
case logUrl
case startTime
case status
case testCaseDefinitionId
case testCaseDefinitionName
case testCaseRunId
case warnings
}
}
public struct TestResult: AWSDecodableShape {
/// Show each group of test results.
public let groups: [GroupResult]?
public init(groups: [GroupResult]? = nil) {
self.groups = groups
}
private enum CodingKeys: String, CodingKey {
case groups
}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("resourceArn")),
AWSMemberEncoding(label: "tagKeys", location: .querystring("tagKeys"))
]
/// The resource ARN of an IoT Device Advisor resource.
public let resourceArn: String
/// List of tag keys to remove from the IoT Device Advisor resource.
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 20)
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
}
try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 50)
}
private enum CodingKeys: CodingKey {}
}
public struct UntagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateSuiteDefinitionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "suiteDefinitionId", location: .uri("suiteDefinitionId"))
]
/// Updates a Device Advisor test suite with suite definition configuration.
public let suiteDefinitionConfiguration: SuiteDefinitionConfiguration?
/// Suite definition ID of the test suite to be updated.
public let suiteDefinitionId: String
public init(suiteDefinitionConfiguration: SuiteDefinitionConfiguration? = nil, suiteDefinitionId: String) {
self.suiteDefinitionConfiguration = suiteDefinitionConfiguration
self.suiteDefinitionId = suiteDefinitionId
}
public func validate(name: String) throws {
try self.suiteDefinitionConfiguration?.validate(name: "\(name).suiteDefinitionConfiguration")
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, max: 36)
try self.validate(self.suiteDefinitionId, name: "suiteDefinitionId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case suiteDefinitionConfiguration
}
}
public struct UpdateSuiteDefinitionResponse: AWSDecodableShape {
/// Timestamp of when the test suite was created.
public let createdAt: Date?
/// Timestamp of when the test suite was updated.
public let lastUpdatedAt: Date?
/// Amazon Resource Name (ARN) of the updated test suite.
public let suiteDefinitionArn: String?
/// Suite definition ID of the updated test suite.
public let suiteDefinitionId: String?
/// Suite definition name of the updated test suite.
public let suiteDefinitionName: String?
/// Suite definition version of the updated test suite.
public let suiteDefinitionVersion: String?
public init(createdAt: Date? = nil, lastUpdatedAt: Date? = nil, suiteDefinitionArn: String? = nil, suiteDefinitionId: String? = nil, suiteDefinitionName: String? = nil, suiteDefinitionVersion: String? = nil) {
self.createdAt = createdAt
self.lastUpdatedAt = lastUpdatedAt
self.suiteDefinitionArn = suiteDefinitionArn
self.suiteDefinitionId = suiteDefinitionId
self.suiteDefinitionName = suiteDefinitionName
self.suiteDefinitionVersion = suiteDefinitionVersion
}
private enum CodingKeys: String, CodingKey {
case createdAt
case lastUpdatedAt
case suiteDefinitionArn
case suiteDefinitionId
case suiteDefinitionName
case suiteDefinitionVersion
}
}
}
| 43.53814 | 514 | 0.637882 |
abd0b5c53fc53f0bc6ee778d15d8d67470066b0c | 448 | //
// Credentials.swift
// netquest
//
// Created by Jorge Sanmartin on 20/12/21.
//
/*{
"access_token": "8d1e620d4323e80c934a635d39bc33deafdc938b",
"expires_in": 315360000,
"token_type": "bearer",
"scope": null,
"refresh_token": "fb9fcc94bd384c175a70ce88c379f6e702a732e6",
"account_id": 158261808,
"account_username": "jorgesanji2"
}*/
struct Credentials : Hashable, Codable{
var access_token : String?
var refresh_token : String?
}
| 20.363636 | 61 | 0.725446 |
1c7778b096e76e7e20718aeec594c35f9cbcb357 | 3,743 | import Foundation
import UIKit
class BaseTableViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func createAll() {
super.createAll()
// table view
tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = UIColor.clear
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
override func layoutAll() {
super.layoutAll()
// table view
view.addConstraint(NSLayoutConstraint(item: tableView!, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: tableView!, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: tableView!, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: tableView!, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1.0, constant: 0.0))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return onTableViewGetNumberOfRows(tableView: tableView, section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return onTableViewCreateCell(tableView: tableView, indexPath: indexPath)
}
func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onTableViewSelectedRow(tableView: tableView, indexPath: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay _: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row > 0, indexPath.row == onTableViewGetNumberOfRows(tableView: tableView, section: 0) - 1 {
onTableViewReachLastItem(tableView: tableView, indexPath: indexPath)
}
}
override func networkErrorViewProtocolOnAction(action: NetworkErrorViewAction) {
super.networkErrorViewProtocolOnAction(action: action)
if action == .refresh {
if remoteDataLoadState != .loading {
remoteDataLoadState = .notLoaded
}
loadData()
}
}
override func viewWillAppear(_: Bool) {
if let selectedRows = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedRows, animated: true)
}
super.viewWillAppear(true)
}
override func getVCTitle() -> String {
return "BaseTableView"
}
// MARK: EVENTS
func onTableViewCreateCell(tableView _: UITableView, indexPath _: IndexPath) -> UITableViewCell {
// Will be implemented on child
return UITableViewCell()
}
func onTableViewGetNumberOfRows(tableView _: UITableView, section _: Int) -> Int {
// Will be implemented on child
return 0
}
func onTableViewSelectedRow(tableView _: UITableView, indexPath _: IndexPath) {
// Will be implemented on child
}
func onTableViewReachLastItem(tableView _: UITableView, indexPath _: IndexPath) {
// Will be implemented on child
}
// MARK: CACHE
override func onCacheExpired() {
super.onCacheExpired()
if remoteDataLoadState != .loading {
remoteDataLoadState = .notLoaded
}
loadData()
}
}
| 34.981308 | 171 | 0.679402 |
380c38501bb6e4c933c531ee1106225b0e32856b | 10,020 | //
// GoodsCollectionViewCell.swift
// Copyright © 2016年 dealsea. All rights reserved.
//
import UIKit
import AFNetworking
class GoodsCollectionViewCell: UICollectionViewCell,UITableViewDataSource,UITableViewDelegate {
var logo = "dealsea"
var placeholder = "Search"
var searchMode = "&search_mode=Deals&"
// let mainUrl = "https://dealsea.com/?app="+appVersion
let searchUrl = "http://dealsea.com/search?q="
var session:NSURLSession!
var tableview:UITableView!
// var DataSource:NSMutableArray! //商品列表
var didselectBlock:((vc:NewGoodsViewController)->Void)?
var enableFrash:Bool = true
var frashPage:NSInteger = 2
var waitview:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
var categoryModel:NotificationsInfo = NotificationsInfo(){
didSet{
categoryurl = categoryModel.url
}
}
var categoryurl:String = String(){
didSet{
self.enableFrash = true
let manager = NetworkTool.sharetool
for task in manager.taskarr{
task.cancel()
}
self.tableview.mj_header.endRefreshing()
if(categoryModel.DataSource.count == 0){
dispatch_async(dispatch_get_main_queue()) {
self.tableview.reloadData()
}
self.waitview.startAnimating()
loadDataSource(NSURL(string: categoryurl)!)
// self.tableview.mj_header.beginRefreshing()
}else{
dispatch_async(dispatch_get_main_queue()) {
self.tableview.reloadData()
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
SetupUI()
}
func SetupUI(){
contentView.backgroundColor = UIColor.whiteColor()
tableview = UITableView()
tableview.separatorStyle = .None
let header = MJRefreshNormalHeader()
header.setRefreshingTarget(self, refreshingAction: #selector(DealseaViewController.headerRefresh))
self.tableview.mj_header = header
tableview.dataSource = self
tableview.delegate = self
tableview.registerClass(DealseaTableViewCell.self, forCellReuseIdentifier: "reusingCell")
contentView.addSubview(tableview)
activityEnable()
}
override func layoutSubviews() {
super.layoutSubviews()
tableview.frame = contentView.frame
self.waitview.center = CGPoint(x: contentView.frame.size.width/2, y: contentView.frame.size.height/2)
}
func headerRefresh(){
loadDataSource(NSURL(string: categoryurl)!)
}
func activityEnable(){
self.waitview.color = UIColor.grayColor()
self.waitview.hidesWhenStopped = true
contentView.addSubview(self.waitview)
}
func activeDisable(){
self.tableview.mj_header.endRefreshing()
self.waitview.stopAnimating()
}
func loadDataSource(url:NSURL){
let manager = NetworkTool.sharetool
manager.manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as? Set<String>
let tmptask:NSURLSessionDataTask = manager.manager.POST(url.absoluteString, parameters: nil, progress: { (progress) in
}, success: { (task, data) in
let dict:[String:AnyObject] = data as! Dictionary
let CouponsDataSource = dict["list"] as! NSArray
let CurrentDeaData = NSMutableArray()
for CurrentDea in CouponsDataSource{
let spList = DeaList()
spList.title = CurrentDea["title"] as! String
spList.post_time = CurrentDea["post_time"] as! String
spList.post_id = CurrentDea["post_id"] as! String
spList.merchant = CurrentDea["merchant"] as! Array
spList.image = CurrentDea["img"] as! Array
spList.comment_count = CurrentDea["comment_count"] as! Int
spList.allowComment = CurrentDea["post_allowcomment"] as! String
spList.expired = CurrentDea["expired"] as! Int
spList.hotness = CurrentDea["hotness"] as! String
CurrentDeaData.addObject(spList)
}
self.categoryModel.DataSource = CurrentDeaData
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.activeDisable()
self.tableview.reloadData()
})
}) { (task, error) in
print(error.localizedDescription)
}!
manager.taskarr.append(tmptask)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return 100
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryModel.DataSource.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableview.dequeueReusableCellWithIdentifier("reusingCell", forIndexPath: indexPath) as! DealseaTableViewCell
let splist = categoryModel.DataSource[indexPath.row] as! DeaList
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.textLabel?.numberOfLines = 0
if(splist.expired != 0){
cell.textLabel?.text = "(Expired) \(splist.title)"
cell.textLabel?.textColor = UIColor.blackColor()
}else{
cell.textLabel?.text = splist.title
if(splist.hotness.hasPrefix("1")){
cell.textLabel?.textColor = UIColor.redColor()
}else{
cell.textLabel?.textColor = UIColor.blackColor()
}
}
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView?.sd_setImageWithURL(NSURL(string: splist.image[0]), placeholderImage: UIImage(named: "goods"))
cell.textLabel?.font = UIFont.systemFontOfSize(14, weight: UIFontWeightMedium)
//cell.textLabel.font = UIFont.weight: UIFontWeightBold
cell.detailTextLabel?.textColor = UIColor.grayColor()
cell.detailTextLabel?.text = splist.merchant[1]
cell.commentlabel.textColor = UIColor.grayColor()
cell.commentlabel.text = "\(splist.comment_count)"
cell.commentlabel.sizeToFit()
cell.timelabel.textColor = UIColor.grayColor()
cell.timelabel.text = splist.post_time
cell.timelabel.sizeToFit()
if(indexPath.row > (self.categoryModel.DataSource.count - 10)){
if(enableFrash == true){
enableFrash = false
waitview.startAnimating()
let manager = NetworkTool.sharetool
for task in manager.taskarr{
task.cancel()
}
manager.manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as? Set<String>
manager.manager.POST(categoryurl+"&page=\(self.frashPage)", parameters: "", progress: { (progress) -> Void in
}, success: { (task, data) -> Void in
self.enableFrash = true
let dict:[String:AnyObject] = data as! Dictionary
if(data != nil){
let CouponsDataSource = dict["list"] as! NSArray
let CurrentDeaData = NSMutableArray(array: self.categoryModel.DataSource)
for CurrentDea in CouponsDataSource{
let spList = DeaList()
spList.title = CurrentDea["title"] as! String
spList.post_time = CurrentDea["post_time"] as! String
spList.post_id = CurrentDea["post_id"] as! String
spList.merchant = CurrentDea["merchant"] as! Array
spList.image = CurrentDea["img"] as! Array
spList.comment_count = CurrentDea["comment_count"] as! Int
spList.allowComment = CurrentDea["post_allowcomment"] as! String
spList.expired = CurrentDea["expired"] as! Int
spList.hotness = CurrentDea["hotness"] as! String
CurrentDeaData.addObject(spList)
}
self.categoryModel.DataSource = CurrentDeaData
self.tableview.reloadData()
self.frashPage = self.frashPage + 1
self.waitview.stopAnimating()
}
}) { (task, error) -> Void in
self.enableFrash = true
self.waitview.stopAnimating()
}
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let goodsvc = NewGoodsViewController(nibName: nil, bundle: nil)
let splist = categoryModel.DataSource[indexPath.row] as! DeaList
goodsvc.goodModel = splist
[NSForegroundColorAttributeName: UIColor.whiteColor()]
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
if(didselectBlock != nil){
didselectBlock!(vc: goodsvc)
}
}
}
| 43.004292 | 132 | 0.582535 |
26b8526f7dfeb4fbeb0b053fc042cf869e51d97e | 9,775 | //
// EECellSwipeGestureRecognizer.swift
// EECellSwipeGestureRecognizer
//
// Created by Enric Enrich on 02/01/16.
// Copyright © 2016 Enric Enrich. All rights reserved.
//
import UIKit
open class EECellSwipeGestureRecognizer: UIPanGestureRecognizer {
// MARK: - Properties
open var animationTime: TimeInterval = 0.2 // Default is 0.2
open var isSwipeActive = false
private var leftActions = [EECellSwipeAction]()
private var rightActions = [EECellSwipeAction]()
private var actionView = EECellSwipeActionView()
private var originalContentViewBackgroundColor: UIColor?
// MARK: - Initialize
public init() {
super.init(target: nil, action: nil)
if #available(iOS 13.4, *) {
allowedScrollTypesMask = .continuous
}
delegate = self
addTarget(self, action: #selector(EECellSwipeGestureRecognizer.handlePan))
}
// MARK: - Actions
@objc private func handlePan() {
guard let cell = self.cell else {
return
}
switch state {
case .began:
sortActions()
if actionView.superview != nil {
actionView.removeFromSuperview()
}
cell.insertSubview(actionView, at: 0)
actionView.frame = cell.contentView.bounds
actionView.active = false
originalContentViewBackgroundColor = cell.contentView.backgroundColor
case .changed:
updateCellPosition()
updateContentViewBackgroundColor()
if isActiveForCurrentCellPosition() != actionView.active {
actionView.active = isActiveForCurrentCellPosition()
if let didChangeState = actionView.action?.didChangeState, let action = actionView.action {
didChangeState(action, actionView.active)
}
}
if actionForCurrentCellPosition() != actionView.action {
actionView.action = actionForCurrentCellPosition()
}
case .ended:
performAction {
self.updateContentViewBackgroundColor()
}
default:
break
}
}
// MARK: - Public API
open func add(actions: [EECellSwipeAction]) {
for action in actions {
if action.fraction > 0 {
leftActions.append(action)
} else {
rightActions.append(action)
}
}
}
open func remove(actions: [EECellSwipeAction]) {
for action in actions {
if action.fraction > 0 {
if let index = leftActions.firstIndex(of: action) {
leftActions.remove(at: index)
}
} else {
if let index = rightActions.firstIndex(of: action) {
rightActions.remove(at: index)
}
}
}
}
open func removeLeftActions() {
leftActions.removeAll()
}
open func removeRightActions() {
rightActions.removeAll()
}
open func removeAllActions() {
leftActions.removeAll()
rightActions.removeAll()
}
open func swipeToOrigin(animated: Bool, completion: ((_ finished: Bool) -> Void)?) {
translateCellHorizontally(0.0, animationDuration: animated ? animationTime : 0.0, completion: { (finished) -> Void in
self.actionView.removeFromSuperview()
self.updateContentViewBackgroundColor()
if let completion = completion {
completion(finished)
}
})
}
// MARK: - Private API
private var tableView: UITableView? {
get {
guard let cell = self.cell else {
return nil
}
var view: UIView? = cell.superview
while let unrappedView = view, (unrappedView is UITableView) == false {
view = unrappedView.superview
}
return view as? UITableView
}
}
private var cell: UITableViewCell? {
get {
guard let cell = view as? UITableViewCell else {
return nil
}
return cell
}
}
private var indexPath: IndexPath? {
get {
guard let tableView = self.tableView, let cell = self.cell else {
return nil
}
return tableView.indexPath(for: cell)
}
}
private func currentHorizontalTranslation() -> CGFloat {
guard let cell = self.cell else {
return 0.0
}
var horizontalTranslation: CGFloat = translation(in: cell).x
if (horizontalTranslation > 0 && leftActions.count == 0) || (horizontalTranslation < 0 && rightActions.count == 0) {
horizontalTranslation = 0.0
}
return horizontalTranslation
}
private func sortActions() {
leftActions.sort { (action1, action2) -> Bool in
return action1.fraction > action2.fraction
}
rightActions.sort { (action1, action2) -> Bool in
return action1.fraction < action2.fraction
}
}
private func fractionForCurrentCellPosition() -> CGFloat {
guard let cell = self.cell else {
return 0.0
}
return cell.contentView.frame.origin.x / cell.contentView.frame.width
}
private func actionsForCurrentCellPosition() -> [EECellSwipeAction] {
return fractionForCurrentCellPosition() > 0 ? leftActions : rightActions
}
private func actionForCurrentCellPosition() -> EECellSwipeAction? {
let actions = actionsForCurrentCellPosition()
var action: EECellSwipeAction? = actions.first
for a in actions {
if abs(fractionForCurrentCellPosition()) > abs(a.fraction) {
action = a
} else {
break
}
}
return action
}
private func isActiveForCurrentCellPosition() -> Bool {
if let currentAction = actionForCurrentCellPosition() {
return abs(fractionForCurrentCellPosition()) >= abs(currentAction.fraction)
}
return false
}
private func updateContentViewBackgroundColor() {
if actionView.superview != nil {
cell?.contentView.backgroundColor = originalContentViewBackgroundColor ?? cell?.backgroundColor
} else {
cell?.contentView.backgroundColor = originalContentViewBackgroundColor
}
}
private func updateCellPosition() {
if let cell = self.cell {
actionView.cellDidUpdatePosition(cell)
}
translateCellHorizontally(currentHorizontalTranslation())
}
private func translateCellHorizontally(_ horizontalTranslation: CGFloat) {
guard let cell = cell else {
return
}
cell.contentView.center = CGPoint(x: cell.contentView.frame.width / 2 + horizontalTranslation, y: cell.contentView.center.y)
}
private func translateCellHorizontally(_ horizontalTranslation: CGFloat, animationDuration: TimeInterval, completion: ((_ finished: Bool) -> Void)?) {
UIView.animate(withDuration: animationDuration, delay: 0.0, options: UIView.AnimationOptions() , animations: { () -> Void in
self.translateCellHorizontally(horizontalTranslation)
}, completion: completion)
}
private func performAction(completion: (() -> Void)? = nil) {
if actionView.active {
if let willTrigger = actionView.action?.willTrigger, let tableView = self.tableView, let indexPath = self.indexPath {
willTrigger(tableView, indexPath)
}
translateCellHorizontally(horizontalTranslationForActionBehavior(), animationDuration: animationTime, completion: { (finished) -> Void in
if self.actionView.action?.behavior == .pull {
self.actionView.removeFromSuperview()
}
if self.actionView.action?.behavior == .push {
self.isSwipeActive = true
}
if let didTrigger = self.actionView.action?.didTrigger, let tableView = self.tableView, let indexPath = self.indexPath {
didTrigger(tableView, indexPath)
}
completion?()
})
} else {
isSwipeActive = false
translateCellHorizontally(0.0, animationDuration: animationTime, completion: { (finished) -> Void in
self.actionView.removeFromSuperview()
completion?()
})
}
}
private func horizontalTranslationForActionBehavior() -> CGFloat {
if let action = actionView.action, let cell = self.cell {
return action.behavior == .pull ? 0 : cell.contentView.frame.width * (action.fraction / abs(action.fraction))
}
return 0.0
}
}
// MARK: - UIGestureRecognizerDelegate
extension EECellSwipeGestureRecognizer: UIGestureRecognizerDelegate {
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let velocity = self.velocity(in: view)
return abs(velocity.x) > abs(velocity.y)
}
}
| 31.430868 | 154 | 0.566445 |
7a37f48fe06c8da09443510d5d409ea66b25b6ea | 2,539 | //
// AmityResponsiveView.swift
// AmityUIKit
//
// Created by Sarawoot Khunsri on 7/8/2563 BE.
// Copyright © 2563 Amity Communication. All rights reserved.
//
import UIKit
final class AmityResponsiveView: UIView {
// MAKR: - Properties
var duration: TimeInterval = 0.3
var menuItems: [UIMenuItem] = []
lazy var overlayView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: "#292B32").withAlphaComponent(0.5)
view.layer.cornerRadius = 4
return view
}()
func showOverlayView() {
overlayView.translatesAutoresizingMaskIntoConstraints = false
addSubview(overlayView)
NSLayoutConstraint.activate([
overlayView.topAnchor.constraint(equalTo: topAnchor),
overlayView.bottomAnchor.constraint(equalTo: bottomAnchor),
overlayView.leadingAnchor.constraint(equalTo: leadingAnchor),
overlayView.trailingAnchor.constraint(equalTo: trailingAnchor),
])
}
func removeOverlayView() {
overlayView.removeFromSuperview()
}
override var canBecomeFirstResponder: Bool {
return true
}
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
private func setupView() {
clipsToBounds = true
layer.masksToBounds = true
isUserInteractionEnabled = true
// Add a long press gesture recognizer to our responsive view
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressTap))
longPress.minimumPressDuration = duration
addGestureRecognizer(longPress)
NotificationCenter.default.addObserver(self, selector: #selector(observeWillHide), name: UIMenuController.willHideMenuNotification, object: nil)
}
@objc
private func observeWillHide() {
removeOverlayView()
}
@objc
private func longPressTap(_ sender: UILongPressGestureRecognizer) {
guard sender.state == .began,
let senderView = sender.view,
let superView = sender.view?.superview else {
return
}
showOverlayView()
// Make responsiveView the window's first responder
senderView.becomeFirstResponder()
UIMenuController.shared.menuItems = menuItems
UIMenuController.shared.setTargetRect(senderView.frame, in: superView)
UIMenuController.shared.setMenuVisible(true, animated: true)
}
}
| 30.590361 | 152 | 0.654982 |
6280a178d2c6cdb5e246800ea0a7eaf6fe6a0dc4 | 81 | // Generated by msgbuilder 2019-05-02 07:55:41 +0000
public enum sensor_msgs {}
| 20.25 | 52 | 0.740741 |
ff9884ed4c37f1681f882e1811a32a9762ceb430 | 4,886 | //
// CommerceEventTableViewController.swift
// TestBed-Swift
//
// Created by David Westgate on 9/16/17.
// Copyright © 2017 Branch Metrics. All rights reserved.
//
import UIKit
class CommerceEventTableViewController: UITableViewController {
@IBOutlet weak var commerceEventDetailsLabel: UILabel!
@IBOutlet weak var commerceEventCustomMetadataTextView: UITextView!
@IBOutlet weak var sendCommerceEventButton: UIButton!
var commerceEventCustomMetadata = [String: AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
refreshControlValues()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch((indexPath as NSIndexPath).section, (indexPath as NSIndexPath).row) {
case (0,0) :
self.performSegue(withIdentifier: "CommerceEventDetails", sender: "CommerceEventDetails")
case (0,1) :
self.performSegue(withIdentifier: "Dictionary", sender: "CommerceEventCustomMetadata")
default : break
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let senderName = sender as? String {
switch senderName {
case "CommerceEventCustomMetadata":
let nc = segue.destination as! UINavigationController
let vc = nc.topViewController as! DictionaryTableViewController
commerceEventCustomMetadata = CommerceEventData.commerceEventCustomMetadata()
vc.dictionary = commerceEventCustomMetadata
vc.viewTitle = "Commerce Metadata"
vc.keyHeader = "Key"
vc.keyPlaceholder = "key"
vc.keyFooter = ""
vc.valueHeader = "Value"
vc.valueFooter = ""
vc.keyKeyboardType = UIKeyboardType.default
vc.valueKeyboardType = UIKeyboardType.default
vc.sender = sender as! String
default:
break
}
}
}
@IBAction func unwindCommerceEventDetails(_ segue:UIStoryboardSegue) { }
@IBAction func unwindDictionary(_ segue:UIStoryboardSegue) {
if let vc = segue.source as? DictionaryTableViewController {
commerceEventCustomMetadata = vc.dictionary
CommerceEventData.setCommerceEventCustomMetadata(commerceEventCustomMetadata)
if commerceEventCustomMetadata.count > 0 {
commerceEventCustomMetadataTextView.text = commerceEventCustomMetadata.description
} else {
commerceEventCustomMetadataTextView.text = ""
}
}
}
@IBAction func unwindByCancelling(_ segue:UIStoryboardSegue) { }
@IBAction func sendCommerceEventButtonTouchUpInside(_ sender: AnyObject) {
let commerceEvent = CommerceEventData.bNCCommerceEvent()
WaitingViewController.showWithMessage(
message: "Getting parameters...",
activityIndicator:true,
disableTouches:true
)
Branch.getInstance()?.send(
commerceEvent,
metadata: commerceEventCustomMetadata,
withCompletion: { (response, error) in
let errorMessage: String = (error?.localizedDescription != nil) ?
error!.localizedDescription : "<nil>"
let responseMessage = (response?.description != nil) ?
response!.description : "<nil>"
let message = String.init(
format:"Commerce event completion called.\nError: %@\nResponse:\n%@",
errorMessage,
responseMessage
)
NSLog("%@", message)
WaitingViewController.hide()
self.showAlert("Commerce Event", withDescription: message)
}
)
}
func refreshControlValues() {
commerceEventCustomMetadata = CommerceEventData.commerceEventCustomMetadata()
if (commerceEventCustomMetadata.count > 0) {
commerceEventCustomMetadataTextView.text = commerceEventCustomMetadata.description
} else {
commerceEventCustomMetadataTextView.text = ""
}
}
func showAlert(_ alertTitle: String, withDescription message: String) {
let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel) {
UIAlertAction in
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
| 37.015152 | 101 | 0.621367 |
4ab600e7bae8b2b977d59891ed06a2b269270365 | 4,352 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
class ViewController: UITableViewController {
let AGNotificationCellIdentifier = "AGNotificationCell"
var isRegistered = false
// holds the messages received and displayed on tableview
var messages: Array<String> = []
override func viewDidLoad() {
super.viewDidLoad()
// register to be notified when state changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "registered", name: "success_registered", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "errorRegistration", name: "error_register", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "messageReceived:", name: "message_received", object: nil)
}
func registered() {
println("registered")
// workaround to get messages when app was not running
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults();
if(defaults.objectForKey("message_received") != nil) {
let msg : String! = defaults.objectForKey("message_received") as String
defaults.removeObjectForKey("message_received")
defaults.synchronize()
if(msg != nil) {
messages.append(msg)
}
}
isRegistered = true
tableView.reloadData()
}
func errorRegistration() {
// can't do much, inform user to verify the UPS details entered and return
let message = UIAlertController(title: "Registration Error!", message: "Please verify the provisionioning profile and the UPS details have been setup correctly.", preferredStyle: .Alert)
self.presentViewController(message, animated:true, completion:nil)
}
func messageReceived(notification: NSNotification) {
println("received")
messages.append(notification.userInfo!["aps"]!["alert"] as String)
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var bgView:UIView?
// determine current state
if (!isRegistered) { // not yet registered
let progress = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("ProgressViewController") as UIViewController
bgView = progress.view
} else if (messages.count == 0) { // registered but no notification received yet
let empty = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("EmptyViewController") as UIViewController
bgView = empty.view
}
// set the background view if needed
if (bgView != nil) {
self.tableView.backgroundView = bgView
self.tableView.separatorStyle = .None
return 0
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// if it's the first message in the stream, let's clear the 'empty' placeholder vier
if (self.tableView.backgroundView != nil) {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .SingleLine
}
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(AGNotificationCellIdentifier) as UITableViewCell
cell.textLabel?.text = messages[indexPath.row]
return cell
}
}
| 39.563636 | 195 | 0.667509 |
3318a7ece6d253ff7ef6c7073b5b56fde1f5835f | 6,568 | import UIKit
import Foundation
// MARK: - PressableRootView
public class PressableRootView: UIView {
// MARK: Lifecycle
public init() {
super.init(frame: .zero)
setUpViews()
setUpConstraints()
update()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public
public var onPressOuter: (() -> Void)? { didSet { update() } }
public var onPressInner: (() -> Void)? { didSet { update() } }
// MARK: Private
private var innerView = UIView(frame: .zero)
private var innerTextView = UILabel()
private var innerTextViewTextStyle = TextStyles.headline
private var topPadding: CGFloat = 24
private var trailingPadding: CGFloat = 24
private var bottomPadding: CGFloat = 24
private var leadingPadding: CGFloat = 24
private var innerViewTopMargin: CGFloat = 0
private var innerViewTrailingMargin: CGFloat = 0
private var innerViewBottomMargin: CGFloat = 0
private var innerViewLeadingMargin: CGFloat = 0
private var innerViewTopPadding: CGFloat = 0
private var innerViewTrailingPadding: CGFloat = 0
private var innerViewBottomPadding: CGFloat = 0
private var innerViewLeadingPadding: CGFloat = 0
private var innerTextViewTopMargin: CGFloat = 0
private var innerTextViewTrailingMargin: CGFloat = 0
private var innerTextViewBottomMargin: CGFloat = 0
private var innerTextViewLeadingMargin: CGFloat = 0
private var hovered = false
private var pressed = false
private var onPress: (() -> Void)?
private var innerViewHovered = false
private var innerViewPressed = false
private var innerViewOnPress: (() -> Void)?
private var innerViewTopAnchorConstraint: NSLayoutConstraint?
private var innerViewBottomAnchorConstraint: NSLayoutConstraint?
private var innerViewLeadingAnchorConstraint: NSLayoutConstraint?
private var innerViewHeightAnchorConstraint: NSLayoutConstraint?
private var innerViewWidthAnchorConstraint: NSLayoutConstraint?
private var innerTextViewTopAnchorConstraint: NSLayoutConstraint?
private var innerTextViewLeadingAnchorConstraint: NSLayoutConstraint?
private var innerTextViewTrailingAnchorConstraint: NSLayoutConstraint?
private func setUpViews() {
innerTextView.numberOfLines = 0
addSubview(innerView)
innerView.addSubview(innerTextView)
innerTextViewTextStyle = TextStyles.headline
innerTextView.attributedText =
innerTextViewTextStyle.apply(to: innerTextView.attributedText ?? NSAttributedString())
}
private func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
innerView.translatesAutoresizingMaskIntoConstraints = false
innerTextView.translatesAutoresizingMaskIntoConstraints = false
let innerViewTopAnchorConstraint = innerView
.topAnchor
.constraint(equalTo: topAnchor, constant: topPadding + innerViewTopMargin)
let innerViewBottomAnchorConstraint = innerView
.bottomAnchor
.constraint(equalTo: bottomAnchor, constant: -(bottomPadding + innerViewBottomMargin))
let innerViewLeadingAnchorConstraint = innerView
.leadingAnchor
.constraint(equalTo: leadingAnchor, constant: leadingPadding + innerViewLeadingMargin)
let innerViewHeightAnchorConstraint = innerView.heightAnchor.constraint(equalToConstant: 100)
let innerViewWidthAnchorConstraint = innerView.widthAnchor.constraint(equalToConstant: 100)
let innerTextViewTopAnchorConstraint = innerTextView
.topAnchor
.constraint(equalTo: innerView.topAnchor, constant: innerViewTopPadding + innerTextViewTopMargin)
let innerTextViewLeadingAnchorConstraint = innerTextView
.leadingAnchor
.constraint(equalTo: innerView.leadingAnchor, constant: innerViewLeadingPadding + innerTextViewLeadingMargin)
let innerTextViewTrailingAnchorConstraint = innerTextView
.trailingAnchor
.constraint(
equalTo: innerView.trailingAnchor,
constant: -(innerViewTrailingPadding + innerTextViewTrailingMargin))
NSLayoutConstraint.activate([
innerViewTopAnchorConstraint,
innerViewBottomAnchorConstraint,
innerViewLeadingAnchorConstraint,
innerViewHeightAnchorConstraint,
innerViewWidthAnchorConstraint,
innerTextViewTopAnchorConstraint,
innerTextViewLeadingAnchorConstraint,
innerTextViewTrailingAnchorConstraint
])
self.innerViewTopAnchorConstraint = innerViewTopAnchorConstraint
self.innerViewBottomAnchorConstraint = innerViewBottomAnchorConstraint
self.innerViewLeadingAnchorConstraint = innerViewLeadingAnchorConstraint
self.innerViewHeightAnchorConstraint = innerViewHeightAnchorConstraint
self.innerViewWidthAnchorConstraint = innerViewWidthAnchorConstraint
self.innerTextViewTopAnchorConstraint = innerTextViewTopAnchorConstraint
self.innerTextViewLeadingAnchorConstraint = innerTextViewLeadingAnchorConstraint
self.innerTextViewTrailingAnchorConstraint = innerTextViewTrailingAnchorConstraint
// For debugging
innerViewTopAnchorConstraint.identifier = "innerViewTopAnchorConstraint"
innerViewBottomAnchorConstraint.identifier = "innerViewBottomAnchorConstraint"
innerViewLeadingAnchorConstraint.identifier = "innerViewLeadingAnchorConstraint"
innerViewHeightAnchorConstraint.identifier = "innerViewHeightAnchorConstraint"
innerViewWidthAnchorConstraint.identifier = "innerViewWidthAnchorConstraint"
innerTextViewTopAnchorConstraint.identifier = "innerTextViewTopAnchorConstraint"
innerTextViewLeadingAnchorConstraint.identifier = "innerTextViewLeadingAnchorConstraint"
innerTextViewTrailingAnchorConstraint.identifier = "innerTextViewTrailingAnchorConstraint"
}
private func update() {
innerView.backgroundColor = Colors.blue500
innerTextView.attributedText = innerTextViewTextStyle.apply(to: "")
backgroundColor = Colors.grey50
onPress = onPressOuter
innerViewOnPress = onPressInner
if hovered {
backgroundColor = Colors.grey100
}
if pressed {
backgroundColor = Colors.grey300
}
if innerViewHovered {
innerView.backgroundColor = Colors.blue300
innerTextView.attributedText = innerTextViewTextStyle.apply(to: "Hovered")
}
if innerViewPressed {
innerView.backgroundColor = Colors.blue800
innerTextView.attributedText = innerTextViewTextStyle.apply(to: "Pressed")
}
if innerViewHovered {
if innerViewPressed {
innerTextView.attributedText = innerTextViewTextStyle.apply(to: "Hovered & Pressed")
}
}
}
}
| 39.806061 | 115 | 0.785323 |
38c306b178183ada0b584cb990b935da4cff63a0 | 7,113 | //: [Previous](@previous)
//: For this page, make sure your build target is set to ParseSwift (macOS) and targeting
//: `My Mac` or whatever the name of your mac is. Also be sure your `Playground Settings`
//: in the `File Inspector` is `Platform = macOS`. This is because
//: Keychain in iOS Playgrounds behaves differently. Every page in Playgrounds should
//: be set to build for `macOS` unless specified.
import PlaygroundSupport
import Foundation
import ParseSwift
PlaygroundPage.current.needsIndefiniteExecution = true
initializeParse()
struct User: ParseUser {
//: These are required for `ParseObject`.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
//: These are required for `ParseUser`.
var username: String?
var email: String?
var password: String?
var authData: [String: [String: String]?]?
//: Your custom keys.
var customKey: String?
}
struct Role<RoleUser: ParseUser>: ParseRole {
//: Required by `ParseObject`.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
//: Provided by Role.
var name: String
init() {
self.name = ""
}
}
//: Roles can provide additional access/security to your apps.
//: This variable will store the saved role.
var savedRole: Role<User>?
//: Now we will create the Role.
if let currentUser = User.current {
//: Every Role requires an ACL that can't be changed after saving.
var acl = ParseACL()
acl.setReadAccess(user: currentUser, value: true)
acl.setWriteAccess(user: currentUser, value: true)
do {
//: Create the actual Role with a name and ACL.
let adminRole = try Role<User>(name: "Administrator", acl: acl)
adminRole.save { result in
switch result {
case .success(let saved):
print("The role saved successfully: \(saved)")
print("Check your \"Role\" class in Parse Dashboard.")
//: Store the saved role so we can use it later...
savedRole = saved
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print("Error: \(error)")
}
}
//: Lets check to see if our Role has saved.
if savedRole != nil {
print("We have a saved Role")
}
//: Users can be added to our previously saved Role.
do {
//: `ParseRoles` have `ParseRelations` that relate them either `ParseUser` and `ParseRole` objects.
//: The `ParseUser` relations can be accessed using `users`. We can then add `ParseUser`'s to the relation.
try savedRole!.users.add([User.current!]).save { result in
switch result {
case .success(let saved):
print("The role saved successfully: \(saved)")
print("Check \"users\" field in your \"Role\" class in Parse Dashboard.")
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print("Error: \(error)")
}
//: To retrieve the users who are all Administrators, we need to query the relation.
let templateUser = User()
do {
try savedRole!.users.query(templateUser).find { result in
switch result {
case .success(let relatedUsers):
print("The following users are part of the \"\(savedRole!.name) role: \(relatedUsers)")
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print(error)
}
//: Of course, you can remove users from the roles as well.
do {
try savedRole!.users.remove([User.current!]).save { result in
switch result {
case .success(let saved):
print("The role removed successfully: \(saved)")
print("Check \"users\" field in your \"Role\" class in Parse Dashboard.")
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print(error)
}
//: Additional roles can be created and tied to already created roles. Lets create a "Member" role.
//: This variable will store the saved role.
var savedRoleModerator: Role<User>?
//: We need another ACL.
var acl = ParseACL()
acl.setReadAccess(user: User.current!, value: true)
acl.setWriteAccess(user: User.current!, value: false)
do {
//: Create the actual Role with a name and ACL.
let memberRole = try Role<User>(name: "Member", acl: acl)
memberRole.save { result in
switch result {
case .success(let saved):
print("The role saved successfully: \(saved)")
print("Check your \"Role\" class in Parse Dashboard.")
//: Store the saved role so we can use it later...
savedRoleModerator = saved
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print("Error: \(error)")
}
//: Lets check to see if our Role has saved
if savedRoleModerator != nil {
print("We have a saved Role")
}
//: Roles can be added to our previously saved Role.
do {
//: `ParseRoles` have `ParseRelations` that relate them either `ParseUser` and `ParseRole` objects.
//: The `ParseUser` relations can be accessed using `users`. We can then add `ParseUser`'s to the relation.
try savedRole!.roles.add([savedRoleModerator!]).save { result in
switch result {
case .success(let saved):
print("The role saved successfully: \(saved)")
print("Check \"roles\" field in your \"Role\" class in Parse Dashboard.")
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print("Error: \(error)")
}
//: To retrieve the users who are all Administrators, we need to query the relation.
//: This time we will use a helper query from `ParseRole`.
savedRole!.queryRoles?.find { result in
switch result {
case .success(let relatedRoles):
print("The following roles are part of the \"\(savedRole!.name) role: \(relatedRoles)")
case .failure(let error):
print("Error saving role: \(error)")
}
}
//: Of course, you can remove users from the roles as well.
do {
try savedRole!.roles.remove([savedRoleModerator!]).save { result in
switch result {
case .success(let saved):
print("The role removed successfully: \(saved)")
print("Check the \"roles\" field in your \"Role\" class in Parse Dashboard.")
case .failure(let error):
print("Error saving role: \(error)")
}
}
} catch {
print(error)
}
//: All `ParseObject`s have a `ParseRelation` attribute that be used on instances.
//: For example, the User has:
let relation = User.current!.relation
//: Example: relation.add(<#T##users: [ParseUser]##[ParseUser]#>)
//: Example: relation.remove(<#T##key: String##String#>, objects: <#T##[ParseObject]#>)
//: Using this relation, you can create many-to-many relationships with other `ParseObjecs`,
//: similar to `users` and `roles`.
PlaygroundPage.current.finishExecution()
//: [Next](@next)
| 30.527897 | 111 | 0.628567 |
d905c1093b1a2f557a86d1e17898a0fc128492d4 | 1,403 | //
// UIViewControllerExt.swift
// RxSwiftX
//
// Created by Pircate on 2018/5/2.
// Copyright © 2018年 Pircate. All rights reserved.
//
import RxSwift
import RxCocoa
public extension Reactive where Base: UIViewController {
func push(_ viewController: @escaping @autoclosure () -> UIViewController,
animated: Bool = true)
-> Binder<Void> {
Binder(base) { this, _ in
this.navigationController?.pushViewController(viewController(), animated: animated)
}
}
func pop(animated: Bool = true) -> Binder<Void> {
Binder(base) { this, _ in
this.navigationController?.popViewController(animated: animated)
}
}
func popToRoot(animated: Bool = true) -> Binder<Void> {
Binder(base) { this, _ in
this.navigationController?.popToRootViewController(animated: animated)
}
}
func present(_ viewController: @escaping @autoclosure () -> UIViewController,
animated: Bool = true,
completion: (() -> Void)? = nil)
-> Binder<Void> {
Binder(base) { this, _ in
this.present(viewController(), animated: animated, completion: completion)
}
}
func dismiss(animated: Bool = true) -> Binder<Void> {
Binder(base) { this, _ in
this.dismiss(animated: animated, completion: nil)
}
}
}
| 28.632653 | 95 | 0.600855 |
22f294c7cce6ea1ae917dcfad0894e514432ca1c | 1,713 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
// MARK: Internal Helpers
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) {
NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
return regex.stringByReplacingMatchesInString(string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template)
} catch {
// no-op
}
return nil
}
| 34.26 | 155 | 0.640397 |
7943bff629e7756aaf34550d8db6e6249d5b9161 | 925 | //
// tipTests.swift
// tipTests
//
// Created by Neha Shah on 8/1/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import XCTest
@testable import tip
class tipTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.428571 | 111 | 0.658378 |
dbb00daf06b7c6430477433507d284786fbd28c9 | 402 | import XCTest
@testable import CompressPublishPlugin
final class CompressPublishPluginTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual("Hello, World!", "Hello, World!")
}
}
| 33.5 | 91 | 0.621891 |
f5637c7806820883c1089f77cd23f8ff538020fe | 1,120 | //
// TestNewInboxRulesetOptions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import AnyCodable
import AnyCodable
@objc public class TestNewInboxRulesetOptions: NSObject, Codable {
public var inboxRulesetTestOptions: InboxRulesetTestOptions
public var createInboxRulesetOptions: CreateInboxRulesetOptions
public init(inboxRulesetTestOptions: InboxRulesetTestOptions, createInboxRulesetOptions: CreateInboxRulesetOptions) {
self.inboxRulesetTestOptions = inboxRulesetTestOptions
self.createInboxRulesetOptions = createInboxRulesetOptions
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case inboxRulesetTestOptions
case createInboxRulesetOptions
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(inboxRulesetTestOptions, forKey: .inboxRulesetTestOptions)
try container.encode(createInboxRulesetOptions, forKey: .createInboxRulesetOptions)
}
}
| 30.27027 | 121 | 0.775893 |
03c35cdbea5546b0e3446588c4600a7575ce255c | 1,127 | //
// IsaiLopezPerez14022019StoryboardTests.swift
// IsaiLopezPerez14022019StoryboardTests
//
// Created by Universidad Politecnica de Gómez Palacio on 20/02/19.
// Copyright © 2019 Universidad Politecnica de Gómez Palacio. All rights reserved.
//
import XCTest
@testable import IsaiLopezPerez14022019Storyboard
class IsaiLopezPerez14022019StoryboardTests: 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.
}
}
}
| 30.459459 | 111 | 0.677906 |
284795f7c695912ccb1a970f6e3ceda1cd4d9fad | 5,640 | //
// HomeViewController.swift
// SwiftAnimationTransition
//
// Created by Jashion on 2017/2/6.
// Copyright © 2017年 BMu. All rights reserved.
//
import UIKit
import os.log
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate {
var items: [String] {
return ["Castle", "Web", "Sun", "Chart", "Signal"]
}
var myTable: UITableView {
let table = UITableView.init(frame: UIScreen.main.bounds, style: .plain)
table.dataSource = self as UITableViewDataSource
table.delegate = self as UITableViewDelegate
table.separatorStyle = .none
table.register(MyTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(MyTableViewCell.self))
return table
}
var selectedCell: MyTableViewCell?
var snapView: UIView?
var snapFrame: CGRect?
var transition: BMAnimateTransition?
var interactive: BMInteractiveTransition?
init() {
super.init(nibName: nil, bundle: nil)
self.navigationItem.title = "Home"
self.transition = BMAnimateTransition.init()
self.interactive = BMInteractiveTransition()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
self.view.addSubview(self.myTable)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.delegate = self
let leftButton = UIButton.init(type: .custom)
leftButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 44)
leftButton.setImage(UIImage.init(named: "HomeMenu")!, for: .normal)
leftButton.addTarget(self, action: #selector(HomeViewController.showMenuController), for: .touchUpInside)
let spaceItem = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spaceItem.width = -8
let leftItem = UIBarButtonItem.init(customView: leftButton)
self.navigationItem.leftBarButtonItems = [spaceItem, leftItem]
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(MyTableViewCell.self)) as! MyTableViewCell
cell.setCellImage(image: UIImage.init(named: items[indexPath.row])!)
return cell
}
//MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.frame.size.width*3/4
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedCell = tableView.cellForRow(at: indexPath) as? MyTableViewCell
self.snapView = self.selectedCell?.snapshotView(afterScreenUpdates: false)
self.snapFrame = self.selectedCell?.convert((self.selectedCell?.contentView.frame)!, to: self.view)
let detail = DetailViewController.init(title: items[indexPath.row], image: UIImage.init(named: items[indexPath.row])!)
detail.loadViewIfNeeded()
self.interactive?.wireToViewController(viewController: detail, operation: .snapViewTransfrom)
self.navigationController?.pushViewController(detail, animated: true)
}
@objc private func showMenuController() {
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .push {
let detail = toVC as! DetailViewController
self.transition?.operationType = .snapViewTransformPush
self.transition?.duration = 0.6
self.transition?.snapView = self.snapView
self.transition?.initialView = self.selectedCell
self.transition?.initialFrame = self.snapFrame
self.transition?.finalView = detail.topImageView
self.transition?.finalFrame = CGRect.init(x: 0, y: 64, width: (self.snapFrame?.size.width)!, height: (self.snapFrame?.size.height)!)
return self.transition
} else if operation == .pop {
let detail = fromVC as! DetailViewController
self.transition?.operationType = .snapViewTransformPop
self.transition?.duration = 0.6
self.transition?.snapView = detail.topImageView?.snapshotView(afterScreenUpdates: false)
self.transition?.initialView = detail.topImageView
self.transition?.initialFrame = detail.topImageView?.convert((detail.topImageView?.bounds)!, to: detail.view)
self.transition?.finalView = self.selectedCell
self.transition?.finalFrame = self.snapFrame!
return self.transition
} else {
return nil
}
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
guard let isInterative = self.interactive?.interacting else {
return nil
}
if (isInterative) {
return self.interactive
} else {
return nil
}
}
}
| 42.089552 | 246 | 0.679255 |
c1a4f71bfd85952eb331131ddd277db54dc0006d | 4,627 | import UIKit
import RealmSwift
import RxCocoa
import RxRealm
import RxSwift
// realm model
class Lap: Object {
@objc dynamic var time: TimeInterval = Date().timeIntervalSinceReferenceDate
}
class TickCounter: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var ticks: Int = 0
override static func primaryKey() -> String? { return "id" }
}
// view controller
class ViewController: UIViewController {
let bag = DisposeBag()
@IBOutlet var tableView: UITableView!
@IBOutlet var tickItemButton: UIBarButtonItem!
@IBOutlet var addTwoItemsButton: UIBarButtonItem!
var laps: Results<Lap>!
let footer: UILabel = {
let l = UILabel()
l.textAlignment = .center
return l
}()
lazy var ticker: TickCounter = {
let realm = try! Realm()
let ticker = TickCounter()
try! realm.write {
realm.add(ticker)
}
return ticker
}()
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
laps = realm.objects(Lap.self).sorted(byKeyPath: "time", ascending: false)
/*
Observable<Results<Lap>> - wrap Results as observable
*/
Observable.collection(from: laps)
.map { results in "laps: \(results.count)" }
.subscribe { event in
self.title = event.element
}
.disposed(by: bag)
/*
Observable<Results<Lap>> - reacting to change sets
*/
Observable.changeset(from: laps)
.subscribe(onNext: { [unowned self] _, changes in
if let changes = changes {
self.tableView.applyChangeset(changes)
} else {
self.tableView.reloadData()
}
})
.disposed(by: bag)
/*
Use bindable sink to add objects
*/
addTwoItemsButton.rx.tap
.map { [Lap(), Lap()] }
.bind(to: Realm.rx.add(onError: { elements, error in
if let elements = elements {
print("Error \(error.localizedDescription) while saving objects \(String(describing: elements))")
} else {
print("Error \(error.localizedDescription) while opening realm.")
}
}))
.disposed(by: bag)
/*
Bind bar item to increasing the ticker
*/
tickItemButton.rx.tap
.subscribe(onNext: { [unowned self] _ in
try! realm.write {
self.ticker.ticks += 1
}
})
.disposed(by: bag)
/*
Observing a single object
*/
let tickerChanges$ = Observable.propertyChanges(object: ticker)
tickerChanges$
.filter { $0.name == "ticks" }
.map { "\($0.newValue!) ticks" }
.bind(to: footer.rx.text)
.disposed(by: bag)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return laps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let lap = laps[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = formatter.string(from: Date(timeIntervalSinceReferenceDate: lap.time))
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Delete objects by tapping them, add ticks to trigger a footer update"
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
Observable.from([laps[indexPath.row]])
.subscribe(Realm.rx.delete())
.disposed(by: bag)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return footer
}
}
extension UITableView {
func applyChangeset(_ changes: RealmChangeset) {
beginUpdates()
deleteRows(at: changes.deleted.map { IndexPath(row: $0, section: 0) }, with: .automatic)
insertRows(at: changes.inserted.map { IndexPath(row: $0, section: 0) }, with: .automatic)
reloadRows(at: changes.updated.map { IndexPath(row: $0, section: 0) }, with: .automatic)
endUpdates()
}
}
| 31.053691 | 117 | 0.571645 |
ab158aaa34f29a1b18a75df5e158dd8c36777382 | 420 | /*: some text
# Swift Playgrounds entry
I wanted to focus this entry on . . .
This is because . . .
## How to Use:
Just do this . . . .
*/
/*:
This is just some setup code to run the playground, don't mess with it. :D
*/
// Code needed to setup and run the playground
import PlaygroundSupport
PlaygroundPage.current.liveView = ViewController()
PlaygroundPage.current.needsIndefiniteExecution = true
| 17.5 | 75 | 0.695238 |
87c231b0700f0bb74272f91c5a921790586ce169 | 446 | //
// ToastContainerVC.swift
// Pods
//
// Created by Franco Meloni on 26/08/16.
//
//
import UIKit
class ToastContainerVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIApplication.shared.statusBarStyle
}
override var prefersStatusBarHidden: Bool {
return UIApplication.shared.isStatusBarHidden
}
}
| 18.583333 | 60 | 0.692825 |
f82ba71f1c7a1a1d95a4f6471ec28f4e43a68db9 | 421 | //
// Constants.swift
// AnimeChest
//
// Created by Erik Kokaev on 5/16/21.
//
struct Constants {
struct Segues {
static let LoginToCollection = "LoginToCollection"
static let CollectionToAdd = "CollectionToAdd"
}
struct DatabaseReferences {
static let AnimeChild = "anime"
}
struct StorageReferences {
static let imagesFolder = "imagesFolder"
}
}
| 17.541667 | 56 | 0.624703 |
61767d7248dca9692981817b6d3ce53fad88b07b | 1,903 | //
// GroupedButtonStyle.swift
// NewTerm (iOS)
//
// Created by Adam Demasi on 16/9/21.
//
import SwiftUI
#if targetEnvironment(macCatalyst)
fileprivate typealias ButtonStyleSuperclass = PrimitiveButtonStyle
#else
fileprivate typealias ButtonStyleSuperclass = ButtonStyle
#endif
struct GroupedButtonStyle: ButtonStyleSuperclass {
func makeBody(configuration: Configuration) -> some View {
#if targetEnvironment(macCatalyst)
HStack {
Spacer()
Button(configuration)
Spacer()
}
#else
HStack {
configuration.label
Spacer()
Text(Image(systemName: "chevron.right"))
.foregroundColor(Color(UIColor.systemGray2))
.fontWeight(.semibold)
.imageScale(.small)
}
.padding([.top, .bottom], 7)
.padding([.leading, .trailing], 15)
.frame(minHeight: 44, alignment: .center)
.background(Color(configuration.isPressed ? UIColor.tertiarySystemGroupedBackground : UIColor.secondarySystemGroupedBackground))
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
.padding([.leading, .trailing], 15)
#endif
}
}
struct GroupedButtonStyle_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
VStack(spacing: 0) {
Button(
action: {},
label: {
HStack {
IconView(
icon: Image(systemName: "sparkles")
.resizable(),
backgroundColor: Color(UIColor.systemIndigo)
)
Text("Do stuff")
}
}
)
.buttonStyle(GroupedButtonStyle())
List {
NavigationLink(
destination: EmptyView(),
label: {
HStack {
IconView(
icon: Image(systemName: "sparkles")
.resizable(),
backgroundColor: Color(UIColor.systemGreen)
)
Text("List button comparison")
}
}
)
}
.listStyle(InsetGroupedListStyle())
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
| 22.127907 | 130 | 0.663163 |
fe06fd70c46450808ac37943c140d8796e22e645 | 2,333 | //
// SceneDelegate.swift
// Day4_RxSwift
//
// Created by 亿存 on 2020/7/10.
// Copyright © 2020 亿存. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.203704 | 147 | 0.712387 |
237cc1ef51a6eb00dca385147c0512050b950934 | 3,512 | //
// PageboyViewControllerDelegate.swift
// Pageboy
//
// Created by Merrick Sapsford on 24/11/2017.
// Copyright © 2018 UI At Six. All rights reserved.
//
import UIKit
public protocol PageboyViewControllerDelegate: class {
/// The page view controller will begin scrolling to a new page.
///
/// - Parameters:
/// - pageboyViewController: The Page view controller.
/// - index: The new page index.
/// - direction: The direction of the scroll.
/// - animation: Whether the scroll will be animated.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
willScrollToPageAt index: PageboyViewController.PageIndex,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
/// The page view controller did scroll to an offset between pages.
///
/// - Parameters:
/// - pageboyViewController: The Page view controller.
/// - position: The current relative page position.
/// - direction: The direction of the scroll.
/// - animated: Whether the scroll is being animated.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollTo position: CGPoint,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
/// The page view controller did not (!) complete scroll to a new page.
///
/// - Parameters:
/// - pageboyViewController: The Page view controller.
/// - index: The expected new page index, that was not (!) scrolled to.
/// - previousIndex: The page index returned to.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didCancelScrollToPageAt index: PageboyViewController.PageIndex,
returnToPageAt previousIndex: PageboyViewController.PageIndex)
/// The page view controller did complete scroll to a new page.
///
/// - Parameters:
/// - pageboyViewController: The Page view controller.
/// - index: The new page index.
/// - direction: The direction of the scroll.
/// - animation: Whether the scroll was animated.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollToPageAt index: PageboyViewController.PageIndex,
direction: PageboyViewController.NavigationDirection,
animated: Bool)
/// The page view controller did reload.
///
/// - Parameters:
/// - pageboyViewController: The Pageboy view controller.
/// - currentViewController: The current view controller.
/// - currentPageIndex: The current page index.
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didReloadWith currentViewController: UIViewController,
currentPageIndex: PageboyViewController.PageIndex)
}
public extension PageboyViewControllerDelegate {
func pageboyViewController(_ pageboyViewController: PageboyViewController,
didCancelScrollToPageAt index: PageboyViewController.PageIndex,
returnToPageAt previousIndex: PageboyViewController.PageIndex) {
// Default implementation
}
}
| 45.61039 | 95 | 0.634396 |
487d48b642693099f7bafa5d35dab25202691387 | 13,097 | //
// EmojiPicker.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/20/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
import SDWebImage
private typealias EmojiCategory = (name: String, emojis: [Emoji])
class EmojiPicker: UIView, RCEmojiKitLocalizable {
static let defaults = UserDefaults(suiteName: "EmojiPicker")
var customEmojis: [Emoji] = []
var customCategory: (name: String, emojis: [Emoji]) {
return (name: "custom", emojis: self.customEmojis)
}
var recentEmojis: [Emoji] {
get {
if let data = EmojiPicker.defaults?.value(forKey: "recentEmojis") as? Data {
let emojis = try? PropertyListDecoder().decode(Array<Emoji>.self, from: data)
return emojis ?? []
}
return []
}
set {
let emojis = newValue.count < 31 ? newValue : Array(newValue.dropLast(newValue.count - 30))
EmojiPicker.defaults?.set(try? PropertyListEncoder().encode(emojis), forKey: "recentEmojis")
}
}
var recentCategory: (name: String, emojis: [Emoji]) {
// remove invalid custom emojis
let recentEmojis = self.recentEmojis.filter {
guard case let .custom(imageUrl) = $0.type else { return true }
return customEmojis.contains(where: { $0.imageUrl == imageUrl })
}
return (name: "recent", emojis: recentEmojis)
}
fileprivate let defaultCategories: [EmojiCategory] = [
(name: "people", emojis: Emojione.people),
(name: "nature", emojis: Emojione.nature),
(name: "food", emojis: Emojione.food),
(name: "activity", emojis: Emojione.activity),
(name: "travel", emojis: Emojione.travel),
(name: "objects", emojis: Emojione.objects),
(name: "symbols", emojis: Emojione.symbols),
(name: "flags", emojis: Emojione.flags)
]
fileprivate var searchedCategories: [(name: String, emojis: [Emoji])] = []
fileprivate func searchCategories(string: String) -> [EmojiCategory] {
return ([customCategory] + defaultCategories).map {
let emojis = $0.emojis.filter {
$0.name.contains(string) || $0.shortname.contains(string) ||
$0.keywords.joined(separator: " ").contains(string) ||
$0.alternates.joined(separator: " ").contains(string)
}
return (name: $0.name, emojis: emojis)
}.filter { !$0.emojis.isEmpty }
}
var isSearching: Bool {
return searchBar?.text != nil && searchBar?.text?.isEmpty != true
}
fileprivate var currentCategories: [EmojiCategory] {
if isSearching { return searchedCategories }
let recent = (recentEmojis.count > 0 ? [recentCategory] : [])
let custom = (customEmojis.count > 0 ? [customCategory] : [])
return recent + custom + defaultCategories
}
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var categoriesView: UITabBar!
@IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.placeholder = localized("searchbar.placeholder")
searchBar.delegate = self
}
}
@IBOutlet weak var emojisCollectionView: UICollectionView!
let skinTones: [(name: String?, color: UIColor)] = [
(name: nil, color: #colorLiteral(red: 0.999120295, green: 0.8114234805, blue: 0.06628075987, alpha: 1)),
(name: "tone1", color: #colorLiteral(red: 0.982526958, green: 0.8808286786, blue: 0.7670835853, alpha: 1)),
(name: "tone2", color: #colorLiteral(red: 0.8934452534, green: 0.7645885944, blue: 0.6247871518, alpha: 1)),
(name: "tone3", color: #colorLiteral(red: 0.7776196599, green: 0.6034522057, blue: 0.4516467452, alpha: 1)),
(name: "tone4", color: #colorLiteral(red: 0.6469842792, green: 0.4368215203, blue: 0.272474587, alpha: 1)),
(name: "tone5", color: #colorLiteral(red: 0.391161263, green: 0.3079459369, blue: 0.2550256848, alpha: 1))
]
var currentSkinToneIndex: Int {
get {
return EmojiPicker.defaults?.integer(forKey: "currentSkinToneIndex") ?? 0
}
set {
EmojiPicker.defaults?.set(newValue, forKey: "currentSkinToneIndex")
}
}
var currentSkinTone: (name: String?, color: UIColor) {
return skinTones[currentSkinToneIndex]
}
@IBOutlet weak var skinToneButton: UIButton! {
didSet {
skinToneButton.layer.cornerRadius = skinToneButton.frame.width/2
skinToneButton.backgroundColor = currentSkinTone.color
skinToneButton.showsTouchWhenHighlighted = true
}
}
@IBAction func didPressSkinToneButton(_ sender: UIButton) {
currentSkinToneIndex += 1
currentSkinToneIndex = currentSkinToneIndex % skinTones.count
skinToneButton.backgroundColor = currentSkinTone.color
emojisCollectionView.reloadData()
}
var emojiPicked: ((String) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("EmojiPicker", owner: self, options: nil)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "|-0-[view]-0-|", options: [], metrics: nil, views: ["view": contentView]
)
)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": contentView]
)
)
}
private func setupCollectionView() {
emojisCollectionView.dataSource = self
emojisCollectionView.delegate = self
emojisCollectionView.register(EmojiCollectionViewCell.self, forCellWithReuseIdentifier: "EmojiCollectionViewCell")
emojisCollectionView.register(EmojiPickerSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "EmojiPickerSectionHeaderView")
if let layout = emojisCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.sectionHeadersPinToVisibleBounds = true
layout.headerReferenceSize = CGSize(width: self.frame.width, height: 20)
}
emojisCollectionView.contentInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}
private func setupCategoriesView() {
let categoryItems = currentCategories.map { category -> UITabBarItem in
let image = UIImage(named: category.name) ?? UIImage(named: "custom")
let item = UITabBarItem(title: nil, image: image, selectedImage: image)
item.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
return item
}
categoriesView.setItems(categoryItems, animated: false)
categoriesView.delegate = self
categoriesView.layoutIfNeeded()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
setupCategoriesView()
setupCollectionView()
}
}
extension EmojiPicker: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return currentCategories.count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: "EmojiPickerSectionHeaderView",
for: indexPath
) as? EmojiPickerSectionHeaderView else { return UICollectionReusableView() }
headerView.textLabel.text = localized("categories.\(currentCategories[indexPath.section].name)")
return headerView
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return currentCategories[section].emojis.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCollectionViewCell", for: indexPath) as? EmojiCollectionViewCell else { return UICollectionViewCell() }
let emoji = currentCategories[indexPath.section].emojis[indexPath.row]
if let file = emoji.imageUrl {
cell.emoji = .custom(URL(string: file))
} else {
var toneModifier = ""
if emoji.supportsTones, let currentTone = currentSkinTone.name { toneModifier = "_\(currentTone)" }
let searchString = String(emoji.shortname.dropFirst().dropLast()) + toneModifier
cell.emoji = .standard(Emojione.values[searchString])
}
return cell
}
}
extension EmojiPicker: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchedCategories = searchCategories(string: searchText.lowercased())
emojisCollectionView.reloadData()
}
}
extension EmojiPicker: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 36.0, height: 36.0)
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emoji = currentCategories[indexPath.section].emojis[indexPath.row]
if emoji.supportsTones, let currentTone = currentSkinTone.name {
let shortname = String(emoji.shortname.dropLast()) + "_\(currentTone):"
emojiPicked?(shortname)
} else {
emojiPicked?(emoji.shortname)
}
if let index = recentEmojis.index(where: { $0.shortname == emoji.shortname }) {
recentEmojis.remove(at: index)
}
recentEmojis = [emoji] + recentEmojis
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 36.0)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let first = collectionView.indexPathsForVisibleItems.first {
categoriesView.selectedItem = categoriesView.items?[first.section]
}
}
}
extension EmojiPicker: UITabBarDelegate {
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let index = tabBar.items?.index(of: item) else { return }
searchBar.resignFirstResponder()
searchBar.text = ""
emojisCollectionView.reloadData()
emojisCollectionView.layoutIfNeeded()
let indexPath = IndexPath(row: 1, section: index)
emojisCollectionView.scrollToItem(at: indexPath, at: .top, animated: false)
emojisCollectionView.setContentOffset(emojisCollectionView.contentOffset.applying(CGAffineTransform(translationX: 0.0, y: -36.0)), animated: false)
}
}
private class EmojiPickerSectionHeaderView: UICollectionReusableView {
var textLabel: UILabel
let screenWidth = UIScreen.main.bounds.width
override init(frame: CGRect) {
textLabel = UILabel()
super.init(frame: frame)
addSubview(textLabel)
textLabel.font = .boldSystemFont(ofSize: UIFont.systemFontSize)
textLabel.textColor = .gray
textLabel.textAlignment = .left
textLabel.numberOfLines = 0
textLabel.lineBreakMode = .byWordWrapping
textLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
NSLayoutConstraint(item: textLabel, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leadingMargin,
multiplier: 1.0, constant: -8.0),
NSLayoutConstraint(item: textLabel, attribute: .trailing, relatedBy: .equal,
toItem: self, attribute: .trailingMargin,
multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: textLabel, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .height,
multiplier: 1.0, constant: 36.0)
])
backgroundColor = .white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 38.634218 | 191 | 0.655723 |
9cffc88402e9df831ef7b1c19bcca9099d6713ed | 29,257 | //
// AppDelegate.swift
// NetNewsWire
//
// Created by Brent Simmons on 7/11/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import UserNotifications
import Articles
import RSTree
import RSWeb
import Account
import RSCore
import RSCoreResources
import Secrets
import OSLog
import CrashReporter
// If we're not going to import Sparkle, provide dummy protocols to make it easy
// for AppDelegate to comply
#if MAC_APP_STORE || TEST
protocol SPUStandardUserDriverDelegate {}
protocol SPUUpdaterDelegate {}
#else
import Sparkle
#endif
var appDelegate: AppDelegate!
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidations, UNUserNotificationCenterDelegate, UnreadCountProvider, SPUStandardUserDriverDelegate, SPUUpdaterDelegate
{
private struct WindowRestorationIdentifiers {
static let mainWindow = "mainWindow"
}
var userNotificationManager: UserNotificationManager!
var faviconDownloader: FaviconDownloader!
var imageDownloader: ImageDownloader!
var authorAvatarDownloader: AuthorAvatarDownloader!
var webFeedIconDownloader: WebFeedIconDownloader!
var extensionContainersFile: ExtensionContainersFile!
var extensionFeedAddRequestFile: ExtensionFeedAddRequestFile!
var appName: String!
var refreshTimer: AccountRefreshTimer?
var syncTimer: ArticleStatusSyncTimer?
var lastRefreshInterval = AppDefaults.shared.refreshInterval
var shuttingDown = false {
didSet {
if shuttingDown {
refreshTimer?.shuttingDown = shuttingDown
refreshTimer?.invalidate()
syncTimer?.shuttingDown = shuttingDown
syncTimer?.invalidate()
}
}
}
var isShutDownSyncDone = false
@IBOutlet var debugMenuItem: NSMenuItem!
@IBOutlet var sortByOldestArticleOnTopMenuItem: NSMenuItem!
@IBOutlet var sortByNewestArticleOnTopMenuItem: NSMenuItem!
@IBOutlet var groupArticlesByFeedMenuItem: NSMenuItem!
@IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
var unreadCount = 0 {
didSet {
if unreadCount != oldValue {
CoalescingQueue.standard.add(self, #selector(updateDockBadge))
postUnreadCountDidChangeNotification()
}
}
}
private var mainWindowController: MainWindowController? {
var bestController: MainWindowController?
for candidateController in mainWindowControllers {
if let bestWindow = bestController?.window, let candidateWindow = candidateController.window {
if bestWindow.orderedIndex > candidateWindow.orderedIndex {
bestController = candidateController
}
} else {
bestController = candidateController
}
}
return bestController
}
private var mainWindowControllers = [MainWindowController]()
private var preferencesWindowController: NSWindowController?
private var addFeedController: AddFeedController?
private var addFolderWindowController: AddFolderWindowController?
private var importOPMLController: ImportOPMLWindowController?
private var exportOPMLController: ExportOPMLWindowController?
private var keyboardShortcutsWindowController: WebViewWindowController?
private var inspectorWindowController: InspectorWindowController?
private var crashReportWindowController: CrashReportWindowController? // For testing only
private let appMovementMonitor = RSAppMovementMonitor()
#if !MAC_APP_STORE && !TEST
private var softwareUpdater: SPUUpdater!
private var crashReporter: PLCrashReporter!
#endif
override init() {
NSWindow.allowsAutomaticWindowTabbing = false
super.init()
#if !MAC_APP_STORE
let crashReporterConfig = PLCrashReporterConfig.defaultConfiguration()
crashReporter = PLCrashReporter(configuration: crashReporterConfig)
crashReporter.enable()
#endif
SecretsManager.provider = Secrets()
AccountManager.shared = AccountManager(accountsFolder: Platform.dataSubfolder(forApplication: nil, folderName: "Accounts")!)
ArticleStylesManager.shared = ArticleStylesManager(folderPath: Platform.dataSubfolder(forApplication: nil, folderName: "Styles")!)
FeedProviderManager.shared.delegate = ExtensionPointManager.shared
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inspectableObjectsDidChange(_:)), name: .InspectableObjectsDidChange, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(didWakeNotification(_:)), name: NSWorkspace.didWakeNotification, object: nil)
appDelegate = self
}
// MARK: - API
func showAddFolderSheetOnWindow(_ window: NSWindow) {
addFolderWindowController = AddFolderWindowController()
addFolderWindowController!.runSheetOnWindow(window)
}
func showAddWebFeedSheetOnWindow(_ window: NSWindow, urlString: String?, name: String?, account: Account?, folder: Folder?) {
addFeedController = AddFeedController(hostWindow: window)
addFeedController?.showAddFeedSheet(.webFeed, urlString, name, account, folder)
}
// MARK: - NSApplicationDelegate
func applicationWillFinishLaunching(_ notification: Notification) {
installAppleEventHandlers()
CacheCleaner.purgeIfNecessary()
// Try to establish a cache in the Caches folder, but if it fails for some reason fall back to a temporary dir
let cacheFolder: String
if let userCacheFolder = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).path {
cacheFolder = userCacheFolder
}
else {
let bundleIdentifier = (Bundle.main.infoDictionary!["CFBundleIdentifier"]! as! String)
cacheFolder = (NSTemporaryDirectory() as NSString).appendingPathComponent(bundleIdentifier)
}
let faviconsFolder = (cacheFolder as NSString).appendingPathComponent("Favicons")
let faviconsFolderURL = URL(fileURLWithPath: faviconsFolder)
try! FileManager.default.createDirectory(at: faviconsFolderURL, withIntermediateDirectories: true, attributes: nil)
faviconDownloader = FaviconDownloader(folder: faviconsFolder)
let imagesFolder = (cacheFolder as NSString).appendingPathComponent("Images")
let imagesFolderURL = URL(fileURLWithPath: imagesFolder)
try! FileManager.default.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil)
imageDownloader = ImageDownloader(folder: imagesFolder)
authorAvatarDownloader = AuthorAvatarDownloader(imageDownloader: imageDownloader)
webFeedIconDownloader = WebFeedIconDownloader(imageDownloader: imageDownloader, folder: cacheFolder)
appName = (Bundle.main.infoDictionary!["CFBundleExecutable"]! as! String)
}
func applicationDidFinishLaunching(_ note: Notification) {
#if MAC_APP_STORE || TEST
checkForUpdatesMenuItem.isHidden = true
#else
// Initialize Sparkle...
let hostBundle = Bundle.main
let updateDriver = SPUStandardUserDriver(hostBundle: hostBundle, delegate: self)
self.softwareUpdater = SPUUpdater(hostBundle: hostBundle, applicationBundle: hostBundle, userDriver: updateDriver, delegate: self)
do {
try self.softwareUpdater.start()
}
catch {
NSLog("Failed to start software updater with error: \(error)")
}
#endif
AppDefaults.shared.registerDefaults()
let isFirstRun = AppDefaults.shared.isFirstRun
if isFirstRun {
os_log(.debug, "Is first run.")
}
let localAccount = AccountManager.shared.defaultAccount
if isFirstRun && !AccountManager.shared.anyAccountHasAtLeastOneFeed() {
// Import feeds. Either old NNW 3 feeds or the default feeds.
if !NNW3ImportController.importSubscriptionsIfFileExists(account: localAccount) {
DefaultFeedsImporter.importDefaultFeeds(account: localAccount)
}
}
updateSortMenuItems()
updateGroupByFeedMenuItem()
if mainWindowController == nil {
let mainWindowController = createAndShowMainWindow()
mainWindowController.restoreStateFromUserDefaults()
}
if isFirstRun {
mainWindowController?.window?.center()
}
NotificationCenter.default.addObserver(self, selector: #selector(webFeedSettingDidChange(_:)), name: .WebFeedSettingDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
DispatchQueue.main.async {
self.unreadCount = AccountManager.shared.unreadCount
}
if InspectorWindowController.shouldOpenAtStartup {
self.toggleInspectorWindow(self)
}
extensionContainersFile = ExtensionContainersFile()
extensionFeedAddRequestFile = ExtensionFeedAddRequestFile()
refreshTimer = AccountRefreshTimer()
syncTimer = ArticleStatusSyncTimer()
UNUserNotificationCenter.current().requestAuthorization(options:[.badge]) { (granted, error) in }
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
DispatchQueue.main.async {
NSApplication.shared.registerForRemoteNotifications()
}
}
}
UNUserNotificationCenter.current().delegate = self
userNotificationManager = UserNotificationManager()
#if DEBUG
refreshTimer!.update()
syncTimer!.update()
#else
if AppDefaults.shared.suppressSyncOnLaunch {
refreshTimer!.update()
syncTimer!.update()
} else {
DispatchQueue.main.async {
self.refreshTimer!.timedRefresh(nil)
self.syncTimer!.timedRefresh(nil)
}
}
#endif
if AppDefaults.shared.showDebugMenu {
// The Web Inspector uses SPI and can never appear in a MAC_APP_STORE build.
#if MAC_APP_STORE
let debugMenu = debugMenuItem.submenu!
let toggleWebInspectorItemIndex = debugMenu.indexOfItem(withTarget: self, andAction: #selector(toggleWebInspectorEnabled(_:)))
if toggleWebInspectorItemIndex != -1 {
debugMenu.removeItem(at: toggleWebInspectorItemIndex)
}
#endif
} else {
debugMenuItem.menu?.removeItem(debugMenuItem)
}
#if !MAC_APP_STORE
DispatchQueue.main.async {
CrashReporter.check(crashReporter: self.crashReporter)
}
#endif
}
func application(_ application: NSApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([NSUserActivityRestoring]) -> Void) -> Bool {
guard let mainWindowController = mainWindowController else {
return false
}
mainWindowController.handle(userActivity)
return true
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
// https://github.com/brentsimmons/NetNewsWire/issues/522
// I couldn’t reproduce the crashing bug, but it appears to happen on creating a main window
// and its views and view controllers. The check below is so that the app does nothing
// if the window doesn’t already exist — because it absolutely *should* exist already.
// And if the window exists, then maybe the views and view controllers are also already loaded?
// We’ll try this, and then see if we get more crash logs like this or not.
guard let mainWindowController = mainWindowController, mainWindowController.isWindowLoaded else {
return false
}
mainWindowController.showWindow(self)
return false
}
func applicationDidBecomeActive(_ notification: Notification) {
fireOldTimers()
}
func applicationDidResignActive(_ notification: Notification) {
ArticleStringFormatter.emptyCaches()
saveState()
}
func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
AccountManager.shared.receiveRemoteNotification(userInfo: userInfo)
}
func applicationWillTerminate(_ notification: Notification) {
shuttingDown = true
saveState()
AccountManager.shared.sendArticleStatusAll() {
self.isShutDownSyncDone = true
}
let timeout = Date().addingTimeInterval(2)
while !isShutDownSyncDone && RunLoop.current.run(mode: .default, before: .distantFuture) && timeout > Date() { }
}
// MARK: Notifications
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is AccountManager {
unreadCount = AccountManager.shared.unreadCount
}
}
@objc func webFeedSettingDidChange(_ note: Notification) {
guard let feed = note.object as? WebFeed, let key = note.userInfo?[WebFeed.WebFeedSettingUserInfoKey] as? String else {
return
}
if key == WebFeed.WebFeedSettingKey.homePageURL || key == WebFeed.WebFeedSettingKey.faviconURL {
let _ = faviconDownloader.favicon(for: feed)
}
}
@objc func inspectableObjectsDidChange(_ note: Notification) {
guard let inspectorWindowController = inspectorWindowController, inspectorWindowController.isOpen else {
return
}
inspectorWindowController.objects = objectsForInspector()
}
@objc func userDefaultsDidChange(_ note: Notification) {
updateSortMenuItems()
updateGroupByFeedMenuItem()
if lastRefreshInterval != AppDefaults.shared.refreshInterval {
refreshTimer?.update()
lastRefreshInterval = AppDefaults.shared.refreshInterval
}
updateDockBadge()
}
@objc func didWakeNotification(_ note: Notification) {
fireOldTimers()
}
// MARK: Main Window
func createMainWindowController() -> MainWindowController {
let controller: MainWindowController
if #available(macOS 11.0, *) {
controller = windowControllerWithName("UnifiedWindow") as! MainWindowController
} else {
controller = windowControllerWithName("MainWindow") as! MainWindowController
}
if !(mainWindowController?.isOpen ?? false) {
mainWindowControllers.removeAll()
}
mainWindowControllers.append(controller)
return controller
}
func windowControllerWithName(_ storyboardName: String) -> NSWindowController {
let storyboard = NSStoryboard(name: NSStoryboard.Name(storyboardName), bundle: nil)
return storyboard.instantiateInitialController()! as! NSWindowController
}
@discardableResult
func createAndShowMainWindow() -> MainWindowController {
let controller = createMainWindowController()
controller.showWindow(self)
if let window = controller.window {
window.restorationClass = Self.self
window.identifier = NSUserInterfaceItemIdentifier(rawValue: WindowRestorationIdentifiers.mainWindow)
}
return controller
}
func createAndShowMainWindowIfNecessary() {
if mainWindowController == nil {
createAndShowMainWindow()
} else {
mainWindowController?.showWindow(self)
}
}
func removeMainWindow(_ windowController: MainWindowController) {
guard mainWindowControllers.count > 1 else { return }
if let index = mainWindowControllers.firstIndex(of: windowController) {
mainWindowControllers.remove(at: index)
}
}
// MARK: NSUserInterfaceValidations
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
if shuttingDown {
return false
}
let isDisplayingSheet = mainWindowController?.isDisplayingSheet ?? false
let isSpecialAccountAvailable = AccountManager.shared.activeAccounts.contains(where: { $0.type == .onMyMac || $0.type == .cloudKit })
if item.action == #selector(refreshAll(_:)) {
return !AccountManager.shared.refreshInProgress && !AccountManager.shared.activeAccounts.isEmpty
}
if item.action == #selector(importOPMLFromFile(_:)) {
return AccountManager.shared.activeAccounts.contains(where: { !$0.behaviors.contains(where: { $0 == .disallowOPMLImports }) })
}
if item.action == #selector(addAppNews(_:)) {
return !isDisplayingSheet && !AccountManager.shared.anyAccountHasNetNewsWireNewsSubscription() && !AccountManager.shared.activeAccounts.isEmpty
}
if item.action == #selector(sortByNewestArticleOnTop(_:)) || item.action == #selector(sortByOldestArticleOnTop(_:)) {
return mainWindowController?.isOpen ?? false
}
if item.action == #selector(showAddWebFeedWindow(_:)) || item.action == #selector(showAddFolderWindow(_:)) {
return !isDisplayingSheet && !AccountManager.shared.activeAccounts.isEmpty
}
if item.action == #selector(showAddRedditFeedWindow(_:)) {
guard !isDisplayingSheet && isSpecialAccountAvailable && ExtensionPointManager.shared.isRedditEnabled else {
return false
}
return ExtensionPointManager.shared.isRedditEnabled
}
if item.action == #selector(showAddTwitterFeedWindow(_:)) {
guard !isDisplayingSheet && isSpecialAccountAvailable && ExtensionPointManager.shared.isTwitterEnabled else {
return false
}
return ExtensionPointManager.shared.isTwitterEnabled
}
#if !MAC_APP_STORE
if item.action == #selector(toggleWebInspectorEnabled(_:)) {
(item as! NSMenuItem).state = AppDefaults.shared.webInspectorEnabled ? .on : .off
}
#endif
return true
}
// MARK: UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
switch response.actionIdentifier {
case "MARK_AS_READ":
handleMarkAsRead(userInfo: userInfo)
case "MARK_AS_STARRED":
handleMarkAsStarred(userInfo: userInfo)
default:
mainWindowController?.handle(response)
}
completionHandler()
}
// MARK: Add Feed
func addWebFeed(_ urlString: String?, name: String? = nil, account: Account? = nil, folder: Folder? = nil) {
createAndShowMainWindowIfNecessary()
if mainWindowController!.isDisplayingSheet {
return
}
showAddWebFeedSheetOnWindow(mainWindowController!.window!, urlString: urlString, name: name, account: account, folder: folder)
}
// MARK: - Dock Badge
@objc func updateDockBadge() {
let label = unreadCount > 0 ? "\(unreadCount)" : ""
NSApplication.shared.dockTile.badgeLabel = label
}
// MARK: - Actions
@IBAction func showPreferences(_ sender: Any?) {
if preferencesWindowController == nil {
preferencesWindowController = windowControllerWithName("Preferences")
}
preferencesWindowController!.showWindow(self)
}
@IBAction func newMainWindow(_ sender: Any?) {
createAndShowMainWindow()
}
@IBAction func showMainWindow(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
mainWindowController?.window?.makeKey()
}
@IBAction func refreshAll(_ sender: Any?) {
AccountManager.shared.refreshAll(errorHandler: ErrorHandler.present)
}
@IBAction func showAddWebFeedWindow(_ sender: Any?) {
addWebFeed(nil)
}
@IBAction func showAddRedditFeedWindow(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
addFeedController = AddFeedController(hostWindow: mainWindowController!.window!)
addFeedController?.showAddFeedSheet(.redditFeed)
}
@IBAction func showAddTwitterFeedWindow(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
addFeedController = AddFeedController(hostWindow: mainWindowController!.window!)
addFeedController?.showAddFeedSheet(.twitterFeed)
}
@IBAction func showAddFolderWindow(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
showAddFolderSheetOnWindow(mainWindowController!.window!)
}
@IBAction func showKeyboardShortcutsWindow(_ sender: Any?) {
if keyboardShortcutsWindowController == nil {
keyboardShortcutsWindowController = WebViewWindowController(title: NSLocalizedString("Keyboard Shortcuts", comment: "window title"))
let htmlFile = Bundle(for: type(of: self)).path(forResource: "KeyboardShortcuts", ofType: "html")!
keyboardShortcutsWindowController?.displayContents(of: htmlFile)
if let window = keyboardShortcutsWindowController?.window {
let point = NSPoint(x: 128, y: 64)
let size = NSSize(width: 620, height: 1100)
let minSize = NSSize(width: 400, height: 400)
window.setPointAndSizeAdjustingForScreen(point: point, size: size, minimumSize: minSize)
}
}
keyboardShortcutsWindowController!.showWindow(self)
}
@IBAction func toggleInspectorWindow(_ sender: Any?) {
if inspectorWindowController == nil {
inspectorWindowController = (windowControllerWithName("Inspector") as! InspectorWindowController)
}
if inspectorWindowController!.isOpen {
inspectorWindowController!.window!.performClose(self)
}
else {
inspectorWindowController!.objects = objectsForInspector()
inspectorWindowController!.showWindow(self)
}
}
@IBAction func importOPMLFromFile(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
if mainWindowController!.isDisplayingSheet {
return
}
importOPMLController = ImportOPMLWindowController()
importOPMLController?.runSheetOnWindow(mainWindowController!.window!)
}
@IBAction func importNNW3FromFile(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
if mainWindowController!.isDisplayingSheet {
return
}
NNW3ImportController.askUserToImportNNW3Subscriptions(window: mainWindowController!.window!)
}
@IBAction func exportOPML(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
if mainWindowController!.isDisplayingSheet {
return
}
exportOPMLController = ExportOPMLWindowController()
exportOPMLController?.runSheetOnWindow(mainWindowController!.window!)
}
@IBAction func addAppNews(_ sender: Any?) {
if AccountManager.shared.anyAccountHasNetNewsWireNewsSubscription() {
return
}
addWebFeed(AccountManager.netNewsWireNewsURL, name: "NetNewsWire News")
}
@IBAction func openWebsite(_ sender: Any?) {
Browser.open("https://netnewswire.com/", inBackground: false)
}
@IBAction func openReleaseNotes(_ sender: Any?) {
Browser.open(URL.releaseNotes.absoluteString, inBackground: false)
}
@IBAction func openHowToSupport(_ sender: Any?) {
Browser.open("https://github.com/brentsimmons/NetNewsWire/blob/main/Technotes/HowToSupportNetNewsWire.markdown", inBackground: false)
}
@IBAction func openRepository(_ sender: Any?) {
Browser.open("https://github.com/brentsimmons/NetNewsWire", inBackground: false)
}
@IBAction func openBugTracker(_ sender: Any?) {
Browser.open("https://github.com/brentsimmons/NetNewsWire/issues", inBackground: false)
}
@IBAction func openSlackGroup(_ sender: Any?) {
Browser.open("https://netnewswire.com/slack", inBackground: false)
}
@IBAction func openTechnotes(_ sender: Any?) {
Browser.open("https://github.com/brentsimmons/NetNewsWire/tree/main/Technotes", inBackground: false)
}
@IBAction func showHelp(_ sender: Any?) {
Browser.open("https://netnewswire.com/help/mac/6.0/en/", inBackground: false)
}
@IBAction func donateToAppCampForGirls(_ sender: Any?) {
Browser.open("https://appcamp4girls.com/contribute/", inBackground: false)
}
@IBAction func showPrivacyPolicy(_ sender: Any?) {
Browser.open("https://netnewswire.com/privacypolicy", inBackground: false)
}
@IBAction func gotoToday(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
mainWindowController!.gotoToday(sender)
}
@IBAction func gotoAllUnread(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
mainWindowController!.gotoAllUnread(sender)
}
@IBAction func gotoStarred(_ sender: Any?) {
createAndShowMainWindowIfNecessary()
mainWindowController!.gotoStarred(sender)
}
@IBAction func sortByOldestArticleOnTop(_ sender: Any?) {
AppDefaults.shared.timelineSortDirection = .orderedAscending
}
@IBAction func sortByNewestArticleOnTop(_ sender: Any?) {
AppDefaults.shared.timelineSortDirection = .orderedDescending
}
@IBAction func groupByFeedToggled(_ sender: NSMenuItem) {
AppDefaults.shared.timelineGroupByFeed.toggle()
}
@IBAction func checkForUpdates(_ sender: Any?) {
#if !MAC_APP_STORE && !TEST
self.softwareUpdater.checkForUpdates()
#endif
}
}
// MARK: - Debug Menu
extension AppDelegate {
@IBAction func debugSearch(_ sender: Any?) {
AccountManager.shared.defaultAccount.debugRunSearch()
}
@IBAction func debugDropConditionalGetInfo(_ sender: Any?) {
#if DEBUG
AccountManager.shared.activeAccounts.forEach{ $0.debugDropConditionalGetInfo() }
#endif
}
@IBAction func debugTestCrashReporterWindow(_ sender: Any?) {
#if DEBUG
crashReportWindowController = CrashReportWindowController(crashLogText: "This is a test crash log.")
crashReportWindowController!.testing = true
crashReportWindowController!.showWindow(self)
#endif
}
@IBAction func debugTestCrashReportSending(_ sender: Any?) {
CrashReporter.sendCrashLogText("This is a test. Hi, Brent.")
}
@IBAction func forceCrash(_ sender: Any?) {
fatalError("This is a deliberate crash.")
}
@IBAction func openApplicationSupportFolder(_ sender: Any?) {
#if DEBUG
guard let appSupport = Platform.dataSubfolder(forApplication: nil, folderName: "") else { return }
NSWorkspace.shared.open(URL(fileURLWithPath: appSupport))
#endif
}
@IBAction func toggleWebInspectorEnabled(_ sender: Any?) {
#if !MAC_APP_STORE
let newValue = !AppDefaults.shared.webInspectorEnabled
AppDefaults.shared.webInspectorEnabled = newValue
// An attached inspector can display incorrectly on certain setups (like mine); default to displaying in a separate window,
// and reset the default to a separate window when the preference is toggled off and on again in case the inspector is
// accidentally reattached.
AppDefaults.shared.webInspectorStartsAttached = false
NotificationCenter.default.post(name: .WebInspectorEnabledDidChange, object: newValue)
#endif
}
}
private extension AppDelegate {
func fireOldTimers() {
// It’s possible there’s a refresh timer set to go off in the past.
// In that case, refresh now and update the timer.
refreshTimer?.fireOldTimer()
syncTimer?.fireOldTimer()
}
func objectsForInspector() -> [Any]? {
guard let window = NSApplication.shared.mainWindow, let windowController = window.windowController as? MainWindowController else {
return nil
}
return windowController.selectedObjectsInSidebar()
}
func saveState() {
mainWindowController?.saveStateToUserDefaults()
inspectorWindowController?.saveState()
}
func updateSortMenuItems() {
let sortByNewestOnTop = AppDefaults.shared.timelineSortDirection == .orderedDescending
sortByNewestArticleOnTopMenuItem.state = sortByNewestOnTop ? .on : .off
sortByOldestArticleOnTopMenuItem.state = sortByNewestOnTop ? .off : .on
}
func updateGroupByFeedMenuItem() {
let groupByFeedEnabled = AppDefaults.shared.timelineGroupByFeed
groupArticlesByFeedMenuItem.state = groupByFeedEnabled ? .on : .off
}
}
/*
the ScriptingAppDelegate protocol exposes a narrow set of accessors with
internal visibility which are very similar to some private vars.
These would be unnecessary if the similar accessors were marked internal rather than private,
but for now, we'll keep the stratification of visibility
*/
extension AppDelegate : ScriptingAppDelegate {
internal var scriptingMainWindowController: ScriptingMainWindowController? {
return mainWindowController
}
internal var scriptingCurrentArticle: Article? {
return self.scriptingMainWindowController?.scriptingCurrentArticle
}
internal var scriptingSelectedArticles: [Article] {
return self.scriptingMainWindowController?.scriptingSelectedArticles ?? []
}
}
extension AppDelegate: NSWindowRestoration {
@objc static func restoreWindow(withIdentifier identifier: NSUserInterfaceItemIdentifier, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) {
var mainWindow: NSWindow? = nil
if identifier.rawValue == WindowRestorationIdentifiers.mainWindow {
mainWindow = appDelegate.createAndShowMainWindow().window
}
completionHandler(mainWindow, nil)
}
}
// Handle Notification Actions
private extension AppDelegate {
func handleMarkAsRead(userInfo: [AnyHashable: Any]) {
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any],
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String else {
return
}
let account = AccountManager.shared.existingAccount(with: accountID)
guard account != nil else {
os_log(.debug, "No account found from notification.")
return
}
let article = try? account!.fetchArticles(.articleIDs([articleID]))
guard article != nil else {
os_log(.debug, "No article found from search using %@", articleID)
return
}
account!.markArticles(article!, statusKey: .read, flag: true) { _ in }
}
func handleMarkAsStarred(userInfo: [AnyHashable: Any]) {
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any],
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String else {
return
}
let account = AccountManager.shared.existingAccount(with: accountID)
guard account != nil else {
os_log(.debug, "No account found from notification.")
return
}
let article = try? account!.fetchArticles(.articleIDs([articleID]))
guard article != nil else {
os_log(.debug, "No article found from search using %@", articleID)
return
}
account!.markArticles(article!, statusKey: .starred, flag: true) { _ in }
}
}
| 33.474828 | 207 | 0.768944 |
f5eaea9d2e114552e9839a168976a4fb2c971674 | 1,051 | //
// NEAvRoomUserDetail.swift
// NELiveRoom
//
// Created by vvj on 2021/8/31.
//
import Foundation
@objc
open class NEAvRoomUserDetail: NSObject {
@objc
public var avRoomCName: String?
/// 音视频房间ID
@objc
public var avRoomUid: String?
/// joinrtc所需token
@objc
public var avRoomCheckSum: String?
/// 账号id
@objc
public var accountId: String?
@objc
public var channelId: String?
/// 昵称
@objc
public var nickName: String?
@objc
override init() {
super.init()
}
/// 初始化方法
init(dictionary: [AnyHashable: Any?]) {
super.init()
self.avRoomCName = dictionary["avRoomCName"] as? String
self.avRoomUid = dictionary["avRoomUid"] as? String
self.avRoomCheckSum = dictionary["avRoomCheckSum"] as? String
self.accountId = dictionary["accountId"] as? String
self.channelId = dictionary["channelId"] as? String
self.nickName = dictionary["nickName"] as? String
}
}
| 19.830189 | 69 | 0.598478 |
567cc32b4b28485fddf66007f14e664eb4edc681 | 1,574 | //
// ScopeNode.swift
// Cub
//
// Created by Louis D'hauwe on 15/11/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
internal class ScopeNode {
weak var parentNode: ScopeNode?
var childNodes: [ScopeNode]
var registerMap: [String : Int]
var functionMap: [String : FunctionMapped]
var internalRegisters: [Int]
// TODO: make Set?
// 0 = reg id
// 1 = decompiled var name
var registersToClean: [(Int, String?)]
init(parentNode: ScopeNode? = nil, childNodes: [ScopeNode]) {
self.parentNode = parentNode
self.childNodes = childNodes
registerMap = [String: Int]()
functionMap = [String: FunctionMapped]()
internalRegisters = [Int]()
registersToClean = [(Int, String?)]()
}
func addRegistersToCleanToParent() {
parentNode?.registersToClean.append(contentsOf: registersToClean)
}
/// Get deep register map (including parents' register map)
func deepRegisterMap() -> [String : Int] {
if let parentNode = parentNode {
// Recursive
var parentMap = parentNode.deepRegisterMap()
registerMap.forEach {
parentMap[$0.0] = $0.1
}
return parentMap
}
return registerMap
}
/// Get deep function map (including parents' function map)
func deepFunctionMap() -> [String : FunctionMapped] {
if let parentNode = parentNode {
// Recursive
var parentMap = parentNode.deepFunctionMap()
functionMap.forEach {
parentMap[$0.0] = $0.1
}
return parentMap
}
return functionMap
}
}
struct FunctionMapped {
let id: Int
let exitId: Int
let returns: Bool
}
| 18.091954 | 67 | 0.683609 |
fbd92432e426f3bc7b1d5f64fc991947464afb43 | 2,421 | /// Copyright (c) 2020 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.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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
extension UIImageView {
func loadImage(url: URL) -> URLSessionDownloadTask {
let session = URLSession.shared
let downloadTask = session.downloadTask(with: url) { [weak self] url, _, error in
if error == nil, let url = url,
let data = try? Data(contentsOf: url),
let image = UIImage(data: data) {
DispatchQueue.main.async {
if let weakSelf = self {
weakSelf.image = image
}
}
}
}
downloadTask.resume()
return downloadTask
}
}
| 45.679245 | 85 | 0.721603 |
e5b1e1a0a9ba84caa7069e8665a66d08ac28b1df | 1,772 | // Copyright (c) 2021 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import XCTest
import SWCompression
class BZip2Tests: XCTestCase {
private static let testType: String = "bz2"
func perform(test testName: String) throws {
let testData = try Constants.data(forTest: testName, withType: BZip2Tests.testType)
let decompressedData = try BZip2.decompress(data: testData)
let answerData = try Constants.data(forAnswer: testName)
XCTAssertEqual(decompressedData, answerData)
}
func test1BZip2() throws {
try self.perform(test: "test1")
}
func test2BZip2() throws {
try self.perform(test: "test2")
}
func test3BZip2() throws {
try self.perform(test: "test3")
}
func test4BZip2() throws {
try self.perform(test: "test4")
}
func test5BZip2() throws {
try self.perform(test: "test5")
}
func test6BZip2() throws {
try self.perform(test: "test6")
}
func test7BZip2() throws {
try self.perform(test: "test7")
}
func test8BZip2() throws {
try self.perform(test: "test8")
}
func test9BZip2() throws {
try self.perform(test: "test9")
}
func testNonStandardRunLength() throws {
try self.perform(test: "test_nonstandard_runlength")
}
func testBadFile_short() {
XCTAssertThrowsError(try BZip2.decompress(data: Data([0])))
}
func testBadFile_invalid() throws {
let testData = try Constants.data(forAnswer: "test6")
XCTAssertThrowsError(try BZip2.decompress(data: testData))
}
func testEmptyData() throws {
XCTAssertThrowsError(try BZip2.decompress(data: Data()))
}
}
| 23.626667 | 91 | 0.638262 |
ddb0491f0a1444ac8744005bbeb01010e7078778 | 669 | //
// SourceLinkView.swift
// Fructus
//
// Created by Oscar Rodriguez Garrucho on 24/6/21.
//
import SwiftUI
struct SourceLinkView: View {
var body: some View {
GroupBox() {
HStack {
Text("Content source")
Spacer()
Link("Wikipedia", destination: URL(string: "https://wikipedia.com")!)
Image(systemName: "arrow.up.right.square")
}
.font(.footnote)
}
}
}
struct SourceLinkView_Previews: PreviewProvider {
static var previews: some View {
SourceLinkView()
.previewLayout(.sizeThatFits)
.padding()
}
}
| 21.580645 | 85 | 0.542601 |
2f1fb6f67c38a953cb9d1fdbe63ffcf155961de2 | 2,167 | //
// AppDelegate.swift
// FXKit
//
// Created by feixue299 on 04/06/2021.
// Copyright (c) 2021 feixue299. 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 throttle down OpenGL ES frame rates. 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 inactive 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.106383 | 285 | 0.754038 |
870813bc7a951aa422f372bb9d97c6069f7e1ef5 | 3,600 | //
// FxCloudSelectAddressCellViewModel.swift
// XWallet
//
// Created by HeiHuaBaiHua on 2020/6/2.
// Copyright © 2020 Andy.Chan 6K. All rights reserved.
//
import WKKit
import RxSwift
import RxCocoa
import FunctionX
import SwiftyJSON
import TrustWalletCore
//MARK: AddressListViewModel
extension FxAnyNodeSelectAddressViewController {
class FCListViewModel: ListViewModel {
let hrp: String
let token: String
let nodeUrl: String
let derivationTemplate: String?
init(_ wallet: Wallet, hrp: String, derivationTemplate: String? = nil, nodeUrl: String, token: String) {
self.hrp = hrp
self.token = token
self.nodeUrl = nodeUrl
self.derivationTemplate = derivationTemplate
super.init(wallet)
}
override func cellVM(derivationAddress: Int) -> CellViewModel {
let cellVM = FCCellViewModel(wallet, derivationAddress: derivationAddress, hrp: hrp, derivationTemplate: derivationTemplate, nodeUrl: nodeUrl, token: token)
cellVM.refreshIfNeed()
return cellVM
}
}
}
//MARK: AddressCellViewModel
extension FxAnyNodeSelectAddressViewController {
class FCCellViewModel: CellViewModel {
let hrp: String
let path: String
let token: String
let nodeUrl: String
init(_ wallet: Wallet, derivationAddress: Int, hrp: String, derivationTemplate: String? = nil, nodeUrl: String, token: String) {
self.hrp = hrp
self.token = token
self.nodeUrl = nodeUrl
let template = derivationTemplate ?? "m/44'/118'/0'/0/0"
var components = template.components(separatedBy: "/")
components.removeLast()
components.append(String(derivationAddress))
self.path = components.joined(separator: "/")
super.init(wallet, derivationAddress: derivationAddress)
}
override var derivationPath: String { path }
override func generateAddress() -> String {
return FunctionXAddress(hrpString: hrp, publicKey: publicKey.data)?.description ?? ""
}
lazy var node: FxNode = FxNode(endpoints: FxNode.Endpoints(rpc: nodeUrl), wallet: nil)
private(set) var balance = ""
public let balanceText = BehaviorRelay<String>(value: TR("Updating") + "...")
var fetchBalance: Observable<String> {
if balance != "" { return Observable.just(balance) }
weak var welf = self
return node.query(address: address)
.do(onNext: { welf?.hanlder(result: $0) },
onError: { welf?.hanlder(error: $0) })
.map{ _ in return welf?.balance ?? "0" }
}
func refreshIfNeed() {
_ = fetchBalance.subscribe({ (_) in })
}
private func hanlder(result: JSON? = nil, error: Error? = nil) {
if let result = result {
let accountInfo = SmsUser.instance(fromQuery: result)
for coin in accountInfo.coins {
if coin.denom == token.lowercased() {
balance = coin.amount
break
}
}
}
let balanceText = balance.isEmpty ? "--" : balance.fxc.thousandth()
self.balanceText.accept(balanceText)
}
}
}
| 33.64486 | 168 | 0.565833 |
8a65a27c431285e329ba3f20a94713bacf7085f8 | 1,363 | //
// UsecaseScanMRZ.swift
// ReadyToUseUIDemo
//
// Created by Sebastian Husche on 02.07.18.
// Copyright © 2018 doo GmbH. All rights reserved.
//
import Foundation
class UsecaseScanMRZ: Usecase, SBSDKUIMRZScannerViewControllerDelegate {
override func start(presenter: UIViewController) {
super.start(presenter: presenter)
let configuration = SBSDKUIMRZScannerConfiguration.default()
configuration.textConfiguration.cancelButtonTitle = "Done"
configuration.uiConfiguration.finderAspectRatio = SBSDKAspectRatio(width: 3, andHeight: 1)
let scanner = SBSDKUIMRZScannerViewController.createNew(with: configuration, andDelegate: self)
self.presentViewController(scanner)
}
func mrzDetectionViewController(_ viewController: SBSDKUIMRZScannerViewController,
didDetect zone: SBSDKMachineReadableZoneRecognizerResult) {
let title = "MRZ detected"
let message = zone.stringRepresentation()
viewController.isRecognitionEnabled = false
UIAlertController.showInfoAlert(title, message: message, presenter: viewController) {
viewController.isRecognitionEnabled = true
}
}
func mrzDetectionViewControllerDidCancel(_ viewController: SBSDKUIMRZScannerViewController) {
self.didFinish()
}
}
| 33.243902 | 103 | 0.718269 |
f8238e193c02366b6b1dcabe07365af3f4da2688 | 686 | //
// StoryboardTests.swift
// ToDoTests
//
// Created by Kazuki Ohara on 2019/02/12.
// Copyright © 2019 Kazuki Ohara. All rights reserved.
//
import XCTest
@testable import ToDo
class StoryboardTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func test_InitialViewController_IsItemListViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
let rootViewController = navigationController?.viewControllers[0]
XCTAssertTrue(rootViewController is ItemListViewController)
}
}
| 23.655172 | 107 | 0.721574 |
e258b02eabc4fb9b9add5654a3a7c55d23aae531 | 895 | //
// ViewController.swift
// AppBottomActionSheet
//
// Created by karthikAdaptavant on 03/21/2018.
// Copyright (c) 2018 karthikAdaptavant. All rights reserved.
//
import UIKit
import AppBottomActionSheet
class ViewController: UIViewController, HalfSheetPresentingProtocol {
var transitionManager: HalfSheetPresentationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnAct(_ sender: Any) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
presentUsingHalfSheet(vc)
}
}
| 27.121212 | 147 | 0.707263 |
e9c688c5a99dafe7823d921c38be62158d09ed66 | 4,512 | //
// FixedList.swift
//
//
// Created by Nail Sharipov on 26.11.2021.
//
public struct FixedList<T> {
private struct Node<T> {
var prev: Int
var next: Int
var value: T
}
private let empty: T
public private (set) var set: IntSet
public private (set) var buffer: [T]
@inline(__always)
public var count: Int { self.set.count }
@inline(__always)
public var first: T? {
let index = set.first
if index != .empty {
return buffer[index]
} else {
return nil
}
}
@inline(__always)
public var sequence: [T] {
var result = [T]()
result.reserveCapacity(count)
set.forEach { index in
result.append(buffer[index])
}
return result
}
@inline(__always)
public var indices: [Int] { self.set.sequence }
@inline(__always)
public subscript(index: Int) -> T {
get {
return buffer[index]
}
set {
self.insert(index, value: newValue)
}
}
public init(size: Int, empty: T) {
self.empty = empty
self.set = IntSet(size: size)
buffer = .init(repeating: empty, count: size)
}
public init(array: [T], empty: T) {
let size = array.count
self.empty = empty
self.set = IntSet(size: size, array: Array(0..<size))
buffer = array
}
@inline(__always)
public func contains(_ index: Int) -> Bool { set.contains(index) }
// @inlinable
@inline(__always)
public func contains(where predicate: (T) -> Bool) -> Bool {
for index in set.sequence {
if predicate(buffer[index]) {
return true
}
}
return false
}
// @inlinable
@inline(__always)
public func contains(where predicate: (Int, T) -> (Bool)) -> Bool {
for index in set.sequence {
if predicate(index, buffer[index]) {
return true
}
}
return false
}
@inline(__always)
public mutating func insert(_ index: Int, value: T) {
assert(index < buffer.count)
buffer[index] = value
set.insert(index)
}
@inline(__always)
public mutating func remove(_ index: Int) {
assert(index < buffer.count)
guard set.contains(index) else { return }
buffer[index] = empty
set.remove(index)
}
@inline(__always)
public mutating func removeAll() {
set.removeAll()
for i in 0..<buffer.count {
buffer[i] = empty
}
}
// @inlinable
@inline(__always)
public func firstIndex(where predicate: (T) -> (Bool)) -> Int {
for index in set.sequence {
if predicate(buffer[index]) {
return index
}
}
return .empty
}
// @inlinable
@inline(__always)
public func firstIndex(where predicate: (Int, T) -> (Bool)) -> Int {
for index in set.sequence {
if predicate(index, buffer[index]) {
return index
}
}
return .empty
}
// @inlinable
@inline(__always)
public func first(where predicate: (T) -> (Bool)) -> T? {
for index in set.sequence {
let value = buffer[index]
if predicate(value) {
return value
}
}
return nil
}
// @inlinable
@inline(__always)
public func forEachIndex(_ body: (Int) -> ()) {
self.set.forEach(body)
}
}
extension FixedList: CustomDebugStringConvertible, CustomStringConvertible {
public var debugDescription: String {
var result = String()
result.append("\n")
result.append("set: \(self.set.debugDescription)\n")
result.append("buffer: \(self.buffer.debugDescription)\n")
return result
}
public var description: String {
var result = String()
result.append("\n")
result.append("set: \(self.set.debugDescription)\n")
result.append("buffer: \(self.buffer.debugDescription)\n")
return result
}
}
extension FixedList: CustomReflectable {
public var customMirror: Mirror {
Mirror(self, children: [
"count": self.count,
"set": self.set.sequence,
"buffer": buffer
])
}
}
| 23.138462 | 76 | 0.526596 |
f49942b05784097e4de5f91a0e304a1a86f92f4f | 3,948 | //
// JSONHubProtocol.swift
// SignalRClient
//
// Created by Pawel Kadluczka on 8/27/17.
// Copyright © 2017 Pawel Kadluczka. All rights reserved.
//
import Foundation
public class JSONHubProtocol: HubProtocol {
private static let recordSeparator = UInt8(0x1e)
private let encoder: JSONEncoder
private let decoder: JSONDecoder
private let logger: Logger
public let name = "json"
public let version = 1
public let type = ProtocolType.Text
public init(logger: Logger,
encoder: JSONEncoder = JSONEncoder(),
decoder: JSONDecoder = JSONDecoder()) {
self.logger = logger
self.encoder = encoder
self.decoder = decoder
}
public func parseMessages(input: Data) throws -> [HubMessage] {
let payloads = input.split(separator: JSONHubProtocol.recordSeparator)
// do not try to parse the last payload if it is not terminated with record sparator
var count = payloads.count
if count > 0 && input.last != JSONHubProtocol.recordSeparator {
logger.log(logLevel: .warning, message: "Partial message received. Here be dragons...")
count = count - 1
}
logger.log(logLevel: .debug, message: "Payload contains \(count) message(s)")
return try payloads[0..<count].map{ try createHubMessage(payload: $0) }
}
public func createHubMessage(payload: Data) throws -> HubMessage {
logger.log(logLevel: .debug, message: "Message received: \(String(data: payload, encoding: .utf8) ?? "(empty)")")
do {
let messageType = try getMessageType(payload: payload)
switch messageType {
case .Invocation:
return try decoder.decode(ClientInvocationMessage.self, from: payload)
case .StreamItem:
return try decoder.decode(StreamItemMessage.self, from: payload)
case .Completion:
return try decoder.decode(CompletionMessage.self, from: payload)
case .Ping:
return PingMessage.instance
case .Close:
return try decoder.decode(CloseMessage.self, from: payload)
default:
logger.log(logLevel: .error, message: "Unsupported messageType: \(messageType)")
throw SignalRError.unknownMessageType
}
} catch {
throw SignalRError.protocolViolation(underlyingError: error)
}
}
private func getMessageType(payload: Data) throws -> MessageType {
struct MessageTypeHelper: Decodable {
let type: MessageType
private enum CodingKeys: String, CodingKey { case type }
}
do {
return try decoder.decode(MessageTypeHelper.self, from: payload).type
} catch {
logger.log(logLevel: .error, message: "Getting messageType failed: \(error)")
throw SignalRError.protocolViolation(underlyingError: error)
}
}
public func writeMessage(message: HubMessage) throws -> Data {
var payload = try createMessageData(message: message)
payload.append(JSONHubProtocol.recordSeparator)
return payload
}
private func createMessageData(message: HubMessage) throws -> Data {
switch message.type {
case .Invocation:
return try encoder.encode(message as! ServerInvocationMessage)
case .StreamItem:
return try encoder.encode(message as! StreamItemMessage)
case .StreamInvocation:
return try encoder.encode(message as! StreamInvocationMessage)
case .CancelInvocation:
return try encoder.encode(message as! CancelInvocationMessage)
case .Completion:
return try encoder.encode(message as! CompletionMessage)
default:
throw SignalRError.invalidOperation(message: "Unexpected MessageType.")
}
}
}
| 37.6 | 121 | 0.636778 |
293e534181c3c916d89e54cf897c88a9aa51197f | 1,536 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 3.0.1.11917
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
How a capability statement is intended to be used.
URL: http://hl7.org/fhir/capability-statement-kind
ValueSet: http://hl7.org/fhir/ValueSet/capability-statement-kind
*/
public enum CapabilityStatementKind: String, FHIRPrimitiveType {
/// The CapabilityStatement instance represents the present capabilities of a specific system instance. This is the
/// kind returned by OPTIONS for a FHIR server end-point.
case instance = "instance"
/// The CapabilityStatement instance represents the capabilities of a system or piece of software, independent of a
/// particular installation.
case capability = "capability"
/// The CapabilityStatement instance represents a set of requirements for other systems to meet; e.g. as part of an
/// implementation guide or 'request for proposal'.
case requirements = "requirements"
}
| 36.571429 | 117 | 0.749349 |
8a45406b2d55ccfdc15183b2f9399e45685485f5 | 2,544 | //
// IFCache.swift
// IFCacheKit
//
// Created by Ivan Foong on 7/9/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import Foundation
public class IFCache<Key: NSObject, Value: NSObject where Key: protocol<NSCoding, Hashable, NSCopying>, Value: protocol<NSCoding, NSCopying>> : IFCacheProtocol {
typealias K = Key
typealias V = Value
public let diskCache:IFDiskCache<K, V>
public let memoryCache:IFMemoryCache<K, V>
public init(cacheDirectoryPath: String, lruItemSize: Int) {
self.diskCache = IFDiskCache(cacheDirectoryPath: cacheDirectoryPath)
self.memoryCache = IFMemoryCache(capacity: lruItemSize)
}
public func all() -> Dictionary<K, V> {
return get(Set(self.diskCache._index.keys.array))
}
public func get(keys: Set<K>) -> Dictionary<K, V> {
var results = Dictionary<K, V>()
var memoryCacheResults = self.memoryCache.get(keys)
let cacheMissedKeys = keys.subtract(Set(memoryCacheResults.keys.array))
var diskCacheResults = self.diskCache.get(cacheMissedKeys)
// add memory cache missed items into memory cache
for (k, v) in diskCacheResults {
self.memoryCache.put(k, value: v)
}
results = self.unionDictionary(memoryCacheResults, rightDictionary: diskCacheResults)
return results
}
public func remove(keys: Set<K>) -> Self {
self.memoryCache.remove(keys)
self.diskCache.remove(keys)
return self
}
public func clear() -> Self {
self.memoryCache.clear()
self.diskCache.clear()
return self;
}
public func put(key: K, value: V) -> Self {
return put(key, value: value, expiryDate: nil)
}
public func put(key: K, value: V, expiryDate: NSDate?) -> Self {
self.memoryCache.put(key, value: value, expiryDate: expiryDate)
self.diskCache.put(key, value: value, expiryDate: expiryDate)
return self;
}
public func size() -> Int {
return all().count
}
func unionDictionary<K, V>(leftDictionary: Dictionary<K, V>, rightDictionary: Dictionary<K, V>) -> Dictionary<K, V> {
var resultDictionary = Dictionary<K, V>()
for (k, v) in leftDictionary {
resultDictionary.updateValue(v, forKey: k)
}
for (k, v) in rightDictionary {
resultDictionary.updateValue(v, forKey: k)
}
return resultDictionary
}
} | 31.8 | 161 | 0.620676 |
894bc0b20b31a1b948a0f1e82e52c5f6d42af940 | 10,597 | //
// Model.swift
// WatsPLAN
//
// Created by Wenjiu Wang on 2020-06-14.
// Copyright © 2020 Jiawen Zhang. All rights reserved.
//
import Foundation
import FirebaseFirestore
import FirebaseAuth
import Firebase
import MaterialComponents.MaterialSnackbar
class Model: ObservableObject {
@Published var fileName = ""
@Published var facultyName = ""
@Published var majorName = ""
@Published var optionName = ""
@Published var changed = false
@Published var done = false
@Published var storedCards: [Card] = []
@Published var cards: [Card] = []
@Published var fContent: [String] = []
@Published var mContent: [String] = []
@Published var oContent: [String] = []
@Published var fileContent: [String] = []
let storage = Storage.storage()
private var db = Firestore.firestore()
func getCollection(type: Int) {
// Clear the cards
resetCard()
if type == 0 {
//load from db
if self.optionName == "!Just click CREATE button if no option" {
self.optionName = ""
}
var docRef = db.collection("/Majors/").document(self.optionName == "" ? self.majorName : self.majorName + " | " + self.optionName)
docRef.getDocument { (document, error) in
if let major = document.flatMap({
$0.data().flatMap({ (data) in
return Major(dictionary: data)
})
}) {
var count = 0
for item in major.Requirements {
let temp = item.components(separatedBy: ";")
self.storedCards.append(Card(id : count, text: temp[0], num: Int(temp[1]) ?? 0, items: [String](temp[2...temp.count-1])))
count += 1
}
self.cards.append(contentsOf: self.storedCards)
} else {
print("Document does not exist")
}
}
} else {
//load from storage
self.storedCards.removeAll()
self.cards.removeAll()
let fileManager = FileManager.default
let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(self.fileName + ".save")
do {
let data: [String] = try String(contentsOf: url).split(whereSeparator: \.isNewline).map(String.init)
self.facultyName = data[0]
let m_o = data[1].split(separator: "|").map(String.init)
self.majorName = String(m_o[0][..<m_o[0].endIndex])
self.optionName = (String(m_o[1][m_o[1].startIndex...]) == " " ? "" : String(m_o[1][m_o[1].startIndex...]))
var lineNum = 2
while lineNum < data.count {
let lineData = data[lineNum].split(separator: "?", omittingEmptySubsequences: false).map(String.init)
var curCard = Card(id: lineNum - 2, text: lineData[0], done: false, num: Int(lineData[3])!, items: lineData[5].split(separator: ";").map(String.init))
curCard.progress = Int(lineData[4])!
curCard.checkedBoxes = []
if lineData[2] != "" {
curCard.checkedBoxes = []
let sl = lineData[2].split(separator: ";").map(String.init)
for s in sl {
curCard.checkedBoxes.append(Int(s)!)
}
}
curCard.comment = lineData[6]
self.storedCards.append(curCard)
lineNum += 1
}
self.cards.append(contentsOf: self.storedCards)
} catch {
print(error.localizedDescription)
}
}
}
func fetchContent(s: String, type: Int) {
if (type == 0) {
self.majorName = ""
self.optionName = ""
} else if (type == 1) {
self.optionName = ""
}
if (type != 3){
//fetch from sever
db.collection(s).addSnapshotListener { (querySnapshot, error) in
DispatchQueue.main.async {
if error != nil {
print((error?.localizedDescription)!)
return
} else {
if type == 0 {
self.fContent = querySnapshot!.documents.map{queryDocumentSnapshot -> String in
return queryDocumentSnapshot.documentID }
} else if type == 1 {
self.mContent = querySnapshot!.documents.map{queryDocumentSnapshot -> String in
return queryDocumentSnapshot.documentID }
} else {
self.oContent = querySnapshot!.documents.map{queryDocumentSnapshot -> String in
return queryDocumentSnapshot.documentID }
}
}
}
}
} else {
//fetch.save files from local dir
self.fileContent.removeAll()
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
for save in (directoryContents.filter{ $0.pathExtension == "save" }) {
self.fileContent.append(save.lastPathComponent.components(separatedBy: ".")[0])
}
} catch {
print("error load from document")
}
}
}
func saveModel(name: String) {
var data = ""
data += self.facultyName + "\n"
data += self.majorName + " | " + self.optionName + "\n"
for c in self.cards {
data += c.text + "?"
data += "false" + "?"
data += c.checkedBoxes.map(String.init).joined(separator: ";") + "?"
data += String(c.num) + "?"
data += String(c.progress) + "?"
data += c.items.joined(separator: ";") + "?"
data += c.comment + "\n"
}
let fName = name + ".save"
let fileManager = FileManager.default
let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(fName)
do {
try data.write(to: url, atomically: true, encoding: .utf8)
} catch {
print(error.localizedDescription)
}
let currentUser = Auth.auth().currentUser
let currentUID = currentUser?.uid
if(currentUID != nil){
let storageRef = storage.reference(withPath: "userData/" + currentUID!)
let fileRef = storageRef.child(fName)
let uploadTask = fileRef.putFile(from: url, metadata: nil) { metadata, error in
if let error = error {
let message = MDCSnackbarMessage()
message.text = "Cloud Sync Fail"
message.duration = 2
MDCSnackbarManager.show(message)
print(error)
}
else{
let message = MDCSnackbarMessage()
message.text = "Cloud Sync Succeed"
message.duration = 2
MDCSnackbarManager.show(message)
}
/*guard let metadata = metadata else {
let message = MDCSnackbarMessage()
message.text = "Cloud Sync Fail"
message.duration = 2
MDCSnackbarManager.show(message)
print(error)
return
}*/
}
}
self.changed = false
self.fileName = name
}
func deleteFile() {
let fName = self.fileName + ".save"
let fileManager = FileManager.default
let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(fName)
do {
try fileManager.removeItem(at: url)
} catch {
print(error.localizedDescription)
}
let currentUser = Auth.auth().currentUser
let currentUID = currentUser?.uid
if(currentUID != nil){
let storageRef = storage.reference(withPath: "userData/" + currentUID!)
let fileRef = storageRef.child(fName)
let deleteTask = fileRef.delete { error in
if let error = error {
let message = MDCSnackbarMessage()
message.text = "Cloud Sync Fail"
message.duration = 2
MDCSnackbarManager.show(message)
print(error)
}
else{
let message = MDCSnackbarMessage()
message.text = "Cloud Sync Succeed"
message.duration = 2
MDCSnackbarManager.show(message)
}
}
}
self.fetchContent(s: "", type: 3)
}
func resetModel() {
self.cards.removeAll()
self.storedCards.removeAll()
self.fileName = ""
self.facultyName = ""
self.majorName = ""
self.optionName = ""
self.mContent = []
self.oContent = []
}
func resetCard() {
self.cards.removeAll()
self.storedCards.removeAll()
}
func resetName() {
self.fileName = ""
self.facultyName = ""
self.majorName = ""
self.optionName = ""
self.mContent = []
self.oContent = []
}
}
fileprivate struct Major {
let Requirements : [String]
init?(dictionary: [String: Any]) {
Requirements = dictionary["Requirements"] as! [String]
}
}
extension String: Identifiable {
public var id: String { self }
func stringAt(_ i: Int) -> String {
return String(Array(self)[i])
}
}
| 36.044218 | 171 | 0.490327 |
380e70c77e0f322c990dab9404eff1b0764ec343 | 455 | //
// Bool.swift
// GloryKit
//
// Created by Rolling Glory on 18/10/19.
// Copyright © 2019 Rolling Glory. All rights reserved.
//
import Foundation
/// Bool function helpers.
public extension Bool {
// MARK: - Vars
/// Return 1 if true, or 0 if false.
var int: Int {
return self ? 1 : 0
}
/// Return "true" if true, or "false" if false.
var string: String {
return self ? "true" : "false"
}
}
| 18.2 | 56 | 0.567033 |
e0cf536df6dac9011874ea187ae0b236913dc072 | 8,562 | //
// AppDelegate.swift
// CaffeineTimer
//
// Created by WataruSuzuki on 2016/01/18.
// Copyright © 2016年 WataruSuzuki. All rights reserved.
//
import UIKit
import UserNotifications
import DJKPurchaseService
@UIApplicationMain
class AppDelegate: UIResponder,
UNUserNotificationCenterDelegate,
UIApplicationDelegate
{
static let privacyPolicyUrl = "https://watarusuzuki.github.io/CaffeineTimer/PRIVACY_POLICY.html"
var window: UIWindow?
private var _launchedShortcutItem: AnyObject?
@available(iOS 9.0, *)
var launchedShortcutItem: UIApplicationShortcutItem? {
get {
return _launchedShortcutItem as? UIApplicationShortcutItem
}
set {
_launchedShortcutItem = newValue
}
}
static let applicationShortcutUserInfoIconKey = "applicationShortcutUserInfoIconKey"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
registerNotifications(application)
if #available(iOS 9.0, *) {
if #available(iOS 10.0, *) {
//do nothing
} else {
if let localNotification = launchOptions?[UIApplication.LaunchOptionsKey.localNotification] as? UILocalNotification {
if NSLocalizedString("digestion_caffeine", comment: "") == localNotification.alertBody {
//TODO
}
}
}
return shouldPerformAdditionalDelegateHandling(application, didFinishLaunchingWithOptions: launchOptions)
} else {
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 throttle down OpenGL ES frame rates. 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) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
}
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:.
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if "digestion_caffeine" == response.notification.request.identifier {
//TODO
}
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
completionHandler(handleShortCutItem(shortcutItem))
}
func registerNotifications(_ application: UIApplication) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, _) in
// got granted :)
}
} else {
let userNotificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
let settings = UIUserNotificationSettings(types: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
func shouldPerformAdditionalDelegateHandling(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let shouldPerformAdditionalDelegateHandling: Bool
// If a shortcut was launched, display its information and take the appropriate action
if let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
launchedShortcutItem = shortcutItem
// This will block "performActionForShortcutItem:completionHandler" from being called.
shouldPerformAdditionalDelegateHandling = false
} else {
shouldPerformAdditionalDelegateHandling = true
}
/*
// Install initial versions of our two extra dynamic shortcuts.
if let shortcutItems = application.shortcutItems where shortcutItems.isEmpty {
// Construct the items.
let shortcut3 = UIMutableApplicationShortcutItem(type: ShortcutIdentifier.Third.type, localizedTitle: "Play", localizedSubtitle: "Will Play an item", icon: UIApplicationShortcutIcon(type: .Play), userInfo: [
AppDelegate.applicationShortcutUserInfoIconKey: UIApplicationShortcutIconType.Play.rawValue
]
)
let shortcut4 = UIMutableApplicationShortcutItem(type: ShortcutIdentifier.Fourth.type, localizedTitle: "Pause", localizedSubtitle: "Will Pause an item", icon: UIApplicationShortcutIcon(type: .Pause), userInfo: [
AppDelegate.applicationShortcutUserInfoIconKey: UIApplicationShortcutIconType.Pause.rawValue
]
)
// Update the application providing the initial 'dynamic' shortcut items.
application.shortcutItems = [shortcut3, shortcut4]
}*/
return shouldPerformAdditionalDelegateHandling
}
func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool {
// Verify that the provided `shortcutItem`'s `type` is one handled by the application.
guard ShortcutIdentifier(fullType: shortcutItem.type) != nil else { return false }
guard let shortCutType = shortcutItem.type as String? else { return false }
launchedShortcutItem = shortcutItem
switch (shortCutType) {
case ShortcutIdentifier.First.type:
// Handle shortcut 1 (static).
return true
/*
case ShortcutIdentifier.Second.type:
// Handle shortcut 2 (static).
handled = true
break
case ShortcutIdentifier.Third.type:
// Handle shortcut 3 (dynamic).
handled = true
break
case ShortcutIdentifier.Fourth.type:
// Handle shortcut 4 (dynamic).
handled = true
break*/
default:
return false
}
}
enum ShortcutIdentifier: String {
case First
//case Second
//case Third
//case Fourth
// MARK: Initializers
init?(fullType: String) {
guard let last = fullType.components(separatedBy: ".").last else { return nil }
self.init(rawValue: last)
}
// MARK: Properties
var type: String {
return Bundle.main.bundleIdentifier! + ".\(self.rawValue)"
}
}
}
| 43.461929 | 285 | 0.66328 |
7a45b31a2a1223ad2815b76c36ed1e217509fa92 | 500 | //
// UserDefaults.swift
// ModularDemo
//
// Created by Oliver Eikemeier on 20.10.15.
// Copyright © 2015 Zalando SE. All rights reserved.
//
import Foundation
private let loggingPreferenceKey = "logging_preference"
func registerUserDefaults(userDefaults: NSUserDefaults) {
let defaults = [loggingPreferenceKey: false]
userDefaults.registerDefaults(defaults)
}
func loggingPreference(userDefaults: NSUserDefaults) -> Bool {
return userDefaults.boolForKey(loggingPreferenceKey)
}
| 23.809524 | 62 | 0.768 |
26480d36b988bbf6e4b3e1249333e4e93b592f05 | 1,503 |
import Foundation
@objc(SAStytch) public class Stytch: NSObject {
@objc public static let shared: Stytch = Stytch()
@objc public let magicLink: StytchMagicLink = StytchMagicLink()
@objc public let otp: StytchOTP = StytchOTP()
@objc public var environment: StytchEnvironment = .test{
didSet{
magicLink.environment = environment
otp.environment = environment
}
}
@objc public var `debug`: Bool = false{
didSet{
magicLink.debug = debug
otp.debug = debug
}
}
@objc public var createUserAsPending: Bool = false{
didSet{
magicLink.createUserAsPending = createUserAsPending
otp.createUserAsPending = createUserAsPending
}
}
private override init() {}
@objc public func configure(publicToken: String,
scheme: String,
host: String) {
magicLink.configure(publicToken: publicToken, scheme: scheme, host: host)
otp.configure(projectID: publicToken)
}
@objc public func configure(publicToken: String,
universalLink: URL) {
magicLink.configure(publicToken: publicToken, universalLink: universalLink)
otp.configure(projectID: publicToken)
}
//For just configuring OTP without Magic Link config.
@objc public func configure(projectID: String) {
otp.configure(projectID: projectID)
}
}
| 29.470588 | 83 | 0.612774 |
ac5accfdfe127e3fb5fdede3f604a781694fc680 | 3,222 | import Foundation
import Logging
import NIO
import NIOHTTP1
import NIOTLS
#if canImport(NIOSSL)
import NIOSSL
#endif
import ElasticSwiftCore
//MARK:- Timeouts
public class Timeouts {
public static let DEFAULT_TIMEOUTS: Timeouts = Timeouts(read: TimeAmount.milliseconds(1000), connect: TimeAmount.milliseconds(3000))
public let read: TimeAmount?
public let connect: TimeAmount?
public init(read: TimeAmount? = nil, connect: TimeAmount? = nil) {
self.read = read
self.connect = connect
}
}
//MARK:- HTTPAdaptorConfiguration
/// Class holding HTTPAdaptor Config
public class HTTPClientAdaptorConfiguration: HTTPAdaptorConfiguration {
public let adaptor: ManagedHTTPClientAdaptor.Type
public let timeouts: Timeouts?
public let eventLoopProvider: EventLoopProvider
#if canImport(NIOSSL)
// ssl config for swift-nio-ssl based clients
public let sslcontext: NIOSSLContext?
public init(adaptor: ManagedHTTPClientAdaptor.Type = DefaultHTTPClientAdaptor.self, eventLoopProvider: EventLoopProvider = .create(threads: 1), timeouts: Timeouts? = Timeouts.DEFAULT_TIMEOUTS, sslContext: NIOSSLContext? = nil) {
self.eventLoopProvider = eventLoopProvider
self.timeouts = timeouts
self.sslcontext = sslContext
self.adaptor = adaptor
}
#else
public init(adaptor: ManagedHTTPClientAdaptor.Type = DefaultHTTPClientAdaptor.self, eventLoopProvider: EventLoopProvider = .create(threads: 1), timeouts: Timeouts? = Timeouts.DEFAULT_TIMEOUTS) {
self.eventLoopProvider = eventLoopProvider
self.timeouts = timeouts
self.adaptor = adaptor
}
#endif
public static var `default`: HTTPAdaptorConfiguration {
get {
return HTTPClientAdaptorConfiguration()
}
}
}
public class URLSessionAdaptorConfiguration: HTTPAdaptorConfiguration {
public let adaptor: ManagedHTTPClientAdaptor.Type
public let timeouts: Timeouts?
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
// URLSession basic SSL support for apple platform
// ssl config for URLSession based clients
public let sslConfig: SSLConfiguration?
public init(adaptor: ManagedHTTPClientAdaptor.Type = URLSessionAdaptor.self, timeouts: Timeouts? = Timeouts.DEFAULT_TIMEOUTS, sslConfig: SSLConfiguration? = nil) {
self.timeouts = timeouts
self.sslConfig = sslConfig
self.adaptor = adaptor
}
#else
public init(adaptor: ManagedHTTPClientAdaptor.Type = URLSessionAdaptor.self, timeouts: Timeouts? = Timeouts.DEFAULT_TIMEOUTS) {
self.timeouts = timeouts
self.adaptor = adaptor
}
#endif
public static var `default`: HTTPAdaptorConfiguration {
get {
return URLSessionAdaptorConfiguration()
}
}
}
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
public class SSLConfiguration {
let certPath: String
let isSelfSigned: Bool
public init(certPath: String, isSelf isSelfSigned: Bool) {
self.certPath = certPath
self.isSelfSigned = isSelfSigned
}
}
#endif
| 28.017391 | 232 | 0.688392 |
cccae3ac099dadca5337f56796f264e45222fbc3 | 2,383 | //
// SceneDelegate.swift
// Pitch Perfect
//
// Created by aekachai tungrattanavalee on 17/1/2563 BE.
// Copyright © 2563 aekachai tungrattanavalee. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.12963 | 147 | 0.716744 |
f85fdf49d45fe4507f67b21283dede7ef57c6724 | 1,709 | //
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// 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 Quick
final class DefaultsBestFroggiesEnumSerializableSpec: QuickSpec, DefaultsSerializableSpec {
typealias Serializable = BestFroggiesEnum
var customValue: BestFroggiesEnum = .Andy
var defaultValue: BestFroggiesEnum = .Dandy
var keyStore = FrogKeyStore<Serializable>()
override func spec() {
given("BestFroggiesEnum") {
self.testValues()
self.testOptionalValues()
self.testOptionalValuesWithoutDefaultValue()
self.testObserving()
}
}
}
| 38.840909 | 91 | 0.739029 |
099ea5440f79dc6ffa192a571cbd883f2e6621d8 | 4,877 | //
// FactoryExtensionTests.swift
// SaberTests
//
// Created by andrey.pleshkov on 29/06/2018.
//
import XCTest
@testable import Saber
class FactoryExtensionTests: XCTestCase {
func testInit() {
let parsedFactory = ParsedDataFactory()
try! FileParser(contents:
"""
// @saber.container(App)
// @saber.scope(Singleton)
// @saber.externals(Bar)
protocol AppConfig {}
// @saber.scope(Singleton)
struct Foo {
init() {}
}
extension Foo {
// @saber.inject
init(bar: Bar) {}
}
"""
).parse(to: parsedFactory)
let repo = try! TypeRepository(parsedData: parsedFactory.make())
let containers = try! ContainerFactory(repo: repo).make()
XCTAssertEqual(
containers.first?.services,
[
Service(
typeResolver: .explicit(
TypeDeclaration(
name: "Foo",
initializer: .some(
args: [
FunctionInvocationArgument(
name: "bar",
typeResolver: .external(
TypeUsage(name: "Bar")
)
)
]
)
)
),
storage: .none
)
]
)
}
func testInjectors() {
let parsedFactory = ParsedDataFactory()
try! FileParser(contents:
"""
// @saber.container(App)
// @saber.scope(Singleton)
// @saber.externals(Bar, Baz)
protocol AppConfig {}
// @saber.scope(Singleton)
struct Foo {}
extension Foo {
// @saber.inject
var bar: Bar {
set {}
get {}
}
// @saber.inject
func set(baz: Baz) {}
// @saber.didInject
func postInject() {}
}
"""
).parse(to: parsedFactory)
let repo = try! TypeRepository(parsedData: parsedFactory.make())
let containers = try! ContainerFactory(repo: repo).make()
XCTAssertEqual(
containers.first?.services,
[
Service(
typeResolver: .explicit(
TypeDeclaration(
name: "Foo",
memberInjections: [
MemberInjection(
name: "bar",
typeResolver: .external(
TypeUsage(name: "Bar")
)
)
],
methodInjections: [
InstanceMethodInjection(
methodName: "set",
args: [
FunctionInvocationArgument(
name: "baz",
typeResolver: .external(
TypeUsage(name: "Baz")
)
)
]
)
],
didInjectHandlerName: "postInject"
)
),
storage: .none
)
]
)
}
func testUnknown() {
let parsedFactory = ParsedDataFactory()
try! FileParser(contents:
"""
// @saber.container(App)
// @saber.scope(Singleton)
protocol AppConfig {}
extension Foo {
// @saber.inject
var bar: Bar {
set {}
get {}
}
// @saber.inject
func set(baz: Baz) {}
// @saber.didInject
func postInject() {}
}
"""
).parse(to: parsedFactory)
let repo = try! TypeRepository(parsedData: parsedFactory.make())
let containers = try! ContainerFactory(repo: repo).make()
XCTAssertEqual(
containers.first?.services,
[]
)
}
}
| 30.48125 | 72 | 0.349395 |
d7293f48e0b5716698e9dcf577eace14fef9b6b6 | 1,721 | //
// MockURLProtocol.swift
// OMDb_Sample
//
// Created by Pavitra Hegde on 23/03/20.
// Copyright © 2020 Pavitra Hegde. All rights reserved.
//
import Foundation
class MockURLProtocol: URLProtocol {
// 1. Handler to test the request and return mock response.
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data?))?
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
return false
}
override func startLoading() {
guard let handler = MockURLProtocol.requestHandler else {
fatalError("Handler is unavailable.")
}
do {
// 2. Call handler with received request and capture the tuple of response and data.
let (response, data) = try handler(request)
// 3. Send received response to the client.
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
if let data = data {
// 4. Send received data to the client.
client?.urlProtocol(self, didLoad: data)
}
// 5. Notify request has been finished.
client?.urlProtocolDidFinishLoading(self)
} catch {
// 6. Notify received error.
client?.urlProtocol(self, didFailWithError: error)
}
}
override func stopLoading() {
//super.stopLoading()
}
}
| 28.213115 | 96 | 0.589192 |
767fc973736eef125bbad3a348bd430339da6037 | 2,171 | //
// AppDelegate.swift
// FoodManagement2021
//
// Created by CNTT on 4/16/21.
// Copyright © 2021 fit.tdc. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.191489 | 285 | 0.754952 |
79c71b9ae65313f94c038dc6f880bd3a734befb6 | 611 | //
// WKJFunc.swift
// WKJoint
//
// Created by Mgen on 19/12/17.
// Copyright © 2017 Mgen. All rights reserved.
//
import UIKit
// Func type for a sync func
typealias WKJFunc = (_ args: WKJArgs) throws -> WKJEncodable?
// Func type for an async func
typealias WKJAsyncFunc = (_ args: WKJArgs, _ promise: WKJPromiseProxy) -> Void
// defines the type used to store an API func
protocol WKJFuncProtocol {
var name: String { get }
}
struct SyncFunc: WKJFuncProtocol {
let name: String
let value: WKJFunc
}
struct AsyncFunc: WKJFuncProtocol {
let name: String
let value: WKJAsyncFunc
}
| 20.366667 | 78 | 0.697218 |
ddae3c2e0d4de81ecb0ba6a70529505ecb21a690 | 3,089 | //
// DetailViewController.swift
// DotstudioPlayer_iOS_Demo
//
// Created by Ketan Sakariya on 01/03/18.
// Copyright © 2018 Ketan Sakariya. All rights reserved.
//
import UIKit
import DotstudioPlayer_iOS
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var dotPlayerView: DotPlayerView!
func configureView() {
// Update the user interface for the detail item.
var strUrl = "https://k7q5a5e5.ssl.hwcdn.net/files/company/53fd1266d66da833047b23c6/assets/videos/540f28fdd66da89e1ed70281/vod/540f28fdd66da89e1ed70281.m3u8"
strUrl = "https://vcndecentric.teleosmedia.com/stream/decentric/dclive1/playlist.m3u8"
let dotPlayerObject = DotPlayerObject()
dotPlayerObject.strVideoUrl = strUrl
dotPlayerObject.isLiveStreaming = true
self.dotPlayerView.setPlayerObject(dotPlayerObject)
self.dotPlayerView.delegate = self
// let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
// label.text = "Test text"
// label.textColor = UIColor.red
// self.dotPlayerView.viewContentOverlayPlayerController?.addSubview(label)
// self.dotPlayerView.viewContentOverlayPlayerController?.bringSubview(toFront: label)
// self.labelTest = label
}
// var labelTest: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.dotPlayerView.play()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// if let labelTest = self.labelTest {
// self.dotPlayerView.viewContentOverlayPlayerController?.bringSubview(toFront: labelTest)
// }
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var detailItem: NSDate? {
didSet {
// Update the view.
configureView()
}
}
}
extension DetailViewController: DotPlayerViewDelegate {
func didPlayerBecomeReady(_ dotPlayerObject: DotPlayerObject) {
}
func didFailedToLoadPlayer(_ dotPlayerObject: DotPlayerObject) {
}
func didPlayDotPlayerVideo(_ dotPlayerObject: DotPlayerObject) {
}
func didPauseDotPlayerVideo(_ dotPlayerObject: DotPlayerObject) {
}
// func didResumeDotPlayerVideo(_ dotPlayerObject: DotPlayerObject)
func didEndPlaybackDotPlayerVideo(_ dotPlayerObject: DotPlayerObject) {
}
func didTriggerActionForCastButton(_ dotPlayerObject: DotPlayerObject) {
}
func didTriggerActionForShareButton(_ dotPlayerObject: DotPlayerObject) {
}
}
| 29.990291 | 165 | 0.674652 |
79820154e75e0821809bb8d2e4994451287087cc | 2,445 | //
// ViewController.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/17.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var libraryEnabled: Bool = true
var croppingEnabled: Bool = true
var allowResizing: Bool = true
var allowMoving: Bool = true
var minimumSize: CGSize = CGSize(width: 60, height: 60)
var croppingParameters: CroppingParameters {
return CroppingParameters(isEnabled: croppingEnabled, allowResizing: allowResizing, allowMoving: allowMoving,squarableCrop: true, minimumSize: minimumSize)
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var croppingParametersView: UIView!
@IBOutlet weak var minimumSizeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.contentMode = .scaleAspectFit
}
@IBAction func openCamera(_ sender: Any) {
let cameraViewController = CameraViewController(croppingParameters: croppingParameters, allowsLibraryAccess: libraryEnabled) { [weak self] image, asset in
self?.imageView.image = image
self?.dismiss(animated: true, completion: nil)
}
present(cameraViewController, animated: true, completion: nil)
}
@IBAction func openLibrary(_ sender: Any) {
let libraryViewController = CameraViewController.imagePickerViewController(croppingParameters: croppingParameters) { [weak self] image, asset in
self?.imageView.image = image
self?.dismiss(animated: true, completion: nil)
}
present(libraryViewController, animated: true, completion: nil)
}
@IBAction func libraryChanged(_ sender: Any) {
libraryEnabled = !libraryEnabled
}
@IBAction func croppingChanged(_ sender: UISwitch) {
croppingEnabled = sender.isOn
croppingParametersView.isHidden = !sender.isOn
}
@IBAction func resizingChanged(_ sender: UISwitch) {
allowResizing = sender.isOn
}
@IBAction func movingChanged(_ sender: UISwitch) {
allowMoving = sender.isOn
}
@IBAction func minimumSizeChanged(_ sender: UISlider) {
let newValue = sender.value
minimumSize = CGSize(width: CGFloat(newValue), height: CGFloat(newValue))
minimumSizeLabel.text = "Minimum size: \(newValue.rounded())"
}
}
| 32.6 | 163 | 0.684254 |
3385e81c0933eaea8e555301814fbe567032e025 | 8,720 | //
// UIColorHexStringTests.swift
// ThunderBasicsTests
//
// Created by Simon Mitchell on 05/11/2018.
// Copyright © 2018 threesidedcube. All rights reserved.
//
import XCTest
#if os(macOS)
import AppKit
typealias UIColor = NSColor
#endif
class UIColorHexStringTests: XCTestCase {
override func 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.
}
func testThreeComponentInitialises() {
let color = UIColor(hexString: "FFF")
XCTAssertNotNil(color, "FFF not initialized correctly")
}
func testFourComponentInitialises() {
let color = UIColor(hexString: "FFFF")
XCTAssertNotNil(color, "FFFF not initialized correctly")
}
func testSixComponentInitialises() {
let color = UIColor(hexString: "FFFFFF")
XCTAssertNotNil(color, "FFFFFF not initialized correctly")
}
func testEightComponentInitialises() {
let color = UIColor(hexString: "FFFFFFFF")
XCTAssertNotNil(color, "FFFFFFFF not initialized correctly")
}
func testWhiteAllocatesCorrectly() {
#if os(macOS)
let threePartWhite = UIColor(hexString: "FFF")?.usingColorSpace(.genericGray)
let fourPartWhite = UIColor(hexString: "FFFF")?.usingColorSpace(.genericGray)
let sixPartWhite = UIColor(hexString: "FFFFFF")?.usingColorSpace(.genericGray)
let eightPartWhite = UIColor(hexString: "FFFFFFFF")?.usingColorSpace(.genericGray)
#else
let threePartWhite = UIColor(hexString: "FFF")
let fourPartWhite = UIColor(hexString: "FFFF")
let sixPartWhite = UIColor(hexString: "FFFFFF")
let eightPartWhite = UIColor(hexString: "FFFFFFFF")
#endif
var white: CGFloat = 0.0
threePartWhite?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 1.0, accuracy: 0.01)
fourPartWhite?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 1.0, accuracy: 0.01)
sixPartWhite?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 1.0, accuracy: 0.01)
eightPartWhite?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 1.0, accuracy: 0.01)
}
func testBlackAllocatesCorrectly() {
#if os(macOS)
let threePartBlack = UIColor(hexString: "000")?.usingColorSpace(.genericGray)
let fourPartBlack = UIColor(hexString: "0000")?.usingColorSpace(.genericGray)
let sixPartBlack = UIColor(hexString: "000000")?.usingColorSpace(.genericGray)
let eightPartBlack = UIColor(hexString: "00000000")?.usingColorSpace(.genericGray)
#else
let threePartBlack = UIColor(hexString: "000")
let fourPartBlack = UIColor(hexString: "0000")
let sixPartBlack = UIColor(hexString: "000000")
let eightPartBlack = UIColor(hexString: "00000000")
#endif
var white: CGFloat = 0.0
threePartBlack?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 0.0, accuracy: 0.01)
fourPartBlack?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 0.0, accuracy: 0.01)
sixPartBlack?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 0.0, accuracy: 0.01)
eightPartBlack?.getWhite(&white, alpha: nil)
XCTAssertEqual(white, 0.0, accuracy: 0.01)
}
func testRedAllocatesCorrectly() {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
let threePartRed = UIColor(hexString: "F00")
threePartRed?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 1.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let fourPartRed = UIColor(hexString: "0F00")
fourPartRed?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 1.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 0.0, accuracy: 0.01)
let sixPartRed = UIColor(hexString: "FF0000")
sixPartRed?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 1.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let eightPartRed = UIColor(hexString: "00FF000000")
eightPartRed?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 1.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
}
func testGreenAllocatesCorrectly() {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
let threePartGreen = UIColor(hexString: "0F0")
threePartGreen?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 1.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let fourPartGreen = UIColor(hexString: "00F0")
fourPartGreen?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 1.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 0.0, accuracy: 0.01)
let sixPartGreen = UIColor(hexString: "00FF00")
sixPartGreen?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 1.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let eightPartGreen = UIColor(hexString: "0000FF00")
eightPartGreen?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 1.0, accuracy: 0.01)
XCTAssertEqual(b, 0.0, accuracy: 0.01)
XCTAssertEqual(a, 0.0, accuracy: 0.01)
}
func testBlueAllocatesCorrectly() {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
let threePartBlue = UIColor(hexString: "00F")
threePartBlue?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 1.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let fourPartBlue = UIColor(hexString: "000F")
fourPartBlue?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 1.0, accuracy: 0.01)
XCTAssertEqual(a, 0.0, accuracy: 0.01)
let sixPartBlue = UIColor(hexString: "0000FF")
sixPartBlue?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 1.0, accuracy: 0.01)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
let eightPartBlue = UIColor(hexString: "000000FF")
eightPartBlue?.getRed(&r, green: &g, blue: &b, alpha: &a)
XCTAssertEqual(r, 0.0, accuracy: 0.01)
XCTAssertEqual(g, 0.0, accuracy: 0.01)
XCTAssertEqual(b, 1.0, accuracy: 0.01)
XCTAssertEqual(a, 0.0, accuracy: 0.01)
}
func testAlpaAllocatesCorrectly() {
var a: CGFloat = 0.0
var fourPart = UIColor(hexString: "f000")
fourPart?.getRed(nil, green: nil, blue: nil, alpha: &a)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
var eightPart = UIColor(hexString: "FF000000")
eightPart?.getRed(nil, green: nil, blue: nil, alpha: &a)
XCTAssertEqual(a, 1.0, accuracy: 0.01)
fourPart = UIColor(hexString: "a000")
fourPart?.getRed(nil, green: nil, blue: nil, alpha: &a)
XCTAssertEqual(a, 170.0/255.0, accuracy: 0.01)
eightPart = UIColor(hexString: "AA000000")
eightPart?.getRed(nil, green: nil, blue: nil, alpha: &a)
XCTAssertEqual(a, 170.0/255.0, accuracy: 0.01)
}
}
| 37.913043 | 111 | 0.600573 |
1169d7e8616d4a33a15fa8bbe4d9ae8d6cebbf67 | 2,809 | import Foundation
import ExpressiveCocoa
import ExpressiveCasting
public class TextOptionType : OptionType {
public override var name: String {
return "text-field"
}
public override func parse(manifest: [String: AnyObject], _ errorSink: LRManifestErrorSink) -> OptionSpec? {
let spec = TextOptionSpec()
if !parse(into: spec, manifest, errorSink) {
return nil
}
if !spec.validate(errorSink) {
return nil
}
return spec
}
internal func parse(into spec: TextOptionSpec, _ manifest: [String: AnyObject], _ errorSink: LRManifestErrorSink) -> Bool {
if !parseCommon(into: spec, manifest, errorSink) {
return false
}
spec.arguments = P2ParseCommandLineSpec(manifest["args"])
spec.placeholder = manifest["placeholder"]~~~
spec.skipArgumentsIfEmpty = manifest["skip-if-empty"]~~~ ?? true
return true
}
}
internal class TextOptionSpec : OptionSpec {
var placeholder: String?
var arguments: [String] = []
var skipArgumentsIfEmpty = true
override func validate(errorSink: LRManifestErrorSink) -> Bool {
if !super.validate(errorSink) {
return false
}
if label == nil {
errorSink.addErrorMessage("Missing label")
return false
}
return true
}
internal override func newOption(rule rule: Rule) -> Option {
return TextOption(rule: rule, spec: self)
}
}
public class TextOption : Option, TextOptionProtocol {
public let label: String
public let placeholder: String?
public let arguments: [String]
public let skipArgumentsIfEmpty: Bool
private init(rule: Rule, spec: TextOptionSpec) {
label = spec.label!
placeholder = spec.placeholder
arguments = spec.arguments
skipArgumentsIfEmpty = spec.skipArgumentsIfEmpty
super.init(rule: rule, identifier: spec.identifier!)
}
public var defaultValue: String {
return ""
}
public var modelValue: String? {
get {
return rule.optionValueForKey(identifier)~~~
}
set {
rule.setOptionValue(newValue, forKey: identifier)
}
}
public var effectiveValue: String {
get {
return modelValue ?? defaultValue
}
set {
if newValue == defaultValue {
modelValue = nil
} else {
modelValue = newValue
}
}
}
public override var commandLineArguments: [String] {
let value = effectiveValue
if value.isEmpty && skipArgumentsIfEmpty {
return []
}
return arguments.substituteValues(["$(value)": value])
}
}
| 27.009615 | 127 | 0.599858 |
db9651af30f574b3a88b87c8dfb6b62e69ae281a | 61 | //
// File.swift
// AppReviewExample
//
import Foundation
| 8.714286 | 20 | 0.672131 |
89195e4746855a69adf901970aed72d1e2e0b50b | 1,606 | import UIKit
import HDRosaryTimeline
class MealData: HDRosaryTimelineViewDataSource {
private let data: [(String, [(String, Int)])] = [
("2017/7/6 19:00", [("Korean style barbecue", 1500)]),
("2017/7/6 13:00", [("Pescatore", 800),
("Green salad", 200)]),
("2017/7/6 9:00", [("Butter toast", 400),
("Boiled egg", 150),
("Milk", 150)]),
("2017/7/5 19:00", [("Meatloaf", 800),
("Caesar salad", 250),
("Vichyssoise", 200)]),
("2017/7/5 13:00", [("Sandwitch", 450),
("Green salad", 200)]),
("2017/7/5 9:00", [("Rice", 250),
("Miso soup", 150),
("Fried egg", 180)])
]
func getNumberOfSections() -> Int {
return self.data.count
}
func getNumberOfItems(in section: Int) -> Int {
let (_, meals) = self.data[section]
return meals.count
}
func getHeaderText(at section: Int) -> String? {
let (timestamp, _) = self.data[section]
return timestamp
}
func getText(at indexPath: IndexPath) -> String? {
let (_, meals) = self.data[indexPath.section]
let (name, _) = meals[indexPath.row]
return name
}
func getDetailText(at indexPath: IndexPath) -> String? {
let (_, meals) = self.data[indexPath.section]
let (_, calory) = meals[indexPath.row]
return String(describing: calory) + " [kcal]"
}
}
| 33.458333 | 62 | 0.482565 |
8f7ec1a46f02d2dbc61f75178ef608aac830fa1f | 2,182 | //
// File.swift
//
//
// Created by Adam Wulf on 5/13/21.
//
import Foundation
struct RationalArray<Element> {
private let range = Fraction.zero ..< Fraction.one
private var elements: [(index: Fraction, value: Element)] = []
var indices: [Fraction] {
return elements.map({ $0.index })
}
mutating func append(_ item: Element) {
if let lastElement = elements.last {
elements.append((index: (lastElement.index + range.upperBound) / 2, value: item))
} else {
elements.append((index: (range.lowerBound + range.upperBound) / 2, value: item))
}
}
mutating func insert(_ item: Element, at index: Fraction) {
let arrIndex = elements.firstIndex { element in
element.index >= index
}
guard let arrIndex = arrIndex else {
append(item)
return
}
if elements[arrIndex].index == index {
let prevIndex = arrIndex > 0 ? elements[arrIndex - 1].index : range.lowerBound
let avgIndex = (prevIndex + index) / 2
elements.insert((index: avgIndex, value: item), at: arrIndex)
} else {
elements.insert((index: index, value: item), at: arrIndex)
}
}
mutating func append(contentsOf items: [Element]) {
items.forEach({ self.append($0) })
}
mutating func remove(at index: Fraction) {
let arrIndex = elements.firstIndex { element in
element.index >= index
}
guard let arrIndex = arrIndex else { return }
elements.remove(at: arrIndex)
}
}
extension RationalArray: ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: Self.ArrayLiteralElement...) {
self.append(contentsOf: elements)
}
}
extension RationalArray where Element: Comparable {
mutating func remove(item: Element) {
while true {
let arrIndex = elements.firstIndex { element in
element.value == item
}
guard let arrIndex = arrIndex else { return }
elements.remove(at: arrIndex)
}
}
}
| 28.710526 | 93 | 0.592576 |
6abb4c9afefa036c27aa084d2398c2c46e215d03 | 4,898 | //
// BLEPairingClient.swift
// i2app
//
// Created by Arcus Team on 7/10/18.
/*
* Copyright 2019 Arcus Project
*
* 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 Cornea
import CoreBluetooth
import CocoaLumberjack
import RxSwift
import RxCocoa
import RxSwiftExt
import RxDataSources
extension Constants {
static let wifiCfgService = CBUUID(string: "9DAB269A-0000-4C87-805F-BC42474D3C0B")
static let wifiCfgScanResult = CBUUID(string: "9DAB269A-0001-4C87-805F-BC42474D3C0B")
static let wifiCfgSupModes = CBUUID(string:"9DAB269A-0002-4C87-805F-BC42474D3C0B")
static let wifiCfgSupFreq = CBUUID(string: "9DAB269A-0003-4C87-805F-BC42474D3C0B")
static let wifiCfgMode = CBUUID(string: "9DAB269A-0004-4C87-805F-BC42474D3C0B")
static let wifiCfgFreq = CBUUID(string: "9DAB269A-0005-4C87-805F-BC42474D3C0B")
static let wifiCfgSSID = CBUUID(string: "9DAB269A-0006-4C87-805F-BC42474D3C0B")
static let wifiCfgAuth = CBUUID(string: "9DAB269A-0007-4C87-805F-BC42474D3C0B")
static let wifiCfgEncrypt = CBUUID(string: "9DAB269A-0080-4C87-805F-BC42474D3C0B")
static let wifiCfgPasswd = CBUUID(string: "9DAB269A-0009-4C87-805F-BC42474D3C0B")
static let wifiCfgStatus = CBUUID(string: "9DAB269A-000A-4C87-805F-BC42474D3C0B")
static let bleGeneralService = CBUUID(string: "000010-10-00805F9B34FB")
static let bleDeviceInformation = CBUUID(string: "0000180A-00-805F9B34FB")
static let bleDeviceName = CBUUID(string: "00002A00-00-805F9B34FB")
static let bleModelNumber = CBUUID(string: "00002A24-00-805F9B34FB")
static let bleSerialNumber = CBUUID(string: "00002A25-00-805F9B34FB")
static let bleFirmwareRevision = CBUUID(string: "00002A26-00-805F9B34FB")
static let bleHardwareRevision = CBUUID(string: "00002A27-00-805F9B34FB")
static let bleManufacturer = CBUUID(string: "00002A29-00-805F9B34FB")
static let bleArcusFilter: String = "Arcus"
static let bleCameraFilter: String = "Arcus_Cam"
static let bleHubFilter: String = "Arcus_Hub"
static let bleWSSFilter: String = "Arcus_Plug"
static let wifiCameraShortName: String = "Security Camera"
static let wifiPlugShortName: String = "Smart Plug"
}
class BLEPairingClient: ArcusBLEAvailability,
ArcusBLEScannable,
ArcusBLEConnectable,
ArcusBLEConfigurable,
ArcusBLEWiFiConfigurable,
ArcusWiFiScanResultFactory,
ArcusBLEPairable,
ArcusCipher,
SwannCameraConfig{
// Required by `ArcusBLEUtility`
var centralManager: CBCentralManager!
var disposeBag: DisposeBag = DisposeBag()
// Required by `ArcusBLEScannable`
var searchFilter: String!
var isScanning: Variable<Bool> = Variable(false)
var discoveredDevices: Variable<[ArcusBLEViewModel]> = Variable([])
var discoveredDevicesDisposable: Disposable?
// Required by `ArcusBLEConnectable`
var connectedDevice: Variable<ArcusBLEViewModel?> = Variable(nil)
var connectedDisposable: Disposable?
// Required by `ArcusBLEConfigurable`
var discoveredCharacteristics: Variable<[CBCharacteristic]> = Variable([])
var discoveredCharacteristicsDisposable: Disposable?
// Required by `ArcusBLEWifiConfigurable`
var availableNetworks: Variable<[WiFiScanItem]> = Variable([])
var selectedNetwork: Variable<WiFiScanItem?> = Variable(nil)
var configStatus: Variable<BLEPairingConfigStatus> = Variable(.intial)
var isSearching: Variable<Bool> = Variable<Bool>(false)
var availableNetworksDisposable: Disposable?
var configStatusDisposable: Disposable?
// Required by `ArcusBLEPairable`
var ipcdDeviceType: String!
required init(_ centralManager: CBCentralManager, searchFilter: String? = Constants.bleArcusFilter, ipcdDeviceType: String = "") {
self.centralManager = centralManager
self.searchFilter = searchFilter
self.ipcdDeviceType = ipcdDeviceType
bindConnectedDevice()
}
func bindConnectedDevice() {
// Subscribe to connectedDevice, and discover services when not nil.
connectedDevice
.asObservable()
.filter { device in
return device != nil
}
.subscribe(onNext: { [unowned self] _ in
self.discoverCharacteristics()
})
.disposed(by: disposeBag)
}
func cleanUp() {
centralManager.stopScan()
if let peripheral = connectedDevice.value?.peripheral {
centralManager.cancelPeripheralConnection(peripheral)
}
discoveredCharacteristics.value = []
availableNetworks.value = []
}
}
| 37.389313 | 132 | 0.759698 |
2079fd732716dfc04ba48a763442230df84c79c0 | 5,360 | //
// SCNNode+Snapshot.swift
// FMEAR
//
// Created by Angus Lau on 2020-08-18.
// Copyright © 2020 Safe Software Inc. All rights reserved.
//
import Foundation
import SceneKit
extension SCNNode {
// This function doesn't work in an emulator
func snapshot(size: CGSize) -> UIImage {
// Create the scen with this node
let scene = SCNScene()
scene.rootNode.addChildNode(self)
// Create bounding box node
let (minBounds, maxBounds) = self.boundingBox
let box = SCNBox(width: CGFloat(maxBounds.x - minBounds.x),
height: CGFloat(maxBounds.y - minBounds.y),
length: CGFloat(maxBounds.z - minBounds.z),
chamferRadius: 0.0)
let material = SCNMaterial()
material.diffuse.contents = DesignSystem.Colour.NeutralPalette.grey
material.transparency = 0.1
box.materials = [material]
let boxNode = SCNNode(geometry: box)
boxNode.position = SCNVector3((minBounds.x + maxBounds.x) * 0.5,
(minBounds.y + maxBounds.y) * 0.5,
(minBounds.z + maxBounds.z) * 0.5)
scene.rootNode.addChildNode(boxNode)
// if axes {
// let (center, radius) = self.boundingSphere
// let (minBounds, maxBounds) = self.boundingBox
// let length: CGFloat = CGFloat(max(maxBounds.x - minBounds.x, maxBounds.y - minBounds.y) * 0.4)
// let capRadius = CGFloat(length) * 0.03
// if radius > 0.0 {
// let southPoleNode: SCNNode = {
// let capsule = SCNCapsule(capRadius: capRadius, height: length)
// let material = SCNMaterial()
// material.diffuse.contents = DesignSystem.Colour.NeutralPalette.grey
// material.transparency = 0.3
// capsule.materials = [material]
// let node = SCNNode(geometry: capsule)
// let position = SCNVector3(x: center.x, y: center.y - Float(capsule.height * 0.5), z: center.z + radius)
// node.position = position
// node.eulerAngles.z = Float.pi
// return node
// }()
// scene.rootNode.addChildNode(southPoleNode)
//
// let westPoleNode: SCNNode = {
// let capsule = SCNCapsule(capRadius: capRadius, height: length)
// let material = SCNMaterial()
// material.diffuse.contents = DesignSystem.Colour.NeutralPalette.grey
// material.transparency = 0.3
// capsule.materials = [material]
// let node = SCNNode(geometry: capsule)
// let position = SCNVector3(x: center.x - Float(capsule.height * 0.5), y: center.y, z: center.z + radius)
// node.position = position
// node.eulerAngles.z = 270.0 * Float.pi / 180.0
// return node
// }()
// scene.rootNode.addChildNode(westPoleNode)
//
// let northPoleNode: SCNNode = {
// let capsule = SCNCapsule(capRadius: capRadius, height: length)
// let material = SCNMaterial()
// material.diffuse.contents = DesignSystem.Colour.SemanticPalette.green
// capsule.materials = [material]
// let node = SCNNode(geometry: capsule)
// let position = SCNVector3(x: center.x, y: center.y + Float(capsule.height * 0.5), z: center.z + radius)
// node.position = position
// return node
// }()
// scene.rootNode.addChildNode(northPoleNode)
//
// let eastPoleNode: SCNNode = {
// let capsule = SCNCapsule(capRadius: capRadius, height: length)
// let material = SCNMaterial()
// material.diffuse.contents = DesignSystem.Colour.SemanticPalette.redDark20
// capsule.materials = [material]
// let node = SCNNode(geometry: capsule)
// let position = SCNVector3(x: center.x + Float(capsule.height * 0.5), y: center.y, z: center.z + radius)
// node.position = position
// node.eulerAngles.z = 90.0 * Float.pi / 180.0
// return node
// }()
// scene.rootNode.addChildNode(eastPoleNode)
// }
// }
// Light
let omniLight = SCNLight()
omniLight.type = .ambient
let omniLightNode = SCNNode()
omniLightNode.light = omniLight
omniLightNode.position = SCNVector3Make(10, 10, 10)
scene.rootNode.addChildNode(omniLightNode)
// Create a renderer
// This is nil in an emulator
let renderer = SCNRenderer(device: MTLCreateSystemDefaultDevice(), options: nil)
renderer.scene = scene
// Render the image
return renderer.snapshot(atTime: 0,
with: size,
antialiasingMode: SCNAntialiasingMode.multisampling4X)
}
}
| 44.297521 | 125 | 0.526866 |
d6be109c45c9a14afd7c1c9945eedb9de52b84b8 | 3,329 | /// Copyright (c) 2019 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 SwiftUI
struct ContentView: View {
@ObservedObject var taskStore: TaskStore
@State var modalIsPresented = false
var body: some View {
NavigationView {
List {
ForEach(taskStore.prioritizedTasks) { index in
SectionView(prioritizedTasks: self.$taskStore.prioritizedTasks[index])
}
}
.listStyle( GroupedListStyle() )
.navigationBarTitle("Tasks")
.navigationBarItems(
leading: EditButton(),
trailing:
Button(
action: { self.modalIsPresented = true }
) {
Image(systemName: "plus")
}
)
}
.sheet(isPresented: $modalIsPresented) {
NewTaskView(taskStore: self.taskStore)
}
.onAppear {
self.loadJSON()
}
}
// MARK: - Private Methods
private func loadJSON() {
guard let taskJSONURL = Bundle.main.url(forResource: "Task", withExtension: "json"),
let prioritizedTaskJSONURL = Bundle.main.url(forResource: "PrioritizedTask", withExtension: "json") else {
return
}
let decoder = JSONDecoder()
do {
let taskData = try Data(contentsOf: taskJSONURL)
let task = try decoder.decode(Task.self, from: taskData)
print(task)
let prioritizedTaskData = try Data(contentsOf: prioritizedTaskJSONURL)
let prioritizedTask = try decoder.decode(TaskStore.PrioritizedTasks.self, from: prioritizedTaskData)
print(prioritizedTask)
} catch let error {
print(error)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView( taskStore: TaskStore() )
}
}
| 36.582418 | 112 | 0.694803 |
e23b9974d281083715b3f1275070e99737a567f8 | 2,583 | import XCTest
import ReactiveSwift
@testable import ReactiveExtensions
@testable import ReactiveExtensions_TestHelpers
final class SlidingWindowTest: XCTestCase {
func testSlidingWindowWithMaxLessThanMin() {
let (signal, observer) = Signal<Int, Never>.pipe()
let window = signal.slidingWindow(max: 3, min: 2)
let test = TestObserver<[Int], Never>()
window.observe(test.observer)
observer.send(value: 1)
test.assertValues([])
observer.send(value: 2)
test.assertValues([[1, 2]])
observer.send(value: 3)
test.assertValues([[1, 2], [1, 2, 3]])
observer.send(value: 4)
test.assertValues([[1, 2], [1, 2, 3], [2, 3, 4]])
observer.send(value: 5)
test.assertValues([[1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]])
}
func testSlidingWindowWithMinEqualToZero() {
let (signal, observer) = Signal<Int, Never>.pipe()
let window = signal.slidingWindow(max: 2, min: 0)
let test = TestObserver<[Int], Never>()
window.observe(test.observer)
observer.send(value: 1)
test.assertValues([[1]])
observer.send(value: 2)
test.assertValues([[1], [1, 2]])
observer.send(value: 3)
test.assertValues([[1], [1, 2], [2, 3]])
observer.send(value: 4)
test.assertValues([[1], [1, 2], [2, 3], [3, 4]])
}
func testSlidingWindowWithMaxEqualToMin() {
let (signal, observer) = Signal<Int, Never>.pipe()
let window = signal.slidingWindow(max: 3, min: 3)
let test = TestObserver<[Int], Never>()
window.observe(test.observer)
observer.send(value: 1)
test.assertValues([])
observer.send(value: 2)
test.assertValues([])
observer.send(value: 3)
test.assertValues([[1, 2, 3]])
observer.send(value: 4)
test.assertValues([[1, 2, 3], [2, 3, 4]])
observer.send(value: 5)
test.assertValues([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
}
func testProducer_SlidingWindowWithMaxLessThanMin() {
let (signal, observer) = Signal<Int, Never>.pipe()
let producer = SignalProducer(signal)
let window = producer.slidingWindow(max: 3, min: 2)
let test = TestObserver<[Int], Never>()
window.start(test.observer)
observer.send(value: 1)
test.assertDidNotEmitValue()
observer.send(value: 2)
test.assertValues([[1, 2]])
observer.send(value: 3)
test.assertValues([[1, 2], [1, 2, 3]])
observer.send(value: 4)
test.assertValues([[1, 2], [1, 2, 3], [2, 3, 4]])
observer.send(value: 5)
test.assertValues([[1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]])
observer.sendCompleted()
test.assertDidComplete()
}
}
| 26.628866 | 64 | 0.624855 |
33c0f11baa172d4170d640a48cd0266b021afd3a | 1,198 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 3.0.1.11917
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
A code that indicates how transactions are supported.
URL: http://hl7.org/fhir/transaction-mode
ValueSet: http://hl7.org/fhir/ValueSet/transaction-mode
*/
public enum TransactionMode: String, FHIRPrimitiveType {
/// Neither batch or transaction is supported.
case notSupported = "not-supported"
/// Batches are supported.
case batch = "batch"
/// Transactions are supported.
case transaction = "transaction"
/// Both batches and transactions are supported.
case both = "both"
}
| 28.52381 | 76 | 0.72621 |
181cc2161a5416d6102658bbdb7493c0246c39dc | 14,206 | import Foundation // For JSONEncoder
/// Types that adopt EncodableRecord can be encoded into the database.
public protocol EncodableRecord {
/// Encodes the record into database values.
///
/// Store in the *container* argument all values that should be stored in
/// the columns of the database table (see databaseTableName()).
///
/// Primary key columns, if any, must be included.
///
/// struct Player: EncodableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
func encode(to container: inout PersistenceContainer)
// MARK: - Customizing the Format of Database Columns
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, you can use this dictionary to customize the encoding process
/// into database rows.
///
/// For example:
///
/// // A key that holds a encoder's name
/// let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
///
/// struct Player: PersistableRecord, Encodable {
/// // Customize the encoder name when encoding a database row
/// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
///
/// func encode(to encoder: Encoder) throws {
/// // Print the encoder name
/// print(encoder.userInfo[encoderName])
/// ...
/// }
/// }
///
/// let player = Player(...)
///
/// // prints "Database"
/// try player.insert(db)
///
/// // prints "JSON"
/// let encoder = JSONEncoder()
/// encoder.userInfo = [encoderName: "JSON"]
/// let data = try encoder.encode(player)
static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, this method controls the encoding process of nested properties
/// into JSON database columns.
///
/// The default implementation returns a JSONEncoder with the
/// following properties:
///
/// - dataEncodingStrategy: .base64
/// - dateEncodingStrategy: .millisecondsSince1970
/// - nonConformingFloatEncodingStrategy: .throw
/// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, tvOS 11.0+, watchOS 4.0+)
///
/// You can override those defaults:
///
/// struct Achievement: Encodable {
/// var name: String
/// var date: Date
/// }
///
/// struct Player: Encodable, PersistableRecord {
/// // stored in a JSON column
/// var achievements: [Achievement]
///
/// static func databaseJSONEncoder(for column: String) -> JSONEncoder {
/// let encoder = JSONEncoder()
/// encoder.dateEncodingStrategy = .iso8601
/// return encoder
/// }
/// }
static func databaseJSONEncoder(for column: String) -> JSONEncoder
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, this property controls the encoding of date properties.
///
/// Default value is .deferredToDate
///
/// For example:
///
/// struct Player: PersistableRecord, Encodable {
/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // encoded as an epoch timestamp
/// }
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
/// When the EncodableRecord type also adopts the standard Encodable
/// protocol, this property controls the encoding of UUID properties.
///
/// Default value is .deferredToUUID
///
/// For example:
///
/// struct Player: PersistableProtocol, Encodable {
/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
///
/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
/// var uuid: UUID
/// }
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
}
extension EncodableRecord {
public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] {
return [:]
}
public static func databaseJSONEncoder(for column: String) -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
// guarantee some stability in order to ease record comparison
encoder.outputFormatting = .sortedKeys
}
return encoder
}
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
return .deferredToDate
}
public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy {
return .deferredToUUID
}
}
extension EncodableRecord {
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
public var databaseDictionary: [String: DatabaseValue] {
return Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null }
}
}
extension EncodableRecord {
// MARK: - Record Comparison
/// Returns a boolean indicating whether this record and the other record
/// have the same database representation.
public func databaseEquals(_ record: Self) -> Bool {
return PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)).next() == nil
}
/// A dictionary of values changed from the other record.
///
/// Its keys are column names. Its values come from the other record.
///
/// Note that this method is not symmetrical, not only in terms of values,
/// but also in terms of columns. When the two records don't define the
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges<Record: EncodableRecord>(from record: Record) -> [String: DatabaseValue] {
let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record))
return Dictionary(uniqueKeysWithValues: changes)
}
}
// MARK: - PersistenceContainer
/// Use persistence containers in the `encode(to:)` method of your
/// encodable records:
///
/// struct Player: EncodableRecord {
/// var id: Int64?
/// var name: String?
///
/// func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
public struct PersistenceContainer {
// fileprivate for Row(_:PersistenceContainer)
// The ordering of the OrderedDictionary helps generating always the same
// SQL queries, and hit the statement cache.
@usableFromInline var storage: OrderedDictionary<String, DatabaseValueConvertible?>
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript(_ column: String) -> DatabaseValueConvertible? {
get { return storage[column] ?? nil }
set { storage.updateValue(newValue, forKey: column) }
}
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
@inlinable
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
get { return self[column.name] }
set { self[column.name] = newValue }
}
init() {
storage = OrderedDictionary()
}
init(minimumCapacity: Int) {
storage = OrderedDictionary(minimumCapacity: minimumCapacity)
}
/// Convenience initializer from a record
init<Record: EncodableRecord>(_ record: Record) {
self.init()
record.encode(to: &self)
}
/// Columns stored in the container, ordered like values.
var columns: [String] {
return Array(storage.keys)
}
/// Values stored in the container, ordered like columns.
var values: [DatabaseValueConvertible?] {
return Array(storage.values)
}
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
///
/// :nodoc:
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
get {
if let value = storage[column] {
return value
}
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value
}
return nil
}
set {
if storage[column] != nil {
storage[column] = newValue
return
}
let lowercaseColumn = column.lowercased()
for key in storage.keys where key.lowercased() == lowercaseColumn {
storage[key] = newValue
return
}
storage[column] = newValue
}
}
// Returns nil if column is not defined
func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? {
let lowercaseColumn = column.lowercased()
for (key, value) in storage where key.lowercased() == lowercaseColumn {
return value?.databaseValue ?? .null
}
return nil
}
var isEmpty: Bool {
return storage.isEmpty
}
/// An iterator over the (column, value) pairs
func makeIterator() -> IndexingIterator<OrderedDictionary<String, DatabaseValueConvertible?>> {
return storage.makeIterator()
}
func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = container[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
if newDbValue != oldDbValue {
return (column, oldDbValue)
}
}
return nil
}
}
}
extension Row {
convenience init<Record: EncodableRecord>(_ record: Record) {
self.init(PersistenceContainer(record))
}
convenience init(_ container: PersistenceContainer) {
self.init(Dictionary(container.storage))
}
}
// MARK: - DatabaseDateEncodingStrategy
/// DatabaseDateEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their date properties.
///
/// For example:
///
/// struct Player: EncodableRecord, Encodable {
/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // encoded as an epoch timestamp
/// }
public enum DatabaseDateEncodingStrategy {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
/// UTC time zone.
case deferredToDate
/// Encodes a Double: the number of seconds between the date and
/// midnight UTC on 1 January 2001
case timeIntervalSinceReferenceDate
/// Encodes a Double: the number of seconds between the date and
/// midnight UTC on 1 January 1970
case timeIntervalSince1970
/// Encodes an Int64: the number of seconds between the date and
/// midnight UTC on 1 January 1970
case secondsSince1970
/// Encodes an Int64: the number of milliseconds between the date and
/// midnight UTC on 1 January 1970
case millisecondsSince1970
/// Encodes dates according to the ISO 8601 and RFC 3339 standards
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> DatabaseValueConvertible?)
}
// MARK: - DatabaseUUIDEncodingStrategy
/// DatabaseUUIDEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their UUID properties.
///
/// For example:
///
/// struct Player: EncodableProtocol, Encodable {
/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
///
/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
/// var uuid: UUID
/// }
public enum DatabaseUUIDEncodingStrategy {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
case deferredToUUID
/// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
case string
}
| 36.51928 | 110 | 0.629452 |
d51589381ca69d9d92c7e368f3deda800ffe86c1 | 89 | open class YHUTIL: NSObject {
open func foo() {
print("print foo()")
}
}
| 14.833333 | 29 | 0.52809 |
4bbf99d06b2843509ec3e6219016140b3fb638e3 | 1,825 | //
// LockMechanism.swift
// Cleanroom Project
//
// Created by Evan Maloney on 3/8/17.
// Copyright © 2017 Gilt Groupe. All rights reserved.
//
/**
Represents different mechanisms that can be used for locking.
*/
public enum LockMechanism
{
/** A mechanism that peforms no read or write locking. This should only
be used to optimize for scenarios where a lock is required but
thread-safety can be guaranteed through other means. (In other
words, if you use this value, you are assuming responsibility for
ensuring thread-safety on your own.)
*/
case none
/** A mechanism that relies on a `CriticalSection` for a re-entrant
mutual exclusion lock. */
case mutex
/** A read/write lock mechanism that relies on a `ReadWriteCoordinator`
for a many-reader/single-writer that can provide optimized `FastWriteLock`
performance. */
case readWrite
}
extension LockMechanism
{
/**
Creates a new `Lock` instance that uses the locking mechanism specified
by the value of the receiver.
- returns: The new `Lock`.
*/
public func createLock()
-> Lock
{
switch self {
case .none: return NoLock()
case .mutex: return MutexLock()
case .readWrite: return ReadWriteLock()
}
}
/**
Creates a new `FastWriteLock` instance that uses the locking mechanism
specified by the value of the receiver.
- returns: The new `FastWriteLock`.
*/
public func createFastWriteLock()
-> FastWriteLock
{
switch self {
case .none: return FastWriteFacade(wrapping: NoLock())
case .mutex: return FastWriteFacade(wrapping: MutexLock())
case .readWrite: return FastWriteLockImpl()
}
}
}
| 27.651515 | 79 | 0.640548 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.