label
int64 0
1
| text
stringlengths 0
2.8M
|
---|---|
0 | import Foundation
/// Different types of transportation
enum Type: String, Codable {
case countryTrain = "Country Train"
case regionTrain = "Region Train"
case cityTrain = "City Train"
case underground = "Underground"
case tram = "Tram"
case bus = "Bus"
/// Get a symbol for the type of transportation
/// - Returns: Symbol for the type
var symbol: String {
get {
return "Types/\(rawValue)"
}
}
}
|
0 | //
// Tabbar.swift
// HungryOsori-iOS
//
// Created by Macbook Pro retina on 2016. 8. 9..
// Copyright © 2016년 HanyangOsori. All rights reserved.
//
import UIKit
import Foundation
class Tabbar: UITabBarController {
} |
0 | //
// ImULanguageHandler.swift
// ImuLanguageHandler
//
// Created by Imu on 6/6/17.
// Copyright © 2017 2ntkh. All rights reserved.
//
import Foundation
// MARK: - Notification
public let ApplicationLanguageDidChangeNotification = "ImranApplicationLanguageDidChangeNotification"
// MARK: - Constants
let EnglishUSLanguageShortName = "en"
let KhmerLanguageShortName = "km"
let FrenchLanguageShortName = "fr"
let JapaneseLanguageShortName = "ja"
let KoreanLanguageShortName = "ko"
let SpanishLanguageShortName = "es"
let TamilLanguageShortName = "ta"
let EnglishUSLanguageLongName = "English(US)"
let KhmerLanguageLongName = "Khmer"
let FrenchLanguageLongName = "French"
let JapaneseLanguageLongName = "Japanese"
let KoreanLanguageLongName = "Korean"
let SpanishLanguageLongName = "Spanish"
let TamilLanguageLongName = "Tamil"
var _languagesLong : Any? = nil
// MARK: - Bundle
var _localizedBundle: Bundle? = nil
func localizedBundle() -> Bundle {
if (_localizedBundle == nil)
{
_localizedBundle = Bundle(path: (Bundle.main.path(forResource: applicationLanguage() as String, ofType: "lproj"))!)
}
return _localizedBundle!;
}
func applicationLanguage() -> String
{
let languages: [Any]? = UserDefaults.standard.object(forKey: "AppleLanguages") as? [Any]
return languages?.first as! String
}
// MARK: - Language
func setApplicationLanguage(language:String) {
let oldLanguage: String = applicationLanguage()
if (oldLanguage != language) {
UserDefaults.standard.set([language], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
_localizedBundle = Bundle(path: (Bundle.main.path(forResource: applicationLanguage() as String, ofType: "lproj"))!)
NotificationCenter.default.post(name: NSNotification.Name(ApplicationLanguageDidChangeNotification), object: nil, userInfo: nil)
}
}
func applicationLanguagesLong() -> Any
{
if _languagesLong == nil {
_languagesLong = [EnglishUSLanguageLongName,KhmerLanguageLongName]
}
return _languagesLong as Any
}
// MARK: - LocalizedString
func ImranLocalizedString (key:String,comment:String) -> String
{
return localizedBundle().localizedString(forKey: key, value: "", table: nil)
}
func applicationLanguageLong() -> String{
let language: String = applicationLanguage()
return shortLanguageToLong(shortLanguage: language)
}
func shortLanguageToLong(shortLanguage:String) -> String {
switch shortLanguage {
case EnglishUSLanguageShortName:
return EnglishUSLanguageLongName
case KhmerLanguageShortName :
return KhmerLanguageLongName
case FrenchLanguageShortName :
return FrenchLanguageLongName
case JapaneseLanguageShortName :
return JapaneseLanguageLongName
case SpanishLanguageShortName :
return SpanishLanguageLongName
case TamilLanguageShortName :
return TamilLanguageLongName
default:
return EnglishUSLanguageLongName
}
}
|
0 | ../../RxSwift/Schedulers/Internal/InvocableType.swift |
0 | //
// PlayerState.swift
// Biu
//
// Created by Ayari on 2019/09/29.
// Copyright © 2019 Ayari. All rights reserved.
//
import Foundation
final class PlayerState: ObservableObject {
@Published var playerIsOn = false
@Published var playerIsOnSp = false
@Published var playerIsOnIns = false
@Published var playListOneIsOn = false
@Published var collectionOneIsOn = false
}
|
0 | //
// MessagesWiring.swift
// CryptoMessages
//
// Created by Giorgio Natili on 5/8/17.
// Copyright © 2017 Giorgio Natili. All rights reserved.
//
import Foundation
class MessagesWiring {
var view: MessagesView
init(_ view: MessagesView) {
// Any additional operation goes here
self.view = view
}
func configure() {
let presenter = Messages()
let localMessageService = LocalMessageService(localStorageGateway: CoreDataLocalStorage())
let interactor = MessagesInteractor(services: localMessageService)
presenter.view = view
presenter.interactor = interactor
view.presenter = presenter
interactor.presenter = presenter
}
}
|
0 | //
// TurnipsChartMinBuyPriceCurve.swift
// ACHNBrowserUI
//
// Created by Renaud JENNY on 03/05/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
struct TurnipsChartMinBuyPriceCurve: Shape {
let data: [TurnipsChart.YAxis]
func path(in rect: CGRect) -> Path {
var path = Path()
let y = data.first?.minBuyPrice.position.y ?? 0
path.move(to: CGPoint(x: rect.minX, y: y))
path.addLine(to: CGPoint(x: rect.maxX, y: y))
return path
}
}
|
0 | //
// WebBrowser.swift
// Coinhako
//
// Created by Ky Nguyen on 10/11/17.
// Copyright © 2017 Coinhako. All rights reserved.
//
import UIKit
|
0 | //
// ViewController.swift
// TextField
//
// Created by Swift on 28/03/16.
// Copyright © 2016 Swift. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate{
@IBOutlet weak var labelTexto: UILabel!
@IBOutlet weak var textFieldUnica: UITextField!
/* Uma textField é um objeto de interaface gráfica que permite realizar a entrada de pequenos textos. Por padrão ao clicarmos em uma caixa de texto o teclado é habilitado para a entrada de dados.
Mas como faço para o teclado sair da tela ?
- Para que o teclado seja removido é necessário tirar o foco ta textField.
Como fazer esta mesma ação clicando no RETURN
*/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Propriedade que define um texto modelo
self.textFieldUnica.placeholder = "Digite seu nome aqui"
// Propriedade que habilita a limpeza do objeto quando ele inicia uma edição
//self.textFieldUnica.clearsOnBeginEditing = true
// Propriedade que habilita a inserção segura de texto
//self.textFieldUnica.secureTextEntry = true
// Propriedade que define e retorna o texto
//self.textFieldUnica.text = "Felipe"
self.textFieldUnica.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func atualizar(_ sender: UIButton) {
self.labelTexto.text = self.textFieldUnica.text
self.textFieldUnica.text = ""
self.textFieldUnica.resignFirstResponder()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.becomeFirstResponder()
}
override var canBecomeFirstResponder : Bool {
return true
}
// Método que é disparado quando a textField recebe foco
func textFieldDidBeginEditing(_ textField: UITextField) {
print("Iniciou a digitação (textFieldDidBeginEditing)")
}
// Método disparado quando a text field perde o foco
func textFieldDidEndEditing(_ textField: UITextField) {
print("Finalizou a edição (textFieldDidEndEditing)")
}
// Método que é disparado quando o usuário clica no RETURN
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.labelTexto.text = textField.text
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// O range define a forma de alteração do texto e onde irá acontecer.
//lengh -> define a forma de alteração
// print(range.length)
//location -> Define a localizacao da alteracao
print(range.location)
if(string == "a"){
return false
}
return true
}
}
|
0 | //
// RequiresHealth.swift
// ActivityPlusTwo
//
// Created by Ben Scheirman on 7/5/16.
// Copyright © 2016 NSScreencast. All rights reserved.
//
import Foundation
import HealthKit
import UIKit
protocol RequiresHealth {
var healthStore: HKHealthStore? { get set }
}
extension UINavigationController : RequiresHealth {
var healthStore: HKHealthStore? {
get {
if let vc = topViewController as? RequiresHealth {
return vc.healthStore
}
return nil
}
set {
if var vc = topViewController as? RequiresHealth {
vc.healthStore = newValue
}
}
}
}
|
0 | //
// ViewController.swift
// MGBookViews
//
// Created by i-Techsys.com on 2017/8/19.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var isShowAlert: Bool = false
lazy var isShowUpdateAlert: Bool = false
lazy var imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
var number = 110;
var number1 = 10
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
// tableView.contentInsetAdjustmentBehavior = .never
} else if #available(iOS 10.0, *) {
automaticallyAdjustsScrollViewInsets = false
extendedLayoutIncludesOpaqueBars = true
} else {
automaticallyAdjustsScrollViewInsets = false
}
view.backgroundColor = UIColor.orange
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试手势", style: .plain, target: self, action: #selector(click))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "加载图片", style: .plain, target: self, action: #selector(click1))
let textF = UITextField(frame: CGRect(x: 10, y: 100, width: 200, height: 30))
textF.borderStyle = .roundedRect
textF.clearButtonMode = .whileEditing
textF.delegate = self
view.addSubview(textF)
let textF1 = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 30))
textF1.loadRightClearButton()
textF1.tag = 100
textF1.delegate = self
textF1.borderStyle = .roundedRect
textF1.clearButtonMode = .whileEditing
view.addSubview(textF1)
}
func click() {
self.show(MGProfileViewController(), sender: nil)
// let vc = MGNextViewController()
// vc.view.backgroundColor = UIColor.mg_randomColor()
// self.show(vc, sender: nil)
}
func click1() {
view.addSubview(imageView)
imageView.center = self.view.center
imageView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: "80@2x", ofType: ".png")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (self.navigationController?.topViewController == self) {
if (self.isShowAlert) {
MGWindow.show(dismiss: {
self.isShowAlert = false
})
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.isShowUpdateAlert = true
var alertView: XLAlertView? = XLAlertView.instance(withTitle: "你个大笨蛋", forceUpdate: "NO", withContent: "你是笨蛋吗?你看我想不想理你", withEnsureBlock: { (reslut) in
UIApplication.shared.openURL(URL(string: "http://baidu.com")!)
self.isShowUpdateAlert = false
}) { (reslut) in
self.isShowUpdateAlert = false
}
DispatchQueue.main.asyncAfter(deadline: .now()+2) {
self.isShowUpdateAlert = true
let vc: UIViewController = (self.tabBarController!.selectedViewController! as! UINavigationController).topViewController!
if (vc == self) {
self.tabBarController?.view.addSubview(alertView!)
}
}
DispatchQueue.main.asyncAfter(deadline: .now()+2) {
self.isShowAlert = true
let vc: UIViewController = (self.tabBarController!.selectedViewController! as! UINavigationController).topViewController!
if (vc == self) {
MGWindow.show(dismiss: {
self.isShowAlert = false
})
}
}
// var alertView: XLAlertView? = XLAlertView.instance(withTitle: "你个大笨蛋", forceUpdate: "NO", withContent: "你是笨蛋吗?你看我想不想理你", withEnsureBlock: { (reslut) in
// UIApplication.shared.openURL(URL(string: "http://baidu.com")!)
// }) { (reslut) in
//
// }
//
// DispatchQueue.main.asyncAfter(deadline: .now()+2) {
// self.tabBarController?.view.addSubview(alertView!)
// }
// self.show(MGProfileViewController(), sender: nil)
// let _ = Timer.new(after: 5.0.minutes) {
// print("5秒后执行定时器")
// }
// var nub = arc4random_uniform(10) + 5
// _ = Timer.every(1.0) { [unowned self] in
// self.number -= 1
// MGLog(self.number)
// if self.number == 0 {
// print("定时器销毁")
// }
// }
// Timer.every(1.0) { [unowned self](timer: Timer) in
// self.number1 -= 1
// MGLog(self.number1)
// if self.number1 == 0 {
// timer.invalidate()
// print("定时器销毁")
// }
// }
//
//
// let num: Int64 = 1111144411111
// print(String(format: "%014ld", num))
//
// let heihie = 111
// print(String(format: "%014ld", heihie))
//
// let num2 = 222
// print(String(format: "%08ld", num2))
//
// let heihie2 = 99
// print(String(format: "%08ld", heihie2))
//
// imageView.image = UIImage(named: "80")
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// if range.length == 0 {
// if textField.tag == 100 {
//// var regex = ""
// if range.location == 1 {
// if textField.text == "0" {
// let regex = "(^([.]\\d{0,1})?)$" // "(^(0|([1-9]{0,}))([.]\\d{0,1})?)$"
// // 2.利用规则创建表达式对象
// let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
// print(predicate.evaluate(with: string))
// return predicate.evaluate(with: string)
// }
// }
// let regex = "(^(0|([1-9]{0,}))([.]\\d{0,1})?)$" // "(^(0|([1-9]{0,}))([.]\\d{0,1})?)$"
// // 2.利用规则创建表达式对象
// let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
// textField.text = textField.text ?? "" + string
// print(predicate.evaluate(with: textField.text))
// return predicate.evaluate(with: textField.text)
// }else {
//
// }
// }
let regex = "(^(0|([1-9]{0,}))([.]\\d{0,2})?)$"
// "^[0-9]*?((.)[0-9]{0,2})?$"
// "(^(0|([1-9]{0,}))([.]\\d{0,2})?)$"
// "(^[1-9]\\d{0,}(([.]\\d{0,2})?))?|(^[0]?(([.]\\d{0,2})?))?"
// "([1-9]\\d{0,}(([.]\\d{0,1})?))?|([0]?(([.]\\d{0,1})?))?"
// "([1-9]\\d{0,}(([.]\\d{0,1})?))?|([0]|(0[.]\\d{0,1}))" // |
// "^[0-9]+(.[0-9]{2})?$" //"[0-9]+\\.?[0-9]{2}" //"^\\d+(\\.\\d{2})?$" // "/^(0|[-][1-9]d{0,}).d{1,2}$/" // "^(0|[1-9]\\d{0,})(([.]\\d{0,1})?)?$"
// 2.利用规则创建表达式对象
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
let text = (textField.text ?? "") + string
if text.hasPrefix(".") {
textField.text = "0" + textField.text!
}
print(predicate.evaluate(with: text))
return predicate.evaluate(with: text)
// return true
}
}
|
0 | //
// ExtensionUITextField.swift
// CombineWithMVVM
//
// Created by mac-00015 on 02/12/19.
// Copyright © 2019 mac-00015. All rights reserved.
//
import Foundation
import UIKit
extension UITextField {
func setLeftPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
func setRightPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
|
0 | //
// SecondaryViewController.swift
// EMPartialModalViewController
//
// Created by Emad A. on 16/02/2015.
// Copyright (c) 2015 Emad A. All rights reserved.
//
import UIKit
class SecondaryViewController: UIViewController {
@IBAction func dismiss() {
parentViewController?.dismissViewControllerAnimated(true) {
println("dismissing view controller - done")
}
}
}
|
0 | //
// Error.swift
// Pods
//
// Created by Marcel Dittmann on 29.04.16.
//
//
import Foundation
import Gloss
public enum SHErrorType: Int {
case unknownError = 0
case unauthorizedUser = 1
case bodyContainsInvalidJSON = 2
case resourceNotAvailable = 3
case methodNotAvailableForResource = 4
case missingParametersBody = 5
case parameterNotAvailable = 6
case invalidValueParameter = 7
case parameterIsNotModifiable = 8
case tooManyItemsInList = 9
case portalConnectionRequired = 10
case internalError = 901
}
public class HueError: NSError, JSONDecodable {
public let address: String
public let errorDescription: String
public let type: SHErrorType
public required init?(json: JSON) {
if let _: Any = "success" <~~ json {
return nil
}
guard let type: Int = "error.type" <~~ json,
let address: String = "error.address" <~~ json,
let errorDescription: String = "error.description" <~~ json
else { print("Can't create Error Object from JSON:\n \(json)"); return nil }
if let type = SHErrorType(rawValue: type) {
self.type = type
} else {
self.type = .unknownError
}
self.address = address
self.errorDescription = errorDescription
super.init(domain: address, code: type, userInfo: ["description": errorDescription])
}
public init(address: String, errorDescription: String, type: SHErrorType) {
self.type = type
self.address = address
self.errorDescription = errorDescription
super.init(domain: address, code: type.rawValue, userInfo: ["description": errorDescription])
}
public init?(address: String, errorDescription: String, type: Int) {
guard let errorType = SHErrorType(rawValue: type) else {return nil};
self.type = errorType;
self.address = address
self.errorDescription = errorDescription
super.init(domain: address, code: type, userInfo: ["description": errorDescription])
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | /*
The MIT License (MIT)
Copyright (c) 2017 Tunespeak
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 Alamofire
import AlamofireObjectMapper
import ObjectMapper
open class AlamoRecordObject<U: URLProtocol, E: AlamoRecordError>: NSObject, Mappable {
/// Key to encode/decode the id variable
private let idKey: String = "id"
/// The RequestManager that is tied to all instances of this class
open class var requestManager: RequestManager<U, E> {
fatalError("requestManager must be overriden in your AlamoRecordObject subclass")
}
/// The RequestManager that is tied to this instance
open var requestManager: RequestManager<U, E> {
return type(of: self).requestManager
}
/// The id of this instance. This can be a String or an Int.
open var id: Any!
/// The root of all instances of this class. This is used when making URL's that relate to a component of this class.
// Example: '/comment/id' --> '/\(Comment.root)/id'
open class var root: String {
fatalError("root must be overriden in your AlamoRecordObject subclass")
}
/// The root of this instance
open var root: String {
return type(of: self).root
}
/// The plural root of all instances of this class. This is used when making URL's that relate to a component of this class.
// Example: '/comments/id' --> '/\(Comment.pluralRoot)/id'
open class var pluralRoot: String {
return "\(root)s"
}
/// The pluralRoot of this instance
open var pluralRoot: String {
return type(of: self).pluralRoot
}
/// The key path of all instances of this class. This is used when mapping instances of this class from JSON.
/*
Example:
{
comment: {
// json encpasulated here
}
}
If this is nil, then the expected JSON woud look like:
{
// json encpasulated here
}
*/
open class var keyPath: String? {
return nil
}
/// The keyPath of this instance
open var keyPath: String? {
return type(of: self).keyPath
}
/// The key path of all instances of this class. This is used when mapping instances of this class from JSON. See keyPath for example
open class var pluralKeyPath: String? {
guard let keyPath = keyPath else {
return nil
}
return "\(keyPath)s"
}
/// The pluralKeyPath of this instance
open var pluralKeyPath: String? {
return type(of: self).pluralKeyPath
}
public override init() {
super.init()
}
public required init?(map: Map) {
super.init()
mapping(map: map)
}
open func mapping(map: Map) {
id <- map["id"]
}
/**
Returns an array of all objects of this instance if the server supports it
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func all<T: AlamoRecordObject>(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (([T]) -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.findArray(T.urlForAll(),
parameters: parameters,
keyPath: T.pluralKeyPath,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Creates an object of this instance
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func create<T: AlamoRecordObject>(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: ((T) -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.createObject(parameters: parameters,
keyPath: keyPath,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Creates an object of this instance
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func create(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (() -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.createObject(url: urlForCreate(),
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Finds an object of this instance based on the given id
- parameter id: The id of the object to find
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func find<T: AlamoRecordObject>(id: Any,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: ((T) -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.findObject(id: id,
parameters: parameters,
keyPath: keyPath,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Updates the object
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open func update<T: AlamoRecordObject>(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: ((T) -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return T.update(id: id,
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Updates an object of this instance based with the given id
- parameter id: The id of the object to update
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func update<T: AlamoRecordObject>(id: Any,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: ((T) -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.updateObject(id: id,
parameters: parameters,
keyPath: keyPath,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Updates an object of this instance based with the given id
- parameter id: The id of the object to update
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func update(id: Any,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (() -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.updateObject(url: urlForUpdate(id),
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Updates an object of this instance based with the given id
- parameter id: The id of the object to update
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open func update(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (() -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return type(of: self).update(id: id,
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Destroys the object
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open func destroy(parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (() -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return type(of: self).destroy(id: id,
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
Finds an object of this instance based on the given id
- parameter id: The id of the object to destroy
- parameter parameters: The parameters. `nil` by default
- parameter encoding: The parameter encoding. `URLEncoding.default` by default
- parameter headers: The HTTP headers. `nil` by default
- parameter success: The block to execute if the request succeeds
- parameter failure: The block to execute if the request fails
*/
@discardableResult
open class func destroy(id: Any,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
success: (() -> Void)?,
failure: ((E) -> Void)?) -> DataRequest {
return requestManager.destroyObject(url: urlForDestroy(id),
parameters: parameters,
encoding: encoding,
headers: headers,
success: success,
failure: failure)
}
/**
The URL to use when making a create request for all objects of this instance
*/
open class func urlForCreate() -> U {
return U(url: "\(pluralRoot)")
}
public func urlForCreate() -> U {
return type(of: self).urlForCreate()
}
/**
The URL to use when making a find request for all objects of this instance
- parameter id: The id of the object to find
*/
open class func urlForFind(_ id: Any) -> U {
return U(url: "\(pluralRoot)/\(id)")
}
public func urlForFind() -> U {
return type(of: self).urlForFind(id)
}
/**
The URL to use when making an update request for all objects of this instance
- parameter id: The id of the object to update
*/
open class func urlForUpdate(_ id: Any) -> U {
return U(url: "\(pluralRoot)/\(id)")
}
public func urlForUpdate() -> U {
return type(of: self).urlForUpdate(id)
}
/**
The URL to use when making a destroy request for all objects this instance
- parameter id: The id of the object to destroy
*/
open class func urlForDestroy(_ id: Any) -> U {
return U(url: "\(pluralRoot)/\(id)")
}
public func urlForDestroy() -> U {
return type(of: self).urlForDestroy(id)
}
/**
The URL to use when making an all request for all objects of this instance
*/
open class func urlForAll() -> U {
return U(url: "\(pluralRoot)")
}
public func urlForAll() -> U {
return type(of: self).urlForAll()
}
}
|
0 | //
// FAAnimationGroup.swift
// FlightAnimator
//
// Created by Anton Doudarev on 2/24/16.
// Copyright © 2016 Anton Doudarev. All rights reserved.
//
import Foundation
import UIKit
/**
Equatable FAAnimationGroup Implementation
*/
func ==(lhs:FAAnimationGroup, rhs:FAAnimationGroup) -> Bool {
return lhs.animatingLayer == rhs.animatingLayer &&
lhs.animationKey == rhs.animationKey
}
/**
Timing Priority to apply during synchronisation of hte animations
within the calling animationGroup.
The more property animations within a group, the more likely some
animations will need more control over the synchronization of
the timing over others.
There are 4 timing priorities to choose from:
.MaxTime, .MinTime, .Median, and .Average
By default .MaxTime is applied, so lets assume we have 4 animations:
1. bounds
2. position
3. alpha
4. transform
FABasicAnimation(s) are not defined as primary by default,
synchronization will figure out the relative progress for each
property animation within the group in flight, then adjust the
timing based on the remaining progress to the final destination
of the new animation being applied.
Then based on .MaxTime, it will pick the longest duration form
all the synchronized property animations, and resynchronize the
others with a new duration, and apply it to the group itself.
If the isPrimary flag is set on the bounds and position
animations, it will only include those two animation in
figuring out the the duration.
Use .MinTime, to select the longest duration in the group
Use .MinTime, to select the shortest duration in the group
Use .Median, to select the median duration in the group
Use .Average, to select the average duration in the group
- MaxTime: find the longest duration, and adjust all animations to match
- MinTime: find the shortest duration and adjust all animations to match
- Median: find the median duration, and adjust all animations to match
- Average: find the average duration, and adjust all animations to match
*/
public enum FAPrimaryTimingPriority : Int {
case MaxTime
case MinTime
case Median
case Average
}
//MARK: - FAAnimationGroup
public class FAAnimationGroup : CAAnimationGroup {
public var animationKey : String?
public weak var animatingLayer : CALayer? { didSet { synchronizeSubAnimationLayers() }}
public var startTime : CFTimeInterval? { didSet { synchronizeSubAnimationStartTime() }}
public var timingPriority : FAPrimaryTimingPriority = .MaxTime
internal weak var primaryAnimation : FABasicAnimation?
public var autoreverse: Bool = false
public var autoreverseCount: Int = 1
public var autoreverseDelay: NSTimeInterval = 0.0
public var autoreverseEasing: Bool = false
internal var _autoreverseActiveCount: Int = 1
internal var _autoreverseConfigured: Bool = false
public var isTimeRelative = true
public var progessValue : CGFloat = 0.0
public var triggerOnRemoval : Bool = false
override public init() {
super.init()
animations = [CAAnimation]()
fillMode = kCAFillModeForwards
removedOnCompletion = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func copyWithZone(zone: NSZone) -> AnyObject {
let animationGroup = super.copyWithZone(zone) as! FAAnimationGroup
animationGroup.animatingLayer = animatingLayer
animationGroup.animationKey = animationKey
animationGroup.animations = animations
animationGroup.duration = duration
animationGroup.primaryAnimation = primaryAnimation
animationGroup.startTime = startTime
animationGroup.timingPriority = timingPriority
animationGroup.autoreverse = autoreverse
animationGroup.autoreverseCount = autoreverseCount
animationGroup.autoreverseDelay = autoreverseDelay
animationGroup.autoreverseEasing = autoreverseEasing
animationGroup._autoreverseActiveCount = _autoreverseActiveCount
animationGroup._autoreverseConfigured = _autoreverseConfigured
return animationGroup
}
final public func synchronizeAnimationGroup(withLayer layer: CALayer, forKey key: String?) {
animationKey = key
animatingLayer = layer
if let keys = animatingLayer?.animationKeys() {
for key in Array(Set(keys)) {
if let oldAnimation = animatingLayer?.animationForKey(key) as? FAAnimationGroup {
_autoreverseActiveCount = oldAnimation._autoreverseActiveCount
synchronizeAnimations(oldAnimation)
}
}
} else {
synchronizeAnimations(nil)
}
}
/**
Not Ready for Prime Time, being declared as private
Adjusts animation based on the progress form 0 - 1
- parameter progress: scrub "to progress" value
private func scrubToProgress(progress : CGFloat) {
animatingLayer?.speed = 0.0
animatingLayer?.timeOffset = CFTimeInterval(duration * Double(progress))
}
*/
}
//MARK: - Auto Reverse Logic
extension FAAnimationGroup {
func configureAutoreverseIfNeeded() {
if autoreverse {
if _autoreverseConfigured == false {
configuredAutoreverseGroup()
}
if autoreverseCount == 0 {
return
}
if _autoreverseActiveCount >= (autoreverseCount * 2) {
clearAutoreverseGroup()
return
}
_autoreverseActiveCount = _autoreverseActiveCount + 1
}
}
func configuredAutoreverseGroup() {
let animationGroup = FAAnimationGroup()
animationGroup.animationKey = animationKey! + "REVERSE"
animationGroup.animatingLayer = animatingLayer
animationGroup.animations = reverseAnimationArray()
animationGroup.duration = duration
animationGroup.timingPriority = timingPriority
animationGroup.autoreverse = autoreverse
animationGroup.autoreverseCount = autoreverseCount
animationGroup._autoreverseActiveCount = _autoreverseActiveCount
animationGroup.autoreverseEasing = autoreverseEasing
/*
if let view = animatingLayer?.owningView() {
let progressDelay = max(0.0 , _autoreverseDelay/duration)
//configureAnimationTrigger(animationGroup, onView: view, atTimeProgress : 1.0 + CGFloat(progressDelay))
}
*/
removedOnCompletion = false
}
func clearAutoreverseGroup() {
//_segmentArray = [FAAnimationTrigger]()
// removedOnCompletion = true
//stopTriggerTimer()
}
func reverseAnimationArray() ->[FABasicAnimation] {
var reverseAnimationArray = [FABasicAnimation]()
if let animations = animations {
for animation in animations {
if let customAnimation = animation as? FABasicAnimation {
let newAnimation = FABasicAnimation(keyPath: customAnimation.keyPath)
newAnimation.easingFunction = autoreverseEasing ? customAnimation.easingFunction.autoreverseEasing() : customAnimation.easingFunction
newAnimation.isPrimary = customAnimation.isPrimary
newAnimation.values = customAnimation.values!.reverse()
newAnimation.toValue = customAnimation.fromValue
newAnimation.fromValue = customAnimation.toValue
reverseAnimationArray.append(newAnimation)
}
}
}
return reverseAnimationArray
}
}
//MARK: - Synchronization Logic
internal extension FAAnimationGroup {
/**
Synchronizes the calling animation group with the passed animation group
- parameter oldAnimationGroup: old animation in flight
*/
func synchronizeAnimations(oldAnimationGroup : FAAnimationGroup?) {
var durationArray = [Double]()
var oldAnimations = animationDictionaryForGroup(oldAnimationGroup)
var newAnimations = animationDictionaryForGroup(self)
// Find all Primary Animations
let filteredPrimaryAnimations = newAnimations.filter({ $0.1.isPrimary == true })
let filteredNonPrimaryAnimations = newAnimations.filter({ $0.1.isPrimary == false })
var primaryAnimations = [String : FABasicAnimation]()
var nonPrimaryAnimations = [String : FABasicAnimation]()
for result in filteredPrimaryAnimations {
primaryAnimations[result.0] = result.1
}
for result in filteredNonPrimaryAnimations {
nonPrimaryAnimations[result.0] = result.1
}
//If no animation is primary, all animations become primary
if primaryAnimations.count == 0 {
primaryAnimations = newAnimations
nonPrimaryAnimations = [String : FABasicAnimation]()
}
for key in primaryAnimations.keys {
if let newPrimaryAnimation = primaryAnimations[key] {
let oldAnimation : FABasicAnimation? = oldAnimations[key]
newPrimaryAnimation.synchronize(relativeTo: oldAnimation)
if newPrimaryAnimation.duration > 0.0 {
durationArray.append(newPrimaryAnimation.duration)
}
newAnimations[key] = newPrimaryAnimation
}
}
animations = newAnimations.map {$1}
updateGroupDurationBasedOnTimePriority(durationArray)
// configureAutoreverseIfNeeded()
}
/**
Updates and syncronizes animations based on timing priority
if the primary animations
- parameter durationArray: durations considered based on primary state of the animations
*/
func updateGroupDurationBasedOnTimePriority(durationArray: Array<CFTimeInterval>) {
switch timingPriority {
case .MaxTime:
duration = durationArray.maxElement()!
case .MinTime:
duration = durationArray.minElement()!
case .Median:
duration = durationArray.sort(<)[durationArray.count / 2]
case .Average:
duration = durationArray.reduce(0, combine: +) / Double(durationArray.count)
}
var filteredPrimaryAnimations = animations!.filter({
$0.duration == duration || timingPriority == .Average || timingPriority == .Median && $0.duration > 0.0
})
if let primaryDrivingAnimation = filteredPrimaryAnimations.first as? FABasicAnimation {
primaryAnimation = primaryDrivingAnimation
}
var filteredNonAnimation = animations!.filter({ $0 != primaryAnimation })
for animation in animations! {
animation.duration = duration
if let customAnimation = animation as? FABasicAnimation {
customAnimation.synchronize()
}
}
}
func synchronizeSubAnimationLayers() {
if let currentAnimations = animations {
for animation in currentAnimations {
if let customAnimation = animation as? FABasicAnimation {
customAnimation.animatingLayer = animatingLayer
}
}
}
}
func synchronizeSubAnimationStartTime() {
if let currentAnimations = animations {
for animation in currentAnimations {
if let customAnimation = animation as? FABasicAnimation {
customAnimation.startTime = startTime
}
}
}
if let currentAnimations = animations {
for animation in currentAnimations {
if let customAnimation = animation as? FABasicAnimation {
customAnimation.animatingLayer = animatingLayer
}
}
}
}
func animationDictionaryForGroup(animationGroup : FAAnimationGroup?) -> [String : FABasicAnimation] {
var animationDictionary = [String: FABasicAnimation]()
if let group = animationGroup {
if let currentAnimations = group.animations {
for animation in currentAnimations {
if let customAnimation = animation as? FABasicAnimation {
animationDictionary[customAnimation.keyPath!] = customAnimation
}
}
}
}
return animationDictionary
}
}
//MARK: - Animation Progress Values
internal extension FAAnimationGroup {
func valueProgress() -> CGFloat {
if let animation = animatingLayer?.animationForKey(animationKey!) as? FAAnimationGroup{
return animation.primaryAnimation!.valueProgress()
}
guard let primaryAnimation = primaryAnimation else {
print("Primary Animation Nil")
return 0.0
}
return primaryAnimation.valueProgress()
}
func timeProgress() -> CGFloat {
if let animation = animatingLayer?.animationForKey(animationKey!) as? FAAnimationGroup{
return animation.primaryAnimation!.timeProgress()
}
guard let primaryAnimation = primaryAnimation else {
print("Primary Animation Nil")
return 0.0
}
return primaryAnimation.timeProgress()
}
}
/**
Attaches the specified animation, on the specified view, and relative
the progress value type defined in the method call
Ommit both timeProgress and valueProgress, to trigger the animation specified
at the start of the calling animation group
Ommit timeProgress, to trigger the animation specified
at the relative time progress of the calling animation group
Ommit valueProgress, to trigger the animation specified
at the relative value progress of the calling animation group
If both valueProgres, and timeProgress values are defined,
it will trigger the animation specified at the relative time
progress of the calling animation group
- parameter animation: the animation or animation group to attach
- parameter view: the view to attach it to
- parameter timeProgress: the relative time progress to trigger animation on the view
- parameter valueProgress: the relative value progress to trigger animation on the view
*/
/*
public func triggerAnimation(animation : AnyObject,
onView view : UIView,
atTimeProgress timeProgress: CGFloat? = nil,
atValueProgress valueProgress: CGFloat? = nil) {
configureAnimationTrigger(animation,
onView : view,
atTimeProgress : timeProgress,
atValueProgress : valueProgress)
}
*/
|
0 | //
// pomMainPage.swift
// Kerwin_UITest
//
// Created by Kerwin Lumpkins on 9/13/20.
//
import Foundation
import XCTest
enum pomMainPage: String {
case useDefCellTypes = "Use default cell types"
case useCustomCellTypes = "Use custom cell types"
case uiLabelCustomization = "UILabel customization"
case dynamicRows = "Dynamic"
case tableRef
var uielement: XCUIElement {
switch self {
case .useDefCellTypes, .useCustomCellTypes, .uiLabelCustomization, .dynamicRows:
return XCUIApplication().staticTexts[self.rawValue]
case .tableRef:
return XCUIApplication().tables.firstMatch
}
}
/** taps on the specified item for this page
- parameter whichItem: which item on this page to tap
- returns: none
*/
static func tapOnTableItem (whichItem: pomMainPage){
whichItem.uielement.tap()
}
}
|
0 | //
// IconImages.swift
// Multi
//
// Created by Andrew Gold on 7/4/18.
// Copyright © 2018 Distributed Systems, Inc. All rights reserved.
//
import UIKit
extension UIImage {
public static var transactionSentIcon: UIImage? {
return templateImageNamed(name: "TransactionSentIcon")
}
public static var transationReceivedIcon: UIImage? {
return templateImageNamed(name: "TransactionReceivedIcon")
}
public static var transactionNewContractIcon: UIImage? {
return templateImageNamed(name: "TransactionNewContractIcon")
}
private static func templateImageNamed(name: String) -> UIImage? {
var image = UIImage(named: name)
image = image?.withRenderingMode(.alwaysTemplate)
return image
}
}
|
0 | //
// RStudioServerSession.swift
// RSwitch
//
// Created by hrbrmstr on 9/5/19.
// Copyright © 2019 Bob Rudis. All rights reserved.
//
import Foundation
import Cocoa
class RStudioServerSession : Codable {
var url : String
var menuTitle : String
var wk : ToolbarWebViewController?
var wv : RstudioServerSessionWebViewController?
private enum CodingKeys: String, CodingKey {
case url
case menuTitle
}
init(url: String, title: String) {
self.url = url
self.menuTitle = title
self.wk = nil
self.wv = nil
}
func show() {
if (wk == nil) {
wk = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "windowWithWkViewAndToolbar") as? ToolbarWebViewController
wk?.nicknname.stringValue = menuTitle
wk?.url.stringValue = url
wv = (wk?.contentViewController as! RstudioServerSessionWebViewController)
}
wk?.showWindow(self)
wv?.loadWebView(urlIn: url)
NSApp.activate(ignoringOtherApps: true)
}
}
|
0 | //
// NextLevel+AVFoundation.swift
// NextLevel (http://nextlevel.engineering/)
//
// Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
import AVFoundation
extension AVCaptureConnection {
/// Returns the capture connection for the desired media type, otherwise nil.
///
/// - Parameters:
/// - mediaType: Specified media type. (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.)
/// - connections: Array of `AVCaptureConnection` objects to search
/// - Returns: Capture connection for the desired media type, otherwise nil
public class func connection(withMediaType mediaType: AVMediaType, fromConnections connections: [AVCaptureConnection]) -> AVCaptureConnection? {
for connection: AVCaptureConnection in connections {
for port: AVCaptureInput.Port in connection.inputPorts {
if port.mediaType == mediaType {
return connection
}
}
}
return nil
}
}
extension AVCaptureDeviceInput {
/// Returns the capture device input for the desired media type and capture session, otherwise nil.
///
/// - Parameters:
/// - mediaType: Specified media type. (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.)
/// - captureSession: Capture session for which to query
/// - Returns: Desired capture device input for the associated media type, otherwise nil
public class func deviceInput(withMediaType mediaType: AVMediaType, captureSession: AVCaptureSession) -> AVCaptureDeviceInput? {
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for deviceInput in inputs {
if deviceInput.device.hasMediaType(mediaType) {
return deviceInput
}
}
}
return nil
}
}
extension AVCaptureDevice {
// MARK: - device lookup
/// Returns the capture device for the desired device type and position.
/// #protip, NextLevelDevicePosition.avfoundationType can provide the AVFoundation type.
///
/// - Parameters:
/// - deviceType: Specified capture device type, (i.e. builtInMicrophone, builtInWideAngleCamera, etc.)
/// - position: Desired position of device
/// - Returns: Capture device for the specified type and position, otherwise nil
public class func captureDevice(withType deviceType: AVCaptureDevice.DeviceType, forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let deviceTypes: [AVCaptureDevice.DeviceType] = [deviceType]
if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first {
return discoverySession
}
return nil
}
/// Returns the default wide angle video device for the desired position, otherwise nil.
///
/// - Parameter position: Desired position of the device
/// - Returns: Wide angle video capture device, otherwise nil
public class func wideAngleVideoDevice(forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let deviceTypes: [AVCaptureDevice.DeviceType] = [AVCaptureDevice.DeviceType.builtInWideAngleCamera]
if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first {
return discoverySession
}
return nil
}
/// Returns the default telephoto video device for the desired position, otherwise nil.
///
/// - Parameter position: Desired position of the device
/// - Returns: Telephoto video capture device, otherwise nil
public class func telephotoVideoDevice(forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let deviceTypes: [AVCaptureDevice.DeviceType] = [AVCaptureDevice.DeviceType.builtInTelephotoCamera]
if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first {
return discoverySession
}
return nil
}
/// Returns the primary video device. Selects first device which is available from the following list:
/// triple camera, dual camera, wide angle camera, ultra wide angle camera, telephoto camera.
///
/// - Parameter position: Desired position of the device
/// - Returns: Primary video capture device found, otherwise nil
public class func primaryVideoDevice(forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
var deviceTypes: [AVCaptureDevice.DeviceType] = []
if #available(iOS 13.0, *) {
deviceTypes.append(.builtInTripleCamera)
deviceTypes.append(.builtInDualWideCamera)
}
if #available(iOS 11.0, *) {
deviceTypes.append(.builtInDualCamera)
}
deviceTypes.append(.builtInWideAngleCamera)
if #available(iOS 13.0, *) {
deviceTypes.append(.builtInUltraWideCamera)
}
deviceTypes.append(.builtInTelephotoCamera)
for deviceType in deviceTypes {
if let device = AVCaptureDevice.default(deviceType, for: .video, position: position) {
return device
}
}
return nil
}
/// Returns the default video capture device, otherwise nil.
///
/// - Returns: Default video capture device, otherwise nil
public class func videoDevice() -> AVCaptureDevice? {
return AVCaptureDevice.default(for: AVMediaType.video)
}
/// Returns the default audio capture device, otherwise nil.
///
/// - Returns: default audio capture device, otherwise nil
public class func audioDevice() -> AVCaptureDevice? {
return AVCaptureDevice.default(for: AVMediaType.audio)
}
// MARK: - utilities
/// Calculates focal length and principle point camera intrinsic parameters for OpenCV.
/// (see Hartley's Mutiple View Geometry, Chapter 6)
///
/// - Parameters:
/// - focalLengthX: focal length along the x-axis
/// - focalLengthY: focal length along the y-axis
/// - principlePointX: principle point x-coordinate
/// - principlePointY: principle point y-coordinate
/// - Returns: `true` when the focal length and principle point parameters are successfully calculated.
public func focalLengthAndPrinciplePoint(focalLengthX: inout Float, focalLengthY: inout Float, principlePointX: inout Float, principlePointY: inout Float) {
let dimensions = CMVideoFormatDescriptionGetPresentationDimensions(self.activeFormat.formatDescription, usePixelAspectRatio: true, useCleanAperture: true)
principlePointX = Float(dimensions.width) * 0.5
principlePointY = Float(dimensions.height) * 0.5
let horizontalFieldOfView = self.activeFormat.videoFieldOfView
let verticalFieldOfView = (horizontalFieldOfView / principlePointX) * principlePointY
focalLengthX = abs( Float(dimensions.width) / (2.0 * tan(horizontalFieldOfView / 180.0 * .pi / 2 )) )
focalLengthY = abs( Float(dimensions.height) / (2.0 * tan(verticalFieldOfView / 180.0 * .pi / 2 )) )
}
}
extension AVCaptureDevice.Format {
/// Returns the maximum capable framerate for the desired capture format and minimum, otherwise zero.
///
/// - Parameters:
/// - format: Capture format to evaluate for a specific framerate.
/// - minFrameRate: Lower bound time scale or minimum desired framerate.
/// - Returns: Maximum capable framerate within the desired format and minimum constraints.
public class func maxFrameRate(forFormat format: AVCaptureDevice.Format, minFrameRate: CMTimeScale) -> CMTimeScale {
var lowestTimeScale: CMTimeScale = 0
for range in format.videoSupportedFrameRateRanges {
if range.minFrameDuration.timescale >= minFrameRate && (lowestTimeScale == 0 || range.minFrameDuration.timescale < lowestTimeScale) {
lowestTimeScale = range.minFrameDuration.timescale
}
}
return lowestTimeScale
}
/// Checks if the specified capture device format supports a desired framerate and dimensions.
///
/// - Parameters:
/// - frameRate: Desired frame rate
/// - dimensions: Desired video dimensions
/// - Returns: `true` if the capture device format supports the given criteria, otherwise false
public func isSupported(withFrameRate frameRate: CMTimeScale, dimensions: CMVideoDimensions = CMVideoDimensions(width: 0, height: 0)) -> Bool {
let formatDimensions = CMVideoFormatDescriptionGetDimensions(self.formatDescription)
if (formatDimensions.width >= dimensions.width && formatDimensions.height >= dimensions.height) {
for frameRateRange in self.videoSupportedFrameRateRanges {
if frameRateRange.minFrameDuration.timescale >= frameRate && frameRateRange.maxFrameDuration.timescale <= frameRate {
return true
}
}
}
return false
}
}
extension AVCaptureDevice.Position {
/// Checks if a camera device is available for a position.
///
/// - Parameter devicePosition: Camera device position to query.
/// - Returns: `true` if the camera device exists, otherwise false.
public var isCameraDevicePositionAvailable: Bool {
return UIImagePickerController.isCameraDeviceAvailable(self.uikitType)
}
/// UIKit device equivalent type
public var uikitType: UIImagePickerController.CameraDevice {
switch self {
case .front:
return .front
case .unspecified:
fallthrough
case .back:
fallthrough
@unknown default:
return .rear
}
}
}
extension AVCaptureDevice.WhiteBalanceGains {
/// Normalize gain values for a capture device.
///
/// - Parameter captureDevice: Device used for adjustment.
/// - Returns: Normalized gains.
public func normalize(_ captureDevice: AVCaptureDevice) -> AVCaptureDevice.WhiteBalanceGains {
var newGains = self
newGains.redGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.redGain))
newGains.greenGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.greenGain))
newGains.blueGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.blueGain))
return newGains
}
}
extension AVCaptureVideoOrientation {
/// UIKit orientation equivalent type
public var uikitType: UIDeviceOrientation {
switch self {
case .portrait:
return .portrait
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
case .portraitUpsideDown:
return .portraitUpsideDown
@unknown default:
return .unknown
}
}
internal static func avorientationFromUIDeviceOrientation(_ orientation: UIDeviceOrientation) -> AVCaptureVideoOrientation {
var avorientation: AVCaptureVideoOrientation = .portrait
switch orientation {
case .portrait:
break
case .landscapeLeft:
avorientation = .landscapeRight
break
case .landscapeRight:
avorientation = .landscapeLeft
break
case .portraitUpsideDown:
avorientation = .portraitUpsideDown
break
default:
break
}
return avorientation
}
}
extension AVCaptureDevice.DeviceType {
public var nextLevelDeviceType: NextLevelDeviceType? {
if self == .builtInWideAngleCamera {
return .wideAngleCamera
}
if self == .builtInDuoCamera {
return .duoCamera
}
if self == .builtInTelephotoCamera {
return .telephotoCamera
}
if #available(iOS 10.2, *) {
if self == .builtInDualCamera {
return .duoCamera
}
}
#if USE_TRUE_DEPTH
if #available(iOS 11.1, *) {
if self == .builtInTrueDepthCamera {
return .trueDepthCamera
}
}
#endif
if #available(iOS 13.0, *) {
if self == .builtInTripleCamera {
return .tripleCamera
}
if self == .builtInDualWideCamera {
return .dualWideCamera
}
if self == .builtInUltraWideCamera {
return .ultraWideAngleCamera
}
}
return nil
}
}
|
0 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "ComposableCacheKit",
platforms: [
.macOS(.v10_12), .iOS(.v10), .watchOS(.v3), .tvOS(.v10)
],
products: [
.library(
name: "ComposableCacheKit",
targets: ["ComposableCacheKit"]
)
],
dependencies: [
.package(url: "https://github.com/khanlou/Promise", .upToNextMajor(from: "2.0.1"))
],
targets: [
.target(
name: "ComposableCacheKit",
dependencies: ["Promise"],
path: "ComposableCacheKit"
),
.testTarget(
name: "ComposableCacheKitTests",
dependencies: ["ComposableCacheKit"],
path: "ComposableCacheKitTests"
)
]
)
|
0 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// This contains `_BTree`'s general implementation of BidirectionalCollection.
// These operations are bounds in contrast to most other methods on _BTree as
// they are designed to be easily propogated to a higher-level data type.
// However, they still do not perform index validation
extension _BTree: BidirectionalCollection {
/// The total number of elements contained within the BTree
/// - Complexity: O(1)
@inlinable
@inline(__always)
internal var count: Int { self.root.storage.header.subtreeCount }
/// A Boolean value that indicates whether the BTree is empty.
@inlinable
@inline(__always)
internal var isEmpty: Bool { self.count == 0 }
// TODO: further consider O(1) implementation
/// Locates the first element and returns a proper path to it, or nil if the BTree is empty.
/// - Complexity: O(`log n`)
@inlinable
internal var startIndex: Index {
if count == 0 { return endIndex }
var depth: Int8 = 0
var currentNode: Unmanaged = .passUnretained(self.root.storage)
while true {
let shouldStop: Bool = currentNode._withUnsafeGuaranteedRef {
$0.read { handle in
if handle.isLeaf {
return true
} else {
depth += 1
currentNode = .passUnretained(handle[childAt: 0].storage)
return false
}
}
}
if shouldStop { break }
}
return Index(
node: currentNode,
slot: 0,
childSlots: _FixedSizeArray(repeating: 0, depth: depth),
offset: 0,
forTree: self
)
}
/// Returns a sentinel value for the last element
/// - Complexity: O(1)
@inlinable
internal var endIndex: Index {
Index(
node: .passUnretained(self.root.storage),
slot: -1,
childSlots: Index.Offsets(repeating: 0),
offset: self.count,
forTree: self
)
}
/// Returns the distance between two indices.
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If end is equal to start, the result is zero.
/// - Returns: The distance between start and end. The result can be negative only if the collection
/// conforms to the BidirectionalCollection protocol.
/// - Complexity: O(1)
@inlinable
internal func distance(from start: Index, to end: Index) -> Int {
return end.offset - start.offset
}
/// Replaces the given index with its successor.
/// - Parameter index: A valid index of the collection. i must be less than endIndex.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(after index: inout Index) {
precondition(index.offset < self.count,
"Attempt to advance out of collection bounds.")
// TODO: this might be redundant given the fact the same (but generalized)
// logic is implemented in offsetBy
let shouldSeekWithinLeaf = index.readNode {
$0.isLeaf && _fastPath(index.slot + 1 < $0.elementCount)
}
if shouldSeekWithinLeaf {
// Continue searching within the same leaf
index.slot += 1
index.offset += 1
} else {
self.formIndex(&index, offsetBy: 1)
}
}
/// Returns the position immediately after the given index.
/// - Parameter i: A valid index of the collection. i must be less than endIndex.
/// - Returns: The index value immediately after i.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func index(after i: Index) -> Index {
var newIndex = i
self.formIndex(after: &newIndex)
return newIndex
}
/// Replaces the given index with its predecessor.
/// - Parameter index: A valid index of the collection. i must be greater than startIndex.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(before index: inout Index) {
precondition(!self.isEmpty && index.offset != 0,
"Attempt to advance out of collection bounds.")
self.formIndex(&index, offsetBy: -1)
}
/// Returns the position immediately before the given index.
/// - Parameter i: A valid index of the collection. i must be greater than startIndex.
/// - Returns: The index value immediately before i.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func index(before i: Index) -> Index {
var newIndex = i
self.formIndex(before: &newIndex)
return newIndex
}
/// Offsets the given index by the specified distance.
///
/// The value passed as distance must not offset i beyond the bounds of the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(_ i: inout Index, offsetBy distance: Int) {
let newIndex = i.offset + distance
precondition(0 <= newIndex && newIndex <= self.count,
"Attempt to advance out of collection bounds.")
if newIndex == self.count {
i = endIndex
return
}
// TODO: optimization for searching within children
if i != endIndex && i.readNode({ $0.isLeaf }) {
// Check if the target element will be in the same node
let targetSlot = i.slot + distance
if 0 <= targetSlot && targetSlot < i.readNode({ $0.elementCount }) {
i.slot = targetSlot
i.offset = newIndex
return
}
}
// Otherwise, re-seek
i = self.index(atOffset: newIndex)
}
/// Returns an index that is the specified distance from the given index.
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls to
/// `index(after:)`. If `distance` is negative, this is the same value as the
/// result of `abs(distance)` calls to `index(before:)`.
@inlinable
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
var newIndex = i
self.formIndex(&newIndex, offsetBy: distance)
return newIndex
}
@inlinable
@inline(__always)
internal subscript(index: Index) -> Element {
// Ensure we don't attempt to dereference the endIndex
precondition(index != endIndex, "Attempt to subscript out of range index.")
return index.element
}
@inlinable
@inline(__always)
internal subscript(bounds: Range<Index>) -> SubSequence {
return SubSequence(base: self, bounds: bounds)
}
}
|
0 | // Zone.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nofel Mahmood ( https://twitter.com/NofelMahmood )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CloudKit
class Zone {
var zone: CKRecordZone!
var subscription: CKSubscription!
init() {
let uniqueID = NSUUID().uuidString
let zoneName = "Seam_Zone_" + uniqueID
zone = CKRecordZone(zoneName: zoneName)
let subscriptionName = zone.zoneID.zoneName + "Subscription"
subscription = CKRecordZoneSubscription(zoneID: zone.zoneID)
subscription = CKRecordZoneSubscription(zoneID: zone.zoneID, subscriptionID: subscriptionName)
let subscriptionNotificationInfo = CKNotificationInfo()
subscriptionNotificationInfo.alertBody = ""
subscriptionNotificationInfo.shouldSendContentAvailable = true
subscription.notificationInfo = subscriptionNotificationInfo
subscriptionNotificationInfo.shouldBadge = false
}
init(zoneName: String) {
zone = CKRecordZone(zoneName: zoneName)
let subscriptionName = zone.zoneID.zoneName + "Subscription"
subscription = CKRecordZoneSubscription(zoneID: zone.zoneID, subscriptionID: subscriptionName)
let subscriptionNotificationInfo = CKNotificationInfo()
subscriptionNotificationInfo.alertBody = ""
subscriptionNotificationInfo.shouldSendContentAvailable = true
subscription.notificationInfo = subscriptionNotificationInfo
subscriptionNotificationInfo.shouldBadge = false
}
// MARK: Error
static let errorDomain = "com.seam.zone.error"
enum ZoneError: Error {
case ZoneCreationFailed
case ZoneSubscriptionCreationFailed
}
// MARK: Methods
func zoneExistsOnServer(resultBlock: @escaping (_ result: Bool) -> ()) {
let fetchRecordZonesOperation = CKFetchRecordZonesOperation(recordZoneIDs: [zone.zoneID])
fetchRecordZonesOperation.fetchRecordZonesCompletionBlock = { (recordZonesByID, error) in
let successful = error == nil && recordZonesByID != nil && recordZonesByID![self.zone.zoneID] != nil
resultBlock(successful)
}
OperationQueue().addOperation(fetchRecordZonesOperation)
}
func subscriptionExistsOnServer(resultBlock: @escaping (_ result: Bool) -> ()) {
let fetchZoneSubscriptionsOperation = CKFetchSubscriptionsOperation(subscriptionIDs: [subscription.subscriptionID])
fetchZoneSubscriptionsOperation.fetchSubscriptionCompletionBlock = { (subscriptionsByID, error) in
let successful = error == nil && subscriptionsByID != nil && subscriptionsByID![self.subscription.subscriptionID] != nil
resultBlock(successful)
}
}
func createZone() throws {
var error: Error?
let operationQueue = OperationQueue()
let modifyRecordZonesOperation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil)
modifyRecordZonesOperation.modifyRecordZonesCompletionBlock = { (_,_,operationError) in
error = operationError
}
operationQueue.addOperation(modifyRecordZonesOperation)
operationQueue.waitUntilAllOperationsAreFinished()
guard error == nil else {
throw ZoneError.ZoneCreationFailed
}
}
func createSubscription() throws {
var error: Error?
let operationQueue = OperationQueue()
let modifyZoneSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
modifyZoneSubscriptionsOperation.modifySubscriptionsCompletionBlock = { (_,_,operationError) in
error = operationError
}
operationQueue.addOperation(modifyZoneSubscriptionsOperation)
operationQueue.waitUntilAllOperationsAreFinished()
guard error == nil else {
throw ZoneError.ZoneSubscriptionCreationFailed
}
}
func createSubscription(completionBlock: ((_ successful: Bool) -> ())?) {
let fetchZoneSubscriptions = CKFetchSubscriptionsOperation(subscriptionIDs: [subscription.subscriptionID])
fetchZoneSubscriptions.fetchSubscriptionCompletionBlock = { (subscriptionsByID, error) in
guard let _ = subscriptionsByID, error == nil else {
completionBlock?(false)
return
}
}
let modifyZoneSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
modifyZoneSubscriptionsOperation.modifySubscriptionsCompletionBlock = { (_,_,operationError) in
if operationError != nil {
completionBlock?(false)
} else {
completionBlock?(true)
}
}
OperationQueue().addOperation(modifyZoneSubscriptionsOperation)
}
}
|
0 | import XCTest
public extension Assertion where Subject: StringProtocol {
@discardableResult
func isEmpty(file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertTrue(subject.isEmpty, "\"\(subject)\" is not empty", file: file, line: line)
return self
}
@discardableResult
func isNotEmpty(file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertFalse(subject.isEmpty, "\"\(subject)\" is empty", file: file, line: line)
return self
}
@discardableResult
func startsWith(_ prefix: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertTrue(
subject.starts(with: prefix),
"\"\(subject)\" does not start with \"\(prefix)\"",
file: file,
line: line
)
return self
}
@discardableResult
func doesNotStartWith(_ prefix: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertFalse(subject.starts(with: prefix), "\"\(subject)\" starts with \"\(prefix)\"", file: file, line: line)
return self
}
@discardableResult
func endsWith(_ suffix: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertTrue(
subject.hasSuffix(suffix),
"\"\(subject)\" does not end with \"\(suffix)\"",
file: file,
line: line
)
return self
}
@discardableResult
func doesNotEndWith(_ suffix: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertFalse(subject.hasSuffix(suffix), "\"\(subject)\" ends with \"\(suffix)\"", file: file, line: line)
return self
}
@discardableResult
func contains(_ other: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertTrue(subject.contains(other), "\"\(subject)\" does not contain \"\(other)\"", file: file, line: line)
return self
}
@discardableResult
func doesNotContain(_ other: Subject, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertFalse(subject.contains(other), "\"\(subject)\" contains \"\(other)\"", file: file, line: line)
return self
}
@discardableResult
func matches(_ pattern: String, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertTrue(
subject.range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil,
"\"\(subject)\" does not match \"\(pattern)\"",
file: file,
line: line
)
return self
}
@discardableResult
func doesNotMatch(_ pattern: String, file: StaticString = #filePath, line: UInt = #line) -> Self {
XCTAssertFalse(
subject.range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil,
"\"\(subject)\" matches \"\(pattern)\"",
file: file,
line: line
)
return self
}
}
|
0 | //
// SettingsViewController.swift
// Tipp
//
// Created by Paulo Sousa on 7/14/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
let defaults = UserDefaults.standard
@IBOutlet weak var seg0Field: UITextField!
@IBOutlet weak var seg1Field: UITextField!
@IBOutlet weak var seg2Field: UITextField!
@IBOutlet weak var line: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Load in the selected theme, defaults to the green/yellow
applyTheme(bgColor: defaults.string(forKey: "bgColor") ?? "85a392", highlightColor: defaults.string(forKey: "highlightColor") ?? "f5b971")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Set-up the percentage fields
let segPercents = defaults.object(forKey: "segPercents") as? [Double]
//Load values into the tip
seg0Field.text = String(format: "%0.0f%%", segPercents![0]*100)
seg1Field.text = String(format: "%0.0f%%", segPercents![1]*100)
seg2Field.text = String(format: "%0.0f%%", segPercents![2]*100)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//Grab our new percentage values from the 3 fields
let rawPercentages = [seg0Field.text, seg1Field.text, seg2Field.text];
var percentages : [Double] = []
//Remove the % and scale down by 100 (/100)
for item in rawPercentages {
let item = String(item!.dropLast())
percentages.append((Double(item) ?? 0) / 100)
}
defaults.set(percentages, forKey: "segPercents")
defaults.synchronize();
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func percentageFieldEditingStart(_ sender: UITextField) {
//Remove the '%' to avoid logic errors later
sender.text = String(sender.text!.dropLast())
}
@IBAction func percentageFieldChanged(_ sender: UITextField) {
//Add the '%' back for clarity
sender.text = sender.text! + "%"
}
//Theres def a better way to do this but i dont know it yet
@IBAction func button1Pressed(_ sender: Any) {
applyTheme(bgColor: "85a392", highlightColor: "f5b971")
}
@IBAction func button2Pressed(_ sender: Any) {
applyTheme(bgColor: "dfd3c3", highlightColor: "596e79")
}
@IBAction func button3Pressed(_ sender: Any) {
applyTheme(bgColor: "ffaaa5", highlightColor: "fcf8f3")
}
@IBAction func button4Pressed(_ sender: Any) {
applyTheme(bgColor: "3f4d71", highlightColor: "ffac8e")
}
func applyTheme(bgColor: String, highlightColor: String) {
let unwrappedBg = unwrapHex(hex: bgColor)
let unwrappedHighlight = unwrapHex(hex: highlightColor)
view.backgroundColor = unwrappedBg
line.backgroundColor = unwrappedHighlight
self.navigationController?.navigationBar.barTintColor = unwrappedHighlight
self.navigationController?.navigationBar.tintColor = unwrappedBg
defaults.set(bgColor, forKey: "bgColor")
defaults.set(highlightColor, forKey: "highlightColor")
defaults.synchronize()
}
//Convert a hex string to UIColor
//I found this online (ty stackoverflow)
func unwrapHex(hex: String) -> UIColor {
var hexInt:UInt64 = 0
Scanner(string: hex).scanHexInt64(&hexInt)
let _red = CGFloat((hexInt & 0xFF0000) >> 16) / 255.0
let _green = CGFloat((hexInt & 0x00FF00) >> 8) / 255.0
let _blue = CGFloat(hexInt & 0x0000FF) / 255.0
let _alpha = CGFloat(1.0)
return UIColor(red: _red, green: _green, blue: _blue, alpha: _alpha)
}
}
|
0 | //
// StringExtensoin.swift
// Twigano
//
// Created by mac on 8/2/17.
// Copyright © 2017 islam elshazly. All rights reserved.
//
import UIKit
public extension String {
var toLocale: Locale {
return Locale(identifier: self)
}
var base64Decoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
guard let decodedData = Data(base64Encoded: self) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
var toNSString: NSString { return self as NSString }
var camelCased: String {
let source = lowercased()
let first = source[..<source.index(after: source.startIndex)]
if source.contains(" ") {
let connected = source.capitalized.replacingOccurrences(of: " ", with: "")
let camel = connected.replacingOccurrences(of: "\n", with: "")
let rest = String(camel.dropFirst())
return first + rest
}
let rest = String(source.dropFirst())
return first + rest
}
var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.count)) ?? 0
}
var countofParagraphs: Int {
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options())
let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: str.count)) ?? -1) + 1
}
var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
var isValidEmail: Bool {
// http://emailregex.com/
let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
}
var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
mutating func capitalizeFirst() {
guard self.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
mutating func lowercaseFirst() {
guard self.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
}
func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed.isEmpty
}
}
func toInt() -> Int? {
guard let num = NumberFormatter().number(from: self) else {
return nil
}
return num.intValue
}
func toDouble() -> Double? {
guard let num = NumberFormatter().number(from: self) else {
return nil
}
return num.doubleValue
}
func toFloat() -> Float? {
guard let num = NumberFormatter().number(from: self) else {
return nil
}
return num.floatValue
}
func toBool() -> Bool? {
let trimmedString = trimmed.lowercased()
if trimmedString == "true" || trimmedString == "false" {
return (trimmedString as NSString).boolValue
}
return nil
}
func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
return underlineString
}
func bold(withFont font: UIFont) -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font: font])
return boldString
}
func italic(withFont font: UIFont) -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font: font])
return italicString
}
func color(_ color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.foregroundColor: color])
return colorString
}
func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString {
var start = 0
var ranges: [NSRange] = []
while true {
let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start))
if range.location == NSNotFound {
break
} else {
ranges.append(range)
start = range.location + range.length
}
}
let attrText = NSMutableAttributedString(string: self)
for range in ranges {
attrText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
return attrText
}
}
|
0 | //
// QQMusicMessageModel.swift
// QQMusic
//
// Created by KC on 16/11/9.
// Copyright © 2016年 KC. All rights reserved.
//
import UIKit
class QQMusicMessageModel: NSObject {
var musicM: QQMusicModel?
var currentTime: TimeInterval = 0
var totalTime: TimeInterval = 0
var isPlaying: Bool = false
//当前的播放时间
var currentTimeFormat: String {
get {
return QQTimeTool.getFormatTime(time: currentTime)
}
}
//总得时间
var totalTimeFormat: String {
get {
return QQTimeTool.getFormatTime(time: totalTime)
}
}
}
|
0 | import Foundation
protocol StencilFontFilter: StencilFilter where Input == [String: Any], Output == FontFilterOutput {
// MARK: - Nested Types
associatedtype FontFilterOutput
// MARK: - Instance Properties
var contextCoder: TemplateContextCoder { get }
// MARK: - Instance Methods
func filter(font: Font) throws -> FontFilterOutput
}
extension StencilFontFilter {
// MARK: - Instance Methods
func filter(input: [String: Any]) throws -> FontFilterOutput {
guard let font = try? contextCoder.decode(Font.self, from: input) else {
throw StencilFilterError(code: .invalidValue(input), filter: name)
}
return try filter(font: font)
}
}
|
0 | //
// ContentsTableViewController.swift
// UKPDFReader
//
// Created by Umakanta Sahoo on 17/09/19.
// Copyright © 2019. All rights reserved.
//
import UIKit
import PDFKit
protocol ContentsDelegate: class {
func goTo(page: PDFPage)
}
class ContentsTableViewController: UITableViewController {
let outline: PDFOutline
weak var delegate: ContentsDelegate?
init(outline: PDFOutline, delegate: ContentsDelegate?) {
self.outline = outline
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.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 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return outline.numberOfChildren
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
// Configure the cell...
if let label = cell.textLabel, let title = outline.child(at: indexPath.row)?.label {
label.text = String(title)
}
if indexPath.row == 0 { cell.textLabel?.font = UIFont.boldSystemFont(ofSize: (cell.textLabel?.font.pointSize)!+2) }
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let page = outline.child(at: indexPath.row)?.destination?.page {
delegate?.goTo(page: page)
}
dismiss(animated: true, completion: nil)
}
}
|
0 | //
// RpcProviderExtensionEndpointTests.swift
// EosioSwiftTests
//
// Created by Ben Martell on 4/15/19.
// Copyright (c) 2017-2019 block.one and its contributors. All rights reserved.
//
//import XCTest
//import OHHTTPStubs
//import OHHTTPStubsSwift
//@testable import EosioSwift
//
//class RpcProviderExtensionEndpointTests: XCTestCase {
//
// var rpcProvider: EosioRpcProvider?
// override func setUp() {
// super.setUp()
// let url = URL(string: "https://localhost")
// rpcProvider = EosioRpcProvider(endpoint: url!)
// HTTPStubs.onStubActivation { (request, stub, _) in
// print("\(request.url!) stubbed by \(stub.name!).")
// }
// }
//
// override func tearDown() {
// super.tearDown()
// //remove all stubs on tear down
// HTTPStubs.removeAllStubs()
// }
//
// /// Test pushTransactions implementation.
// func testPushTransactions() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "PushTransactions stub"
// let expect = expectation(description: "testPushTransactions")
// // swiftlint:disable line_length
// let transOne = EosioRpcPushTransactionRequest(signatures: ["a5rfyyupat55m08z8zzkgm7r02gzjszk"], compression: 0, packedContextFreeData: "", packedTrx: "klvbqrcpt294x9jdj89a2d0nvrxgu1g6")
// let transTwo = EosioRpcPushTransactionRequest(signatures: ["a5rfyyupat55m08z8zzkgm7r02gzjszk"], compression: 0, packedContextFreeData: "", packedTrx: "x9veoxust22r3x4i8onkb6cqtklug5tj")
// // swiftlint:enable line_length
// let requestParameters = EosioRpcPushTransactionsRequest(transactions: [transOne, transTwo])
// rpcProvider?.pushTransactions(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcPushTransactionsResponse):
// XCTAssertNotNil(eosioRpcPushTransactionsResponse._rawResponse)
// XCTAssertNotNil(eosioRpcPushTransactionsResponse.transactionResponses)
// XCTAssert(eosioRpcPushTransactionsResponse.transactionResponses.count == 2)
// XCTAssert(eosioRpcPushTransactionsResponse.transactionResponses[0].transactionId == "2de4cd382c2e231c8a3ac80acfcea493dd2d9e7178b46d165283cf91c2ce6121")
// XCTAssert(eosioRpcPushTransactionsResponse.transactionResponses[1].transactionId == "8bddd86928d396dcec91e15d910086a4f8682167ff9616a84f23de63258c78fe")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed push_transactions")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test testGetBlockHeaderState() implementation.
// // swiftlint:disable function_body_length
// func testGetBlockHeaderState() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetBlockHeaderState stub"
// let expect = expectation(description: "testGetBlockHeaderState")
// let requestParameters = EosioRpcBlockHeaderStateRequest(blockNumOrId: "25260035")
// rpcProvider?.getBlockHeaderState(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcBlockHeaderStateResponse):
// XCTAssertNotNil(eosioRpcBlockHeaderStateResponse._rawResponse)
// XCTAssert(eosioRpcBlockHeaderStateResponse.id == "0137c067c65e9db8f8ee467c856fb6d1779dfeb0332a971754156d075c9a37ca")
// XCTAssert(eosioRpcBlockHeaderStateResponse.header.producerSignature == "iwrafzcv64cw9niep8a0fhrj02gu5ar0")
// guard let version = eosioRpcBlockHeaderStateResponse.pendingSchedule["version"] as? UInt64 else {
// return XCTFail("Should be able to get pendingSchedule as [String : Any].")
// }
// XCTAssert(version == 2)
// guard let activeSchedule = eosioRpcBlockHeaderStateResponse.activeSchedule["producers"] as? [[String: Any]] else {
// return XCTFail("Should be able to get activeSchedule as [String : Any].")
// }
// guard let producerName = activeSchedule.first?["producer_name"] as? String else {
// return XCTFail("Should be able to get producer_name as String.")
// }
// XCTAssert(producerName == "blkproducer1")
// guard let nodeCount = eosioRpcBlockHeaderStateResponse.blockRootMerkle["_node_count"] as? UInt64 else {
// return XCTFail("Should be able to get _node_count as Int.")
// }
// XCTAssert(nodeCount == 20430950)
// XCTAssert(eosioRpcBlockHeaderStateResponse.confirmCount.count == 12)
// XCTAssertNotNil(eosioRpcBlockHeaderStateResponse.producerToLastImpliedIrb)
// XCTAssert(eosioRpcBlockHeaderStateResponse.producerToLastImpliedIrb.count == 2)
// if let irb = eosioRpcBlockHeaderStateResponse.producerToLastImpliedIrb[0] as? [Any] {
// XCTAssertNotNil(irb)
// XCTAssert(irb.count == 2)
// guard let name = irb[0] as? String, name == "blkproducer1" else {
// XCTFail("Should be able to find name.")
// return
// }
// guard let num = irb[1] as? UInt64, num == 20430939 else {
// XCTFail("Should be able to find number.")
// return
// }
// } else {
// XCTFail("Should be able to find producer to last implied irb.")
// }
//
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_block_header_state.")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
// // swiftlint:enable function_body_length
//
// /// Test testGetAbi() implementation.
// func testGetAbi() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetAbi stub"
// let expect = expectation(description: "testGetAbi")
// let requestParameters = EosioRpcAbiRequest(accountName: "eosio.token")
// rpcProvider?.getAbi(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcAbiResponse):
// XCTAssertNotNil(eosioRpcAbiResponse._rawResponse)
// let abi = eosioRpcAbiResponse.abi
// if let abiVersion = abi["version"] as? String {
// XCTAssert(abiVersion == "eosio::abi/1.0")
// } else {
// XCTFail("Should be able to find and verify abi version.")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_abi \(String(describing: err.originalError))")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test testGetAccount() implementation.
// // swiftlint:disable function_body_length
// // swiftlint:disable cyclomatic_complexity
// func testGetAccount() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetAccount stub"
// let expect = expectation(description: "testGetAccount")
// let requestParameters = EosioRpcAccountRequest(accountName: "cryptkeeper")
// rpcProvider?.getAccount(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcAccountResponse):
// XCTAssertNotNil(eosioRpcAccountResponse)
// XCTAssert(eosioRpcAccountResponse.accountName == "cryptkeeper")
// XCTAssert(eosioRpcAccountResponse.ramQuota.value == 13639863)
// let permissions = eosioRpcAccountResponse.permissions
// XCTAssertNotNil(permissions)
// guard let activePermission = permissions.filter({$0.permName == "active"}).first else {
// return XCTFail("Cannot find Active permission in permissions structure of the account")
// }
// XCTAssert(activePermission.parent == "owner")
// guard let keysAndWeight = activePermission.requiredAuth.keys.first else {
// return XCTFail("Cannot find key in keys structure of the account")
// }
// XCTAssert(keysAndWeight.key == "h8ukqn9o5dvymf40nx96cbh03gg6b54v")
// guard let firstPermission = activePermission.requiredAuth.accounts.first else {
// return XCTFail("Can't find permission in keys structure of the account")
// }
// XCTAssert(firstPermission.permission.actor == "eosaccount1")
// XCTAssert(firstPermission.permission.permission == "active")
// XCTAssert(activePermission.requiredAuth.waits.first?.waitSec.value == 259200)
// XCTAssertNotNil(eosioRpcAccountResponse.totalResources)
// if let dict = eosioRpcAccountResponse.totalResources {
// if let owner = dict["owner"] as? String {
// XCTAssert(owner == "cryptkeeper")
// } else {
// XCTFail("Should be able to get total_resources owner as String and should equal cryptkeeper.")
// }
// if let rambytes = dict["ram_bytes"] as? UInt64 {
// XCTAssert(rambytes == 13639863)
// } else {
// XCTFail("Should be able to get total_resources ram_bytes as UIn64 and should equal 13639863.")
// }
// } else {
// XCTFail("Should be able to get total_resources as [String : Any].")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_account")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// func testGetAccountNegativeUsageValues() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// if let urlString = request.url?.absoluteString {
// if callCount == 1 && urlString == "https://localhost/v1/chain/get_info" {
// callCount += 1
// return RpcTestConstants.getInfoOHHTTPStubsResponse()
// } else if callCount == 2 && urlString == "https://localhost/v1/chain/get_account" {
// return RpcTestConstants.getOHHTTPStubsResponseForJson(json: RpcTestConstants.accountNegativeUsageValuesJson)
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(code: NSURLErrorUnknown, reason: "Unexpected call count in stub: \(callCount)")
// }
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(reason: "No valid url string in request in stub")
// }
// }).name = "Get Account Negative Usage Values stub"
// let expect = expectation(description: "testGetAccountNegativeUsageValues")
// let requestParameters = EosioRpcAccountRequest(accountName: "cryptkeeper")
// rpcProvider?.getAccount(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcAccountResponse):
// XCTAssertNotNil(eosioRpcAccountResponse)
// XCTAssert(eosioRpcAccountResponse.accountName == "cryptkeeper")
// XCTAssert(eosioRpcAccountResponse.ramQuota.value == -1)
// XCTAssert(eosioRpcAccountResponse.cpuWeight.value == -1)
// let permissions = eosioRpcAccountResponse.permissions
// XCTAssertNotNil(permissions)
// guard let activePermission = permissions.filter({$0.permName == "active"}).first else {
// return XCTFail("Cannot find Active permission in permissions structure of the account")
// }
// XCTAssert(activePermission.parent == "owner")
// guard let keysAndWeight = activePermission.requiredAuth.keys.first else {
// return XCTFail("Cannot find key in keys structure of the account")
// }
// XCTAssert(keysAndWeight.key == "h8ukqn9o5dvymf40nx96cbh03gg6b54v")
// guard let firstPermission = activePermission.requiredAuth.accounts.first else {
// return XCTFail("Can't find permission in keys structure of the account")
// }
// XCTAssert(firstPermission.permission.actor == "eosaccount1")
// XCTAssert(firstPermission.permission.permission == "active")
// XCTAssert(activePermission.requiredAuth.waits.first?.waitSec.value == 259200)
// XCTAssertNotNil(eosioRpcAccountResponse.totalResources)
// if let dict = eosioRpcAccountResponse.totalResources {
// if let owner = dict["owner"] as? String {
// XCTAssert(owner == "cryptkeeper")
// } else {
// XCTFail("Should be able to get total_resources owner as String and should equal cryptkeeper.")
// }
// if let rambytes = dict["ram_bytes"] as? UInt64 {
// XCTAssert(rambytes == 13639863)
// } else {
// XCTFail("Should be able to get total_resources ram_bytes as UIn64 and should equal 13639863.")
// }
// } else {
// XCTFail("Should be able to get total_resources as [String : Any].")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_account")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
// // swiftlint:enable function_body_length
// // swiftlint:enable cyclomatic_complexity
//
// /// Test testGetCurrencyBalance() implementation.
// func testGetCurrencyBalance() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetCurrencyBalance stub"
// let expect = expectation(description: "testGetCurrencyBalance")
// let requestParameters = EosioRpcCurrencyBalanceRequest(code: "eosio.token", account: "cryptkeeper", symbol: "EOS")
// rpcProvider?.getCurrencyBalance(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcCurrencyBalanceResponse):
// XCTAssertNotNil(eosioRpcCurrencyBalanceResponse._rawResponse)
// XCTAssert(eosioRpcCurrencyBalanceResponse.currencyBalance.count == 1)
// XCTAssert(eosioRpcCurrencyBalanceResponse.currencyBalance[0].contains(words: "EOS") )
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_currency_balance")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getCurrencyStats() implementation.
// func testGetCurrencyStats() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetCurrencyStats stub"
// let expect = expectation(description: "getCurrencyStats")
// let requestParameters = EosioRpcCurrencyStatsRequest(code: "eosio.token", symbol: "EOS")
// rpcProvider?.getCurrencyStats(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcCurrencyStatsResponse):
// XCTAssertNotNil(eosioRpcCurrencyStatsResponse._rawResponse)
// XCTAssert(eosioRpcCurrencyStatsResponse.symbol == "EOS")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_currency_stats")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getCurrencyStatsSYS() implementation.
// func testGetCurrencyStatsSYS() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// if let urlString = request.url?.absoluteString {
// if callCount == 1 && urlString == "https://localhost/v1/chain/get_info" {
// callCount += 1
// return RpcTestConstants.getInfoOHHTTPStubsResponse()
// } else if callCount == 2 && urlString == "https://localhost/v1/chain/get_currency_stats" {
// let json = RpcTestConstants.currencyStatsSYS
// let data = json.data(using: .utf8)
// return HTTPStubsResponse(data: data!, statusCode: 200, headers: nil)
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(code: NSURLErrorUnknown, reason: "Unexpected call count in stub: \(callCount)")
// }
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(reason: "No valid url string in request in stub")
// }
// }).name = "GetCurrencyStats stub"
// let expect = expectation(description: "getCurrencyStats")
// let requestParameters = EosioRpcCurrencyStatsRequest(code: "eosio.token", symbol: "SYS")
// rpcProvider?.getCurrencyStats(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcCurrencyStatsResponse):
// XCTAssertNotNil(eosioRpcCurrencyStatsResponse._rawResponse)
// XCTAssert(eosioRpcCurrencyStatsResponse.symbol == "SYS")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_currency_stats")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getRawCodeAndAbi() implementation.
// func testGetRawCodeAndAbi() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetRawCodeAndAbis stub"
// let expect = expectation(description: "getRawCodeAndAbi")
// let requestParameters = EosioRpcRawCodeAndAbiRequest(accountName: "eosio.token")
// rpcProvider?.getRawCodeAndAbi(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcRawCodeAndAbiResponse):
// XCTAssertNotNil(eosioRpcRawCodeAndAbiResponse._rawResponse)
// XCTAssert(eosioRpcRawCodeAndAbiResponse.accountName == "eosio.token")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_raw_code_and_abi")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getRawCodeAndAbi() with String signature implementation.
// func testGetRawCodeAndAbiWithStringSignature() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetRawCodeAndAbis w String stub"
// let expect = expectation(description: "testGetRawCodeAndAbiWithStringSignature")
// rpcProvider?.getRawCodeAndAbi(accountName: "eosio.token" ) { response in
// switch response {
// case .success(let eosioRpcRawCodeAndAbiResponse):
// XCTAssertNotNil(eosioRpcRawCodeAndAbiResponse._rawResponse)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_raw_code_and_abi")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getCode() implementation.
// func testgetCode() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetCode stub"
// let expect = expectation(description: "testGetCode")
// let requestParameters = EosioRpcCodeRequest(accountName: "tropical")
// rpcProvider?.getCode(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcCodeResponse):
// XCTAssertNotNil(eosioRpcCodeResponse._rawResponse)
// XCTAssert(eosioRpcCodeResponse.accountName == "tropical")
// XCTAssert(eosioRpcCodeResponse.codeHash == "68721c88e8b04dea76962d8afea28d2f39b870d72be30d1d143147cdf638baad")
// if let dict = eosioRpcCodeResponse.abi {
// if let version = dict["version"] as? String {
// XCTAssert(version == "eosio::abi/1.1")
// } else {
// XCTFail("Should be able to get abi version as String and should equal eosio::abi/1.1.")
// }
// } else {
// XCTFail("Should be able to get abi as [String : Any].")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_code")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getCode() with String signature implementation.
// func testGetCodeWithStringSignature() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetCodeWithStringSignature stub"
// let expect = expectation(description: "testGetCodeWithStringSignature")
// rpcProvider?.getCode(accountName: "cryptkeeper" ) { response in
// switch response {
// case .success(let eosioRpcCodeResponse):
// XCTAssertNotNil(eosioRpcCodeResponse._rawResponse)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_code")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getTableRows() implementation.
// func testGetTableRows() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetTableRows stub"
// let expect = expectation(description: "testGetTableRows")
// let requestParameters = EosioRpcTableRowsRequest(scope: "cryptkeeper", code: "eosio.token", table: "accounts")
// rpcProvider?.getTableRows(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcTableRowsResponse):
// XCTAssertNotNil(eosioRpcTableRowsResponse._rawResponse)
// XCTAssertNotNil(eosioRpcTableRowsResponse.rows)
// XCTAssert(eosioRpcTableRowsResponse.rows.count == 1)
// if let row = eosioRpcTableRowsResponse.rows[0] as? [String: Any],
// let balance = row["balance"] as? String {
// XCTAssert(balance == "986420.1921 EOS")
// } else {
// XCTFail("Cannot get returned table row or balance string.")
// }
// XCTAssertFalse(eosioRpcTableRowsResponse.more)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_table_rows")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getTableByScope() implementation.
// func testGetTableByScope() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetTableByScope stub"
// let expect = expectation(description: "testGetTableByScope")
// let requestParameters = EosioRpcTableByScopeRequest(code: "eosio.token")
// rpcProvider?.getTableByScope(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcTableByScopeResponse):
// XCTAssertNotNil(eosioRpcTableByScopeResponse._rawResponse)
// XCTAssertNotNil(eosioRpcTableByScopeResponse.rows)
// XCTAssert(eosioRpcTableByScopeResponse.rows.count == 10)
// let row = eosioRpcTableByScopeResponse.rows[8]
// XCTAssert(row.code == "eosio.token")
// XCTAssert(row.scope == "eosio")
// XCTAssert(row.table == "accounts")
// XCTAssert(row.payer == "eosio")
// XCTAssert(row.count == 1)
// XCTAssert(eosioRpcTableByScopeResponse.more == "eosio.ramfee")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_table_by_scope")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getProducers implementation.
// func testGetProducers() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetProducers stub"
// let expect = expectation(description: "testGetProducers")
// let requestParameters = EosioRpcProducersRequest(limit: 10, lowerBound: "blkproducer2", json: true)
// rpcProvider?.getProducers(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcProducersResponse):
// XCTAssertNotNil(eosioRpcProducersResponse._rawResponse)
// XCTAssertNotNil(eosioRpcProducersResponse.rows)
// XCTAssert(eosioRpcProducersResponse.rows.count == 2)
// XCTAssert(eosioRpcProducersResponse.rows[0].owner == "blkproducer2")
// XCTAssert(eosioRpcProducersResponse.rows[0].unpaidBlocks.value == 0)
// XCTAssert(eosioRpcProducersResponse.rows[1].owner == "blkproducer3")
// XCTAssert(eosioRpcProducersResponse.rows[0].isActive == 1)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_producers")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getActions implementation.
// func testGetActions() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetActions stub"
// let expect = expectation(description: "testGetActions")
// let requestParameters = EosioRpcHistoryActionsRequest(position: -1, offset: -20, accountName: "cryptkeeper")
// rpcProvider?.getActions(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcActionsResponse):
// XCTAssertNotNil(eosioRpcActionsResponse._rawResponse)
// XCTAssert(eosioRpcActionsResponse.lastIrreversibleBlock.value == 55535908)
// XCTAssert(eosioRpcActionsResponse.timeLimitExceededError == false)
// XCTAssert(eosioRpcActionsResponse.actions.first?.globalActionSequence.value == 6483908013)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.receiverSequence.value == 1236)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.count == 1)
// if let firstSequence = eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.first as? [Any] {
// guard let accountName = firstSequence.first as? String, accountName == "powersurge22" else {
// return XCTFail("Should be able to find account name")
// }
// }
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.name == "transfer")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.authorization.first?.permission == "active")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.data["memo"] as? String == "l2sbjsdrfd.m")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.hexData == "10826257e3ab38ad000000004800a739f3eef20b00000000044d4545544f4e450c6c3273626a736472666a2e6f")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.accountRamDeltas.first?.delta.value == 472)
// if let console = eosioRpcActionsResponse.actions.first?.actionTrace.console {
// XCTAssert(console == "contracts console")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_actions")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// func testGetActionsNegativeDelta() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// if let urlString = request.url?.absoluteString {
// if callCount == 1 && urlString == "https://localhost/v1/chain/get_info" {
// callCount += 1
// return RpcTestConstants.getInfoOHHTTPStubsResponse()
// } else if callCount == 2 && urlString == "https://localhost/v1/history/get_actions" {
// return RpcTestConstants.getOHHTTPStubsResponseForJson(json: RpcTestConstants.actionsNegativeDeltaJson)
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(code: NSURLErrorUnknown, reason: "Unexpected call count in stub: \(callCount)")
// }
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(reason: "No valid url string in request in stub")
// }
// }).name = "Get Actions Negative Delta stub"
// let expect = expectation(description: "testGetActionsNegativeDelta")
// let requestParameters = EosioRpcHistoryActionsRequest(position: -1, offset: -20, accountName: "cryptkeeper")
// rpcProvider?.getActions(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcActionsResponse):
// XCTAssertNotNil(eosioRpcActionsResponse._rawResponse)
// XCTAssert(eosioRpcActionsResponse.lastIrreversibleBlock.value == 55535908)
// XCTAssert(eosioRpcActionsResponse.timeLimitExceededError == false)
// XCTAssert(eosioRpcActionsResponse.actions.first?.globalActionSequence.value == 6483908013)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.receiverSequence.value == 1236)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.count == 1)
// if let firstSequence = eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.first as? [Any] {
// guard let accountName = firstSequence.first as? String, accountName == "powersurge22" else {
// return XCTFail("Should be able to find account name")
// }
// }
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.name == "transfer")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.authorization.first?.permission == "active")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.data["memo"] as? String == "l2sbjsdrfd.m")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.hexData == "10826257e3ab38ad000000004800a739f3eef20b00000000044d4545544f4e450c6c3273626a736472666a2e6f")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.accountRamDeltas.first?.delta.value == -1)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_actions")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// func testGetActionsNoConsole() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// if let urlString = request.url?.absoluteString {
// if callCount == 1 && urlString == "https://localhost/v1/chain/get_info" {
// callCount += 1
// return RpcTestConstants.getInfoOHHTTPStubsResponse()
// } else if callCount == 2 && urlString == "https://localhost/v1/history/get_actions" {
// return RpcTestConstants.getOHHTTPStubsResponseForJson(json: RpcTestConstants.actionsNoConsoleJson)
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(code: NSURLErrorUnknown, reason: "Unexpected call count in stub: \(callCount)")
// }
// } else {
// return RpcTestConstants.getErrorOHHTTPStubsResponse(reason: "No valid url string in request in stub")
// }
// }).name = "Get Actions No Console stub"
// let expect = expectation(description: "testGetActionsNoConsole")
// let requestParameters = EosioRpcHistoryActionsRequest(position: -1, offset: -20, accountName: "cryptkeeper")
// rpcProvider?.getActions(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcActionsResponse):
// XCTAssertNotNil(eosioRpcActionsResponse._rawResponse)
// XCTAssert(eosioRpcActionsResponse.lastIrreversibleBlock.value == 55535908)
// XCTAssert(eosioRpcActionsResponse.timeLimitExceededError == false)
// XCTAssert(eosioRpcActionsResponse.actions.first?.globalActionSequence.value == 6483908013)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.receiverSequence.value == 1236)
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.count == 1)
// if let firstSequence = eosioRpcActionsResponse.actions.first?.actionTrace.receipt.authorizationSequence.first as? [Any] {
// guard let accountName = firstSequence.first as? String, accountName == "powersurge22" else {
// return XCTFail("Should be able to find account name")
// }
// }
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.name == "transfer")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.authorization.first?.permission == "active")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.data["memo"] as? String == "l2sbjsdrfd.m")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.action.hexData == "10826257e3ab38ad000000004800a739f3eef20b00000000044d4545544f4e450c6c3273626a736472666a2e6f")
// XCTAssert(eosioRpcActionsResponse.actions.first?.actionTrace.accountRamDeltas.first?.delta.value == 472)
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_actions")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getControlledAccounts implementation.
// func testGetControlledAccounts() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetControlledAccounts stub"
// let expect = expectation(description: "testGetControlledAccounts")
// let requestParameters = EosioRpcHistoryControlledAccountsRequest(controllingAccount: "cryptkeeper")
// rpcProvider?.getControlledAccounts(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcControlledAccountsResponse):
// XCTAssertNotNil(eosioRpcControlledAccountsResponse._rawResponse)
// XCTAssertNotNil(eosioRpcControlledAccountsResponse.controlledAccounts)
// XCTAssert(eosioRpcControlledAccountsResponse.controlledAccounts.count == 2)
// XCTAssert(eosioRpcControlledAccountsResponse.controlledAccounts[0] == "subcrypt1")
// XCTAssert(eosioRpcControlledAccountsResponse.controlledAccounts[1] == "subcrypt2")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_controlled_accounts")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getTransaction implementation.
// func testGetTransaction() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetTransaction stub"
// let expect = expectation(description: "testGetTransaction")
// let requestParameters = EosioRpcHistoryTransactionRequest(transactionId: "ae735820e26a7b771e1b522186294d7cbba035d0c31ca88237559d6c0a3bf00a", blockNumHint: 21098575)
// rpcProvider?.getTransaction(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcGetTransactionResponse):
// XCTAssert(eosioRpcGetTransactionResponse.id == "ae735820e26a7b771e1b522186294d7cbba035d0c31ca88237559d6c0a3bf00a")
// XCTAssert(eosioRpcGetTransactionResponse.blockNum.value == 21098575)
// guard let dict = eosioRpcGetTransactionResponse.trx["trx"] as? [String: Any] else {
// XCTFail("Should find trx.trx dictionary.")
// return
// }
// if let refBlockNum = dict["ref_block_num"] as? UInt64 {
// XCTAssert(refBlockNum == 61212)
// } else {
// XCTFail("Should find trx ref_block_num and it should match.")
// }
// if let signatures = dict["signatures"] as? [String] {
// XCTAssert(signatures[0] == "h8ukqn9o5dvymf40nx96cbh03gg6b54v")
// } else {
// XCTFail("Should find trx signatures and it should match.")
// }
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_transaction")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test getKeyAccounts implementation.
// func testGetKeyAccounts() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "GetKeyAccounts stub"
// let expect = expectation(description: "testGetKeyAccounts")
// let requestParameters = EosioRpcHistoryKeyAccountsRequest(publicKey: "dks0st8f8xsfgpmvakivc16d22ul34xx")
// rpcProvider?.getKeyAccounts(requestParameters: requestParameters) { response in
// switch response {
// case .success(let eosioRpcKeyAccountsResponse):
// XCTAssertNotNil(eosioRpcKeyAccountsResponse.accountNames)
// XCTAssert(eosioRpcKeyAccountsResponse.accountNames.count == 2)
// XCTAssert(eosioRpcKeyAccountsResponse.accountNames[0] == "cryptkeeper")
// case .failure(let err):
// print(err.description)
// XCTFail("Failed get_key_accounts")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//
// /// Test sendTransaction() implementation.
// func testSendTransaction() {
// var callCount = 1
// (stub(condition: isHost("localhost")) { request in
// let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath)
// callCount += 1
// return retVal
// }).name = "Send Transaction stub"
// let expect = expectation(description: "testSendTransaction")
// // swiftlint:disable line_length
// let requestParameters = EosioRpcSendTransactionRequest(signatures: ["h8ukqn9o5dvymf40nx96cbh03gg6b54v"], compression: 0, packedContextFreeData: "", packedTrx: "a5rfyyupat55m08z8zzkgm7r02gzjszk")
// // swiftlint:enable line_length
// rpcProvider?.sendTransactionBase(requestParameters: requestParameters) { response in
// switch response {
// case .success(let sentResponse):
// XCTAssertTrue(sentResponse.transactionId == "2e611730d904777d5da89e844cac4936da0ff844ad8e3c7eccd5da912423c9e9")
// if let sentTransactionResponse = sentResponse as? EosioRpcTransactionResponse {
// if let processed = sentTransactionResponse.processed as [String: Any]?,
// let receipt = processed["receipt"] as? [String: Any],
// let status = receipt["status"] as? String {
// XCTAssert(status == "executed")
// } else {
// XCTFail("Should be able to find processed.receipt.status and verify its value.")
// }
// } else {
// XCTFail("Concrete response type should be EosioRpcTransactionResponse.")
// }
// case .failure(let err):
// XCTFail("\(err.description)")
// }
// expect.fulfill()
// }
// wait(for: [expect], timeout: 30)
// }
//}
|
0 | //
// ViewController.swift
// GLPageView
//
// Created by GL on 2017/7/11.
// Copyright © 2017年 GL. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let ming: Person = Person()
var pageView: GLPageView? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ming.name="哈利波特"
var myContext = "啦啦"
ming.addObserver(self, forKeyPath: "name", options: NSKeyValueObservingOptions.old , context: &myContext)
let inset: Float = 225.0 / 255.0
self.view.backgroundColor = UIColor.init(colorLiteralRed: inset, green: inset, blue: inset, alpha: 1)
let titleArray: Array = ["推荐","手游","娱乐","游戏","趣玩"]
let recommend = RecommendVC()
let phoneGame = PhoneGameVC()
let entertainment = EntertainmentVC()
let game = GameVC()
let funPlay = FunPlayVC()
self.addChildViewController(recommend)
self.addChildViewController(phoneGame)
self.addChildViewController(entertainment)
self.addChildViewController(game)
self.addChildViewController(funPlay)
let frame = CGRect(x: 0, y: 60, width: self.view.bounds.size.width, height: self.view.bounds.size.height-60-0)
print(self.view.bounds.size.height)
print(NSStringFromCGRect(frame))
pageView = GLPageView.init(frame: frame, childTitles: titleArray, childControllers: self.childViewControllers)
pageView?.titleStyle = GLPageTitleStyle.Gradient
pageView?.maxNumberOfPageItems = 5
pageView?.selectedColor = UIColor.yellow
//pageView?.selectedPageIndex = 1;
pageView?.delegete=self
self.view.addSubview(pageView!)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
ming.setValue("哈利", forKey: "name")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// print(keyPath!);
//
// print(context!);
//
// print(change!);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: GLPageViewDelegate {
func pageTabViewDidEndChange() {
print("哈哈")
}
}
|
0 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
@testable import FBSDKCoreKit
@testable import FBSDKGamingServicesKit
import TestTools
import XCTest
final class SwitchContextDialogTests: XCTestCase, ContextDialogDelegate {
var dialogDidCompleteSuccessfully = false
var dialogDidCancel = false
var dialogError: NSError?
// swiftlint:disable implicitly_unwrapped_optional
var windowFinder: TestWindowFinder!
var content: SwitchContextContent!
var dialog: SwitchContextDialog!
// swiftlint:enable implicitly_unwrapped_optional
override func setUp() {
super.setUp()
windowFinder = TestWindowFinder()
content = SwitchContextContent(contextID: "1234567890")
dialog = SwitchContextDialog(
content: content,
windowFinder: windowFinder,
delegate: self
)
_WebDialog.setDependencies(
.init(
errorFactory: TestErrorFactory(),
windowFinder: TestWindowFinder(window: UIWindow())
)
)
}
override func tearDown() {
_WebDialog.resetDependencies()
GamingContext.current = nil
dialogError = nil
windowFinder = nil
content = nil
dialog = nil
_WebDialog.resetDependencies()
super.tearDown()
}
func testShowDialogWithInvalidContent() {
content = SwitchContextContent(contextID: "")
dialog = SwitchContextDialog(content: content, windowFinder: windowFinder, delegate: self)
_ = dialog.show()
XCTAssertNotNil(dialog)
XCTAssertNotNil(dialogError)
XCTAssertNil(dialog.currentWebDialog)
}
func testShowingDialogWithInvalidContentType() throws {
let invalidContent = ChooseContextContent()
dialog = SwitchContextDialog(content: content, windowFinder: windowFinder, delegate: self)
dialog.dialogContent = invalidContent
_ = dialog.show()
XCTAssertNotNil(dialog)
let error = try XCTUnwrap(dialogError as? GamingServicesDialogError)
XCTAssertEqual(error, .invalidContentType)
XCTAssertNil(dialog.currentWebDialog)
}
func testShowDialogWithValidContent() {
_ = dialog.show()
XCTAssertNotNil(dialog)
XCTAssertNil(dialogError)
XCTAssertNotNil(dialog.currentWebDialog)
}
func testDialogCancelsWhenResultDoesNotContainContextID() {
_ = dialog.show()
guard let webDialogDelegate = dialog.currentWebDialog else {
return XCTFail("Web dialog should be a web dialog view delegate")
}
let results = ["foo": name]
webDialogDelegate.webDialogView(FBWebDialogView(), didCompleteWithResults: results)
XCTAssertNotNil(webDialogDelegate)
XCTAssertFalse(dialogDidCompleteSuccessfully)
XCTAssertTrue(dialogDidCancel)
XCTAssertNil(dialogError)
}
func testDialogSuccessfullyCreatesGamingContext() throws {
XCTAssertNil(GamingContext.current, "Should not have a context by default")
_ = dialog.show()
let webDialogDelegate = try XCTUnwrap(dialog.currentWebDialog)
let resultContextIDKey = "context_id"
let resultContextID = "1234"
let results = [resultContextIDKey: resultContextID]
webDialogDelegate.webDialogView(FBWebDialogView(), didCompleteWithResults: results)
XCTAssertEqual(
resultContextID,
GamingContext.current?.identifier,
"Should create a gaming context using the identifier from the web dialog result"
)
XCTAssertNotNil(webDialogDelegate)
XCTAssertNotNil(GamingContext.current?.identifier)
XCTAssertTrue(dialogDidCompleteSuccessfully)
XCTAssertFalse(dialogDidCancel)
XCTAssertNil(dialogError)
}
func testDialogSuccessfullyUpdatesGamingContext() throws {
GamingContext.current = GamingContext(identifier: "foo", size: 2)
_ = dialog.show()
let webDialogDelegate = try XCTUnwrap(dialog.currentWebDialog)
let resultContextIDKey = "context_id"
let resultContextID = "1234"
let results = [resultContextIDKey: resultContextID]
webDialogDelegate.webDialogView(FBWebDialogView(), didCompleteWithResults: results)
XCTAssertEqual(
resultContextID,
GamingContext.current?.identifier,
"Should update the current gaming context to use the identifer from the web dialog result"
)
XCTAssertNotNil(webDialogDelegate)
XCTAssertNotNil(GamingContext.current?.identifier)
XCTAssertTrue(dialogDidCompleteSuccessfully)
XCTAssertFalse(dialogDidCancel)
XCTAssertNil(dialogError)
}
func testDialogCompletesWithServerError() throws {
_ = dialog.show()
let webDialogDelegate = try XCTUnwrap(dialog.currentWebDialog)
let resultErrorCodeKey = "error_code"
let resultErrorCode = 1234
let resultErrorMessageKey = "error_message"
let resultErrorMessage = "Webview error"
let results = [resultErrorCodeKey: resultErrorCode, resultErrorMessageKey: resultErrorMessage] as [String: Any]
webDialogDelegate.webDialogView(FBWebDialogView(), didCompleteWithResults: results)
let error = try XCTUnwrap(dialogError)
XCTAssertNotNil(webDialogDelegate)
XCTAssertEqual(resultErrorCode, error.code)
XCTAssertEqual(resultErrorMessage, error.userInfo.values.first as? String)
XCTAssertFalse(dialogDidCompleteSuccessfully)
XCTAssertFalse(dialogDidCancel)
}
func testDialogCancels() throws {
_ = dialog.show()
let webDialogDelegate = try XCTUnwrap(dialog.currentWebDialog)
webDialogDelegate.webDialogViewDidCancel(FBWebDialogView())
XCTAssertNotNil(webDialogDelegate)
XCTAssertFalse(dialogDidCompleteSuccessfully)
XCTAssertTrue(dialogDidCancel)
XCTAssertNil(dialogError)
}
func testDialogFailsWithError() throws {
_ = dialog.show()
let webDialogDelegate = try XCTUnwrap(dialog.currentWebDialog)
let error = NSError(domain: "Test", code: 1, userInfo: nil)
webDialogDelegate.webDialogView(FBWebDialogView(), didFailWithError: error)
XCTAssertNotNil(webDialogDelegate)
XCTAssertFalse(dialogDidCompleteSuccessfully)
XCTAssertFalse(dialogDidCancel)
XCTAssertNotNil(dialogError)
}
// MARK: - Delegate Methods
func contextDialogDidComplete(_ contextDialog: ContextWebDialog) {
dialogDidCompleteSuccessfully = true
}
func contextDialog(_ contextDialog: ContextWebDialog, didFailWithError error: Error) {
dialogError = error as NSError
}
func contextDialogDidCancel(_ contextDialog: ContextWebDialog) {
dialogDidCancel = true
}
}
|
0 | //
// BeaconCollectionViewCell.swift
// RayBroadcast
//
// Created by Sean Ooi on 7/3/15.
// Copyright (c) 2015 Yella Inc. All rights reserved.
//
import UIKit
class BeaconCollectionViewCell: UICollectionViewCell {
@IBOutlet weak private var beaconImageView: UIImageView!
@IBOutlet weak private var majorLabel: UILabel!
@IBOutlet weak private var minorLabel: UILabel!
@IBOutlet weak private var regionLabel: UILabel!
@IBOutlet weak var majorValueLabel: UILabel!
@IBOutlet weak var minorValueLabel: UILabel!
@IBOutlet weak var regionValueLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor(red: 236/255, green: 240/255, blue: 241/255, alpha: 1.0)
beaconImageView.contentMode = .ScaleAspectFit
majorLabel.text = "Major:"
majorLabel.font = UIFont.boldSystemFontOfSize(16)
minorLabel.text = "Minor:"
minorLabel.font = UIFont.boldSystemFontOfSize(16)
regionLabel.text = "Region:"
regionLabel.font = UIFont.boldSystemFontOfSize(16)
}
override func layoutSubviews() {
super.layoutSubviews()
beaconImageView.image = UIImage(named: "Beacon")
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSize(width: 2, height: 2)
layer.shadowRadius = 3
layer.shadowOpacity = 0.6
layer.cornerRadius = 4
clipsToBounds = false
}
}
|
0 | // A playground demonstrating an image view that supports zooming.
// https://schiavo.me/2019/pinch-to-zoom-image-view/
// Copyright (c) 2019 Julian Schiavo. All rights reserved. Licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import PlaygroundSupport
class ImageZoomView: UIScrollView, UIScrollViewDelegate {
var imageView: UIImageView!
var gestureRecognizer: UITapGestureRecognizer!
convenience init(frame: CGRect, image: UIImage?) {
self.init(frame: frame)
var imageToUse: UIImage
if let image = image {
imageToUse = image
} else if let url = Bundle.main.url(forResource: "image", withExtension: "jpeg"),
let data = try? Data(contentsOf: url),
let fileImage = UIImage(data: data) {
imageToUse = fileImage
} else {
fatalError("No image was passed in and failed to find an image at the path.")
}
// Creates the image view and adds it as a subview to the scroll view
imageView = UIImageView(image: imageToUse)
imageView.frame = frame
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
setupScrollView(image: imageToUse)
setupGestureRecognizer()
}
// Sets the scroll view delegate and zoom scale limits.
// Change the `maximumZoomScale` to allow zooming more than 2x.
func setupScrollView(image: UIImage) {
delegate = self
minimumZoomScale = 1.0
maximumZoomScale = 2.0
}
// Sets up the gesture recognizer that receives double taps to auto-zoom
func setupGestureRecognizer() {
gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
gestureRecognizer.numberOfTapsRequired = 2
addGestureRecognizer(gestureRecognizer)
}
// Handles a double tap by either resetting the zoom or zooming to where was tapped
@IBAction func handleDoubleTap() {
if zoomScale == 1 {
zoom(to: zoomRectForScale(maximumZoomScale, center: gestureRecognizer.location(in: gestureRecognizer.view)), animated: true)
} else {
setZoomScale(1, animated: true)
}
}
// Calculates the zoom rectangle for the scale
func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
zoomRect.size.height = imageView.frame.size.height / scale
zoomRect.size.width = imageView.frame.size.width / scale
let newCenter = convert(center, from: imageView)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
// Tell the scroll view delegate which view to use for zooming and scrolling
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
// Create a ImageZoomView and present it in the live view
let imageView = ImageZoomView(frame: CGRect(x: 0, y: 0, width: 300, height: 300), image: nil)
imageView.layer.borderColor = UIColor.black.cgColor
imageView.layer.borderWidth = 5
PlaygroundPage.current.liveView = imageView
|
0 | import Alamofire
// Ensure that framework was correctly integrated by using public API:
let alamofireRequestType = Alamofire.Request.self
|
0 | import Foundation
/// This adapter connects to remote directly.
open class DirectAdapter: AdapterSocket {
/// If this is set to `false`, then the IP address will be resolved by system.
var resolveHost = false
/**
Connect to remote according to the `ConnectSession`.
- parameter session: The connect session.
*/
override open func openSocketWith(session: ConnectSession) {
super.openSocketWith(session: session)
guard !isCancelled else {
return
}
do {
try socket.connectTo(host: session.host, port: Int(session.port), enableTLS: false, tlsSettings: nil)
} catch let error {
observer?.signal(.errorOccured(error, on: self))
disconnect()
}
}
/**
The socket did connect to remote.
- parameter socket: The connected socket.
*/
override open func didConnectWith(socket: RawTCPSocketProtocol) {
super.didConnectWith(socket: socket)
observer?.signal(.readyForForward(self))
delegate?.didBecomeReadyToForwardWith(socket: self)
}
override open func didRead(data: Data, from rawSocket: RawTCPSocketProtocol) {
super.didRead(data: data, from: rawSocket)
delegate?.didRead(data: data, from: self)
}
override open func didWrite(data: Data?, by rawSocket: RawTCPSocketProtocol) {
super.didWrite(data: data, by: rawSocket)
delegate?.didWrite(data: data, by: self)
}
}
|
0 | //
extension UInt256: Comparable {
public static func <(lhs: UInt256, rhs: UInt256) -> Bool {
for i in 0..<4 {
if lhs[i] < rhs[i] {
return true
} else if lhs[i] > rhs[i] {
return false
}
}
return false
}
public static func >(lhs: UInt256, rhs: UInt256) -> Bool {
return rhs < lhs
}
public static func <=(lhs: UInt256, rhs: UInt256) -> Bool {
return lhs == rhs || lhs < rhs
}
public static func >=(lhs: UInt256, rhs: UInt256) -> Bool {
return lhs == rhs || lhs > rhs
}
}
|
0 | //
// UITableViewCell-Styling.swift
// Unwrap
//
// Created by Paul Hudson on 09/08/2018.
// Copyright © 2019 Hacking with Swift.
//
import UIKit
extension UITableViewCell: ReusableView {
/// Styles a table view cell as representing a correct answer.
func setCorrectAnswerStyle() {
backgroundColor = UIColor(bundleName: "ReviewCorrect")
multipleSelectionBackgroundView?.backgroundColor = backgroundColor
textLabel?.textColor = .white
detailTextLabel?.textColor = .white
// FIXME: iOS 12 used a clear color for the checkmark inside a selected table view cell, and the tint color affected the circle around the check. iOS 13 uses a white color for the checkmark, which means if we use pure white tint color the checkmark becomes invisible. Compromise: use a blended white, so the check still stands out, but the old behavior was nicer. Perhaps this will be fixed in the future.
tintColor = UIColor.white.withAlphaComponent(0.35)
}
/// Styles a table view cell as representing a wrong answer.
func setWrongAnswerStyle() {
backgroundColor = UIColor(bundleName: "ReviewWrong")
multipleSelectionBackgroundView?.backgroundColor = backgroundColor
textLabel?.textColor = .white
detailTextLabel?.textColor = .white
// FIXME: iOS 12 used a clear color for the checkmark inside a selected table view cell, and the tint color affected the circle around the check. iOS 13 uses a white color for the checkmark, which means if we use pure white tint color the checkmark becomes invisible. Compromise: use a blended white, so the check still stands out, but the old behavior was nicer. Perhaps this will be fixed in the future.
tintColor = UIColor.white.withAlphaComponent(0.35)
}
/// Styles a table view cell as representing an unknown answer.
func setUnknownAnswerStyle() {
if #available(iOS 13, *) {
backgroundColor = .systemBackground
} else {
backgroundColor = .white
}
multipleSelectionBackgroundView?.backgroundColor = backgroundColor
tintColor = nil
}
// we'll do some refactoring here so -> feedData(from: Reader), so that it accept any data;
func feedData(title: String?, detailText: String?, accessLabel: String?, accessId: String? = nil) {
self.textLabel?.text = title
self.detailTextLabel?.text = detailText
self.accessibilityLabel = accessLabel
if let accessId = accessId {
self.accessibilityIdentifier = accessId
}
}
}
|
0 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Standards open source project
//
// Copyright (c) Stairtree GmbH
// Licensed under the MIT license
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: MIT
//
//===----------------------------------------------------------------------===//
import Foundation
/// Country according to ISO 3166-1
///
/// Source: Wikipedia
public struct ISOCountryInfo: Hashable, Equatable {
/// The official name as assigned by the United Nations
public let name: String
/// The ISO 3166-1 numeric code
public let numeric: String
/// The ISO 3166-1 alpha-2 code
public let alpha2: String
/// The ISO 3166-1 alpha-3 code
public let alpha3: String
/// The continent, the country is considered to be part of
///
/// - Note: Some countries span multiple continents (e.g. Turkey)
public let continents: Set<String>
/// The Unicode flag symbol for this country
public var flag: String {
ISOCountries.flag(countryCode: alpha2)
}
/// The country's name in the language of the given locale
/// - Parameter locale: The locale to provide the country's name. By default the system's current locale is used.
/// - Returns: The localized name of the country
public func localizedName(for locale: NSLocale = NSLocale.current as NSLocale) -> String? {
locale.displayName(forKey: .countryCode, value: alpha2)
}
}
extension ISOCountryInfo {
public var otherCurrencies: Set<ISOCurrencyInfo> {
Set(ISOCurrencies.all.filter { $0.used.contains(alpha3) })
}
public var continentInfo: Set<ContinentInfo> {
Set(continents.compactMap(ISOContinents.find(byCode:)))
}
}
|
0 | //
// MapViewController.swift
// TravelGuide
//
// Created by Anton Makarov on 31/03/2018.
// Copyright © 2018 Anton Makarov. All rights reserved.
//
import UIKit
import MapKit
import Kingfisher
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var cityNameLabel: UILabel!
let locationManager = CLLocationManager()
var sightViewModel: SightViewModel?
override func viewDidLoad() {
super.viewDidLoad()
cityNameLabel.text = CurrentUser.sharedInstance.city?.name
mapView.delegate = self
for place in (sightViewModel?.diplaySights)! {
let annotation = PinAnnotation()
annotation.coordinate = place.coordinate
annotation.title = place.name
annotation.image = UIImageView()
let url = URL(string: place.imagesURL.first!)
annotation.image!.kf.setImage(with: url)
mapView.addAnnotation(annotation)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: MKUserLocation.self) {
return nil
}
if !annotation.isKind(of: PinAnnotation.self) {
var pinAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "PinView")
if pinAnnotationView == nil {
pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "PinView")
}
return pinAnnotationView
}
var view: AnnotationImageView? = mapView.dequeueReusableAnnotationView(withIdentifier: "imageAnnotation") as? AnnotationImageView
if view == nil {
view = AnnotationImageView(annotation: annotation, reuseIdentifier: "imageAnnotation")
}
let annotation = annotation as! PinAnnotation
view?.image = annotation.image?.image
view?.annotation = annotation
//view?.canShowCallout = true
return view
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
}
@IBAction func closeView(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
}
|
0 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "EDSunriseSet",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "EDSunriseSet",
targets: ["EDSunriseSet"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "EDSunriseSet",
dependencies: [],
path: ".",
publicHeadersPath: "Sources/EDSunriseSet"),
]
)
|
0 | // Copyright © 2019 Brad Howes. All rights reserved.
import Foundation
import UIKit
/// The collection of event types that can be targeted in the `InfoBarManager.addTarget` method
public enum InfoBarEvent {
/// Move the keyboard up in scale so that the new first key value is the key after the current highest key
case shiftKeyboardUp
/// Move the keyboard down in scale so that the new last key value is the key before the current lowest key
case shiftKeyboardDown
/// Add a new sound font file to the collection of known files
case addSoundFont
/// Edit the collection of sound fonts
case editSoundFonts
/// User performed a double-tap action on the info bar. Switch between favorites view and file/preset view
case doubleTap
/// Show the guide overlay
case showGuide
/// Show/hide the settings panel
case showSettings
/// Enter edit mode to change individual preset visibility settings
case editVisibility
/// Show/hide the effects panel
case showEffects
/// Show/hide the tags list
case showTags
/// Expose additional buttons on width-constrained devices
case showMoreButtons
/// Hide additional buttons on width-constrained devices
case hideMoreButtons
}
/// Handles the actions and display of items in a hypothetical info bar above the keyboard
public protocol AnyInfoBar: AnyObject {
/**
Link a button / gesture event to a target/selector combination
- parameter event: the event to link to
- parameter closure: the closure to invoke when the event appears
*/
func addEventClosure(_ event: InfoBarEvent, _ closure: @escaping UIControl.Closure)
/**
Show status information on the bar. This will appear temporarily and then fade back to the preset name.
- parameter value: the value to show
*/
func setStatusText(_ value: String)
/**
Set the lowest and highest note labels of the keyboard
- parameter from: the lowest note
- parameter to: the highest note
*/
func setVisibleKeyLabels(from: String, to: String)
/// True if there are more buttons to be seen
var moreButtonsVisible: Bool { get }
/// Show the remaining buttons
func showMoreButtons()
/// Hide the remaining buttons
func hideMoreButtons()
/**
Reset a button state for a given event. Some buttons show an 'active' state while another piece of UI is visible.
This provides a programatic way to reset the button to the 'inactive' state.
- parameter event: the event associated with the button to reset
*/
func resetButtonState(_ event: InfoBarEvent)
/**
Update the enabled state of info buttons depending on appearance of presets view.
- parameter visible: true if presets view is showin
*/
func updateButtonsForPresetsViewState(visible: Bool)
func updateTuningIndicator()
}
|
0 | //
// UiLabelPadding.swift
// client-mpp-ios
//
// Created by Simon Schubert on 11.05.19.
// Copyright © 2019 ktor. All rights reserved.
//
import Foundation
import UIKit
class UILabelPadding: UILabel {
let padding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
override var intrinsicContentSize : CGSize {
let superContentSize = super.intrinsicContentSize
let width = superContentSize.width + padding.left + padding.right
let heigth = superContentSize.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}
}
|
0 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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.
/// Represents a direct message channel with another user.
public struct DiscordDMChannel : DiscordChannel {
// MARK: Properties
/// The snowflake id of the channel.
public let id: String
/// Whether this channel is private. Should always be true for DMChannels
public let isPrivate = true
/// The user this channel is with.
public let recipient: DiscordUser
/// A DiscordDMChannel should always be a direct channel
public let type = DiscordChannelType.direct
/// Reference to the client.
public weak var client: DiscordClient?
/// The snowflake id of the last received message on this channel.
public var lastMessageId: String
init(dmObject: [String: Any]) {
recipient = DiscordUser(userObject: dmObject.get("recipient", or: [String: Any]()))
id = dmObject.get("id", or: "")
lastMessageId = dmObject.get("lastMessageId", or: "")
}
init(dmReadyObject: [String: Any], client: DiscordClient? = nil) {
recipient = DiscordUser(userObject: dmReadyObject.get("recipients", or: [[String: Any]]())[0])
id = dmReadyObject.get("id", or: "")
lastMessageId = dmReadyObject.get("lastMessageId", or: "")
self.client = client
}
static func DMsfromArray(_ dmArray: [[String: Any]]) -> [String: DiscordDMChannel] {
var dms = [String: DiscordDMChannel]()
for dm in dmArray {
let dmChannel = DiscordDMChannel(dmObject: dm)
dms[dmChannel.id] = dmChannel
}
return dms
}
}
/// Represents a direct message channel with a group of users.
public struct DiscordGroupDMChannel : DiscordChannel {
// MARK: Properties
/// The snowflake id of the channel.
public let id: String
/// Whether this channel is private. Should always be true for DMChannels
public let isPrivate = true
/// The users in this channel.
public let recipients: [DiscordUser]
/// A DiscordGroupDMChannel should always be a direct channel
public let type = DiscordChannelType.groupDM
/// Reference to the client.
public weak var client: DiscordClient?
/// The snowflake id of the last received message on this channel.
public var lastMessageId: String
/// The name of this group dm.
public var name: String?
init(dmReadyObject: [String: Any], client: DiscordClient? = nil) {
recipients = dmReadyObject.get("recipients", or: [[String: Any]]()).map(DiscordUser.init)
id = dmReadyObject.get("id", or: "")
lastMessageId = dmReadyObject.get("lastMessageId", or: "")
name = dmReadyObject["name"] as? String
self.client = client
}
}
|
0 | //
// FeedCell.swift
// YouTube
//
// Created by GA GA on 2018/10/25.
// Copyright © 2018 GA GA. All rights reserved.
//
import UIKit
class FeedCell: BaseCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .white
cv.delegate = self
cv.dataSource = self
return cv
}()
var videos: [Video]?
let cellId = "cellId"
func fetchVideos() {
ApiService.shareInstance.fetchVideos { videos in
self.videos = videos
self.collectionView.reloadData()
}
}
override func setupViews() {
super.setupViews()
fetchVideos()
backgroundColor = .blue
addSubview(collectionView)
addConstraintWithFormat(format: "H:|[v0]|", views: collectionView)
addConstraintWithFormat(format: "V:|[v0]|", views: collectionView)
collectionView.register(VideoCell.self, forCellWithReuseIdentifier: cellId)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = videos?.count {
return count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! VideoCell
cell.video = videos?[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = (frame.width - 16 - 16) * 9 / 16
return CGSize(width: frame.width, height: height + 16 + 86)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
|
0 | //
// File.swift
//
//
// Created by Nicolas Bush on 26/05/2020.
//
import Foundation
struct Languages {
var languages : [Language]
}
extension Languages : Codable { }
struct Language {
var name : String
var code : String
}
extension Language : Codable { }
|
0 | //
// MockTrack.swift
// Aural
//
// Copyright © 2022 Kartik Venugopal. All rights reserved.
//
// This software is licensed under the MIT software license.
// See the file "LICENSE" in the project root directory for license terms.
//
import Foundation
class MockTrack: Track {
init(_ file: URL) {
super.init(file)
}
}
extension Track: CustomStringConvertible {
var description: String {
self.displayName
}
}
|
0 | //
// OHHTTPStubsResponse+Init.swift
// CleanArchitectureTests
//
// Created by Alberto on 21/03/2019.
// Copyright © 2019 Alberto. All rights reserved.
//
import Foundation
import OHHTTPStubs
extension OHHTTPStubsResponse {
static func _200(jsonFileName: String, inBundleForClass: AnyClass) throws -> OHHTTPStubsResponse {
guard let filePath = OHPathForFile(jsonFileName, inBundleForClass) else {
throw Error.fileNotFound
}
return OHHTTPStubsResponse(fileAtPath: filePath,
statusCode: 200,
headers: ["Content-Type":"application/json"])
}
static func _400() -> OHHTTPStubsResponse {
let BadRequest = NSError(domain: NSURLErrorDomain,
code: 400,
userInfo: ["NSLocalizedDescription": "Bad Request"])
return OHHTTPStubsResponse(error: BadRequest)
}
enum Error: Swift.Error {
case fileNotFound
}
}
|
0 | import Vapor
import Lingo
extension Droplet {
/// Convenience method for accessing Lingo object.
///
/// Note that accessing this property might crash the app if the LingoProvider is not added.
/// This tradeoff was done on purpose in order to gain a cleaner API (without optionals).
public var lingo: Lingo {
guard let lingo = self.storage["lingo"] as? Lingo else {
fatalError("Lingo is not initialized. Make sure you have registered the provider by doing: `config.addProvider(LingoProvider.Provider.self)`.")
}
return lingo
}
}
public struct Provider: Vapor.Provider {
public let lingo: Lingo
public static let repositoryName = "lingo-provider"
public init(config: Config) throws {
guard let lingo = config["lingo"] else {
throw ConfigError.missingFile("lingo")
}
// Check if `localizationsDir` is specified in the config,
// otherwise default to workDir/Localizations
let rootPath: String
if let localizationsDir = lingo["localizationsDir"]?.string {
rootPath = config.workDir.appending(localizationsDir)
} else {
rootPath = config.workDir.appending("Localizations")
}
/// Extract the default locale
guard let defaultLocale = lingo["defaultLocale"]?.string else {
throw ConfigError.missing(key: ["defaultLocale"], file: "lingo", desiredType: String.self)
}
self.lingo = try Lingo(rootPath: rootPath, defaultLocale: defaultLocale)
}
public func boot(_ droplet: Droplet) throws {
droplet.storage["lingo"] = self.lingo
}
public func boot(_ config: Config) throws { }
public func beforeRun(_ droplet: Droplet) throws { }
}
|
0 | // swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "XcodeConfig",
products: [
.library(name: "XcodeConfig", targets: ["XcodeConfig"])
],
targets: [
.target(name: "XcodeConfig"),
.testTarget(
name: "XcodeConfigTests",
dependencies: ["XcodeConfig"]
)
]
)
|
0 | //
// YNPDescriptor.swift
// YNBluetooth
//
// Created by yuyan7 on 2017/07/08.
// Copyright © 2017年 yuyan7. All rights reserved.
//
import CoreBluetooth
/// YNPDescriptor
public class YNPDescriptor {
/// Descriptor
public let descriptor: CBMutableDescriptor
/// Value
public var value: Any? {
return self.descriptor.value
}
/// Initialize
///
/// - Parameters:
/// - uuid: Descriptor's UUID
/// - value: Descriptor's value
public init(uuid: String, value: Any?) {
self.descriptor = CBMutableDescriptor(type: CBUUID(string: uuid),
value: value)
}
}
|
0 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
let afterGuessTimeout: TimeInterval = 2 // seconds
// border colors for image views
let successColor = UIColor(red: 80.0/255.0, green: 192.0/255.0, blue: 202.0/255.0, alpha: 1.0)
let failureColor = UIColor(red: 203.0/255.0, green: 85.0/255.0, blue: 89.0/255.0, alpha: 1.0)
let defaultColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1)
/** The Main View Controller for the Game */
class GameViewController: UIViewController {
let game = MatchingGame()
var circleRecognizer: CircleGestureRecognizer!
// The image views
fileprivate var imageViews = [UIImageView]()
@IBOutlet weak var image1: RoundedImageView!
@IBOutlet weak var image2: RoundedImageView!
@IBOutlet weak var image3: RoundedImageView!
@IBOutlet weak var image4: RoundedImageView!
// the game views
@IBOutlet weak var gameButton: UIButton!
@IBOutlet weak var circlerDrawer: CircleDrawView! // draws the user input
var goToNextTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// put the views in an array to help with game logic
imageViews = [image1, image2, image3, image4]
// create and add the circle recognizer here
circleRecognizer = CircleGestureRecognizer(target: self, action: #selector(self.circled))
view.addGestureRecognizer(circleRecognizer)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startNewSet(view) // start the game
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// clear any drawn circles when the view is rotated; this simplifies the drawing logic by not having to transform the coordinates and redraw the circle
circlerDrawer.clear()
}
// MARK: - Game stuff
// pick a new set of images, and reset the views
@IBAction func startNewSet(_ sender: AnyObject) {
goToNextTimer?.invalidate()
circlerDrawer.clear()
gameButton.setTitle("New Set!", for: UIControlState())
gameButton.setTitleColor(UIColor.white, for: UIControlState())
gameButton.backgroundColor = successColor
imageViews.map { $0.layer.borderColor = defaultColor.cgColor }
let images = game.getImages()
for (index, image) in images.enumerated() {
imageViews[index].image = image
}
}
func goToGameOver() {
performSegue(withIdentifier: "gameOver", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "gameOver" {
let gameOverViewController = segue.destination as! GameOverViewController
gameOverViewController.game = game
}
}
func selectImageViewAtIndex(_ guessIndex: Int) {
// a view was selected - find out if it was the right one show the appropriate view states
let selectedImageView = imageViews[guessIndex]
let (won, correct, gameover) = game.didUserWin(guessIndex)
if gameover {
goToGameOver()
return
}
let color: UIColor
let title: String
if won {
title = "Correct!"
color = successColor
} else {
title = "That wasn't it!"
color = failureColor
}
selectedImageView.layer.borderColor = color.cgColor
gameButton.setTitle(title, for: UIControlState())
gameButton.backgroundColor = UIColor.clear
gameButton.setTitleColor(color, for: UIControlState())
// stop any drawing and go to the next round after a timeout
goToNextTimer?.invalidate()
goToNextTimer = Timer.scheduledTimer(timeInterval: afterGuessTimeout, target: self, selector: #selector(GameViewController.startNewSet(_:)), userInfo: nil, repeats: false)
}
func findCircledView(_ center: CGPoint) {
// walk through the image views and see if the center of the drawn circle was over one of the views
for (index, view) in imageViews.enumerated() {
let windowRect = self.view.window?.convert(view.frame, from: view.superview)
if windowRect!.contains(center) {
print("Circled view # \(index)")
selectImageViewAtIndex(index)
}
}
}
// MARK: - Circle Stuff
func circled(gesture: CircleGestureRecognizer) {
switch gesture.state {
case .ended:
findCircledView(gesture.fitResult.center)
circlerDrawer.updateFit(gesture.fitResult, madeCircle: gesture.isCircle)
case .began:
circlerDrawer.clear()
case .changed:
circlerDrawer.updatePath(gesture.path)
case .failed:
circlerDrawer.updateFit(gesture.fitResult, madeCircle: gesture.isCircle)
case .cancelled:
circlerDrawer.updateFit(gesture.fitResult, madeCircle: gesture.isCircle)
default:
break
}
}
}
|
0 | import Foundation
import NIO
import NIOConcurrencyHelpers
/// Conforming to this protocol adds the ability to schedule tasks to be executed on a "fire and forget"
/// basis and at the same time ensure that only one task is executed at the same time. As a result, only
/// one thread will be accessing the underlying resources at the same time, which is useful for interacting
/// with constructs that are not thread-safe.
///
/// Alternatively to "fire-and-forget", the `ask` method can be used in order to interact with an actor and
/// get an eventual response wrapped in an `EventLoopFuture`
///
/// TODO right now working with this is clunky because the initialized actor doesn't know its own reference so implementations of this protocol have to cater for this in one way or another
/// TODO think of a (simple) mechanism by which to simplify the receive (the callback doesn't look all that nice)
protocol Actor {
associatedtype MessageType
associatedtype ResponseType
var el: EventLoop { get }
/// The entry point to implement in order to process messages
///
/// - Parameters:
/// - msg: the message to process
/// - callback: an optional callback passed by the caller to be invoked once processing is done.
/// Can be used both as a way to execute side-effecting code or to return a response
mutating func receive(_ msg: MessageType, _ callback: ((Result<ResponseType, Error>) ->())?)
/// Perform any startup tasks here, including storing the ActorRef if needed
///
/// - Parameter ref: the ActorRef of this actor
/// TODO it would be nice if we didn't have to do this explicitly, but I don't see how.
func start(ref: ActorRef<Self>) throws
/// Perform any shutdown tasks here
func stop(el: EventLoop) -> EventLoopFuture<Void>
}
class ActorRef<A: Actor> {
private var actor: A
private let dispatchQueue: DispatchQueue
private let isStopping: NIOAtomic = NIOAtomic.makeAtomic(value: false)
init(for actor: A) {
self.actor = actor
self.dispatchQueue = DispatchQueue(label: String(describing: actor.self))
}
/// Handle a message in a fire-and-forget fashion
func tell(_ msg: A.MessageType) {
if (!isStopping.load()) {
dispatchQueue.async {
self.actor.receive(msg, nil)
}
}
}
/// Handle a message that expects to return a response at some point
func ask(_ msg: A.MessageType) -> EventLoopFuture<A.ResponseType> {
let promise = actor.el.makePromise(of: A.ResponseType.self)
if (!isStopping.load()) {
let callback = { (result: Result<A.ResponseType, Error>) in
switch result {
case .success(let value):
promise.succeed(value)
case .failure(let error):
promise.fail(error)
}
}
dispatchQueue.async {
self.actor.receive(msg, callback)
}
return promise.futureResult
} else {
promise.fail(ActorError.stopping)
return promise.futureResult
}
}
/// Starts the actor
func start() throws {
try actor.start(ref: self)
}
/// Stops the actor
func stop(el: EventLoop) -> EventLoopFuture<Void> {
isStopping.store(true)
return self.actor.stop(el: el)
}
}
class ActorRefProvider {
private let group: MultiThreadedEventLoopGroup
init(group: MultiThreadedEventLoopGroup) {
self.group = group
}
// TODO try to make this into a builder
func actorFor<A>(_ creator: (EventLoop) throws -> A) rethrows -> ActorRef<A> where A: Actor {
ActorRef(for: try creator(group.next()))
}
}
enum ActorError: Error, Equatable {
case stopping
}
|
0 | //
// SelectionViewTests.swift
// SelectionViewTests
//
// Created by Srujan Simha Adicharla on 7/29/20.
// Copyright © 2020 Srujan Simha Adicharla. All rights reserved.
//
import XCTest
@testable import SASelectionView
class SelectionViewTests: XCTestCase {
var selectionView: SASelectionView!
override func setUp() {
selectionView = SASelectionView()
}
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.
measure {
// Put the code you want to measure the time of here.
}
}
}
|
0 | //
// BoardInteractor.swift
// tictactoe-ios
//
// Created by F K on 08/02/2022.
//
class BoardInteractor: BaseInteractor {
private let board: Board
var cells: [Cell] {
return board.cells
}
init(_ board: Board) {
self.board = board
}
}
extension BoardInteractor {
func getCell(at position: Int) -> Cell {
return board.getCell(at: position)
}
private func isCellEmpty(at position: Int) -> Bool {
return board.isCellEmpty(at: position)
}
}
|
0 | //
// uploadResultViewController.swift
// HealthyLife
//
// Created by admin on 8/18/16.
// Copyright © 2016 NHD Group. All rights reserved.
//
import UIKit
import MobileCoreServices
import Firebase
class uploadResultViewController: uploadFoodViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Upload Result"
desTextField.placeholder = "Current Weight"
desTextField.keyboardType = .DecimalPad
}
override func updateImage(image: UIImage, text: String) {
let ref = FIRDatabase.database().reference()
let currentUserID = DataService.currentUserID
showLoading()
let key = ref.child("users").child(currentUserID!).child("results_journal").childByAutoId().key
let newPost: Dictionary<String, AnyObject> = [
"ImageUrl": key,
"CurrentWeight": desTextField.text!,
"Love": 0,
"time": FIRServerValue.timestamp()
]
ref.child("users").child(currentUserID!).child("results_journal").child(key).setValue(newPost)
DataService.uploadImage(image, key: key, complete: { (downloadURL) in
self.onBack()
self.hideLoading()
}) { (error) in
Helper.showAlert("Error", message: error.localizedDescription, inViewController: self)
self.hideLoading()
}
}
}
|
0 | //
// RealmSwiftServiceTests.swift
// RealmSwiftServiceTests
//
// Created by Tsubasa Hayashi on 2018/11/05.
// Copyright © 2018 Tsubasa Hayashi. All rights reserved.
//
import XCTest
@testable import RealmSwiftService
class RealmSwiftServiceTests: 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 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.
}
}
}
|
0 | //
// ViewController.swift
// Example
//
// Created by Rui Peres on 05/12/2015.
// Copyright © 2015 MailOnline. All rights reserved.
//
import UIKit
extension UIImageView: DisplaceableView {}
struct DataItem {
let imageView: UIImageView
let galleryItem: GalleryItem
}
class ViewController: UIViewController {
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
@IBOutlet weak var image3: UIImageView!
@IBOutlet weak var image4: UIImageView!
@IBOutlet weak var image5: UIImageView!
@IBOutlet weak var image6: UIImageView!
@IBOutlet weak var image7: UIImageView!
var items: [DataItem] = []
override func viewDidLoad() {
super.viewDidLoad()
let imageViews = [image1, image2, image3, image4, image5, image6, image7]
for (index, imageView) in imageViews.enumerated() {
guard let imageView = imageView else { continue }
var galleryItem: GalleryItem!
switch index {
case 2:
galleryItem = GalleryItem.video(
identifier: nil,
fetchPreviewImageBlock: { _, completion in completion(UIImage(named: "2")!) },
videoURL: URL(string: "http://video.dailymail.co.uk/video/mol/test/2016/09/21/5739239377694275356/1024x576_MP4_5739239377694275356.mp4")!
)
case 4:
let myFetchImageBlock: FetchImageBlock = { _, completion in completion(imageView.image!) }
let itemViewControllerBlock: ItemViewControllerBlock = { index, itemCount, fetchImageBlock, configuration, isInitialController in
return AnimatedViewController(index: index, itemCount: itemCount, fetchImageBlock: myFetchImageBlock, configuration: configuration, isInitialController: isInitialController)
}
galleryItem = GalleryItem.custom(
identifier: nil,
fetchImageBlock: myFetchImageBlock,
itemViewControllerBlock: itemViewControllerBlock
)
default:
let image = imageView.image ?? UIImage(named: "0")!
galleryItem = GalleryItem.image(
identifier: nil,
fetchImageBlock: { _, completion in completion(image) }
)
}
items.append(DataItem(imageView: imageView, galleryItem: galleryItem))
}
}
@IBAction func showGalleryImageViewer(_ sender: UITapGestureRecognizer) {
guard let displacedView = sender.view as? UIImageView else { return }
guard let displacedViewIndex = items.index(where: { $0.imageView == displacedView }) else { return }
let frame = CGRect(x: 0, y: 0, width: 200, height: 24)
let headerView = CounterView(frame: frame, currentIndex: displacedViewIndex, count: items.count)
let footerView = CounterView(frame: frame, currentIndex: displacedViewIndex, count: items.count)
let galleryViewController = GalleryViewController(startIndex: displacedViewIndex, itemsDataSource: self, itemsDelegate: self, displacedViewsDataSource: self, configuration: galleryConfiguration())
galleryViewController.headerView = headerView
galleryViewController.footerView = footerView
galleryViewController.launchedCompletion = { print("LAUNCHED") }
galleryViewController.closedCompletion = { print("CLOSED") }
galleryViewController.swipedToDismissCompletion = { print("SWIPE-DISMISSED") }
galleryViewController.landedPageAtIndexCompletion = { index in
print("LANDED AT INDEX: \(index)")
headerView.count = self.items.count
headerView.currentIndex = index
footerView.count = self.items.count
footerView.currentIndex = index
}
self.presentImageGallery(galleryViewController)
}
func galleryConfiguration() -> GalleryConfiguration {
return [
GalleryConfigurationItem.closeButtonMode(.builtIn),
GalleryConfigurationItem.pagingMode(.standard),
GalleryConfigurationItem.presentationStyle(.displacement),
GalleryConfigurationItem.hideDecorationViewsOnLaunch(false),
GalleryConfigurationItem.swipeToDismissMode(.vertical),
GalleryConfigurationItem.toggleDecorationViewsBySingleTap(false),
GalleryConfigurationItem.activityViewByLongPress(false),
GalleryConfigurationItem.overlayColor(UIColor(white: 0.035, alpha: 1)),
GalleryConfigurationItem.overlayColorOpacity(1),
GalleryConfigurationItem.overlayBlurOpacity(1),
GalleryConfigurationItem.overlayBlurStyle(UIBlurEffect.Style.light),
GalleryConfigurationItem.videoControlsColor(.white),
GalleryConfigurationItem.maximumZoomScale(8),
GalleryConfigurationItem.swipeToDismissThresholdVelocity(500),
GalleryConfigurationItem.doubleTapToZoomDuration(0.15),
GalleryConfigurationItem.blurPresentDuration(0.5),
GalleryConfigurationItem.blurPresentDelay(0),
GalleryConfigurationItem.colorPresentDuration(0.25),
GalleryConfigurationItem.colorPresentDelay(0),
GalleryConfigurationItem.blurDismissDuration(0.1),
GalleryConfigurationItem.blurDismissDelay(0.4),
GalleryConfigurationItem.colorDismissDuration(0.45),
GalleryConfigurationItem.colorDismissDelay(0),
GalleryConfigurationItem.itemFadeDuration(0.3),
GalleryConfigurationItem.decorationViewsFadeDuration(0.15),
GalleryConfigurationItem.rotationDuration(0.15),
GalleryConfigurationItem.displacementDuration(0.55),
GalleryConfigurationItem.reverseDisplacementDuration(0.25),
GalleryConfigurationItem.displacementTransitionStyle(.springBounce(0.7)),
GalleryConfigurationItem.displacementTimingCurve(.linear),
GalleryConfigurationItem.statusBarHidden(true),
GalleryConfigurationItem.displacementKeepOriginalInPlace(false),
GalleryConfigurationItem.displacementInsetMargin(50)
]
}
}
extension ViewController: GalleryDisplacedViewsDataSource {
func provideDisplacementItem(atIndex index: Int) -> DisplaceableView? {
return index < items.count ? items[index].imageView : nil
}
}
extension ViewController: GalleryItemsDataSource {
func itemCount() -> Int {
return items.count
}
func provideGalleryItem(_ index: Int) -> GalleryItem {
return items[index].galleryItem
}
}
extension ViewController: GalleryItemsDelegate {
func removeGalleryItem(at index: Int) {
print("remove item at \(index)")
let imageView = items[index].imageView
imageView.removeFromSuperview()
items.remove(at: index)
}
}
// Some external custom UIImageView we want to show in the gallery
class FLSomeAnimatedImage: UIImageView {
}
// Extend ImageBaseController so we get all the functionality for free
class AnimatedViewController: ItemBaseController<FLSomeAnimatedImage> {
}
|
0 | //
// TrialButtonViewController.swift
// FocusPlan
//
// Created by Vojtech Rinik on 5/24/17.
// Copyright © 2017 Median. All rights reserved.
//
import Cocoa
import ReactiveSwift
import ReactiveCocoa
import SwiftDate
class TrialButtonViewController: NSTitlebarAccessoryViewController {
@IBOutlet weak var label: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
guard let app = AppDelegate.instance else { return }
label.reactive.stringValue <~ app.expirationDate.map { date in
guard let date = date else { return "" }
let diff = date.startOf(component: .day) - Date().startOf(component: .day)
var days = Int(diff / (3600 * 24))
if days < 0 {
days = 0
}
return "Trial expires in \(days) days"
}
}
@IBAction func openAppStore(_ sender: Any) {
guard let app = AppDelegate.instance else { return }
app.openAppStore(event: "buy-button")
}
}
|
0 | //
// ContentInsetsController.swift
// edX
//
// Created by Akiva Leffert on 5/18/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public protocol ContentInsetsSourceDelegate : class {
func contentInsetsSourceChanged(_ source : ContentInsetsSource)
}
public protocol ContentInsetsSource : class {
var currentInsets : UIEdgeInsets { get }
weak var insetsDelegate : ContentInsetsSourceDelegate? { get set }
var affectsScrollIndicators : Bool { get }
}
open class ConstantInsetsSource : ContentInsetsSource {
open var currentInsets : UIEdgeInsets {
didSet {
self.insetsDelegate?.contentInsetsSourceChanged(self)
}
}
open let affectsScrollIndicators : Bool
open weak var insetsDelegate : ContentInsetsSourceDelegate?
public init(insets : UIEdgeInsets, affectsScrollIndicators : Bool) {
self.currentInsets = insets
self.affectsScrollIndicators = affectsScrollIndicators
}
}
/// General solution to the problem of edge insets that can change and need to
/// match a scroll view. When we drop iOS 7 support there may be a way to simplify this
/// by using the new layout margins API.
///
/// Other things like pull to refresh can be supported by creating a class that implements `ContentInsetsSource`
/// and providing a way to add it to the `insetsSources` list.
///
/// To use:
/// #. Call `setupInController:scrollView:` in the `viewDidLoad` method of your controller
/// #. Call `updateInsets` in the `viewDidLayoutSubviews` method of your controller
open class ContentInsetsController: NSObject, ContentInsetsSourceDelegate {
fileprivate var scrollView : UIScrollView?
fileprivate weak var owner : UIViewController?
fileprivate var insetSources : [ContentInsetsSource] = []
// Keyboard is separated out since it isn't a simple sum, but instead overrides other
// insets when present
fileprivate var keyboardSource : ContentInsetsSource?
open func setupInController(_ owner : UIViewController, scrollView : UIScrollView) {
self.owner = owner
self.scrollView = scrollView
keyboardSource = KeyboardInsetsSource(scrollView: scrollView)
keyboardSource?.insetsDelegate = self
}
fileprivate var controllerInsets : UIEdgeInsets {
let topGuideHeight = self.owner?.topLayoutGuide.length ?? 0
let bottomGuideHeight = self.owner?.bottomLayoutGuide.length ?? 0
return UIEdgeInsets(top : topGuideHeight, left : 0, bottom : bottomGuideHeight, right : 0)
}
open func contentInsetsSourceChanged(_ source: ContentInsetsSource) {
updateInsets()
}
open func addSource(_ source : ContentInsetsSource) {
source.insetsDelegate = self
insetSources.append(source)
updateInsets()
}
open func updateInsets() {
var regularInsets = insetSources
.map { $0.currentInsets }
.reduce(controllerInsets, +)
let indicatorSources = insetSources
.filter { $0.affectsScrollIndicators }
.map { $0.currentInsets }
var indicatorInsets = indicatorSources.reduce(controllerInsets, +)
if let keyboardHeight = keyboardSource?.currentInsets.bottom {
regularInsets.bottom = max(keyboardHeight, regularInsets.bottom)
indicatorInsets.bottom = max(keyboardHeight, indicatorInsets.bottom)
}
self.scrollView?.contentInset = regularInsets
self.scrollView?.scrollIndicatorInsets = indicatorInsets
}
}
|
0 | //
// AppData.swift
// tealium-swift
//
// Copyright © 2019 Tealium. All rights reserved.
//
import Foundation
struct AppData: Codable {
var name: String?,
rdns: String?,
version: String?,
build: String?,
persistentData: PersistentAppData?
public var dictionary: [String: Any] {
var allData = [String: Any]()
if let persistentData = persistentData {
allData += persistentData.dictionary
}
if let name = name {
allData[TealiumKey.appName] = name
}
if let rdns = rdns {
allData[TealiumKey.appRDNS] = rdns
}
if let version = version {
allData[TealiumKey.appVersion] = version
}
if let build = build {
allData[TealiumKey.appBuild] = build
}
return allData
}
mutating func removeAll() {
persistentData = nil
name = nil
version = nil
rdns = nil
build = nil
}
var count: Int {
return self.dictionary.count
}
}
|
0 | //
// Coordinator.swift
// GoogleMapDirectionLib
//
// Created by TriNgo on 5/12/20.
// Copyright © 2020 RoverDream. All rights reserved.
//
import Foundation
import ObjectMapper
public struct Coordination: Mappable {
public private(set) var latitude: Double = 0.0
public private(set) var longitude: Double = 0.0
init() { }
public init?(map: Map) { }
public mutating func mapping(map: Map) {
latitude <- map[CoordinationKey.lat]
longitude <- map[CoordinationKey.lng]
}
}
fileprivate struct CoordinationKey {
static let lat = "lat"
static let lng = "lng"
}
|
0 | import MongoSwiftSync
import Nimble
import TestsCommon
import XCTest
let center = NotificationCenter.default
final class CommandMonitoringTests: MongoSwiftTestCase {
override func setUp() {
self.continueAfterFailure = false
}
func testCommandMonitoring() throws {
guard MongoSwiftTestCase.topologyType != .sharded else {
print(unsupportedTopologyMessage(testName: self.name))
return
}
let client = try MongoClient.makeTestClient()
let monitor = client.addCommandMonitor()
let tests = try retrieveSpecTestFiles(specName: "command-monitoring", asType: CMTestFile.self)
for (filename, testFile) in tests {
// read in the file data and parse into a struct
let name = filename.components(separatedBy: ".")[0]
// TODO: SWIFT-346: remove this skip
if name.lowercased().contains("bulkwrite") { continue }
// remove this when command.json is updated with the new count API (see SPEC-1272)
if name.lowercased() == "command" { continue }
print("-----------------------")
print("Executing tests for file \(name)...\n")
// execute the tests for this file
for var test in testFile.tests {
if try !client.serverVersionIsInRange(test.minServerVersion, test.maxServerVersion) {
print("Skipping test case \(test.description) for server version \(try client.serverVersion())")
continue
}
if test.description == "A successful find event with a getmore and the server kills the cursor" {
print("Skipping test case \(test.description), see SWIFT-1228")
continue
}
print("Test case: \(test.description)")
// Setup the specified DB and collection with provided data
let db = client.db(testFile.databaseName)
try db.drop() // In case last test run failed, drop to clear out DB
let collection = try db.createCollection(testFile.collectionName)
try collection.insertMany(testFile.data)
try monitor.captureEvents {
try test.doOperation(withCollection: collection)
}
let receivedEvents = monitor.events()
expect(receivedEvents).to(haveCount(test.expectations.count))
for (receivedEvent, expectedEvent) in zip(receivedEvents, test.expectations) {
expectedEvent.compare(to: receivedEvent, testContext: &test.context)
}
try db.drop()
}
}
}
}
/// A struct to hold the data for a single file, containing one or more tests.
private struct CMTestFile: Decodable {
let data: [BSONDocument]
let collectionName: String
let databaseName: String
let tests: [CMTest]
let namespace: String?
enum CodingKeys: String, CodingKey {
case data, collectionName = "collection_name",
databaseName = "database_name", tests, namespace
}
}
/// A struct to hold the data for a single test from a CMTestFile.
private struct CMTest: Decodable {
struct Operation: Decodable {
let name: String
let args: BSONDocument
let readPreference: ReadPreference?
enum CodingKeys: String, CodingKey {
case name, args = "arguments", readPreference = "read_preference"
}
}
let op: Operation
let description: String
let expectationDocs: [BSONDocument]
let minServerVersion: String?
let maxServerVersion: String?
// Some tests contain cursors/getMores and we need to verify that the
// IDs are consistent across sinlge operations. we store that data in this
// `context` dictionary so we can access it in future events for the same test
var context = [String: Any]()
var expectations: [ExpectationType] { try! self.expectationDocs.map { try makeExpectation($0) } }
enum CodingKeys: String, CodingKey {
case description, op = "operation", expectationDocs = "expectations",
minServerVersion = "ignore_if_server_version_less_than",
maxServerVersion = "ignore_if_server_version_greater_than"
}
// Given a collection, perform the operation specified for this test on it.
// try? each operation because we expect some of them to fail.
// If something fails/succeeds incorrectly, we'll know because the generated
// events won't match up.
// swiftlint:disable cyclomatic_complexity
func doOperation(withCollection collection: MongoCollection<BSONDocument>) throws {
let filter: BSONDocument = self.op.args["filter"]?.documentValue ?? [:]
switch self.op.name {
case "count":
let options = CountDocumentsOptions(readPreference: self.op.readPreference)
_ = try? collection.countDocuments(filter, options: options)
case "deleteMany":
_ = try? collection.deleteMany(filter)
case "deleteOne":
_ = try? collection.deleteOne(filter)
case "find":
let modifiers = self.op.args["modifiers"]?.documentValue
var hint: IndexHint?
if let hintDoc = modifiers?["$hint"]?.documentValue {
hint = .indexSpec(hintDoc)
}
let options = FindOptions(
batchSize: self.op.args["batchSize"]?.toInt(),
comment: modifiers?["$comment"]?.stringValue,
hint: hint,
limit: self.op.args["limit"]?.toInt(),
max: modifiers?["$max"]?.documentValue,
maxTimeMS: modifiers?["$maxTimeMS"]?.toInt(),
min: modifiers?["$min"]?.documentValue,
readPreference: self.op.readPreference,
returnKey: modifiers?["$returnKey"]?.boolValue,
showRecordID: modifiers?["$showDiskLoc"]?.boolValue,
skip: self.op.args["skip"]?.toInt(),
sort: self.op.args["sort"]?.documentValue
)
do {
let cursor = try collection.find(filter, options: options)
for _ in cursor {}
} catch {}
case "insertMany":
let documents = (self.op.args["documents"]?.arrayValue?.compactMap { $0.documentValue })!
let options = InsertManyOptions(ordered: self.op.args["ordered"]?.boolValue)
_ = try? collection.insertMany(documents, options: options)
case "insertOne":
let document = self.op.args["document"]!.documentValue!
_ = try? collection.insertOne(document)
case "updateMany":
let update = self.op.args["update"]!.documentValue!
_ = try? collection.updateMany(filter: filter, update: update)
case "updateOne":
let update = self.op.args["update"]!.documentValue!
let options = UpdateOptions(upsert: self.op.args["upsert"]?.boolValue)
_ = try? collection.updateOne(filter: filter, update: update, options: options)
default:
XCTFail("Unrecognized operation name \(self.op.name)")
}
}
// swiftlint:enable cyclomatic_complexity
}
/// A protocol for the different types of expected events to implement
private protocol ExpectationType {
/// Compare this expectation's data to that in a `CommandEvent`, possibly
/// using/adding to the provided test context
func compare(to receivedEvent: CommandEvent, testContext: inout [String: Any])
}
/// Based on the name of the expectation, generate a corresponding
/// `ExpectationType` to be compared to incoming events
private func makeExpectation(_ document: BSONDocument) throws -> ExpectationType {
let decoder = BSONDecoder()
if let doc = document["command_started_event"]?.documentValue {
return try decoder.decode(CommandStartedExpectation.self, from: doc)
}
if let doc = document["command_succeeded_event"]?.documentValue {
return try decoder.decode(CommandSucceededExpectation.self, from: doc)
}
if let doc = document["command_failed_event"]?.documentValue {
return try decoder.decode(CommandFailedExpectation.self, from: doc)
}
throw TestError(message: "Unknown expectation type in document \(document)")
}
/// An expectation for a `CommandStartedEvent`
private struct CommandStartedExpectation: ExpectationType, Decodable {
var command: BSONDocument
let commandName: String
let databaseName: String
enum CodingKeys: String, CodingKey {
case command,
commandName = "command_name",
databaseName = "database_name"
}
func compare(to receivedEvent: CommandEvent, testContext: inout [String: Any]) {
guard let event = receivedEvent.commandStartedValue else {
XCTFail("Notification \(receivedEvent) did not contain a CommandStartedEvent")
return
}
// compare the command and DB names
expect(event.commandName).to(equal(self.commandName))
expect(event.databaseName).to(equal(self.databaseName))
// if it's a getMore, we can't directly compare the results
if self.commandName == "getMore" {
// verify that the getMore ID matches the stored cursor ID for this test
expect(event.command["getMore"]).to(equal(testContext["cursorId"] as? BSON))
// compare collection and batchSize fields
expect(event.command["collection"]).to(equal(self.command["collection"]))
expect(event.command["batchSize"]).to(equal(self.command["batchSize"]))
} else {
// remove fields from the command we received that are not in the expected
// command, and reorder them, so we can do a direct comparison of the documents
let normalizedSelf = normalizeCommand(self.command)
let receivedCommand = rearrangeDoc(event.command, toLookLike: normalizedSelf)
expect(receivedCommand).to(equal(normalizedSelf))
}
}
}
private func normalizeCommand(_ input: BSONDocument) -> BSONDocument {
var output = BSONDocument()
for (k, v) in input {
// temporary fix pending resolution of SPEC-1049. removes the field
// from the expected command unless if it is set to true, because none of the
// tests explicitly provide upsert: false or multi: false, yet they
// are in the expected commands anyway.
if ["upsert", "multi"].contains(k), let bV = v.boolValue {
if bV { output[k] = true } else { continue }
// The tests don't explicitly store maxTimeMS as an Int64, so libmongoc
// parses it as an Int32 which we convert to Int. convert to Int64 here because we
// (as per the crud spec) use an Int64 for maxTimeMS and send that to
// the server in our actual commands.
} else if k == "maxTimeMS", let iV = v.toInt64() {
output[k] = .int64(iV)
// recursively normalize if it's a document
} else if let docVal = v.documentValue {
output[k] = .document(normalizeCommand(docVal))
// recursively normalize each element if it's an array
} else if case let .array(arrVal) = v {
output[k] = .array(arrVal.map {
switch $0 {
case let .document(d):
return .document(normalizeCommand(d))
default:
return $0
}
})
// just copy the value over as is
} else {
output[k] = v
}
}
return output
}
private struct CommandFailedExpectation: ExpectationType, Decodable {
let commandName: String
enum CodingKeys: String, CodingKey {
case commandName = "command_name"
}
func compare(to receivedEvent: CommandEvent, testContext _: inout [String: Any]) {
guard let event = receivedEvent.commandFailedValue else {
XCTFail("Notification \(receivedEvent) did not contain a CommandFailedEvent")
return
}
/// The only info we get here is the command name so just compare those
expect(event.commandName).to(equal(self.commandName))
}
}
private struct CommandSucceededExpectation: ExpectationType, Decodable {
let originalReply: BSONDocument
let commandName: String
var reply: BSONDocument { normalizeExpectedReply(self.originalReply) }
var writeErrors: [BSONDocument]? { self.originalReply["writeErrors"]?.arrayValue?.compactMap { $0.documentValue } }
var cursor: BSONDocument? { self.originalReply["cursor"]?.documentValue }
enum CodingKeys: String, CodingKey {
case commandName = "command_name", originalReply = "reply"
}
func compare(to receivedEvent: CommandEvent, testContext: inout [String: Any]) {
guard let event = receivedEvent.commandSucceededValue else {
XCTFail("Notification \(receivedEvent) did not contain a CommandSucceededEvent")
return
}
// compare everything excluding writeErrors and cursor
let cleanedReply = rearrangeDoc(event.reply, toLookLike: self.reply)
expect(cleanedReply).to(equal(self.reply))
expect(event.commandName).to(equal(self.commandName))
// compare writeErrors, if any
let receivedWriteErrs = event.reply["writeErrors"]?.arrayValue?.compactMap { $0.documentValue }
if let expectedErrs = self.writeErrors {
expect(receivedWriteErrs).toNot(beNil())
self.checkWriteErrors(expected: expectedErrs, actual: receivedWriteErrs!)
} else {
expect(receivedWriteErrs).to(beNil())
}
let receivedCursor = event.reply["cursor"]?.documentValue
if let expectedCursor = self.cursor {
// if the received cursor has an ID, and the expected ID is not 0, compare cursor IDs
if let id = receivedCursor!["id"], expectedCursor["id"]?.toInt() != 0 {
let storedId = testContext["cursorId"] as? BSON
// if we aren't already storing a cursor ID for this test, add one
if storedId == nil {
testContext["cursorId"] = id
// otherwise, verify that this ID matches the stored one
} else {
expect(storedId).to(equal(id))
}
}
self.compareCursors(expected: expectedCursor, actual: receivedCursor!)
} else {
expect(receivedCursor).to(beNil())
}
}
/// Compare expected vs actual write errors.
func checkWriteErrors(expected: [BSONDocument], actual: [BSONDocument]) {
// The expected writeErrors has placeholder values,
// so just make sure the count is the same
expect(expected.count).to(equal(actual.count))
for err in actual {
// check each error code exists and is > 0
expect(err["code"]?.toInt()).to(beGreaterThan(0))
// check each error msg exists and has length > 0
expect(err["errmsg"]?.stringValue).toNot(beEmpty())
}
}
/// Compare expected vs actual cursor data, excluding the cursor ID
/// (handled in `compare` because we need the test context).
func compareCursors(expected: BSONDocument, actual: BSONDocument) {
let ordered = rearrangeDoc(actual, toLookLike: expected)
expect(ordered["ns"]).to(equal(expected["ns"]))
if let firstBatch = expected["firstBatch"] {
expect(ordered["firstBatch"]).to(equal(firstBatch))
} else if let nextBatch = expected["nextBatch"] {
expect(ordered["nextBatch"]).to(equal(nextBatch))
}
}
}
/// Clean up expected replies for easier comparison to received replies
private func normalizeExpectedReply(_ input: BSONDocument) -> BSONDocument {
var output = BSONDocument()
for (k, v) in input {
// These fields both have placeholder values in them,
// so we can't directly compare. Remove them from the expected
// reply so we can == the remaining fields and compare
// writeErrors and cursor separately.
if ["writeErrors", "cursor"].contains(k) {
continue
// The server sends back doubles, but the JSON test files
// contain integer statuses (see SPEC-1050.)
} else if k == "ok", let dV = v.toDouble() {
output[k] = .double(dV)
// just copy the value over as is
} else {
output[k] = v
}
}
return output
}
|
0 | import XCTest
@testable import SwiftCSPTests
XCTMain([
testCase(AustralianMapColoringTest.allTests),
testCase(EightQueensTest.allTests),
testCase(SendMoreMoneyTest.allTests),
testCase(SudokuTest.allTests),
])
|
0 | //
// ImageForApiResponseTests.swift
// TheUniverseTests
//
// Created by Ronaldo Gomes on 08/02/21.
// Copyright © 2021 Ronaldo Gomes. All rights reserved.
//
import UIKit
import XCTest
@testable import TheUniverse
class CelestialBodyImagesViewModelTests: XCTestCase {
let session = URLSessionMock()
// func test_imageForApi_indexForFetchImage_returnData() {
// //Given
// let sut = CelestialBodyImagesViewModel(celestialBodyName: "Terra")
//
// let path = createLocalUrl(forImageNamed: "Terra")
// session.testURLData = path
// sut.apiModel = ApiModel(session: session)
//
// let expect = expectation(description: "nasaApi")
//
// //When
// sut.imageForApi(index: 2) { image in
// XCTAssertNotNil(image)
// expect.fulfill()
// }
//
// wait(for: [expect], timeout: 5)
// }
// MARK: - Help Functions
func createLocalUrl(forImageNamed name: String) -> URL? {
let fileManager = FileManager.default
let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let url = cacheDirectory.appendingPathComponent("\(name).png")
guard fileManager.fileExists(atPath: url.path) else {
guard
let image = UIImage(named: name),
let data = image.jpegData(compressionQuality: 1.0)
else { return nil }
fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
return url
}
return url
}
}
|
0 | //
// AppDelegate.swift
// Myra
//
// Created by Amir Shayegh on 2018-02-13.
// Copyright © 2018 Government of British Columbia. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
import Fabric
import Crashlytics
import Realm
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var realmNotificationToken: NotificationToken?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
migrateRealm()
#if (arch(i386) || arch(x86_64)) && os(iOS) && DEBUG
// so we can find our Documents
print("documents = \(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!)")
#endif
// Remove dummy plan if exists
DummyData.removeDummyPlanAndAgreement()
// My way of making sure the settingsManager singleton exists before referenced elsewhere
print("Current Environment is \(SettingsManager.shared.getCurrentEnvironment())")
// Keyboard settings
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enableAutoToolbar = false
// Fabric
Fabric.with([Crashlytics.self])
// Begin Autosync change listener
AutoSync.shared.beginListener()
return true
}
/// https://realm.io/docs/swift/latest/#migrations
func migrateRealm() {
guard let generatedSchemaVersion = SettingsManager.generateAppIntegerVersion() else {
return
}
let config = Realm.Configuration(schemaVersion: UInt64(generatedSchemaVersion),
migrationBlock: { migration, oldSchemaVersion in
// check oldSchemaVersion here, if we're newer call
// a method(s) specifically designed to migrate to
// the desired schema. ie `self.migrateSchemaV0toV1(migration)`
if (oldSchemaVersion < 4) {
// Nothing to do. Realm will automatically remove and add fields
}
},
shouldCompactOnLaunch: { totalBytes, usedBytes in
// totalBytes refers to the size of the file on disk in bytes (data + free space)
// usedBytes refers to the number of bytes used by data in the file
// Compact if the file is over 100MB in size and less than 50% 'used'
let oneHundredMB = 100 * 1024 * 1024
return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
})
Realm.Configuration.defaultConfiguration = config
}
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.
AutoSync.shared.endListener()
}
func applicationWillEnterForeground(_ application: UIApplication) {
print(SettingsManager.shared.getCurrentEnvironment())
// 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.
AutoSync.shared.beginListener()
}
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:.
}
}
|
0 | //
// List.swift
// mas-cli
//
// Created by Andrew Naylor on 21/08/2015.
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
//
import Commandant
import Result
/// Command which lists all installed apps.
public struct ListCommand: CommandProtocol {
public typealias Options = NoOptions<MASError>
public let verb = "list"
public let function = "Lists apps from the Mac App Store which are currently installed"
private let appLibrary: AppLibrary
/// Designated initializer.
///
/// - Parameter appLibrary: AppLibrary manager.
public init(appLibrary: AppLibrary = MasAppLibrary()) {
self.appLibrary = appLibrary
}
/// Runs the command.
public func run(_: Options) -> Result<(), MASError> {
let products = appLibrary.installedApps
if products.isEmpty {
print("No installed apps found")
return .success(())
}
for product in products {
print("\(product.itemIdentifier) \(product.appName) (\(product.bundleVersion))")
}
return .success(())
}
}
|
0 | //
// InsetLabel.swift
// GDPC
//
// Created by Ben Shutt on 21/11/2019.
// Copyright © 2019 3 SIDED CUBE APP PRODUCTIONS LTD. All rights reserved.
//
import UIKit
open class InsetLabel: UILabel
{
public var insets = UIEdgeInsets.zero {
didSet {
invalidateIntrinsicContentSize()
}
}
/// Add `cornerRadius` according to the `min(bounds.size.width, bounds.size.height)`
public var roundCorners = true {
didSet {
setNeedsLayout()
}
}
// MARK: - View
override open func layoutSubviews() {
super.layoutSubviews()
preferredMaxLayoutWidth = frame.width - (insets.left + insets.right)
if roundCorners {
clipsToBounds = true
layer.cornerRadius = 0.5 * min(bounds.size.height, bounds.size.width)
}
}
override open func drawText(in rect: CGRect) {
let insetRect = rect.inset(by: insets)
super.drawText(in: insetRect)
}
override open var intrinsicContentSize: CGSize {
return addInsets(to: super.intrinsicContentSize)
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
return addInsets(to: super.sizeThatFits(size))
}
// MARK: - Inset
private func addInsets(to size: CGSize) -> CGSize {
let width = size.width + insets.left + insets.right
let height = size.height + insets.top + insets.bottom
return CGSize(width: width, height: height)
}
}
|
0 |
import Foundation
public class Circuit<ImpulseType: Impulse> { // Signal
private var etches = [Etch<ImpulseType>]()
private let impulseQueue: dispatch_queue_t = dispatch_queue_create("circuit_impulse_queue", DISPATCH_QUEUE_SERIAL)
private let defaultDispatchQueue: dispatch_queue_t = dispatch_queue_create("circuit_default_dispatch_queue", DISPATCH_QUEUE_CONCURRENT)
public init() { }
/// Add an etch to this circuit from any thread.
public func addEtch(etch: Etch<ImpulseType>) {
dispatch_async(impulseQueue) { _ in
self.etches.append(etch)
}
}
/// Send an impulse from any thread.
public func sendImpulse(impulse: ImpulseType) {
dispatch_async(impulseQueue) { _ in
self.recursiveSendImpulseToEtches(impulse, etches: self.etches)
}
}
private func sendImpulses(impulses: [ImpulseType]) {
for impulse in impulses {
self.sendImpulse(impulse)
}
}
private func removeDeadEtch(deadEtch: Etch<ImpulseType>) {
dispatch_async(impulseQueue) { _ in
if let index = self.etches.indexOf(deadEtch) {
self.etches.removeAtIndex(index)
}
}
}
private func recursiveSendImpulseToEtches(impulse: ImpulseType, etches: [Etch<ImpulseType>]) {
if (etches.count == 0) {
return
}
var remainingEtches = etches
let currentEtch = remainingEtches.removeFirst()
if (!currentEtch.alive()) {
self.removeDeadEtch(currentEtch)
recursiveSendImpulseToEtches(impulse, etches: remainingEtches)
return
}
// if let filter = currentEtch.filter {
// if !filter(impulse) {
// recursiveSendImpulseToEtches(impulse, etches: remainingEtches)
// return
// }
// }
var value: AnyObject!
if let unwrap = currentEtch.unwrap, unwrappedValue = unwrap(impulse) {
value = unwrappedValue
} else {
recursiveSendImpulseToEtches(impulse, etches: remainingEtches)
return
}
let queue = currentEtch.queue ?? self.defaultDispatchQueue
dispatch_async(queue) { _ in
if let impulses = currentEtch.dispatch(value) {
self.sendImpulses(impulses)
}
}
self.recursiveSendImpulseToEtches(impulse, etches: remainingEtches)
return
}
}
public struct Etch<ImpulseType: Impulse> { // "Observer"
/// A unique identifier for this Etch. For supporting equatable.
private let id = NSUUID()
/// When the etch should permanently cease to receieve impulses.
private(set) internal var alive: (() -> Bool) = { true }
/// Which impulses this etch should be dispatched for.
// private(set) internal var filter: (ImpulseType -> Bool)? = nil
/// Filters and unwraps the impulse.
/// If this block returns nil, the dispatch block will not be called.
private(set) internal var unwrap: (ImpulseType -> AnyObject?)? = nil
/// Preferred scheduler to on which to run dispatch if necessary.
/// If not provided, the circuit will run it on a default queue.
private(set) internal var queue: dispatch_queue_t? = nil
/// The code to run in response to a matching Impulse.
private(set) internal var dispatch: (AnyObject -> [ImpulseType]?) = { _ in nil }
public init() { }
public func withAlive(block: (() -> Bool)) -> Etch {
var etch = self
etch.alive = block
return etch
}
// internal func withFilter(block: (ImpulseType -> Bool)?) -> Etch {
// var etch = self
// etch.filter = block
// return etch
// }
public func withUnwrap(unwrap: (ImpulseType -> AnyObject?)?) -> Etch {
var etch = self
etch.unwrap = unwrap
return etch
}
public func withQueue(queue: dispatch_queue_t?) -> Etch {
var etch = self
etch.queue = queue
return etch
}
public func withDispatch(dispatch: (AnyObject -> [ImpulseType]?)) -> Etch {
var etch = self
etch.dispatch = dispatch
return etch
}
}
public extension Etch {
public func withAliveHost(host: AnyObject) -> Etch {
return self.withAlive { [weak host] in host != nil }
}
}
extension Etch: Equatable {}
public func ==<T: Impulse>(lhs: Etch<T>, rhs: Etch<T>) -> Bool {
return lhs.id == rhs.id
}
/// A message. Intended to be an enum type.
public protocol Impulse { } // "Event"
infix operator <++ { associativity right precedence 93 }
public func <++<ImpulseType: Impulse>(lhs: Circuit<ImpulseType>, rhs: Etch<ImpulseType>) {
lhs.addEtch(rhs)
} |
0 | //
// FetchRequest.swift
// dopravaBrno
//
// Created by Thành Đỗ Long on 20/03/2019.
// Copyright © 2019 Thành Đỗ Long. All rights reserved.
//
import Foundation
import RealmSwift
struct FetchRequest<Model, RealmObject: Object> {
let predicate: NSPredicate?
let sortDescriptors: [SortDescriptor]
let transformer: (Results<RealmObject>) -> Model
}
extension VendingMachine {
static let all = FetchRequest<[VendingMachine], VendingMachineObject> (
predicate: nil,
sortDescriptors: [],
transformer: { $0.map(VendingMachine.init) }
)
}
extension Vehicle {
static let all = FetchRequest<[Vehicle], VehicleObject> (
predicate: nil,
sortDescriptors: [],
transformer: { $0.map(Vehicle.init) }
)
}
extension Stop {
static let all = FetchRequest<[Stop], StopObject> (
predicate: nil,
sortDescriptors: [],
transformer: { $0.map(Stop.init) }
)
}
|
0 | import SwiftUI
let pitches: [PitchClass] = [.cSharp, .gSharp, .dSharp, .aSharp, .f, .c, .g, .d, .a, .e, .b, .fSharp]
let chordTypes: [ChordType] = [.major, .minor, .major7, .minor7, .dominant7, .minor7flat5, .diminished, .minormajor7, .major7sharp5]
struct ContentView: View {
var conductor: Conductor
let chords = pitches.map { pitch in
chordTypes.map { chordType in
Chord(
chordType,
at: Pitch(pitch, 3 + (pitch.rawValue > 7 ? 0 : 1))
)
}
}
var body: some View {
HStack {
ForEach(chords, id: \.self) { column in
VStack {
ForEach(column, id: \.self) { chord in
Button("\(chord.title)") {}
.onLongPressGesture(
minimumDuration: .infinity,
maximumDistance: .infinity,
pressing: {
toggleNotes(notes: chord.notes, state: $0)
},
perform: { }
)
}
}
}
}
.padding()
.buttonStyle(ChordButton())
}
func toggleNotes(notes: [UInt8], state: Bool) {
if state {
conductor.playNotes(notes: notes, velocity: 100)
} else {
conductor.stopNotes(notes: notes)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(conductor: Conductor())
}
}
|
0 | //
// ColorsHelpView.swift
// Schedulee
//
// Created by Kirill Khlopko on 8/23/16.
// Copyright © 2016 Kirill Khlopko. All rights reserved.
//
import CustomUI
import Tools
class ColorsHelpView: UIView {
let table = ColorsHelpView.makeTable()
private static func makeTable() -> UITableView {
let table = UITableView(frame: .zero, style: .grouped)
table.allowsMultipleSelection = false
table.allowsSelection = false
table.backgroundColor = .clear
table.bounces = false
table.separatorColor = .clear
table.tableFooterView = UIView()
table.tableHeaderView = UIView()
table.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.reuseId)
return table
}
private var startPoint: CGPoint?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
addSubview(table)
table.dataSource = self
table.delegate = self
let pan = UIPanGestureRecognizer()
pan.addTarget(self, action: #selector(handle(pan:)))
addGestureRecognizer(pan)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
table.frame = bounds
table.frame.origin.y += 20
table.frame.size.height -= 20
}
func handle(pan: UIPanGestureRecognizer) {
let point = pan.location(in: self)
if let startPoint = startPoint {
let rtl = point.x < startPoint.x
if rtl && fabs(startPoint.x) - fabs(point.x) > frame.width * 0.35 {
frame.origin.x = -frame.width
}
} else {
startPoint = point
}
}
}
extension ColorsHelpView: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return Color.allColors.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Color.allColors[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.reuseId, for: indexPath)
let color = Color.allColors[indexPath.section][indexPath.row]
cell.backgroundColor = color
cell.textLabel?.textAlignment = .center
cell.textLabel?.font = Font.regular.withSize(16)
cell.textLabel?.text = "(\(color.components.map{"\($0)"}.joined(separator: ", ")))"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 128
}
}
private extension UIColor {
var components: [CGFloat] {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return [
round(red * 255),
round(green * 255),
round(blue * 255),
round(alpha),
]
}
}
|
0 | import Foundation
@objc protocol ViperInteractorOutput: class {
}
|
0 | //
// OtherData.swift
// CollectionViewSwiftUI
//
// Created by mac-00013 on 09/10/19.
// Copyright © 2019 swift. All rights reserved.
//
import Foundation
import SwiftUI
import UIKit
let CScreenSizeBounds = UIScreen.main.bounds
let CScreenWidth = CScreenSizeBounds.width
let CScreenHeight = CScreenSizeBounds.height
func resignKeyboard() {
UIApplication.shared.endEditing()
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
extension String {
var trim: String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
var isBlank: Bool {
return self.trim.isEmpty
}
var isAlphanumeric: Bool {
// if self.count < 8 {
// return true
// }
// return !isBlank && rangeOfCharacter(from: .alphanumerics) != nil
let regex = "^[a-zA-Z0-9]+$"
let predicate = NSPredicate(format:"SELF MATCHES %@", regex)
return predicate.evaluate(with:self)
}
var isValidEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9-]+\\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return predicate.evaluate(with:self)
}
var isValidPhoneNo: Bool {
let phoneCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let arrCharacters = self.components(separatedBy: phoneCharacters)
return self == arrCharacters.joined(separator: "")
}
var isValidPassword: Bool {
let passwordRegex = "^(?=.*[a-z])(?=.*[@$!%*#?&])[0-9a-zA-Z@$!%*#?&]{8,}"
let predicate = NSPredicate(format:"SELF MATCHES %@", passwordRegex)
return predicate.evaluate(with:self)
}
var isValidPhone: Bool {
let phoneRegex = "^[0-9+]{0,1}+[0-9]{4,15}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: self)
}
var isValidURL: Bool {
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluate(with: self)
}
var isValidBidValue: Bool {
guard let doubleValue = Double(self) else { return false}
if doubleValue < 0{
return false
}
return true
}
var verifyURL: Bool {
if let url = URL(string: self) {
return UIApplication.shared.canOpenURL(url)
}
return false
}
}
class KeyboardResponder: ObservableObject {
private var notificationCenter: NotificationCenter
@Published private(set) var currentHeight: CGFloat = 0
init(center: NotificationCenter = .default) {
notificationCenter = center
notificationCenter.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
deinit {
notificationCenter.removeObserver(self)
}
@objc func keyBoardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
currentHeight = max(keyboardSize.height, 340.0)
}
}
@objc func keyBoardWillHide(notification: Notification) {
currentHeight = 0
}
}
|
0 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "QuesstionableIntelligence",
platforms: [
.iOS(.v13),
.macOS(.v10_15),
.tvOS(.v13),
.watchOS(.v6),
],
dependencies: [
.package(url: "https://github.com/autoreleasefool/quess-engine", branch: "main"),
.package(url: "https://github.com/vapor/console-kit", from: "4.0.0"),
],
targets: [
.executableTarget(
name: "QuesstionableIntelligence",
dependencies: [
.product(name: "ConsoleKit", package: "console-kit"),
.product(name: "QuessEngine", package: "quess-engine"),
]
),
.testTarget(
name: "QuesstionableIntelligenceTests",
dependencies: ["QuesstionableIntelligence"]
),
]
)
|
0 | //
// AnimationsViewController.swift
// AC3.2-MidUnit-6-Exam
//
// Created by Louis Tur on 2/2/17.
// Copyright © 2017 AccessCode. All rights reserved.
//
import UIKit
import SnapKit
class AnimationsViewController: UIViewController, CellTitled {
// -------------------------------------------------------------------------------------------
// DO NOT MODIFY THIS SECTION
// But please do read the code
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
var titleForCell: String = "Fire + Database - Data"
var springPropertyAnimator: UIViewPropertyAnimator? // this is instantiated for you in viewWillAppear
var dynamicAnimator: UIDynamicAnimator? // be sure to instantiate this!
var collisionBehavior: UICollisionBehavior? // nothing fancy
var gravityBehavior: UIGravityBehavior? // nothing fancy, just straight down
var bounceBehavior: UIDynamicItemBehavior? // add a little bit of a "bounce"
var bouncyViews: [UIView] = [] // use this to store any views you add for the gravity/bounce animation
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = titleForCell
setupViewHierarchy()
_ = [fireDatabaseLogo, usernameContainerView, passwordContainerView, loginButton].map{ $0.isHidden = true }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.springPropertyAnimator = UIViewPropertyAnimator(duration: 2.0, dampingRatio: 0.75, animations: nil)
configureConstraints()
setupBehaviorsAndAnimators()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_ = [fireDatabaseLogo, usernameContainerView, passwordContainerView, loginButton].map{ $0.isHidden = false }
self.animateLogo()
self.addSlidingAnimationToUsername()
self.addSlidingAnimationToPassword()
self.addSlidingAnimationToLoginButton()
self.startSlidingAnimations()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.resetViews()
self.removeBehaviors()
self.removeConstraints()
}
// MARK: - Setup
private func setupViewHierarchy() {
// View controller appearance changes
UIApplication.shared.statusBarStyle = .lightContent
self.navigationController?.navigationBar.barTintColor = AnimationColors.primary
self.navigationController?.navigationBar.tintColor = AnimationColors.backgroundWhite
self.navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : AnimationColors.backgroundWhite]
self.view.backgroundColor = AnimationColors.backgroundWhite
self.view.addSubview(usernameContainerView)
self.view.addSubview(passwordContainerView)
self.view.addSubview(loginButton)
self.view.addSubview(fireDatabaseLogo)
usernameContainerView.addSubview(usernameTextField)
passwordContainerView.addSubview(passwordTextField)
loginButton.addTarget(self, action: #selector(didTapLogin(sender:)), for: .touchUpInside)
}
private func configureConstraints() {
self.edgesForExtendedLayout = []
// logo
fireDatabaseLogo.snp.makeConstraints { (view) in
view.top.equalToSuperview().offset(16.0)
view.centerX.equalToSuperview()
view.size.equalTo(CGSize(width: 200, height: 200))
}
// containers
usernameContainerView.snp.makeConstraints { (view) in
view.width.equalToSuperview().multipliedBy(0.8)
view.height.equalTo(44.0)
view.trailing.equalTo(self.view.snp.leading)
view.top.equalTo(fireDatabaseLogo.snp.bottom).offset(24.0)
}
passwordContainerView.snp.makeConstraints { (view) in
view.width.equalTo(usernameContainerView.snp.width)
view.height.equalTo(usernameContainerView.snp.height)
view.top.equalTo(usernameContainerView.snp.bottom).offset(16.0)
view.trailing.equalTo(self.view.snp.leading)
}
// textfields
usernameTextField.snp.makeConstraints { (view) in
view.leading.top.equalTo(usernameContainerView).offset(4.0)
view.trailing.bottom.equalTo(usernameContainerView).inset(4.0)
}
passwordTextField.snp.makeConstraints { (view) in
view.leading.top.equalTo(passwordContainerView).offset(4.0)
view.trailing.bottom.equalTo(passwordContainerView).inset(4.0)
}
// login button
loginButton.snp.makeConstraints { (view) in
view.top.equalTo(passwordContainerView.snp.bottom).offset(32.0)
view.trailing.equalTo(self.view.snp.leading)
}
}
// MARK: - Tear Down
internal func removeBehaviors() {
self.springPropertyAnimator = nil
self.gravityBehavior = nil
self.bounceBehavior = nil
self.collisionBehavior = nil
}
internal func resetViews() {
_ = self.bouncyViews.map { $0.removeFromSuperview() }
_ = [fireDatabaseLogo, usernameContainerView, passwordContainerView, loginButton].map{ $0.isHidden = true }
self.fireDatabaseLogo.alpha = 0.0
}
private func removeConstraints() {
_ = [usernameContainerView, passwordContainerView, loginButton].map { $0.snp.removeConstraints() }
}
// ☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️☝️
// DO NOT MODIFY THIS SECTION
// But do please read the code
// ------------------------------------------------------------------------------------------------------
// MARK: -✅🎉 EXAM STARTS HERE 🎉✅-
// MARK: - Dynamics
// ViewWillAppear = "This method is called before the view controller's view is about to be added to a view hierarchy and before any animations are configured for showing the view."
// Meaning it is called after ViewDidLoad. ViewWillAppear is called the first time the view is displayed as well as when the view is displayed again...that sounds right. So maybe I need to display the view again to get gravity to work
internal func setupBehaviorsAndAnimators() {
// 1. Instantiate your dynamicAnimator
dynamicAnimator = UIDynamicAnimator(referenceView: view)
// 2. Instantiate/setup your behaviors
// a. Collision
self.collisionBehavior = UICollisionBehavior()
collisionBehavior?.translatesReferenceBoundsIntoBoundary = true
// self.collisionBehavior
// b. Gravity
self.gravityBehavior = UIGravityBehavior()
self.gravityBehavior?.magnitude = 0.8
// c. Bounce
self.bounceBehavior = UIDynamicItemBehavior()
bounceBehavior?.elasticity = 1.0
// Why do the behaviors need to be added before the view is added to the hieraracy? The balls are created at a button pressed so can I add the behaviors in.... somewhere else?
// 3. Add your behaviors to the dynamic animator
dynamicAnimator?.addBehavior(gravityBehavior!)
dynamicAnimator?.addBehavior(collisionBehavior!)
dynamicAnimator?.addBehavior(bounceBehavior!)
// Why will this work only if I unrwapped gravityBehavior? I thought making an instance above would mean unwrapping is not needed.
}
// MARK: Slide Animations
internal func addSlidingAnimationToUsername() {
// 1. Add in animation for just the usernameContainerView here (the textField is a subview, so it will animate with it)
// Note: You must use constraints to do this animation
// Reminder: You need to call something self.view in order to apply the new constraints
UIView.animate(withDuration: 2.0, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: [.curveEaseInOut], animations: {
self.usernameContainerView.snp.remakeConstraints({ (view) in
view.width.equalToSuperview().multipliedBy(0.8)
view.height.equalTo(44.0)
view.trailing.equalTo(self.view.snp.trailing).inset(30.0)
view.top.equalTo(self.fireDatabaseLogo.snp.bottom).offset(24.0)
})
self.view.layoutIfNeeded()
//FRAME Solution: I move the frames. A bug occurs that each time I go back to the viewcontroller. The animation gets called and they move off screen
//self.usernameTextField.center.x += self.view.bounds.width - 40
}, completion: nil)
}
internal func addSlidingAnimationToPassword() {
// 1. Add in animation for just the passwordContainerView here (the textField is a subview, so it will animate with it)
// Note: You must use constraints to do this animation
// Reminder: You need to call something self.view in order to apply the new constraints
// Reminder: There is a small delay you need to account for
UIView.animate(withDuration: 2.0, delay: 0.3, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: [.curveEaseInOut], animations: {
self.passwordContainerView.snp.remakeConstraints({ (view) in
view.width.equalTo(self.usernameContainerView.snp.width)
view.height.equalTo(self.usernameContainerView.snp.height)
view.top.equalTo(self.usernameContainerView.snp.bottom).offset(16.0)
view.trailing.equalTo(self.view.snp.trailing).inset(30)
})
self.view.layoutIfNeeded()
// FRAME SOLUTION: It is listed below.
//self.passwordTextField.center.x += self.view.bounds.width - 40
}, completion: nil)
}
internal func addSlidingAnimationToLoginButton() {
// 1. Add in animation for just the login button
// Note: You must use constraints to do this animation
// Reminder: You need to call something self.view in order to apply the new constraints
// Reminder: There is a small delay you need to account for
UIView.animate(withDuration: 2.0, delay: 0.5, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: [.curveEaseInOut], animations: {
self.loginButton.snp.remakeConstraints({ (view) in
view.top.equalTo(self.passwordContainerView.snp.bottom).offset(32.0)
view.trailing.equalTo(self.view.snp.trailing).inset(150)
})
self.view.layoutIfNeeded()
//FRAME SOLUTION,
// self.loginButton.center.x += self.view.bounds.width - 150
}, completion: nil)
}
internal func startSlidingAnimations() {
// 1. Begin the animations
}
// MARK: Scale & Fade-In Logo
internal func animateLogo() {
// MARK: Note to self, I animate the view frame in order to make it grow.
// 1. Ensure the scale and alpha are set properly prior to animating
fireDatabaseLogo.frame.size = CGSize(width: 150, height: 150)
// 2. Add the animations
UIView.animate(withDuration: 1.0, delay: 0.0, options: [], animations: {
self.fireDatabaseLogo.alpha = 1.0
self.fireDatabaseLogo.frame.size = CGSize(width: 200, height: 200)
}, completion: nil) }
// MARK: - Actions
// Button is called in ViewDidLoad
internal func didTapLogin(sender: UIButton) {
// 1. instantiate a new view (Provided for you!)
let newView = UIView()
newView.backgroundColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
newView.layer.cornerRadius = 20.0
bouncyViews.append(newView)
// 2. add it to the view hierarchy
self.view.addSubview(newView)
// 3. add constraints (make it 40.0 x 40.0)
newView.snp.makeConstraints { (view) in
view.top.equalTo(loginButton.snp.bottom)
view.centerX.equalTo(loginButton.snp.centerX)
view.height.equalTo(40.0)
view.width.equalTo(40.0)
}
self.view.layoutIfNeeded()
// 4. Add the view to your behaviors
gravityBehavior?.addItem(newView)
collisionBehavior?.addItem(newView)
bounceBehavior?.addItem(newView)
// I have three behaviors in the dynamicAnimator. But gravity is not being applied to my views
// var count = dynamicAnimator?.behaviors
// view.setNeedsDisplay()
// view.setNeedsLayout()
//
// Okay so my view is being stored in an array after it is made. The views in the array have no bounce? Maybe?
// How can I use an array of bouncy views? When the button gets pressed ...
// 5. (Extra Credit) Add a random angular velocity (between 0 and 15 degrees) to the bounceBehavior
}
// MARK: - ⛔️EXAM ENDS HERE⛔️ -
// -------------------------------------------------------------------------------------------
// DO NOT MODIFY THIS SECTION
// But please do read the code
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
// MARK: Lazy Inits
// text fields
internal lazy var usernameTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Username..."
textField.textColor = AnimationColors.primaryDark
textField.tintColor = AnimationColors.primaryDark
textField.borderStyle = .bezel
return textField
}()
internal lazy var passwordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password..."
textField.textColor = AnimationColors.primaryDark
textField.tintColor = AnimationColors.primaryDark
textField.borderStyle = .bezel
textField.isSecureTextEntry = true
return textField
}()
// containers
internal lazy var usernameContainerView: UIView = {
let view: UIView = UIView()
return view
}()
internal lazy var passwordContainerView: UIView = {
let view: UIView = UIView()
return view
}()
// login button
internal lazy var loginButton: UIButton = {
let button: UIButton = UIButton(type: .roundedRect)
button.setTitle("LOG IN", for: .normal)
button.backgroundColor = AnimationColors.primaryLight
button.titleLabel?.font = UIFont.systemFont(ofSize: 16.0, weight: UIFontWeightMedium)
button.setTitleColor(AnimationColors.backgroundWhite, for: .normal)
button.layer.cornerRadius = 4.0
button.layer.borderColor = AnimationColors.primary.cgColor
button.layer.borderWidth = 2.0
button.contentEdgeInsets = UIEdgeInsetsMake(8.0, 24.0, 8.0, 24.0)
return button
}()
// logo
internal lazy var fireDatabaseLogo: UIImageView = {
let image = UIImage(named: "full")
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.alpha = 0.0
return imageView
}()
}
|
0 | //
// ProfileAllocator.swift
// Radishing
//
// Created by Nathaniel Dillinger on 4/25/18.
// Copyright © 2018 Nathaniel Dillinger. All rights reserved.
//
import Foundation
enum ProfileAllocator: AllocatorSetupable {
//MARK: Properties
static var presenter: Presentable.Type!
//MARK: Parent Function
static func fetchRequest(_ request: Request) {
switch request.assignment {
case let authAssignment as AuthAssignment:
handleAuthProducerInitialization(assignment: authAssignment, model: request.model)
case let offlineStorageAssignment as OfflineStorageAssignment:
handleOfflineStorageProducerInitialization(assignment: offlineStorageAssignment, model: request.model)
case let databaseAssignment as DatabaseAssignment:
handleDatabaseProducerInitialization(assignment: databaseAssignment, model: request.model)
default:
let error = ImproperSceneError.invalidAssignmentAtAllocator
let results = improperSceneErrorResult(error: error)
presenter.fetchResults(results)
}
}
//MARK: Child Functions
private static func handleAuthProducerInitialization(assignment: AuthAssignment, model: RequestModelable?) {
let work = Work(assignment: assignment, model: model, presenter: presenter)
let producer: Producable.Type = ProfileAuthProducer.self
producer.fetchWork(work)
}
private static func handleOfflineStorageProducerInitialization(assignment: OfflineStorageAssignment, model: RequestModelable?) {
let work = Work(assignment: assignment, model: model, presenter: presenter)
let producer: Producable.Type = ProfileOfflineStorageProducer.self
producer.fetchWork(work)
}
private static func handleDatabaseProducerInitialization(assignment: DatabaseAssignment, model: RequestModelable?) {
let work = Work(assignment: assignment, model: model, presenter: presenter)
let producer: Producable.Type = ProfileDatabaseProducer.self
producer.fetchWork(work)
}
private static func improperSceneErrorResult(error: Error) -> Results {
return Results(assignment: ImproperAssignment.catchError, error: error, model: nil)
}
}
|
0 | //
// OtaDataModel.swift
// BLE-Swift
//
// Created by SuJiang on 2019/1/8.
// Copyright © 2019 ss. All rights reserved.
//
import Foundation
public enum OtaDataType: Int, Codable {
case platform = 1
case touchPanel
case heartRate
case picture
case freeScale // 只有Nordic平台才有 kl17
case agps
case gps
}
public class OtaDataModel {
public var type: OtaDataType
public var data: Data
public var otaAddressData: Data!
public var otaData: Data!
public var crcData: Data!
public var sections = [OtaDataSection]()
// 这两个也是为了兼容Nordic平台ota
public var datData: Data!
public var typeData: Data!
// TLSR ota数据
public var tlsrOtaDataIndex = 0
public var tlsrOtaDataPackages: [Data]!
// deinit {
// data.removeAll()
// otaData.removeAll()
// }
public init(type: OtaDataType, data: Data) {
self.type = type
self.data = data
}
func getApolloDataReady() -> Bool {
guard let otaData = getOtaData(for: data) else {
return false
}
guard let addressData = getOtaAddressData(for: data) else {
return false
}
guard let crcData = getCrcData(for: otaData) else {
return false
}
self.otaData = otaData
self.otaAddressData = addressData
self.crcData = crcData
self.sections = splitDataToSections(otaData)
self.data.removeAll()
return true
}
func getNordicDataReady() -> Bool {
if type == .platform{
self.otaData = data
self.crcData = datData
self.typeData = getNordicTypeData()
self.sections = splitNordicDataToSections(otaData)
return true
}
guard let otaData = getNordicOtaData(for: data) else {
return false
}
guard let addressData = getNordicOtaAddressData(for: data) else {
return false
}
guard let crcData = getNordicCrcData(for: otaData) else {
return false
}
self.otaData = otaData
self.otaAddressData = addressData
self.crcData = crcData
self.typeData = getNordicTypeData()
self.sections = splitNordicDataToSections(otaData)
return true
}
func getTlsrDataReady() -> Bool {
tlsrOtaDataIndex = 0
tlsrOtaDataPackages = [Data]()
if data.count == 0 {
return false
}
let offset = 16
var count = data.count / offset
if data.count % offset > 0 {
count += 1
}
for i in 0 ..< count {
let start = i * offset
let end = (i + 1) * offset > data.count ? data.count : (i + 1) * offset
let subData = data.subdata(in: start ..< end)
let subBytes = subData.bytes
var pack_head = [UInt8](repeating: 0, count: 2)
pack_head[0] = UInt8(i & 0xff)
pack_head[1] = UInt8((i >> 8) & 0xff)
var otaBuffer = [UInt8](repeating: 0, count: offset + 4)
var otaCmd = [UInt8](repeating: 0, count: offset + 2)
otaBuffer[0] = pack_head[0]
otaBuffer[1] = pack_head[1]
for j in 0 ..< offset {
if j < subData.count {
otaBuffer[j + 2] = subBytes[j]
} else {
otaBuffer[j + 2] = 0xff
}
}
for j in 0 ..< offset + 2 {
otaCmd[j] = otaBuffer[j]
}
let crc_t = getTlsrCrcData(for: otaCmd)
// var crc = [UInt8](repeating: 0, count: 2)
//
// crc[0] = UInt8(crc_t & 0xff)
// crc[1] = UInt8((crc_t >> 8) & 0xff)
otaBuffer[offset + 2] = UInt8(crc_t & 0xff)
otaBuffer[offset + 3] = UInt8((crc_t >> 8) & 0xff)
let pack = Data(bytes: otaBuffer, count: offset + 4)
self.tlsrOtaDataPackages.append(pack)
}
return true
}
// apollo平台,ota 拆分数据是已 2048 为一块
private func splitDataToSections(_ data: Data) -> [OtaDataSection] {
var sections = [OtaDataSection]()
let num = data.count / kSizeOfPieceData
let left = data.count % kSizeOfPieceData
for i in 0..<num {
let data = data.subdata(in: i * kSizeOfPieceData ..< (i + 1) * kSizeOfPieceData)
let section = OtaDataSection(data: data, range: i * kSizeOfPieceData ..< (i + 1) * kSizeOfPieceData)
sections.append(section)
}
if left > 0 {
let data = data.subdata(in: data.count - left ..< data.count)
let section = OtaDataSection(data: data, range: data.count - left ..< data.count)
sections.append(section)
}
return sections
}
// nordic 没有分块的设计,只是设计成20的packages回传一次
private func splitNordicDataToSections(_ data: Data) -> [OtaDataSection] {
var sections = [OtaDataSection]()
let sectionSize = kPackageCountCallback * BLEConfig.shared.mtu
let num = data.count / sectionSize
let left = data.count % sectionSize
for i in 0..<num {
let data = data.subdata(in: i * sectionSize ..< (i + 1) * sectionSize)
let section = OtaDataSection(data: data, range: i * sectionSize ..< (i + 1) * sectionSize)
sections.append(section)
}
if left > 0 {
let data = data.subdata(in: data.count - left ..< data.count)
let section = OtaDataSection(data: data, range: data.count - left ..< data.count)
sections.append(section)
}
return sections
}
// MARK: - 工具
func getCrcData(for sendData: Data) -> Data? {
var crc: UInt16 = 0xffff
let binBytes = sendData.bytes
for i in 0..<(sendData.count) {
crc = crc >> 8 | (crc << 8)
crc ^= UInt16(binBytes[i])
crc ^= UInt16((UInt8((crc & 0xff)) >> 4))
crc ^= UInt16((crc << 8) << 4)
crc ^= UInt16(((crc & 0xff) << 4) << 1)
}
let dataCrc = Data(bytes: &crc, count: 2)
let num: Int = 4 - dataCrc.count
var zero: Int = 0
if num == 0 {
return dataCrc
} else {
var dataM = Data()
dataM.append(dataCrc)
dataM.append(Data(bytes: &zero, count: num))
return dataM
}
}
func getOtaData(for data: Data) -> Data? {
if data.count <= 4 {
return nil
}
return data.subdata(in: 4 ..< data.count)
}
func getOtaAddressData(for data: Data) -> Data? {
if data.count < 4 {
return nil
}
return data.subdata(in: 0 ..< 4)
}
func getNordicOtaData(for data: Data) -> Data? {
if type == .platform {
return data
}
var offset = 5
if type == .picture {
offset = 4
}
if data.count <= offset {
return nil
}
return data.subdata(in: offset ..< data.count)
}
func getNordicOtaAddressData(for data: Data) -> Data? {
var offset = 5
if type == .picture {
offset = 4
}
if data.count < offset {
return nil
}
return data.subdata(in: 0 ..< offset)
}
func getNordicTypeData() -> Data {
switch type {
case .platform:
return Data([0x01, 0x04])
case .touchPanel:
return Data([0x01, 0x10])
case .heartRate:
return Data([0x01, 0x20])
case .picture:
return Data([0x01, 0x40])
case .agps:
return Data([0x00, 0x00])
case .freeScale:
return Data([0x01, 0x08])
case .gps:
return Data([0x00, 0x00])
}
}
func getNordicCrcData(for data: Data) -> Data? {
guard let crc = getCrcData(for: data) else {
return nil
}
var tmpData = Data([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
tmpData.append(crc)
return tmpData
}
/*
let crc16Poly = [0, 0xa001] //0x8005 <==> 0xa001
func crc16(pD: UInt8, len: Int) -> UInt16 {
var crc: UInt16 = 0xffff
var i: Int
var j: Int
j = len
while j > 0 {
var ds: UInt8 = pD += 1
for i in 0..<8 {
crc = (crc >> 1) ^ crc16Poly[(UInt(crc) ^ UInt(ds)) & 1]
ds = ds >> 1
}
j -= 1
}
return crc
}
*/
func getTlsrCrcData(for bytes: [UInt8]) -> UInt16 {
let crc16Poly: [UInt16] = [0, 0xa001]
var crc: UInt16 = 0xffff
var j = bytes.count
while j > 0 {
var ds = bytes[bytes.count - j]
for _ in 0..<8 {
crc = (crc >> 1) ^ crc16Poly[Int((crc ^ UInt16(ds)) & 1)]
ds = ds >> 1
}
j -= 1
}
return crc
}
}
|
0 | // swift-tools-version:5.5
//
// Package.swift
// Gtk4SwiftTestApp
//
// Created 01/12/2021.
//
import PackageDescription
let package = Package(
name: "Gtk4TestApp",
platforms: [.macOS(.v12)],
products: [
.library(
name: "Gtk4TestApp",
targets: ["Gtk4TestAppSwift", "Gtk4TestAppC"]),
],
dependencies: [],
targets: [
.systemLibrary(
name: "CGtk",
path: "CGtk",
pkgConfig: "gtk4",
providers: [
.brew(["gtk4", "glib", "glib-networking"/*, "gobject-introspection"*/]),
.apt(["libgtk-4-dev", "libglib2.0-dev", "glib-networking"/*, "gobject-introspection", "libgirepository1.0-dev"*/])
]
),
.target(
name: "Gtk4TestAppC",
dependencies: ["CGtk"],
path: "Gtk4TestAppC",
publicHeadersPath: "publicHeaders"
),
.executableTarget(name: "Gtk4TestAppSwift", dependencies: ["Gtk4TestAppC"], path: "Gtk4TestAppSwift")
]
)
|
0 | //
// UIApplication+Extension.swift
// NAExtensions
//
// Created by Nitin A on 22/01/20.
// Copyright © 2020 Nitin A. All rights reserved.
//
import UIKit
public extension UIApplication {
// to get top view controller from the application.
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController, let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
|
0 |
/// Combine two termination conditions together by the OR operation.
///
/// **Pro Tip:** You can use this class with nicer syntax by combining conditions with the `||` operator.
open class OrCondition<Chromosome: ChromosomeType>: TerminationCondition<Chromosome> {
/// The first operand of the OR operation.
open let firstOperand: TerminationCondition<Chromosome>
/// The second operand of the OR operation.
open let secondOperand: TerminationCondition<Chromosome>
/**
Combine two termination conditions together by the OR operation.
**Pro Tip:** You can use this class with nicer syntax by combining conditions with the `||` operator.
- parameter first: The first operand of the OR operation.
- parameter second: The second operand of the OR operation.
- returns: New termination condition.
*/
public init(_ first: TerminationCondition<Chromosome>, _ second: TerminationCondition<Chromosome>) {
self.firstOperand = first
self.secondOperand = second
super.init()
}
open override func shouldTerminate(_ population: MatingPool<Chromosome>) -> Bool {
return firstOperand.shouldTerminate(population) || secondOperand.shouldTerminate(population)
}
}
public func ||<Chromosome: ChromosomeType>(lhs: TerminationCondition<Chromosome>, rhs: TerminationCondition<Chromosome>) -> TerminationCondition<Chromosome> {
return OrCondition(lhs, rhs)
}
|
0 | //
// SampleAppModel.swift
// SampleApp
//
// Created by Peter Livesey on 7/22/16.
// Copyright © 2016 LinkedIn. All rights reserved.
//
import Foundation
import RocketData
/**
Here, we're going to define a custom protocol for all the models in this app to adhere to.
It's going to extend from Model, so we can use it with Rocket Data.
*/
protocol SampleAppModel: Model {
init?(data: [NSObject: AnyObject])
func data() -> [NSObject: AnyObject]
} |
0 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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.
*/
/// TabBar is a component responsible to display a tab layout.
/// It works by displaying tabs that can change a context when clicked.
public struct TabBar: ServerDrivenComponent, AutoDecodable {
/// Defines yours tabs title and icon.
public let items: [TabBarItem]
/// Reference a native style configured to be applied on this view.
public var styleId: String?
/// Defines the expression that is observed to change the current tab selected.
public var currentTab: Expression<Int>?
/// Defines a list of action that will be executed when a tab is selected.
public var onTabSelection: [Action]?
}
/// Defines the view item in the tab view
public struct TabBarItem {
/// Displays the text on the `TabView` component. If it is null or not declared it won't display any text.
public var icon: StringOrExpression?
/// Display an icon image on the `TabView` component.
/// If it is left as null or not declared it won't display any icon.
public var title: String?
}
extension TabBarItem: Decodable {
enum CodingKeys: String, CodingKey {
case icon
case title
}
enum LocalImageCodingKey: String, CodingKey {
case mobileId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let nestedContainer = try? container.nestedContainer(keyedBy: LocalImageCodingKey.self, forKey: .icon)
icon = try nestedContainer?.decodeIfPresent(String.self, forKey: .mobileId)
title = try container.decodeIfPresent(String.self, forKey: .title)
}
}
|
0 | //
// ProductOrderCompleteVC.swift
// martkurly
//
// Created by ㅇ오ㅇ on 2020/10/08.
// Copyright © 2020 Team3x3. All rights reserved.
//
import UIKit
class ProductOrderCompleteVC: UIViewController {
// MARK: - Properties
let checkView = ProductOrderCheckView()
let line = UIView()
private let goHomeButton = KurlyButton(title: "홈으로 이동", style: .purple)
var orderName = ""
var orderPay = 0
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setConfigure()
setUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarStatus(type: .whiteType,
isShowCart: false,
leftBarbuttonStyle: .dismiss,
titleText: "주문완료")
}
// MARK: - UI
private func setConfigure() {
[checkView, line, goHomeButton].forEach {
view.addSubview($0)
}
view.backgroundColor = ColorManager.General.backGray.rawValue
line.backgroundColor = ColorManager.General.mainGray.rawValue
checkView.name = orderName // 유저 이름
checkView.payment = orderPay // 결제 금액
checkView.orderListButton.addTarget(self, action: #selector(orderListButtonTap(_:)), for: .touchUpInside)
goHomeButton.addTarget(self, action: #selector(goHomeButtonTap(_:)), for: .touchUpInside)
}
@objc
func orderListButtonTap(_ sender: UIButton) {
print("주문 내역이 없습니다.")
}
@objc
func goHomeButtonTap(_ sender: UIButton) {
dismiss(animated: true)
}
private func setUI() {
checkView.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide)
$0.leading.equalToSuperview().offset(8)
$0.trailing.equalToSuperview().inset(8)
$0.bottom.equalTo(goHomeButton.snp.top).offset(8)
$0.centerX.equalToSuperview()
}
line.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.height.equalTo(1)
}
goHomeButton.snp.makeConstraints {
$0.bottom.equalToSuperview().inset(40)
$0.leading.equalToSuperview().offset(8)
$0.width.equalTo(checkView)
$0.height.equalTo(55)
}
}
}
|
0 | //
// Book+CoreDataProperties.swift
// CoreDataDemo
//
// Created by 吴伟城 on 16/1/5.
// Copyright © 2016年 cn-wu.cn. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Book {
@NSManaged var title: String?
@NSManaged var price: NSNumber?
@NSManaged var yearPublished: NSNumber?
@NSManaged var author: NSManagedObject?
}
|
0 | //
// SDK.swift
// SDKSCT
//
// Created by Inficare Pvt. Ltd. on 09/02/2018.
// Copyright © 2018 Inficare Pvt. Ltd. All rights reserved.
//
import Foundation
public class SDK: NSObject {
public class var Instance : SDK{
struct Static {
static let shared = SDK();
}
return Static.shared
}
public func getMessage() ->String{
return "hello, World"
}
public func startPayment(viewController:UIViewController){
viewController.present(SCTVC(), animated: true, completion: nil)
}
}
|
0 | //
// YepFayeService.swift
// Yep
//
// Created by NIX on 16/5/18.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import Foundation
import RealmSwift
import YepKit
import YepNetworking
import FayeClient
protocol YepFayeServiceDelegate: class {
func fayeRecievedInstantStateType(_ instantStateType: YepFayeService.InstantStateType, userID: String)
/*
func fayeRecievedNewMessages(AllMessageIDs: [String], messageAgeRawValue: MessageAge.RawValue)
func fayeMessagesMarkAsReadByRecipient(lastReadAt: NSTimeInterval, recipientType: String, recipientID: String)
*/
}
private let fayeQueue = DispatchQueue(label: "RefrainFaye", attributes: [])
final class YepFayeService: NSObject {
static let sharedManager = YepFayeService()
enum MessageType: String {
case `default` = "ChatMessage"
case instant = "ChatStatus"
case read = "ReadMessage"
case messageDeleted = "DeleteMessage"
}
enum InstantStateType: Int, CustomStringConvertible {
case text = 0
case audio
var description: String {
switch self {
case .text:
return NSLocalizedString("typing", comment: "")
case .audio:
return NSLocalizedString("recording", comment: "")
}
}
}
let fayeClient: FayeClient = {
let client = FayeClient(serverURL: fayeBaseURL)
return client
}()
weak var delegate: YepFayeServiceDelegate?
fileprivate lazy var realm: Realm = {
return try! Realm()
}()
override init() {
super.init()
fayeClient.delegate = self
}
}
// MARK: - Public
struct LastRead {
let atUnixTime: TimeInterval
let messageID: String
let recipient: Recipient
init?(info: JSONDictionary) {
guard let atUnixTime = info["last_read_at"] as? TimeInterval else {
println("LastRead: Missing key: last_read_at")
return nil
}
guard let messageID = info["last_read_id"] as? String else {
println("LastRead: Missing key: last_read_id")
return nil
}
guard let recipientType = info["recipient_type"] as? String else {
println("LastRead: Missing key: recipient_type")
return nil
}
guard let recipientID = info["recipient_id"] as? String else {
println("LastRead: Missing key: recipient_id")
return nil
}
guard let conversationType = ConversationType(nameForServer: recipientType) else {
println("LastRead: Create conversationType failed!")
return nil
}
self.atUnixTime = atUnixTime
self.messageID = messageID
self.recipient = Recipient(type: conversationType, ID: recipientID)
}
}
extension YepFayeService {
func prepareForChannel(_ channel: String) {
if let extensionData = extensionData() {
fayeClient.setExtension(extensionData, forChannel: channel)
}
}
func tryStartConnect() {
fayeQueue.async { [weak self] in
guard let strongSelf = self else { return }
guard let userID = YepUserDefaults.userID.value, let personalChannel = strongSelf.personalChannelWithUserID(userID) else {
println("FayeClient startConnect failed, not userID or personalChannel!")
return
}
println("Faye will subscribe \(personalChannel)")
strongSelf.prepareForChannel("connect")
strongSelf.prepareForChannel("handshake")
strongSelf.prepareForChannel(personalChannel)
_ = strongSelf.fayeClient.connect()
}
}
fileprivate func subscribeChannel() {
fayeQueue.async { [weak self] in
guard let userID = YepUserDefaults.userID.value, let personalChannel = self?.personalChannelWithUserID(userID) else {
println("FayeClient subscribeChannel failed, not userID or personalChannel!")
return
}
self?.fayeClient.subscribeToChannel(personalChannel) { [weak self] data in
println("receive faye data: \(data)")
let info: JSONDictionary = data
// Service 消息
if let messageInfo = info["payload"] as? JSONDictionary {
guard let realm = try? Realm() else {
return
}
realm.beginWrite()
let isServiceMessage = isServiceMessageAndHandleMessageInfo(messageInfo, inRealm: realm)
_ = try? realm.commitWrite()
if isServiceMessage {
return
}
}
guard let
messageTypeString = info["type"] as? String,
let messageType = MessageType(rawValue: messageTypeString)
else {
println("Faye recieved unknown message type")
return
}
//println("messageType: \(messageType)")
switch messageType {
case .default:
guard let messageInfo = info["payload"] as? JSONDictionary else {
println("Error: Faye Default not messageInfo!")
break
}
self?.saveMessageWithMessageInfo(messageInfo)
case .instant:
guard let messageInfo = info["payload"] as? JSONDictionary else {
println("Error: Faye Instant not messageInfo!")
break
}
if let userID = messageInfo["from"] as? String,
let state = messageInfo["status"] as? Int {
if let instantStateType = InstantStateType(rawValue: state) {
self?.delegate?.fayeRecievedInstantStateType(instantStateType, userID: userID)
}
}
case .read:
guard let messageInfo = info["payload"] as? JSONDictionary else {
println("Error: Faye Read not messageInfo!")
break
}
guard let lastRead = LastRead(info: messageInfo) else {
break
}
SafeDispatch.async {
NotificationCenter.default.post(name: Config.NotificationName.messageBatchMarkAsRead, object: lastRead)
//self?.delegate?.fayeMessagesMarkAsReadByRecipient(last_read_at, recipientType: recipient_type, recipientID: recipient_id)
}
case .messageDeleted:
guard let messageInfo = info["payload"] as? JSONDictionary else {
println("Error: Faye MessageDeleted not messageInfo!")
break
}
guard let messageID = messageInfo["id"] as? String else {
break
}
handleMessageDeletedFromServer(messageID: messageID)
}
}
}
}
func sendInstantMessage(_ message: JSONDictionary, completion: @escaping (_ success: Bool) -> Void) {
fayeQueue.async { [unowned self] in
guard let extensionData = self.extensionData() else {
println("Can NOT sendInstantMessage, not extensionData")
completion(false)
return
}
let data: JSONDictionary = [
"version": "1.0.0",
"type": MessageType.instant.rawValue,
"payload": message
]
self.fayeClient.sendMessage(data, toChannel: self.instantChannel(), usingExtension: extensionData, usingBlock: { message in
if message.successful {
completion(true)
} else {
completion(false)
}
})
}
}
}
// MARK: - Private
extension YepFayeService {
fileprivate func extensionData() -> [String: String]? {
if let v1AccessToken = YepUserDefaults.v1AccessToken.value {
return [
"accessToken": v1AccessToken,
"version": "1.0.0",
]
} else {
return nil
}
}
fileprivate func instantChannel() -> String {
return "/public/status"
}
fileprivate func personalChannelWithUserID(_ userID: String) -> String? {
guard !userID.isEmpty else {
return nil
}
return "/private/\(userID)"
}
fileprivate func saveMessageWithMessageInfo(_ messageInfo: JSONDictionary) {
//println("faye received messageInfo: \(messageInfo)")
func isMessageSendFromMe() -> Bool {
guard let senderInfo = messageInfo["sender"] as? JSONDictionary, let senderID = senderInfo["id"] as? String, let currentUserID = YepUserDefaults.userID.value else {
return false
}
return senderID == currentUserID
}
if isMessageSendFromMe() {
// 如果收到的消息在本地的 SendingMessagesPool 里,那就不同步了
if let tempMesssageID = messageInfo["random_id"] as? String {
if SendingMessagesPool.containsMessage(with: tempMesssageID) {
println("SendingMessagesPool.containsMessage \(tempMesssageID)")
// 广播只有一次,可从池子里清除 tempMesssageID
SendingMessagesPool.removeMessage(with: tempMesssageID)
return
}
} else {
// 是自己发的消息被广播过来,但没有 random_id,也不同步了
println("isMessageSendFromMe but NOT random_id")
return
}
}
SafeDispatch.async {
guard let realm = try? Realm() else {
return
}
realm.beginWrite()
var messageIDs: [String] = []
syncMessageWithMessageInfo(messageInfo, messageAge: .new, inRealm: realm) { _messageIDs in
messageIDs = _messageIDs
}
let _ = try? realm.commitWrite()
tryPostNewMessagesReceivedNotificationWithMessageIDs(messageIDs, messageAge: .new)
/*
self?.delegate?.fayeRecievedNewMessages(messageIDs, messageAgeRawValue: MessageAge.New.rawValue)
// Notification 可能导致 Crash,Conversation 有可能在有些时候没有释放监听,但是现在还没找到没释放的原因
// 上面的 Delegate fayeRecievedNewMessages 替代了 Notification
*/
}
}
}
// MARK: - FayeClientDelegate
extension YepFayeService: FayeClientDelegate {
func fayeClient(_ client: FayeClient, didConnectToURL URL: URL) {
println("fayeClient didConnectToURL \(URL)")
subscribeChannel()
}
func fayeClient(_ client: FayeClient, didDisconnectWithError error: Swift.Error?) {
if let error = error {
println("fayeClient didDisconnectWithError \(error)")
}
}
func fayeClient(_ client: FayeClient, didSubscribeToChannel channel: String) {
println("fayeClient didSubscribeToChannel \(channel)")
}
func fayeClient(_ client: FayeClient, didUnsubscribeFromChannel channel: String) {
println("fayeClient didUnsubscribeFromChannel \(channel)")
}
func fayeClient(_ client: FayeClient, didFailWithError error: Swift.Error?) {
if let error = error {
println("fayeClient didFailWithError \(error)")
}
}
func fayeClient(_ client: FayeClient, didFailDeserializeMessage message: [String: Any]?, withError error: Swift.Error?) {
if let error = error {
println("fayeClient didFailDeserializeMessage \(error)")
}
}
func fayeClient(_ client: FayeClient, didReceiveMessage messageData: [String: Any], fromChannel channel: String) {
println("fayeClient didReceiveMessage \(messageData)")
}
}
|
0 | import Foundation
/// An error occuring while sending a request
public enum APIError: Error {
case unexpectedError
case responseMissing
case decodingError(Error)
case clientError(statusCode: Int, error: Error?, body: Data?)
case serverError(statusCode: Int, error: Error?, body: Data?)
case missingResponseBody
case invalidURLComponents
}
public final class Client {
public typealias RequestCompletion<ResponseType> = (HTTPURLResponse?, Result<ResponseType, Error>) -> Void
// MARK: - Properties
public lazy var sessionCache: SessionCache = .init(configuration: configuration)
public let configuration: Configuration
public let session: URLSession
private lazy var responseHandler: ResponseHandler = .init(configuration: configuration)
private lazy var requestExecuter: RequestExecuter = {
switch configuration.requestExecuterType {
case .sync:
return SyncRequestExecuter(session: session)
case .async:
return AsyncRequestExecuter(session: session)
case let .custom(executerType):
return executerType.init(session: session)
}
}()
// MARK: - Initialisation
/**
* Initialises a new client instance with a default url session.
*
* - Parameter configuration: The client configuration.
* - Parameter session: The URLSession which is used for executing requests
*/
public init(
configuration: Configuration,
session: URLSession = .init(configuration: .default)
) {
self.configuration = configuration
self.session = session
}
// MARK: - Methods
@discardableResult
public func get<ResponseType: Decodable>(
endpoint: Endpoint<ResponseType>,
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let request: URLRequest = try createRequest(
forHttpMethod: .GET,
and: endpoint,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleDecodableResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func post<BodyType: Encodable, ResponseType: Decodable>(
endpoint: Endpoint<ResponseType>,
body: BodyType,
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let encoder: Encoder = endpoint.encoder ?? configuration.encoder
let bodyData: Data = try encoder.encode(body)
let request: URLRequest = try createRequest(
forHttpMethod: .POST,
and: endpoint,
and: bodyData,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleDecodableResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func post<ResponseType>(
endpoint: Endpoint<ResponseType>,
body: ExpressibleByNilLiteral? = nil,
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let request: URLRequest = try createRequest(
forHttpMethod: .POST,
and: endpoint,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleVoidResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func put<BodyType: Encodable, ResponseType: Decodable>(
endpoint: Endpoint<ResponseType>,
body: BodyType,
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let encoder: Encoder = endpoint.encoder ?? configuration.encoder
let bodyData: Data = try encoder.encode(body)
let request: URLRequest = try createRequest(
forHttpMethod: .PUT,
and: endpoint,
and: bodyData,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleDecodableResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func patch<BodyType: Encodable, ResponseType: Decodable>(
endpoint: Endpoint<ResponseType>,
body: BodyType,
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let encoder: Encoder = endpoint.encoder ?? configuration.encoder
let bodyData: Data = try encoder.encode(body)
let request: URLRequest = try createRequest(
forHttpMethod: .PATCH,
and: endpoint,
and: bodyData,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleDecodableResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func delete<ResponseType: Decodable>(
endpoint: Endpoint<ResponseType>,
parameter: [String: Any] = [:],
andAdditionalHeaderFields additionalHeaderFields: [String: String] = [:],
_ completion: @escaping RequestCompletion<ResponseType>
) -> CancellableRequest? {
do {
let request: URLRequest = try createRequest(
forHttpMethod: .DELETE,
and: endpoint,
andAdditionalHeaderFields: additionalHeaderFields
)
return requestExecuter.send(request: request) { [weak self] data, urlResponse, error in
guard let self = self else { return }
self.responseHandler.handleDecodableResponse(
data: data,
urlResponse: urlResponse,
error: error,
endpoint: endpoint,
completion: completion
)
}
} catch {
enqueue(completion(nil, .failure(error)))
}
return nil
}
@discardableResult
public func send(request: URLRequest, _ completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> CancellableRequest? {
return requestExecuter.send(request: request, completion)
}
private func createRequest<ResponseType>(
forHttpMethod httpMethod: HTTPMethod,
and endpoint: Endpoint<ResponseType>,
and body: Data? = nil,
andAdditionalHeaderFields additionalHeaderFields: [String: String]
) throws -> URLRequest {
var request = URLRequest(
url: try URLFactory.makeURL(from: endpoint, withBaseURL: configuration.baseURLProvider.baseURL),
httpMethod: httpMethod,
httpBody: body
)
var requestInterceptors: [Interceptor] = configuration.interceptors
// Extra case: POST-request with empty content
//
// Adds custom interceptor after last interceptor for header fields
// to avoid conflict with other custom interceptor if any.
if body == nil && httpMethod == .POST {
let targetIndex = requestInterceptors.lastIndex { $0 is HeaderFieldsInterceptor }
let indexToInsert = targetIndex.flatMap { requestInterceptors.index(after: $0) }
requestInterceptors.insert(
EmptyContentHeaderFieldsInterceptor(),
at: indexToInsert ?? requestInterceptors.endIndex
)
}
// Append additional header fields.
additionalHeaderFields.forEach { key, value in
request.addValue(value, forHTTPHeaderField: key)
}
return requestInterceptors.reduce(request) { request, interceptor in
return interceptor.intercept(request)
}
}
/// Perform something on the configuration's response queue.
public func enqueue(_ completion: @escaping @autoclosure () -> Void) {
configuration.responseQueue.async {
completion()
}
}
}
|
0 | import Foundation
import Quick
import Nimble
import PromiseKit
func waitUntil(_ expression: @autoclosure @escaping () throws -> Bool,
file: FileString = #file,
line: UInt = #line) {
expect(try expression(), file: file, line: line).toEventually(beTrue())
}
func waitFor<T>(_ expression: @autoclosure @escaping () throws -> T?,
file: FileString = #file,
line: UInt = #line) -> T? {
expect(try expression(), file: file, line: line).toEventuallyNot(beNil())
do {
let result = try expression()
return result!
} catch {
fail("Error thrown while retrieving value: \(error)")
return nil
}
}
func it<T>(_ desc: String,
timeout: TimeInterval = 1.0,
failOnError: Bool = true,
file: FileString = #file,
line: UInt = #line,
closure: @escaping () -> Promise<T>) {
it(desc, file: file.description, line: line, closure: {
let promise = closure()
waitUntil(timeout: timeout, file: file, line: line) { done in
promise.done { _ in
done()
}.catch { error in
if failOnError {
fail("Promise failed with error \(error)", file: file, line: line)
}
done()
}
}
} as () -> Void)
}
func expectToSucceed<T>(_ promise: Promise<T>, file: FileString = #file, line: UInt = #line)
-> Promise<Void> {
return promise.asVoid().recover { (error: Error) -> Void in
fail("Expected promise to succeed, but failed with \(error)", file: file, line: line)
}
}
func expectToFail<T>(_ promise: Promise<T>, file: FileString = #file, line: UInt = #line)
-> Promise<Void> {
return promise.asVoid().done {
fail("Expected promise to fail, but succeeded", file: file, line: line)
}.recover { (error: Error) -> Promise<Void> in
expect(file, line: line, expression: { throw error }).to(throwError())
return Promise.value(())
}
}
func expectToFail<T, E: Error>(_ promise: Promise<T>,
with expectedError: E,
file: FileString = #file,
line: UInt = #line) -> Promise<Void> {
return promise.asVoid().done {
fail("Expected promise to fail with error \(expectedError), but succeeded",
file: file, line: line)
}.recover { (error: Error) -> Void in
expect(file, line: line, expression: { throw error }).to(throwError(expectedError))
}
}
/// Convenience struct for when errors need to be thrown from tests to abort execution (e.g. during
/// a promise chain).
struct TestError: Error {
let description: String
init(_ description: String) { self.description = description }
}
|
0 | // EXPLICIT-CONTROL EVALUATOR FROM SECTION 5.4 OF
// STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS
// MODIFIED TO SUPPORT COMPILED CODE (AS IN SECTION 5.5.7)
// Changes to basic evaluator machine are
// (1) some new eceval controller code for the driver and apply-dispatch;
// (2) some additional machine operations from;
// (3) support for compiled code to call interpreted code (exercise 5.47) --
// (new register and 1 new instruction at start)
// (4) new startup aid start-eceval
// Explicit-control evaluator.
// To use it, load "load-eceval-compiler.scm", which loads this file and the
// support it needs (including the register-machine simulator)
// To start, can use compile-and-go as in section 5.5.7
// or start-eceval as in the section 5.5.7 footnote.
// To resume the machine without reinitializing the global environment
// if you have somehow interrupted out of the machine back to Scheme, do
// $> (set-register-contents! eceval 'flag false)
// $> (start eceval)
//
// any old value to create the variable so that
// compile-and-go and/or start-eceval can set! it.
(define the-global-environment '())
// Interfacing compiled code with eceval machine
// From section 5.5.7
(define (start-eceval)
(set! the-global-environment (setup-environment))
(set-register-contents! eceval 'flag false)
(start eceval))
// Modification of section 4.1.4 procedure
// **replaces version in syntax file
(define (user-print object)
(cond ((compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>)))
((compiled-procedure? object)
(display '<compiled-procedure>))
(else (display object))))
(define (compile-and-go expression)
(let ((instructions
(assemble (statements
(compile expression 'val 'return))
eceval)))
(set! the-global-environment (setup-environment))
(set-register-contents! eceval 'val instructions)
(set-register-contents! eceval 'flag true)
(start eceval)))
// **NB. To [not] monitor stack operations, comment in/[out] the line after
// print-result in the machine controller below
// **Also choose the desired make-stack version in regsim.scm
(define eceval-operations
(list
;;primitive Scheme operations
(list 'read read) ;used by eceval
;;used by compiled code
(list 'list list)
(list 'cons cons)
;;operations in syntax.scm
(list 'self-evaluating? self-evaluating?)
(list 'quoted? quoted?)
(list 'text-of-quotation text-of-quotation)
(list 'variable? variable?)
(list 'assignment? assignment?)
(list 'assignment-variable assignment-variable)
(list 'assignment-value assignment-value)
(list 'definition? definition?)
(list 'definition-variable definition-variable)
(list 'definition-value definition-value)
(list 'lambda? lambda?)
(list 'lambda-parameters lambda-parameters)
(list 'lambda-body lambda-body)
(list 'if? if?)
(list 'if-predicate if-predicate)
(list 'if-consequent if-consequent)
(list 'if-alternative if-alternative)
(list 'begin? begin?)
(list 'begin-actions begin-actions)
(list 'last-exp? last-exp?)
(list 'first-exp first-exp)
(list 'rest-exps rest-exps)
(list 'application? application?)
(list 'operator operator)
(list 'operands operands)
(list 'no-operands? no-operands?)
(list 'first-operand first-operand)
(list 'rest-operands rest-operands)
;;operations in eceval-support.scm
(list 'true? true?)
(list 'false? false?) ;for compiled code
(list 'make-procedure make-procedure)
(list 'compound-procedure? compound-procedure?)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
(list 'extend-environment extend-environment)
(list 'lookup-variable-value lookup-variable-value)
(list 'set-variable-value! set-variable-value!)
(list 'define-variable! define-variable!)
(list 'primitive-procedure? primitive-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'prompt-for-input prompt-for-input)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'no-more-exps? no-more-exps?) ;for non-tail-recursive machine
(list 'get-global-environment get-global-environment)
;;for compiled code (also in eceval-support.scm)
(list 'make-compiled-procedure make-compiled-procedure)
(list 'compiled-procedure? compiled-procedure?)
(list 'compiled-procedure-entry compiled-procedure-entry)
(list 'compiled-procedure-env compiled-procedure-env)
))
(define eceval
(make-machine
'(exp env val proc argl continue unev
compapp ;*for compiled to call interpreted
)
eceval-operations
'(
// SECTION 5.4.4, as modified in 5.5.7
// *for compiled to call interpreted (from exercise 5.47)
(assign compapp (label compound-apply))
// *next instruction supports entry from compiler (from section 5.5.7)
(branch (label external-entry))
read-eval-print-loop
(perform (op initialize-stack))
(perform
(op prompt-for-input) (const ";;; EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (label eval-dispatch))
print-result
// **following instruction optional -- if use it, need monitored stack
(perform (op print-stack-statistics))
(perform
(op announce-output) (const ";;; EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
// *support for entry from compiler (from section 5.5.7)
external-entry
(perform (op initialize-stack))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (reg val))
unknown-expression-type
(assign val (const unknown-expression-type-error))
(goto (label signal-error))
unknown-procedure-type
(restore continue)
(assign val (const unknown-procedure-type-error))
(goto (label signal-error))
signal-error
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
// SECTION 5.4.1
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(goto (reg continue))
ev-quoted
(assign val (op text-of-quotation) (reg exp))
(goto (reg continue))
ev-lambda
(assign unev (op lambda-parameters) (reg exp))
(assign exp (op lambda-body) (reg exp))
(assign val (op make-procedure)
(reg unev) (reg exp) (reg env))
(goto (reg continue))
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore unev)
(restore env)
(assign argl (op empty-arglist))
(assign proc (reg val))
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
ev-appl-operand-loop
(save argl)
(assign exp (op first-operand) (reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-appl-last-arg))
(save env)
(save unev)
(assign continue (label ev-appl-accumulate-arg))
(goto (label eval-dispatch))
ev-appl-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(assign unev (op rest-operands) (reg unev))
(goto (label ev-appl-operand-loop))
ev-appl-last-arg
(assign continue (label ev-appl-accum-last-arg))
(goto (label eval-dispatch))
ev-appl-accum-last-arg
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(restore proc)
(goto (label apply-dispatch))
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
// *next added to call compiled code from evaluator (section 5.5.7)
(test (op compiled-procedure?) (reg proc))
(branch (label compiled-apply))
(goto (label unknown-procedure-type))
// *next added to call compiled code from evaluator (section 5.5.7)
compiled-apply
(restore continue)
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(assign unev (op procedure-parameters) (reg proc))
(assign env (op procedure-environment) (reg proc))
(assign env (op extend-environment)
(reg unev) (reg argl) (reg env))
(assign unev (op procedure-body) (reg proc))
(goto (label ev-sequence))
// SECTION 5.4.2
ev-begin
(assign unev (op begin-actions) (reg exp))
(save continue)
(goto (label ev-sequence))
ev-sequence
(assign exp (op first-exp) (reg unev))
(test (op last-exp?) (reg unev))
(branch (label ev-sequence-last-exp))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-last-exp
(restore continue)
(goto (label eval-dispatch))
// SECTION 5.4.3
ev-if
(save exp)
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
(goto (label eval-dispatch))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
ev-assignment
(assign unev (op assignment-variable) (reg exp))
(save unev)
(assign exp (op assignment-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-assignment-1))
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform
(op set-variable-value!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
ev-definition
(assign unev (op definition-variable) (reg exp))
(save unev)
(assign exp (op definition-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform
(op define-variable!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
)))
'(EXPLICIT CONTROL EVALUATOR FOR COMPILER LOADED) |
0 | //
// LocalizationNetworkTest.swift
// LocalizationKit
//
// Created by Will Powell on 28/12/2017.
// Copyright © 2017 willpowell8. All rights reserved.
//
import XCTest
import LocalizationKit
class NetworkTest: XCTestCase {
override func setUp() {
super.setUp()
Localization.start(appKey: "407f3581-648e-4099-b761-e94136a6628d", live: false)
}
override func tearDown() {
super.tearDown()
}
func testAvailableLanguagesPerformance() {
self.measure {
Localization.availableLanguages({ (languages) in
self.stopMeasuring()
})
}
}
func testChangeLanguagesPerformance() {
self.measure {
Localization.availableLanguages { (languages) in
Localization.setLanguage(languages[0], {
Localization.setLanguage(languages[1], {
self.stopMeasuring()
})
})
}
}
}
}
|
0 | //
// TouchEventAggregator.swift
// CesiumKit
//
// Created by Ryan Walklin on 4/04/2015.
// Copyright (c) 2015 Test Toast. All rights reserved.
//
import UIKit
import MetalKit
protocol TouchEvent {}
struct PanEvent: TouchEvent {
let tapCount: Int
let startPosition: Cartesian2
let endPosition: Cartesian2
init (tapCount: Int, startPosition: Cartesian2, endPosition: Cartesian2) {
self.tapCount = tapCount
self.startPosition = startPosition
self.endPosition = endPosition
}
}
protocol EventAggregator {
func reset ()
}
class TouchEventAggregator: EventAggregator {
func reset() {
}
}
class TouchEventHandler: NSObject, UIGestureRecognizerDelegate {
/**
* A parameter in the range <code>[0, 1)</code> used to limit the range
* of various user inputs to a percentage of the window width/height per animation frame.
* This helps keep the camera under control in low-frame-rate situations.
* @type {Number}
* @default 0.1
*/
var maximumMovementRatio = 0.1
/**
* The minimum height the camera must be before picking the terrain instead of the ellipsoid.
* @type {Number}
* @default 150000.0
*/
var minimumPickingTerrainHeight = 150000.0
/**
* The minimum magnitude, in meters, of the camera position when zooming. Defaults to 20.0.
* @type {Number}
* @default 20.0
*/
var minimumZoomDistance = 20.0
/**
* The maximum magnitude, in meters, of the camera position when zooming. Defaults to positive infinity.
* @type {Number}
* @default {@link Number.POSITIVE_INFINITY}
*/
var maximumZoomDistance = Double.infinity
//private var _events = [TouchEvent]()
//private var _panStartPosition: Cartesian2? = nil
private var _panRecognizer: UIPanGestureRecognizer!
private var _pinchRecognizer: UIPinchGestureRecognizer!
private var _scene: Scene!
private var _view: MTKView!
// Constants, Make any of these public?*/
private var _zoomFactor = 5.0
private var _rotateFactor = 0.0
private var _rotateRateRangeAdjustment = 0.0
private var _maximumRotateRate = 1.77
private var _minimumRotateRate = 1.0 / 5000.0
/*this._translateFactor = 1.0;*/
private var _minimumZoomRate = 20.0
private var _maximumZoomRate = 5906376272000.0 // distance from the Sun to Pluto in meters.
init (scene: Scene, view: MTKView) {
_scene = scene
_view = view
super.init()
addRecognizers()
}
func addRecognizers () {
_view.isUserInteractionEnabled = true
_view.isMultipleTouchEnabled = true
//var tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
_panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TouchEventHandler.handlePanGesture(_:)))
_panRecognizer.delegate = self
_view.addGestureRecognizer(_panRecognizer)
_pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(TouchEventHandler.handlePinchGesture(_:)))
_pinchRecognizer.delegate = self
_view.addGestureRecognizer(_pinchRecognizer)
}
func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
let location = recognizer.location(in: _view)
let offset = recognizer.translation(in: _view)
var event: TouchEvent? = nil
switch recognizer.state {
//case .Began:
//println("panstart, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
/*event = PanStartEvent(
tapCount: recognizer.numberOfTouches(),
startPosition: [Cartesian2(x: Double(location.x), y: Double(location.y))])*/
case .changed:
//println("panchanged, x: \(location.x) - \(offset.x), y: \(location.y) - \(offset.y), fingers: \(recognizer.numberOfTouches())")
var movement = MouseMovement()
movement.startPosition = Cartesian2(x: Double((location.x - offset.x) * _view.contentScaleFactor), y: Double((location.y - offset.y) * _view.contentScaleFactor))
movement.endPosition = Cartesian2(x: Double(location.x * _view.contentScaleFactor), y: Double(location.y * _view.contentScaleFactor))
//let view = _view as! MetalView
//dispatch_async(view.renderQueue, {
self._scene.screenSpaceCameraController.spin3D(movement.startPosition, movement: movement)
//})
/*event = PanMoveEvent(
tapCount: recognizer.numberOfTouches(),
startPosition: Cartesian2(x: Double(location.x), y: Double(location.y)),
endPosition: Cartesian2(x: Double(location.x + offset.x), y: Double(location.y + offset.y)))*/
//case .Ended:
//println("panended, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
// do velocity here
//globe?.eventHandler.handlePanEnd(Cartesian2(x: Double(location.x), y: Double(location.y)))
//let event = PanEndEvent(tapCount: recognizer.numberOfTouches())
//case .Cancelled:
//println("pancancelled, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
default:
return
}
recognizer.setTranslation(CGPoint.zero, in: _view)
/*if let touchHandler = globe?.eventAggregator as? TouchEventAggregator {
touchHander.addEvent(event)
}*/
}
func handlePinchGesture(_ recognizer: UIPinchGestureRecognizer) {
let fingerOne = recognizer.location(ofTouch: 0, in: _view)
/*let fingerTwo = recognizer.locationOfTouch(1, inView: view)
let diff = Cartesian2(x: Double(fingerOne.x), y: Double(fingerOne.x)).distance(Cartesian2(x: Double(fingerTwo.x), y: Double(fingerTwo.x)))*/
switch recognizer.state {
//case .Began:
//println("pinchstart, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
//globe?.eventHandler.handlePanStart(Cartesian2(x: Double(location.x), y: Double(location.y)))
case .changed:
//println("pinchchanged, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
//let view = _view as! MetalView
let scale = Double(recognizer.scale)
recognizer.scale = 1
//dispatch_async(view.renderQueue, {
self.zoomToPosition(Cartesian2(x: Double(fingerOne.x), y: Double(fingerOne.y)), scale: scale)
//})
//globe?.eventHandler.handlePanMove(Cartesian2(x: Double(location.x), y: Double(location.y)))
//case .Ended:
//println("pinchended, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
//globe?.eventHandler.handlePanEnd(Cartesian2(x: Double(location.x), y: Double(location.y)))
//case .Cancelled:
//println("pinchcancelled, x: \(location.x), y: \(location.y), fingers: \(recognizer.numberOfTouches())")
default:
return
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == _panRecognizer && otherGestureRecognizer == _pinchRecognizer {
return true
}
return false
}
// MARK: Zoom
func zoomToPosition (_ position: Cartesian2, scale: Double) {
let ray = _scene.camera.getPickRay(position)
var intersection: Cartesian3? = nil
let height = _scene.globe.ellipsoid.cartesianToCartographic(_scene.camera.position)!.height
if height < minimumPickingTerrainHeight {
intersection = _scene.globe.pick(ray, scene: _scene)
}
var distance: Double
if intersection != nil {
distance = ray.origin.distance(intersection!)
} else {
distance = height
}
let newDistance = distance * scale
let diff = newDistance - distance
/*let unitPosition = _scene.camera.position.normalize()
let unitPositionDotDirection = unitPosition.dot(_scene.camera.direction)
var distanceMeasure = distance
//handleZoom(startPosition, movement: movement, zoomFactor: _zoomFactor, distanceMeasure: distance, unitPositionDotDirection: unitPosition.dot(_scene.camera.direction))
var percentage = 1.0
//if unitPositionDotDirection != nil {
percentage = Math.clamp(abs(unitPositionDotDirection), min: 0.25, max: 1.0)
//}
// distanceMeasure should be the height above the ellipsoid.
// The zoomRate slows as it approaches the surface and stops minimumZoomDistance above it.
let minHeight = minimumZoomDistance * percentage
var maxHeight = maximumZoomDistance
let minDistance = distanceMeasure - minHeight
var zoomRate = _zoomFactor * minDistance
zoomRate = Math.clamp(zoomRate, min: _minimumZoomRate, max: _maximumZoomRate)
/*let diff = movement.endPosition.y - movement.startPosition.y
var rangeWindowRatio = diff / Double(_scene.drawableHeight)*/
//var rangeWindowRatio = //min(scale, maximumMovementRatio)
distance *= scale
if distance > 0.0 && abs(distanceMeasure - minHeight) < 1.0 {
return
}
if distance < 0.0 && abs(distanceMeasure - maxHeight) < 1.0 {
return
}
if distanceMeasure - distance < minHeight {
distance = distanceMeasure - minHeight - 1.0
} else if distanceMeasure - distance > maxHeight {
distance = distanceMeasure - maxHeight
}*/
_scene.camera.zoomIn(diff)
}
func appendEvent(_ event: TouchEvent) {
//_events.append(event)
}
func reset () {
//_events.removeAll()
}
}
|
0 | //
// 17.11.swift
// Leetcode-Swift
//
// Created by 95cc on 2022/6/2.
//
import Foundation
/*
面试题 17.11. 单词距离 (中等)
https://leetcode.cn/problems/find-closest-lcci/
*/
class Solution_17_11 {
// MARK: - 一次遍历
func findClosest(_ words: [String], _ word1: String, _ word2: String) -> Int {
if words.isEmpty {
return -1
}
var index1 = -1
var index2 = -1
var ans = words.count
for (index, word) in words.enumerated() {
if word == word1 {
index1 = index
} else if word == word2 {
index2 = index
}
if index1 != -1 && index2 != -1 {
ans = min(ans, abs(index1 - index2))
}
}
return ans
}
// MARK: - 双指针
func findClosest_v2(_ words: [String], _ word1: String, _ word2: String) -> Int {
if words.isEmpty {
return Int.max
}
var indexesOfWord1 = [Int]()
var indexesOfWord2 = [Int]()
for (index, word) in words.enumerated() {
if word == word1 {
indexesOfWord1.append(index)
} else if (word == word2) {
indexesOfWord2.append(index)
}
}
if indexesOfWord1.isEmpty || indexesOfWord2.isEmpty {
return Int.max
}
var ans = Int.max
var p0 = 0, p1 = 0
while p0 < indexesOfWord1.count && p1 < indexesOfWord2.count {
let index0 = indexesOfWord1[p0]
let index1 = indexesOfWord2[p1]
ans = min(ans, abs(index0 - index1))
if index0 >= index1 {
p1 += 1
} else {
p0 += 1
}
}
return ans
}
}
|
0 | /*
* find-in-drives.swift
* officectl
*
* Created by François Lamboley on 26/06/2020.
*/
import Foundation
import ArgumentParser
import Vapor
import OfficeKit
import SemiSingleton
import URLRequestOperation
struct FindInDrivesCommand : ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "find-in-drives",
abstract: "Find the given file or folder in all users drives."
)
@OptionGroup()
var globalOptions: OfficectlRootCommand.Options
@ArgumentParser.Option(help: "The id of the Google service to use to do the search. Required if there are more than one Google service in officectl conf, otherwise the only Google service is used.")
var serviceId: String?
@ArgumentParser.Argument()
var filename: String
func run() throws {
let config = try OfficectlConfig(globalOptions: globalOptions, serverOptions: nil)
try Application.runSync(officectlConfig: config, configureHandler: { _ in }, vaporRun)
}
/* We don’t technically require Vapor, but it’s convenient. */
func vaporRun(_ context: CommandContext) throws -> EventLoopFuture<Void> {
let app = context.application
let officeKitConfig = app.officeKitConfig
let eventLoop = try app.services.make(EventLoop.self)
let googleConfig: GoogleServiceConfig = try officeKitConfig.getServiceConfig(id: serviceId)
_ = try nil2throw(googleConfig.connectorSettings.userBehalf, "Google User Behalf")
let googleConnector = try GoogleJWTConnector(key: googleConfig.connectorSettings)
return googleConnector
.connect(scope: SearchGoogleUsersOperation.scopes, eventLoop: eventLoop)
.flatMap{ _ -> EventLoopFuture<[GoogleUserAndDest]> in
GoogleUserAndDest.fetchListToBackup(
googleConfig: googleConfig, googleConnector: googleConnector,
usersFilter: nil, disabledUserSuffix: nil,
downloadsDestinationFolder: URL(fileURLWithPath: "/tmp/not_used", isDirectory: true), archiveDestinationFolder: nil,
skipIfArchiveFound: false, console: context.console, eventLoop: eventLoop
)
}
.flatMap{ usersAndDest -> EventLoopFuture<[String]> in
let futureResults = usersAndDest.map{ self.futureSearchResults(for: $0, searchedString: self.filename, mainConnector: googleConnector, eventLoop: eventLoop) }
return EventLoopFuture.reduce(into: [String](), futureResults, on: eventLoop, { (currentResult, newResult) in
if let u = newResult {currentResult.append(u)}
})
}
.map{ searchResults in
context.console.info("\(searchResults)")
}
.transform(to:())
}
private func futureSearchResults(for userAndDest: GoogleUserAndDest, searchedString: String, mainConnector: GoogleJWTConnector, eventLoop: EventLoop) -> EventLoopFuture<String?> {
let connector = GoogleJWTConnector(from: mainConnector, userBehalf: userAndDest.user.primaryEmail.stringValue)
return connector.connect(scope: driveROScope, eventLoop: eventLoop)
.flatMap{ _ -> EventLoopFuture<GoogleDriveFilesList> in
var urlComponents = URLComponents(url: driveApiBaseURL.appendingPathComponent("files", isDirectory: false), resolvingAgainstBaseURL: false)!
urlComponents.queryItems = (urlComponents.queryItems ?? []) + [
URLQueryItem(name: "q", value: "name contains '\(searchedString.replacingOccurrences(of: #"'"#, with: #"\'"#))'") /* add " and trashed = true" to the query if needed */
]
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .customISO8601
decoder.keyDecodingStrategy = .useDefaultKeys
let op = AuthenticatedJSONOperation<GoogleDriveFilesList>(url: urlComponents.url!, authenticator: connector.authenticate, decoder: decoder)
return EventLoopFuture<GoogleDriveFilesList>.future(from: op, on: eventLoop)
}
.map{ filesList in
return (filesList.files?.map{ $0.id } ?? []).isEmpty ? nil : userAndDest.user.primaryEmail.stringValue
}
}
}
|
0 | //
// SortType.swift
// ecommerce-ios
//
// Created by Nguyen M. Tam on 21/05/2021.
//
enum SortType: Int, CaseIterable {
case new
case priceHighToLow
case priceLowToHigh
var title: String {
switch self {
case .new: return "New"
case .priceHighToLow, .priceLowToHigh: return "Price"
}
}
var subtitle: String {
switch self {
case .new: return ""
case .priceHighToLow: return "High to low"
case .priceLowToHigh: return "Low to high"
}
}
}
|
0 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "RunningProcessSize",
platforms: [
.macOS(.v10_13)
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "RunningProcessSize",
dependencies: []),
.testTarget(
name: "RunningProcessSizeTests",
dependencies: ["RunningProcessSize"]),
]
)
|
0 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class B<H,f{
class d<g{
class d<T>:d
class B{
protocol A{
struct A{
let:{{
}
struct A{
|
0 | //
// UITextViewTests.swift
// LocalizableUITests
//
// Created by Jan Weiß on 15.10.17.
// Copyright © 2017 Jan Weiß, Philipp Weiß. All rights reserved.
//
import XCTest
import LocalizableUI
class UITextViewTests: BaseTestCase {
func testLocalizableTextView() {
let textView = UITextView(frame: CGRect.zero, textContainer: nil, localizedKey: Constants.sampleStringKey)
XCTAssertEqual(textView.text, Constants.localizedSampleStringEn)
changeLanguage(to: .custom)
XCTAssertEqual(textView.text, Constants.localizedSampleStringCustom)
}
}
|
0 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{class B<T{struct a{class B<I{struct S<T where g:d{class A:B<T>
|
0 | //
// Extensions.swift
//
//
// Created by Eneko Alonso on 11/2/19.
//
import XCTest
extension XCTestCase {
/// Path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
/// Path to binary executable.
var binaryURL: URL {
return productsDirectory.appendingPathComponent("sourcedocs")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.