hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
623dc5f69e116b89e76a08599e145d797a835a74 | 770 | import XCTest
@testable import RazeCore
final class RazeColorTests: XCTestCase {
func testColorRedEqual() {
let color = RazeCore.Color.fromHexString("FF0000")
XCTAssertEqual(color, .red)
}
func testRazeColorsAreEqual() {
let color = RazeCore.Color.fromHexString("006736")
XCTAssertEqual(color, RazeCore.Color.razeColor)
}
func testSecondaryRazeColorAreEqual() {
let color = RazeCore.Color.fromHexString("FCFFFD")
XCTAssertEqual(color, RazeCore.Color.secondaryRazeColor)
}
static var allTests = [
("testColorRedEqual", testColorRedEqual),
("testRazeColorsAreEqual", testRazeColorsAreEqual),
("testSecondaryRazeColorAreEqual", testSecondaryRazeColorAreEqual)
]
}
| 28.518519 | 74 | 0.697403 |
2ff84a847881a94cee8c4e6068a32923627a8006 | 986 | //
// OverlayContainerStateDiffer.swift
// DynamicOverlay
//
// Created by Gaétan Zanella on 23/07/2021.
// Copyright © 2021 Fabernovel. All rights reserved.
//
import Foundation
struct OverlayContainerStateDiffer {
struct Changes: OptionSet {
let rawValue: Int
static let layout = Changes(rawValue: 1 << 0)
static let index = Changes(rawValue: 1 << 1)
static let scrollView = Changes(rawValue: 1 << 2)
}
func diff(from previous: OverlayContainerState, to next: OverlayContainerState) -> Changes {
var changes: Changes = []
if previous.notchIndex != next.notchIndex {
changes.insert(.index)
}
// issue #21
// The scroll view depends on the content, we need to first for a potential new scroll view
// at each update
changes.insert(.scrollView)
if previous.layout != next.layout {
changes.insert(.layout)
}
return changes
}
}
| 27.388889 | 99 | 0.625761 |
1ec673e5d4cb9c2162344085acd6fe5dbfacbd9b | 724 | //
// BaseNodeController.swift
// TextureExamples
//
// Created by YYKJ0048 on 2021/7/7.
//
import UIKit
import RxSwift
import RxCocoa
import AsyncDisplayKit
class BaseNodeController: ASDKViewController<ASDisplayNode> {
let disposeBag = DisposeBag()
override init() {
super.init(node: ASDisplayNode())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
node.automaticallyRelayoutOnSafeAreaChanges = true
view.backgroundColor = .white
emptyBackBarButtonItem()
log.debug(self.className)
}
deinit {
log.debug(self.className)
}
}
| 19.567568 | 61 | 0.661602 |
64ad6569baccb10ee579aea67034bd7643d48d85 | 5,990 | //
// PasscodeCoordinator.swift
// WavesWallet-iOS
//
// Created by mefilt on 25/09/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import DomainLayer
protocol PasscodeCoordinatorDelegate: AnyObject {
func passcodeCoordinatorAuthorizationCompleted(wallet: DomainLayer.DTO.Wallet)
func passcodeCoordinatorVerifyAcccesCompleted(signedWallet: DomainLayer.DTO.SignedWallet)
func passcodeCoordinatorWalletLogouted()
}
final class PasscodeCoordinator: Coordinator {
enum BehaviorPresentation {
case push(NavigationRouter, dissmissToRoot: Bool)
case modal(Router)
var isPush: Bool {
switch self {
case .push:
return true
default:
return false
}
}
}
var childCoordinators: [Coordinator] = []
weak var parent: Coordinator?
private let mainNavigationRouter: NavigationRouter
private let kind: PasscodeTypes.DTO.Kind
private let behaviorPresentation: BehaviorPresentation
weak var delegate: PasscodeCoordinatorDelegate?
init(kind: PasscodeTypes.DTO.Kind, behaviorPresentation: BehaviorPresentation) {
self.kind = kind
self.behaviorPresentation = behaviorPresentation
switch behaviorPresentation {
case .modal:
mainNavigationRouter = NavigationRouter(navigationController: CustomNavigationController())
case .push(let router, _):
mainNavigationRouter = router
}
}
func start() {
let vc = PasscodeModuleBuilder(output: self)
.build(input: .init(kind: kind, hasBackButton: behaviorPresentation.isPush))
switch behaviorPresentation {
case .modal(let router):
mainNavigationRouter.pushViewController(vc)
router.present(mainNavigationRouter.navigationController, animated: true, completion: nil)
case .push:
mainNavigationRouter.pushViewController(vc, animated: true) { [weak self] in
guard let self = self else { return }
self.removeFromParentCoordinator()
}
}
}
private func dissmiss() {
removeFromParentCoordinator()
switch behaviorPresentation {
case .modal(let router):
router.dismiss(animated: true, completion: nil)
case .push(_, let dissmissToRoot):
if dissmissToRoot {
self.mainNavigationRouter.popToRootViewController(animated: true)
} else {
self.mainNavigationRouter.popViewController()
}
}
}
}
// MARK: PasscodeOutput
extension PasscodeCoordinator: PasscodeModuleOutput {
func passcodeVerifyAccessCompleted(_ wallet: DomainLayer.DTO.SignedWallet) {
delegate?.passcodeCoordinatorVerifyAcccesCompleted(signedWallet: wallet)
}
func passcodeTapBackButton() {
dissmiss()
}
func passcodeLogInCompleted(passcode: String, wallet: DomainLayer.DTO.Wallet, isNewWallet: Bool) {
if isNewWallet, BiometricType.enabledBiometric != .none {
let vc = UseTouchIDModuleBuilder(output: self)
.build(input: .init(passcode: passcode, wallet: wallet))
mainNavigationRouter.present(vc, animated: true, completion: nil)
} else {
delegate?.passcodeCoordinatorAuthorizationCompleted(wallet: wallet)
dissmiss()
}
}
func passcodeUserLogouted() {
delegate?.passcodeCoordinatorWalletLogouted()
dissmiss()
}
func passcodeLogInByPassword() {
switch kind {
case .verifyAccess(let wallet):
showAccountPassword(kind: .verifyAccess(wallet))
case .logIn(let wallet):
showAccountPassword(kind: .logIn(wallet))
case .changePasscode(let wallet):
showAccountPassword(kind: .verifyAccess(wallet))
case .setEnableBiometric(_, let wallet):
showAccountPassword(kind: .verifyAccess(wallet))
case .changePassword(let wallet, _, _):
showAccountPassword(kind: .verifyAccess(wallet))
default:
break
}
}
func showAccountPassword(kind: AccountPasswordTypes.DTO.Kind) {
let vc = AccountPasswordModuleBuilder(output: self)
.build(input: .init(kind: kind))
mainNavigationRouter.pushViewController(vc)
}
}
// MARK: AccountPasswordModuleOutput
extension PasscodeCoordinator: AccountPasswordModuleOutput {
func accountPasswordVerifyAccess(signedWallet: DomainLayer.DTO.SignedWallet, password: String) {
let vc = PasscodeModuleBuilder(output: self)
.build(input: .init(kind: .changePasscodeByPassword(signedWallet.wallet,
password: password),
hasBackButton: true))
mainNavigationRouter.pushViewController(vc)
}
func accountPasswordAuthorizationCompleted(wallet: DomainLayer.DTO.Wallet, password: String) {
let vc = PasscodeModuleBuilder(output: self)
.build(input: .init(kind: .changePasscodeByPassword(wallet,
password: password),
hasBackButton: true))
mainNavigationRouter.pushViewController(vc)
}
}
// MARK: UseTouchIDModuleOutput
extension PasscodeCoordinator: UseTouchIDModuleOutput {
func userSkipRegisterBiometric(wallet: DomainLayer.DTO.Wallet) {
mainNavigationRouter.dismiss(animated: true, completion: nil)
delegate?.passcodeCoordinatorAuthorizationCompleted(wallet: wallet)
dissmiss()
}
func userRegisteredBiometric(wallet: DomainLayer.DTO.Wallet) {
mainNavigationRouter.dismiss(animated: true, completion: nil)
delegate?.passcodeCoordinatorAuthorizationCompleted(wallet: wallet)
dissmiss()
}
}
| 30.876289 | 103 | 0.652087 |
5b1415457d0a6e0eb00788876c6faf6b71eada24 | 2,845 | //
// UserDefaults+.swift
// UserDefaults
//
// Created by Tatsuya Tanaka on 20170526.
// Copyright © 2017年 tattn. All rights reserved.
//
import Foundation
// MARK:- UserDefaults.Key
public extension UserDefaults {
struct Key: RawRepresentable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
}
// MARK:- getter
public extension UserDefaults {
func get<T: Codable>(_ type: T.Type = T.self, for key: Key) -> T? {
guard let data = data(for: key) else { return nil }
return try? JSONDecoder().decode(T.self, from: data)
}
func object<T>(_ type: T.Type = T.self, for key: Key) -> T? {
return object(forKey: key.rawValue) as? T
}
func object(for key: Key) -> Any? {
return object(forKey: key.rawValue)
}
func string(for key: Key) -> String? {
return string(forKey: key.rawValue)
}
func array<T>(_ elementType: T, for key: Key) -> [T]? {
return array(forKey: key.rawValue) as? [T]
}
func array(for key: Key) -> [Any]? {
return array(forKey: key.rawValue)
}
func dictionary(for key: Key) -> [String : Any]? {
return dictionary(forKey: key.rawValue)
}
func data(for key: Key) -> Data? {
return data(forKey: key.rawValue)
}
func url(for key: Key) -> URL? {
return url(forKey: key.rawValue)
}
func integer(for key: Key) -> Int {
return integer(forKey: key.rawValue)
}
func float(for key: Key) -> Float {
return float(forKey: key.rawValue)
}
func double(for key: Key) -> Double {
return double(forKey: key.rawValue)
}
func bool(for key: Key) -> Bool {
return bool(forKey: key.rawValue)
}
}
// MARK:- setter
public extension UserDefaults {
func set<T: Codable>(_ value: T, for key: Key) {
guard let data = try? JSONEncoder().encode(value) else { return }
set(data, forKey: key.rawValue)
}
func set(_ value: Any?, for key: Key) {
set(value, forKey: key.rawValue)
}
func set(_ url: URL?, for key: Key) {
set(url, forKey: key.rawValue)
}
func set(_ value: Int, for key: Key) {
set(value, forKey: key.rawValue)
}
func set(_ value: Float, for key: Key) {
set(value, forKey: key.rawValue)
}
func set(_ value: Double, for key: Key) {
set(value, forKey: key.rawValue)
}
func set(_ value: Bool, for key: Key) {
set(value, forKey: key.rawValue)
}
}
// MARK:- other
public extension UserDefaults {
func remove(for key: Key) {
removeObject(forKey: key.rawValue)
}
}
| 22.943548 | 73 | 0.575044 |
086a6d5c82e926d774d04451f7b7cde70c58d885 | 1,623 | //
// MagicRoad.swift
// Spiral
//
// Created by 杨萧玉 on 15/10/7.
// Copyright © 2015年 杨萧玉. All rights reserved.
//
import SpriteKit
import GameplayKit
class MagicRoad: SKNode {
init(graph: GKGridGraph<GKGridGraphNode>, position: vector_int2){
let roadWidth: CGFloat = 2
super.init()
let left = graph.node(atGridPosition: vector_int2(position.x - 1, position.y))
let right = graph.node(atGridPosition: vector_int2(position.x + 1, position.y))
let up = graph.node(atGridPosition: vector_int2(position.x, position.y + 1))
let down = graph.node(atGridPosition: vector_int2(position.x, position.y - 1))
if left != nil && right != nil && up == nil && down == nil {
// 一
if let magic = SKEmitterNode(fileNamed: "magic") {
magic.particlePositionRange = CGVector(dx: mazeCellWidth, dy: roadWidth)
addChild(magic)
}
}
else if up != nil && down != nil && left == nil && right == nil {
// |
if let magic = SKEmitterNode(fileNamed: "magic") {
magic.particlePositionRange = CGVector(dx: roadWidth, dy: mazeCellWidth)
addChild(magic)
}
}
else {
//丄丅卜十...
if let magic = SKEmitterNode(fileNamed: "magic") {
magic.particlePositionRange = CGVector(dx: roadWidth, dy: roadWidth)
addChild(magic)
}
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.8125 | 88 | 0.564387 |
8a45800b34776e633d509d5068e53a30bfbd3dce | 1,788 | //
// +-+-+-+-+-+-+
// |y|o|o|n|i|t|
// +-+-+-+-+-+-+
//
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Yoonit Handshake lib for iOS applications |
// | Haroldo Teruya @ Yoonit-Labs 2021 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
import UIKit
import WultraSSLPinning
@objc
public class Handshake: NSObject {
@objc
public var handshakeListener: HandshakeListener?
@objc
public func updateFingerprints(
_ publicKey: String,
_ serviceUrl: String
) {
var certStore: CertStore? = nil
if let url = URL(string: serviceUrl) {
let configuration = CertStoreConfiguration(
serviceUrl: url,
publicKey: publicKey
)
certStore = CertStore.powerAuthCertStore(configuration: configuration)
} else {
self.handshakeListener?.onResult(HandshakeResult.INVALID_URL_SERVICE)
}
certStore?.update { (result, error) in
switch result {
case .ok:
self.handshakeListener?.onResult(HandshakeResult.OK)
case .storeIsEmpty:
self.handshakeListener?.onResult(HandshakeResult.STORE_IS_EMPTY)
case .networkError:
self.handshakeListener?.onResult(HandshakeResult.NETWORK_ERROR)
case .invalidData:
self.handshakeListener?.onResult(HandshakeResult.INVALID_DATA)
case .invalidSignature:
self.handshakeListener?.onResult(HandshakeResult.INVALID_SIGNATURE)
}
}
}
}
| 30.305085 | 95 | 0.495526 |
7ae7db42428e6a2c3b79ed55b0d0aa1668c89e1b | 4,025 | //
// Helper.swift
//
//
// Created by Christian Treffs on 31.08.19.
//
extension Array {
public subscript<R>(representable: R) -> Element where R: RawRepresentable, R.RawValue: FixedWidthInteger {
get { self[Int(representable.rawValue)] }
set { self[Int(representable.rawValue)] = newValue }
}
}
/// Compute the prefix sum of `seq`.
public func scan<
S: Sequence, U
>(_ seq: S, _ initial: U, _ combine: (U, S.Iterator.Element) -> U) -> [U] {
var result: [U] = []
result.reserveCapacity(seq.underestimatedCount)
var runningResult = initial
for element in seq {
runningResult = combine(runningResult, element)
result.append(runningResult)
}
return result
}
/// https://oleb.net/blog/2016/10/swift-array-of-c-strings/
// from: https://forums.swift.org/t/bridging-string-to-const-char-const/3804/4
public func withArrayOfCStrings<R>(
_ args: [String],
_ body: ([UnsafePointer<CChar>?]) -> R) -> R {
let argsCounts = Array(args.map {
$0.utf8.count + 1
})
let argsOffsets = [0] + scan(argsCounts, 0, +)
let argsBufferSize = argsOffsets.last!
var argsBuffer: [UInt8] = []
argsBuffer.reserveCapacity(argsBufferSize)
for arg in args {
argsBuffer.append(contentsOf: arg.utf8)
argsBuffer.append(0)
}
return argsBuffer.withUnsafeBufferPointer {
argsBuffer in
let ptr = UnsafeRawPointer(argsBuffer.baseAddress!)
.bindMemory(to: CChar.self, capacity: argsBuffer.count)
var cStrings: [UnsafePointer<CChar>?] = argsOffsets.map {
ptr + $0
}
cStrings[cStrings.count - 1] = nil
return body(cStrings)
}
}
public func withArrayOfCStringsBasePointer<Result>(_ strings: [String], _ body: (UnsafePointer<UnsafePointer<Int8>?>?) -> Result) -> Result {
withArrayOfCStrings(strings) { arrayPtr in
arrayPtr.withUnsafeBufferPointer { bufferPtr in
body(bufferPtr.baseAddress)
}
}
}
extension Optional where Wrapped == String {
@inlinable public func withOptionalCString<Result>(_ body: (UnsafePointer<Int8>?) throws -> Result) rethrows -> Result {
guard let string = self else {
return try body(nil)
}
return try string.withCString(body)
}
}
/// https://forums.developer.apple.com/thread/72120
/// https://forums.swift.org/t/fixed-size-array-hacks/32962/4
/// https://github.com/stephentyrone/swift-numerics/blob/static-array/Sources/StaticArray/StaticArray.swift
public enum CArray<T> {
@discardableResult
@_transparent
public static func write<C, O>(_ cArray: inout C, _ body: (UnsafeMutableBufferPointer<T>) throws -> O) rethrows -> O {
try withUnsafeMutablePointer(to: &cArray) {
try body(UnsafeMutableBufferPointer<T>(start: UnsafeMutableRawPointer($0).assumingMemoryBound(to: T.self),
count: (MemoryLayout<C>.stride / MemoryLayout<T>.stride)))
}
}
@discardableResult
@_transparent
public static func read<C, O>(_ cArray: C, _ body: (UnsafeBufferPointer<T>) throws -> O) rethrows -> O {
try withUnsafePointer(to: cArray) {
try body(UnsafeBufferPointer<T>(start: UnsafeRawPointer($0).assumingMemoryBound(to: T.self),
count: (MemoryLayout<C>.stride / MemoryLayout<T>.stride)))
}
}
}
/// Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++.
public func IM_OFFSETOF<T>(_ member: PartialKeyPath<T>) -> Int {
MemoryLayout<T>.offset(of: member)!
}
/// Size of a static C-style array. Don't use on pointers!
public func IM_ARRAYSIZE<T>(_ cTupleArray: T) -> Int {
//#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
let mirror = Mirror(reflecting: cTupleArray)
precondition(mirror.displayStyle == Mirror.DisplayStyle.tuple, "IM_ARRAYSIZE may only be applied to C array tuples")
return mirror.children.count
}
| 36.926606 | 141 | 0.649193 |
7a6a87a8b0660bc07bc82b02628c4a2f884f46c6 | 1,024 | //
// AppDelegate.swift
// AdjustMLImage
//
// Created by 국윤수 on 06/12/2018.
// Copyright © 2018 국윤수. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let initialViewController = MainViewController()
let nav = UINavigationController(rootViewController: initialViewController)
self.window?.rootViewController = nav
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| 21.787234 | 77 | 0.775391 |
4618ea4c70ea8b53eb4fc7e5122f9588ea14d2ef | 7,966 | //
// SDetailViewController.swift
// Pipa
//
// Created by 黄景川 on 16/12/8.
// Copyright © 2016年 Pipa. All rights reserved.
//
import UIKit
import Alamofire
class SDetailViewController: UIViewController,UIScrollViewDelegate {
//空间详情
//上级传递
var detailDic:NSDictionary!
//当前加载
var spaceDetail = NSDictionary()
//滑动视图
var detailScrollView:UIScrollView!
//内容视图
var contentView:UIView!
//空间照片
var spaceImageView = UIImageView()
//空间名
var titleLabel = UILabel()
//空间大小
var spaceSizeLabel = UILabel()
//空间最大容纳人数
var spacePeopleNumberLabel = UILabel()
//空间位置
var spacelocationLabel = UILabel()
//空间详情
var detailLabel = UILabel()
//点击租用
var rentBtn = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "空间详情"
createUI()
getSpaceDetail()
}
func getSpaceDetail(){
Alamofire.request(SEVER_IP + "url",
method: .get).responseJSON { (response) in
let arr:Array<NSDictionary> = response.result.value as! Array
self.spaceDetail = arr[0]
self.titleLabel.text = (self.detailDic["name"] as! String)
self.spaceSizeLabel.text = "空间大小:\(self.spaceDetail["area"]!) ㎡"
self.spacePeopleNumberLabel.text = "空间最大容纳人数:\(self.spaceDetail["max_capacity"]!) 人"
self.spacelocationLabel.text = "空间位置:"+(self.spaceDetail["building_name"] as? String)!+" \(self.spaceDetail["room"]!)"
}
}
func createUI(){
let detail = detailDic["details"] as? String
detailScrollView = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
detailScrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: 0)
detailScrollView.backgroundColor = BG_COLOR
detailScrollView.delegate = self
self.view.addSubview(detailScrollView)
detailScrollView.snp.makeConstraints { (make) in
make.top.bottom.left.right.equalToSuperview().offset(0)
}
contentView = UIView.init()
contentView.backgroundColor = BG_COLOR
detailScrollView.addSubview(contentView)
contentView.snp.makeConstraints { (make) in
make.top.bottom.right.left.equalToSuperview().offset(0)
make.width.height.equalTo(self.view)
}
let url = URL(string: SEVER_IP + (detailDic["headimg"] as! String))
spaceImageView.contentMode = UIViewContentMode.scaleToFill
spaceImageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "imgbad"), options: nil, progressBlock: nil, completionHandler: nil)
spaceImageView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT/3)
spaceImageView.backgroundColor = .white
contentView.addSubview(spaceImageView)
spaceImageView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(contentView).offset(0)
make.height.equalTo(SCREEN_HEIGHT/3)
}
titleLabel = Utilitys.createLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0), text: "", fontSize: 18, textColor: NAV_COLOR)
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(spaceImageView.snp.bottom).offset(15)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.height.equalTo(20)
}
spaceSizeLabel = Utilitys.createLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0), text: "", fontSize: 12, textColor: .gray)
contentView.addSubview(spaceSizeLabel)
spaceSizeLabel.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.height.equalTo(15)
}
spacelocationLabel = Utilitys.createLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0), text: "", fontSize: 12, textColor: .gray)
contentView.addSubview(spacelocationLabel)
spacelocationLabel.snp.makeConstraints { (make) in
make.top.equalTo(spaceSizeLabel.snp.bottom).offset(5)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.height.equalTo(15)
}
spacePeopleNumberLabel = Utilitys.createLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0), text: "", fontSize: 12, textColor: .gray)
contentView.addSubview(spacePeopleNumberLabel)
spacePeopleNumberLabel.snp.makeConstraints { (make) in
make.top.equalTo(spacelocationLabel.snp.bottom).offset(5)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.height.equalTo(15)
}
let strHeight = heightSizeWithContent(content: detail!,widthSize:SCREEN_WIDTH-20, fontSize: 18).height
detailLabel = Utilitys.createLabel(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH-20, height:strHeight+20), text: detail!, fontSize: 14, textColor: NAV_COLOR, textAlignment: .left, numberOfLines: 0)
//解决多行显示不全的问题
detailLabel.adjustsFontSizeToFitWidth = true
let attributedString = NSMutableAttributedString.init(string: detail!)
let paragraphStyle = NSMutableParagraphStyle.init()
paragraphStyle.lineSpacing = 6
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, detail!.characters.count))
detailLabel.attributedText = attributedString
contentView.addSubview(detailLabel)
detailLabel.snp.makeConstraints { (make) in
make.top.equalTo(spacePeopleNumberLabel.snp.bottom).offset(10)
make.left.equalToSuperview().offset(10)
make.height.equalTo(strHeight)
make.right.equalToSuperview().offset(-10)
}
rentBtn = Utilitys.createBtnString(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH-20, height: 40), title: "租用空间", titleColor: .white, titleSize: 16, target: self, action: #selector(rentSpace(sender:)), touch: .touchDown)
rentBtn.isHidden = true
contentView.addSubview(rentBtn)
rentBtn.snp.makeConstraints { (make) in
make.top.equalTo(detailLabel.snp.bottom).offset(20)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.height.equalTo(40)
}
contentView.snp.removeConstraints()
contentView.snp.makeConstraints { (make) in
make.top.bottom.right.left.equalToSuperview().offset(0)
make.width.equalTo(self.view)
make.bottom.equalTo(rentBtn.snp.bottom).offset(20)
}
}
func rentSpace(sender:UIButton){
self.performSegue(withIdentifier: "showOrder", sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 40.436548 | 227 | 0.618253 |
d5bb7e792cca8ed64aec1d7ba13e57180592af55 | 1,472 | import Elements
#if canImport(UIKit)
import UIKit
public final class DefaultTableViewCell: UITableViewCell {
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
}
}
public final class SubtitleTableViewCell: UITableViewCell {
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
}
public final class ValueTableViewCell: UITableViewCell {
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
}
public final class ValueAltTableViewCell: UITableViewCell {
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value2, reuseIdentifier: reuseIdentifier)
}
}
#endif
| 30.040816 | 86 | 0.704484 |
b972ec297d8b72a095ad279d691334e3803ee1e7 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
f( [Void : {
protocol a {
class B {
{
}
{
}
struct A {
extension String {
class
case ,
| 15.529412 | 87 | 0.704545 |
e9292f55ab2abe968c0150fd404af375a7cc90a7 | 687 | //
// SwitchCell.swift
// Yelp
//
// Created by Daniel Moreh on 2/18/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol SwitchCellDelegate {
optional func switchCell(switchCell: SwitchCell, didChangeValue value: Bool)
}
class SwitchCell: UITableViewCell {
@IBOutlet weak var switchLabel: UILabel!
@IBOutlet weak var onSwitch: UISwitch!
weak var delegate: SwitchCellDelegate?
override func awakeFromNib() {
onSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: .ValueChanged)
}
func switchValueChanged() {
self.delegate?.switchCell?(self, didChangeValue: onSwitch.on)
}
}
| 22.9 | 95 | 0.710335 |
75fd712888b9f1a2eba64be486385dad9bd393dc | 2,542 | //
// ColorExtensions.swift
// Markit
//
// Created by patr0nus on 2018/6/7.
//
import Foundation
//credit: https://github.com/thii/SwiftHEXColors/blob/master/Sources/SwiftHEXColors.swift
#if canImport(UIKit)
import UIKit
fileprivate typealias Color = UIColor
#elseif canImport(Cocoa)
import Cocoa
fileprivate typealias Color = NSColor
#endif
private extension Int {
func duplicate4bits() -> Int {
return (self << 4) + self
}
}
fileprivate let colorCases: [String: Color] = [
"red": .red,
"white": .white
]
fileprivate func color(fromLiteral literal: String) throws -> Color {
guard literal.hasPrefix("#") else {
throw Compiler.Error.invalidLiteral(literal, className: "Color")
}
var hexString = literal.dropFirst()
var alpha: Float = 1
if let alphaDelimier = hexString.index(of: "@") {
guard let alphaStartIndex = hexString.index(alphaDelimier, offsetBy: 1, limitedBy: hexString.endIndex) else {
throw Compiler.Error.invalidLiteral(literal, className: "Color")
}
guard let theAlpha = Float(hexString[alphaStartIndex..<hexString.endIndex]) else {
throw Compiler.Error.invalidLiteral(literal, className: "Color")
}
alpha = theAlpha
hexString = hexString[..<alphaDelimier]
}
if hexString.count == 3, let hexValue = Int(hexString, radix: 16) {
return Color(red: CGFloat(((hexValue & 0xF00) >> 8).duplicate4bits()) / 255.0,
green: CGFloat(((hexValue & 0x0F0) >> 4).duplicate4bits()) / 255.0,
blue: CGFloat(((hexValue & 0x00F) >> 0).duplicate4bits()) / 255.0,
alpha: CGFloat(alpha))
}
if hexString.count == 6, let hexValue = Int(hexString, radix: 16) {
return Color(red: CGFloat((hexValue & 0xFF0000) >> 16 ) / 255.0,
green: CGFloat((hexValue & 0x00FF00) >> 8 ) / 255.0,
blue: CGFloat((hexValue & 0x0000FF) >> 0 ) / 255.0,
alpha: CGFloat(alpha))
}
throw Compiler.Error.invalidLiteral(literal, className: "Color")
}
let ColorExtensions: [String: [ClassExtension]] = [
Color.self.className(): [
.caseLiteralConvertor(type: Color.self, cases: colorCases, fallbackConvertor: color(fromLiteral:))
],
"CGColor": [
.caseLiteralConvertor(type: CGColor.self, cases: colorCases.mapValues { $0.cgColor }) {
try color(fromLiteral: $0).cgColor
}
]
]
| 32.589744 | 117 | 0.611723 |
2f219892178d44b485ad75c94c467211c9db7010 | 5,199 | //
// NewMovementView.swift
//
//
// Created by Bastián Véliz Vega on 17-10-20.
//
import AccountsUI
import DataManagement
import DependencyResolver
import NewMovement
import SwiftUI
/// New movement view
public struct NewMovementView: View {
@ObservedObject var viewModel: NewMovementViewModel
@EnvironmentObject var resolver: DependencyResolver
private var dataModel: NewMovementViewDataModel
private var movement: Movement
private let isIncome: Bool
/// Default initializer
/// - Parameters:
/// - dataModel: data used to populate the view
/// - movement: movement used to edit its data.
/// - isIncome: indicates if view must be prepared for an income
/// - onEnd: called when movement edition ends
public init(dataModel: NewMovementViewDataModel,
movement: Movement,
isIncome: Bool,
onEnd: @escaping () -> Void)
{
self.dataModel = dataModel
self.movement = movement
self.isIncome = isIncome
let model = NewMovementViewInternalDataModel(movement: movement)
let initialViewModel = NewMovementViewModel(model: model,
dataSource: dataModel.dataSource,
incomeData: dataModel.incomeData,
expenditureData: dataModel.expenditureData,
onEnd: onEnd)
initialViewModel.isIncome = isIncome
initialViewModel.isEdition = true
self.viewModel = initialViewModel
}
public var body: some View {
NavigationView {
ZStack {
if self.viewModel.state.error != nil {
self.errorView
} else {
self.newMovementView
}
self.loadingView
}
}.alert(isPresented: self.$viewModel.state.showDeleteAlert,
content: {
self.deleteAlert
})
.accentColor(self.resolver.appearance.accentColor)
}
private var newMovementView: some View {
let dataResources = NewMovementViewInternalDataResources(
categories: self.viewModel.categories,
stores: self.viewModel.stores, customDataSectionTitle: self.viewModel.state.movementDetailTitle,
isIncome: self.isIncome
)
return NewMovementViewInternal(model: self.$viewModel.model,
dataResources: dataResources,
deleteAction: {
self.viewModel.setState(.askingForDelete)
})
.navigationBarTitle(self.viewModel.state.navigationBarTitle)
.navigationBarItems(leading: self.cancelButton,
trailing: self.saveButton)
}
// MARK: - Navigation bar buttons
private var cancelButton: some View {
Button {
self.viewModel.setState(.end)
} label: {
Text(L10n.cancel)
}
.disabled(self.viewModel.state.showLoading)
}
private var saveButton: some View {
let disabled = self.viewModel.state.showLoading || self.viewModel.state.error != nil
return Button {
self.viewModel.setState(.saving)
} label: {
Text(L10n.save).bold()
}
.disabled(disabled)
}
// MARK: - Loading view
private var loadingView: some View {
VStack {
if self.viewModel.state.showLoading {
VStack {
ProgressView()
}
.frame(minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity)
.background(Color.backgroundColor.opacity(0.5))
}
}
}
// MARK: - Delete alert
private var deleteAlert: Alert {
let message = L10n.areYouSureYouWantToDeleteThisMovement
let title = self.isIncome ? L10n.deleteIncome : L10n.deleteExpenditure
let deleteButtonLabel = L10n.delete
let deleteButton = Alert.Button.destructive(Text(deleteButtonLabel)) {
self.viewModel.setState(.deleting)
}
let alertCancelButton = Alert.Button.cancel()
return Alert(title: Text(title),
message: Text(message),
primaryButton: deleteButton,
secondaryButton: alertCancelButton)
}
// MARK: - Error view
private var errorView: some View {
GenericErrorView(title: L10n.couldnTExecuteTransaction,
error: self.viewModel.state.error)
}
}
#if DEBUG
import NewMovementPreview
import Previews
struct NewMovementView_Previews: PreviewProvider {
static var previews: some View {
NewMovementView(dataModel: NewMovementDataFake.dataModel,
movement: DataFake.movement,
isIncome: true,
onEnd: {})
}
}
#endif
| 32.698113 | 108 | 0.565493 |
bf59b16b2211e33f55ba7e89bc26bb49469a7916 | 2,818 | //
// MainMenuViewController.swift
// IceCreamBuilderMessagesExtension
//
// Created by Lorne Miller on 10/22/18.
// Copyright © 2018 Apple. All rights reserved.
//
import Foundation
import UIKit
import Messages
class MainMenuViewController :UIViewController{
// @IBOutlet weak var ScrollView: UIScrollView!
@IBOutlet weak var Logo: UILabel!
@IBOutlet weak var Continue: UIButton!
@IBOutlet weak var ContinueLabel: UILabel!
@IBOutlet weak var NewSurveyView: UIView!
@IBOutlet weak var NewSurvey: UIButton!
@IBOutlet weak var NewSurveyLabel: UILabel!
@IBOutlet weak var HelpView: UIView!
@IBOutlet weak var Help: UIButton!
@IBOutlet weak var HelpLabel: UILabel!
@IBOutlet weak var SettingsView: UIView!
@IBOutlet weak var Settings: UIButton!
@IBOutlet weak var SettingsLabel: UILabel!
@IBOutlet weak var MadeByLorne: UILabel!
weak var delegate: MainMenuViewControllerDelegate?
static let storyboardIdentifier = "MainMenuViewController"
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//TODO: Do class init
/**
Initializes a new bicycle with the provided parts and specifications.
Description is something you might want
- Throws: SomeError you might want to catch
- parameter radius: The frame size of the bicycle, in centimeters
- Returns: A beautiful, brand-new bicycle, custom-built just for you.
*/
override func viewDidLoad() {
//if view is compact, hide buttons
let viewIsCompact = MessagesViewController.presentationStyle == MSMessagesAppPresentationStyle.compact
self.NewSurveyView.isHidden = viewIsCompact
self.SettingsView.isHidden = viewIsCompact
self.HelpView.isHidden = viewIsCompact
}
//TODO: Do class init
/**
Initializes a new bicycle with the provided parts and specifications.
Description is something you might want
- Throws: SomeError you might want to catch
- parameter radius: The frame size of the bicycle, in centimeters
- Returns: A beautiful, brand-new bicycle, custom-built just for you.
*/
@IBAction func AddNewSurvey(_ sender: UIGestureRecognizer) {
delegate?.switchState_StartMenu(newState: AppState.CategorySelection)
}
}
class ScrollingFoodCell : UICollectionViewCell{
static let reuseIdentifier = "ScrollingFoodCell"
@IBOutlet weak var Foooood: UILabel!
}
// A delegate protocol for the `IceCreamsViewController` class
protocol MainMenuViewControllerDelegate: class {
/// Called to start a new survey
func switchState_StartMenu(newState:AppState)
}
| 27.359223 | 110 | 0.685238 |
ab5974651d235d0bdf50d61632b78d97c5ed8320 | 1,294 | //
// TownWeatherHeaderCell.swift
// Weather
//
// Created by Artem Argus Gusakov on 28.10.2020.
// Copyright © 2020 PhilosophyIT. All rights reserved.
//
import UIKit
class TownWeatherHeaderCell: GenericCell<TownWeatherHeaderCellVM> {
static let mainTextLabelFont: UIFont = UIFont.boldSystemFont(ofSize: 28.0)
static let additionalTextLabelFont: UIFont = UIFont.systemFont(ofSize: 14.0)
@IBOutlet weak var mainTextLabel: UILabel!
@IBOutlet weak var additionalTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
configureView()
}
override func configureView() {
mainTextLabel.font = Self.mainTextLabelFont
mainTextLabel.textColor = .mtTextColor
additionalTextLabel.font = Self.additionalTextLabelFont
additionalTextLabel.textColor = .mtAdditionalTextColor
}
override func configureWith(_ viewModel: TownWeatherHeaderCellVM) {
mainTextLabel.text = viewModel.townName
additionalTextLabel.text = viewModel.date
}
// MARK: - Cell size
override class func cellSizeWith(_ containerSize: CGSize, _ viewModel: TownWeatherHeaderCellVM) -> CGSize {
return CGSize(width: containerSize.width, height: 64.0)
}
}
| 29.409091 | 111 | 0.697836 |
d6770711cc924dfe81ca228eaff995c6e487bdef | 1,445 | //
// LifehashSeedView.swift
// GordianSigner
//
// Created by Peter on 12/14/20.
// Copyright © 2020 Blockchain Commons. All rights reserved.
//
import UIKit
class LifehashSeedView: UIView {
@IBOutlet weak var background: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var lifehashImage: UIImageView!
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var iconLabel: UILabel!
let nibName = "LifehashSeedView"
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
lifehashImage.layer.magnificationFilter = .nearest
background.clipsToBounds = true
//background.layer.cornerRadius = 8
background.backgroundColor = .clear
self.addSubview(view)
}
func loadViewFromNib() -> UIView? {
let nib = UINib(nibName: nibName, bundle: nil)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 26.272727 | 78 | 0.641522 |
4abd1b3ed56a04c9d66c80d808859564031fac38 | 12,315 | //
// AmityChannelMemberViewController.swift
// AmityUIKit
//
// Created by Sarawoot Khunsri on 15/10/2563 BE.
// Copyright © 2563 Amity. All rights reserved.
//
import UIKit
import AmitySDK
enum AmityChannelMemberViewType {
case moderator, member
}
extension AmityChannelMemberViewController: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: AmityPagerTabViewController) -> IndicatorInfo {
return IndicatorInfo(title: pageTitle)
}
}
class AmityChannelMemberViewController: AmityViewController {
// MARK: - IBOutlet Properties
@IBOutlet private var tableView: UITableView!
@IBOutlet private weak var searchBar: UISearchBar!
// MARK: - Properties
private var pageTitle: String!
private var screenViewModel: AmityChannelMemberScreenViewModelType!
private var viewType: AmityChannelMemberViewType = .member
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupSearchBar()
screenViewModel.action.getMember(viewType: viewType)
}
static func make(pageTitle: String,
viewType: AmityChannelMemberViewType,
channel: AmityChannelModel) -> AmityChannelMemberViewController {
let fetchMemberController = AmityChannelFetchMemberController(channelId: channel.channelId)
let removeMemberController = AmityChannelRemoveMemberController(channelId: channel.channelId)
let addMemberController = AmityChannelAddMemberController(channelId: channel.channelId)
let roleController = AmityChannelRoleController(channelId: channel.channelId)
let viewModel: AmityChannelMemberScreenViewModelType = AmityChannelMemberScreenViewModel(channel: channel,
fetchMemberController: fetchMemberController,
removeMemberController: removeMemberController,
addMemberController: addMemberController,
roleController: roleController)
let vc = AmityChannelMemberViewController(nibName: AmityChannelMemberViewController.identifier,
bundle: AmityUIKitManager.bundle)
vc.pageTitle = pageTitle
vc.screenViewModel = viewModel
vc.viewType = viewType
return vc
}
private func setupSearchBar() {
searchBar.backgroundImage = UIImage()
searchBar.delegate = self
searchBar.tintColor = AmityColorSet.base
searchBar.returnKeyType = .done
(searchBar.value(forKey: "searchField") as? UITextField)?.textColor = AmityColorSet.base
((searchBar.value(forKey: "searchField") as? UITextField)?.leftView as? UIImageView)?.tintColor = AmityColorSet.base.blend(.shade2)
}
func addMember(users: [AmitySelectMemberModel]) {
screenViewModel.action.addUser(users: users)
}
func passMember() -> [AmitySelectMemberModel] {
return screenViewModel.dataSource.prepareData()
}
}
// MARK: - Setup view
private extension AmityChannelMemberViewController {
func setupView() {
screenViewModel.delegate = self
view.backgroundColor = AmityColorSet.backgroundColor
setupTableView()
}
func setupTableView() {
tableView.register(AmityChannelMemberSettingsTableViewCell.nib, forCellReuseIdentifier: AmityChannelMemberSettingsTableViewCell.identifier)
tableView.separatorColor = .clear
tableView.backgroundColor = AmityColorSet.backgroundColor
tableView.tableFooterView = UIView()
tableView.delegate = self
tableView.dataSource = self
}
}
// MARK: - UITableView Delegate
extension AmityChannelMemberViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tablbeView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.isBottomReached {
screenViewModel.action.loadMore()
}
}
}
// MARK: - UITableView DataSource
extension AmityChannelMemberViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return screenViewModel.dataSource.numberOfMembers()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: AmityChannelMemberSettingsTableViewCell.identifier, for: indexPath)
configure(for: cell, at: indexPath)
return cell
}
private func configure(for cell: UITableViewCell, at indexPath: IndexPath) {
if let cell = cell as? AmityChannelMemberSettingsTableViewCell {
let member = screenViewModel.dataSource.member(at: indexPath)
cell.display(with: member, isJoined: true)
cell.setIndexPath(with: indexPath)
cell.delegate = self
}
}
}
extension AmityChannelMemberViewController: AmityChannelMemberScreenViewModelDelegate {
func screenViewModelDidGetMember() {
tableView.reloadData()
}
func screenViewModel(_ viewModel: AmityChannelMemberScreenViewModel, loadingState state: AmityLoadingState) {
switch state {
case .loading:
tableView.showLoadingIndicator()
case .loaded:
tableView.tableFooterView = nil
case .initial:
break
}
}
func screenViewModel(_ viewModel: AmityChannelMemberScreenViewModel, didRemoveUserAt indexPath: IndexPath) {
tableView.deleteRows(at: [indexPath], with: .fade)
}
func screenViewModelDidAddMemberSuccess() {
AmityHUD.hide()
}
func screenViewModelDidRemoveMemberSuccess() {
AmityHUD.hide()
}
func screenViewModelDidAddRoleSuccess() {
AmityHUD.hide()
}
func screenViewModelDidRemoveRoleSuccess() {
AmityHUD.hide()
}
func screenViewModel(_ viewModel: AmityChannelMemberScreenViewModel, failure error: AmityError) {
AmityHUD.hide { [weak self] in
switch error {
case .noPermission:
let alert = UIAlertController(title: AmityLocalizedStringSet.Community.alertUnableToPerformActionTitle.localizedString, message: AmityLocalizedStringSet.Community.alertUnableToPerformActionDesc.localizedString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: AmityLocalizedStringSet.General.ok.localizedString, style: .default, handler: { _ in
self?.navigationController?.popToRootViewController(animated: true)
}))
self?.present(alert, animated: true, completion: nil)
default:
AmityHUD.show(.error(message: AmityLocalizedStringSet.HUD.somethingWentWrong.localizedString))
}
}
}
func screenViewModelDidSearchUser() {
tableView.reloadData()
}
}
extension AmityChannelMemberViewController: AmityChannelMemberSettingsTableViewCellDelegate {
func didPerformAction(at indexPath: IndexPath, action: AmityChannelMemberAction) {
switch action {
case .tapAvatar, .tapDisplayName:
let member = screenViewModel.dataSource.member(at: indexPath)
AmityEventHandler.shared.userDidTap(from: self, userId: member.userId)
case .tapOption:
openOptionsBottomSheet(for: indexPath)
}
}
}
// MARK:- Private Methods
private extension AmityChannelMemberViewController {
func openOptionsBottomSheet(for indexPath: IndexPath) {
let bottomSheet = BottomSheetViewController()
let contentView = ItemOptionView<TextItemOption>()
bottomSheet.sheetContentView = contentView
bottomSheet.isTitleHidden = true
bottomSheet.modalPresentationStyle = .overFullScreen
var options: [TextItemOption] = []
screenViewModel.dataSource.getChannelEditUserPermission { [weak self] (hasPermission) in
guard let strongSelf = self else { return }
// remove user options
if hasPermission {
let member = strongSelf.screenViewModel.dataSource.member(at: indexPath)
switch strongSelf.viewType {
case .member:
if !member.isModerator {
let addRoleOption = TextItemOption(title: AmityLocalizedStringSet.ChatSettings.promoteToModerator.localizedString) {
AmityHUD.show(.loading)
strongSelf.screenViewModel.action.addRole(at: indexPath)
}
options.append(addRoleOption)
}
case .moderator:
let removeRoleOption = TextItemOption(title: AmityLocalizedStringSet.ChatSettings.dismissFromModerator.localizedString) {
AmityHUD.show(.loading)
strongSelf.screenViewModel.action.removeRole(at: indexPath)
}
options.append(removeRoleOption)
}
let removeOption = TextItemOption(title: AmityLocalizedStringSet.ChatSettings.removeFromGroupChat.localizedString, textColor: AmityColorSet.alert) {
let alert = UIAlertController(title: AmityLocalizedStringSet.ChatSettings.removeMemberAlertTitle.localizedString,
message: AmityLocalizedStringSet.ChatSettings.removeMemberAlertBody.localizedString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: AmityLocalizedStringSet.General.cancel.localizedString, style: .default, handler: nil))
alert.addAction(UIAlertAction(title: AmityLocalizedStringSet.General.remove.localizedString, style: .destructive, handler: { _ in
strongSelf.screenViewModel.action.removeUser(at: indexPath)
}))
strongSelf.present(alert, animated: true, completion: nil)
}
options.append(removeOption)
}
// report/unreport option
strongSelf.screenViewModel.dataSource.getReportUserStatus(at: indexPath) { isReported in
var option: TextItemOption
if isReported {
// unreport option
option = TextItemOption(title: AmityLocalizedStringSet.General.undoReport.localizedString) {
strongSelf.screenViewModel.action.unreportUser(at: indexPath)
}
} else {
// report option
option = TextItemOption(title: AmityLocalizedStringSet.General.report.localizedString) {
strongSelf.screenViewModel.action.reportUser(at: indexPath)
}
}
// the options wil show like this below:
// - Promote moderator/Dismiss moderator
// - Report/Unreport
// - Remove from community
// option 'Remove from community' always show last element
// if options more than 2 items, the report/unreport option will insert at index 1
// if options less than 2 items, the report/unreport option will insert at index 0
options.insert(option, at: options.count > 1 ? 1:0)
contentView.configure(items: options, selectedItem: nil)
strongSelf.present(bottomSheet, animated: false, completion: nil)
}
}
}
}
extension AmityChannelMemberViewController: UISearchBarDelegate {
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
screenViewModel.action.searchUser(with: searchText)
}
}
| 44.139785 | 250 | 0.647503 |
29de6a6f6f80fd77af11780d02b692b3c850250f | 1,268 | #if canImport(UIKit)
import UIKit
import Aegithalos
public extension Setup where Subject: UIButton {
@inlinable func titleFont(_ font: UIFont) -> Setup {
composed { button in button.titleLabel?.font = font }
}
@inlinable func title(_ title: String, for state: UIControl.State = .normal) -> Setup {
composed { button in button.setTitle(title, for: state) }
}
@inlinable func attributedTitle(_ attributedTitle: NSAttributedString, for state: UIControl.State = .normal) -> Setup {
composed { button in button.setAttributedTitle(attributedTitle, for: state) }
}
@inlinable func titleColor(_ color: UIColor, state: UIControl.State = .normal) -> Setup {
composed { button in button.setTitleColor(color, for: state) }
}
@inlinable func titleAlignment(_ alignment: NSTextAlignment) -> Setup {
composed { button in button.titleLabel?.textAlignment = alignment }
}
@inlinable func backgroundImage(_ image: UIImage?, for state: UIControl.State = .normal) -> Setup {
composed { button in button.setBackgroundImage(image, for: state) }
}
@inlinable func titleLineBreakMode(_ lineBreakMode: NSLineBreakMode) -> Setup {
composed { button in button.titleLabel?.lineBreakMode = lineBreakMode }
}
}
#endif
| 33.368421 | 121 | 0.713722 |
76ec98a245e445fcd8d5143d6dfe62530db89a97 | 694 | //
// ViewController.swift
// Add
//
// Created by Tatsuya Tobioka on 2017/11/29.
// Copyright © 2017 tnantoka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/// [marker1]
let lastName = "田中"
let firstName = "太郎"
let fullName = lastName + firstName
print("あなたの名前は" + fullName + "さんですね")
/// [marker1]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.6875 | 80 | 0.619597 |
75876785ef7d3c3109cec2495d2c81f048d317e3 | 2,586 | //
// ErrorView.swift
// CoreUIKit
//
// Created by Bartosz Żmija on 11/02/2021.
//
import UIKit
/// View presented when there is an error.
public final class ErrorView: UIView {
// MARK: Private properties
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = configuration.title
label.textAlignment = .center
label.numberOfLines = 0
return label
}()
private lazy var button: Button = {
let button = Button()
button.action = configuration.buttonAction
button.title = configuration.buttonTitle
return button
}()
private let configuration: Configuration
// MARK: Initializers
/// Initializes the receiver.
/// - Parameters:
/// - configuration: Configuration used to setup this view.
public init(
configuration: Configuration
) {
self.configuration = configuration
super.init(frame: .zero)
setupHierarchy()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private methods
private func setupHierarchy() {
[
titleLabel,
button
].forEach(addSubview)
}
private func setupConstraints() {
[
titleLabel,
button
].forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
titleLabel.topAnchor.constraint(equalTo: topAnchor),
button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
button.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
button.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
@objc private func didTapButton() {
configuration.buttonAction()
}
// MARK: Structs
/// Configuration used to setup this view.
public struct Configuration {
let title: String
let buttonTitle: String
let buttonAction: () -> Void
public init(title: String, buttonTitle: String, buttonAction: @escaping () -> Void) {
self.title = title
self.buttonTitle = buttonTitle
self.buttonAction = buttonAction
}
}
}
| 27.221053 | 93 | 0.62181 |
fe2655b87767e8f7cde91b22a8b49767e6ff12af | 1,164 | //
// MeetupEventListAPIWorker.swift
// ITApp
//
// Created by kuotinyen on 2020/10/26.
//
import Foundation
class MeetupEventListAPIWorker {
typealias APIResult = Result<[MeetupEvent], Error>
typealias APICallback = (APIResult) -> Void
private let jsonAPIWorker: JsonAPIWorker
init(jsonAPIWorker: JsonAPIWorker = .init()) {
self.jsonAPIWorker = jsonAPIWorker
}
func fetchMeetupEvents(callback: @escaping APICallback) {
guard let url = URL(string: Constant.Fake.jsonFileName) else { return }
jsonAPIWorker.fetchModel(from: url) { (result: Result<MeetupEventListResultRawModel, Error>) in
switch result {
case let .success(resultRawModel):
let meetupEvents = resultRawModel.data.map { $0.makeMeetupEvent() }
callback(.success(meetupEvents))
case let .failure(error):
callback(.failure(error))
}
}
}
}
// MARK: - Constant
extension MeetupEventListAPIWorker {
private enum Constant {
enum Fake {
static var jsonFileName: String { "fake-meetup-event-list" }
}
}
}
| 25.866667 | 103 | 0.632302 |
0e81d9b602ff02955849d1a21d5fdbea66d1e60b | 16,831 | //
// AKSamplerAudioUnit.swift
// AudioKit Core
//
// Created by Shane Dunne, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
import AVFoundation
public class AKSamplerAudioUnit: AKGeneratorAudioUnitBase {
var pDSP: UnsafeMutableRawPointer?
func setParameter(_ address: AKSamplerParameter, value: Double) {
setParameterWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
func setParameterImmediately(_ address: AKSamplerParameter, value: Double) {
setParameterImmediatelyWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
var masterVolume: Double = 0.0 {
didSet { setParameter(.masterVolume, value: masterVolume) }
}
var pitchBend: Double = 0.0 {
didSet { setParameter(.pitchBend, value: pitchBend) }
}
var vibratoDepth: Double = 1.0 {
didSet { setParameter(.vibratoDepth, value: vibratoDepth) }
}
var filterCutoff: Double = 4.0 {
didSet { setParameter(.filterCutoff, value: filterCutoff) }
}
var filterEgStrength: Double = 20.0 {
didSet { setParameter(.filterEgStrength, value: filterCutoff) }
}
var filterResonance: Double = 0.0 {
didSet { setParameter(.filterResonance, value: filterResonance) }
}
var rampDuration: Double = 0.0 {
didSet { setParameter(.rampDuration, value: rampDuration) }
}
var attackDuration: Double = 0.0 {
didSet { setParameter(.attackDuration, value: attackDuration) }
}
var decayDuration: Double = 0.0 {
didSet { setParameter(.decayDuration, value: decayDuration) }
}
var sustainLevel: Double = 0.0 {
didSet { setParameter(.sustainLevel, value: sustainLevel) }
}
var releaseDuration: Double = 0.0 {
didSet { setParameter(.releaseDuration, value: releaseDuration) }
}
var filterAttackDuration: Double = 0.0 {
didSet { setParameter(.filterAttackDuration, value: filterAttackDuration) }
}
var filterDecayDuration: Double = 0.0 {
didSet { setParameter(.filterDecayDuration, value: filterDecayDuration) }
}
var filterSustainLevel: Double = 0.0 {
didSet { setParameter(.filterSustainLevel, value: filterSustainLevel) }
}
var filterReleaseDuration: Double = 0.0 {
didSet { setParameter(.filterReleaseDuration, value: filterReleaseDuration) }
}
var filterEnable: Double = 0.0 {
didSet { setParameter(.filterEnable, value: filterEnable) }
}
public override func initDSP(withSampleRate sampleRate: Double,
channelCount count: AVAudioChannelCount) -> UnsafeMutableRawPointer! {
pDSP = createAKSamplerDSP(Int32(count), sampleRate)
return pDSP
}
override init(componentDescription: AudioComponentDescription,
options: AudioComponentInstantiationOptions = []) throws {
try super.init(componentDescription: componentDescription, options: options)
let rampFlags: AudioUnitParameterOptions = [.flag_IsReadable, .flag_IsWritable, .flag_CanRamp]
let nonRampFlags: AudioUnitParameterOptions = [.flag_IsReadable, .flag_IsWritable]
var paramAddress = 0
let masterVolumeParam = AUParameterTree.createParameter(withIdentifier: "masterVolume",
name: "Master Volume",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1.0,
unit: .generic, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let pitchBendParam = AUParameterTree.createParameter(withIdentifier: "pitchBend",
name: "Pitch Offset (semitones)",
address: AUParameterAddress(paramAddress),
min: -1_000.0, max: 1_000.0,
unit: .relativeSemiTones, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let vibratoDepthParam = AUParameterTree.createParameter(withIdentifier: "vibratoDepth",
name: "Vibrato amount (semitones)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 24.0,
unit: .relativeSemiTones, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterCutoffParam = AUParameterTree.createParameter(withIdentifier: "filterCutoff",
name: "Filter cutoff (harmonic))",
address: AUParameterAddress(paramAddress),
min: 1.0, max: 1_000.0,
unit: .ratio, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterEgStrengthParam = AUParameterTree.createParameter(withIdentifier: "filterEgStrength",
name: "Filter EG strength",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .ratio, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterResonanceParam = AUParameterTree.createParameter(withIdentifier: "filterResonance",
name: "Filter resonance (dB))",
address: AUParameterAddress(paramAddress),
min: -20.0, max: 20.0,
unit: .decibels, unitName: nil,
flags: rampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let attackDurationParam = AUParameterTree.createParameter(withIdentifier: "attackDuration",
name: "Amplitude Attack duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let decayDurationParam = AUParameterTree.createParameter(withIdentifier: "decayDuration",
name: "Amplitude Decay duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let sustainLevelParam = AUParameterTree.createParameter(withIdentifier: "sustainLevel",
name: "Amplitude Sustain level (fraction)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1.0,
unit: .generic, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let releaseDurationParam = AUParameterTree.createParameter(withIdentifier: "releaseDuration",
name: "Amplitude Release duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterAttackDurationParam = AUParameterTree.createParameter(withIdentifier: "filterAttackDuration",
name: "Filter Attack duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterDecayDurationParam = AUParameterTree.createParameter(withIdentifier: "filterDecayDuration",
name: "Filter Decay duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterSustainLevelParam = AUParameterTree.createParameter(withIdentifier: "filterSustainLevel",
name: "Filter Sustain level (fraction)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1.0,
unit: .generic, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterReleaseDurationParam = AUParameterTree.createParameter(withIdentifier: "filterReleaseDuration",
name: "Filter Release duration (seconds)",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1_000.0,
unit: .seconds, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
paramAddress += 1
let filterEnableParam = AUParameterTree.createParameter(withIdentifier: "filterEnable",
name: "Filter Enable",
address: AUParameterAddress(paramAddress),
min: 0.0, max: 1.0,
unit: .boolean, unitName: nil,
flags: nonRampFlags,
valueStrings: nil, dependentParameters: nil)
setParameterTree(AUParameterTree.createTree(withChildren: [masterVolumeParam, pitchBendParam, vibratoDepthParam,
filterCutoffParam, filterEgStrengthParam, filterResonanceParam,
attackDurationParam, decayDurationParam,
sustainLevelParam, releaseDurationParam,
filterAttackDurationParam, filterDecayDurationParam,
filterSustainLevelParam, filterReleaseDurationParam,
filterEnableParam ]))
masterVolumeParam.value = 1.0
pitchBendParam.value = 0.0
vibratoDepthParam.value = 0.0
filterCutoffParam.value = 4.0
filterEgStrengthParam.value = 20.0
filterResonanceParam.value = 0.0
attackDurationParam.value = 0.0
decayDurationParam.value = 0.0
sustainLevelParam.value = 1.0
releaseDurationParam.value = 0.0
filterAttackDurationParam.value = 0.0
filterDecayDurationParam.value = 0.0
filterSustainLevelParam.value = 1.0
filterReleaseDurationParam.value = 0.0
filterEnableParam.value = 0.0
}
public override var canProcessInPlace: Bool { return true }
public func stopAllVoices() {
doAKSamplerStopAllVoices(pDSP)
}
public func restartVoices() {
doAKSamplerRestartVoices(pDSP)
}
public func loadSampleData(from sampleDataDescriptor: AKSampleDataDescriptor) {
var copy = sampleDataDescriptor
doAKSamplerLoadData(pDSP, ©)
}
public func loadCompressedSampleFile(from sampleFileDescriptor: AKSampleFileDescriptor) {
var copy = sampleFileDescriptor
doAKSamplerLoadCompressedFile(pDSP, ©)
}
public func unloadAllSamples() {
doAKSamplerUnloadAllSamples(pDSP)
}
public func buildSimpleKeyMap() {
doAKSamplerBuildSimpleKeyMap(pDSP)
}
public func buildKeyMap() {
doAKSamplerBuildKeyMap(pDSP)
}
public func setLoop(thruRelease: Bool) {
doAKSamplerSetLoopThruRelease(pDSP, thruRelease)
}
public func playNote(noteNumber: UInt8, velocity: UInt8, noteFrequency: Float) {
doAKSamplerPlayNote(pDSP, noteNumber, velocity, noteFrequency)
}
public func stopNote(noteNumber: UInt8, immediate: Bool) {
doAKSamplerStopNote(pDSP, noteNumber, immediate)
}
public func sustainPedal(down: Bool) {
doAKSamplerSustainPedal(pDSP, down)
}
}
| 57.054237 | 130 | 0.451013 |
01a043d92be7024a83bac06de3685e89336c6928 | 323 | // Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
//
// DataSinkListener.swift
// GoldenGate
//
// Created by Vlad Corneci on 03/06/2020.
//
public protocol DataSinkListener: AnyObject {
/// Called when the DataSink accepts more data after reporting `GG_WOULD_BLOCK`
func onCanPut()
}
| 23.071429 | 83 | 0.71517 |
1ae2d2c0f66de8f8d1588f9de19206e78ce6e3a5 | 1,474 | //
// SKDetectingImageView.swift
// SKPhotoBrowser
//
// Created by suzuki_keishi on 2015/10/01.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
import SDWebImage
@objc protocol SKDetectingImageViewDelegate {
func handleImageViewSingleTap(_ touchPoint: CGPoint)
func handleImageViewDoubleTap(_ touchPoint: CGPoint)
}
class SKDetectingImageView: SDAnimatedImageView {
weak var delegate: SKDetectingImageViewDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
@objc func handleDoubleTap(_ recognizer: UITapGestureRecognizer) {
delegate?.handleImageViewDoubleTap(recognizer.location(in: self))
}
@objc func handleSingleTap(_ recognizer: UITapGestureRecognizer) {
delegate?.handleImageViewSingleTap(recognizer.location(in: self))
}
}
private extension SKDetectingImageView {
func setup() {
isUserInteractionEnabled = true
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
doubleTap.numberOfTapsRequired = 2
addGestureRecognizer(doubleTap)
let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(_:)))
singleTap.require(toFail: doubleTap)
addGestureRecognizer(singleTap)
}
}
| 28.346154 | 100 | 0.698779 |
8729f694ee68c66602f8d2ebf165eff96e38641f | 955 | //
// YPTradeRecord.swift
// PropertyExchange
//
// Created by itachi on 16/10/17.
// Copyright © 2016年 com.itachi. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct YPTradeRecord
{
public var money:Float = 0.0
public var desc:String = ""
public var date:String = ""
public var isOut:Bool = true
public init(_ json: JSON){
self.desc = (json.dictionary?["desc"]?.stringValue)!
if let _isOut = json.dictionary?["isOut"]?.intValue , _isOut == 1{
self.isOut = true
}else{
self.isOut = false
}
self.money = (json.dictionary?["money"]?.floatValue)!
self.date = (json.dictionary?["date"]?.stringValue)!
}
public static func models(json: JSON) -> [YPTradeRecord]{
var models = [YPTradeRecord]()
guard let jsonArray = json.array else {return models}
for i in 0..<jsonArray.count{
models.append(YPTradeRecord(jsonArray[i]))
}
return models
}
}
| 22.738095 | 70 | 0.646073 |
4bd2ee833a7fe2752b6e9fbb71bf92f901f4106f | 471 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// ModuleListResultProtocol is the response model for the list module operation.
public protocol ModuleListResultProtocol : Codable {
var value: [ModuleProtocol?]? { get set }
var _nextLink: String? { get set }
}
| 42.818182 | 96 | 0.740977 |
50e48584650b2b6874d3415f8e637d953f71afb1 | 3,355 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public struct ConfigModelSubscriptionAdd: AcknowledgedConfigMessage, ConfigAddressMessage, ConfigAnyModelMessage {
public static let opCode: UInt32 = 0x801B
public static let responseType: StaticMeshMessage.Type = ConfigModelSubscriptionStatus.self
public var parameters: Data? {
let data = Data() + elementAddress + address
if let companyIdentifier = companyIdentifier {
return data + companyIdentifier + modelIdentifier
} else {
return data + modelIdentifier
}
}
public let address: Address
public let elementAddress: Address
public let modelIdentifier: UInt16
public let companyIdentifier: UInt16?
public init?(group: Group, to model: Model) {
guard group.address.address.isGroup else {
// ConfigModelSubscriptionVirtualAddressAdd should be used instead.
return nil
}
guard let elementAddress = model.parentElement?.unicastAddress else {
return nil
}
self.address = group.address.address
self.elementAddress = elementAddress
self.modelIdentifier = model.modelIdentifier
self.companyIdentifier = model.companyIdentifier
}
public init?(parameters: Data) {
guard parameters.count == 6 || parameters.count == 8 else {
return nil
}
elementAddress = parameters.read(fromOffset: 0)
address = parameters.read(fromOffset: 2)
if parameters.count == 8 {
companyIdentifier = parameters.read(fromOffset: 4)
modelIdentifier = parameters.read(fromOffset: 6)
} else {
companyIdentifier = nil
modelIdentifier = parameters.read(fromOffset: 4)
}
}
}
| 41.9375 | 114 | 0.712072 |
50811d4b189ed57ce8da2fda645da398c589ee00 | 930 | //
// DefaultCryptoRepository.swift
// Assignment
//
// Created by Yashashree on 02/05/22.
//
import Foundation
final class DefaultCryptoRepository {
private let dataTransferService: DataTransferService
init(dataTransferService: DataTransferService) {
self.dataTransferService = dataTransferService
}
}
extension DefaultCryptoRepository: CryptoRepository{
func performCryptoDetails(requestDto: CryptoRequestDTO,completion:@escaping (Result<CryptoResponseDTO, NetworkError>) -> Void) {
let endpoint = APIEndpoints.cryptoDetails(cryptoRequestDTO: requestDto)
dataTransferService.request(with: endpoint) { (result: Result<CryptoResponseDTO, NetworkError>) in
switch result{
case .success(let model):
completion(.success(model))
case .failure(let error):
completion(.failure(error))
}
}
}
}
| 30 | 132 | 0.686022 |
c1b59bc772d7928c6a81c4634a88d56e66f904d4 | 1,397 | //
// JXHorizontalViewController.swift
// JXFoundation_Example
//
// Created by Admin on 8/5/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
import JXFoundation
class JXScrollContainerViewController: JXBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.customNavigationBar.backgroundView.backgroundColor = UIColor.cyan
self.customNavigationBar.separatorView.backgroundColor = UIColor.gray
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
@IBAction func horizontalAction(_ sender: Any) {
let vc = JXHorizontalViewController()
vc.title = "JXScrollContainerView-horizontal"
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func verticallyAction(_ sender: Any) {
let vc = JXVerticallyViewController()
vc.title = "JXScrollContainerView-vertically"
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func customAction(_ sender: Any) {
let vc = HomeViewController()
vc.title = "JXScrollContainerView-custom"
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 33.261905 | 78 | 0.708661 |
71adf053854129af87ba805547d28f914ecff71f | 5,718 | //
// PhotosViewController.swift
// Tumblr
//
// Created by Jinan Huang on 9/6/18.
// Copyright © 2018 Jinan Huang. All rights reserved.
//
import UIKit
import AlamofireImage
class PhotosViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {
var posts: [[String: Any]] = []
var refreshControl: UIRefreshControl!
var isMoreDataLoading = false
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(PhotosViewController.didPullToRefresh(_:)), for: .valueChanged)
tableView.insertSubview(refreshControl, at: 0)
tableView.dataSource = self
tableView.rowHeight = 200
tableView.delegate = self
fetchPosts()
}
@objc func didPullToRefresh(_ refreshControl: UIRefreshControl) {
fetchPosts()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if(!isMoreDataLoading){
// Calculate the position of one screen length before the bottom of the results
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
// When the user has scrolled past the threshold, start requesting
if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) {
isMoreDataLoading = true
fetchPosts()
}
}
}
func displayAlert(){
let alertController = UIAlertController(title: "Can't Find Photos", message: "Check Internet Connection", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in // create a cancel button
// handle cancel button, when click on the button masssge will dismiss
}
// add the cancel button to the alertController
alertController.addAction(cancelAction)
// create an OK button
let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in
// handle ok button, when click on the button masssge will dismiss
}
// add the OK button to the alert controller
alertController.addAction(OKAction)
DispatchQueue.main.async {
self.present(alertController, animated: true, completion: nil)
}
}
func fetchPosts() {
// Network request snippet
let url = URL(string: "https://api.tumblr.com/v2/blog/humansofnewyork.tumblr.com/posts/photo?api_key=Q6vHoaVm5L1u2ZAW1fqv3Jw48gFzYVg9P0vH0VHl3GVy6quoGV")!
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let task : URLSessionDataTask = session.dataTask(with: url, completionHandler: { (data, response, error) in
self.isMoreDataLoading = false
if let error = error {
self.displayAlert()
print(error.localizedDescription)
} else if let data = data,
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print(dataDictionary)
// TODO: Get the posts and store in posts property
// Get the dictionary from the response key
let responseDictionary = dataDictionary["response"] as! [String: Any]
// Store the returned array of dictionaries in our posts property
self.posts = responseDictionary["posts"] as! [[String: Any]]
// TODO: Reload the table view
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
})
task.resume()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexpath: IndexPath) {
tableView.deselectRow(at: indexpath, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = posts[indexPath.row]
if let photos = post["photos"] as? [[String: Any]] {
// photos is NOT nil, we can use it!
// TODO: Get the photo url
// 1.
let photo = photos[0]
// 2.
let originalSize = photo["original_size"] as! [String: Any]
// 3.
let urlString = originalSize["url"] as! String
// 4.
let url = URL(string: urlString)
cell.postImageView.af_setImage(withURL: url!)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! PhotoDetailsViewController
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPath(for: cell)!
let post = posts[indexPath.row]
vc.post = post
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 38.12 | 162 | 0.614201 |
89dd24629774d4c30b9daa59dffe0ae44c008ce6 | 15,163 | //
// FBGeometry.swift
// Swift VectorBoolean for iOS
//
// Based on FBGeometry - Created by Andrew Finnell on 5/28/11.
// Copyright 2011 Fortunate Bear, LLC. All rights reserved.
//
// Created by Leslie Titze on 2015-05-21.
// Copyright (c) 2015 Leslie Titze. All rights reserved.
//
import UIKit
// ===================================
// MARK: Point Helpers
// ===================================
let isRunningOn64BitDevice = MemoryLayout<Int>.size == MemoryLayout<Int64>.size
var FBPointClosenessThreshold: Double {
if isRunningOn64BitDevice {
return 1e-10
} else {
return 1e-2
}
}
var FBTangentClosenessThreshold: Double {
if isRunningOn64BitDevice {
return 1e-12
} else {
return 1e-2
}
}
var FBBoundsClosenessThreshold: Double {
if isRunningOn64BitDevice {
return 1e-9
} else {
return 1e-2
}
}
func FBDistanceBetweenPoints(_ point1: CGPoint, point2: CGPoint) -> Double {
let xDelta = Double(point2.x - point1.x)
let yDelta = Double(point2.y - point1.y)
return sqrt(xDelta * xDelta + yDelta * yDelta);
}
func FBDistancePointToLine(_ point: CGPoint, lineStartPoint: CGPoint, lineEndPoint: CGPoint) -> Double {
let lineLength = FBDistanceBetweenPoints(lineStartPoint, point2: lineEndPoint)
if lineLength == 0.0 {
return 0.0
}
let xDelta = Double(lineEndPoint.x - lineStartPoint.x)
let yDelta = Double(lineEndPoint.y - lineStartPoint.y)
let num = Double(point.x - lineStartPoint.x) * xDelta + Double(point.y - lineStartPoint.y) * yDelta
let u = num / (lineLength * lineLength)
let intersectionPoint = CGPoint(
x: lineStartPoint.x + CGFloat(u * xDelta),
y: lineStartPoint.y + CGFloat(u * yDelta)
)
return FBDistanceBetweenPoints(point, point2: intersectionPoint)
}
func FBAddPoint(_ point1: CGPoint, point2: CGPoint) -> CGPoint {
return CGPoint(
x: point1.x + point2.x,
y: point1.y + point2.y)
}
func FBUnitScalePoint(_ point: CGPoint, scale: Double) -> CGPoint {
var result = point
let length = FBPointLength(point)
if length != 0.0 {
result.x = CGFloat(Double(result.x) * (scale/length))
result.y = CGFloat(Double(result.y) * (scale/length))
}
return result
}
func FBScalePoint(_ point: CGPoint, scale: CGFloat) -> CGPoint {
return CGPoint(
x: point.x * scale,
y: point.y * scale)
}
func FBDotMultiplyPoint(_ point1: CGPoint, point2: CGPoint) -> Double {
let dotX = Double(point1.x) * Double(point2.x)
let dotY = Double(point1.y) * Double(point2.y)
return dotX + dotY
}
func FBSubtractPoint(_ point1: CGPoint, point2: CGPoint) -> CGPoint {
return CGPoint(
x: point1.x - point2.x,
y: point1.y - point2.y)
}
func FBPointLength(_ point: CGPoint) -> Double {
let xSq = Double(point.x) * Double(point.x)
let ySq = Double(point.y) * Double(point.y)
return sqrt(xSq + ySq)
}
func FBPointSquaredLength(_ point: CGPoint) -> Double {
let xSq = Double(point.x) * Double(point.x)
let ySq = Double(point.y) * Double(point.y)
return xSq + ySq
}
func FBNormalizePoint(_ point: CGPoint) -> CGPoint {
var result = point
let length = FBPointLength(point)
if length != 0.0 {
result.x = CGFloat(Double(result.x) / length)
result.y = CGFloat(Double(result.y) / length)
}
return result
}
func FBNegatePoint(_ point: CGPoint) -> CGPoint {
return CGPoint(
x: -point.x,
y: -point.y)
}
func FBRoundPoint(_ point: CGPoint) -> CGPoint {
return CGPoint(
x: round(point.x),
y: round(point.y))
}
func FBLineNormal(_ lineStart: CGPoint, lineEnd: CGPoint) -> CGPoint {
return FBNormalizePoint(CGPoint(
x: -(lineEnd.y - lineStart.y),
y: lineEnd.x - lineStart.x))
}
func FBLineMidpoint(_ lineStart: CGPoint, lineEnd: CGPoint) -> CGPoint {
let distance = FBDistanceBetweenPoints(lineStart, point2: lineEnd)
let tangent = FBNormalizePoint(FBSubtractPoint(lineEnd, point2: lineStart))
return FBAddPoint(lineStart, point2: FBUnitScalePoint(tangent, scale: distance / 2.0))
}
func FBRectGetTopLeft(_ rect : CGRect) -> CGPoint {
return CGPoint(
x: rect.minX,
y: rect.minY)
}
func FBRectGetTopRight(_ rect : CGRect) -> CGPoint {
return CGPoint(
x: rect.maxX,
y: rect.minY)
}
func FBRectGetBottomLeft(_ rect : CGRect) -> CGPoint {
return CGPoint(
x: rect.minX,
y: rect.maxY)
}
func FBRectGetBottomRight(_ rect : CGRect) -> CGPoint {
return CGPoint(
x: rect.maxX,
y: rect.maxY)
}
func FBExpandBoundsByPoint(_ topLeft: inout CGPoint, bottomRight: inout CGPoint, point: CGPoint) {
if point.x < topLeft.x { topLeft.x = point.x }
if point.x > bottomRight.x { bottomRight.x = point.x }
if point.y < topLeft.y { topLeft.y = point.y }
if point.y > bottomRight.y { bottomRight.y = point.y }
}
func FBUnionRect(_ rect1: CGRect, rect2: CGRect) -> CGRect {
var topLeft = FBRectGetTopLeft(rect1)
var bottomRight = FBRectGetBottomRight(rect1)
FBExpandBoundsByPoint(&topLeft, bottomRight: &bottomRight, point: FBRectGetTopLeft(rect2))
FBExpandBoundsByPoint(&topLeft, bottomRight: &bottomRight, point: FBRectGetTopRight(rect2))
FBExpandBoundsByPoint(&topLeft, bottomRight: &bottomRight, point: FBRectGetBottomRight(rect2))
FBExpandBoundsByPoint(&topLeft, bottomRight: &bottomRight, point: FBRectGetBottomLeft(rect2))
return CGRect(
x: topLeft.x,
y: topLeft.y,
width: bottomRight.x - topLeft.x,
height: bottomRight.y - topLeft.y)
}
// ===================================
// MARK: -- Distance Helper methods --
// ===================================
func FBArePointsClose(_ point1: CGPoint, point2: CGPoint) -> Bool {
return FBArePointsCloseWithOptions(point1, point2: point2, threshold: FBPointClosenessThreshold)
}
func FBArePointsCloseWithOptions(_ point1: CGPoint, point2: CGPoint, threshold: Double) -> Bool {
return FBAreValuesCloseWithOptions(Double(point1.x), value2: Double(point2.x), threshold: threshold) && FBAreValuesCloseWithOptions(Double(point1.y), value2: Double(point2.y), threshold: threshold);
}
func FBAreValuesClose(_ value1: CGFloat, value2: CGFloat) -> Bool {
return FBAreValuesCloseWithOptions(Double(value1), value2: Double(value2), threshold: FBPointClosenessThreshold)
}
func FBAreValuesClose(_ value1: Double, value2: Double) -> Bool {
return FBAreValuesCloseWithOptions(value1, value2: value2, threshold: Double(FBPointClosenessThreshold))
}
func FBAreValuesCloseWithOptions(_ value1: Double, value2: Double, threshold: Double) -> Bool {
let delta = value1 - value2
return (delta <= threshold) && (delta >= -threshold)
}
// ===================================
// MARK: ---- Angle Helpers ----
// ===================================
//////////////////////////////////////////////////////////////////////////
// Helper methods for angles
//
let Two_π = 2.0 * M_PI
let π = M_PI
let Half_π = M_PI_2
// Normalize the angle between 0 and 2 π
func NormalizeAngle(_ value: Double) -> Double {
var value = value
while value < 0.0 { value = value + Two_π }
while value >= Two_π { value = value - Two_π }
return value
}
// Compute the polar angle from the cartesian point
func PolarAngle(_ point: CGPoint) -> Double {
var value = 0.0
let dpx = Double(point.x)
let dpy = Double(point.y)
if point.x > 0.0 {
value = atan(dpy / dpx)
}
else if point.x < 0.0 {
if point.y >= 0.0 {
value = atan(dpy / dpx) + π
} else {
value = atan(dpy / dpx) - π
}
} else {
if point.y > 0.0 {
value = Half_π
}
else if point.y < 0.0 {
value = -Half_π
}
else {
value = 0.0
}
}
return NormalizeAngle(value)
}
// ===================================
// MARK: ---- Angle Range ----
// ===================================
//////////////////////////////////////////////////////////////////////////
// Angle Range structure provides a simple way to store angle ranges
// and determine if a specific angle falls within.
//
struct FBAngleRange {
var minimum : Double
var maximum : Double
}
// NOTE: Should just use Swift:
// var something = FBAngleRange(minimum: 12.0, maximum: 4.0)
//func FBAngleRangeMake(minimum: CGFloat, maximum: CGFloat) -> FBAngleRange {
//
// return FBAngleRange(minimum: minimum, maximum: maximum)
//}
//func FBIsValueGreaterThanWithOptions(value: CGFloat, minimum: CGFloat, threshold: CGFloat) -> Bool {
//
// if FBAreValuesCloseWithOptions(value, value2: minimum, threshold: threshold) {
// return false
// }
//
// return value > minimum
//}
//
func FBIsValueGreaterThan(_ value: CGFloat, minimum: CGFloat) -> Bool {
return FBIsValueGreaterThanWithOptions(Double(value), minimum: Double(minimum), threshold: FBTangentClosenessThreshold)
}
func FBIsValueGreaterThanWithOptions(_ value: Double, minimum: Double, threshold: Double) -> Bool {
if FBAreValuesCloseWithOptions(value, value2: minimum, threshold: threshold) {
return false
}
return value > minimum
}
func FBIsValueGreaterThan(_ value: Double, minimum: Double) -> Bool {
return FBIsValueGreaterThanWithOptions(value, minimum: minimum, threshold: Double(FBTangentClosenessThreshold))
}
func FBIsValueLessThan(_ value: CGFloat, maximum: CGFloat) -> Bool {
if FBAreValuesCloseWithOptions(Double(value), value2: Double(maximum), threshold: FBTangentClosenessThreshold) {
return false
}
return value < maximum
}
func FBIsValueLessThan(_ value: Double, maximum: Double) -> Bool {
if FBAreValuesCloseWithOptions(value, value2: maximum, threshold: Double(FBTangentClosenessThreshold)) {
return false
}
return value < maximum
}
func FBIsValueGreaterThanEqual(_ value: CGFloat, minimum: CGFloat) -> Bool {
if FBAreValuesCloseWithOptions(Double(value), value2: Double(minimum), threshold: FBTangentClosenessThreshold) {
return true
}
return value >= minimum
}
func FBIsValueGreaterThanEqual(_ value: Double, minimum: Double) -> Bool {
if FBAreValuesCloseWithOptions(value, value2: minimum, threshold: Double(FBTangentClosenessThreshold)) {
return true
}
return value >= minimum
}
//
//func FBIsValueLessThanEqualWithOptions(value: CGFloat, maximum: CGFloat, threshold: CGFloat) -> Bool {
//
// if FBAreValuesCloseWithOptions(value, value2: maximum, threshold: threshold) {
// return true
// }
//
// return value <= maximum
//}
func FBIsValueLessThanEqualWithOptions(_ value: Double, maximum: Double, threshold: Double) -> Bool {
if FBAreValuesCloseWithOptions(value, value2: maximum, threshold: threshold) {
return true
}
return value <= maximum
}
func FBIsValueLessThanEqual(_ value: CGFloat, maximum: CGFloat) -> Bool {
return FBIsValueLessThanEqualWithOptions(Double(value), maximum: Double(maximum), threshold: FBTangentClosenessThreshold)
}
func FBIsValueLessThanEqual(_ value: Double, maximum: Double) -> Bool {
return FBIsValueLessThanEqualWithOptions(value, maximum: maximum, threshold: FBTangentClosenessThreshold)
}
func FBAngleRangeContainsAngle(_ range: FBAngleRange, angle: Double) -> Bool {
if range.minimum <= range.maximum {
return FBIsValueGreaterThan(angle, minimum: range.minimum) && FBIsValueLessThan(angle, maximum: range.maximum)
}
// The range wraps around 0. See if the angle falls in the first half
if FBIsValueGreaterThan(angle, minimum: range.minimum) && angle <= Two_π {
return true
}
return angle >= 0.0 && FBIsValueLessThan(angle, maximum: range.maximum)
}
// ===================================
// MARK: Parameter ranges
// ===================================
// FBRange is a range of parameter (t)
struct FBRange {
var minimum : Double
var maximum : Double
}
func FBRangeHasConverged(_ range: FBRange, decimalPlaces: Int) -> Bool {
let factor = pow(10.0, Double(decimalPlaces))
let minimum = Int(range.minimum * factor)
let maxiumum = Int(range.maximum * factor)
return minimum == maxiumum
}
func FBRangeGetSize(_ range: FBRange) -> Double {
return range.maximum - range.minimum
}
func FBRangeAverage(_ range: FBRange) -> Double {
return (range.minimum + range.maximum) / 2.0
}
func FBRangeScaleNormalizedValue(_ range: FBRange, value: Double) -> Double {
return (range.maximum - range.minimum) * value + range.minimum
}
func FBRangeUnion(_ range1: FBRange, range2: FBRange) -> FBRange {
return FBRange(minimum: min(range1.minimum, range2.minimum), maximum: max(range1.maximum, range2.maximum))
}
// ===================================
// MARK: Tangents
// ===================================
struct FBTangentPair {
var left: CGPoint
var right: CGPoint
}
func FBAreTangentsAmbigious(_ edge1Tangents: FBTangentPair, edge2Tangents: FBTangentPair) -> Bool {
let normalEdge1 = FBTangentPair(left: FBNormalizePoint(edge1Tangents.left), right: FBNormalizePoint(edge1Tangents.right))
let normalEdge2 = FBTangentPair(left: FBNormalizePoint(edge2Tangents.left), right: FBNormalizePoint(edge2Tangents.right))
return FBArePointsCloseWithOptions(normalEdge1.left, point2: normalEdge2.left, threshold: FBTangentClosenessThreshold)
|| FBArePointsCloseWithOptions(normalEdge1.left, point2: normalEdge2.right, threshold: FBTangentClosenessThreshold)
|| FBArePointsCloseWithOptions(normalEdge1.right, point2: normalEdge2.left, threshold: FBTangentClosenessThreshold)
|| FBArePointsCloseWithOptions(normalEdge1.right, point2: normalEdge2.right, threshold: FBTangentClosenessThreshold)
}
struct FBAnglePair {
var a: Double
var b: Double
}
func FBTangentsCross(_ edge1Tangents: FBTangentPair, edge2Tangents: FBTangentPair) -> Bool {
// Calculate angles for the tangents
let edge1Angles = FBAnglePair(a: PolarAngle(edge1Tangents.left), b: PolarAngle(edge1Tangents.right))
let edge2Angles = FBAnglePair(a: PolarAngle(edge2Tangents.left), b: PolarAngle(edge2Tangents.right))
// Count how many times edge2 angles appear between the self angles
let range1 = FBAngleRange(minimum: edge1Angles.a, maximum: edge1Angles.b)
var rangeCount1 = 0
if FBAngleRangeContainsAngle(range1, angle: edge2Angles.a) {
rangeCount1 += 1
}
if FBAngleRangeContainsAngle(range1, angle: edge2Angles.b) {
rangeCount1 += 1
}
// Count how many times self angles appear between the edge2 angles
let range2 = FBAngleRange(minimum: edge1Angles.b, maximum: edge1Angles.a)
var rangeCount2 = 0
if FBAngleRangeContainsAngle(range2, angle: edge2Angles.a) {
rangeCount2 += 1
}
if FBAngleRangeContainsAngle(range2, angle: edge2Angles.b) {
rangeCount2 += 1
}
// If each pair of angles split the other two, then the edges cross.
return rangeCount1 == 1 && rangeCount2 == 1
}
func FBLineBoundsMightOverlap(_ bounds1: CGRect, bounds2: CGRect) -> Bool
{
let left = Double(max(bounds1.minX, bounds2.minX))
let right = Double(min(bounds1.maxX, bounds2.maxX))
if FBIsValueGreaterThanWithOptions(left, minimum: right, threshold: FBBoundsClosenessThreshold) {
return false // no horizontal overlap
}
let top = Double(max(bounds1.minY, bounds2.minY))
let bottom = Double(min(bounds1.maxY, bounds2.maxY))
return FBIsValueLessThanEqualWithOptions(top, maximum: bottom, threshold: FBBoundsClosenessThreshold)
}
| 27.370036 | 200 | 0.688122 |
0a2a8e3eb23fde40e201dbdb02c90ddc6417cd98 | 989 | import XCTest
@testable import OpenColorKit
public final class OpenColorTealTests: XCTestCase {
public func testTeal0() {
XCTAssertNotNil(OpenColor.teal.teal0.color)
}
public func testTeal1() {
XCTAssertNotNil(OpenColor.teal.teal1.color)
}
public func testTeal2() {
XCTAssertNotNil(OpenColor.teal.teal2.color)
}
public func testTeal3() {
XCTAssertNotNil(OpenColor.teal.teal3.color)
}
public func testTeal4() {
XCTAssertNotNil(OpenColor.teal.teal4.color)
}
public func testTeal5() {
XCTAssertNotNil(OpenColor.teal.teal5.color)
}
public func testTeal6() {
XCTAssertNotNil(OpenColor.teal.teal6.color)
}
public func testTeal7() {
XCTAssertNotNil(OpenColor.teal.teal7.color)
}
public func testTeal8() {
XCTAssertNotNil(OpenColor.teal.teal8.color)
}
public func testTeal9() {
XCTAssertNotNil(OpenColor.teal.teal9.color)
}
}
| 21.5 | 51 | 0.659252 |
794faf8994fd650525fe78232cdf6d0ad8a8cda4 | 14,825 | // Copyright 2020 Espressif Systems
//
// 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.
//
// ESPBLETransport.swift
// ESPProvision
//
import CoreBluetooth
import Foundation
/// The `ESPBLEStatusDelegate` protocol define methods that provide information
/// of current BLE device connection status
protocol ESPBLEStatusDelegate {
/// Peripheral is connected successfully.
func peripheralConnected()
/// Perpiheral disconnected.
func peripheralDisconnected()
/// Failed to connect with peripheral.
func peripheralFailedToConnect()
}
/// Delegate which will receive events relating to BLE device scanning
protocol ESPBLETransportDelegate {
/// Peripheral devices found with matching Service UUID
/// Callers should call the BLETransport.connect method with
/// one of the peripherals found here
///
/// - Parameter peripherals: peripheral devices array
func peripheralsFound(peripherals: [String:CBPeripheral])
/// No peripherals found with matching Service UUID
///
/// - Parameter serviceUUID: the service UUID provided at the time of creating the BLETransport object
func peripheralsNotFound(serviceUUID: UUID?)
/// Peripheral device configured.
/// This tells the caller that the connected BLE device is now configured
/// and can be provisioned
///
/// - Parameter peripheral: peripheral that has been connected to
func peripheralConfigured(peripheral: CBPeripheral)
/// Peripheral device could not be configured.
/// This tells the called that the connected device cannot be configured for provisioning
/// - Parameter peripheral: peripheral that has been connected to
func peripheralNotConfigured(peripheral: CBPeripheral)
/// Peripheral device disconnected
///
/// - Parameters:
/// - peripheral: peripheral device
/// - error: error
func peripheralDisconnected(peripheral: CBPeripheral, error: Error?)
}
/// The `ESPBleTransport` class conforms and implememnt methods of `ESPCommunicable` protocol.
/// This class provides methods for sending configuration and session related data to `ESPDevice`.
class ESPBleTransport: NSObject, ESPCommunicable {
/// Instance of 'ESPUtility' class.
var utility: ESPUtility
private var transportToken = DispatchSemaphore(value: 1)
private var isBLEEnabled = false
private var scanTimeout = 5.0
private var readCounter = 0
private var deviceNamePrefix:String!
/// Stores Proof of Possesion for a device.
var proofOfPossession:String?
var centralManager: CBCentralManager!
var espressifPeripherals: [String:CBPeripheral] = [:]
var currentPeripheral: CBPeripheral?
var currentService: CBService?
var bleConnectTimer = Timer()
var bleDeviceConnected = false
var peripheralCanRead: Bool = true
var peripheralCanWrite: Bool = false
var currentRequestCompletionHandler: ((Data?, Error?) -> Void)?
public var delegate: ESPBLETransportDelegate?
var bleStatusDelegate: ESPBLEStatusDelegate?
/// Create BLETransport object.
///
/// - Parameters:
/// - deviceNamePrefix: Device name prefix.
/// - scanTimeout: Timeout in seconds for which BLE scan should happen.
init(scanTimeout: TimeInterval, deviceNamePrefix: String, proofOfPossession:String? = nil) {
ESPLog.log("Initalising BLE transport class with scan timeout \(scanTimeout)")
self.scanTimeout = scanTimeout
self.deviceNamePrefix = deviceNamePrefix
self.proofOfPossession = proofOfPossession
utility = ESPUtility()
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
/// BLE implementation of `ESPCommunicable` protocol.
///
/// - Parameters:
/// - data: Data to be sent.
/// - completionHandler: Handler called when data is sent.
func SendSessionData(data: Data,
completionHandler: @escaping (Data?, Error?) -> Void) {
ESPLog.log("Sending session data.")
guard peripheralCanWrite, peripheralCanRead,
let espressifPeripheral = currentPeripheral else {
completionHandler(nil, ESPTransportError.deviceUnreachableError("BLE device unreachable"))
return
}
transportToken.wait()
espressifPeripheral.writeValue(data, for: utility.sessionCharacteristic, type: .withResponse)
currentRequestCompletionHandler = completionHandler
}
/// BLE implemenation of the `ESPCommunicable` protocol
///
/// - Parameters:
/// - path: Path of the configuration endpoint.
/// - data: Data to be sent.
/// - completionHandler: Handler called when data is sent.
func SendConfigData(path: String,
data: Data,
completionHandler: @escaping (Data?, Error?) -> Void) {
ESPLog.log("Sending configration data to path \(path)")
guard peripheralCanWrite, peripheralCanRead,
let espressifPeripheral = currentPeripheral else {
completionHandler(nil, ESPTransportError.deviceUnreachableError("BLE device unreachable"))
return
}
transportToken.wait()
if let characteristic = utility.configUUIDMap[path] {
espressifPeripheral.writeValue(data, for: characteristic, type: .withResponse)
currentRequestCompletionHandler = completionHandler
} else {
completionHandler(nil,NSError(domain: "com.espressif.ble", code: 1, userInfo: [NSLocalizedDescriptionKey:"BLE characteristic does not exist."]))
transportToken.signal()
}
}
/// Connect to a BLE peripheral device.
///
/// - Parameters:
/// - peripheral: The peripheral device
/// - options: An optional dictionary specifying connection behavior options.
/// Sent as is to the CBCentralManager.connect function.
func connect(peripheral: CBPeripheral, withOptions options: [String: Any]?, delegate: ESPBLEStatusDelegate) {
ESPLog.log("Connecting peripheral device...")
self.bleStatusDelegate = delegate
if let currentPeripheral = currentPeripheral {
centralManager.cancelPeripheralConnection(currentPeripheral)
}
currentPeripheral = peripheral
centralManager.connect(currentPeripheral!, options: options)
currentPeripheral?.delegate = self
bleDeviceConnected = false
bleConnectTimer.invalidate()
ESPLog.log("Initiating timeout for connection completion.")
bleConnectTimer = Timer.scheduledTimer(timeInterval: 20, target: self, selector: #selector(bleConnectionTimeout), userInfo: nil, repeats: false)
}
/// This method is invoked on timeout of connection with BLE device.
@objc func bleConnectionTimeout() {
if !bleDeviceConnected {
ESPLog.log("Peripheral connection timeout occured.")
self.disconnect()
bleConnectTimer.invalidate()
bleStatusDelegate?.peripheralFailedToConnect()
}
}
/// Disconnect from the current connected peripheral.
func disconnect() {
if let currentPeripheral = currentPeripheral {
ESPLog.log("Cancelling peripheral connection.")
centralManager.cancelPeripheralConnection(currentPeripheral)
}
}
/// Scan for BLE devices.
///
/// - Parameter delegate: Delegate which will receive resulting events.
func scan(delegate: ESPBLETransportDelegate) {
ESPLog.log("Ble scan started...")
self.delegate = delegate
if isBLEEnabled {
_ = Timer.scheduledTimer(timeInterval: scanTimeout,
target: self,
selector: #selector(stopScan(timer:)),
userInfo: nil,
repeats: true)
centralManager.scanForPeripherals(withServices: nil)
}
}
/// Stop scan when timer runs off.
@objc func stopScan(timer: Timer) {
ESPLog.log("Ble scan stopped.")
centralManager.stopScan()
timer.invalidate()
if espressifPeripherals.count > 0 {
delegate?.peripheralsFound(peripherals: espressifPeripherals)
espressifPeripherals.removeAll()
} else {
delegate?.peripheralsNotFound(serviceUUID: UUID(uuidString: ""))
}
}
/// BLE implementation of `ESPCommunicable` protocol.
func isDeviceConfigured() -> Bool {
ESPLog.log("Device configured status: \(utility.peripheralConfigured)")
return utility.peripheralConfigured
}
}
// MARK: CBCentralManagerDelegate
extension ESPBleTransport: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
ESPLog.log("Bluetooth state unknown")
case .resetting:
ESPLog.log("Bluetooth state resetting")
case .unsupported:
ESPLog.log("Bluetooth state unsupported")
case .unauthorized:
ESPLog.log("Bluetooth state unauthorized")
case .poweredOff:
if let currentPeripheral = currentPeripheral {
delegate?.peripheralDisconnected(peripheral: currentPeripheral, error: nil)
}
ESPLog.log("Bluetooth state off")
case .poweredOn:
ESPLog.log("Bluetooth state on")
isBLEEnabled = true
_ = Timer.scheduledTimer(timeInterval: scanTimeout,
target: self,
selector: #selector(stopScan(timer:)),
userInfo: nil,
repeats: true)
centralManager.scanForPeripherals(withServices: nil)
@unknown default: break
}
}
func centralManager(_: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData data: [String: Any],
rssi _: NSNumber) {
ESPLog.log("Peripheral devices discovered.\(data.debugDescription)")
if let peripheralName = data["kCBAdvDataLocalName"] as? String ?? peripheral.name {
if peripheralName.lowercased().hasPrefix(deviceNamePrefix.lowercased()) {
espressifPeripherals[peripheralName] = peripheral
}
}
}
func centralManager(_: CBCentralManager, didConnect _: CBPeripheral) {
ESPLog.log("Connected to peripheral. Discover services.")
currentPeripheral?.discoverServices(nil)
}
func centralManager(_: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
ESPLog.log("Fail to connect to peripheral.")
delegate?.peripheralDisconnected(peripheral: peripheral, error: error)
}
func centralManager(_: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
ESPLog.log("Disconnected with peripheral")
delegate?.peripheralDisconnected(peripheral: peripheral, error: error)
}
}
// MARK: CBPeripheralDelegate
extension ESPBleTransport: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices _: Error?) {
ESPLog.log("Peripheral did discover services.")
guard let services = peripheral.services else { return }
currentPeripheral = peripheral
currentService = services[0]
if let currentService = currentService {
currentPeripheral?.discoverCharacteristics(nil, for: currentService)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error _: Error?) {
ESPLog.log("Peripheral did discover chatacteristics.")
guard let characteristics = service.characteristics else { return }
peripheralCanWrite = true
readCounter = characteristics.count
for characteristic in characteristics {
if !characteristic.properties.contains(.read) {
peripheralCanRead = false
}
if !characteristic.properties.contains(.write) {
peripheralCanWrite = false
}
currentPeripheral?.discoverDescriptors(for: characteristic)
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
ESPLog.log("Writing value for characterisitic \(characteristic)")
guard error == nil else {
currentRequestCompletionHandler?(nil, error)
return
}
peripheral.readValue(for: characteristic)
}
func peripheral(_: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
ESPLog.log("Updating value for characterisitic \(characteristic)")
guard error == nil else {
currentRequestCompletionHandler?(nil, error)
return
}
if let currentRequestCompletionHandler = currentRequestCompletionHandler {
DispatchQueue.global().async {
currentRequestCompletionHandler(characteristic.value, nil)
}
self.currentRequestCompletionHandler = nil
}
transportToken.signal()
}
func peripheral(_: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error _: Error?) {
ESPLog.log("Did sicover descriptor for characterisitic: \(characteristic)")
for descriptor in characteristic.descriptors! {
currentPeripheral?.readValue(for: descriptor)
}
}
func peripheral(_: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error _: Error?) {
ESPLog.log("Did update value for descriptor: \(descriptor)")
utility.processDescriptor(descriptor: descriptor)
readCounter -= 1
if readCounter < 1 {
if utility.peripheralConfigured {
bleConnectTimer.invalidate()
bleStatusDelegate?.peripheralConnected()
}
}
}
}
| 39.219577 | 156 | 0.657875 |
1d498908f451c5dd1071e6f0d8e5f33f7b66cd91 | 1,623 | // AppView.swift
// Copyright (c) 2022 Joe Blau
import ComposableArchitecture
import SwiftUI
struct AppView: View {
let store: Store<AppState, AppAction>
var body: some View {
WithViewStore(store) { viewStore in
TabView(selection: viewStore.binding(\.$selectedTab)) {
ChartsView(store: store)
.tabItem {
Image(systemName: "chart.line.uptrend.xyaxis")
Text("Chart")
}
.tag(Tab.charts)
AccountsView(store: store)
.tabItem {
Image(systemName: "creditcard.fill")
Text("Accounts")
}
.tag(Tab.accounts)
PlanView(store: store)
.tabItem {
Image(systemName: "calendar")
Text("Plan")
}
.tag(Tab.calculator)
}
.preferredColorScheme(viewStore.colorScheme)
.sheet(item: viewStore.binding(\.$modalPresent), content: { modalPresent in
switch modalPresent {
case .edit: EditView(store: store)
case .speculate: SpeculateView(store: store,
price: viewStore.speculativePrice.doubleValue)
}
})
}
}
}
#if DEBUG
struct AppView_Previews: PreviewProvider {
static var previews: some View {
AppView(store: sampleAppStore)
}
}
#endif
| 29.509091 | 93 | 0.473198 |
d5bcd798534efb8b567f020390196dad4e526e32 | 193 | struct Todo {
let id: String
let title: String
let done: Bool
}
extension Todo: CustomStringConvertible {
var description: String {
return "[\(done ? "x" : " ")] \(title)"
}
}
| 16.083333 | 41 | 0.611399 |
ef592062c84e454d34c959ed57e04e07467ddbdb | 898 | //
// ChildMOCCreationTests.swift
// CoreDataStack
//
// Created by Robert Edwards on 4/22/16.
// Copyright © 2015-2016 Big Nerd Ranch. All rights reserved.
//
import XCTest
@testable import CoreDataStack
class ChildMOCCreationTests: TempDirectoryTestCase {
var stack: CoreDataStack!
override func setUp() {
super.setUp()
do {
stack = try CoreDataStack.constructInMemoryStack(modelName: "Sample", in: unitTestBundle)
} catch {
XCTFail("Unexpected error in test: \(error)")
}
}
func testBackgroundMOCCreation() {
XCTAssertEqual(stack.newChildContext(type: .privateQueueConcurrencyType).concurrencyType, .privateQueueConcurrencyType)
}
func testMainQueueMOCCreation() {
XCTAssertEqual(stack.newChildContext(type: .mainQueueConcurrencyType).concurrencyType, .mainQueueConcurrencyType)
}
}
| 25.657143 | 127 | 0.698218 |
edd15f3b00a7dce580455c4989f6a05b73089674 | 1,262 | //
// tipCalculatorUITests.swift
// tipCalculatorUITests
//
// Created by David Wayman on 11/27/15.
// Copyright © 2015 David Wayman. All rights reserved.
//
import XCTest
class tipCalculatorUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.108108 | 182 | 0.667195 |
692367da1b28c77482af4c877c781ed074c9f338 | 1,428 | //
// AppDelegate.swift
// SimpleLoginSystem
//
// Created by Gaspard Rosay on 27.01.20.
// Copyright © 2020 Gaspard Rosay. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.578947 | 179 | 0.7493 |
f7bc45b0f3aa3813ebffb7c4432af0f60607afd2 | 9,056 | //
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
@testable import ENA
import Foundation
import XCTest
class ExposureSubmissionCoordinatorTests: XCTestCase {
// MARK: - Attributes.
private var parentNavigationController: UINavigationController!
private var exposureSubmissionService: MockExposureSubmissionService!
// swiftlint:disable:next weak_delegate
private var delegate: MockExposureSubmissionCoordinatorDelegate!
// MARK: - Setup and teardown methods.
override func setUp() {
parentNavigationController = UINavigationController()
exposureSubmissionService = MockExposureSubmissionService()
delegate = MockExposureSubmissionCoordinatorDelegate()
}
// MARK: - Helper methods.
private func createCoordinator(
parentNavigationController: UINavigationController,
exposureSubmissionService: ExposureSubmissionService,
delegate: ExposureSubmissionCoordinatorDelegate) -> ExposureSubmissionCoordinator {
return ExposureSubmissionCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
}
private func getNavigationController(from coordinator: ExposureSubmissionCoordinating) -> UINavigationController? {
guard let navigationController = (coordinator as? ExposureSubmissionCoordinator)?.navigationController else {
XCTFail("Could not load navigation controller from coordinator.")
return nil
}
return navigationController
}
// MARK: - Navigation tests.
func testStart_default() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionIntroViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
}
func testStart_withResult() {
let result = TestResult.negative
exposureSubmissionService.hasRegistrationTokenCallback = { true }
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: result)
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionTestResultViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
XCTAssertNotNil(vc.exposureSubmissionService)
XCTAssertEqual(vc.testResult, result)
}
func testDismiss() {
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = parentNavigationController
window.makeKeyAndVisible()
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
let expectation = self.expectation(description: "Expect delegate to be called on disappear.")
delegate.onExposureSubmissionCoordinatorWillDisappear = { _ in expectation.fulfill() }
XCTAssertNil(parentNavigationController.presentedViewController)
coordinator.start(with: nil)
XCTAssertNotNil(parentNavigationController.presentedViewController)
coordinator.dismiss()
waitForExpectations(timeout: 1.0)
}
func testShowOverview() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showOverviewScreen()
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
XCTAssertNotNil(navigationController?.topViewController as? ExposureSubmissionOverviewViewController)
}
func testShowTestResultScreen() {
let result = TestResult.negative
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showTestResultScreen(with: result)
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionTestResultViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
XCTAssertNotNil(vc.exposureSubmissionService)
XCTAssertEqual(vc.testResult, result)
}
func testShowHotlineScreen() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showHotlineScreen()
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionHotlineViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
}
func testShowTanScreen() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showTanScreen()
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionTanInputViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
XCTAssertNotNil(vc.exposureSubmissionService)
}
func testShowWarnOthersScreen() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showWarnOthersScreen()
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
XCTAssertNotNil(navigationController?.topViewController as? ExposureSubmissionWarnOthersViewController)
}
func testShowThankYouScreen() {
let coordinator = createCoordinator(
parentNavigationController: parentNavigationController,
exposureSubmissionService: exposureSubmissionService,
delegate: delegate
)
coordinator.start(with: nil)
coordinator.showThankYouScreen()
// Get navigation controller and make sure to load view.
let navigationController = getNavigationController(from: coordinator)
_ = navigationController?.view
XCTAssertNotNil(navigationController)
XCTAssertNotNil(navigationController?.topViewController)
guard let vc = navigationController?.topViewController as? ExposureSubmissionSuccessViewController else {
XCTFail("Could not load presented view controller.")
return
}
XCTAssertNotNil(vc.coordinator)
}
}
| 32.693141 | 116 | 0.80466 |
e6b855b1c1d738f066b4f6fff58146fb593b6e50 | 1,238 | // 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: "RayonModule",
platforms: [
.macOS(.v11),
.iOS(.v14),
],
products: [
.library(
name: "RayonModule",
type: .static,
targets: ["RayonModule"]
),
// so we can save disk space for menubar app
// .library(
// name: "RayonModule-Framework",
// type: .dynamic,
// targets: ["RayonModule"]
// ),
],
dependencies: [
.package(name: "PropertyWrapper", path: "../PropertyWrapper"),
.package(name: "NSRemoteShell", path: "../NSRemoteShell"),
.package(name: "XTerminalUI", path: "../XTerminalUI"),
.package(name: "XMLCoder", path: "../XMLCoder"),
.package(name: "Keychain", path: "../Keychain"),
],
targets: [
.target(
name: "RayonModule",
dependencies: [
"PropertyWrapper",
"NSRemoteShell",
"XTerminalUI",
"XMLCoder",
"Keychain",
]
),
]
)
| 27.511111 | 96 | 0.5 |
1dddf1b50639a8479e89f0d6058949bc388e298f | 2,045 | //
// DragGestureExample3.swift
// Gestures
//
// Created by Stewart Lynch on 2020-06-15.
// Copyright © 2020 CreaTECH Solutions. All rights reserved.
//
import SwiftUI
struct DragGestureExample2: View {
let topOffset: CGFloat = 80
let bottomOffset: CGFloat = 120
@State private var dragOffset: CGSize = .zero
@State private var position: CGSize = .zero
var body: some View {
ZStack {
Text("Hello World")
Rectangle()
.fill(Color.blue)
.cornerRadius(30)
.offset(y: topOffset + dragOffset.height + position.height)
.gesture(DragGesture()
.onChanged{ self.dragOffset = $0.translation }
.onEnded({ (value) in
withAnimation(.spring()) {
if self.position == .zero {
// at the top
if value.translation.height < 0 || value.translation.height < 150 {
self.position = .zero
} else {
self.position.height = UIScreen.main.bounds.height - self.bottomOffset
}
} else {
// We are at the bottom
if value.translation.height > 0 || value.translation.height > -150 {
self.position.height = UIScreen.main.bounds.height - self.bottomOffset
} else {
self.position = .zero
}
}
self.dragOffset = .zero
}
})
)
.edgesIgnoringSafeArea(.all)
}
}
}
struct DragGestureExample2_Previews: PreviewProvider {
static var previews: some View {
DragGestureExample2()
}
}
| 35.877193 | 106 | 0.443032 |
fc426c608b2fd73c0758ae2d41abdb93fbdfe24a | 569 | //
// CheckinTableViewCell.swift
// Spoint
//
// Created by kalyan on 23/11/17.
// Copyright © 2017 Personal. All rights reserved.
//
import UIKit
class CheckinTableViewCell: UITableViewCell {
@IBOutlet var locationLbl : UILabel!
@IBOutlet var timelabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.884615 | 65 | 0.669596 |
e92f126440dde762fb9ad51a42d2281246b6e412 | 2,694 | // MenuViewTableViewCell.swift
// Copyright (c) 2017 Nyx0uf
//
// 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
final class MenuViewTableViewCell : UITableViewCell
{
// MARK: - Public properties
// Section image
private(set) var ivLogo: UIImageView!
// Section label
private(set) var lblSection: UILabel!
// MARK: - Initializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 0)
self.isAccessibilityElement = true
self.selectionStyle = .none
self.layoutMargins = .zero
let logoSize = CGSize(96.0, 96.0)
self.ivLogo = UIImageView(frame: CGRect(48.0, (128.0 - logoSize.height) * 0.5, logoSize))
self.contentView.addSubview(self.ivLogo)
self.lblSection = UILabel(frame: CGRect(0.0, 0.0, logoSize.width + 32.0, 32.0))
self.lblSection.font = UIFont.systemFont(ofSize: 14.0)
self.contentView.addSubview(self.lblSection)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
self.backgroundColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 0)
self.isAccessibilityElement = true
self.selectionStyle = .none
self.layoutMargins = .zero
let logoSize = CGSize(96.0, 96.0)
self.ivLogo = UIImageView(frame: CGRect(48.0, (128.0 - logoSize.height) * 0.5, logoSize))
self.contentView.addSubview(self.ivLogo)
self.lblSection = UILabel(frame: CGRect(0.0, 0.0, logoSize.width + 32.0, 32.0))
self.lblSection.font = UIFont.systemFont(ofSize: 14.0)
self.contentView.addSubview(self.lblSection)
}
}
| 39.043478 | 95 | 0.746845 |
b99432c3d175827ceeb0aefb4ce3c4ff12c4df16 | 430 | //
// DateExt.swift
// BiketoTibet
//
// Created by 李京城 on 2020/4/9.
//
import Foundation
extension Date {
public static var formatter: DateFormatter {
return DateFormatter()
}
public func string(withFormat format: String = "yyyy.MM.dd") -> String {
let dateFormatter = Date.formatter
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
| 19.545455 | 76 | 0.630233 |
dd73f5bdf1afd70ec637f7c0622cca46c2edb46c | 2,525 | //
// Logger.swift
// Lunar
//
// Created by Alin on 07/07/2018.
// Copyright © 2018 Alin. All rights reserved.
//
import Defaults
import Foundation
import SwiftyBeaver
class Logger: SwiftyBeaver {
static let console = ConsoleDestination()
static let file = FileDestination()
static var debugModeObserver: DefaultsObservation?
class func initLogger() {
console.format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - $M \n$X"
file.format = "$DHH:mm:ss.SSS$d $L $N.$F:$l - $M \n$X"
setMinLevel(debug: Defaults[.debug])
debugModeObserver = Defaults.observe(.debug) { change in
self.setMinLevel(debug: change.newValue)
}
Logger.addDestination(console)
Logger.addDestination(file)
}
class func setMinLevel(debug _: Bool) {
if !Defaults[.debug] {
console.minLevel = .info
file.minLevel = .info
} else {
console.minLevel = .verbose
file.minLevel = .verbose
}
}
override open class func verbose(
_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
line: Int = #line,
context: Any? = nil
) {
super.verbose(message(), file, function, line: line, context: context)
}
override open class func debug(
_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
line: Int = #line,
context: Any? = nil
) {
super.debug(message(), file, function, line: line, context: context)
}
override open class func info(
_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
line: Int = #line,
context: Any? = nil
) {
super.info(message(), file, function, line: line, context: context)
}
override open class func warning(
_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
line: Int = #line,
context: Any? = nil
) {
super.warning(message(), file, function, line: line, context: context)
}
override open class func error(
_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
line: Int = #line,
context: Any? = nil
) {
super.error(message(), file, function, line: line, context: context)
}
}
| 26.302083 | 78 | 0.564752 |
fc6cf4834bf39472c1a55bc1f610593214d6b2c4 | 2,956 | //
// LoggingService.swift
// Logging
//
// Copyright (c) 2020 Anodized Software, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
public class LoggingService<CategoryType>
where CategoryType: Hashable & CaseIterable & RawRepresentable,
CategoryType.RawValue == String {
private var loggers: [CategoryType: Logger<CategoryType>]!
public private(set) var destinations: [AnyDestination<CategoryType>] = []
public var fileDestinations: [AnyFileDestination<CategoryType>] {
return destinations.compactMap {
$0 as? AnyFileDestination<CategoryType>
}
}
public init() {
self.loggers = {
var d = [CategoryType: Logger<CategoryType>]()
for c in CategoryType.allCases {
d[c] = Logger(parent: self, category: c)
}
return d
}()
}
public func add<DestinationType>(destination: DestinationType) where DestinationType: Destination, DestinationType.CategoryType == CategoryType {
destinations.append(AnyDestination(destination: destination))
}
public func add<DestinationType>(fileDestination: DestinationType) where DestinationType: FileDestination, DestinationType.CategoryType == CategoryType {
destinations.append(AnyFileDestination(fileDestination: fileDestination))
}
public func setMinimumLevel(_ level: Level) {
for logger in loggers.values {
logger.minimumLevel = level
}
}
internal func log(_ message: Message<CategoryType>) {
destinations.forEach {
$0.log(message)
}
}
public func logger(for category: CategoryType) -> Logger<CategoryType> {
return loggers[category]!
}
public subscript(_ category: CategoryType) -> Logger<CategoryType> {
get {
return loggers[category]!
}
}
}
| 36.04878 | 157 | 0.689783 |
fec516bfed56f5587cbba2765781eecb0f9c3cba | 1,211 | //
// UIStoryboard+Controllers.swift
// MovieApp
//
// Created by Anshul Shah on 12/11/18.
// Copyright © 2018 Anshul Shah. All rights reserved.
//
import Foundation
import UIKit
extension UIStoryboard {
static var main: UIStoryboard {
return UIStoryboard(name: "Main", bundle: nil)
}
}
extension UIStoryboard {
var moviesListViewController: MoviesListViewController {
guard let viewController = instantiateViewController(withIdentifier: String(describing: MoviesListViewController.self)) as? MoviesListViewController else {
fatalError(String(describing: MoviesListViewController.self) + "\(NSLocalizedString("couldn't be found in Storyboard file", comment: ""))")
}
return viewController
}
var movieDetailsViewController: MovieDetailsViewController {
guard let viewController = instantiateViewController(withIdentifier: String(describing: MovieDetailsViewController.self)) as? MovieDetailsViewController else {
fatalError(String(describing: MovieDetailsViewController.self) + "\(NSLocalizedString("couldn't be found in Storyboard file", comment: ""))")
}
return viewController
}
}
| 31.868421 | 167 | 0.718415 |
e639608ff1b78b80d919873d1eabbf6fe3765829 | 34,808 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// XFAIL: interpret
import StdlibUnittest
#if _runtime(_ObjC)
import Foundation // For NSRange
#endif
extension String {
var bufferID: UInt {
return unsafeBitCast(_core._owner, to: UInt.self)
}
var nativeCapacity: Int {
return _core.nativeBuffer!.capacity
}
var capacity: Int {
return _core.nativeBuffer?.capacity ?? 0
}
}
var StringTests = TestSuite("StringTests")
StringTests.test("sizeof") {
expectEqual(3 * sizeof(Int.self), sizeof(String.self))
}
func checkUnicodeScalarViewIteration(
_ expectedScalars: [UInt32], _ str: String
) {
do {
let us = str.unicodeScalars
var i = us.startIndex
let end = us.endIndex
var decoded: [UInt32] = []
while i != end {
expectTrue(i < i.successor()) // Check for Comparable conformance
decoded.append(us[i].value)
i = i.successor()
}
expectEqual(expectedScalars, decoded)
}
do {
let us = str.unicodeScalars
let start = us.startIndex
var i = us.endIndex
var decoded: [UInt32] = []
while i != start {
i = i.predecessor()
decoded.append(us[i].value)
}
expectEqual(expectedScalars, decoded)
}
}
StringTests.test("unicodeScalars") {
checkUnicodeScalarViewIteration([], "")
checkUnicodeScalarViewIteration([ 0x0000 ], "\u{0000}")
checkUnicodeScalarViewIteration([ 0x0041 ], "A")
checkUnicodeScalarViewIteration([ 0x007f ], "\u{007f}")
checkUnicodeScalarViewIteration([ 0x0080 ], "\u{0080}")
checkUnicodeScalarViewIteration([ 0x07ff ], "\u{07ff}")
checkUnicodeScalarViewIteration([ 0x0800 ], "\u{0800}")
checkUnicodeScalarViewIteration([ 0xd7ff ], "\u{d7ff}")
checkUnicodeScalarViewIteration([ 0x8000 ], "\u{8000}")
checkUnicodeScalarViewIteration([ 0xe000 ], "\u{e000}")
checkUnicodeScalarViewIteration([ 0xfffd ], "\u{fffd}")
checkUnicodeScalarViewIteration([ 0xffff ], "\u{ffff}")
checkUnicodeScalarViewIteration([ 0x10000 ], "\u{00010000}")
checkUnicodeScalarViewIteration([ 0x10ffff ], "\u{0010ffff}")
}
StringTests.test("indexComparability") {
let empty = ""
expectTrue(empty.startIndex == empty.endIndex)
expectFalse(empty.startIndex != empty.endIndex)
expectTrue(empty.startIndex <= empty.endIndex)
expectTrue(empty.startIndex >= empty.endIndex)
expectFalse(empty.startIndex > empty.endIndex)
expectFalse(empty.startIndex < empty.endIndex)
let nonEmpty = "borkus biqualificated"
expectFalse(nonEmpty.startIndex == nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex != nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex <= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex >= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex > nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex < nonEmpty.endIndex)
}
StringTests.test("ForeignIndexes/Valid") {
// It is actually unclear what the correct behavior is. This test is just a
// change detector.
//
// <rdar://problem/18037897> Design, document, implement invalidation model
// for foreign String indexes
do {
let donor = "abcdef"
let acceptor = "uvwxyz"
expectEqual("u", acceptor[donor.startIndex])
expectEqual("wxy",
acceptor[donor.startIndex.advanced(by: 2)..<donor.startIndex.advanced(by: 5)])
}
do {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}", acceptor[donor.startIndex])
expectEqual("\u{fffd}", acceptor[donor.startIndex.successor()])
expectEqualUnicodeScalars([ 0xfffd, 0x1f602, 0xfffd ],
acceptor[donor.startIndex.advanced(by: 1)..<donor.startIndex.advanced(by: 5)])
expectEqualUnicodeScalars([ 0x1f602, 0xfffd ],
acceptor[donor.startIndex.advanced(by: 2)..<donor.startIndex.advanced(by: 5)])
}
}
StringTests.test("ForeignIndexes/UnexpectedCrash")
.xfail(
.always("<rdar://problem/18029290> String.Index caches the grapheme " +
"cluster size, but it is not always correct to use"))
.code {
let donor = "\u{1f601}\u{1f602}\u{1f603}"
let acceptor = "abcdef"
// FIXME: this traps right now when trying to construct Character("ab").
expectEqual("a", acceptor[donor.startIndex])
}
StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("u", acceptor[donor.startIndex.advanced(by: 0)])
expectEqual("v", acceptor[donor.startIndex.advanced(by: 1)])
expectEqual("w", acceptor[donor.startIndex.advanced(by: 2)])
expectCrashLater()
acceptor[donor.startIndex.advanced(by: 3)]
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.startIndex.advanced(by: 3)])
expectCrashLater()
acceptor[donor.startIndex..<donor.startIndex.advanced(by: 4)]
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.startIndex.advanced(by: 3)])
expectCrashLater()
acceptor[donor.startIndex.advanced(by: 4)..<donor.startIndex.advanced(by: 5)]
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/1") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.startIndex.successor(), with: "u")
expectEqual("uvw", acceptor)
expectCrashLater()
acceptor.replaceSubrange(
donor.startIndex..<donor.startIndex.advanced(by: 4), with: "")
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.startIndex.successor(), with: "u")
expectEqual("uvw", acceptor)
expectCrashLater()
acceptor.replaceSubrange(
donor.startIndex.advanced(by: 4)..<donor.startIndex.advanced(by: 5), with: "")
}
StringTests.test("ForeignIndexes/removeAt/OutOfBoundsTrap") {
do {
let donor = "abcdef"
var acceptor = "uvw"
let removed = acceptor.remove(at: donor.startIndex)
expectEqual("u", removed)
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
expectCrashLater()
acceptor.remove(at: donor.startIndex.advanced(by: 4))
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/1") {
do {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.removeSubrange(
donor.startIndex..<donor.startIndex.successor())
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
expectCrashLater()
acceptor.removeSubrange(
donor.startIndex..<donor.startIndex.advanced(by: 4))
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
expectCrashLater()
acceptor.removeSubrange(
donor.startIndex.advanced(by: 4)..<donor.startIndex.advanced(by: 5))
}
StringTests.test("_splitFirst") {
var (before, after, found) = "foo.bar"._splitFirst(separator: ".")
expectTrue(found)
expectEqual("foo", before)
expectEqual("bar", after)
}
StringTests.test("hasPrefix")
.skip(.nativeRuntime("String.hasPrefix undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
expectFalse("".hasPrefix(""))
expectFalse("".hasPrefix("a"))
expectFalse("a".hasPrefix(""))
expectTrue("a".hasPrefix("a"))
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
expectFalse("abc".hasPrefix("a\u{0301}"))
expectFalse("a\u{0301}bc".hasPrefix("a"))
expectTrue("\u{00e1}bc".hasPrefix("a\u{0301}"))
expectTrue("a\u{0301}bc".hasPrefix("\u{00e1}"))
#else
expectUnreachable()
#endif
}
StringTests.test("literalConcatenation") {
do {
// UnicodeScalarLiteral + UnicodeScalarLiteral
var s = "1" + "2"
expectType(String.self, &s)
expectEqual("12", s)
}
do {
// UnicodeScalarLiteral + ExtendedGraphemeClusterLiteral
var s = "1" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("1a\u{0301}", s)
}
do {
// UnicodeScalarLiteral + StringLiteral
var s = "1" + "xyz"
expectType(String.self, &s)
expectEqual("1xyz", s)
}
do {
// ExtendedGraphemeClusterLiteral + UnicodeScalar
var s = "a\u{0301}" + "z"
expectType(String.self, &s)
expectEqual("a\u{0301}z", s)
}
do {
// ExtendedGraphemeClusterLiteral + ExtendedGraphemeClusterLiteral
var s = "a\u{0301}" + "e\u{0302}"
expectType(String.self, &s)
expectEqual("a\u{0301}e\u{0302}", s)
}
do {
// ExtendedGraphemeClusterLiteral + StringLiteral
var s = "a\u{0301}" + "xyz"
expectType(String.self, &s)
expectEqual("a\u{0301}xyz", s)
}
do {
// StringLiteral + UnicodeScalar
var s = "xyz" + "1"
expectType(String.self, &s)
expectEqual("xyz1", s)
}
do {
// StringLiteral + ExtendedGraphemeClusterLiteral
var s = "xyz" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("xyza\u{0301}", s)
}
do {
// StringLiteral + StringLiteral
var s = "xyz" + "abc"
expectType(String.self, &s)
expectEqual("xyzabc", s)
}
}
StringTests.test("appendToSubstring") {
for initialSize in 1..<16 {
for sliceStart in [ 0, 2, 8, initialSize ] {
for sliceEnd in [ 0, 2, 8, sliceStart + 1 ] {
if sliceStart > initialSize || sliceEnd > initialSize ||
sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: UnicodeScalar("x"), count: initialSize)
let originalIdentity = s0.bufferID
s0 = s0[
s0.startIndex.advanced(by: sliceStart)..<s0.startIndex.advanced(by: sliceEnd)]
expectEqual(originalIdentity, s0.bufferID)
s0 += "x"
// For a small string size, the allocator could round up the allocation
// and we could get some unused capacity in the buffer. In that case,
// the identity would not change.
if sliceEnd != initialSize {
expectNotEqual(originalIdentity, s0.bufferID)
}
expectEqual(
String(
repeating: UnicodeScalar("x"),
count: sliceEnd - sliceStart + 1),
s0)
}
}
}
}
StringTests.test("appendToSubstringBug") {
// String used to have a heap overflow bug when one attempted to append to a
// substring that pointed to the end of a string buffer.
//
// Unused capacity
// VVV
// String buffer [abcdefghijk ]
// ^ ^
// +----+
// Substring -----------+
//
// In the example above, there are only three elements of unused capacity.
// The bug was that the implementation mistakenly assumed 9 elements of
// unused capacity (length of the prefix "abcdef" plus truly unused elements
// at the end).
let size = 1024 * 16
let suffixSize = 16
let prefixSize = size - suffixSize
for i in 1..<10 {
// We will be overflowing s0 with s1.
var s0 = String(repeating: UnicodeScalar("x"), count: size)
let s1 = String(repeating: UnicodeScalar("x"), count: prefixSize)
let originalIdentity = s0.bufferID
// Turn s0 into a slice that points to the end.
s0 = s0[s0.startIndex.advanced(by: prefixSize)..<s0.endIndex]
// Slicing should not reallocate.
expectEqual(originalIdentity, s0.bufferID)
// Overflow.
s0 += s1
// We should correctly determine that the storage is too small and
// reallocate.
expectNotEqual(originalIdentity, s0.bufferID)
expectEqual(
String(
repeating: UnicodeScalar("x"),
count: suffixSize + prefixSize),
s0)
}
}
StringTests.test("COW/removeSubrange/start") {
var str = "12345678"
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
do {
let slice = str
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.startIndex.advanced(by: 1))
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("2345678", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.startIndex.advanced(by: 1))
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("345678", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("345678", str)
do {
let heapStrIdentity1 = str.bufferID
let slice = str
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("345678", str)
expectEqual("345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.startIndex.advanced(by: 1))
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity2 = str.bufferID
expectEqual("45678", str)
expectEqual("345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.startIndex.advanced(by: 1))
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity2, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("5678", str)
expectEqual("345678", slice)
}
}
StringTests.test("COW/removeSubrange/end") {
var str = "12345678"
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
expectEqual("12345678", str)
do {
let slice = str
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.append(UnicodeScalar("x"))
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("1234567", str)
expectEqual("12345678", slice)
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
str.append(UnicodeScalar("x"))
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
//expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("123456", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("123456", str)
do {
let heapStrIdentity1 = str.bufferID
let slice = str
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("123456", str)
expectEqual("123456", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("12345", str)
expectEqual("123456", slice)
// No more reallocations are expected.
str.append(UnicodeScalar("x"))
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("12345", str)
expectEqual("123456", slice)
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
str.append(UnicodeScalar("x"))
str.removeSubrange(str.endIndex.advanced(by: -1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
//expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("1234", str)
expectEqual("123456", slice)
}
}
StringTests.test("COW/replaceSubrange/end") {
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
var slice = str[str.startIndex..<str.startIndex.advanced(by: 7)]
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("1234567", slice)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(literalIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(slice.endIndex.advanced(by: -1)..<slice.endIndex, with: "b")
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, slice.bufferID)
// end FIXME
expectEqual(literalIdentity, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
// Move the string to the heap.
str.reserveCapacity(32)
expectNotEqual(literalIdentity, str.bufferID)
let heapStrIdentity1 = str.bufferID
var slice = str[str.startIndex..<str.startIndex.advanced(by: 7)]
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(heapStrIdentity1, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
let heapStrIdentity2 = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(slice.endIndex.advanced(by: -1)..<slice.endIndex, with: "b")
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity2, slice.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
}
func asciiString<
S: Sequence where S.Iterator.Element == Character
>(_ content: S) -> String {
var s = String()
s.append(contentsOf: content)
expectEqual(1, s._core.elementWidth)
return s
}
StringTests.test("stringCoreExtensibility")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let ascii = UTF16.CodeUnit(UnicodeScalar("X").value)
let nonAscii = UTF16.CodeUnit(UnicodeScalar("é").value)
for k in 0..<3 {
for count in 1..<16 {
for boundary in 0..<count {
var x = (
k == 0 ? asciiString("b".characters)
: k == 1 ? ("b" as NSString as String)
: ("b" as NSMutableString as String)
)._core
if k == 0 { expectEqual(1, x.elementWidth) }
for i in 0..<count {
x.append(contentsOf:
repeatElement(i < boundary ? ascii : nonAscii, count: 3))
}
// Make sure we can append pure ASCII to wide storage
x.append(contentsOf: repeatElement(ascii, count: 2))
expectEqualSequence(
[UTF16.CodeUnit(UnicodeScalar("b").value)]
+ Array(repeatElement(ascii, count: 3*boundary))
+ repeatElement(nonAscii, count: 3*(count - boundary))
+ repeatElement(ascii, count: 2),
x
)
}
}
}
#else
expectUnreachable()
#endif
}
StringTests.test("stringCoreReserve")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
for k in 0...5 {
var base: String
var startedNative: Bool
let shared: String = "X"
switch k {
case 0: (base, startedNative) = (String(), true)
case 1: (base, startedNative) = (asciiString("x".characters), true)
case 2: (base, startedNative) = ("Ξ", true)
case 3: (base, startedNative) = ("x" as NSString as String, false)
case 4: (base, startedNative) = ("x" as NSMutableString as String, false)
case 5: (base, startedNative) = (shared, true)
default:
fatalError("case unhandled!")
}
expectEqual(!base._core.hasCocoaBuffer, startedNative)
var originalBuffer = base.bufferID
let startedUnique = startedNative && base._core._owner != nil
&& isUniquelyReferencedNonObjC(&base._core._owner!)
base._core.reserveCapacity(0)
// Now it's unique
// If it was already native and unique, no reallocation
if startedUnique && startedNative {
expectEqual(originalBuffer, base.bufferID)
}
else {
expectNotEqual(originalBuffer, base.bufferID)
}
// Reserving up to the capacity in a unique native buffer is a no-op
let nativeBuffer = base.bufferID
let currentCapacity = base.capacity
base._core.reserveCapacity(currentCapacity)
expectEqual(nativeBuffer, base.bufferID)
// Reserving more capacity should reallocate
base._core.reserveCapacity(currentCapacity + 1)
expectNotEqual(nativeBuffer, base.bufferID)
// None of this should change the string contents
var expected: String
switch k {
case 0: expected = ""
case 1,3,4: expected = "x"
case 2: expected = "Ξ"
case 5: expected = shared
default:
fatalError("case unhandled!")
}
expectEqual(expected, base)
}
#else
expectUnreachable()
#endif
}
func makeStringCore(_ base: String) -> _StringCore {
var x = _StringCore()
// make sure some - but not all - replacements will have to grow the buffer
x.reserveCapacity(base._core.count * 3 / 2)
x.append(contentsOf: base._core)
// In case the core was widened and lost its capacity
x.reserveCapacity(base._core.count * 3 / 2)
return x
}
StringTests.test("StringCoreReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ makeStringCore(s1) },
{ makeStringCore(s2 + s2)[0..<$0] }
)
checkRangeReplaceable(
{ makeStringCore(s1) },
{ Array(makeStringCore(s2 + s2)[0..<$0]) }
)
}
}
}
StringTests.test("CharacterViewReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ String.CharacterView(makeStringCore(s2 + s2)[0..<$0]) }
)
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ Array(String.CharacterView(makeStringCore(s2 + s2)[0..<$0])) }
)
}
}
}
StringTests.test("UnicodeScalarViewReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ String(makeStringCore(s1)).unicodeScalars },
{ String(makeStringCore(s2 + s2)[0..<$0]).unicodeScalars }
)
checkRangeReplaceable(
{ String(makeStringCore(s1)).unicodeScalars },
{ Array(String(makeStringCore(s2 + s2)[0..<$0]).unicodeScalars) }
)
}
}
}
StringTests.test("reserveCapacity") {
var s = ""
let id0 = s.bufferID
let oldCap = s.capacity
let x: Character = "x" // Help the typechecker - <rdar://problem/17128913>
s.insert(contentsOf: repeatElement(x, count: s.capacity + 1), at: s.endIndex)
expectNotEqual(id0, s.bufferID)
s = ""
print("empty capacity \(s.capacity)")
s.reserveCapacity(oldCap + 2)
print("reserving \(oldCap + 2) -> \(s.capacity), width = \(s._core.elementWidth)")
let id1 = s.bufferID
s.insert(contentsOf: repeatElement(x, count: oldCap + 2), at: s.endIndex)
print("extending by \(oldCap + 2) -> \(s.capacity), width = \(s._core.elementWidth)")
expectEqual(id1, s.bufferID)
s.insert(contentsOf: repeatElement(x, count: s.capacity + 100), at: s.endIndex)
expectNotEqual(id1, s.bufferID)
}
StringTests.test("toInt") {
expectEmpty(Int(""))
expectEmpty(Int("+"))
expectEmpty(Int("-"))
expectOptionalEqual(20, Int("+20"))
expectOptionalEqual(0, Int("0"))
expectOptionalEqual(-20, Int("-20"))
expectEmpty(Int("-cc20"))
expectEmpty(Int(" -20"))
expectEmpty(Int(" \t 20ddd"))
expectOptionalEqual(Int.min, Int("\(Int.min)"))
expectOptionalEqual(Int.min + 1, Int("\(Int.min + 1)"))
expectOptionalEqual(Int.max, Int("\(Int.max)"))
expectOptionalEqual(Int.max - 1, Int("\(Int.max - 1)"))
expectEmpty(Int("\(Int.min)0"))
expectEmpty(Int("\(Int.max)0"))
// Make a String from an Int, mangle the String's characters,
// then print if the new String is or is not still an Int.
func testConvertabilityOfStringWithModification(
_ initialValue: Int,
modification: (chars: inout [UTF8.CodeUnit]) -> Void
) {
var chars = Array(String(initialValue).utf8)
modification(chars: &chars)
let str = String._fromWellFormedCodeUnitSequence(UTF8.self, input: chars)
expectEmpty(Int(str))
}
testConvertabilityOfStringWithModification(Int.min) {
$0[2] += 1; () // underflow by lots
}
testConvertabilityOfStringWithModification(Int.max) {
$0[1] += 1; () // overflow by lots
}
// Test values lower than min.
do {
let base = UInt(Int.max)
expectOptionalEqual(Int.min + 1, Int("-\(base)"))
expectOptionalEqual(Int.min, Int("-\(base + 1)"))
for i in 2..<20 {
expectEmpty(Int("-\(base + UInt(i))"))
}
}
// Test values greater than min.
do {
let base = UInt(Int.max)
for i in UInt(0)..<20 {
expectOptionalEqual(-Int(base - i) , Int("-\(base - i)"))
}
}
// Test values greater than max.
do {
let base = UInt(Int.max)
expectOptionalEqual(Int.max, Int("\(base)"))
for i in 1..<20 {
expectEmpty(Int("\(base + UInt(i))"))
}
}
// Test values lower than max.
do {
let base = Int.max
for i in 0..<20 {
expectOptionalEqual(base - i, Int("\(base - i)"))
}
}
}
// Make sure strings don't grow unreasonably quickly when appended-to
StringTests.test("growth") {
var s = ""
var s2 = s
for i in 0..<20 {
s += "x"
s2 = s
}
expectLE(s.nativeCapacity, 34)
}
StringTests.test("Construction") {
expectEqual("abc", String([ "a", "b", "c" ] as [Character]))
}
StringTests.test("Conversions") {
do {
var c: Character = "a"
let x = String(c)
expectTrue(x._core.isASCII)
var s: String = "a"
expectEqual(s, x)
}
do {
var c: Character = "\u{B977}"
let x = String(c)
expectFalse(x._core.isASCII)
var s: String = "\u{B977}"
expectEqual(s, x)
}
}
// Check the internal functions are correct for ASCII values
StringTests.test(
"forall x: Int8, y: Int8 . x < 128 ==> x <ascii y == x <unicode y")
.skip(.nativeRuntime("String._compareASCII undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
let asciiDomain = (0..<128).map({ String(UnicodeScalar($0)) })
expectEqualMethodsForDomain(
asciiDomain, asciiDomain,
String._compareDeterministicUnicodeCollation, String._compareASCII)
#else
expectUnreachable()
#endif
}
#if os(Linux)
import Glibc
#endif
StringTests.test("lowercased()") {
// Use setlocale so tolower() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(tolower($0)))) },
{ String(UnicodeScalar(Int($0))).lowercased() })
expectEqual("", "".lowercased())
expectEqual("abcd", "abCD".lowercased())
expectEqual("абвг", "абВГ".lowercased())
expectEqual("たちつてと", "たちつてと".lowercased())
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0130}".lowercased())
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0049}\u{0307}".lowercased())
}
StringTests.test("uppercased()") {
// Use setlocale so toupper() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(toupper($0)))) },
{ String(UnicodeScalar(Int($0))).uppercased() })
expectEqual("", "".uppercased())
expectEqual("ABCD", "abCD".uppercased())
expectEqual("АБВГ", "абВГ".uppercased())
expectEqual("たちつてと", "たちつてと".uppercased())
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectEqual("\u{0049}", "\u{0069}".uppercased())
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectEqual("\u{0053}\u{0053}", "\u{00df}".uppercased())
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectEqual("\u{0046}\u{0049}", "\u{fb01}".uppercased())
}
StringTests.test("unicodeViews") {
// Check the UTF views work with slicing
// U+FFFD REPLACEMENT CHARACTER
// U+1F3C2 SNOWBOARDER
// U+2603 SNOWMAN
let winter = "\u{1F3C2}\u{2603}"
// slices
// It is 4 bytes long, so it should return a replacement character.
expectEqual(
"\u{FFFD}", String(
winter.utf8[
winter.utf8.startIndex..<winter.utf8.startIndex.successor().successor()
]))
expectEqual(
"\u{1F3C2}", String(
winter.utf8[winter.utf8.startIndex..<winter.utf8.startIndex.advanced(by: 4)]))
expectEqual(
"\u{1F3C2}", String(
winter.utf16[
winter.utf16.startIndex..<winter.utf16.startIndex.advanced(by: 2)
]))
expectEqual(
"\u{1F3C2}", String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex
..< winter.unicodeScalars.startIndex.successor()
]))
// views
expectEqual(
winter, String(
winter.utf8[
winter.utf8.startIndex..<winter.utf8.startIndex.advanced(by: 7)
]))
expectEqual(
winter, String(
winter.utf16[
winter.utf16.startIndex..<winter.utf16.startIndex.advanced(by: 3)
]))
expectEqual(
winter, String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex
..< winter.unicodeScalars.startIndex.advanced(by: 2)
]))
let ga = "\u{304b}\u{3099}"
expectEqual(ga, String(ga.utf8[ga.utf8.startIndex ..<
ga.utf8.startIndex.advanced(by: 6)]))
}
// Validate that index conversion does something useful for Cocoa
// programmers.
StringTests.test("indexConversion")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let re : NSRegularExpression
do {
re = try NSRegularExpression(
pattern: "([^ ]+)er", options: NSRegularExpressionOptions())
} catch { fatalError("couldn't build regexp: \(error)") }
let s = "go further into the larder to barter."
var matches: [String] = []
re.enumerateMatches(
in: s, options: NSMatchingOptions(), range: NSRange(0..<s.utf16.count)
) {
result, flags, stop
in
let r = result!.range(at: 1)
let start = String.UTF16Index(_offset: r.location)
let end = String.UTF16Index(_offset: r.location + r.length)
matches.append(String(s.utf16[start..<end])!)
}
expectEqual(["furth", "lard", "bart"], matches)
#else
expectUnreachable()
#endif
}
StringTests.test("String.append(_: UnicodeScalar)") {
var s = ""
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
s.append(input)
expectEqual([ "\u{61}" ], Array(s.unicodeScalars))
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
s.append(input)
expectEqual([ "\u{61}", "\u{304b}" ], Array(s.unicodeScalars))
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
s.append(input)
expectEqual([ "\u{61}", "\u{304b}", "\u{3099}" ], Array(s.unicodeScalars))
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
s.append(input)
expectEqual(
[ "\u{61}", "\u{304b}", "\u{3099}", "\u{1f425}" ],
Array(s.unicodeScalars))
}
}
StringTests.test("String.append(_: Character)") {
let baseCharacters: [Character] = [
// U+0061 LATIN SMALL LETTER A
"\u{61}",
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
"\u{304b}\u{3099}",
// U+3072 HIRAGANA LETTER HI
// U+309A COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
"\u{3072}\u{309A}",
// U+1F425 FRONT-FACING BABY CHICK
"\u{1f425}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
"\u{61}\u{0300}\u{0301}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
"\u{61}\u{0300}\u{0301}\u{0302}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
// U+0303 COMBINING TILDE
"\u{61}\u{0300}\u{0301}\u{0302}\u{0303}",
]
let baseStrings = [ "" ] + baseCharacters.map { String($0) }
for baseIdx in baseStrings.indices {
for prefix in ["", " "] {
let base = baseStrings[baseIdx]
for inputIdx in baseCharacters.indices {
let input = (prefix + String(baseCharacters[inputIdx])).characters.last!
var s = base
s.append(input)
expectEqualSequence(
Array(base.characters) + [ input ],
Array(s.characters),
"baseIdx=\(baseIdx) inputIdx=\(inputIdx)")
}
}
}
}
runAllTests()
| 29.548387 | 88 | 0.662147 |
6955372b388f3494e7dc55660ac174c83a5b4ccc | 6,497 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
#if compiler(>=5.5.2) && canImport(_Concurrency)
import SotoCore
// MARK: Paginators
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Drs {
/// Retrieves a detailed Job log with pagination.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeJobLogItemsPaginator(
_ input: DescribeJobLogItemsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeJobLogItemsRequest, DescribeJobLogItemsResponse> {
return .init(
input: input,
command: describeJobLogItems,
inputKey: \DescribeJobLogItemsRequest.nextToken,
outputKey: \DescribeJobLogItemsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Returns a list of Jobs. Use the JobsID and fromDate and toDate filters to limit which jobs are returned. The response is sorted by creationDataTime - latest date first. Jobs are created by the StartRecovery, TerminateRecoveryInstances and StartFailbackLaunch APIs. Jobs are also created by DiagnosticLaunch and TerminateDiagnosticInstances, which are APIs available only to *Support* and only used in response to relevant support tickets.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeJobsPaginator(
_ input: DescribeJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeJobsRequest, DescribeJobsResponse> {
return .init(
input: input,
command: describeJobs,
inputKey: \DescribeJobsRequest.nextToken,
outputKey: \DescribeJobsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Lists all Recovery Instances or multiple Recovery Instances by ID.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeRecoveryInstancesPaginator(
_ input: DescribeRecoveryInstancesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeRecoveryInstancesRequest, DescribeRecoveryInstancesResponse> {
return .init(
input: input,
command: describeRecoveryInstances,
inputKey: \DescribeRecoveryInstancesRequest.nextToken,
outputKey: \DescribeRecoveryInstancesResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Lists all Recovery Snapshots for a single Source Server.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeRecoverySnapshotsPaginator(
_ input: DescribeRecoverySnapshotsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeRecoverySnapshotsRequest, DescribeRecoverySnapshotsResponse> {
return .init(
input: input,
command: describeRecoverySnapshots,
inputKey: \DescribeRecoverySnapshotsRequest.nextToken,
outputKey: \DescribeRecoverySnapshotsResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Lists all ReplicationConfigurationTemplates, filtered by Source Server IDs.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeReplicationConfigurationTemplatesPaginator(
_ input: DescribeReplicationConfigurationTemplatesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeReplicationConfigurationTemplatesRequest, DescribeReplicationConfigurationTemplatesResponse> {
return .init(
input: input,
command: describeReplicationConfigurationTemplates,
inputKey: \DescribeReplicationConfigurationTemplatesRequest.nextToken,
outputKey: \DescribeReplicationConfigurationTemplatesResponse.nextToken,
logger: logger,
on: eventLoop
)
}
/// Lists all Source Servers or multiple Source Servers filtered by ID.
/// Return PaginatorSequence for operation.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
public func describeSourceServersPaginator(
_ input: DescribeSourceServersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) -> AWSClient.PaginatorSequence<DescribeSourceServersRequest, DescribeSourceServersResponse> {
return .init(
input: input,
command: describeSourceServers,
inputKey: \DescribeSourceServersRequest.nextToken,
outputKey: \DescribeSourceServersResponse.nextToken,
logger: logger,
on: eventLoop
)
}
}
#endif // compiler(>=5.5.2) && canImport(_Concurrency)
| 40.60625 | 447 | 0.655225 |
237e5aba225fee03323b9f5818cbd02b339a5236 | 1,114 | //
// TomlResponseSignatureMismatchMock.swift
// stellarsdkTests
//
// Created by Soneso on 13/11/2018.
// Copyright © 2018 Soneso. All rights reserved.
//
import Foundation
class TomlResponseSignatureMismatchMock: ResponsesMock {
var address: String
init(address:String) {
self.address = address
super.init()
}
override func requestMock() -> RequestMock {
let handler: MockHandler = { [weak self] mock, request in
return self?.stellarToml
}
return RequestMock(host: address,
path: "/.well-known/stellar.toml",
httpMethod: "GET",
mockHandler: handler)
}
let stellarToml = """
# Sample stellar.toml
FEDERATION_SERVER="https://api.domain.com/federation"
AUTH_SERVER="https://api.domain.com/auth"
TRANSFER_SERVER="https://api.domain.com"
URI_REQUEST_SIGNING_KEY="GCCHBLJOZUFBVAUZP55N7ZU6ZB5VGEDHSXT23QC6UIVDQNGI6QDQTOOR"
"""
}
| 27.170732 | 94 | 0.573609 |
64137c3b363b34013a53cbcef7d8e45dbeece958 | 9,447 | //
// BRBSPatch.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet 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 Foundation
enum BRBSPatchError: Error {
case unknown
case corruptPatch
case patchFileDoesntExist
case oldFileDoesntExist
}
class BRBSPatch {
static let patchLogEnabled = true
static func patch(_ oldFilePath: String, newFilePath: String, patchFilePath: String)
throws -> UnsafeMutablePointer<CUnsignedChar> {
func offtin(_ b: UnsafePointer<CUnsignedChar>) -> off_t {
var y = off_t(b[0])
y |= off_t(b[1]) << 8
y |= off_t(b[2]) << 16
y |= off_t(b[3]) << 24
y |= off_t(b[4]) << 32
y |= off_t(b[5]) << 40
y |= off_t(b[6]) << 48
y |= off_t(b[7] & 0x7f) << 56
if Int(b[7]) & 0x80 != 0 {
y = -y
}
return y
}
let patchFilePathBytes = UnsafePointer<Int8>((patchFilePath as NSString).utf8String)
let r = UnsafePointer<Int8>(("r" as NSString).utf8String)
// open patch file
guard let f = FileHandle(forReadingAtPath: patchFilePath) else {
log("unable to open file for reading at path \(patchFilePath)")
throw BRBSPatchError.patchFileDoesntExist
}
// read header
let headerData = f.readData(ofLength: 32)
let header = (headerData as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: headerData.count)
if headerData.count != 32 {
log("incorrect header read length \(headerData.count)")
throw BRBSPatchError.corruptPatch
}
// check for appropriate magic
let magicData = headerData.subdata(in: 0..<8)
if let magic = String(bytes: magicData, encoding: String.Encoding.ascii), magic != "BSDIFF40" {
log("incorrect magic: \(magic)")
throw BRBSPatchError.corruptPatch
}
// read lengths from header
let bzCrtlLen = offtin(header + 8)
let bzDataLen = offtin(header + 16)
let newSize = offtin(header + 24)
if bzCrtlLen < 0 || bzDataLen < 0 || newSize < 0 {
log("incorrect header data: crtlLen: \(bzCrtlLen) dataLen: \(bzDataLen) newSize: \(newSize)")
throw BRBSPatchError.corruptPatch
}
// close patch file and re-open it with bzip2 at the right positions
f.closeFile()
let cpf = fopen(patchFilePathBytes, r)
if cpf == nil {
let s = String(cString: strerror(errno))
let ff = String(cString: patchFilePathBytes!)
log("unable to open patch file c: \(s) \(ff)")
throw BRBSPatchError.unknown
}
let cpfseek = fseeko(cpf, 32, SEEK_SET)
if cpfseek != 0 {
log("unable to seek patch file c: \(cpfseek)")
throw BRBSPatchError.unknown
}
let cbz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let cpfbz2 = BZ2_bzReadOpen(cbz2err, cpf, 0, 0, nil, 0)
if cpfbz2 == nil {
log("unable to bzopen patch file c: \(cbz2err)")
throw BRBSPatchError.unknown
}
let dpf = fopen(patchFilePathBytes, r)
if dpf == nil {
log("unable to open patch file d")
throw BRBSPatchError.unknown
}
let dpfseek = fseeko(dpf, 32 + bzCrtlLen, SEEK_SET)
if dpfseek != 0 {
log("unable to seek patch file d: \(dpfseek)")
throw BRBSPatchError.unknown
}
let dbz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let dpfbz2 = BZ2_bzReadOpen(dbz2err, dpf, 0, 0, nil, 0)
if dpfbz2 == nil {
log("unable to bzopen patch file d: \(dbz2err)")
throw BRBSPatchError.unknown
}
let epf = fopen(patchFilePathBytes, r)
if epf == nil {
log("unable to open patch file e")
throw BRBSPatchError.unknown
}
let epfseek = fseeko(epf, 32 + bzCrtlLen + bzDataLen, SEEK_SET)
if epfseek != 0 {
log("unable to seek patch file e: \(epfseek)")
throw BRBSPatchError.unknown
}
let ebz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let epfbz2 = BZ2_bzReadOpen(ebz2err, epf, 0, 0, nil, 0)
if epfbz2 == nil {
log("unable to bzopen patch file e: \(ebz2err)")
throw BRBSPatchError.unknown
}
guard let oldData = try? Data(contentsOf: URL(fileURLWithPath: oldFilePath)) else {
log("unable to read old file path")
throw BRBSPatchError.unknown
}
let old = (oldData as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: oldData.count)
let oldSize = off_t(oldData.count)
var oldPos: off_t = 0, newPos: off_t = 0
let new = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: Int(newSize) + 1)
let buf = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 8)
var crtl = Array<off_t>(repeating: 0, count: 3)
while newPos < newSize {
// read control data
for i in 0...2 {
let lenread = BZ2_bzRead(cbz2err, cpfbz2, buf, 8)
if (lenread < 8) || ((cbz2err.pointee != BZ_OK) && (cbz2err.pointee != BZ_STREAM_END)) {
log("unable to read control data \(lenread) \(cbz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
crtl[i] = offtin(UnsafePointer<CUnsignedChar>(buf))
}
// sanity check
if (newPos + crtl[0]) > newSize {
log("incorrect size of crtl[0]")
throw BRBSPatchError.corruptPatch
}
// read diff string
let dlenread = BZ2_bzRead(dbz2err, dpfbz2, new + Int(newPos), Int32(crtl[0]))
if (dlenread < Int32(crtl[0])) || ((dbz2err.pointee != BZ_OK) && (dbz2err.pointee != BZ_STREAM_END)) {
log("unable to read diff string \(dlenread) \(dbz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
// add old data to diff string
if crtl[0] > 0 {
for i in 0...(Int(crtl[0]) - 1) {
if (oldPos + i >= 0) && (oldPos + i < oldSize) {
let np = Int(newPos) + i, op = Int(oldPos) + i
new[np] = new[np] &+ old[op]
}
}
}
// adjust pointers
newPos += crtl[0]
oldPos += crtl[0]
// sanity check
if (newPos + crtl[1]) > newSize {
log("incorrect size of crtl[1]")
throw BRBSPatchError.corruptPatch
}
// read extra string
let elenread = BZ2_bzRead(ebz2err, epfbz2, new + Int(newPos), Int32(crtl[1]))
if (elenread < Int32(crtl[1])) || ((ebz2err.pointee != BZ_OK) && (ebz2err.pointee != BZ_STREAM_END)) {
log("unable to read extra string \(elenread) \(ebz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
// adjust pointers
newPos += crtl[1]
oldPos += crtl[2]
}
// clean up bz2 reads
BZ2_bzReadClose(cbz2err, cpfbz2)
BZ2_bzReadClose(dbz2err, dpfbz2)
BZ2_bzReadClose(ebz2err, epfbz2)
if (fclose(cpf) != 0) || (fclose(dpf) != 0) || (fclose(epf) != 0) {
log("unable to close bzip file handles")
throw BRBSPatchError.unknown
}
// write out new file
let fm = FileManager.default
if fm.fileExists(atPath: newFilePath) {
try fm.removeItem(atPath: newFilePath)
}
let newData = Data(bytes: UnsafePointer<UInt8>(new), count: Int(newSize))
try newData.write(to: URL(fileURLWithPath: newFilePath), options: .atomic)
return new
}
static fileprivate func log(_ string: String) {
if patchLogEnabled {
print("[BRBSPatch] \(string)")
}
}
}
| 40.2 | 114 | 0.5642 |
fe489d7de1d235fbe7c8fe4035852769cf606e61 | 2,226 | //
// ActivityIndicator.swift
// PDDExam
//
// Created by Николай on 21.11.2019.
// Copyright © 2019 Nickolay. All rights reserved.
//
import RxSwift
import RxCocoa
import Foundation
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> Void) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator : SharedSequenceConvertibleType {
public typealias Element = Bool
public typealias SharingStrategy = DriverSharingStrategy
private let _lock = NSRecursiveLock()
private let _relay = BehaviorRelay(value: 0)
private let _loading: SharedSequence<SharingStrategy, Bool>
public init() {
_loading = _relay.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
fileprivate func trackActivityOfObservable<Source: ObservableConvertibleType>(_ source: Source) -> Observable<Source.Element> {
return Observable.using({ () -> ActivityToken<Source.Element> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
private func increment() {
_lock.lock()
_relay.accept(_relay.value + 1)
_lock.unlock()
}
private func decrement() {
_lock.lock()
_relay.accept(_relay.value - 1)
_lock.unlock()
}
public func asSharedSequence() -> SharedSequence<SharingStrategy, Element> {
return _loading
}
}
extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<Element> {
return activityIndicator.trackActivityOfObservable(self)
}
}
| 27.146341 | 131 | 0.670261 |
f7262d7692455cc24c66eb8b23d808d6b3fa3bec | 388 | //
// Int+Extensions.swift
// expensetracker
//
// Created by Victor Idongesit on 23/08/2020.
// Copyright © 2020 Victor Idongesit. All rights reserved.
//
import Foundation
extension Int {
struct AppViewTags {
static let horizontalLayerGradientTag: Int = 888
static let loaderOverlayViewTag: Int = 999
}
static let minimumPasswordLength: Int = 8
}
| 20.421053 | 59 | 0.685567 |
29d3c4bd10607d9dbd8a22a28e623d4108f42244 | 1,802 | //
// ConversationHandler.swift
// Telegrammer
//
// Created by Givi Pataridze on 08.06.2018.
//
import Foundation
import NIO
public class ConversationHandler: Handler {
public var name: String
public struct Options: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
///Determines if a user can restart a conversation with an entry point.
public static let allowReentry = Options(rawValue: 1)
///If the conversationkey should contain the Chat’s ID.
public static let perChat = Options(rawValue: 2)
///If the conversationkey should contain the User’s ID.
public static let perUser = Options(rawValue: 4)
///If the conversationkey should contain the Message’s ID.
public static let perMessage = Options(rawValue: 8)
}
public var entryPoints: [Handler] = []
public var states: [String: [Handler]] = [:]
public var fallbacks: [Handler] = []
public var timeoutBehavior: [Handler] = []
let options: Options
let conversationTimeout: TimeAmount?
let callback: HandlerCallback
public init(
name: String = String(describing: ConversationHandler.self),
options: Options = [],
conversationTimeout: TimeAmount? = nil,
callback: @escaping HandlerCallback
) {
self.name = name
self.options = options
self.conversationTimeout = conversationTimeout
self.callback = callback
}
public func check(update: Update) -> Bool {
return true
}
public func handle(update: Update, dispatcher: Dispatcher) {
do {
try callback(update, nil)
} catch {
log.error(error.logMessage)
}
}
}
| 27.723077 | 79 | 0.631521 |
5bd26be6e21b35ae21e309f0693cc8770c292a46 | 1,567 | //
// Timer.swift
// LispKit
//
// Created by Matthias Zenger on 20/03/2016.
// Copyright © 2016 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Timer utilities based on Darwin framework.
///
public struct Timer {
private static let (TIME_NUMER, TIME_DENOM): (UInt64, UInt64) = {
var info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
mach_timebase_info(&info)
return (UInt64(info.numer), UInt64(info.denom))
}()
/// Returns a current time measurement in seconds, as a Double. This is only useful for
/// measuring short time intervals.
public static var currentTimeInSec: Double {
return Double(mach_absolute_time() * Timer.TIME_NUMER / Timer.TIME_DENOM) / 1e9
}
/// Returns a current time measurement in milliseconds, as a UInt64. This is only useful for
/// measuring short time intervals.
public static var currentTimeInMSec: UInt64 {
return (mach_absolute_time() * Timer.TIME_NUMER) / (Timer.TIME_DENOM * 1000000)
}
}
| 34.065217 | 94 | 0.719209 |
1d322c2acc662183b6bd496b546709a6e9429984 | 75 | protocol LayoutConfigurable: AnyObject {
func configureLayout()
}
| 15 | 40 | 0.72 |
89fcf5e14c7768497d58ab4c24f65990266ca39b | 1,066 | // Copyright 2021-present Xsolla (USA), Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at q
//
// 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 and permissions and
import Foundation
import XsollaSDKUtilities
final class GetCouponRewardsErrorHandler: APIBaseErrorHandler
{
override func setHandlers()
{
add(handler: APIServerCode400ErrorHandler())
add(handler: APIServerCode401ErrorHandler())
add(handler: APIServerCode403ErrorHandler())
add(handler: APIServerCode404ErrorHandler())
add(handler: APIServerCode422ErrorHandler())
add(handler: APIServerCode429ErrorHandler())
}
}
| 36.758621 | 75 | 0.742026 |
d6eb55cf809bfcebd9a13a4a868fa3dc39f1b142 | 830 | //
// String.swift
// Squid
//
// Created by Oliver Borchert on 9/22/19.
//
import Foundation
extension String {
internal func indent(spaces: Int, skipLines: Int = 0) -> String {
return self
.split { char in char == "\n" }
.enumerated()
.map { count, line in
count < skipLines ? line : String.init(repeating: " ", count: spaces) + line
}.joined(separator: "\n")
}
internal func prefixed(with prefix: String) -> String {
return self
.split { char in char == "\n" }
.map { line in prefix + line }
.joined(separator: "\n")
}
internal func truncate(to max: Int) -> String {
if self.count > max {
return self.prefix(max - 3) + "..."
}
return self
}
}
| 23.714286 | 92 | 0.508434 |
50006d2bd694b41a4b2e0922afcd3226cd150976 | 959 | import Foundation
import Sonar
final class SubmitRadarDelegate: APIDelegate {
// MARK: - Properties
let display: StatusDisplay
var finishHandler: (_ succes: Bool) -> Void = { _ in }
// MARK: - Init/Deinit
init(_ display: StatusDisplay) {
self.display = display
}
// APIDelegate Methods
func didStartLoading() {
display.showLoading()
}
func didFail(with error: SonarError) {
display.hideLoading()
display.showError(title: nil, message: error.localizedDescription, dismissButtonTitle: nil, completion: nil)
finishHandler(false)
}
func didPostToAppleRadar() {
display.hideLoading()
let delay = 3.0
display.showSuccess(message: NSLocalizedString("Radar.Post.Success", comment: ""), autoDismissAfter: delay)
finishHandler(true)
}
func didPostToOpenRadar() {
display.hideLoading()
display.showSuccess(message: NSLocalizedString("Radar.Post.Success", comment: ""), autoDismissAfter: 3.0)
finishHandler(false)
}
}
| 20.847826 | 110 | 0.73097 |
9134090081533c644de45966f131a72a0328a8a2 | 1,912 | //
// RadioStation.swift
// Swift Radio
//
// Created by Matthew Fecher on 7/4/15.
// Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//
import UIKit
//*****************************************************************
// Radio Station
//*****************************************************************
// Class inherits from NSObject so that you may easily add features
// i.e. Saving favorite stations to CoreData, etc
class RadioStation: NSObject {
var stationName : String
var stationStreamURL: String
var stationImageURL : String
var stationDesc : String
var stationLongDesc : String
init(name: String, streamURL: String, imageURL: String, desc: String, longDesc: String) {
self.stationName = name
self.stationStreamURL = streamURL
self.stationImageURL = imageURL
self.stationDesc = desc
self.stationLongDesc = longDesc
}
// Convenience init without longDesc
convenience init(name: String, streamURL: String, imageURL: String, desc: String) {
self.init(name: name, streamURL: streamURL, imageURL: imageURL, desc: desc, longDesc: "")
}
//*****************************************************************
// MARK: - JSON Parsing into object
//*****************************************************************
class func parseStation(stationJSON: JSON) -> (RadioStation) {
let name = stationJSON["name"].string ?? ""
let streamURL = stationJSON["streamURL"].string ?? ""
let imageURL = stationJSON["imageURL"].string ?? ""
let desc = stationJSON["desc"].string ?? ""
let longDesc = stationJSON["longDesc"].string ?? ""
let station = RadioStation(name: name, streamURL: streamURL, imageURL: imageURL, desc: desc, longDesc: longDesc)
return station
}
}
| 34.142857 | 120 | 0.544979 |
f595df60f28ba0030499d71c26838439d133358b | 949 | //
// NotificationController.swift
// ESMigrationDemo_wtchos WatchKit Extension
//
// Created by 罗树新 on 2020/12/24.
//
import WatchKit
import Foundation
import UserNotifications
class NotificationController: WKUserNotificationInterfaceController {
override init() {
// Initialize variables here.
super.init()
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
}
override func didReceive(_ notification: UNNotification) {
// This method is called when a notification needs to be presented.
// Implement it if you use a dynamic notification interface.
// Populate your dynamic notification interface as quickly as possible.
}
}
| 27.114286 | 90 | 0.694415 |
b962756ed813e8467c485178e37bf67e6e1d9be6 | 9,541 | //
// Modified MIT License
//
// Copyright (c) 2010-2018 Kite Tech Ltd. https://www.kite.ly
//
// 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 software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified
// to be used with any competitor platforms. This means the software MAY NOT be modified
// to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the
// Kite Tech Ltd platform servers.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Photobook
class DeliveryDetailsTests: XCTestCase {
func validDetails() -> DeliveryDetails {
let deliveryDetails = DeliveryDetails()
deliveryDetails.firstName = "George"
deliveryDetails.lastName = "Clowney"
deliveryDetails.email = "[email protected]"
deliveryDetails.phone = "399945528234"
deliveryDetails.line1 = "9 Fiesta Place"
deliveryDetails.line2 = "Old Street"
deliveryDetails.city = "London"
deliveryDetails.zipOrPostcode = "CL0 WN4"
deliveryDetails.stateOrCounty = "Clownborough"
deliveryDetails.country = Country(name: "United Kingdom", codeAlpha2: "UK", codeAlpha3: "GBA", currencyCode: "GBP")
return deliveryDetails
}
func testCopy() {
let validDetails = self.validDetails()
let validDetailsCopy = validDetails.copy() as! DeliveryDetails
XCTAssertEqual(validDetails.firstName, validDetailsCopy.firstName)
XCTAssertEqual(validDetails.lastName, validDetailsCopy.lastName)
XCTAssertEqual(validDetails.email, validDetailsCopy.email)
XCTAssertEqual(validDetails.phone, validDetailsCopy.phone)
XCTAssertEqual(validDetails.line1, validDetailsCopy.line1)
XCTAssertEqual(validDetails.line2, validDetailsCopy.line2)
XCTAssertEqual(validDetails.city, validDetailsCopy.city)
XCTAssertEqual(validDetails.zipOrPostcode, validDetailsCopy.zipOrPostcode)
XCTAssertEqual(validDetails.stateOrCounty, validDetailsCopy.stateOrCounty)
XCTAssertEqual(validDetails.country.codeAlpha2, validDetailsCopy.country.codeAlpha2)
}
func testIsValid_shouldBeTrueWithAValidAddress() {
let deliveryDetails = validDetails()
XCTAssertTrue(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfFirstNameIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.firstName = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfFirstNameIsEmpty() {
let deliveryDetails = validDetails()
deliveryDetails.firstName = ""
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfLastNameIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.lastName = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfLastNameIsEmpty() {
let deliveryDetails = validDetails()
deliveryDetails.lastName = ""
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfEmailIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.email = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfEmailIsNotValid() {
let deliveryDetails = validDetails()
deliveryDetails.email = "notrealmail@bonkers"
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfPhoneIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.phone = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfPhoneIsNotValid() {
let deliveryDetails = validDetails()
deliveryDetails.phone = "3434"
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfLine1IsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.line1 = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfTheCityIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.city = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testIsValid_shouldBeFalseIfThePostCodeIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.zipOrPostcode = nil
XCTAssertFalse(deliveryDetails.isValid)
}
func testDescriptionWithoutLine1_shouldReturnTheRightAddress() {
let addressDescription = validDetails().descriptionWithoutLine1()
XCTAssertEqual(addressDescription, "Old Street, London, Clownborough, CL0 WN4, United Kingdom")
}
func testFullName_shouldBeNilIfFirstNameAndLastNameAreMissing() {
let deliveryDetails = validDetails()
deliveryDetails.firstName = nil
deliveryDetails.lastName = nil
XCTAssertNil(deliveryDetails.fullName)
}
func testFullName_shouldReturnFullName() {
let deliveryDetails = validDetails()
XCTAssertEqualOptional(deliveryDetails.fullName, "George Clowney")
}
func testFullName_shouldReturnLastNameIfFirstNameIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.firstName = nil
XCTAssertEqualOptional(deliveryDetails.fullName, "Clowney")
}
func testFullName_shouldReturnLastNameIfLastNameIsMissing() {
let deliveryDetails = validDetails()
deliveryDetails.lastName = nil
XCTAssertEqualOptional(deliveryDetails.fullName, "George")
}
func testDetails_canBePersisted() {
let deliveryDetails = validDetails()
DeliveryDetails.add(deliveryDetails)
DeliveryDetails.loadSavedDetails()
XCTAssertEqual([deliveryDetails], DeliveryDetails.savedDeliveryDetails)
}
func testSelectedDetails() {
let deliveryDetails = validDetails()
let deliveryDetails2 = validDetails()
let deliveryDetails3 = validDetails()
DeliveryDetails.add(deliveryDetails)
DeliveryDetails.add(deliveryDetails3)
DeliveryDetails.add(deliveryDetails2)
let selected = DeliveryDetails.selectedDetails()
XCTAssertEqualOptional(selected, deliveryDetails2)
}
func testJsonRepresentation() {
let deliveryDetails = validDetails()
let dictionary = deliveryDetails.jsonRepresentation()
XCTAssertEqualOptional(dictionary["recipient_first_name"], deliveryDetails.firstName)
XCTAssertEqualOptional(dictionary["recipient_last_name"], deliveryDetails.lastName)
XCTAssertEqualOptional(dictionary["recipient_name"], deliveryDetails.fullName)
XCTAssertEqualOptional(dictionary["address_line_1"], deliveryDetails.line1)
XCTAssertEqualOptional(dictionary["address_line_2"], deliveryDetails.line2)
XCTAssertEqualOptional(dictionary["city"], deliveryDetails.city)
XCTAssertEqualOptional(dictionary["county_state"], deliveryDetails.stateOrCounty)
XCTAssertEqualOptional(dictionary["postcode"], deliveryDetails.zipOrPostcode)
XCTAssertEqualOptional(dictionary["country_code"], deliveryDetails.country.codeAlpha3)
}
func testDetails_shouldBeEmpty() {
XCTAssertTrue(DeliveryDetails.savedDeliveryDetails.count == 0)
}
func testDetails_shouldSaveTheDetails() {
let deliveryDetails = validDetails()
DeliveryDetails.add(deliveryDetails)
DeliveryDetails.loadSavedDetails()
XCTAssertEqual([deliveryDetails], DeliveryDetails.savedDeliveryDetails)
}
func testDetails_shouldEditTheDetails() {
let deliveryDetails = validDetails()
DeliveryDetails.add(deliveryDetails)
deliveryDetails.city = "Clowntown"
DeliveryDetails.edit(deliveryDetails, at: 0)
DeliveryDetails.loadSavedDetails()
XCTAssertEqual([deliveryDetails], DeliveryDetails.savedDeliveryDetails)
}
func testDetails_shouldRemoveTheDetails() {
let deliveryDetails = validDetails()
DeliveryDetails.add(deliveryDetails)
DeliveryDetails.remove(deliveryDetails)
XCTAssertFalse(DeliveryDetails.savedDeliveryDetails.contains(deliveryDetails))
}
override func setUp() {
UserDefaults.standard.removeObject(forKey: DeliveryDetails.savedDetailsKey)
DeliveryDetails.loadSavedDetails()
}
}
| 40.773504 | 123 | 0.720365 |
e511941d73e49f186fc1f1d082d81d3f4c87826e | 494 | //
// ViewController.swift
// expectApp
//
// Created by wangtao on 15/3/2.
// Copyright (c) 2015年 王涛. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19 | 80 | 0.661943 |
875adc19297506505f2c9ffe067de0a9e3d60a08 | 440 | //
// Runtime.swift
// SimlatorControl
//
// Created by Yu Tawata on 2020/02/07.
// Copyright © 2020 Yu Tawata. All rights reserved.
//
import Foundation
extension CLI.Simctl {
struct Runtime: Decodable {
let version: String?
let bundlePath: String?
let isAvailable: Bool?
let name: String?
let identifier: String?
let buildversion: String?
let runtimeRoot: String?
}
}
| 20 | 52 | 0.622727 |
f4945f118480a7ccb220c009978e1e61b42fdd8e | 460 | import SwiftUI
import GitHub
struct LoadingRequirementsView: View {
let repository: Repository
var body: some View {
LoadingView(message: "Loading tags and branches for repository '\(repository.fullName)'...")
}
}
#if DEBUG
struct LoadingRequirementsView_Previews: PreviewProvider {
static var previews: some View {
LoadingRequirementsView(repository: sampleRepo)
.previewLayout(.sizeThatFits)
}
}
#endif
| 23 | 100 | 0.706522 |
f8b460165d12c80bffd793f1bd8823e12f28b4cf | 1,469 | //
// ImagePicker.swift
// Latime
//
// Created by Andrei Niunin on 10.07.2021.
//
import UIKit
class ImagePicker: UIImagePickerController {
// MARK: life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.sourceType = .photoLibrary
delegate = self
// Do any additional setup after loading the view.
}
}
extension ImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
guard let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage else {
return
}
dismiss(animated: true) {
let imageInfo = ["image": image as Any]
NotificationCenter.default.post(name: .pickerImageReady, object: nil, userInfo: imageInfo)
}
}
}
// MARK: - Utilities
private func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (key.rawValue, value) })
}
private func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
| 29.38 | 143 | 0.710007 |
64299ae8f9b95d6b8b00b6b81237d5cbdb859f98 | 3,118 | //
// TorchLight.swift
// TorchLight
//
// Created by Suh Fangmbeng on 5/3/20.
// Copyright © 2020 Hourworth LLC. All rights reserved.
//
import Foundation
import AVFoundation
public class Torch {
public var captureDevice: AVCaptureDevice?
public var timer: Timer?
public var blinkStyle: BlinkStyle = .default
public enum BlinkStyle {
case `default`, trafficate, airplane
}
public init() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video), device.hasTorch, device.hasFlash else {
print("Could not initialize TorchLight framework because the device is not supported.")
return
}
captureDevice = device
}
public func isOn() -> Bool {
try? captureDevice?.lockForConfiguration()
let result = captureDevice?.torchMode == AVCaptureDevice.TorchMode.on
captureDevice?.unlockForConfiguration()
return result
}
public func isOff() -> Bool {
try? captureDevice?.lockForConfiguration()
let result = captureDevice?.torchMode == AVCaptureDevice.TorchMode.off
captureDevice?.unlockForConfiguration()
return result
}
public func turnOn() {
if isOff() {
guard let device = captureDevice else {return}
try? device.lockForConfiguration()
try? device.setTorchModeOn(level: 1.0)
device.unlockForConfiguration()
} else {
print("Torch Light is already on")
}
}
public func turnOff() {
if isOn() {
guard let device = captureDevice else {return}
try? device.lockForConfiguration()
device.torchMode = AVCaptureDevice.TorchMode.off
device.unlockForConfiguration()
} else {
print("Torch Light is already off")
}
}
private func trafficate() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {[weak self] (_) in
self?.turnOn()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {[weak self] in
self?.turnOff()
}
})
}
private func startDefaultBlinking() {
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: {[weak self] (_) in
self?.turnOn()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {[weak self] in
self?.turnOff()
}
})
}
func startBlinking() {
switch blinkStyle {
case .trafficate: trafficate()
case .airplane: airplane()
default: startDefaultBlinking()
}
}
private func airplane() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {[weak self] (_) in
self?.turnOn()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {[weak self] in
self?.turnOff()
}
})
}
deinit {
print("Memory allocated for Torchlight has been deallocated")
}
}
| 29.140187 | 115 | 0.582104 |
01058526543dcb1b7a245d51608d3340846aa369 | 6,150 | //
// TweetsDetailViewController.swift
// Twitter
//
// Created by Lucas Andrade on 2/26/16.
// Copyright © 2016 LucasAndradeRibeiro. All rights reserved.
//
import UIKit
class TweetsDetailViewController: UIViewController, UITextViewDelegate {
var tweet: Tweet?
var rowFromTableView: Int = 0
@IBOutlet weak var imageProfilePicture: UIImageView!
@IBOutlet weak var textViewReply: UITextView!
@IBOutlet weak var labelDate: UILabel!
@IBOutlet weak var labelUserHandle: UILabel!
@IBOutlet weak var labelUserName: UILabel!
@IBOutlet weak var labelTweetText: UILabel!
@IBOutlet weak var buttonReplyWithImage: UIButton!
@IBOutlet weak var buttonReply: UIButton!
@IBOutlet weak var buttonFavorite: UIButton!
@IBOutlet weak var labelRetweetNumber: UILabel!
@IBOutlet weak var labelFavoriteNumber: UILabel!
@IBOutlet weak var buttonRetweet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//change backbutton to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.textViewReply.delegate = self
//setting labels and picture with User Data
self.imageProfilePicture.setImageWithURL(tweet!.imageProfileURL!)
self.imageProfilePicture.layer.cornerRadius = 28
self.imageProfilePicture.clipsToBounds = true
self.labelUserName.text = String(tweet!.userName!)
self.labelUserHandle.text = "@\(tweet!.userHandle!)"
self.labelTweetText.text = String(tweet!.text!)
self.labelFavoriteNumber.text = String(tweet!.favoritesCount)
self.labelRetweetNumber.text = String(tweet!.retweetCount)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateStyle = .MediumStyle
let dateToPrint: NSString = dateFormatter.stringFromDate(tweet!.timeStamp!) as NSString
self.labelDate.text = String(dateToPrint)
if(tweet?.favorited == 1){
buttonFavorite.setImage(UIImage(named: "like-action-pink"), forState: .Normal)
labelFavoriteNumber.textColor = UIColor.redColor()
}
else{
buttonFavorite.setImage(UIImage(named: "like-action-grey"), forState: .Normal)
labelFavoriteNumber.textColor = UIColor.grayColor()
}
if(tweet?.retweeted == 1){
buttonRetweet.setImage(UIImage(named: "retweet-action-green"), forState: .Normal)
labelRetweetNumber.textColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 1)
}
else{
buttonRetweet.setImage(UIImage(named: "retweet-action-grey"), forState: .Normal)
labelRetweetNumber.textColor = UIColor.grayColor()
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func favoriteAction(sender: AnyObject) {
if(tweet?.favorited == 0){
buttonFavorite.setImage(UIImage(named: "like-action-pink"), forState: .Normal)
labelFavoriteNumber.textColor = UIColor.redColor()
tweet?.favorited = 1
var pastFavorite = Int(self.labelFavoriteNumber.text!)
pastFavorite = pastFavorite! + 1
self.labelFavoriteNumber.text = String(pastFavorite!)
tweet?.favoritesCount = tweet!.favoritesCount + 1
}
else{
buttonFavorite.setImage(UIImage(named: "like-action-grey"), forState: .Normal)
labelFavoriteNumber.textColor = UIColor.grayColor()
tweet?.favorited = 0
var pastFavorite = Int(self.labelFavoriteNumber.text!)
pastFavorite = pastFavorite! - 1
self.labelFavoriteNumber.text = String(pastFavorite!)
tweet?.favoritesCount = tweet!.favoritesCount - 1
}
}
@IBAction func retweetAction(sender: AnyObject) {
if(tweet?.retweeted == 0){
buttonRetweet.setImage(UIImage(named: "retweet-action-green"), forState: .Normal)
labelRetweetNumber.textColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 1)
tweet?.retweeted = 1
var pastRetweet = Int(self.labelRetweetNumber.text!)
pastRetweet = pastRetweet! + 1
self.labelRetweetNumber.text = String(pastRetweet!)
tweet?.retweetCount = tweet!.retweetCount + 1
}
else{
buttonRetweet.setImage(UIImage(named: "retweet-action-grey"), forState: .Normal)
labelRetweetNumber.textColor = UIColor.grayColor()
tweet?.retweeted = 0
var pastRetweet = Int(self.labelRetweetNumber.text!)
pastRetweet = pastRetweet! - 1
self.labelRetweetNumber.text = String(pastRetweet!)
tweet?.retweetCount = tweet!.retweetCount - 1
}
}
override func viewWillDisappear(animated: Bool) {
let tweetsViewController = self.navigationController?.viewControllers[0] as? TweetsViewController
tweetsViewController?.tweets[rowFromTableView] = tweet!
}
func textViewDidBeginEditing(textView: UITextView) {
self.textViewReply.text = ""
UIView.animateWithDuration(1, animations: { () -> Void in
self.buttonReply.alpha = 1
})
}
@IBAction func sendReplyButton(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 37.272727 | 106 | 0.637886 |
21498274402932c51b13c6199c60ce7a489d5dfc | 3,563 | //
// PluginPointBuilderTests.swift
// Plug
//
// Created by Tomasz Lewandowski on 15/02/2020.
// Copyright © 2020 LionSoftware.org. All rights reserved.
//
@testable import Plug
import XCTest
public class PluginPointBuilderTests: XCTestCase {
var sut: PluginPointBuilder<ResolvingContextMock, PluginMock>!
public override func setUp() {
sut = PluginPointBuilder()
}
// swiftlint:disable function_body_length
func testBuilding_WhenCalledAfterSetOfOperations_ShouldReturnCorrectPluginPoint() {
let p1 = PluginMock()
let p2 = PluginMock()
let p3 = PluginMock()
let p4 = PluginMock()
let p5 = PluginMock()
let p6 = PluginMock()
let p7 = PluginMock()
let p8 = PluginMock()
// test adding and removing plugins
sut.add(plugin: p1)
sut.add(plugin: p2)
sut.remove(plugin: p2)
// test adding and removing children
sut.add(
child: PluginPoint(
rules: [DisabledRule().any()],
plugins: [p3],
children: [PluginPoint(
rules: [EnabledRule().any()],
plugins: [p4],
children: []
)
]
)
)
sut.add(
child: PluginPoint(
rules: [EnabledRule().any()],
plugins: [p5],
children: [PluginPoint(
rules: [],
plugins: [p6],
children: [PluginPoint(
rules: [DisabledRule().any()],
plugins: [p7],
children: [])
])
]
)
)
let child = PluginPoint<ResolvingContextMock, PluginMock>(rules: [], plugins: [p8], children: [])
sut.add(child: child)
sut.remove(child: child)
// test adding and removing rules and actual output
let rule = DisabledRule<ResolvingContextMock>().any()
sut.add(rule: rule)
let pp1 = sut.build()
XCTAssertEqual(0, pp1.getAvailablePlugins(context: ResolvingContextMock()).count)
sut.remove(rule: rule)
let pp2 = sut.build()
let plugins = pp2.getAvailablePlugins(context: ResolvingContextMock())
XCTAssertEqual(3, plugins.count)
XCTAssertTrue(plugins.contains(where: { $0 === p1 }))
XCTAssertTrue(plugins.contains(where: { $0 === p5 }))
XCTAssertTrue(plugins.contains(where: { $0 === p6 }))
}
func testDSL_WhenUsed_ShouldReturnCorrectPluginPoint() {
let p1 = PluginMock()
let p2 = PluginMock()
let p3 = PluginMock()
let p4 = PluginMock()
let p5 = PluginMock()
let child = PluginPoint<ResolvingContextMock, PluginMock>(rules: [], plugins: [p5], children: [])
let rule = DisabledRule<ResolvingContextMock>().any()
let pp = (sut
<+ p1
<+ p2
>- p2
|+ (PluginPointBuilder() §+ DisabledRule().any() <+ p3
|+ (PluginPointBuilder() <+ p4 §+ EnabledRule().any())^
)^
|+ child |- child
§+ rule
§- rule
)^
XCTAssertEqual(1, pp.getAvailablePlugins(context: ResolvingContextMock()).count)
let plugins = pp.getAvailablePlugins(context: ResolvingContextMock())
XCTAssertTrue(plugins.contains(where: { $0 === p1 }))
}
}
| 33.613208 | 105 | 0.527365 |
1d1d31cd77d406c1c0dba06f0ae67f1c1ec2e2d4 | 3,144 | //
// SeatPlan.swift
// MiramarTicketMaster
//
// Created by 𝕎𝔸𝕐ℕ𝔼 on 2019/4/11.
// Copyright © 2019 Wayne. All rights reserved.
//
import Foundation
class SeatPlan: Decodable {
let result: Int
let data: Data
enum CodingKeys: String, CodingKey {
case result = "Result"
case data = "Data"
}
var areas: [SeatLayoutData.Area] {
return data.seatLayoutData.areas
}
}
extension SeatPlan {
class Data: Decodable {
let seatLayoutData: SeatLayoutData
enum CodingKeys: String, CodingKey {
case seatLayoutData = "SeatLayoutData"
}
}
}
extension SeatPlan {
class SeatLayoutData: Decodable {
let areas: [Area]
enum CodingKeys: String, CodingKey {
case areas = "Areas"
}
}
}
extension SeatPlan.SeatLayoutData {
class Area: Decodable {
let areaCategoryCode: String
let rows: [Row]
enum CodingKeys: String, CodingKey {
case areaCategoryCode = "AreaCategoryCode"
case rows = "Rows"
}
}
}
extension SeatPlan.SeatLayoutData.Area {
class Row: Decodable {
let physicalName: String?
let seats: [Seat]
enum CodingKeys: String, CodingKey {
case physicalName = "PhysicalName"
case seats = "Seats"
}
}
}
extension SeatPlan.SeatLayoutData.Area.Row {
class Seat: Decodable {
let id: String
let originalStatus: Int
let position: Position
let status: Int
var score: Int
enum CodingKeys: String, CodingKey {
case id = "Id"
case originalStatus = "OriginalStatus"
case position = "Position"
case status = "Status"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.originalStatus = try container.decode(Int.self, forKey: .originalStatus)
self.position = try container.decode(Position.self, forKey: .position)
self.status = try container.decode(Int.self, forKey: .status)
self.score = 0
}
var seatStatus: Status {
return Status(rawValue: status)
}
func toSelectedSeat(with areaCategoryCode: String) -> Order.SelectedSeat {
let selectedSeat = Order.SelectedSeat()
selectedSeat.areaCategoryCode = areaCategoryCode
selectedSeat.areaNumber = String(position.areaNumber)
selectedSeat.columnIndex = String(position.columnIndex)
selectedSeat.rowIndex = String(position.rowIndex)
return selectedSeat
}
}
}
extension SeatPlan.SeatLayoutData.Area.Row.Seat {
enum Status: Int {
case empty = 0
case sold = 2
case other
init(rawValue: Int) {
if rawValue == 0 {
self = .empty
} else if rawValue == 2 {
self = .sold
} else {
self = .other
}
}
}
struct Position: Decodable {
let areaNumber: Int
let columnIndex: Int
let rowIndex: Int
enum CodingKeys: String, CodingKey {
case areaNumber = "AreaNumber"
case columnIndex = "ColumnIndex"
case rowIndex = "RowIndex"
}
}
}
| 21.833333 | 89 | 0.638041 |
560443ac1fae64cf9970de062c23be7a3582a58b | 1,002 | //
// CAPersistentAnimationsShapeLayer.swift
// Notifire
//
// Created by David Bielik on 05/09/2018.
// Copyright © 2018 David Bielik. All rights reserved.
//
import UIKit
class CAPersistentAnimationsShapeLayer: CAShapeLayer, PersistentAnimationsObserving {
// MARK: - Properties
var observers = [NSObjectProtocol]()
var persistentAnimations: [String: CAAnimation] = [:]
var persistentSpeed: Float = 0.0
// MARK: - Inherited
override init() {
super.init()
setupSublayers()
}
override init(layer: Any) {
super.init(layer: layer)
setupSublayers()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSublayers()
}
override func hitTest(_ point: CGPoint) -> CALayer? {
return super.hitTest(point)
}
deinit {
stopObservingNotifications()
}
// MARK: - Private
private func setupSublayers() {
startObservingNotifications()
}
}
| 21.782609 | 85 | 0.636727 |
095a3067f6242350fff67fb39008082ba26a40cb | 447 | //
// Driver.swift
// CleanArchitecture
//
// Created by Su Ho V. on 12/19/18.
// Copyright © 2018 mlsuho. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
extension ObservableType {
func emptyDriverIfError() -> Driver<E> {
return asDriver { _ in return Driver<E>.empty() }
}
func emptyObservableIfError() -> Observable<E> {
return catchError { _ in return Observable<E>.empty() }
}
}
| 20.318182 | 63 | 0.655481 |
bf2683b2eb0272d84e88f92f2e9e89e73e69015f | 1,451 | //
// SelectViewModel.swift
// TextureBase
//
// Created by HJQ on 2018/12/16.
// Copyright © 2018 ml. All rights reserved.
//
import UIKit
import SwiftyJSON
class SelectViewModel {
// 广告
var infos: [AWSelectInfo] = [AWSelectInfo]()
// 列表
var listInfos: [AWSelectListInfo] = [AWSelectListInfo]()
func loadTopData(r: SelectTopRequest, successBlock: @escaping () -> (), failureBlock: @escaping () -> ()) {
HTTPClient.shared.send(r, progressBlock: { (progress) in
}, success: { (result) in
self.listInfos = AWSelectListModel.init(json: JSON.init(result)).info
print(result)
successBlock()
}, failure: { (error) in
self.listInfos = [AWSelectListInfo]()
failureBlock()
}) { (_, error) in
self.listInfos = [AWSelectListInfo]()
failureBlock()
}
}
func loadListData(r: SelectRequest, successBlock: @escaping () -> (), failureBlock: @escaping () -> ()) {
HTTPClient.shared.send(r, progressBlock: { (progress) in
}, success: { (result) in
self.infos = AWSelectModel.init(json: JSON.init(result)).info
print(result)
successBlock()
}, failure: { (error) in
self.infos = [AWSelectInfo]()
failureBlock()
}) { (_, error) in
self.infos = [AWSelectInfo]()
failureBlock()
}
}
}
| 28.45098 | 111 | 0.560992 |
e6862d2dcee8d394c3b5625152624bc775e5f95b | 1,593 | //
// SwitchFilter.swift
// Canyoneer
//
// Created by Brice Pollock on 1/9/22.
//
import Foundation
import UIKit
class SwitchFilter: UIStackView {
enum Strings {
static let yes = "Yes"
static let no = "No"
static let any = "Any"
}
private let filterTitle = UILabel()
private let filterSwitch = UISegmentedControl()
public var selections: [String] {
switch self.filterSwitch.selectedSegmentIndex {
case 0: return [Strings.yes]
case 1: return [Strings.no]
case 2: return [Strings.any]
default: return [Strings.any]
}
}
public
init() {
super.init(frame: .zero)
self.axis = .horizontal
self.spacing = Grid.medium
self.addArrangedSubview(self.filterTitle)
self.addArrangedSubview(UIView())
self.addArrangedSubview(self.filterSwitch)
self.filterSwitch.insertSegment(withTitle: Strings.yes, at: 0, animated: false)
self.filterSwitch.insertSegment(withTitle: Strings.no, at: 1, animated: false)
self.filterSwitch.insertSegment(withTitle: Strings.any, at: 2, animated: false)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(title: String, isYes: Bool?) {
self.filterTitle.text = title
if let isYes = isYes {
self.filterSwitch.selectedSegmentIndex = isYes ? 0 : 1
} else {
self.filterSwitch.selectedSegmentIndex = 2
}
}
}
| 26.55 | 87 | 0.608286 |
2937e542e01596d9fa111c440551a212e32e722a | 159 | let N = 10
func fib(x: Int) -> Int {
guard x > 1 else { return x }
return fib(x: x - 1) + fib(x: x - 2)
}
for i in 1..<N {
print(i, " - ", fib(x: i))
} | 15.9 | 38 | 0.471698 |
9c1d145d0229e06d6823df57a8181eef21691176 | 181,220 | // Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable explicit_type_interface identifier_name line_length nesting type_body_length type_name
internal enum Localizable {
internal enum InfoPlist {
/// The camera is needed to scan QR codes
internal static var nsCameraUsageDescription: String { return Localizable.tr("InfoPlist", "NSCameraUsageDescription") }
internal static var nsCameraUsageDescriptionKey: String { return "NSCameraUsageDescription" }
/// Access to your wallet
internal static var nsFaceIDUsageDescription: String { return Localizable.tr("InfoPlist", "NSFaceIDUsageDescription") }
internal static var nsFaceIDUsageDescriptionKey: String { return "NSFaceIDUsageDescription" }
/// The camera is needed to scan QR codes
internal static var nsPhotoLibraryAddUsageDescription: String { return Localizable.tr("InfoPlist", "NSPhotoLibraryAddUsageDescription") }
internal static var nsPhotoLibraryAddUsageDescriptionKey: String { return "NSPhotoLibraryAddUsageDescription" }
}
internal enum Waves {
internal enum Accountpassword {
internal enum Button {
internal enum Signin {
/// Sign In
internal static var title: String { return Localizable.tr("Waves", "accountpassword.button.signIn.title") }
internal static var titleKey: String { return "accountpassword.button.signIn.title" }
}
}
internal enum Error {
/// Wrong password
internal static var wrongpassword: String { return Localizable.tr("Waves", "accountpassword.error.wrongpassword") }
internal static var wrongpasswordKey: String { return "accountpassword.error.wrongpassword" }
}
internal enum Textfield {
internal enum Error {
/// Minimum %d characters
internal static func atleastcharacters(_ p1: Int) -> String {
return Localizable.tr("Waves", "accountpassword.textfield.error.atleastcharacters", p1)
}
}
internal enum Password {
/// Account password
internal static var placeholder: String { return Localizable.tr("Waves", "accountpassword.textfield.password.placeholder") }
internal static var placeholderKey: String { return "accountpassword.textfield.password.placeholder" }
}
}
}
internal enum Addaddressbook {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "addAddressbook.button.cancel") }
internal static var cancelKey: String { return "addAddressbook.button.cancel" }
/// Delete
internal static var delete: String { return Localizable.tr("Waves", "addAddressbook.button.delete") }
internal static var deleteKey: String { return "addAddressbook.button.delete" }
/// Delete address
internal static var deleteAddress: String { return Localizable.tr("Waves", "addAddressbook.button.deleteAddress") }
internal static var deleteAddressKey: String { return "addAddressbook.button.deleteAddress" }
/// Save
internal static var save: String { return Localizable.tr("Waves", "addAddressbook.button.save") }
internal static var saveKey: String { return "addAddressbook.button.save" }
}
internal enum Error {
/// %d characters maximum
internal static func charactersMaximum(_ p1: Int) -> String {
return Localizable.tr("Waves", "addAddressbook.error.charactersMaximum", p1)
}
/// Minimum %d characters
internal static func charactersMinimum(_ p1: Int) -> String {
return Localizable.tr("Waves", "addAddressbook.error.charactersMinimum", p1)
}
}
internal enum Label {
/// Add
internal static var add: String { return Localizable.tr("Waves", "addAddressbook.label.add") }
internal static var addKey: String { return "addAddressbook.label.add" }
/// Address
internal static var address: String { return Localizable.tr("Waves", "addAddressbook.label.address") }
internal static var addressKey: String { return "addAddressbook.label.address" }
/// Are you sure you want to delete address from address book?
internal static var deleteAlertMessage: String { return Localizable.tr("Waves", "addAddressbook.label.deleteAlertMessage") }
internal static var deleteAlertMessageKey: String { return "addAddressbook.label.deleteAlertMessage" }
/// Edit
internal static var edit: String { return Localizable.tr("Waves", "addAddressbook.label.edit") }
internal static var editKey: String { return "addAddressbook.label.edit" }
/// Name
internal static var name: String { return Localizable.tr("Waves", "addAddressbook.label.name") }
internal static var nameKey: String { return "addAddressbook.label.name" }
}
internal enum Textfield {
internal enum Address {
internal enum Error {
/// Already in use
internal static var addressexist: String { return Localizable.tr("Waves", "addAddressbook.textfield.address.error.addressexist") }
internal static var addressexistKey: String { return "addAddressbook.textfield.address.error.addressexist" }
}
}
}
}
internal enum Addressbook {
internal enum Label {
/// Address book
internal static var addressBook: String { return Localizable.tr("Waves", "addressbook.label.addressBook") }
internal static var addressBookKey: String { return "addressbook.label.addressBook" }
/// Address deleted
internal static var addressDeleted: String { return Localizable.tr("Waves", "addressbook.label.addressDeleted") }
internal static var addressDeletedKey: String { return "addressbook.label.addressDeleted" }
/// Nothing Here…\nYou can create new address
internal static var noInfo: String { return Localizable.tr("Waves", "addressbook.label.noInfo") }
internal static var noInfoKey: String { return "addressbook.label.noInfo" }
}
}
internal enum Addressbookbutton {
internal enum Title {
/// Edit name
internal static var editName: String { return Localizable.tr("Waves", "addressBookButton.title.editName") }
internal static var editNameKey: String { return "addressBookButton.title.editName" }
/// Save address
internal static var saveAddress: String { return Localizable.tr("Waves", "addressBookButton.title.saveAddress") }
internal static var saveAddressKey: String { return "addressBookButton.title.saveAddress" }
}
}
internal enum Addresseskeys {
internal enum Cell {
internal enum Address {
/// Your address
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.address.title") }
internal static var titleKey: String { return "addresseskeys.cell.address.title" }
}
internal enum Aliases {
/// Aliases
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.aliases.title") }
internal static var titleKey: String { return "addresseskeys.cell.aliases.title" }
internal enum Subtitle {
/// You have %d
internal static func withaliaces(_ p1: Int) -> String {
return Localizable.tr("Waves", "addresseskeys.cell.aliases.subtitle.withaliaces", p1)
}
/// You do not have
internal static var withoutaliaces: String { return Localizable.tr("Waves", "addresseskeys.cell.aliases.subtitle.withoutaliaces") }
internal static var withoutaliacesKey: String { return "addresseskeys.cell.aliases.subtitle.withoutaliaces" }
}
}
internal enum Privatekey {
/// Private Key
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.privatekey.title") }
internal static var titleKey: String { return "addresseskeys.cell.privatekey.title" }
}
internal enum Privatekeyhidde {
internal enum Button {
/// Show
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.privatekeyhidde.button.title") }
internal static var titleKey: String { return "addresseskeys.cell.privatekeyhidde.button.title" }
}
}
internal enum Publickey {
/// Public Key
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.publickey.title") }
internal static var titleKey: String { return "addresseskeys.cell.publickey.title" }
}
internal enum Seed {
/// SEED
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.cell.seed.title") }
internal static var titleKey: String { return "addresseskeys.cell.seed.title" }
}
}
internal enum Navigation {
/// Addresses, keys
internal static var title: String { return Localizable.tr("Waves", "addresseskeys.navigation.title") }
internal static var titleKey: String { return "addresseskeys.navigation.title" }
}
}
internal enum Aliases {
internal enum Cell {
internal enum Head {
/// Your Aliases
internal static var title: String { return Localizable.tr("Waves", "aliases.cell.head.title") }
internal static var titleKey: String { return "aliases.cell.head.title" }
}
}
internal enum View {
internal enum Info {
internal enum Button {
/// Create a new alias
internal static var create: String { return Localizable.tr("Waves", "aliases.view.info.button.create") }
internal static var createKey: String { return "aliases.view.info.button.create" }
}
internal enum Label {
/// Your Alias must be between 4 and 30 characters long, and must contain only lowercase Latin letters, digits and symbols (@, -, _ and dot)
internal static var secondsubtitle: String { return Localizable.tr("Waves", "aliases.view.info.label.secondsubtitle") }
internal static var secondsubtitleKey: String { return "aliases.view.info.label.secondsubtitle" }
/// An Alias is a nickname for your address. You can use an Alias instead of an address to make transactions.
internal static var subtitle: String { return Localizable.tr("Waves", "aliases.view.info.label.subtitle") }
internal static var subtitleKey: String { return "aliases.view.info.label.subtitle" }
/// About Alias
internal static var title: String { return Localizable.tr("Waves", "aliases.view.info.label.title") }
internal static var titleKey: String { return "aliases.view.info.label.title" }
}
}
}
}
internal enum Aliaseswithout {
internal enum View {
internal enum Info {
internal enum Button {
/// Create a new alias
internal static var create: String { return Localizable.tr("Waves", "aliaseswithout.view.info.button.create") }
internal static var createKey: String { return "aliaseswithout.view.info.button.create" }
}
internal enum Label {
/// Your Alias must be between 4 and 30 characters long, and must contain only lowercase Latin letters, digits and symbols (@, -, _ and dot)
internal static var secondsubtitle: String { return Localizable.tr("Waves", "aliaseswithout.view.info.label.secondsubtitle") }
internal static var secondsubtitleKey: String { return "aliaseswithout.view.info.label.secondsubtitle" }
/// An Alias is a nickname for your address. You can use an Alias instead of an address to make transactions.
internal static var subtitle: String { return Localizable.tr("Waves", "aliaseswithout.view.info.label.subtitle") }
internal static var subtitleKey: String { return "aliaseswithout.view.info.label.subtitle" }
/// You do not have Aliases
internal static var title: String { return Localizable.tr("Waves", "aliaseswithout.view.info.label.title") }
internal static var titleKey: String { return "aliaseswithout.view.info.label.title" }
}
}
}
}
internal enum Appnews {
internal enum Button {
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "appnews.button.okey") }
internal static var okeyKey: String { return "appnews.button.okey" }
}
}
internal enum Asset {
internal enum Cell {
/// Transaction history
internal static var viewHistory: String { return Localizable.tr("Waves", "asset.cell.viewHistory") }
internal static var viewHistoryKey: String { return "asset.cell.viewHistory" }
internal enum Assetinfo {
/// You can not perform transactions with this token
internal static var cantPerformTransactions: String { return Localizable.tr("Waves", "asset.cell.assetInfo.cantPerformTransactions") }
internal static var cantPerformTransactionsKey: String { return "asset.cell.assetInfo.cantPerformTransactions" }
/// Decimal points
internal static var decimalPoints: String { return Localizable.tr("Waves", "asset.cell.assetInfo.decimalPoints") }
internal static var decimalPointsKey: String { return "asset.cell.assetInfo.decimalPoints" }
/// Description
internal static var description: String { return Localizable.tr("Waves", "asset.cell.assetInfo.description") }
internal static var descriptionKey: String { return "asset.cell.assetInfo.description" }
/// ID
internal static var id: String { return Localizable.tr("Waves", "asset.cell.assetInfo.id") }
internal static var idKey: String { return "asset.cell.assetInfo.id" }
/// Issue date
internal static var issueDate: String { return Localizable.tr("Waves", "asset.cell.assetInfo.issueDate") }
internal static var issueDateKey: String { return "asset.cell.assetInfo.issueDate" }
/// Issuer
internal static var issuer: String { return Localizable.tr("Waves", "asset.cell.assetInfo.issuer") }
internal static var issuerKey: String { return "asset.cell.assetInfo.issuer" }
/// Name
internal static var name: String { return Localizable.tr("Waves", "asset.cell.assetInfo.name") }
internal static var nameKey: String { return "asset.cell.assetInfo.name" }
/// Token Info
internal static var title: String { return Localizable.tr("Waves", "asset.cell.assetInfo.title") }
internal static var titleKey: String { return "asset.cell.assetInfo.title" }
/// Total amount
internal static var totalAmount: String { return Localizable.tr("Waves", "asset.cell.assetInfo.totalAmount") }
internal static var totalAmountKey: String { return "asset.cell.assetInfo.totalAmount" }
internal enum Kind {
/// Not reissuable
internal static var notReissuable: String { return Localizable.tr("Waves", "asset.cell.assetInfo.kind.notReissuable") }
internal static var notReissuableKey: String { return "asset.cell.assetInfo.kind.notReissuable" }
/// Reissuable
internal static var reissuable: String { return Localizable.tr("Waves", "asset.cell.assetInfo.kind.reissuable") }
internal static var reissuableKey: String { return "asset.cell.assetInfo.kind.reissuable" }
/// Type
internal static var title: String { return Localizable.tr("Waves", "asset.cell.assetInfo.kind.title") }
internal static var titleKey: String { return "asset.cell.assetInfo.kind.title" }
}
}
internal enum Balance {
/// Available balance
internal static var avaliableBalance: String { return Localizable.tr("Waves", "asset.cell.balance.avaliableBalance") }
internal static var avaliableBalanceKey: String { return "asset.cell.balance.avaliableBalance" }
/// In order
internal static var inOrderBalance: String { return Localizable.tr("Waves", "asset.cell.balance.inOrderBalance") }
internal static var inOrderBalanceKey: String { return "asset.cell.balance.inOrderBalance" }
/// Leased
internal static var leased: String { return Localizable.tr("Waves", "asset.cell.balance.leased") }
internal static var leasedKey: String { return "asset.cell.balance.leased" }
/// Total
internal static var totalBalance: String { return Localizable.tr("Waves", "asset.cell.balance.totalBalance") }
internal static var totalBalanceKey: String { return "asset.cell.balance.totalBalance" }
internal enum Button {
/// Exchange
internal static var exchange: String { return Localizable.tr("Waves", "asset.cell.balance.button.exchange") }
internal static var exchangeKey: String { return "asset.cell.balance.button.exchange" }
/// Receive
internal static var receive: String { return Localizable.tr("Waves", "asset.cell.balance.button.receive") }
internal static var receiveKey: String { return "asset.cell.balance.button.receive" }
/// Send
internal static var send: String { return Localizable.tr("Waves", "asset.cell.balance.button.send") }
internal static var sendKey: String { return "asset.cell.balance.button.send" }
}
}
}
internal enum Header {
/// Last transactions
internal static var lastTransactions: String { return Localizable.tr("Waves", "asset.header.lastTransactions") }
internal static var lastTransactionsKey: String { return "asset.header.lastTransactions" }
/// You do not have any transactions
internal static var notHaveTransactions: String { return Localizable.tr("Waves", "asset.header.notHaveTransactions") }
internal static var notHaveTransactionsKey: String { return "asset.header.notHaveTransactions" }
}
}
internal enum Assetlist {
internal enum Button {
/// All list
internal static var allList: String { return Localizable.tr("Waves", "assetlist.button.allList") }
internal static var allListKey: String { return "assetlist.button.allList" }
/// With balance
internal static var myList: String { return Localizable.tr("Waves", "assetlist.button.myList") }
internal static var myListKey: String { return "assetlist.button.myList" }
/// With balance
internal static var withBalance: String { return Localizable.tr("Waves", "assetlist.button.withBalance") }
internal static var withBalanceKey: String { return "assetlist.button.withBalance" }
}
internal enum Label {
/// Tokens
internal static var assets: String { return Localizable.tr("Waves", "assetlist.label.assets") }
internal static var assetsKey: String { return "assetlist.label.assets" }
/// Loading tokens…
internal static var loadingAssets: String { return Localizable.tr("Waves", "assetlist.label.loadingAssets") }
internal static var loadingAssetsKey: String { return "assetlist.label.loadingAssets" }
}
}
internal enum Backup {
internal enum Backup {
internal enum Navigation {
/// Backup phrase
internal static var title: String { return Localizable.tr("Waves", "backup.backup.navigation.title") }
internal static var titleKey: String { return "backup.backup.navigation.title" }
}
}
internal enum Confirmbackup {
internal enum Button {
/// Confirm
internal static var confirm: String { return Localizable.tr("Waves", "backup.confirmbackup.button.confirm") }
internal static var confirmKey: String { return "backup.confirmbackup.button.confirm" }
}
internal enum Error {
/// Wrong order, try again
internal static var label: String { return Localizable.tr("Waves", "backup.confirmbackup.error.label") }
internal static var labelKey: String { return "backup.confirmbackup.error.label" }
}
internal enum Info {
/// Please, tap each word in the correct order
internal static var label: String { return Localizable.tr("Waves", "backup.confirmbackup.info.label") }
internal static var labelKey: String { return "backup.confirmbackup.info.label" }
}
internal enum Navigation {
/// Confirm backup
internal static var title: String { return Localizable.tr("Waves", "backup.confirmbackup.navigation.title") }
internal static var titleKey: String { return "backup.confirmbackup.navigation.title" }
}
}
internal enum Needbackup {
internal enum Button {
/// Back Up Now
internal static var backupnow: String { return Localizable.tr("Waves", "backup.needbackup.button.backupnow") }
internal static var backupnowKey: String { return "backup.needbackup.button.backupnow" }
/// Do it later
internal static var doitlater: String { return Localizable.tr("Waves", "backup.needbackup.button.doitlater") }
internal static var doitlaterKey: String { return "backup.needbackup.button.doitlater" }
}
internal enum Label {
/// You must save the secret phrase. It is crucial for accessing your account.
internal static var detail: String { return Localizable.tr("Waves", "backup.needbackup.label.detail") }
internal static var detailKey: String { return "backup.needbackup.label.detail" }
/// No Backup, No Money
internal static var title: String { return Localizable.tr("Waves", "backup.needbackup.label.title") }
internal static var titleKey: String { return "backup.needbackup.label.title" }
}
}
internal enum Savebackup {
internal enum Copy {
internal enum Label {
/// Please carefully write down these 15 words or copy them
internal static var title: String { return Localizable.tr("Waves", "backup.savebackup.copy.label.title") }
internal static var titleKey: String { return "backup.savebackup.copy.label.title" }
}
}
internal enum Label {
/// Since only you control your money, you’ll need to save your backup phrase in case this app is deleted
internal static var title: String { return Localizable.tr("Waves", "backup.savebackup.label.title") }
internal static var titleKey: String { return "backup.savebackup.label.title" }
}
internal enum Navigation {
/// Save backup phrase
internal static var title: String { return Localizable.tr("Waves", "backup.savebackup.navigation.title") }
internal static var titleKey: String { return "backup.savebackup.navigation.title" }
}
internal enum Next {
internal enum Button {
/// I've written it down
internal static var title: String { return Localizable.tr("Waves", "backup.savebackup.next.button.title") }
internal static var titleKey: String { return "backup.savebackup.next.button.title" }
}
internal enum Label {
/// You will confirm this phrase on the next screen
internal static var title: String { return Localizable.tr("Waves", "backup.savebackup.next.label.title") }
internal static var titleKey: String { return "backup.savebackup.next.label.title" }
}
}
}
}
internal enum Biometric {
/// Cancel
internal static var localizedCancelTitle: String { return Localizable.tr("Waves", "biometric.localizedCancelTitle") }
internal static var localizedCancelTitleKey: String { return "biometric.localizedCancelTitle" }
/// Enter Passcode
internal static var localizedFallbackTitle: String { return Localizable.tr("Waves", "biometric.localizedFallbackTitle") }
internal static var localizedFallbackTitleKey: String { return "biometric.localizedFallbackTitle" }
/// Access to your wallet
internal static var readfromkeychain: String { return Localizable.tr("Waves", "biometric.readfromkeychain") }
internal static var readfromkeychainKey: String { return "biometric.readfromkeychain" }
/// Access to your wallet
internal static var saveinkeychain: String { return Localizable.tr("Waves", "biometric.saveinkeychain") }
internal static var saveinkeychainKey: String { return "biometric.saveinkeychain" }
internal enum Manyattempts {
/// To unlock biometric, sign in with your account password
internal static var subtitle: String { return Localizable.tr("Waves", "biometric.manyattempts.subtitle") }
internal static var subtitleKey: String { return "biometric.manyattempts.subtitle" }
/// Too many attempts
internal static var title: String { return Localizable.tr("Waves", "biometric.manyattempts.title") }
internal static var titleKey: String { return "biometric.manyattempts.title" }
}
}
internal enum Cameraaccess {
internal enum Alert {
/// Allow Camera
internal static var allow: String { return Localizable.tr("Waves", "cameraAccess.alert.allow") }
internal static var allowKey: String { return "cameraAccess.alert.allow" }
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "cameraAccess.alert.cancel") }
internal static var cancelKey: String { return "cameraAccess.alert.cancel" }
/// Camera access is required to make full use of this app
internal static var message: String { return Localizable.tr("Waves", "cameraAccess.alert.message") }
internal static var messageKey: String { return "cameraAccess.alert.message" }
/// Need Camera Access
internal static var title: String { return Localizable.tr("Waves", "cameraAccess.alert.title") }
internal static var titleKey: String { return "cameraAccess.alert.title" }
}
}
internal enum Changepassword {
internal enum Button {
internal enum Confirm {
/// Confirm
internal static var title: String { return Localizable.tr("Waves", "changepassword.button.confirm.title") }
internal static var titleKey: String { return "changepassword.button.confirm.title" }
}
}
internal enum Navigation {
/// Changed password
internal static var title: String { return Localizable.tr("Waves", "changepassword.navigation.title") }
internal static var titleKey: String { return "changepassword.navigation.title" }
}
internal enum Textfield {
internal enum Confirmpassword {
/// Confirm password
internal static var title: String { return Localizable.tr("Waves", "changepassword.textfield.confirmpassword.title") }
internal static var titleKey: String { return "changepassword.textfield.confirmpassword.title" }
}
internal enum Createpassword {
/// New password
internal static var title: String { return Localizable.tr("Waves", "changepassword.textfield.createpassword.title") }
internal static var titleKey: String { return "changepassword.textfield.createpassword.title" }
}
internal enum Error {
/// Minimum %d characters
internal static func atleastcharacters(_ p1: Int) -> String {
return Localizable.tr("Waves", "changepassword.textfield.error.atleastcharacters", p1)
}
/// incorrect password
internal static var incorrectpassword: String { return Localizable.tr("Waves", "changepassword.textfield.error.incorrectpassword") }
internal static var incorrectpasswordKey: String { return "changepassword.textfield.error.incorrectpassword" }
/// password not match
internal static var passwordnotmatch: String { return Localizable.tr("Waves", "changepassword.textfield.error.passwordnotmatch") }
internal static var passwordnotmatchKey: String { return "changepassword.textfield.error.passwordnotmatch" }
}
internal enum Oldpassword {
/// Old password
internal static var title: String { return Localizable.tr("Waves", "changepassword.textfield.oldpassword.title") }
internal static var titleKey: String { return "changepassword.textfield.oldpassword.title" }
}
}
}
internal enum Chooseaccount {
internal enum Alert {
internal enum Button {
/// Cancel
internal static var no: String { return Localizable.tr("Waves", "chooseaccount.alert.button.no") }
internal static var noKey: String { return "chooseaccount.alert.button.no" }
/// Yes
internal static var ok: String { return Localizable.tr("Waves", "chooseaccount.alert.button.ok") }
internal static var okKey: String { return "chooseaccount.alert.button.ok" }
}
internal enum Delete {
/// Are you sure you want to delete this account?
internal static var message: String { return Localizable.tr("Waves", "chooseaccount.alert.delete.message") }
internal static var messageKey: String { return "chooseaccount.alert.delete.message" }
/// Delete account
internal static var title: String { return Localizable.tr("Waves", "chooseaccount.alert.delete.title") }
internal static var titleKey: String { return "chooseaccount.alert.delete.title" }
}
}
internal enum Label {
/// Nothing Here…\nYou do not have saved accounts
internal static var nothingWallets: String { return Localizable.tr("Waves", "chooseaccount.label.nothingWallets") }
internal static var nothingWalletsKey: String { return "chooseaccount.label.nothingWallets" }
}
internal enum Navigation {
/// Choose account
internal static var title: String { return Localizable.tr("Waves", "chooseaccount.navigation.title") }
internal static var titleKey: String { return "chooseaccount.navigation.title" }
}
}
internal enum Coinomat {
/// Service Coinomat temporarily unavailable
internal static var temporarilyUnavailable: String { return Localizable.tr("Waves", "coinomat.temporarilyUnavailable") }
internal static var temporarilyUnavailableKey: String { return "coinomat.temporarilyUnavailable" }
/// Try again later
internal static var tryAgain: String { return Localizable.tr("Waves", "coinomat.tryAgain") }
internal static var tryAgainKey: String { return "coinomat.tryAgain" }
}
internal enum Createalias {
internal enum Button {
internal enum Create {
/// Create
internal static var title: String { return Localizable.tr("Waves", "createalias.button.create.title") }
internal static var titleKey: String { return "createalias.button.create.title" }
}
}
internal enum Cell {
internal enum Input {
internal enum Textfiled {
internal enum Input {
/// Symbolic name
internal static var placeholder: String { return Localizable.tr("Waves", "createalias.cell.input.textfiled.input.placeholder") }
internal static var placeholderKey: String { return "createalias.cell.input.textfiled.input.placeholder" }
/// Symbolic name
internal static var title: String { return Localizable.tr("Waves", "createalias.cell.input.textfiled.input.title") }
internal static var titleKey: String { return "createalias.cell.input.textfiled.input.title" }
}
}
}
}
internal enum Error {
/// Already in use
internal static var alreadyinuse: String { return Localizable.tr("Waves", "createalias.error.alreadyinuse") }
internal static var alreadyinuseKey: String { return "createalias.error.alreadyinuse" }
/// 30 characters maximum
internal static var charactersmaximum: String { return Localizable.tr("Waves", "createalias.error.charactersmaximum") }
internal static var charactersmaximumKey: String { return "createalias.error.charactersmaximum" }
/// Invalid character
internal static var invalidcharacter: String { return Localizable.tr("Waves", "createalias.error.invalidcharacter") }
internal static var invalidcharacterKey: String { return "createalias.error.invalidcharacter" }
/// Minimum 4 characters
internal static var minimumcharacters: String { return Localizable.tr("Waves", "createalias.error.minimumcharacters") }
internal static var minimumcharactersKey: String { return "createalias.error.minimumcharacters" }
}
internal enum Navigation {
/// New alias
internal static var title: String { return Localizable.tr("Waves", "createalias.navigation.title") }
internal static var titleKey: String { return "createalias.navigation.title" }
}
}
internal enum Dex {
internal enum General {
internal enum Error {
/// Nothing Here…
internal static var nothingHere: String { return Localizable.tr("Waves", "dex.general.error.nothingHere") }
internal static var nothingHereKey: String { return "dex.general.error.nothingHere" }
/// Something went wrong
internal static var somethingWentWrong: String { return Localizable.tr("Waves", "dex.general.error.somethingWentWrong") }
internal static var somethingWentWrongKey: String { return "dex.general.error.somethingWentWrong" }
}
}
}
internal enum Dexchart {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "dexchart.button.cancel") }
internal static var cancelKey: String { return "dexchart.button.cancel" }
}
internal enum Label {
/// No chart data available
internal static var emptyData: String { return Localizable.tr("Waves", "dexchart.label.emptyData") }
internal static var emptyDataKey: String { return "dexchart.label.emptyData" }
/// hour
internal static var hour: String { return Localizable.tr("Waves", "dexchart.label.hour") }
internal static var hourKey: String { return "dexchart.label.hour" }
/// hours
internal static var hours: String { return Localizable.tr("Waves", "dexchart.label.hours") }
internal static var hoursKey: String { return "dexchart.label.hours" }
/// Loading chart…
internal static var loadingChart: String { return Localizable.tr("Waves", "dexchart.label.loadingChart") }
internal static var loadingChartKey: String { return "dexchart.label.loadingChart" }
/// minutes
internal static var minutes: String { return Localizable.tr("Waves", "dexchart.label.minutes") }
internal static var minutesKey: String { return "dexchart.label.minutes" }
}
}
internal enum Dexcompleteorder {
internal enum Button {
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "dexcompleteorder.button.okey") }
internal static var okeyKey: String { return "dexcompleteorder.button.okey" }
}
internal enum Label {
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "dexcompleteorder.label.amount") }
internal static var amountKey: String { return "dexcompleteorder.label.amount" }
/// Open
internal static var `open`: String { return Localizable.tr("Waves", "dexcompleteorder.label.open") }
internal static var openKey: String { return "dexcompleteorder.label.open" }
/// The order is created
internal static var orderIsCreated: String { return Localizable.tr("Waves", "dexcompleteorder.label.orderIsCreated") }
internal static var orderIsCreatedKey: String { return "dexcompleteorder.label.orderIsCreated" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "dexcompleteorder.label.price") }
internal static var priceKey: String { return "dexcompleteorder.label.price" }
/// Status
internal static var status: String { return Localizable.tr("Waves", "dexcompleteorder.label.status") }
internal static var statusKey: String { return "dexcompleteorder.label.status" }
/// Time
internal static var time: String { return Localizable.tr("Waves", "dexcompleteorder.label.time") }
internal static var timeKey: String { return "dexcompleteorder.label.time" }
}
}
internal enum Dexcreateorder {
internal enum Button {
/// Ask
internal static var ask: String { return Localizable.tr("Waves", "dexcreateorder.button.ask") }
internal static var askKey: String { return "dexcreateorder.button.ask" }
/// Bid
internal static var bid: String { return Localizable.tr("Waves", "dexcreateorder.button.bid") }
internal static var bidKey: String { return "dexcreateorder.button.bid" }
/// Buy
internal static var buy: String { return Localizable.tr("Waves", "dexcreateorder.button.buy") }
internal static var buyKey: String { return "dexcreateorder.button.buy" }
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "dexcreateorder.button.cancel") }
internal static var cancelKey: String { return "dexcreateorder.button.cancel" }
/// day
internal static var day: String { return Localizable.tr("Waves", "dexcreateorder.button.day") }
internal static var dayKey: String { return "dexcreateorder.button.day" }
/// days
internal static var days: String { return Localizable.tr("Waves", "dexcreateorder.button.days") }
internal static var daysKey: String { return "dexcreateorder.button.days" }
/// hour
internal static var hour: String { return Localizable.tr("Waves", "dexcreateorder.button.hour") }
internal static var hourKey: String { return "dexcreateorder.button.hour" }
/// Last
internal static var last: String { return Localizable.tr("Waves", "dexcreateorder.button.last") }
internal static var lastKey: String { return "dexcreateorder.button.last" }
/// minutes
internal static var minutes: String { return Localizable.tr("Waves", "dexcreateorder.button.minutes") }
internal static var minutesKey: String { return "dexcreateorder.button.minutes" }
/// Sell
internal static var sell: String { return Localizable.tr("Waves", "dexcreateorder.button.sell") }
internal static var sellKey: String { return "dexcreateorder.button.sell" }
/// Use total balance
internal static var useTotalBalanace: String { return Localizable.tr("Waves", "dexcreateorder.button.useTotalBalanace") }
internal static var useTotalBalanaceKey: String { return "dexcreateorder.button.useTotalBalanace" }
/// week
internal static var week: String { return Localizable.tr("Waves", "dexcreateorder.button.week") }
internal static var weekKey: String { return "dexcreateorder.button.week" }
}
internal enum Label {
/// Amount in
internal static var amountIn: String { return Localizable.tr("Waves", "dexcreateorder.label.amountIn") }
internal static var amountInKey: String { return "dexcreateorder.label.amountIn" }
/// Value is too big
internal static var bigValue: String { return Localizable.tr("Waves", "dexcreateorder.label.bigValue") }
internal static var bigValueKey: String { return "dexcreateorder.label.bigValue" }
/// days
internal static var days: String { return Localizable.tr("Waves", "dexcreateorder.label.days") }
internal static var daysKey: String { return "dexcreateorder.label.days" }
/// Expiration
internal static var expiration: String { return Localizable.tr("Waves", "dexcreateorder.label.Expiration") }
internal static var expirationKey: String { return "dexcreateorder.label.Expiration" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "dexcreateorder.label.fee") }
internal static var feeKey: String { return "dexcreateorder.label.fee" }
/// Limit Price in
internal static var limitPriceIn: String { return Localizable.tr("Waves", "dexcreateorder.label.limitPriceIn") }
internal static var limitPriceInKey: String { return "dexcreateorder.label.limitPriceIn" }
/// Not enough
internal static var notEnough: String { return Localizable.tr("Waves", "dexcreateorder.label.notEnough") }
internal static var notEnoughKey: String { return "dexcreateorder.label.notEnough" }
/// Value is too small
internal static var smallValue: String { return Localizable.tr("Waves", "dexcreateorder.label.smallValue") }
internal static var smallValueKey: String { return "dexcreateorder.label.smallValue" }
/// Total in
internal static var totalIn: String { return Localizable.tr("Waves", "dexcreateorder.label.totalIn") }
internal static var totalInKey: String { return "dexcreateorder.label.totalIn" }
internal enum Error {
/// You don't have enough funds to pay the required fees.
internal static var notFundsFee: String { return Localizable.tr("Waves", "dexcreateorder.label.error.notFundsFee") }
internal static var notFundsFeeKey: String { return "dexcreateorder.label.error.notFundsFee" }
}
}
}
internal enum Dexinfo {
internal enum Label {
/// Amount Token
internal static var amountAsset: String { return Localizable.tr("Waves", "dexinfo.label.amountAsset") }
internal static var amountAssetKey: String { return "dexinfo.label.amountAsset" }
/// Popular
internal static var popular: String { return Localizable.tr("Waves", "dexinfo.label.popular") }
internal static var popularKey: String { return "dexinfo.label.popular" }
/// Price Token
internal static var priceAsset: String { return Localizable.tr("Waves", "dexinfo.label.priceAsset") }
internal static var priceAssetKey: String { return "dexinfo.label.priceAsset" }
}
}
internal enum Dexlasttrades {
internal enum Button {
/// BUY
internal static var buy: String { return Localizable.tr("Waves", "dexlasttrades.button.buy") }
internal static var buyKey: String { return "dexlasttrades.button.buy" }
/// SELL
internal static var sell: String { return Localizable.tr("Waves", "dexlasttrades.button.sell") }
internal static var sellKey: String { return "dexlasttrades.button.sell" }
}
internal enum Label {
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "dexlasttrades.label.amount") }
internal static var amountKey: String { return "dexlasttrades.label.amount" }
/// Nothing Here…\nThe trading history is empty
internal static var emptyData: String { return Localizable.tr("Waves", "dexlasttrades.label.emptyData") }
internal static var emptyDataKey: String { return "dexlasttrades.label.emptyData" }
/// Loading last trades…
internal static var loadingLastTrades: String { return Localizable.tr("Waves", "dexlasttrades.label.loadingLastTrades") }
internal static var loadingLastTradesKey: String { return "dexlasttrades.label.loadingLastTrades" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "dexlasttrades.label.price") }
internal static var priceKey: String { return "dexlasttrades.label.price" }
/// Sum
internal static var sum: String { return Localizable.tr("Waves", "dexlasttrades.label.sum") }
internal static var sumKey: String { return "dexlasttrades.label.sum" }
/// Time
internal static var time: String { return Localizable.tr("Waves", "dexlasttrades.label.time") }
internal static var timeKey: String { return "dexlasttrades.label.time" }
}
}
internal enum Dexlist {
internal enum Button {
/// Add Markets
internal static var addMarkets: String { return Localizable.tr("Waves", "dexlist.button.addMarkets") }
internal static var addMarketsKey: String { return "dexlist.button.addMarkets" }
}
internal enum Label {
/// Decentralised Exchange
internal static var decentralisedExchange: String { return Localizable.tr("Waves", "dexlist.label.decentralisedExchange") }
internal static var decentralisedExchangeKey: String { return "dexlist.label.decentralisedExchange" }
/// Trade quickly and securely. You retain complete control over your funds when trading them on our decentralised exchange.
internal static var description: String { return Localizable.tr("Waves", "dexlist.label.description") }
internal static var descriptionKey: String { return "dexlist.label.description" }
/// Last update
internal static var lastUpdate: String { return Localizable.tr("Waves", "dexlist.label.lastUpdate") }
internal static var lastUpdateKey: String { return "dexlist.label.lastUpdate" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "dexlist.label.price") }
internal static var priceKey: String { return "dexlist.label.price" }
/// Today
internal static var today: String { return Localizable.tr("Waves", "dexlist.label.today") }
internal static var todayKey: String { return "dexlist.label.today" }
/// Yesterday
internal static var yesterday: String { return Localizable.tr("Waves", "dexlist.label.yesterday") }
internal static var yesterdayKey: String { return "dexlist.label.yesterday" }
}
internal enum Navigationbar {
/// DEX
internal static var title: String { return Localizable.tr("Waves", "dexlist.navigationBar.title") }
internal static var titleKey: String { return "dexlist.navigationBar.title" }
}
}
internal enum Dexmarket {
internal enum Label {
/// Loading markets…
internal static var loadingMarkets: String { return Localizable.tr("Waves", "dexmarket.label.loadingMarkets") }
internal static var loadingMarketsKey: String { return "dexmarket.label.loadingMarkets" }
}
internal enum Navigationbar {
/// Markets
internal static var title: String { return Localizable.tr("Waves", "dexmarket.navigationBar.title") }
internal static var titleKey: String { return "dexmarket.navigationBar.title" }
}
internal enum Searchbar {
/// Search
internal static var placeholder: String { return Localizable.tr("Waves", "dexmarket.searchBar.placeholder") }
internal static var placeholderKey: String { return "dexmarket.searchBar.placeholder" }
}
}
internal enum Dexmyorders {
internal enum Label {
/// Buy
internal static var buy: String { return Localizable.tr("Waves", "dexmyorders.label.buy") }
internal static var buyKey: String { return "dexmyorders.label.buy" }
/// Nothing Here…\nYou do not have any orders
internal static var emptyData: String { return Localizable.tr("Waves", "dexmyorders.label.emptyData") }
internal static var emptyDataKey: String { return "dexmyorders.label.emptyData" }
/// Loading orders…
internal static var loadingLastTrades: String { return Localizable.tr("Waves", "dexmyorders.label.loadingLastTrades") }
internal static var loadingLastTradesKey: String { return "dexmyorders.label.loadingLastTrades" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "dexmyorders.label.price") }
internal static var priceKey: String { return "dexmyorders.label.price" }
/// Sell
internal static var sell: String { return Localizable.tr("Waves", "dexmyorders.label.sell") }
internal static var sellKey: String { return "dexmyorders.label.sell" }
/// Status
internal static var status: String { return Localizable.tr("Waves", "dexmyorders.label.status") }
internal static var statusKey: String { return "dexmyorders.label.status" }
/// Time
internal static var time: String { return Localizable.tr("Waves", "dexmyorders.label.time") }
internal static var timeKey: String { return "dexmyorders.label.time" }
/// Type
internal static var type: String { return Localizable.tr("Waves", "dexmyorders.label.type") }
internal static var typeKey: String { return "dexmyorders.label.type" }
internal enum Status {
/// Open
internal static var accepted: String { return Localizable.tr("Waves", "dexmyorders.label.status.accepted") }
internal static var acceptedKey: String { return "dexmyorders.label.status.accepted" }
/// Cancelled
internal static var cancelled: String { return Localizable.tr("Waves", "dexmyorders.label.status.cancelled") }
internal static var cancelledKey: String { return "dexmyorders.label.status.cancelled" }
/// Filled
internal static var filled: String { return Localizable.tr("Waves", "dexmyorders.label.status.filled") }
internal static var filledKey: String { return "dexmyorders.label.status.filled" }
/// Partial
internal static var partiallyFilled: String { return Localizable.tr("Waves", "dexmyorders.label.status.partiallyFilled") }
internal static var partiallyFilledKey: String { return "dexmyorders.label.status.partiallyFilled" }
}
}
}
internal enum Dexorderbook {
internal enum Button {
/// BUY
internal static var buy: String { return Localizable.tr("Waves", "dexorderbook.button.buy") }
internal static var buyKey: String { return "dexorderbook.button.buy" }
/// SELL
internal static var sell: String { return Localizable.tr("Waves", "dexorderbook.button.sell") }
internal static var sellKey: String { return "dexorderbook.button.sell" }
}
internal enum Label {
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "dexorderbook.label.amount") }
internal static var amountKey: String { return "dexorderbook.label.amount" }
/// Nothing Here…\nThe order book is empty
internal static var emptyData: String { return Localizable.tr("Waves", "dexorderbook.label.emptyData") }
internal static var emptyDataKey: String { return "dexorderbook.label.emptyData" }
/// LAST PRICE
internal static var lastPrice: String { return Localizable.tr("Waves", "dexorderbook.label.lastPrice") }
internal static var lastPriceKey: String { return "dexorderbook.label.lastPrice" }
/// Loading orderbook…
internal static var loadingOrderbook: String { return Localizable.tr("Waves", "dexorderbook.label.loadingOrderbook") }
internal static var loadingOrderbookKey: String { return "dexorderbook.label.loadingOrderbook" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "dexorderbook.label.price") }
internal static var priceKey: String { return "dexorderbook.label.price" }
/// SPREAD
internal static var spread: String { return Localizable.tr("Waves", "dexorderbook.label.spread") }
internal static var spreadKey: String { return "dexorderbook.label.spread" }
/// Sum
internal static var sum: String { return Localizable.tr("Waves", "dexorderbook.label.sum") }
internal static var sumKey: String { return "dexorderbook.label.sum" }
}
}
internal enum Dexscriptassetmessage {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "dexScriptAssetMessage.button.cancel") }
internal static var cancelKey: String { return "dexScriptAssetMessage.button.cancel" }
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "dexScriptAssetMessage.button.continue") }
internal static var continueKey: String { return "dexScriptAssetMessage.button.continue" }
/// Do not show again
internal static var doNotShowAgain: String { return Localizable.tr("Waves", "dexScriptAssetMessage.button.doNotShowAgain") }
internal static var doNotShowAgainKey: String { return "dexScriptAssetMessage.button.doNotShowAgain" }
}
internal enum Label {
/// Smart assets are assets that include a script that sets the conditions for the circulation of the token.\n\nWe do not recommend you perform operations with smart assets if you are an inexperienced user. Before making a transaction, please read the information about the asset and its script carefully.
internal static var description: String { return Localizable.tr("Waves", "dexScriptAssetMessage.label.description") }
internal static var descriptionKey: String { return "dexScriptAssetMessage.label.description" }
/// Order placement for a pair that includes a Smart Asset
internal static var title: String { return Localizable.tr("Waves", "dexScriptAssetMessage.label.title") }
internal static var titleKey: String { return "dexScriptAssetMessage.label.title" }
}
}
internal enum Dexsort {
internal enum Navigationbar {
/// Sorting
internal static var title: String { return Localizable.tr("Waves", "dexsort.navigationBar.title") }
internal static var titleKey: String { return "dexsort.navigationBar.title" }
}
}
internal enum Dextradercontainer {
internal enum Button {
/// Chart
internal static var chart: String { return Localizable.tr("Waves", "dextradercontainer.button.chart") }
internal static var chartKey: String { return "dextradercontainer.button.chart" }
/// Last trades
internal static var lastTrades: String { return Localizable.tr("Waves", "dextradercontainer.button.lastTrades") }
internal static var lastTradesKey: String { return "dextradercontainer.button.lastTrades" }
/// My orders
internal static var myOrders: String { return Localizable.tr("Waves", "dextradercontainer.button.myOrders") }
internal static var myOrdersKey: String { return "dextradercontainer.button.myOrders" }
/// Orderbook
internal static var orderbook: String { return Localizable.tr("Waves", "dextradercontainer.button.orderbook") }
internal static var orderbookKey: String { return "dextradercontainer.button.orderbook" }
}
}
internal enum Editaccountname {
internal enum Button {
/// Save
internal static var save: String { return Localizable.tr("Waves", "editaccountname.button.save") }
internal static var saveKey: String { return "editaccountname.button.save" }
}
internal enum Label {
/// New account name
internal static var newName: String { return Localizable.tr("Waves", "editaccountname.label.newName") }
internal static var newNameKey: String { return "editaccountname.label.newName" }
}
internal enum Navigation {
/// Edit name
internal static var title: String { return Localizable.tr("Waves", "editaccountname.navigation.title") }
internal static var titleKey: String { return "editaccountname.navigation.title" }
}
}
internal enum Enter {
internal enum Block {
internal enum Blockchain {
/// Become part of a fast-growing area of the crypto world. You are the only person who can access your crypto assets.
internal static var text: String { return Localizable.tr("Waves", "enter.block.blockchain.text") }
internal static var textKey: String { return "enter.block.blockchain.text" }
/// Get Started with Blockchain
internal static var title: String { return Localizable.tr("Waves", "enter.block.blockchain.title") }
internal static var titleKey: String { return "enter.block.blockchain.title" }
}
internal enum Exchange {
/// Trade quickly and securely. You retain complete control over your funds when trading them on our decentralised exchange.
internal static var text: String { return Localizable.tr("Waves", "enter.block.exchange.text") }
internal static var textKey: String { return "enter.block.exchange.text" }
/// Decentralised Exchange
internal static var title: String { return Localizable.tr("Waves", "enter.block.exchange.title") }
internal static var titleKey: String { return "enter.block.exchange.title" }
}
internal enum Token {
/// Issue your own tokens. These can be integrated into your business not only as an internal currency but also as a token for decentralised voting, as a rating system, or loyalty program.
internal static var text: String { return Localizable.tr("Waves", "enter.block.token.text") }
internal static var textKey: String { return "enter.block.token.text" }
/// Token Launcher
internal static var title: String { return Localizable.tr("Waves", "enter.block.token.title") }
internal static var titleKey: String { return "enter.block.token.title" }
}
internal enum Wallet {
/// Store, manage and receive interest on your digital tokens balance, easily and securely.
internal static var text: String { return Localizable.tr("Waves", "enter.block.wallet.text") }
internal static var textKey: String { return "enter.block.wallet.text" }
/// Wallet
internal static var title: String { return Localizable.tr("Waves", "enter.block.wallet.title") }
internal static var titleKey: String { return "enter.block.wallet.title" }
}
}
internal enum Button {
internal enum Confirm {
/// Confirm
internal static var title: String { return Localizable.tr("Waves", "enter.button.confirm.title") }
internal static var titleKey: String { return "enter.button.confirm.title" }
}
internal enum Createnewaccount {
/// Create a new account
internal static var title: String { return Localizable.tr("Waves", "enter.button.createNewAccount.title") }
internal static var titleKey: String { return "enter.button.createNewAccount.title" }
}
internal enum Importaccount {
/// via pairing code or manually
internal static var detail: String { return Localizable.tr("Waves", "enter.button.importAccount.detail") }
internal static var detailKey: String { return "enter.button.importAccount.detail" }
/// Import account
internal static var title: String { return Localizable.tr("Waves", "enter.button.importAccount.title") }
internal static var titleKey: String { return "enter.button.importAccount.title" }
internal enum Error {
/// Insecure SEED
internal static var insecureSeed: String { return Localizable.tr("Waves", "enter.button.importAccount.error.insecureSeed") }
internal static var insecureSeedKey: String { return "enter.button.importAccount.error.insecureSeed" }
}
}
internal enum Signin {
/// to a saved account
internal static var detail: String { return Localizable.tr("Waves", "enter.button.signIn.detail") }
internal static var detailKey: String { return "enter.button.signIn.detail" }
/// Sign in
internal static var title: String { return Localizable.tr("Waves", "enter.button.signIn.title") }
internal static var titleKey: String { return "enter.button.signIn.title" }
}
}
internal enum Label {
/// or
internal static var or: String { return Localizable.tr("Waves", "enter.label.or") }
internal static var orKey: String { return "enter.label.or" }
}
internal enum Language {
internal enum Navigation {
/// Change language
internal static var title: String { return Localizable.tr("Waves", "enter.language.navigation.title") }
internal static var titleKey: String { return "enter.language.navigation.title" }
}
}
}
internal enum General {
internal enum Biometric {
internal enum Faceid {
/// Face ID
internal static var title: String { return Localizable.tr("Waves", "general.biometric.faceID.title") }
internal static var titleKey: String { return "general.biometric.faceID.title" }
}
internal enum Touchid {
/// Touch ID
internal static var title: String { return Localizable.tr("Waves", "general.biometric.touchID.title") }
internal static var titleKey: String { return "general.biometric.touchID.title" }
}
}
internal enum Error {
internal enum Subtitle {
/// Do not worry, we are already fixing this problem.\nSoon everything will work!
internal static var notfound: String { return Localizable.tr("Waves", "general.error.subtitle.notfound") }
internal static var notfoundKey: String { return "general.error.subtitle.notfound" }
}
internal enum Title {
/// No connection to the Internet
internal static var noconnectiontotheinternet: String { return Localizable.tr("Waves", "general.error.title.noconnectiontotheinternet") }
internal static var noconnectiontotheinternetKey: String { return "general.error.title.noconnectiontotheinternet" }
/// Oh… It's all broken!
internal static var notfound: String { return Localizable.tr("Waves", "general.error.title.notfound") }
internal static var notfoundKey: String { return "general.error.title.notfound" }
}
}
internal enum Label {
internal enum Title {
/// / My token
internal static var myasset: String { return Localizable.tr("Waves", "general.label.title.myasset") }
internal static var myassetKey: String { return "general.label.title.myasset" }
}
}
internal enum Tabbar {
internal enum Title {
/// DEX
internal static var dex: String { return Localizable.tr("Waves", "general.tabbar.title.dex") }
internal static var dexKey: String { return "general.tabbar.title.dex" }
/// History
internal static var history: String { return Localizable.tr("Waves", "general.tabbar.title.history") }
internal static var historyKey: String { return "general.tabbar.title.history" }
/// Profile
internal static var profile: String { return Localizable.tr("Waves", "general.tabbar.title.profile") }
internal static var profileKey: String { return "general.tabbar.title.profile" }
/// Wallet
internal static var wallet: String { return Localizable.tr("Waves", "general.tabbar.title.wallet") }
internal static var walletKey: String { return "general.tabbar.title.wallet" }
}
}
internal enum Ticker {
internal enum Title {
/// Cryptocurrency
internal static var cryptocurrency: String { return Localizable.tr("Waves", "general.ticker.title.cryptocurrency") }
internal static var cryptocurrencyKey: String { return "general.ticker.title.cryptocurrency" }
/// Fiat Money
internal static var fiatmoney: String { return Localizable.tr("Waves", "general.ticker.title.fiatmoney") }
internal static var fiatmoneyKey: String { return "general.ticker.title.fiatmoney" }
/// SUSPICIOUS
internal static var spam: String { return Localizable.tr("Waves", "general.ticker.title.spam") }
internal static var spamKey: String { return "general.ticker.title.spam" }
/// Waves Token
internal static var wavestoken: String { return Localizable.tr("Waves", "general.ticker.title.wavestoken") }
internal static var wavestokenKey: String { return "general.ticker.title.wavestoken" }
}
}
internal enum Tost {
internal enum Savebackup {
/// Store your SEED safely, it is the only way to restore your wallet
internal static var subtitle: String { return Localizable.tr("Waves", "general.tost.saveBackup.subtitle") }
internal static var subtitleKey: String { return "general.tost.saveBackup.subtitle" }
/// Save your backup phrase (SEED)
internal static var title: String { return Localizable.tr("Waves", "general.tost.saveBackup.title") }
internal static var titleKey: String { return "general.tost.saveBackup.title" }
}
}
}
internal enum Hello {
internal enum Button {
/// Begin
internal static var begin: String { return Localizable.tr("Waves", "hello.button.begin") }
internal static var beginKey: String { return "hello.button.begin" }
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "hello.button.continue") }
internal static var continueKey: String { return "hello.button.continue" }
/// Next
internal static var next: String { return Localizable.tr("Waves", "hello.button.next") }
internal static var nextKey: String { return "hello.button.next" }
}
internal enum Page {
internal enum Confirm {
/// I understand that my funds are held securely on this device, not by a company. If this app is moved to another device or deleted, my Waves can only be recovered with the backup phrase.
internal static var description1: String { return Localizable.tr("Waves", "hello.page.confirm.description1") }
internal static var description1Key: String { return "hello.page.confirm.description1" }
/// I have read and agree with the Privacy Policy
internal static var description2: String { return Localizable.tr("Waves", "hello.page.confirm.description2") }
internal static var description2Key: String { return "hello.page.confirm.description2" }
/// I have read and agree with the Terms and Conditions
internal static var description3: String { return Localizable.tr("Waves", "hello.page.confirm.description3") }
internal static var description3Key: String { return "hello.page.confirm.description3" }
/// All the data on your Waves Wallet is encrypted and stored only on your device
internal static var subtitle: String { return Localizable.tr("Waves", "hello.page.confirm.subtitle") }
internal static var subtitleKey: String { return "hello.page.confirm.subtitle" }
/// Confirm and begin
internal static var title: String { return Localizable.tr("Waves", "hello.page.confirm.title") }
internal static var titleKey: String { return "hello.page.confirm.title" }
internal enum Button {
/// Privacy policy
internal static var privacyPolicy: String { return Localizable.tr("Waves", "hello.page.confirm.button.privacyPolicy") }
internal static var privacyPolicyKey: String { return "hello.page.confirm.button.privacyPolicy" }
/// Terms and conditions
internal static var termsAndConditions: String { return Localizable.tr("Waves", "hello.page.confirm.button.termsAndConditions") }
internal static var termsAndConditionsKey: String { return "hello.page.confirm.button.termsAndConditions" }
}
}
internal enum Info {
internal enum Fifth {
/// How To Protect Yourself from Phishers
internal static var title: String { return Localizable.tr("Waves", "hello.page.info.fifth.title") }
internal static var titleKey: String { return "hello.page.info.fifth.title" }
internal enum Detail {
/// Do not open emails or links from unknown senders.
internal static var first: String { return Localizable.tr("Waves", "hello.page.info.fifth.detail.first") }
internal static var firstKey: String { return "hello.page.info.fifth.detail.first" }
/// Do not access your wallet when using public Wi-Fi or someone else’s device.
internal static var fourth: String { return Localizable.tr("Waves", "hello.page.info.fifth.detail.fourth") }
internal static var fourthKey: String { return "hello.page.info.fifth.detail.fourth" }
/// Regularly update your operating system.
internal static var second: String { return Localizable.tr("Waves", "hello.page.info.fifth.detail.second") }
internal static var secondKey: String { return "hello.page.info.fifth.detail.second" }
/// Use official security software. Do not install unknown software which could be hacked.
internal static var third: String { return Localizable.tr("Waves", "hello.page.info.fifth.detail.third") }
internal static var thirdKey: String { return "hello.page.info.fifth.detail.third" }
}
}
internal enum First {
/// Please take some time to understand some important things for your own safety.\n\nWe cannot recover your funds or freeze your account if you visit a phishing site or lose your backup phrase (aka SEED phrase).\n\nBy continuing to use our platform, you agree to accept all risks associated with the loss of your SEED, including but not limited to the inability to obtain your funds and dispose of them. In case you lose your SEED, you agree and acknowledge that the Waves Platform would not be responsible for the negative consequences of this.
internal static var detail: String { return Localizable.tr("Waves", "hello.page.info.first.detail") }
internal static var detailKey: String { return "hello.page.info.first.detail" }
/// Welcome to the Waves Platform!
internal static var title: String { return Localizable.tr("Waves", "hello.page.info.first.title") }
internal static var titleKey: String { return "hello.page.info.first.title" }
}
internal enum Fourth {
/// One of the most common forms of scamming is phishing, which is when scammers create fake communities on Facebook or other websites that look similar to the authentic ones.
internal static var detail: String { return Localizable.tr("Waves", "hello.page.info.fourth.detail") }
internal static var detailKey: String { return "hello.page.info.fourth.detail" }
/// How To Protect Yourself from Phishers
internal static var title: String { return Localizable.tr("Waves", "hello.page.info.fourth.title") }
internal static var titleKey: String { return "hello.page.info.fourth.title" }
}
internal enum Second {
/// When registering your account, you will be asked to save your secret phrase (Seed) and to protect your account with a password. On normal centralized servers, special attention is paid to the password, which can be changed and reset via email, if the need arises. However, on decentralized platforms such as Waves, everything is arranged differently.
internal static var detail: String { return Localizable.tr("Waves", "hello.page.info.second.detail") }
internal static var detailKey: String { return "hello.page.info.second.detail" }
/// What you need to know about your SEED
internal static var title: String { return Localizable.tr("Waves", "hello.page.info.second.title") }
internal static var titleKey: String { return "hello.page.info.second.title" }
}
internal enum Third {
/// What you need to know about your SEED
internal static var title: String { return Localizable.tr("Waves", "hello.page.info.third.title") }
internal static var titleKey: String { return "hello.page.info.third.title" }
internal enum Detail {
/// You use your wallet anonymously, meaning your account is not connected to an email account or any other identifying data.
internal static var first: String { return Localizable.tr("Waves", "hello.page.info.third.detail.first") }
internal static var firstKey: String { return "hello.page.info.third.detail.first" }
/// You cannot change your secret phrase. If you accidentally sent it to someone or suspect that scammers have taken it over, then create a new Waves wallet immediately and transfer your funds to it.
internal static var fourth: String { return Localizable.tr("Waves", "hello.page.info.third.detail.fourth") }
internal static var fourthKey: String { return "hello.page.info.third.detail.fourth" }
/// Your password protects your account when working on a certain device or browser. It is needed in order to ensure that your secret phrase is not saved in storage.
internal static var second: String { return Localizable.tr("Waves", "hello.page.info.third.detail.second") }
internal static var secondKey: String { return "hello.page.info.third.detail.second" }
/// If you forget your password, you can easily create a new one by using the account recovery form via your secret phrase. If you lose your secret phrase, however, you will have no way to access your account.
internal static var third: String { return Localizable.tr("Waves", "hello.page.info.third.detail.third") }
internal static var thirdKey: String { return "hello.page.info.third.detail.third" }
}
}
}
}
}
internal enum History {
internal enum Navigationbar {
/// History
internal static var title: String { return Localizable.tr("Waves", "history.navigationBar.title") }
internal static var titleKey: String { return "history.navigationBar.title" }
}
internal enum Segmentedcontrol {
/// Active Now
internal static var activeNow: String { return Localizable.tr("Waves", "history.segmentedControl.activeNow") }
internal static var activeNowKey: String { return "history.segmentedControl.activeNow" }
/// All
internal static var all: String { return Localizable.tr("Waves", "history.segmentedControl.all") }
internal static var allKey: String { return "history.segmentedControl.all" }
/// Canceled
internal static var canceled: String { return Localizable.tr("Waves", "history.segmentedControl.canceled") }
internal static var canceledKey: String { return "history.segmentedControl.canceled" }
/// Exchanged
internal static var exchanged: String { return Localizable.tr("Waves", "history.segmentedControl.exchanged") }
internal static var exchangedKey: String { return "history.segmentedControl.exchanged" }
/// Issued
internal static var issued: String { return Localizable.tr("Waves", "history.segmentedControl.issued") }
internal static var issuedKey: String { return "history.segmentedControl.issued" }
/// Leased
internal static var leased: String { return Localizable.tr("Waves", "history.segmentedControl.leased") }
internal static var leasedKey: String { return "history.segmentedControl.leased" }
/// Received
internal static var received: String { return Localizable.tr("Waves", "history.segmentedControl.received") }
internal static var receivedKey: String { return "history.segmentedControl.received" }
/// Sent
internal static var sent: String { return Localizable.tr("Waves", "history.segmentedControl.sent") }
internal static var sentKey: String { return "history.segmentedControl.sent" }
}
internal enum Transaction {
internal enum Cell {
internal enum Exchange {
/// Buy: %@/%@
internal static func buy(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "history.transaction.cell.exchange.buy", p1, p2)
}
/// Sell: %@/%@
internal static func sell(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "history.transaction.cell.exchange.sell", p1, p2)
}
}
}
internal enum Title {
/// Create Alias
internal static var alias: String { return Localizable.tr("Waves", "history.transaction.title.alias") }
internal static var aliasKey: String { return "history.transaction.title.alias" }
/// Canceled Leasing
internal static var canceledLeasing: String { return Localizable.tr("Waves", "history.transaction.title.canceledLeasing") }
internal static var canceledLeasingKey: String { return "history.transaction.title.canceledLeasing" }
/// Data transaction
internal static var data: String { return Localizable.tr("Waves", "history.transaction.title.data") }
internal static var dataKey: String { return "history.transaction.title.data" }
/// Entry in blockchain
internal static var entryInBlockchain: String { return Localizable.tr("Waves", "history.transaction.title.entryInBlockchain") }
internal static var entryInBlockchainKey: String { return "history.transaction.title.entryInBlockchain" }
/// Exchange
internal static var exchange: String { return Localizable.tr("Waves", "history.transaction.title.exchange") }
internal static var exchangeKey: String { return "history.transaction.title.exchange" }
/// Incoming Leasing
internal static var incomingLeasing: String { return Localizable.tr("Waves", "history.transaction.title.incomingLeasing") }
internal static var incomingLeasingKey: String { return "history.transaction.title.incomingLeasing" }
/// Mass Received
internal static var massreceived: String { return Localizable.tr("Waves", "history.transaction.title.massreceived") }
internal static var massreceivedKey: String { return "history.transaction.title.massreceived" }
/// Mass Sent
internal static var masssent: String { return Localizable.tr("Waves", "history.transaction.title.masssent") }
internal static var masssentKey: String { return "history.transaction.title.masssent" }
/// Received
internal static var received: String { return Localizable.tr("Waves", "history.transaction.title.received") }
internal static var receivedKey: String { return "history.transaction.title.received" }
/// Received Sponsorship
internal static var receivedSponsorship: String { return Localizable.tr("Waves", "history.transaction.title.receivedSponsorship") }
internal static var receivedSponsorshipKey: String { return "history.transaction.title.receivedSponsorship" }
/// Self-transfer
internal static var selfTransfer: String { return Localizable.tr("Waves", "history.transaction.title.selfTransfer") }
internal static var selfTransferKey: String { return "history.transaction.title.selfTransfer" }
/// Sent
internal static var sent: String { return Localizable.tr("Waves", "history.transaction.title.sent") }
internal static var sentKey: String { return "history.transaction.title.sent" }
/// Entry in blockchain
internal static var setAssetScript: String { return Localizable.tr("Waves", "history.transaction.title.setAssetScript") }
internal static var setAssetScriptKey: String { return "history.transaction.title.setAssetScript" }
/// Entry in blockchain
internal static var setScript: String { return Localizable.tr("Waves", "history.transaction.title.setScript") }
internal static var setScriptKey: String { return "history.transaction.title.setScript" }
/// Started Leasing
internal static var startedLeasing: String { return Localizable.tr("Waves", "history.transaction.title.startedLeasing") }
internal static var startedLeasingKey: String { return "history.transaction.title.startedLeasing" }
/// Token Burn
internal static var tokenBurn: String { return Localizable.tr("Waves", "history.transaction.title.tokenBurn") }
internal static var tokenBurnKey: String { return "history.transaction.title.tokenBurn" }
/// Token Generation
internal static var tokenGeneration: String { return Localizable.tr("Waves", "history.transaction.title.tokenGeneration") }
internal static var tokenGenerationKey: String { return "history.transaction.title.tokenGeneration" }
/// Token Reissue
internal static var tokenReissue: String { return Localizable.tr("Waves", "history.transaction.title.tokenReissue") }
internal static var tokenReissueKey: String { return "history.transaction.title.tokenReissue" }
/// Unrecognised Transaction
internal static var unrecognisedTransaction: String { return Localizable.tr("Waves", "history.transaction.title.unrecognisedTransaction") }
internal static var unrecognisedTransactionKey: String { return "history.transaction.title.unrecognisedTransaction" }
}
internal enum Value {
/// Entry in blockchain
internal static var data: String { return Localizable.tr("Waves", "history.transaction.value.data") }
internal static var dataKey: String { return "history.transaction.value.data" }
/// Script Invocation
internal static var scriptInvocation: String { return Localizable.tr("Waves", "history.transaction.value.scriptInvocation") }
internal static var scriptInvocationKey: String { return "history.transaction.value.scriptInvocation" }
/// Update Script
internal static var setAssetScript: String { return Localizable.tr("Waves", "history.transaction.value.setAssetScript") }
internal static var setAssetScriptKey: String { return "history.transaction.value.setAssetScript" }
internal enum Setscript {
/// Cancel Script
internal static var cancel: String { return Localizable.tr("Waves", "history.transaction.value.setScript.cancel") }
internal static var cancelKey: String { return "history.transaction.value.setScript.cancel" }
/// Set Script
internal static var `set`: String { return Localizable.tr("Waves", "history.transaction.value.setScript.set") }
internal static var setKey: String { return "history.transaction.value.setScript.set" }
}
internal enum Setsponsorship {
/// Disable Sponsorship
internal static var cancel: String { return Localizable.tr("Waves", "history.transaction.value.setSponsorship.cancel") }
internal static var cancelKey: String { return "history.transaction.value.setSponsorship.cancel" }
/// Set Sponsorship
internal static var `set`: String { return Localizable.tr("Waves", "history.transaction.value.setSponsorship.set") }
internal static var setKey: String { return "history.transaction.value.setSponsorship.set" }
}
}
}
}
internal enum Import {
internal enum Account {
internal enum Button {
internal enum Enter {
/// Enter SEED manually
internal static var title: String { return Localizable.tr("Waves", "import.account.button.enter.title") }
internal static var titleKey: String { return "import.account.button.enter.title" }
}
internal enum Scan {
/// Scan pairing code
internal static var title: String { return Localizable.tr("Waves", "import.account.button.scan.title") }
internal static var titleKey: String { return "import.account.button.scan.title" }
}
}
internal enum Label {
internal enum Info {
internal enum Step {
internal enum One {
/// Settings — General — Export account
internal static var detail: String { return Localizable.tr("Waves", "import.account.label.info.step.one.detail") }
internal static var detailKey: String { return "import.account.label.info.step.one.detail" }
/// Log in to your Waves Client via your PC or Mac at https://client.wavesplatform.com
internal static var title: String { return Localizable.tr("Waves", "import.account.label.info.step.one.title") }
internal static var titleKey: String { return "import.account.label.info.step.one.title" }
}
internal enum Two {
/// Click «Show Pairing Code» to reveal a QR Code. Scan the code with your camera.
internal static var title: String { return Localizable.tr("Waves", "import.account.label.info.step.two.title") }
internal static var titleKey: String { return "import.account.label.info.step.two.title" }
}
}
}
}
internal enum Navigation {
/// Import account
internal static var title: String { return Localizable.tr("Waves", "import.account.navigation.title") }
internal static var titleKey: String { return "import.account.navigation.title" }
}
internal enum Warning {
internal enum Seed {
/// The SEED phrase you entered is too short. Make sure you do not confuse the phrase with a wallet address. Using an address as a SEED phrase can result in loss of funds.
internal static var subtitle: String { return Localizable.tr("Waves", "import.account.warning.seed.subtitle") }
internal static var subtitleKey: String { return "import.account.warning.seed.subtitle" }
/// The SEED phrase must consist of 15 words with spaces between each word
internal static var title: String { return Localizable.tr("Waves", "import.account.warning.seed.title") }
internal static var titleKey: String { return "import.account.warning.seed.title" }
}
}
}
internal enum General {
internal enum Error {
/// Already in use
internal static var alreadyinuse: String { return Localizable.tr("Waves", "import.general.error.alreadyinuse") }
internal static var alreadyinuseKey: String { return "import.general.error.alreadyinuse" }
}
internal enum Navigation {
/// Import account
internal static var title: String { return Localizable.tr("Waves", "import.general.navigation.title") }
internal static var titleKey: String { return "import.general.navigation.title" }
}
internal enum Segmentedcontrol {
/// Manually
internal static var manually: String { return Localizable.tr("Waves", "import.general.segmentedControl.manually") }
internal static var manuallyKey: String { return "import.general.segmentedControl.manually" }
/// Scan
internal static var scan: String { return Localizable.tr("Waves", "import.general.segmentedControl.scan") }
internal static var scanKey: String { return "import.general.segmentedControl.scan" }
}
}
internal enum Manually {
internal enum Button {
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "import.manually.button.continue") }
internal static var continueKey: String { return "import.manually.button.continue" }
}
internal enum Label {
internal enum Address {
/// Your SEED is the 15 words you saved when creating your account
internal static var placeholder: String { return Localizable.tr("Waves", "import.manually.label.address.placeholder") }
internal static var placeholderKey: String { return "import.manually.label.address.placeholder" }
/// Your account SEED
internal static var title: String { return Localizable.tr("Waves", "import.manually.label.address.title") }
internal static var titleKey: String { return "import.manually.label.address.title" }
}
}
}
internal enum Password {
internal enum Button {
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "import.password.button.continue") }
internal static var continueKey: String { return "import.password.button.continue" }
}
}
internal enum Scan {
internal enum Button {
/// Scan pairing code
internal static var title: String { return Localizable.tr("Waves", "import.scan.button.title") }
internal static var titleKey: String { return "import.scan.button.title" }
}
internal enum Label {
internal enum Step {
internal enum One {
/// Log in to your Waves Client via web or Mac, PC
internal static var title: String { return Localizable.tr("Waves", "import.scan.label.step.one.title") }
internal static var titleKey: String { return "import.scan.label.step.one.title" }
}
internal enum Three {
/// Scan the code with your camera
internal static var title: String { return Localizable.tr("Waves", "import.scan.label.step.three.title") }
internal static var titleKey: String { return "import.scan.label.step.three.title" }
}
internal enum Two {
/// Settings — General — Export account
internal static var detail: String { return Localizable.tr("Waves", "import.scan.label.step.two.detail") }
internal static var detailKey: String { return "import.scan.label.step.two.detail" }
/// Click «Show Pairing Code» to reveal a QR Code
internal static var title: String { return Localizable.tr("Waves", "import.scan.label.step.two.title") }
internal static var titleKey: String { return "import.scan.label.step.two.title" }
}
}
}
}
internal enum Welcome {
internal enum Button {
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "import.welcome.button.continue") }
internal static var continueKey: String { return "import.welcome.button.continue" }
}
internal enum Label {
internal enum Address {
/// Your SEED is the 15 words you saved when creating your account
internal static var placeholder: String { return Localizable.tr("Waves", "import.welcome.label.address.placeholder") }
internal static var placeholderKey: String { return "import.welcome.label.address.placeholder" }
/// Your account SEED
internal static var title: String { return Localizable.tr("Waves", "import.welcome.label.address.title") }
internal static var titleKey: String { return "import.welcome.label.address.title" }
}
}
internal enum Navigation {
/// Welcome back
internal static var title: String { return Localizable.tr("Waves", "import.welcome.navigation.title") }
internal static var titleKey: String { return "import.welcome.navigation.title" }
}
}
}
internal enum Menu {
internal enum Button {
/// Support Wavesplatform
internal static var supportwavesplatform: String { return Localizable.tr("Waves", "menu.button.supportwavesplatform") }
internal static var supportwavesplatformKey: String { return "menu.button.supportwavesplatform" }
/// Terms and conditions
internal static var termsandconditions: String { return Localizable.tr("Waves", "menu.button.termsandconditions") }
internal static var termsandconditionsKey: String { return "menu.button.termsandconditions" }
/// Whitepaper
internal static var whitepaper: String { return Localizable.tr("Waves", "menu.button.whitepaper") }
internal static var whitepaperKey: String { return "menu.button.whitepaper" }
}
internal enum Label {
/// Join the Waves Community
internal static var communities: String { return Localizable.tr("Waves", "menu.label.communities") }
internal static var communitiesKey: String { return "menu.label.communities" }
/// Keep up with the latest news and articles, and find out all about events happening on the Waves Platform
internal static var description: String { return Localizable.tr("Waves", "menu.label.description") }
internal static var descriptionKey: String { return "menu.label.description" }
}
}
internal enum Myaddress {
internal enum Button {
internal enum Copy {
/// Copy
internal static var title: String { return Localizable.tr("Waves", "myaddress.button.copy.title") }
internal static var titleKey: String { return "myaddress.button.copy.title" }
}
internal enum Share {
/// Share
internal static var title: String { return Localizable.tr("Waves", "myaddress.button.share.title") }
internal static var titleKey: String { return "myaddress.button.share.title" }
}
}
internal enum Cell {
internal enum Aliases {
/// Aliases
internal static var title: String { return Localizable.tr("Waves", "myaddress.cell.aliases.title") }
internal static var titleKey: String { return "myaddress.cell.aliases.title" }
internal enum Subtitle {
/// You have %d
internal static func withaliaces(_ p1: Int) -> String {
return Localizable.tr("Waves", "myaddress.cell.aliases.subtitle.withaliaces", p1)
}
/// You do not have
internal static var withoutaliaces: String { return Localizable.tr("Waves", "myaddress.cell.aliases.subtitle.withoutaliaces") }
internal static var withoutaliacesKey: String { return "myaddress.cell.aliases.subtitle.withoutaliaces" }
}
}
internal enum Info {
/// Your address
internal static var title: String { return Localizable.tr("Waves", "myaddress.cell.info.title") }
internal static var titleKey: String { return "myaddress.cell.info.title" }
}
internal enum Qrcode {
/// Your QR Code
internal static var title: String { return Localizable.tr("Waves", "myaddress.cell.qrcode.title") }
internal static var titleKey: String { return "myaddress.cell.qrcode.title" }
}
}
}
internal enum Networksettings {
internal enum Button {
internal enum Save {
/// Save
internal static var title: String { return Localizable.tr("Waves", "networksettings.button.save.title") }
internal static var titleKey: String { return "networksettings.button.save.title" }
}
internal enum Setdefault {
/// Set default
internal static var title: String { return Localizable.tr("Waves", "networksettings.button.setdefault.title") }
internal static var titleKey: String { return "networksettings.button.setdefault.title" }
}
}
internal enum Label {
internal enum Switchspam {
/// Spam filtering
internal static var title: String { return Localizable.tr("Waves", "networksettings.label.switchspam.title") }
internal static var titleKey: String { return "networksettings.label.switchspam.title" }
}
}
internal enum Navigation {
/// Network
internal static var title: String { return Localizable.tr("Waves", "networksettings.navigation.title") }
internal static var titleKey: String { return "networksettings.navigation.title" }
}
internal enum Textfield {
internal enum Spamfilter {
/// Spam filter
internal static var title: String { return Localizable.tr("Waves", "networksettings.textfield.spamfilter.title") }
internal static var titleKey: String { return "networksettings.textfield.spamfilter.title" }
}
}
}
internal enum Newaccount {
internal enum Avatar {
/// You cannot change it later
internal static var detail: String { return Localizable.tr("Waves", "newaccount.avatar.detail") }
internal static var detailKey: String { return "newaccount.avatar.detail" }
/// Choose your unique address avatar
internal static var title: String { return Localizable.tr("Waves", "newaccount.avatar.title") }
internal static var titleKey: String { return "newaccount.avatar.title" }
}
internal enum Backup {
internal enum Navigation {
/// New Account
internal static var title: String { return Localizable.tr("Waves", "newaccount.backup.navigation.title") }
internal static var titleKey: String { return "newaccount.backup.navigation.title" }
}
}
internal enum Error {
/// No avatar selected
internal static var noavatarselected: String { return Localizable.tr("Waves", "newaccount.error.noavatarselected") }
internal static var noavatarselectedKey: String { return "newaccount.error.noavatarselected" }
}
internal enum Main {
internal enum Navigation {
/// New Account
internal static var title: String { return Localizable.tr("Waves", "newaccount.main.navigation.title") }
internal static var titleKey: String { return "newaccount.main.navigation.title" }
}
}
internal enum Secret {
internal enum Navigation {
/// New Account
internal static var title: String { return Localizable.tr("Waves", "newaccount.secret.navigation.title") }
internal static var titleKey: String { return "newaccount.secret.navigation.title" }
}
}
internal enum Textfield {
internal enum Accountname {
/// Account name
internal static var title: String { return Localizable.tr("Waves", "newaccount.textfield.accountName.title") }
internal static var titleKey: String { return "newaccount.textfield.accountName.title" }
}
internal enum Confirmpassword {
/// Confirm password
internal static var title: String { return Localizable.tr("Waves", "newaccount.textfield.confirmpassword.title") }
internal static var titleKey: String { return "newaccount.textfield.confirmpassword.title" }
}
internal enum Createpassword {
/// Create a password
internal static var title: String { return Localizable.tr("Waves", "newaccount.textfield.createpassword.title") }
internal static var titleKey: String { return "newaccount.textfield.createpassword.title" }
}
internal enum Error {
/// Minimum %d characters
internal static func atleastcharacters(_ p1: Int) -> String {
return Localizable.tr("Waves", "newaccount.textfield.error.atleastcharacters", p1)
}
/// %d characters maximum
internal static func charactersmaximum(_ p1: Int) -> String {
return Localizable.tr("Waves", "newaccount.textfield.error.charactersmaximum", p1)
}
/// Does not match
internal static var doesnotmatch: String { return Localizable.tr("Waves", "newaccount.textfield.error.doesnotmatch") }
internal static var doesnotmatchKey: String { return "newaccount.textfield.error.doesnotmatch" }
/// %d characters maximum
internal static func maximumcharacters(_ p1: Int) -> String {
return Localizable.tr("Waves", "newaccount.textfield.error.maximumcharacters", p1)
}
/// Minimum %d characters
internal static func minimumcharacters(_ p1: Int) -> String {
return Localizable.tr("Waves", "newaccount.textfield.error.minimumcharacters", p1)
}
/// password not match
internal static var passwordnotmatch: String { return Localizable.tr("Waves", "newaccount.textfield.error.passwordnotmatch") }
internal static var passwordnotmatchKey: String { return "newaccount.textfield.error.passwordnotmatch" }
/// Wrong order, try again
internal static var wrongordertryagain: String { return Localizable.tr("Waves", "newaccount.textfield.error.wrongordertryagain") }
internal static var wrongordertryagainKey: String { return "newaccount.textfield.error.wrongordertryagain" }
}
}
}
internal enum Passcode {
internal enum Alert {
internal enum Attempsended {
/// To unlock, sign in with your account password
internal static var subtitle: String { return Localizable.tr("Waves", "passcode.alert.attempsended.subtitle") }
internal static var subtitleKey: String { return "passcode.alert.attempsended.subtitle" }
/// Too many attempts
internal static var title: String { return Localizable.tr("Waves", "passcode.alert.attempsended.title") }
internal static var titleKey: String { return "passcode.alert.attempsended.title" }
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "passcode.alert.attempsended.button.cancel") }
internal static var cancelKey: String { return "passcode.alert.attempsended.button.cancel" }
/// Use Password
internal static var enterpassword: String { return Localizable.tr("Waves", "passcode.alert.attempsended.button.enterpassword") }
internal static var enterpasswordKey: String { return "passcode.alert.attempsended.button.enterpassword" }
/// Ok
internal static var ok: String { return Localizable.tr("Waves", "passcode.alert.attempsended.button.ok") }
internal static var okKey: String { return "passcode.alert.attempsended.button.ok" }
}
}
}
internal enum Button {
internal enum Forgotpasscode {
/// Use account password
internal static var title: String { return Localizable.tr("Waves", "passcode.button.forgotPasscode.title") }
internal static var titleKey: String { return "passcode.button.forgotPasscode.title" }
}
}
internal enum Label {
internal enum Forgotpasscode {
/// Forgot passcode?
internal static var title: String { return Localizable.tr("Waves", "passcode.label.forgotPasscode.title") }
internal static var titleKey: String { return "passcode.label.forgotPasscode.title" }
}
internal enum Passcode {
/// Create a passcode
internal static var create: String { return Localizable.tr("Waves", "passcode.label.passcode.create") }
internal static var createKey: String { return "passcode.label.passcode.create" }
/// Enter Passcode
internal static var enter: String { return Localizable.tr("Waves", "passcode.label.passcode.enter") }
internal static var enterKey: String { return "passcode.label.passcode.enter" }
/// Enter old Passcode
internal static var old: String { return Localizable.tr("Waves", "passcode.label.passcode.old") }
internal static var oldKey: String { return "passcode.label.passcode.old" }
/// Verify your passcode
internal static var verify: String { return Localizable.tr("Waves", "passcode.label.passcode.verify") }
internal static var verifyKey: String { return "passcode.label.passcode.verify" }
}
}
}
internal enum Profile {
internal enum Alert {
internal enum Deleteaccount {
/// Are you sure you want to delete this account from device?
internal static var message: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.message") }
internal static var messageKey: String { return "profile.alert.deleteAccount.message" }
/// You did not save your SEED
internal static var notSaveSeed: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.notSaveSeed") }
internal static var notSaveSeedKey: String { return "profile.alert.deleteAccount.notSaveSeed" }
/// Delete account
internal static var title: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.title") }
internal static var titleKey: String { return "profile.alert.deleteAccount.title" }
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.button.cancel") }
internal static var cancelKey: String { return "profile.alert.deleteAccount.button.cancel" }
/// Delete
internal static var delete: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.button.delete") }
internal static var deleteKey: String { return "profile.alert.deleteAccount.button.delete" }
}
internal enum Withoutbackup {
/// Deleting an account will lead to its irretrievable loss!
internal static var message: String { return Localizable.tr("Waves", "profile.alert.deleteAccount.withoutbackup.message") }
internal static var messageKey: String { return "profile.alert.deleteAccount.withoutbackup.message" }
}
}
internal enum Setupbiometric {
/// To use fast and secure login, go to settings to enable biometrics
internal static var message: String { return Localizable.tr("Waves", "profile.alert.setupbiometric.message") }
internal static var messageKey: String { return "profile.alert.setupbiometric.message" }
/// Biometrics is disabled
internal static var title: String { return Localizable.tr("Waves", "profile.alert.setupbiometric.title") }
internal static var titleKey: String { return "profile.alert.setupbiometric.title" }
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "profile.alert.setupbiometric.button.cancel") }
internal static var cancelKey: String { return "profile.alert.setupbiometric.button.cancel" }
/// Settings
internal static var settings: String { return Localizable.tr("Waves", "profile.alert.setupbiometric.button.settings") }
internal static var settingsKey: String { return "profile.alert.setupbiometric.button.settings" }
}
}
}
internal enum Button {
internal enum Delete {
/// Delete account from device
internal static var title: String { return Localizable.tr("Waves", "profile.button.delete.title") }
internal static var titleKey: String { return "profile.button.delete.title" }
}
internal enum Logout {
/// Logout of account
internal static var title: String { return Localizable.tr("Waves", "profile.button.logout.title") }
internal static var titleKey: String { return "profile.button.logout.title" }
}
}
internal enum Cell {
internal enum Addressbook {
/// Address book
internal static var title: String { return Localizable.tr("Waves", "profile.cell.addressbook.title") }
internal static var titleKey: String { return "profile.cell.addressbook.title" }
}
internal enum Addresses {
/// Addresses, keys
internal static var title: String { return Localizable.tr("Waves", "profile.cell.addresses.title") }
internal static var titleKey: String { return "profile.cell.addresses.title" }
}
internal enum Backupphrase {
/// Backup phrase
internal static var title: String { return Localizable.tr("Waves", "profile.cell.backupphrase.title") }
internal static var titleKey: String { return "profile.cell.backupphrase.title" }
}
internal enum Changepasscode {
/// Change passcode
internal static var title: String { return Localizable.tr("Waves", "profile.cell.changepasscode.title") }
internal static var titleKey: String { return "profile.cell.changepasscode.title" }
}
internal enum Changepassword {
/// Change password
internal static var title: String { return Localizable.tr("Waves", "profile.cell.changepassword.title") }
internal static var titleKey: String { return "profile.cell.changepassword.title" }
}
internal enum Currentheight {
/// Current height
internal static var title: String { return Localizable.tr("Waves", "profile.cell.currentheight.title") }
internal static var titleKey: String { return "profile.cell.currentheight.title" }
}
internal enum Feedback {
/// Feedback
internal static var title: String { return Localizable.tr("Waves", "profile.cell.feedback.title") }
internal static var titleKey: String { return "profile.cell.feedback.title" }
}
internal enum Info {
internal enum Currentheight {
/// Current height
internal static var title: String { return Localizable.tr("Waves", "profile.cell.info.currentheight.title") }
internal static var titleKey: String { return "profile.cell.info.currentheight.title" }
}
internal enum Version {
/// Version
internal static var title: String { return Localizable.tr("Waves", "profile.cell.info.version.title") }
internal static var titleKey: String { return "profile.cell.info.version.title" }
}
}
internal enum Language {
/// Language
internal static var title: String { return Localizable.tr("Waves", "profile.cell.language.title") }
internal static var titleKey: String { return "profile.cell.language.title" }
}
internal enum Network {
/// Network
internal static var title: String { return Localizable.tr("Waves", "profile.cell.network.title") }
internal static var titleKey: String { return "profile.cell.network.title" }
}
internal enum Pushnotifications {
/// Push Notifications
internal static var title: String { return Localizable.tr("Waves", "profile.cell.pushnotifications.title") }
internal static var titleKey: String { return "profile.cell.pushnotifications.title" }
}
internal enum Rateapp {
/// Rate app
internal static var title: String { return Localizable.tr("Waves", "profile.cell.rateApp.title") }
internal static var titleKey: String { return "profile.cell.rateApp.title" }
}
internal enum Supportwavesplatform {
/// Support Wavesplatform
internal static var title: String { return Localizable.tr("Waves", "profile.cell.supportwavesplatform.title") }
internal static var titleKey: String { return "profile.cell.supportwavesplatform.title" }
}
}
internal enum Header {
internal enum General {
/// General settings
internal static var title: String { return Localizable.tr("Waves", "profile.header.general.title") }
internal static var titleKey: String { return "profile.header.general.title" }
}
internal enum Other {
/// Other
internal static var title: String { return Localizable.tr("Waves", "profile.header.other.title") }
internal static var titleKey: String { return "profile.header.other.title" }
}
internal enum Security {
/// Security
internal static var title: String { return Localizable.tr("Waves", "profile.header.security.title") }
internal static var titleKey: String { return "profile.header.security.title" }
}
}
internal enum Language {
internal enum Navigation {
/// Language
internal static var title: String { return Localizable.tr("Waves", "profile.language.navigation.title") }
internal static var titleKey: String { return "profile.language.navigation.title" }
}
}
internal enum Navigation {
/// Profile
internal static var title: String { return Localizable.tr("Waves", "profile.navigation.title") }
internal static var titleKey: String { return "profile.navigation.title" }
}
}
internal enum Receive {
internal enum Button {
/// Card
internal static var card: String { return Localizable.tr("Waves", "receive.button.card") }
internal static var cardKey: String { return "receive.button.card" }
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "receive.button.continue") }
internal static var continueKey: String { return "receive.button.continue" }
/// Сryptocurrency
internal static var cryptocurrency: String { return Localizable.tr("Waves", "receive.button.cryptocurrency") }
internal static var cryptocurrencyKey: String { return "receive.button.cryptocurrency" }
/// Invoice
internal static var invoice: String { return Localizable.tr("Waves", "receive.button.invoice") }
internal static var invoiceKey: String { return "receive.button.invoice" }
/// Use total balance
internal static var useTotalBalance: String { return Localizable.tr("Waves", "receive.button.useTotalBalance") }
internal static var useTotalBalanceKey: String { return "receive.button.useTotalBalance" }
}
internal enum Error {
/// Service is temporarily unavailable
internal static var serviceUnavailable: String { return Localizable.tr("Waves", "receive.error.serviceUnavailable") }
internal static var serviceUnavailableKey: String { return "receive.error.serviceUnavailable" }
}
internal enum Label {
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "receive.label.amount") }
internal static var amountKey: String { return "receive.label.amount" }
/// Amount in
internal static var amountIn: String { return Localizable.tr("Waves", "receive.label.amountIn") }
internal static var amountInKey: String { return "receive.label.amountIn" }
/// Token
internal static var asset: String { return Localizable.tr("Waves", "receive.label.asset") }
internal static var assetKey: String { return "receive.label.asset" }
/// Receive
internal static var receive: String { return Localizable.tr("Waves", "receive.label.receive") }
internal static var receiveKey: String { return "receive.label.receive" }
/// Select your token
internal static var selectYourAsset: String { return Localizable.tr("Waves", "receive.label.selectYourAsset") }
internal static var selectYourAssetKey: String { return "receive.label.selectYourAsset" }
}
}
internal enum Receiveaddress {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "receiveaddress.button.cancel") }
internal static var cancelKey: String { return "receiveaddress.button.cancel" }
/// Close
internal static var close: String { return Localizable.tr("Waves", "receiveaddress.button.close") }
internal static var closeKey: String { return "receiveaddress.button.close" }
/// Сopied!
internal static var copied: String { return Localizable.tr("Waves", "receiveaddress.button.copied") }
internal static var copiedKey: String { return "receiveaddress.button.copied" }
/// Copy
internal static var copy: String { return Localizable.tr("Waves", "receiveaddress.button.copy") }
internal static var copyKey: String { return "receiveaddress.button.copy" }
/// Share
internal static var share: String { return Localizable.tr("Waves", "receiveaddress.button.share") }
internal static var shareKey: String { return "receiveaddress.button.share" }
}
internal enum Label {
/// Link to an Invoice
internal static var linkToInvoice: String { return Localizable.tr("Waves", "receiveaddress.label.linkToInvoice") }
internal static var linkToInvoiceKey: String { return "receiveaddress.label.linkToInvoice" }
/// Your %@ address
internal static func yourAddress(_ p1: String) -> String {
return Localizable.tr("Waves", "receiveaddress.label.yourAddress", p1)
}
/// Your QR Code
internal static var yourQRCode: String { return Localizable.tr("Waves", "receiveaddress.label.yourQRCode") }
internal static var yourQRCodeKey: String { return "receiveaddress.label.yourQRCode" }
}
}
internal enum Receivecard {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "receivecard.button.cancel") }
internal static var cancelKey: String { return "receivecard.button.cancel" }
}
internal enum Label {
/// Change currency
internal static var changeCurrency: String { return Localizable.tr("Waves", "receivecard.label.changeCurrency") }
internal static var changeCurrencyKey: String { return "receivecard.label.changeCurrency" }
/// The minimum is %@, the maximum is %@
internal static func minimunAmountInfo(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "Receivecard.Label.minimunAmountInfo", p1, p2)
}
/// For making a payment from your card you will be redirected to the merchant's website
internal static var warningInfo: String { return Localizable.tr("Waves", "receivecard.label.warningInfo") }
internal static var warningInfoKey: String { return "receivecard.label.warningInfo" }
}
}
internal enum Receivecardcomplete {
internal enum Button {
/// Okay
internal static var okay: String { return Localizable.tr("Waves", "receivecardcomplete.button.okay") }
internal static var okayKey: String { return "receivecardcomplete.button.okay" }
}
internal enum Label {
/// After payment has been made your balance will be updated
internal static var afterPaymentUpdateBalance: String { return Localizable.tr("Waves", "receivecardcomplete.label.afterPaymentUpdateBalance") }
internal static var afterPaymentUpdateBalanceKey: String { return "receivecardcomplete.label.afterPaymentUpdateBalance" }
/// You have been redirected to «Indacoin»
internal static var redirectToIndacoin: String { return Localizable.tr("Waves", "receivecardcomplete.label.redirectToIndacoin") }
internal static var redirectToIndacoinKey: String { return "receivecardcomplete.label.redirectToIndacoin" }
}
}
internal enum Receivecryptocurrency {
internal enum Label {
/// The minimum amount of deposit is %@
internal static func minumumAmountOfDeposit(_ p1: String) -> String {
return Localizable.tr("Waves", "receivecryptocurrency.label.minumumAmountOfDeposit", p1)
}
/// Send only %@ to this deposit address
internal static func sendOnlyOnThisDeposit(_ p1: String) -> String {
return Localizable.tr("Waves", "receivecryptocurrency.label.sendOnlyOnThisDeposit", p1)
}
/// If you will send less than %@, you will lose that money.
internal static func warningMinimumAmountOfDeposit(_ p1: String) -> String {
return Localizable.tr("Waves", "receivecryptocurrency.label.warningMinimumAmountOfDeposit", p1)
}
/// Sending any other currency to this address may result in the loss of your deposit.
internal static var warningSendOnlyOnThisDeposit: String { return Localizable.tr("Waves", "receivecryptocurrency.label.warningSendOnlyOnThisDeposit") }
internal static var warningSendOnlyOnThisDepositKey: String { return "receivecryptocurrency.label.warningSendOnlyOnThisDeposit" }
internal enum Warningsmartcontracts {
/// Check if you wallet or exchange users smart-contracts to withdraw %@. We do not accept such transactions and can’t refund them. You will lose that money.
internal static func subtitle(_ p1: String) -> String {
return Localizable.tr("Waves", "receivecryptocurrency.label.warningSmartContracts.subtitle", p1)
}
/// Please do not deposit %@ form smart contracts! Do not deposit ERC20 tokens! Only %@ is allowed.
internal static func title(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "receivecryptocurrency.label.warningSmartContracts.title", p1, p2)
}
}
}
}
internal enum Receivegenerate {
internal enum Label {
/// Generate…
internal static var generate: String { return Localizable.tr("Waves", "receivegenerate.label.generate") }
internal static var generateKey: String { return "receivegenerate.label.generate" }
/// Your %@ address
internal static func yourAddress(_ p1: String) -> String {
return Localizable.tr("Waves", "receivegenerate.label.yourAddress", p1)
}
}
}
internal enum Receiveinvoice {
internal enum Label {
/// US Dollar
internal static var dollar: String { return Localizable.tr("Waves", "receiveinvoice.label.dollar") }
internal static var dollarKey: String { return "receiveinvoice.label.dollar" }
}
}
internal enum Scannerqrcode {
internal enum Label {
/// Scan QR
internal static var scan: String { return Localizable.tr("Waves", "scannerqrcode.label.scan") }
internal static var scanKey: String { return "scannerqrcode.label.scan" }
}
}
internal enum Send {
internal enum Button {
/// Choose from Address book
internal static var chooseFromAddressBook: String { return Localizable.tr("Waves", "send.button.chooseFromAddressBook") }
internal static var chooseFromAddressBookKey: String { return "send.button.chooseFromAddressBook" }
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "send.button.continue") }
internal static var continueKey: String { return "send.button.continue" }
/// Use total balance
internal static var useTotalBalanace: String { return Localizable.tr("Waves", "send.button.useTotalBalanace") }
internal static var useTotalBalanaceKey: String { return "send.button.useTotalBalanace" }
}
internal enum Label {
/// The address is not valid
internal static var addressNotValid: String { return Localizable.tr("Waves", "send.label.addressNotValid") }
internal static var addressNotValidKey: String { return "send.label.addressNotValid" }
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "send.label.amount") }
internal static var amountKey: String { return "send.label.amount" }
/// US Dollar
internal static var dollar: String { return Localizable.tr("Waves", "send.label.dollar") }
internal static var dollarKey: String { return "send.label.dollar" }
/// Gateway fee is
internal static var gatewayFee: String { return Localizable.tr("Waves", "send.label.gatewayFee") }
internal static var gatewayFeeKey: String { return "send.label.gatewayFee" }
/// Monero Payment ID
internal static var moneroPaymentId: String { return Localizable.tr("Waves", "send.label.moneroPaymentId") }
internal static var moneroPaymentIdKey: String { return "send.label.moneroPaymentId" }
/// Recipient
internal static var recipient: String { return Localizable.tr("Waves", "send.label.recipient") }
internal static var recipientKey: String { return "send.label.recipient" }
/// Recipient address…
internal static var recipientAddress: String { return Localizable.tr("Waves", "send.label.recipientAddress") }
internal static var recipientAddressKey: String { return "send.label.recipientAddress" }
/// Send
internal static var send: String { return Localizable.tr("Waves", "send.label.send") }
internal static var sendKey: String { return "send.label.send" }
internal enum Error {
/// The token is not valid
internal static var assetIsNotValid: String { return Localizable.tr("Waves", "send.label.error.assetIsNotValid") }
internal static var assetIsNotValidKey: String { return "send.label.error.assetIsNotValid" }
/// Insufficient funds
internal static var insufficientFunds: String { return Localizable.tr("Waves", "send.label.error.insufficientFunds") }
internal static var insufficientFundsKey: String { return "send.label.error.insufficientFunds" }
/// invalid ID
internal static var invalidId: String { return Localizable.tr("Waves", "send.label.error.invalidId") }
internal static var invalidIdKey: String { return "send.label.error.invalidId" }
/// Maximum %@ %@
internal static func maximum(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "send.label.error.maximum", p1, p2)
}
/// Minimum %@ %@
internal static func minimun(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "send.label.error.minimun", p1, p2)
}
/// You don't have enough funds to pay the required fees.
internal static var notFundsFee: String { return Localizable.tr("Waves", "send.label.error.notFundsFee") }
internal static var notFundsFeeKey: String { return "send.label.error.notFundsFee" }
/// You don't have enough funds to pay the required fees. You must pay %@ transaction fee and %@ gateway fee.
internal static func notFundsFeeGateway(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "Send.Label.Error.notFundsFeeGateway", p1, p2)
}
/// Sending funds to suspicious token is not possible
internal static var sendingToSpamAsset: String { return Localizable.tr("Waves", "send.label.error.sendingToSpamAsset") }
internal static var sendingToSpamAssetKey: String { return "send.label.error.sendingToSpamAsset" }
}
internal enum Warning {
/// Do not withdraw %@ to an ICO. We will not credit your account with tokens from that sale.
internal static func description(_ p1: String) -> String {
return Localizable.tr("Waves", "Send.Label.Warning.description", p1)
}
/// We detected %@ address and will send your money through Coinomat gateway to that address. Minimum amount is %@, maximum amount is %@.
internal static func subtitle(_ p1: String, _ p2: String, _ p3: String) -> String {
return Localizable.tr("Waves", "Send.Label.Warning.subtitle", p1, p2, p3)
}
}
}
internal enum Textfield {
/// Paste or type your Payment ID
internal static var placeholderPaymentId: String { return Localizable.tr("Waves", "send.textField.placeholderPaymentId") }
internal static var placeholderPaymentIdKey: String { return "send.textField.placeholderPaymentId" }
}
}
internal enum Sendcomplete {
internal enum Button {
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "sendcomplete.button.okey") }
internal static var okeyKey: String { return "sendcomplete.button.okey" }
}
internal enum Label {
/// Do you want to save this address?
internal static var saveThisAddress: String { return Localizable.tr("Waves", "sendcomplete.label.saveThisAddress") }
internal static var saveThisAddressKey: String { return "sendcomplete.label.saveThisAddress" }
/// Your transaction is on the way!
internal static var transactionIsOnWay: String { return Localizable.tr("Waves", "sendcomplete.label.transactionIsOnWay") }
internal static var transactionIsOnWayKey: String { return "sendcomplete.label.transactionIsOnWay" }
/// You have sent
internal static var youHaveSent: String { return Localizable.tr("Waves", "sendcomplete.label.youHaveSent") }
internal static var youHaveSentKey: String { return "sendcomplete.label.youHaveSent" }
}
}
internal enum Sendconfirmation {
internal enum Button {
/// Confirm
internal static var confim: String { return Localizable.tr("Waves", "sendconfirmation.button.confim") }
internal static var confimKey: String { return "sendconfirmation.button.confim" }
}
internal enum Label {
/// Confirmation
internal static var confirmation: String { return Localizable.tr("Waves", "sendconfirmation.label.confirmation") }
internal static var confirmationKey: String { return "sendconfirmation.label.confirmation" }
/// Description
internal static var description: String { return Localizable.tr("Waves", "sendconfirmation.label.description") }
internal static var descriptionKey: String { return "sendconfirmation.label.description" }
/// The description is too long
internal static var descriptionIsTooLong: String { return Localizable.tr("Waves", "sendconfirmation.label.descriptionIsTooLong") }
internal static var descriptionIsTooLongKey: String { return "sendconfirmation.label.descriptionIsTooLong" }
/// US Dollar
internal static var dollar: String { return Localizable.tr("Waves", "sendconfirmation.label.dollar") }
internal static var dollarKey: String { return "sendconfirmation.label.dollar" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "sendconfirmation.label.fee") }
internal static var feeKey: String { return "sendconfirmation.label.fee" }
/// Write an optional message
internal static var optionalMessage: String { return Localizable.tr("Waves", "sendconfirmation.label.optionalMessage") }
internal static var optionalMessageKey: String { return "sendconfirmation.label.optionalMessage" }
/// Sent to
internal static var sentTo: String { return Localizable.tr("Waves", "sendconfirmation.label.sentTo") }
internal static var sentToKey: String { return "sendconfirmation.label.sentTo" }
}
}
internal enum Sendfee {
internal enum Label {
/// Not available
internal static var notAvailable: String { return Localizable.tr("Waves", "sendfee.label.notAvailable") }
internal static var notAvailableKey: String { return "sendfee.label.notAvailable" }
/// Transaction Fee
internal static var transactionFee: String { return Localizable.tr("Waves", "sendfee.label.transactionFee") }
internal static var transactionFeeKey: String { return "sendfee.label.transactionFee" }
}
}
internal enum Sendloading {
internal enum Label {
/// Sending…
internal static var sending: String { return Localizable.tr("Waves", "sendloading.label.sending") }
internal static var sendingKey: String { return "sendloading.label.sending" }
}
}
internal enum Serverdisconnect {
internal enum Label {
/// Check your connection to the mobile Internet or Wi-Fi network
internal static var subtitle: String { return Localizable.tr("Waves", "serverDisconnect.label.subtitle") }
internal static var subtitleKey: String { return "serverDisconnect.label.subtitle" }
/// No connection to the Internet
internal static var title: String { return Localizable.tr("Waves", "serverDisconnect.label.title") }
internal static var titleKey: String { return "serverDisconnect.label.title" }
}
}
internal enum Serverengineering {
internal enum Label {
/// Hi, at the moment we are doing a very important job of improving the application
internal static var subtitle: String { return Localizable.tr("Waves", "serverEngineering.label.subtitle") }
internal static var subtitleKey: String { return "serverEngineering.label.subtitle" }
/// Engineering works
internal static var title: String { return Localizable.tr("Waves", "serverEngineering.label.title") }
internal static var titleKey: String { return "serverEngineering.label.title" }
}
}
internal enum Servererror {
internal enum Button {
/// Retry
internal static var retry: String { return Localizable.tr("Waves", "serverError.button.retry") }
internal static var retryKey: String { return "serverError.button.retry" }
/// Send a report
internal static var sendReport: String { return Localizable.tr("Waves", "serverError.button.sendReport") }
internal static var sendReportKey: String { return "serverError.button.sendReport" }
}
internal enum Label {
/// Oh… It's all broken!
internal static var allBroken: String { return Localizable.tr("Waves", "serverError.label.allBroken") }
internal static var allBrokenKey: String { return "serverError.label.allBroken" }
/// Do not worry, we are already fixing this problem.\nSoon everything will work!
internal static var allBrokenDescription: String { return Localizable.tr("Waves", "serverError.label.allBrokenDescription") }
internal static var allBrokenDescriptionKey: String { return "serverError.label.allBrokenDescription" }
/// No connection to the Internet
internal static var noInternetConnection: String { return Localizable.tr("Waves", "serverError.label.noInternetConnection") }
internal static var noInternetConnectionKey: String { return "serverError.label.noInternetConnection" }
/// Check your connection to the mobile Internet or Wi-Fi network
internal static var noInternetConnectionDescription: String { return Localizable.tr("Waves", "serverError.label.noInternetConnectionDescription") }
internal static var noInternetConnectionDescriptionKey: String { return "serverError.label.noInternetConnectionDescription" }
/// Do not worry, we are already fixing this problem.\nSoon everything will work!
internal static var subtitle: String { return Localizable.tr("Waves", "serverError.label.subtitle") }
internal static var subtitleKey: String { return "serverError.label.subtitle" }
/// Oh… It's all broken!
internal static var title: String { return Localizable.tr("Waves", "serverError.label.title") }
internal static var titleKey: String { return "serverError.label.title" }
}
}
internal enum Startleasing {
internal enum Button {
/// Choose from Address book
internal static var chooseFromAddressBook: String { return Localizable.tr("Waves", "startleasing.button.chooseFromAddressBook") }
internal static var chooseFromAddressBookKey: String { return "startleasing.button.chooseFromAddressBook" }
/// Start Lease
internal static var startLease: String { return Localizable.tr("Waves", "startleasing.button.startLease") }
internal static var startLeaseKey: String { return "startleasing.button.startLease" }
/// Use total balance
internal static var useTotalBalanace: String { return Localizable.tr("Waves", "startleasing.button.useTotalBalanace") }
internal static var useTotalBalanaceKey: String { return "startleasing.button.useTotalBalanace" }
/// Use total balance
internal static var useTotalBalance: String { return Localizable.tr("Waves", "startleasing.button.useTotalBalance") }
internal static var useTotalBalanceKey: String { return "startleasing.button.useTotalBalance" }
}
internal enum Label {
/// Address is not valid
internal static var addressIsNotValid: String { return Localizable.tr("Waves", "startleasing.label.addressIsNotValid") }
internal static var addressIsNotValidKey: String { return "startleasing.label.addressIsNotValid" }
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "startleasing.label.amount") }
internal static var amountKey: String { return "startleasing.label.amount" }
/// Balance
internal static var balance: String { return Localizable.tr("Waves", "startleasing.label.balance") }
internal static var balanceKey: String { return "startleasing.label.balance" }
/// Generator
internal static var generator: String { return Localizable.tr("Waves", "startleasing.label.generator") }
internal static var generatorKey: String { return "startleasing.label.generator" }
/// Insufficient funds
internal static var insufficientFunds: String { return Localizable.tr("Waves", "startleasing.label.insufficientFunds") }
internal static var insufficientFundsKey: String { return "startleasing.label.insufficientFunds" }
/// Node address…
internal static var nodeAddress: String { return Localizable.tr("Waves", "startleasing.label.nodeAddress") }
internal static var nodeAddressKey: String { return "startleasing.label.nodeAddress" }
/// Not enough
internal static var notEnough: String { return Localizable.tr("Waves", "startleasing.label.notEnough") }
internal static var notEnoughKey: String { return "startleasing.label.notEnough" }
/// Start leasing
internal static var startLeasing: String { return Localizable.tr("Waves", "startleasing.label.startLeasing") }
internal static var startLeasingKey: String { return "startleasing.label.startLeasing" }
}
}
internal enum Startleasingcomplete {
internal enum Button {
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "startleasingcomplete.button.okey") }
internal static var okeyKey: String { return "startleasingcomplete.button.okey" }
}
internal enum Label {
/// You have canceled a leasing transaction
internal static var youHaveCanceledTransaction: String { return Localizable.tr("Waves", "startleasingcomplete.label.youHaveCanceledTransaction") }
internal static var youHaveCanceledTransactionKey: String { return "startleasingcomplete.label.youHaveCanceledTransaction" }
/// You have leased %@ %@
internal static func youHaveLeased(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "startleasingcomplete.label.youHaveLeased", p1, p2)
}
/// Your transaction is on the way!
internal static var yourTransactionIsOnWay: String { return Localizable.tr("Waves", "startleasingcomplete.label.yourTransactionIsOnWay") }
internal static var yourTransactionIsOnWayKey: String { return "startleasingcomplete.label.yourTransactionIsOnWay" }
}
}
internal enum Startleasingconfirmation {
internal enum Button {
/// Cancel leasing
internal static var cancelLeasing: String { return Localizable.tr("Waves", "startleasingconfirmation.button.cancelLeasing") }
internal static var cancelLeasingKey: String { return "startleasingconfirmation.button.cancelLeasing" }
/// Confirm
internal static var confirm: String { return Localizable.tr("Waves", "startleasingconfirmation.button.confirm") }
internal static var confirmKey: String { return "startleasingconfirmation.button.confirm" }
}
internal enum Label {
/// Confirmation
internal static var confirmation: String { return Localizable.tr("Waves", "startleasingconfirmation.label.confirmation") }
internal static var confirmationKey: String { return "startleasingconfirmation.label.confirmation" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "startleasingconfirmation.label.fee") }
internal static var feeKey: String { return "startleasingconfirmation.label.fee" }
/// Leasing TX
internal static var leasingTX: String { return Localizable.tr("Waves", "startleasingconfirmation.label.leasingTX") }
internal static var leasingTXKey: String { return "startleasingconfirmation.label.leasingTX" }
/// Node address
internal static var nodeAddress: String { return Localizable.tr("Waves", "startleasingconfirmation.label.nodeAddress") }
internal static var nodeAddressKey: String { return "startleasingconfirmation.label.nodeAddress" }
/// TXID
internal static var txid: String { return Localizable.tr("Waves", "startleasingconfirmation.label.TXID") }
internal static var txidKey: String { return "startleasingconfirmation.label.TXID" }
}
}
internal enum Startleasingloading {
internal enum Label {
/// Cancel leasing…
internal static var cancelLeasing: String { return Localizable.tr("Waves", "startleasingloading.label.cancelLeasing") }
internal static var cancelLeasingKey: String { return "startleasingloading.label.cancelLeasing" }
/// Start leasing…
internal static var startLeasing: String { return Localizable.tr("Waves", "startleasingloading.label.startLeasing") }
internal static var startLeasingKey: String { return "startleasingloading.label.startLeasing" }
}
}
internal enum Tokenburn {
internal enum Button {
/// Burn
internal static var burn: String { return Localizable.tr("Waves", "tokenBurn.button.burn") }
internal static var burnKey: String { return "tokenBurn.button.burn" }
/// Continue
internal static var `continue`: String { return Localizable.tr("Waves", "tokenBurn.button.continue") }
internal static var continueKey: String { return "tokenBurn.button.continue" }
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "tokenBurn.button.okey") }
internal static var okeyKey: String { return "tokenBurn.button.okey" }
/// Use total balance
internal static var useTotalBalanace: String { return Localizable.tr("Waves", "tokenBurn.button.useTotalBalanace") }
internal static var useTotalBalanaceKey: String { return "tokenBurn.button.useTotalBalanace" }
}
internal enum Label {
/// Confirmation
internal static var confirmation: String { return Localizable.tr("Waves", "tokenBurn.label.confirmation") }
internal static var confirmationKey: String { return "tokenBurn.label.confirmation" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "tokenBurn.label.fee") }
internal static var feeKey: String { return "tokenBurn.label.fee" }
/// ID
internal static var id: String { return Localizable.tr("Waves", "tokenBurn.label.id") }
internal static var idKey: String { return "tokenBurn.label.id" }
/// Burn…
internal static var loading: String { return Localizable.tr("Waves", "tokenBurn.label.loading") }
internal static var loadingKey: String { return "tokenBurn.label.loading" }
/// Not reissuable
internal static var notReissuable: String { return Localizable.tr("Waves", "tokenBurn.label.notReissuable") }
internal static var notReissuableKey: String { return "tokenBurn.label.notReissuable" }
/// Quantity of tokens to be burned
internal static var quantityTokensBurned: String { return Localizable.tr("Waves", "tokenBurn.label.quantityTokensBurned") }
internal static var quantityTokensBurnedKey: String { return "tokenBurn.label.quantityTokensBurned" }
/// Reissuable
internal static var reissuable: String { return Localizable.tr("Waves", "tokenBurn.label.reissuable") }
internal static var reissuableKey: String { return "tokenBurn.label.reissuable" }
/// Token Burn
internal static var tokenBurn: String { return Localizable.tr("Waves", "tokenBurn.label.tokenBurn") }
internal static var tokenBurnKey: String { return "tokenBurn.label.tokenBurn" }
/// Your transaction is on the way!
internal static var transactionIsOnWay: String { return Localizable.tr("Waves", "tokenBurn.label.transactionIsOnWay") }
internal static var transactionIsOnWayKey: String { return "tokenBurn.label.transactionIsOnWay" }
/// Type
internal static var type: String { return Localizable.tr("Waves", "tokenBurn.label.type") }
internal static var typeKey: String { return "tokenBurn.label.type" }
/// You have burned
internal static var youHaveBurned: String { return Localizable.tr("Waves", "tokenBurn.label.youHaveBurned") }
internal static var youHaveBurnedKey: String { return "tokenBurn.label.youHaveBurned" }
internal enum Error {
/// Insufficient funds
internal static var insufficientFunds: String { return Localizable.tr("Waves", "tokenBurn.label.error.insufficientFunds") }
internal static var insufficientFundsKey: String { return "tokenBurn.label.error.insufficientFunds" }
/// You don't have enough funds to pay the required fees.
internal static var notFundsFee: String { return Localizable.tr("Waves", "tokenBurn.label.error.notFundsFee") }
internal static var notFundsFeeKey: String { return "tokenBurn.label.error.notFundsFee" }
}
}
}
internal enum Transaction {
internal enum Error {
internal enum Commission {
/// Commission receiving error
internal static var receiving: String { return Localizable.tr("Waves", "transaction.error.commission.receiving") }
internal static var receivingKey: String { return "transaction.error.commission.receiving" }
}
}
}
internal enum Transactioncard {
internal enum Timestamp {
/// dd.MM.yyyy HH:mm
internal static var format: String { return Localizable.tr("Waves", "transactioncard.timestamp.format") }
internal static var formatKey: String { return "transactioncard.timestamp.format" }
}
internal enum Title {
/// Active Now
internal static var activeNow: String { return Localizable.tr("Waves", "transactioncard.title.activeNow") }
internal static var activeNowKey: String { return "transactioncard.title.activeNow" }
/// Amount
internal static var amount: String { return Localizable.tr("Waves", "transactioncard.title.amount") }
internal static var amountKey: String { return "transactioncard.title.amount" }
/// Amount per transaction
internal static var amountPerTransaction: String { return Localizable.tr("Waves", "transactioncard.title.amountPerTransaction") }
internal static var amountPerTransactionKey: String { return "transactioncard.title.amountPerTransaction" }
/// Token
internal static var asset: String { return Localizable.tr("Waves", "transactioncard.title.asset") }
internal static var assetKey: String { return "transactioncard.title.asset" }
/// Token ID
internal static var assetId: String { return Localizable.tr("Waves", "transactioncard.title.assetId") }
internal static var assetIdKey: String { return "transactioncard.title.assetId" }
/// Block
internal static var block: String { return Localizable.tr("Waves", "transactioncard.title.block") }
internal static var blockKey: String { return "transactioncard.title.block" }
/// Canceled Leasing
internal static var canceledLeasing: String { return Localizable.tr("Waves", "transactioncard.title.canceledLeasing") }
internal static var canceledLeasingKey: String { return "transactioncard.title.canceledLeasing" }
/// Cancel Leasing
internal static var cancelLeasing: String { return Localizable.tr("Waves", "transactioncard.title.cancelLeasing") }
internal static var cancelLeasingKey: String { return "transactioncard.title.cancelLeasing" }
/// (Cancelled)
internal static var cancelled: String { return Localizable.tr("Waves", "transactioncard.title.cancelled") }
internal static var cancelledKey: String { return "transactioncard.title.cancelled" }
/// Cancel order
internal static var cancelOrder: String { return Localizable.tr("Waves", "transactioncard.title.cancelOrder") }
internal static var cancelOrderKey: String { return "transactioncard.title.cancelOrder" }
/// Cancel Script
internal static var cancelScriptTransaction: String { return Localizable.tr("Waves", "transactioncard.title.cancelScriptTransaction") }
internal static var cancelScriptTransactionKey: String { return "transactioncard.title.cancelScriptTransaction" }
/// COMPLETED
internal static var completed: String { return Localizable.tr("Waves", "transactioncard.title.completed") }
internal static var completedKey: String { return "transactioncard.title.completed" }
/// Confirmations
internal static var confirmations: String { return Localizable.tr("Waves", "transactioncard.title.confirmations") }
internal static var confirmationsKey: String { return "transactioncard.title.confirmations" }
/// Copied
internal static var copied: String { return Localizable.tr("Waves", "transactioncard.title.copied") }
internal static var copiedKey: String { return "transactioncard.title.copied" }
/// Copy all data
internal static var copyAllData: String { return Localizable.tr("Waves", "transactioncard.title.copyAllData") }
internal static var copyAllDataKey: String { return "transactioncard.title.copyAllData" }
/// Copy TX ID
internal static var copyTXID: String { return Localizable.tr("Waves", "transactioncard.title.copyTXID") }
internal static var copyTXIDKey: String { return "transactioncard.title.copyTXID" }
/// Create Alias
internal static var createAlias: String { return Localizable.tr("Waves", "transactioncard.title.createAlias") }
internal static var createAliasKey: String { return "transactioncard.title.createAlias" }
/// Data Transaction
internal static var dataTransaction: String { return Localizable.tr("Waves", "transactioncard.title.dataTransaction") }
internal static var dataTransactionKey: String { return "transactioncard.title.dataTransaction" }
/// Description
internal static var description: String { return Localizable.tr("Waves", "transactioncard.title.description") }
internal static var descriptionKey: String { return "transactioncard.title.description" }
/// Disable Sponsorship
internal static var disableSponsorship: String { return Localizable.tr("Waves", "transactioncard.title.disableSponsorship") }
internal static var disableSponsorshipKey: String { return "transactioncard.title.disableSponsorship" }
/// Entry in blockchain
internal static var entryInBlockchain: String { return Localizable.tr("Waves", "transactioncard.title.entryInBlockchain") }
internal static var entryInBlockchainKey: String { return "transactioncard.title.entryInBlockchain" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "transactioncard.title.fee") }
internal static var feeKey: String { return "transactioncard.title.fee" }
/// Filled
internal static var filled: String { return Localizable.tr("Waves", "transactioncard.title.filled") }
internal static var filledKey: String { return "transactioncard.title.filled" }
/// From
internal static var from: String { return Localizable.tr("Waves", "transactioncard.title.from") }
internal static var fromKey: String { return "transactioncard.title.from" }
/// Incoming Leasing
internal static var incomingLeasing: String { return Localizable.tr("Waves", "transactioncard.title.incomingLeasing") }
internal static var incomingLeasingKey: String { return "transactioncard.title.incomingLeasing" }
/// Leasing from
internal static var leasingFrom: String { return Localizable.tr("Waves", "transactioncard.title.leasingFrom") }
internal static var leasingFromKey: String { return "transactioncard.title.leasingFrom" }
/// Mass Received
internal static var massReceived: String { return Localizable.tr("Waves", "transactioncard.title.massReceived") }
internal static var massReceivedKey: String { return "transactioncard.title.massReceived" }
/// Mass Sent
internal static var massSent: String { return Localizable.tr("Waves", "transactioncard.title.massSent") }
internal static var massSentKey: String { return "transactioncard.title.massSent" }
/// Node address
internal static var nodeAddress: String { return Localizable.tr("Waves", "transactioncard.title.nodeAddress") }
internal static var nodeAddressKey: String { return "transactioncard.title.nodeAddress" }
/// Not Reissuable
internal static var notReissuable: String { return Localizable.tr("Waves", "transactioncard.title.notReissuable") }
internal static var notReissuableKey: String { return "transactioncard.title.notReissuable" }
/// Payment
internal static var payment: String { return Localizable.tr("Waves", "transactioncard.title.payment") }
internal static var paymentKey: String { return "transactioncard.title.payment" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "transactioncard.title.price") }
internal static var priceKey: String { return "transactioncard.title.price" }
/// Received
internal static var received: String { return Localizable.tr("Waves", "transactioncard.title.received") }
internal static var receivedKey: String { return "transactioncard.title.received" }
/// Received from
internal static var receivedFrom: String { return Localizable.tr("Waves", "transactioncard.title.receivedFrom") }
internal static var receivedFromKey: String { return "transactioncard.title.receivedFrom" }
/// Received Sponsorship
internal static var receivedSponsorship: String { return Localizable.tr("Waves", "transactioncard.title.receivedSponsorship") }
internal static var receivedSponsorshipKey: String { return "transactioncard.title.receivedSponsorship" }
/// #%@ Recipient
internal static func recipient(_ p1: String) -> String {
return Localizable.tr("Waves", "transactioncard.title.recipient", p1)
}
/// Reissuable
internal static var reissuable: String { return Localizable.tr("Waves", "transactioncard.title.reissuable") }
internal static var reissuableKey: String { return "transactioncard.title.reissuable" }
/// Script address
internal static var scriptAddress: String { return Localizable.tr("Waves", "transactioncard.title.scriptAddress") }
internal static var scriptAddressKey: String { return "transactioncard.title.scriptAddress" }
/// Script Invocation
internal static var scriptInvocation: String { return Localizable.tr("Waves", "transactioncard.title.scriptInvocation") }
internal static var scriptInvocationKey: String { return "transactioncard.title.scriptInvocation" }
/// Self-transfer
internal static var selfTransfer: String { return Localizable.tr("Waves", "transactioncard.title.selfTransfer") }
internal static var selfTransferKey: String { return "transactioncard.title.selfTransfer" }
/// Send again
internal static var sendAgain: String { return Localizable.tr("Waves", "transactioncard.title.sendAgain") }
internal static var sendAgainKey: String { return "transactioncard.title.sendAgain" }
/// Sent
internal static var sent: String { return Localizable.tr("Waves", "transactioncard.title.sent") }
internal static var sentKey: String { return "transactioncard.title.sent" }
/// Sent to
internal static var sentTo: String { return Localizable.tr("Waves", "transactioncard.title.sentTo") }
internal static var sentToKey: String { return "transactioncard.title.sentTo" }
/// Update Script
internal static var setAssetScript: String { return Localizable.tr("Waves", "transactioncard.title.setAssetScript") }
internal static var setAssetScriptKey: String { return "transactioncard.title.setAssetScript" }
/// Set Script
internal static var setScriptTransaction: String { return Localizable.tr("Waves", "transactioncard.title.setScriptTransaction") }
internal static var setScriptTransactionKey: String { return "transactioncard.title.setScriptTransaction" }
/// Set Sponsorship
internal static var setSponsorship: String { return Localizable.tr("Waves", "transactioncard.title.setSponsorship") }
internal static var setSponsorshipKey: String { return "transactioncard.title.setSponsorship" }
/// Show all (%@)
internal static func showAll(_ p1: String) -> String {
return Localizable.tr("Waves", "transactioncard.title.showAll", p1)
}
/// Suspicious received
internal static var spamReceived: String { return Localizable.tr("Waves", "transactioncard.title.spamReceived") }
internal static var spamReceivedKey: String { return "transactioncard.title.spamReceived" }
/// Started Leasing
internal static var startedLeasing: String { return Localizable.tr("Waves", "transactioncard.title.startedLeasing") }
internal static var startedLeasingKey: String { return "transactioncard.title.startedLeasing" }
/// Status
internal static var status: String { return Localizable.tr("Waves", "transactioncard.title.status") }
internal static var statusKey: String { return "transactioncard.title.status" }
/// Timestamp
internal static var timestamp: String { return Localizable.tr("Waves", "transactioncard.title.timestamp") }
internal static var timestampKey: String { return "transactioncard.title.timestamp" }
/// Token Burn
internal static var tokenBurn: String { return Localizable.tr("Waves", "transactioncard.title.tokenBurn") }
internal static var tokenBurnKey: String { return "transactioncard.title.tokenBurn" }
/// Token Generation
internal static var tokenGeneration: String { return Localizable.tr("Waves", "transactioncard.title.tokenGeneration") }
internal static var tokenGenerationKey: String { return "transactioncard.title.tokenGeneration" }
/// Token Reissue
internal static var tokenReissue: String { return Localizable.tr("Waves", "transactioncard.title.tokenReissue") }
internal static var tokenReissueKey: String { return "transactioncard.title.tokenReissue" }
/// Total
internal static var total: String { return Localizable.tr("Waves", "transactioncard.title.total") }
internal static var totalKey: String { return "transactioncard.title.total" }
/// Unconfirmed
internal static var unconfirmed: String { return Localizable.tr("Waves", "transactioncard.title.unconfirmed") }
internal static var unconfirmedKey: String { return "transactioncard.title.unconfirmed" }
/// Unrecognised Transaction
internal static var unrecognisedTransaction: String { return Localizable.tr("Waves", "transactioncard.title.unrecognisedTransaction") }
internal static var unrecognisedTransactionKey: String { return "transactioncard.title.unrecognisedTransaction" }
/// View on Explorer
internal static var viewOnExplorer: String { return Localizable.tr("Waves", "transactioncard.title.viewOnExplorer") }
internal static var viewOnExplorerKey: String { return "transactioncard.title.viewOnExplorer" }
internal enum Exchange {
/// Buy
internal static var buy: String { return Localizable.tr("Waves", "transactioncard.title.exchange.buy") }
internal static var buyKey: String { return "transactioncard.title.exchange.buy" }
/// Buy: %@/%@
internal static func buyPair(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "transactioncard.title.exchange.buyPair", p1, p2)
}
/// Sell
internal static var sell: String { return Localizable.tr("Waves", "transactioncard.title.exchange.sell") }
internal static var sellKey: String { return "transactioncard.title.exchange.sell" }
/// Sell: %@/%@
internal static func sellPair(_ p1: String, _ p2: String) -> String {
return Localizable.tr("Waves", "transactioncard.title.exchange.sellPair", p1, p2)
}
}
}
}
internal enum Transactionfee {
internal enum Label {
/// Transaction Fee
internal static var transactionFee: String { return Localizable.tr("Waves", "transactionFee.label.transactionFee") }
internal static var transactionFeeKey: String { return "transactionFee.label.transactionFee" }
}
}
internal enum Transactionhistory {
internal enum Cell {
/// Block
internal static var block: String { return Localizable.tr("Waves", "transactionhistory.cell.block") }
internal static var blockKey: String { return "transactionhistory.cell.block" }
/// Data Transaction
internal static var dataTransaction: String { return Localizable.tr("Waves", "transactionhistory.cell.dataTransaction") }
internal static var dataTransactionKey: String { return "transactionhistory.cell.dataTransaction" }
/// Fee
internal static var fee: String { return Localizable.tr("Waves", "transactionhistory.cell.fee") }
internal static var feeKey: String { return "transactionhistory.cell.fee" }
/// ID
internal static var id: String { return Localizable.tr("Waves", "transactionhistory.cell.id") }
internal static var idKey: String { return "transactionhistory.cell.id" }
/// Leasing to
internal static var leasingTo: String { return Localizable.tr("Waves", "transactionhistory.cell.leasingTo") }
internal static var leasingToKey: String { return "transactionhistory.cell.leasingTo" }
/// Price
internal static var price: String { return Localizable.tr("Waves", "transactionhistory.cell.price") }
internal static var priceKey: String { return "transactionhistory.cell.price" }
/// Recipient
internal static var recipient: String { return Localizable.tr("Waves", "transactionhistory.cell.recipient") }
internal static var recipientKey: String { return "transactionhistory.cell.recipient" }
/// Recipients
internal static var recipients: String { return Localizable.tr("Waves", "transactionhistory.cell.recipients") }
internal static var recipientsKey: String { return "transactionhistory.cell.recipients" }
/// Type
internal static var type: String { return Localizable.tr("Waves", "transactionhistory.cell.type") }
internal static var typeKey: String { return "transactionhistory.cell.type" }
internal enum Status {
/// at
internal static var at: String { return Localizable.tr("Waves", "transactionhistory.cell.status.at") }
internal static var atKey: String { return "transactionhistory.cell.status.at" }
}
}
internal enum Copy {
/// Date
internal static var date: String { return Localizable.tr("Waves", "transactionhistory.copy.date") }
internal static var dateKey: String { return "transactionhistory.copy.date" }
/// Recipient
internal static var recipient: String { return Localizable.tr("Waves", "transactionhistory.copy.recipient") }
internal static var recipientKey: String { return "transactionhistory.copy.recipient" }
/// Sender
internal static var sender: String { return Localizable.tr("Waves", "transactionhistory.copy.sender") }
internal static var senderKey: String { return "transactionhistory.copy.sender" }
/// Transaction ID
internal static var transactionId: String { return Localizable.tr("Waves", "transactionhistory.copy.transactionId") }
internal static var transactionIdKey: String { return "transactionhistory.copy.transactionId" }
/// Type
internal static var type: String { return Localizable.tr("Waves", "transactionhistory.copy.type") }
internal static var typeKey: String { return "transactionhistory.copy.type" }
}
}
internal enum Transactionscript {
internal enum Button {
/// Okay
internal static var okey: String { return Localizable.tr("Waves", "transactionScript.button.okey") }
internal static var okeyKey: String { return "transactionScript.button.okey" }
}
internal enum Label {
/// To work with a scripted account/token, use the Waves Client
internal static var subtitle: String { return Localizable.tr("Waves", "transactionScript.label.subtitle") }
internal static var subtitleKey: String { return "transactionScript.label.subtitle" }
/// A script is installed on your account or token
internal static var title: String { return Localizable.tr("Waves", "transactionScript.label.title") }
internal static var titleKey: String { return "transactionScript.label.title" }
}
}
internal enum Usetouchid {
internal enum Button {
internal enum Notnow {
/// Not now
internal static var text: String { return Localizable.tr("Waves", "usetouchid.button.notNow.text") }
internal static var textKey: String { return "usetouchid.button.notNow.text" }
}
internal enum Usebiometric {
/// Use %@
internal static func text(_ p1: String) -> String {
return Localizable.tr("Waves", "usetouchid.button.useBiometric.text", p1)
}
}
}
internal enum Label {
internal enum Detail {
/// Use your %@ for faster, easier access to your account
internal static func text(_ p1: String) -> String {
return Localizable.tr("Waves", "usetouchid.label.detail.text", p1)
}
}
internal enum Title {
/// Use %@ to sign in?
internal static func text(_ p1: String) -> String {
return Localizable.tr("Waves", "usetouchid.label.title.text", p1)
}
}
}
}
internal enum Wallet {
internal enum Button {
/// Start Lease
internal static var startLease: String { return Localizable.tr("Waves", "wallet.button.startLease") }
internal static var startLeaseKey: String { return "wallet.button.startLease" }
}
internal enum Clearassets {
internal enum Label {
/// We have redesigned the display of assets to allow you to keep your wallet clean and tidy. You can customise your asset list however you want!
internal static var subtitle: String { return Localizable.tr("Waves", "wallet.clearAssets.label.subtitle") }
internal static var subtitleKey: String { return "wallet.clearAssets.label.subtitle" }
/// No more mess!
internal static var title: String { return Localizable.tr("Waves", "wallet.clearAssets.label.title") }
internal static var titleKey: String { return "wallet.clearAssets.label.title" }
}
}
internal enum Label {
/// Available
internal static var available: String { return Localizable.tr("Waves", "wallet.label.available") }
internal static var availableKey: String { return "wallet.label.available" }
/// Leased
internal static var leased: String { return Localizable.tr("Waves", "wallet.label.leased") }
internal static var leasedKey: String { return "wallet.label.leased" }
/// Leased in
internal static var leasedIn: String { return Localizable.tr("Waves", "wallet.label.leasedIn") }
internal static var leasedInKey: String { return "wallet.label.leasedIn" }
/// My token
internal static var myAssets: String { return Localizable.tr("Waves", "wallet.label.myAssets") }
internal static var myAssetsKey: String { return "wallet.label.myAssets" }
/// Search
internal static var search: String { return Localizable.tr("Waves", "wallet.label.search") }
internal static var searchKey: String { return "wallet.label.search" }
/// Started Leasing
internal static var startedLeasing: String { return Localizable.tr("Waves", "wallet.label.startedLeasing") }
internal static var startedLeasingKey: String { return "wallet.label.startedLeasing" }
/// Total balance
internal static var totalBalance: String { return Localizable.tr("Waves", "wallet.label.totalBalance") }
internal static var totalBalanceKey: String { return "wallet.label.totalBalance" }
/// Transaction history
internal static var viewHistory: String { return Localizable.tr("Waves", "wallet.label.viewHistory") }
internal static var viewHistoryKey: String { return "wallet.label.viewHistory" }
internal enum Quicknote {
internal enum Description {
/// You can only transfer or trade WAVES that aren’t leased. The leased amount cannot be transferred or traded by you or anyone else.
internal static var first: String { return Localizable.tr("Waves", "wallet.label.quickNote.description.first") }
internal static var firstKey: String { return "wallet.label.quickNote.description.first" }
/// You can cancel a leasing transaction as soon as it appears in the blockchain which usually occurs in a minute or less.
internal static var second: String { return Localizable.tr("Waves", "wallet.label.quickNote.description.second") }
internal static var secondKey: String { return "wallet.label.quickNote.description.second" }
/// The generating balance will be updated after 1000 blocks.
internal static var third: String { return Localizable.tr("Waves", "wallet.label.quickNote.description.third") }
internal static var thirdKey: String { return "wallet.label.quickNote.description.third" }
}
}
}
internal enum Navigationbar {
/// Wallet
internal static var title: String { return Localizable.tr("Waves", "wallet.navigationBar.title") }
internal static var titleKey: String { return "wallet.navigationBar.title" }
}
internal enum Section {
/// Active now (%d)
internal static func activeNow(_ p1: Int) -> String {
return Localizable.tr("Waves", "wallet.section.activeNow", p1)
}
/// Hidden tokens (%d)
internal static func hiddenAssets(_ p1: Int) -> String {
return Localizable.tr("Waves", "wallet.section.hiddenAssets", p1)
}
/// Quick note
internal static var quickNote: String { return Localizable.tr("Waves", "wallet.section.quickNote") }
internal static var quickNoteKey: String { return "wallet.section.quickNote" }
/// Suspicious tokens (%d)
internal static func spamAssets(_ p1: Int) -> String {
return Localizable.tr("Waves", "wallet.section.spamAssets", p1)
}
}
internal enum Segmentedcontrol {
/// Tokens
internal static var assets: String { return Localizable.tr("Waves", "wallet.segmentedControl.assets") }
internal static var assetsKey: String { return "wallet.segmentedControl.assets" }
/// Leasing
internal static var leasing: String { return Localizable.tr("Waves", "wallet.segmentedControl.leasing") }
internal static var leasingKey: String { return "wallet.segmentedControl.leasing" }
}
internal enum Updateapp {
internal enum Label {
/// We are constantly working to make Waves Wallet better and more useful. Please update your app to gain access to new features.
internal static var subtitle: String { return Localizable.tr("Waves", "wallet.updateApp.label.subtitle") }
internal static var subtitleKey: String { return "wallet.updateApp.label.subtitle" }
/// It's time to update your app!
internal static var title: String { return Localizable.tr("Waves", "wallet.updateApp.label.title") }
internal static var titleKey: String { return "wallet.updateApp.label.title" }
}
}
}
internal enum Walletsearch {
internal enum Button {
/// Cancel
internal static var cancel: String { return Localizable.tr("Waves", "walletsearch.button.cancel") }
internal static var cancelKey: String { return "walletsearch.button.cancel" }
}
internal enum Label {
/// Hidden tokens
internal static var hiddenTokens: String { return Localizable.tr("Waves", "walletsearch.label.hiddenTokens") }
internal static var hiddenTokensKey: String { return "walletsearch.label.hiddenTokens" }
/// Suspicious tokens
internal static var suspiciousTokens: String { return Localizable.tr("Waves", "walletsearch.label.suspiciousTokens") }
internal static var suspiciousTokensKey: String { return "walletsearch.label.suspiciousTokens" }
}
}
internal enum Walletsort {
internal enum Button {
/// Position
internal static var position: String { return Localizable.tr("Waves", "walletsort.button.position") }
internal static var positionKey: String { return "walletsort.button.position" }
/// Visibility
internal static var visibility: String { return Localizable.tr("Waves", "walletsort.button.visibility") }
internal static var visibilityKey: String { return "walletsort.button.visibility" }
}
internal enum Label {
/// Hidden tokens
internal static var hiddenAssets: String { return Localizable.tr("Waves", "walletsort.label.hiddenAssets") }
internal static var hiddenAssetsKey: String { return "walletsort.label.hiddenAssets" }
/// The list of tokens is empty
internal static var listOfAssetsEmpty: String { return Localizable.tr("Waves", "walletsort.label.listOfAssetsEmpty") }
internal static var listOfAssetsEmptyKey: String { return "walletsort.label.listOfAssetsEmpty" }
/// You didn't add tokens in favorite
internal static var notAddedAssetsInFavorites: String { return Localizable.tr("Waves", "walletsort.label.notAddedAssetsInFavorites") }
internal static var notAddedAssetsInFavoritesKey: String { return "walletsort.label.notAddedAssetsInFavorites" }
/// You didn't add tokens in hidden
internal static var notAddedAssetsInHidden: String { return Localizable.tr("Waves", "walletsort.label.notAddedAssetsInHidden") }
internal static var notAddedAssetsInHiddenKey: String { return "walletsort.label.notAddedAssetsInHidden" }
}
internal enum Navigationbar {
/// Sorting
internal static var title: String { return Localizable.tr("Waves", "walletsort.navigationBar.title") }
internal static var titleKey: String { return "walletsort.navigationBar.title" }
}
}
internal enum Wavespopup {
internal enum Button {
/// Exchange
internal static var exchange: String { return Localizable.tr("Waves", "wavespopup.button.exchange") }
internal static var exchangeKey: String { return "wavespopup.button.exchange" }
/// Receive
internal static var receive: String { return Localizable.tr("Waves", "wavespopup.button.receive") }
internal static var receiveKey: String { return "wavespopup.button.receive" }
/// Send
internal static var send: String { return Localizable.tr("Waves", "wavespopup.button.send") }
internal static var sendKey: String { return "wavespopup.button.send" }
}
internal enum Label {
/// Coming soon
internal static var comingsoon: String { return Localizable.tr("Waves", "wavespopup.label.comingsoon") }
internal static var comingsoonKey: String { return "wavespopup.label.comingsoon" }
}
}
}
}
// swiftlint:enable explicit_type_interface identifier_name line_length nesting type_body_length type_name
extension Localizable {
struct Current {
var locale: Locale
var bundle: Bundle
}
private static let english: Localizable.Current = Localizable.Current(locale: Locale(identifier: "en"), bundle: Bundle(for: BundleToken.self))
static var current: Localizable.Current = Localizable.Current(locale: Locale.current, bundle: Bundle(for: BundleToken.self))
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = NSLocalizedString(key, tableName: table, bundle: current.bundle, comment: "")
let value = String(format: format, locale: current.locale, arguments: args)
if value.localizedLowercase == key.localizedLowercase {
let format = NSLocalizedString(key, tableName: table, bundle: english.bundle, comment: "")
return String(format: format, locale: english.locale, arguments: args)
} else {
return value
}
}
}
private final class BundleToken {}
| 54.998483 | 558 | 0.671383 |
8735ddcccaf47553394d4091445de6b44bab4588 | 748 | import XCTest
import RxWKWebView
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.793103 | 111 | 0.601604 |
209af7f5c618d3f4f59133c25c48df3ed1be584f | 1,957 | //
// ProfileSummary.swift
// Landmarks
//
// Created by Shane Leigh on 17/06/2019.
// Copyright © 2019 SoundWorm LLC. All rights reserved.
//
import SwiftUI
struct ProfileSummary : View {
var profile: Profile
static let goalFormat: DateFormatter = {
let formatter = DateFormatter()
// formatter.dateFormat = "MMMM d, yyyy"
formatter.dateStyle = .long
formatter.timeStyle = .none
return formatter
}()
var body: some View {
List {
Text(profile.username)
.bold()
.font(.title)
Text("Notifications: \(self.profile.prefersNotifications ? "On": "Off" )")
Text("Seasonal Photos: \(self.profile.seasonalPhoto.rawValue)")
Text("Goal Date: \(self.profile.goalDate, formatter: Self.goalFormat)")
VStack(alignment: .leading) {
Text("Completed Badges")
.font(.headline)
ScrollView {
HStack {
HikeBadge(name: "First Hike")
HikeBadge(name: "Earth Day")
.hueRotation(Angle(degrees: 90))
HikeBadge(name: "Tenth Hike")
.grayscale(0.5)
.hueRotation(Angle(degrees: 45))
}
}
.frame(height: 140)
}
VStack(alignment: .leading) {
Text("Recent Hikes")
.font(.headline)
HikeView(hike: hikeData[0])
}
}
}
}
#if DEBUG
struct ProfileSummary_Previews : PreviewProvider {
static var previews: some View {
ProfileSummary(profile: Profile.default)
}
}
#endif
| 27.56338 | 86 | 0.459888 |
f8b41c4947c19538c27e8639683bad1b70df1623 | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let P {
( {
for in {
class A {
init {
class
case ,
| 18.333333 | 87 | 0.722727 |
11f1756a8d8a063733d90445060f80fca9089d06 | 2,387 | //
// RefCount.swift
// Rx
//
// Created by Krunoslav Zaher on 3/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RefCountSink<CO: ConnectableObservableType, O: ObserverType>
: Sink<O>
, ObserverType where CO.E == O.E {
typealias Element = O.E
typealias Parent = RefCount<CO>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
let subscription = _parent._source.subscribeSafe(self)
_parent._lock.lock(); defer { _parent._lock.unlock() } // {
if _parent._count == 0 {
_parent._count = 1
_parent._connectableSubscription = _parent._source.connect()
}
else {
_parent._count = _parent._count + 1
}
// }
return Disposables.create {
subscription.dispose()
self._parent._lock.lock(); defer { self._parent._lock.unlock() } // {
if self._parent._count == 1 {
self._parent._connectableSubscription!.dispose()
self._parent._count = 0
self._parent._connectableSubscription = nil
}
else if self._parent._count > 1 {
self._parent._count = self._parent._count - 1
}
else {
rxFatalError("Something went wrong with RefCount disposing mechanism")
}
// }
}
}
func on(_ event: Event<Element>) {
switch event {
case .next:
forwardOn(event)
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
class RefCount<CO: ConnectableObservableType>: Producer<CO.E> {
fileprivate let _lock = NSRecursiveLock()
// state
fileprivate var _count = 0
fileprivate var _connectableSubscription = nil as Disposable?
fileprivate let _source: CO
init(source: CO) {
_source = source
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == CO.E {
let sink = RefCountSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
| 28.082353 | 90 | 0.546292 |
38a5ae933fd78dbafb0ffe793700fe98d75ac799 | 21,302 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListViewController` class displays the contents of a list document. It also allows the user to create, update, and delete items, change the color of the list, or delete the list.
*/
import UIKit
import NotificationCenter
import ListerKit
class ListViewController: UITableViewController, UITextFieldDelegate, ListColorCellDelegate, ListDocumentDelegate, ListPresenterDelegate {
// MARK: Types
struct MainStoryboard {
struct TableViewCellIdentifiers {
// Used for normal items and the add item cell.
static let listItemCell = "listItemCell"
// Used in edit mode to allow the user to change colors.
static let listColorCell = "listColorCell"
}
}
// MARK: Properties
var listsController: ListsController!
/// Set in `textFieldDidBeginEditing(_:)`. `nil` otherwise.
weak var activeTextField: UITextField?
/// Set in `configureWithListInfo(_:)`. `nil` otherwise.
var listInfo: ListInfo?
var document: ListDocument! {
didSet {
if document == nil { return }
document.delegate = self
listPresenter.undoManager = document.undoManager
listPresenter.delegate = self
}
}
// Provide the document's undoManager property as the default NSUndoManager for this UIViewController.
override var undoManager: NSUndoManager? {
return document?.undoManager
}
var listPresenter: AllListItemsPresenter! {
return document.listPresenter as? AllListItemsPresenter
}
var documentURL: NSURL {
return document.fileURL
}
// Return the toolbar items since they are used in edit mode.
var listToolbarItems: [UIBarButtonItem] {
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let title = NSLocalizedString("Delete List", comment: "The title of the button to delete the current list.")
let deleteList = UIBarButtonItem(title: title, style: .Plain, target: self, action: "deleteList:")
deleteList.tintColor = UIColor.redColor()
if documentURL.lastPathComponent == AppConfiguration.localizedTodayDocumentNameAndExtension {
deleteList.enabled = false
}
return [flexibleSpace, deleteList, flexibleSpace]
}
var textAttributes = [String: AnyObject]() {
didSet {
if isViewLoaded() {
updateInterfaceWithTextAttributes()
}
}
}
// MARK: View Life Cycle
// Return `true` to indicate that we want to handle undo events through the responder chain.
override func canBecomeFirstResponder() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44.0
updateInterfaceWithTextAttributes()
// Use the edit button item provided by the table view controller.
navigationItem.rightBarButtonItem = editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
document.openWithCompletionHandler { success in
if !success {
// In your app, handle this gracefully.
print("Couldn't open document: \(self.documentURL).")
abort()
}
self.textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: self.listPresenter.color.colorValue
]
/*
When the document is opened, make sure that the document stores its extra metadata in the `userInfo`
dictionary. See `ListDocument`'s `updateUserActivityState(_:)` method for more information.
*/
if let userActivity = self.document.userActivity {
self.document.updateUserActivityState(userActivity)
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleDocumentStateChangedNotification:", name: UIDocumentStateChangedNotification, object: document)
}
// Become first responder after the view appears so that we can respond to undo events.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
becomeFirstResponder()
// If available, obtain a reference to the 'newItemCell` and make its `textField` the first responder.
let newItemIndexPath = NSIndexPath(forRow: 0, inSection: 0)
guard let newItemCell = tableView.cellForRowAtIndexPath(newItemIndexPath) as? ListItemCell else { return }
newItemCell.textField.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Resign as first responder after its view disappears to stop handling undo events.
resignFirstResponder()
document.delegate = nil
document.closeWithCompletionHandler(nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDocumentStateChangedNotification, object: document)
// Hide the toolbar so the list can't be edited.
navigationController?.setToolbarHidden(true, animated: animated)
}
// MARK: Setup
func configureWithListInfo(aListInfo: ListInfo) {
listInfo = aListInfo
let listPresenter = AllListItemsPresenter()
document = ListDocument(fileURL: aListInfo.URL, listPresenter: listPresenter)
navigationItem.title = aListInfo.name
textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: aListInfo.color?.colorValue ?? List.Color.Gray.colorValue
]
}
// MARK: Notifications
func handleDocumentStateChangedNotification(notification: NSNotification) {
if document.documentState.contains(.InConflict) {
resolveConflicts()
}
// In order to update the UI, dispatch back to the main queue as there are no promises about the queue this will be called on.
dispatch_async(dispatch_get_main_queue(), tableView.reloadData)
}
// MARK: UIViewController Overrides
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
// Prevent navigating back in edit mode.
navigationItem.setHidesBackButton(editing, animated: animated)
// Make sure to resign first responder on the active text field if needed.
activeTextField?.endEditing(false)
// Reload the first row to switch from "Add Item" to "Change Color".
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// If moving out of edit mode, notify observers about the list color and trigger a save.
if !editing {
// If the list info doesn't already exist (but it should), then create a new one.
listInfo = listInfo ?? ListInfo(URL: documentURL)
listInfo!.color = listPresenter.color
listsController!.setListInfoHasNewContents(listInfo!)
triggerNewDataForWidget()
}
navigationController?.setToolbarHidden(!editing, animated: animated)
navigationController?.toolbar?.setItems(listToolbarItems, animated: animated)
}
// MARK: UITableViewDataSource
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
// Don't show anything if the document hasn't been loaded.
if document == nil {
return 0
}
// Show the items in a list, plus a separate row that lets users enter a new item.
return listPresenter.count + 1
}
override func tableView(_: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var identifier: String
// Show the "color selection" cell if in edit mode.
if editing && indexPath.row == 0 {
identifier = MainStoryboard.TableViewCellIdentifiers.listColorCell
}
else {
identifier = MainStoryboard.TableViewCellIdentifiers.listItemCell
}
return tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
}
override func tableView(_: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// The initial row is reserved for adding new items so it can't be deleted or edited.
if indexPath.row == 0 {
return false
}
return true
}
override func tableView(_: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// The initial row is reserved for adding new items so it can't be moved.
if indexPath.row == 0 {
return false
}
return true
}
override func tableView(_: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle != .Delete {
return
}
let listItem = listPresenter.presentedListItems[indexPath.row - 1]
listPresenter.removeListItem(listItem)
}
override func tableView(_: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
let listItem = listPresenter.presentedListItems[fromIndexPath.row - 1]
// `toIndexPath.row` will never be `0` since we don't allow moving to the zeroth row (it's the color selection row).
listPresenter.moveListItem(listItem, toIndex: toIndexPath.row - 1)
}
// MARK: UITableViewDelegate
override func tableView(_: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
switch cell {
case let colorCell as ListColorCell:
colorCell.configure()
colorCell.selectedColor = listPresenter.color
colorCell.delegate = self
case let itemCell as ListItemCell:
configureListItemCell(itemCell, forRow: indexPath.row)
default:
fatalError("Attempting to configure an unknown or unsupported cell type in `ListViewController`.")
}
}
override func tableView(_: UITableView, willBeginEditingRowAtIndexPath: NSIndexPath) {
/*
When the user swipes to show the delete confirmation, don't enter editing mode.
`UITableViewController` enters editing mode by default so we override without calling super.
*/
}
override func tableView(_: UITableView, didEndEditingRowAtIndexPath: NSIndexPath) {
/*
When the user swipes to hide the delete confirmation, no need to exit edit mode because we didn't
enter it. `UITableViewController` enters editing mode by default so we override without calling
super.
*/
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(_: UITableView, targetIndexPathForMoveFromRowAtIndexPath fromIndexPath: NSIndexPath, toProposedIndexPath proposedIndexPath: NSIndexPath) -> NSIndexPath {
let listItem = listPresenter.presentedListItems[fromIndexPath.row - 1]
if proposedIndexPath.row == 0 {
return fromIndexPath
}
else if listPresenter.canMoveListItem(listItem, toIndex: proposedIndexPath.row - 1) {
return proposedIndexPath
}
return fromIndexPath
}
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
activeTextField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
defer {
activeTextField = nil
}
guard let text = textField.text else { return }
let indexPath = indexPathForView(textField)
if indexPath != nil && indexPath!.row > 0 {
let listItem = listPresenter.presentedListItems[indexPath!.row - 1]
listPresenter.updateListItem(listItem, withText: text)
}
else if !text.isEmpty {
let listItem = ListItem(text: text)
listPresenter.insertListItem(listItem)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let indexPath = indexPathForView(textField)!
// The 'add item' row can always dismiss the keyboard.
if indexPath.row == 0 {
textField.resignFirstResponder()
return true
}
// An item must have text to dismiss the keyboard.
guard let text = textField.text where !text.isEmpty else { return false }
textField.resignFirstResponder()
return true
}
// MARK: ListColorCellDelegate
func listColorCellDidChangeSelectedColor(listColorCell: ListColorCell) {
listPresenter.color = listColorCell.selectedColor
}
// MARK: IBActions
@IBAction func deleteList(_: UIBarButtonItem) {
listsController.removeListInfo(listInfo!)
hideViewControllerAfterListWasDeleted()
}
@IBAction func checkBoxTapped(sender: CheckBox) {
let indexPath = indexPathForView(sender)!
// Check to see if the tapped row is within the list item rows.
if 1...listPresenter.count ~= indexPath.row {
let listItem = listPresenter.presentedListItems[indexPath.row - 1]
listPresenter.toggleListItem(listItem)
}
}
// MARK: ListDocumentDelegate
func listDocumentWasDeleted(listDocument: ListDocument) {
hideViewControllerAfterListWasDeleted()
}
// MARK: ListPresenterDelegate
func listPresenterDidRefreshCompleteLayout(listPresenter: ListPresenterType) {
// Updating `textAttributes` will updated the color for the items in the interface.
textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: listPresenter.color.colorValue
]
tableView.reloadData()
}
func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
tableView.beginUpdates()
}
func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) {
let indexPathsForInsertion = [NSIndexPath(forRow: index + 1, inSection: 0)]
tableView.insertRowsAtIndexPaths(indexPathsForInsertion, withRowAnimation: .Fade)
// Reload the ListItemCell to be configured for the row to create a new list item.
if index == 0 {
let indexPathsForReloading = [NSIndexPath(forRow: 0, inSection: 0)]
tableView.reloadRowsAtIndexPaths(indexPathsForReloading, withRowAnimation: .Automatic)
}
}
func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) {
let indexPaths = [NSIndexPath(forRow: index + 1, inSection: 0)]
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) {
tableView.endUpdates()
tableView.beginUpdates()
let indexPath = NSIndexPath(forRow: index + 1, inSection: 0)
if let listItemCell = tableView.cellForRowAtIndexPath(indexPath) as? ListItemCell {
configureListItemCell(listItemCell, forRow: index + 1)
}
}
func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) {
let fromIndexPath = NSIndexPath(forRow: fromIndex + 1, inSection: 0)
let toIndexPath = NSIndexPath(forRow: toIndex + 1, inSection: 0)
tableView.moveRowAtIndexPath(fromIndexPath, toIndexPath: toIndexPath)
}
func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) {
// Updating `textAttributes` will updated the color for the items in the interface.
textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: color.colorValue
]
// The document infrastructure needs to be updated to capture the list's color when it changes.
if let userActivity = self.document.userActivity {
self.document.updateUserActivityState(userActivity)
}
}
func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
tableView.endUpdates()
}
// MARK: Convenience
func updateInterfaceWithTextAttributes() {
let controller = navigationController?.navigationController ?? navigationController!
controller.navigationBar.titleTextAttributes = textAttributes
controller.navigationBar.tintColor = textAttributes[NSForegroundColorAttributeName] as! UIColor
controller.toolbar?.tintColor = textAttributes[NSForegroundColorAttributeName] as! UIColor
tableView.tintColor = textAttributes[NSForegroundColorAttributeName] as! UIColor
}
func hideViewControllerAfterListWasDeleted() {
if splitViewController != nil && splitViewController!.collapsed {
let controller = navigationController?.navigationController ?? navigationController!
controller.popViewControllerAnimated(true)
}
else {
let emptyViewController = storyboard?.instantiateViewControllerWithIdentifier(AppDelegate.MainStoryboard.Identifiers.emptyViewController) as! UINavigationController
emptyViewController.topViewController?.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
let masterViewController = splitViewController?.viewControllers.first! as! UINavigationController
splitViewController?.viewControllers = [masterViewController, emptyViewController]
}
}
func configureListItemCell(listItemCell: ListItemCell, forRow row: Int) {
listItemCell.checkBox.isChecked = false
listItemCell.checkBox.hidden = false
listItemCell.textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
listItemCell.textField.delegate = self
listItemCell.textField.textColor = UIColor.darkTextColor()
listItemCell.textField.enabled = true
if row == 0 {
// Configure an "Add Item" list item cell.
listItemCell.textField.placeholder = NSLocalizedString("Add Item", comment: "")
listItemCell.textField.text = ""
listItemCell.checkBox.hidden = true
}
else {
let listItem = listPresenter.presentedListItems[row - 1]
listItemCell.isComplete = listItem.isComplete
listItemCell.textField.text = listItem.text
}
}
func triggerNewDataForWidget() {
if document.localizedName == AppConfiguration.localizedTodayDocumentName {
NCWidgetController.widgetController().setHasContent(true, forWidgetWithBundleIdentifier: AppConfiguration.Extensions.widgetBundleIdentifier)
}
}
func resolveConflicts() {
/*
Any automatic merging logic or presentation of conflict resolution UI should go here.
For Lister we'll pick the current version and mark the conflict versions as resolved.
*/
do {
try NSFileVersion.removeOtherVersionsOfItemAtURL(documentURL)
let conflictVersions = NSFileVersion.unresolvedConflictVersionsOfItemAtURL(documentURL)!
for fileVersion in conflictVersions {
fileVersion.resolved = true
}
}
// Any encountered errors are swallowed, handle this appropriately in your own apps.
catch {}
}
func indexPathForView(view: UIView) -> NSIndexPath? {
let viewOrigin = view.bounds.origin
let viewLocation = tableView.convertPoint(viewOrigin, fromView: view)
return tableView.indexPathForRowAtPoint(viewLocation)
}
}
| 38.107335 | 187 | 0.661957 |
720584618fa83e24b7c7c8ecbbc5e0d83184b776 | 2,200 | //
// FirebaseAuthData.swift
// Fuel economy smart calc.
//
// Created by Nikolay Prodanow on 4/1/17.
// Copyright © 2017 Nikolay Prodanow. All rights reserved.
//
import Foundation
import Firebase
import FirebaseAuth
class FirebaseAuthData: BaseAuthData {
var delegate: AuthDataDelegate?
init() {
}
func setDelegate(delegate: AuthDataDelegate){
self.delegate = delegate
}
func createUser(withEmail email: String, andPassword password: String){
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
DispatchQueue.main.async {
if let user = user {
self?.delegate?.didReceiveCreateUser(withEmail: user.email!)
} else {
self?.delegate?.didReceiveCreateUserError()
}
}
}
}
}
func signInUser(withEmail email: String, andPassowrd password: String){
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
DispatchQueue.main.async {
if let user = user {
self?.delegate?.didReceiveSignInUser(withEmail: user.email!)
} else {
self?.delegate?.didReceiveSignInUserError()
}
}
}
}
}
func getCurrentUser(){
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
let user = FIRAuth.auth()?.currentUser
DispatchQueue.main.async {
if let user = user {
self?.delegate?.didReceiveCurrentUser(withEmail: user.email!)
} else {
self?.delegate?.didReceiveCurrentUser(withEmail: nil)
}
}
}
}
func signOutUser() {
DispatchQueue.global(qos: .userInitiated).async {
try? FIRAuth.auth()?.signOut()
}
}
}
| 30.985915 | 95 | 0.538636 |
647336492cdfe9993fb84361483cf4d33be9d4d3 | 3,769 | //
// File.swift
//
//
// Created by Cobey Hollier on 2019-10-05.
//
import Foundation
class AlphaBeta {
class func getNextMove(with data: Data) -> [String: String] {
let MIN = -1000000
let MAX = 1000000
let myId = data.you.id
var enemyId = "temp"
for snake in data.board.snakes {
if(snake.id != myId) {
enemyId = snake.id
}
}
let (score, bestMove) = AlphaBeta.minimax(with: data, max_player: true, enemyId: enemyId, myId: myId, depth: 1, alpha: MIN, beta: MAX)
print(score, bestMove)
let bestDir = score > MIN ? data.you.dir(to: bestMove) : data.you.find_safe_move(from: data)
return ["move": bestDir]
}
class func minimax(with data: Data, max_player: Bool, enemyId: String, myId: String, depth: Int, alpha: Int, beta: Int) -> (Int, Point) {
let mySnake = data.getSnake(by: myId)
let enemySnake = data.getSnake(by: enemyId)
if(depth > 4) {
return (2 * finalScore(for: mySnake!, from: data) - finalScore(for: enemySnake!, from: data), Point(x: 0, y: 0))
}
var (temp_snake, best_score) = max_player ? (data.getSnake(by: myId), -1000000) : (data.getSnake(by: enemyId), 1000000)
var best_move = Point(x: 0, y: 0)
var successors = temp_snake!.body[0].successors(from: data)
//Add our head as a possible move for the enemy
if(!max_player) {
let ourHead = data.getSnake(by: myId)!.body[0]
for point in temp_snake!.body[0].orthogonal() {
if(point == ourHead) {
successors.insert(ourHead)
}
}
}
for pos_move in successors {
var new_st = data
if(max_player) {
let index = new_st.index(of: myId)!
new_st.update(snake: &(new_st.board.snakes[index]), from: pos_move)
if(new_st.board.snakes[index].health == 0) {
continue
}
let (val, _) = minimax(with: new_st, max_player: false, enemyId: enemyId, myId: myId, depth: depth + 1, alpha: alpha, beta: beta)
if(val > best_score) {
best_move = pos_move
}
best_score = max(val, best_score)
let new_alpha = max(alpha, best_score)
if(beta <= new_alpha) {
break
}
} else {
let index = new_st.index(of: enemyId)!
new_st.update(snake: &(new_st.board.snakes[index]), from: pos_move)
// Handle head on condition
let our_snake = new_st.getSnake(by: myId)!
if(our_snake.body[0] == pos_move) {
if(our_snake.body.count > new_st.board.snakes[index].body.count) {
continue
} else {
return (-1000000, best_move)
}
}
let (val, _) = minimax(with: new_st, max_player: true, enemyId: enemyId, myId: myId, depth: depth + 1, alpha: alpha, beta: beta)
if val < best_score {
best_move = pos_move
}
best_score = min(best_score, val)
let new_beta = min(best_score, beta)
if(new_beta < alpha) {
break
}
}
}
return (best_score, best_move)
}
class func finalScore(for snake: Snake, from data: Data) -> Int {
return snake.floodFill(from: data)
}
}
| 37.316832 | 145 | 0.495888 |
69e3de90c26c7aaccd25d1eb8f5105b0e22a50b0 | 642 | //
// AllProfilenames.swift
// RsyncOSX
//
// Created by Thomas Evensen on 15.05.2018.
// Copyright © 2018 Thomas Evensen. All rights reserved.
//
import Foundation
class AllProfilenames {
var allprofiles: [String]?
private func getprofilenames() {
let profile = Files(whichroot: .profileRoot, configpath: ViewControllerReference.shared.configpath)
self.allprofiles = profile.getDirectorysStrings()
guard self.allprofiles != nil else { return }
self.allprofiles!.append(NSLocalizedString("Default profile", comment: "default profile"))
}
init() {
self.getprofilenames()
}
}
| 25.68 | 107 | 0.685358 |
d655f54693aa949bdd096808b9655044482ec7a3 | 412 | // Copyright © 2019 Optimove. All rights reserved.
final class SetUserEmailEvent: Event {
struct Constants {
static let name = OptimoveKeys.Configuration.setEmail.rawValue
struct Key {
static let email = OptimoveKeys.Configuration.email.rawValue
}
}
init(email: String) {
super.init(name: Constants.name, context: [Constants.Key.email: email])
}
}
| 25.75 | 79 | 0.65534 |
7adfd2988a26a351997602004085ce870634551f | 1,776 | //
// NSTextView+Snippet.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2017-12-29.
//
// ---------------------------------------------------------------------------
//
// © 2017-2019 1024jp
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
extension NSTextView {
func insert(snippet: Snippet) {
guard !snippet.string.isEmpty else { return }
let ranges = (self.rangesForUserTextChange ?? self.selectedRanges).map { $0.rangeValue }
let strings = [String](repeating: snippet.string, count: ranges.count)
let selectedRanges: [NSRange]? = {
guard let selection = snippet.selection else { return nil }
let snippetLength = (snippet.string as NSString).length
return ranges.map { range in
let offset = ranges
.prefix { $0 != range }
.map { snippetLength - $0.length }
.reduce(range.location, +)
return selection.shifted(offset: offset)
}
}()
self.replace(with: strings, ranges: ranges, selectedRanges: selectedRanges, actionName: "Insert Snippet".localized)
}
}
| 32.290909 | 123 | 0.590653 |
3801b2bb0ecddf7726cd3e25fa79b206fa8d54af | 923 | //
// IssueTemplate.swift
// github-issue-browser
//
// useful resouce:
// json handling: https://matteomanferdini.com/codable/
//
// Created by Lor Worwag on 3/8/21.
//
import Foundation
struct IssueTemplate: Codable, Identifiable {
let url: String?
var comments_url: String?
var id: Int
var number: Int?
var title: String?
var user: UserTemplate?
var state: String?
var locked: Bool
var comments: Int?
var created_at: String?
var updated_at: String?
var closed_at: String?
var body: String?
}
struct UserTemplate: Codable, Identifiable {
var login: String
var id: Int
}
struct LabelTemplate: Codable, Identifiable {
var id: Int
var name: String
}
struct CommentTemplate: Codable, Identifiable {
var url: String?
var issue_url: String?
var id: Int
var user: UserTemplate?
var created_at: String?
var body: String?
}
| 19.638298 | 60 | 0.664139 |
036a81045b156ba3fac5faec3b5fedf69324d286 | 750 | //
// JSContext+Utility.swift
// Eunomia
//
// Created by Ian Grossberg on 11/26/15.
// Copyright © 2015 Adorkable. All rights reserved.
//
import JavaScriptCore
extension JSContext {
// public func setConsoleLogHandler(_ handler : @escaping @convention(block)(String) -> String) {
// self.setObject(unsafeBitCast(handler, to: AnyObject.self), forKeyedSubscript: "log" as NSCopying & NSObjectProtocol)
//
// // TODO: test if console already exists before creating each time
// self.evaluateScript("var console = new Object();")
//
// self.objectForKeyedSubscript("console").setObject(unsafeBitCast(handler, to: AnyObject.self), forKeyedSubscript: "log" as NSCopying & NSObjectProtocol)
// }
}
| 34.090909 | 161 | 0.688 |
bbf82f11ad7f4f8623c3d873a455595c0fbbcf52 | 2,661 | public struct ValidatorResults {
public struct Nested {
public let results: [ValidatorResult]
}
public struct Skipped { }
public struct Missing { }
public struct NotFound { }
public struct Codable {
public let error: Error
}
public struct Invalid {
public let reason: String
}
public struct TypeMismatch {
public let type: Any.Type
}
}
extension ValidatorResults.Nested: ValidatorResult {
public var isFailure: Bool {
!self.results.filter { $0.isFailure }.isEmpty
}
public var successDescription: String? {
self.results.filter { !$0.isFailure }
.compactMap { $0.successDescription }
.joined(separator: " and ")
}
public var failureDescription: String? {
self.results.filter { $0.isFailure }
.compactMap { $0.failureDescription }
.joined(separator: " and ")
}
}
extension ValidatorResults.Skipped: ValidatorResult {
public var isFailure: Bool {
false
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
nil
}
}
extension ValidatorResults.Missing: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"is required"
}
}
extension ValidatorResults.Invalid: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"is invalid: \(self.reason)"
}
}
extension ValidatorResults.NotFound: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"cannot be null"
}
}
extension ValidatorResults.TypeMismatch: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"is not a(n) \(self.type)"
}
}
extension ValidatorResults.Codable: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"failed to decode: \(error)"
}
}
public protocol ValidatorResult {
var isFailure: Bool { get }
var successDescription: String? { get }
var failureDescription: String? { get }
}
| 20.007519 | 58 | 0.608042 |
acd9fbcbb56e6b181faf5a43fd965183fac1ebdc | 742 | import XCTest
import RCSDK
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.586207 | 111 | 0.598383 |
29c9757d57ec813e97607ab0c52e71f8305e0b5a | 1,888 | //
// AnimalVIew.swift
// ReduxSwiftUI
//
// Created by Calvin Chang on 2020/12/1.
//
import SwiftUI
import ComposableArchitecture
struct AnimalView: View {
let router: Application.RouterType
let store: Store<Animal.State, Animal.Action>
var mainRouter: Main.RouterType {
router.scope(
state: \.main,
action: Application.RoutingAction.mainStateChanged
)
}
var body: some View {
let mainViewStore = ViewStore(mainRouter)
WithViewStore(store) { viewStore in
VStack {
if viewStore.inProgress {
ProgressView("Fetching Animal…")
} else if let error = viewStore.error {
Text("Some error occur\n \(error.localizedDescription)")
.foregroundColor(.red)
.multilineTextAlignment(.center)
Button("Try again") {
viewStore.send(.fetch)
}
} else {
Text(viewStore.current)
.font(.system(.largeTitle))
.padding()
Button("Tap me") { viewStore.send(.fetch) }
WithViewStore(mainRouter) { router in
NavigationLink(
destination: mainViewStore.viewBuilder(mainRouter),
isActive: mainViewStore.binding(get: \.isActive, send: {
if $0 { viewStore.send(.setName) }
return Main.RoutingAction.activeStateChanged($0)
}),
label: {
Text("To main")
}
)
}
}
}
}
}
}
| 33.122807 | 84 | 0.450742 |
164efce2d076ebf6dcd65943c1b1ea9f12413609 | 1,339 | import Foundation
extension NSLayoutConstraint
{
/** Changes the visiblity of the constrained view assuming preconditions are met.
*
* In addition to this constraint there should be a second constraint in the UI which dictates the actual
* height for the view (it's priority should be set to UILayoutPriorityDefaultHigh (750).
*/
@objc func setConstrainedViewHidden(hidden: Bool) {
// Hide constrained view by adjusting priorities (and setting height to 0).
//
// Explicitly use priorities for changing the height of the view. It seems that
// toggling isActive state of the constraint also works but setting .active = NO calls
// removeConstraint() method under the hood. This may cause the constraint to be garbage
// collected (if held in a weak property) even though this behaviour has not been observed
// during tests. Toggling active state may also cause auto layout issues in some cases
// --> altering priorities if probably better
// https://developer.apple.com/documentation/uikit/nslayoutconstraint/1527000-isactive
if (hidden) {
self.priority = UILayoutPriority.defaultHigh + 1
self.constant = 0
} else {
self.priority = UILayoutPriority.defaultHigh - 1
}
}
}
| 46.172414 | 109 | 0.685586 |
1496c04b1eaed021df81aae81ca0dd8f63c9ef91 | 2,167 | //
// AppDelegate.swift
// UIViewExtension
//
// Created by Wang on 2018/1/11.
// Copyright © 2018年 Wang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.755422 |
468af127ffcba01e5f02df1c6b549b7c56df88a0 | 1,010 | //
// PasscodecheckTests.swift
// PasscodecheckTests
//
// Created by GDB Consultants on 03/03/17.
// Copyright © 2017 GDB Technologies Pvt Ltd. All rights reserved.
//
import XCTest
@testable import Passcodecheck
class PasscodecheckTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.297297 | 111 | 0.644554 |
fe332d8c3d54b58c13b218cc42309656375d9910 | 9,363 | import Foundation
import TSCBasic
import TuistCore
import TuistSupport
/// A component responsible for generating Xcode projects & workspaces
@available(
*,
deprecated,
message: "Generating is deprecated and will be removed in a future Tuist version. Please use `DescriptorGenerating` instead."
)
public protocol Generating {
/// Generates an Xcode project at a given path. Only the specified project is generated (excluding its dependencies).
///
/// - Parameters:
/// - path: The absolute path to the directory where an Xcode project should be generated
/// - Returns: An absolute path to the generated Xcode project many of which adopt `FatalError`
/// - Throws: Errors encountered during the generation process
/// - seealso: TuistCore.FatalError
func generateProject(at path: AbsolutePath) throws -> (AbsolutePath, Graph)
/// Generates the given project in the same directory where it's defined.
/// - Parameters:
/// - project: The project to be generated.
/// - graph: The dependencies graph.
func generateProject(_ project: Project, graph: Graph) throws -> AbsolutePath
/// Generate an Xcode workspace for the project at a given path. All the project's dependencies will also be generated and included.
///
/// - Parameters:
/// - path: The absolute path to the directory where an Xcode workspace should be generated
/// (e.g. /path/to/directory)
/// - workspaceFiles: Additional files to include in the final generated workspace
/// - Returns: An absolute path to the generated Xcode workspace
/// (e.g. /path/to/directory/project.xcodeproj)
/// - Throws: Errors encountered during the generation process
/// many of which adopt `FatalError`
/// - seealso: TuistCore.FatalError
@discardableResult
func generateProjectWorkspace(at path: AbsolutePath, workspaceFiles: [AbsolutePath]) throws -> (AbsolutePath, Graph)
/// Generate an Xcode workspace at a given path. All referenced projects and their dependencies will be generated and included.
///
/// - Parameters:
/// - path: The absolute path to the directory where an Xcode workspace should be generated
/// (e.g. /path/to/directory)
/// - workspaceFiles: Additional files to include in the final generated workspace
/// - Returns: An absolute path to the generated Xcode workspace
/// (e.g. /path/to/directory/project.xcodeproj)
/// - Throws: Errors encountered during the generation process
/// many of which adopt `FatalError`
/// - seealso: TuistCore.FatalError
@discardableResult
func generateWorkspace(at path: AbsolutePath, workspaceFiles: [AbsolutePath]) throws -> (AbsolutePath, Graph)
}
/// A default implementation of `Generating`
///
/// - seealso: Generating
/// - seealso: GeneratorModelLoading
@available(
*,
deprecated,
message: "Generator is deprecated and will be removed in a future Tuist version. Please use `DescriptorGenerator` instead."
)
public class Generator: Generating {
private let graphLoader: GraphLoading
private let graphLinter: GraphLinting
private let workspaceGenerator: WorkspaceGenerating
private let projectGenerator: ProjectGenerating
private let writer: XcodeProjWriting
private let cocoapodsInteractor: CocoaPodsInteracting
private let swiftPackageManagerInteractor: SwiftPackageManagerInteracting
/// Instance to lint the Tuist configuration against the system.
private let environmentLinter: EnvironmentLinting
public convenience init(defaultSettingsProvider: DefaultSettingsProviding = DefaultSettingsProvider(),
modelLoader: GeneratorModelLoading) {
let graphLinter = GraphLinter()
let graphLoader = GraphLoader(modelLoader: modelLoader)
let configGenerator = ConfigGenerator(defaultSettingsProvider: defaultSettingsProvider)
let targetGenerator = TargetGenerator(configGenerator: configGenerator)
let projectGenerator = ProjectGenerator(targetGenerator: targetGenerator,
configGenerator: configGenerator)
let environmentLinter = EnvironmentLinter()
let workspaceStructureGenerator = WorkspaceStructureGenerator()
let schemesGenerator = SchemesGenerator()
let workspaceGenerator = WorkspaceGenerator(projectGenerator: projectGenerator,
workspaceStructureGenerator: workspaceStructureGenerator,
schemesGenerator: schemesGenerator)
let writer = XcodeProjWriter()
let cocoapodsInteractor: CocoaPodsInteracting = CocoaPodsInteractor()
let swiftPackageManagerInteractor: SwiftPackageManagerInteracting = SwiftPackageManagerInteractor()
self.init(graphLoader: graphLoader,
graphLinter: graphLinter,
workspaceGenerator: workspaceGenerator,
projectGenerator: projectGenerator,
environmentLinter: environmentLinter,
writer: writer,
cocoapodsInteractor: cocoapodsInteractor,
swiftPackageManagerInteractor: swiftPackageManagerInteractor)
}
init(graphLoader: GraphLoading,
graphLinter: GraphLinting,
workspaceGenerator: WorkspaceGenerating,
projectGenerator: ProjectGenerating,
environmentLinter: EnvironmentLinting,
writer: XcodeProjWriting,
cocoapodsInteractor: CocoaPodsInteracting,
swiftPackageManagerInteractor: SwiftPackageManagerInteracting) {
self.graphLoader = graphLoader
self.graphLinter = graphLinter
self.workspaceGenerator = workspaceGenerator
self.projectGenerator = projectGenerator
self.environmentLinter = environmentLinter
self.writer = writer
self.cocoapodsInteractor = cocoapodsInteractor
self.swiftPackageManagerInteractor = swiftPackageManagerInteractor
}
public func generateProject(_ project: Project, graph: Graph) throws -> AbsolutePath {
let descriptor = try projectGenerator.generate(project: project, graph: graph)
try writer.write(project: descriptor)
return descriptor.xcodeprojPath
}
public func generateProject(at path: AbsolutePath) throws -> (AbsolutePath, Graph) {
let config = try graphLoader.loadConfig(path: path)
try environmentLinter.lint(config: config).printAndThrowIfNeeded()
let (graph, project) = try graphLoader.loadProject(path: path)
try graphLinter.lint(graph: graph).printAndThrowIfNeeded()
let descriptor = try projectGenerator.generate(project: project, graph: graph)
try writer.write(project: descriptor)
return (descriptor.xcodeprojPath, graph)
}
public func generateProjectWorkspace(at path: AbsolutePath,
workspaceFiles: [AbsolutePath]) throws -> (AbsolutePath, Graph) {
let config = try graphLoader.loadConfig(path: path)
try environmentLinter.lint(config: config).printAndThrowIfNeeded()
let (graph, project) = try graphLoader.loadProject(path: path)
try graphLinter.lint(graph: graph).printAndThrowIfNeeded()
let workspace = Workspace(path: path,
name: project.name,
projects: graph.projects.compactMap { $0.path },
additionalFiles: workspaceFiles.map(FileElement.file))
let descriptor = try workspaceGenerator.generate(workspace: workspace,
path: path,
graph: graph)
try writer.write(workspace: descriptor)
try postGenerationActions(for: graph, workspaceName: descriptor.xcworkspacePath.basename)
return (descriptor.xcworkspacePath, graph)
}
public func generateWorkspace(at path: AbsolutePath,
workspaceFiles: [AbsolutePath]) throws -> (AbsolutePath, Graph) {
let config = try graphLoader.loadConfig(path: path)
try environmentLinter.lint(config: config).printAndThrowIfNeeded()
let (graph, workspace) = try graphLoader.loadWorkspace(path: path)
try graphLinter.lint(graph: graph).printAndThrowIfNeeded()
let updatedWorkspace = workspace
.merging(projects: graph.projects.map { $0.path })
.adding(files: workspaceFiles)
let descriptor = try workspaceGenerator.generate(workspace: updatedWorkspace,
path: path,
graph: graph)
try writer.write(workspace: descriptor)
try postGenerationActions(for: graph, workspaceName: descriptor.xcworkspacePath.basename)
return (descriptor.xcworkspacePath, graph)
}
private func postGenerationActions(for graph: Graph, workspaceName: String) throws {
try swiftPackageManagerInteractor.install(graph: graph, workspaceName: workspaceName)
try cocoapodsInteractor.install(graph: graph)
}
}
| 48.512953 | 136 | 0.675318 |
f4aaf626ccbb1b6f9e84146f5fec2c3ec200719e | 77,959 | //
// PieceMovementTests.swift
// SwiftChess
//
// Created by Steve Barnegren on 20/09/2016.
// Copyright © 2016 Steve Barnegren. All rights reserved.
//
// swiftlint:disable type_body_length
// swiftlint:disable file_length
import XCTest
@testable import SwiftChess
class PieceMovementTests: XCTestCase {
// MARK: - Setup / Tear down
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// MARK: - Board Testing
func testBoard(board: ASCIIBoard, movingPiece: Character, movement: PieceMovement) {
// Get the index of the moving piece
let movingIndex = board.indexOfCharacter(movingPiece)
// Test allowed locations
let allowedIndexes = board.indexesWithCharacter("*")
if allowedIndexes.count > 0 {
for allowedIndex in allowedIndexes {
XCTAssertTrue(
movement.canPieceMove(from: BoardLocation(index: movingIndex),
to: BoardLocation(index: allowedIndex),
board: board.board),
"Allowed index was invalid: \(allowedIndex)")
}
}
// Test invalid locations
let invalidIndexes = board.indexesWithCharacter("!")
if invalidIndexes.count > 0 {
for invalidIndex in invalidIndexes {
XCTAssertFalse(
movement.canPieceMove(from: BoardLocation(index: movingIndex),
to: BoardLocation(index: invalidIndex),
board: board.board),
"Invalid index was valid: \(invalidIndex)")
}
}
}
func canMakeMove(board: ASCIIBoard, from: Character, to: Character, movement: PieceMovement) -> Bool {
let movingIndex = board.indexOfCharacter(from)
let targetIndex = board.indexOfCharacter(to)
return movement.canPieceMove(from: BoardLocation(index: movingIndex),
to: BoardLocation(index: targetIndex),
board: board.board)
}
// MARK: - Straight Line Movement
func testStraightLineMovementCanMoveUp() {
let board = ASCIIBoard(colors: "* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"W - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCanMoveDown() {
let board = ASCIIBoard(colors: "W - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" +
"* - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCanMoveRight() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"W * * * * * * *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCanMoveLeft() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"* * * * * * * W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveToInvalidPositionFromCenter() {
let board = ASCIIBoard(colors: "! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"* * * W * * * *" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W * * * * * * *" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "* * * * * * * W" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"W * * * * * * *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"* * * * * * * W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCannotMoveThroughOpponent() {
let board = ASCIIBoard(colors: "- - - ! - - - -" +
"- - - ! - - - -" +
"- - - B - - - -" +
"- - - * - - - -" +
"! B * W * B ! !" +
"- - - * - - - -" +
"- - - B - - - -" +
"- - - ! - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementStraightLine())
}
func testStraightLineMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"W - - - B - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementStraightLine()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testStraightLineMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"Q - - - g - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("Q")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementStraightLine()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Diagonal Movement
func testDiagonalMovementCanMoveNE() {
let board = ASCIIBoard(colors: "- - - - - - - *" +
"- - - - - - * -" +
"- - - - - * - -" +
"- - - - * - - -" +
"- - - * - - - -" +
"- - * - - - - -" +
"- * - - - - - -" +
"W - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCanMoveSE() {
let board = ASCIIBoard(colors: "W - - - - - - -" +
"- * - - - - - -" +
"- - * - - - - -" +
"- - - * - - - -" +
"- - - - * - - -" +
"- - - - - * - -" +
"- - - - - - * -" +
"- - - - - - - *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCanMoveSW() {
let board = ASCIIBoard(colors: "- - - - - - - W" +
"- - - - - - * -" +
"- - - - - * - -" +
"- - - - * - - -" +
"- - - * - - - -" +
"- - * - - - - -" +
"- * - - - - - -" +
"* - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCanMoveNW() {
let board = ASCIIBoard(colors: "* - - - - - - -" +
"- * - - - - - -" +
"- - * - - - - -" +
"- - - * - - - -" +
"- - - - * - - -" +
"- - - - - * - -" +
"- - - - - - * -" +
"- - - - - - - W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCannotMoveToInvalidPositionFromCenter() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"* ! ! ! ! ! * !" +
"! * ! ! ! * ! !" +
"! ! * ! * ! ! !" +
"! ! ! W ! ! ! !" +
"! ! * ! * ! ! !" +
"! * ! ! ! * ! !" +
"* ! ! ! ! ! * !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W ! ! ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! * ! ! !" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! W" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! * ! !" +
"! ! ! ! * ! ! !" +
"! ! ! * ! ! ! !" +
"! ! * ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! * ! !" +
"! ! ! ! * ! ! !" +
"! ! ! * ! ! ! !" +
"! ! * ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"W ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! * ! ! !" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! ! ! W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementDiagonal())
}
func testDiagonalMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - B - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - W" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementDiagonal()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testDiagonalMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - g - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - Q" )
let pieceIndex = board.indexOfCharacter("Q")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementDiagonal()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Knight Movement
func testKnightMovementCanMoveToClockwisePosition1() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - * - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition2() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - * - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition3() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - * - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition4() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - * - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition5() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - * - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition6() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- * - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition7() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- * - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCanMoveToClockwisePosition8() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - * - - - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToInvalidPositionFromCenter() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! * ! * ! ! !" +
"! * ! ! ! * ! !" +
"! ! ! W ! ! ! !" +
"! * ! ! ! * ! !" +
"! ! * ! * ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W ! ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! W" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"W ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! ! W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKnight())
}
func testKnightMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .knight, color: .white), at: location)
let movement = PieceMovementKnight()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testKnightMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - B - - -" +
"- - - - - - - -" +
"- - - W - - - -" +
"- - - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementKnight()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testKnightMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - g - - -" +
"- - - - - - - -" +
"- - - K - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("K")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementKnight()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - King Movement
func testKingMovementCannotMoveToInvalidPositionFromCenter() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! * * * ! ! !" +
"! ! * W * ! ! !" +
"! ! * * * ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKing())
}
func testKingMovementCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W * ! ! ! ! ! !" +
"* * ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKing())
}
func testKingMovementCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! * W" +
"! ! ! ! ! ! * *" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKing())
}
func testKingMovementCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"* * ! ! ! ! ! !" +
"W * ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKing())
}
func testKingMovementCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! * *" +
"! ! ! ! ! ! * W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementKing())
}
func testKingMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .king, color: .white), at: location)
let movement = PieceMovementKing()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testKingMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - B - - -" +
"- - - W - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementKing()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testKingMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - g - - -" +
"- - - G - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("G")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementKing()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Pawn Movement
func testWhitePawnCanMoveAheadOneSpace() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - * - - - -" +
"- - - P - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testBlackPawnCanMoveAheadOneSpace() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - p - - - -" +
"- - - * - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testWhitePawnCanMoveAheadTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - * - - - -" +
"- - - - - - - -" +
"- - - P - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testBlackPawnCanMoveAheadTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - p - - - -" +
"- - - - - - - -" +
"- - - * - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testStartingWhitePawnCannotJumpOverPiece() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - ! - - - -" +
"- - - K - - - -" +
"- - - P - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testStartingBlackPawnCannotJumpOverPiece() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - p - - - -" +
"- - - k - - - -" +
"- - - ! - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testNonStartingRowWhitePawnCannotMoveAheadTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - ! - - - -" +
"- - - - - - - -" +
"- - - P - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testNonStartingRowBlackPawnCannotMoveAheadTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - p - - - -" +
"- - - - - - - -" +
"- - - ! - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testStartingRowWhitePawnCannotMoveToInvalidPosition() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! P ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testStartingRowBlackPawnCannotMoveToInvalidPosition() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! p ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testPawnMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .pawn, color: .white), at: location)
let movement = PieceMovementPawn()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testNonStartingRowWhitePawnCannotMoveToInvalidPosition() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! P ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "P", movement: PieceMovementPawn())
}
func testNonStartingRowBlackPawnCannotMoveToInvalidPosition() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! p ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" +
"! ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "p", movement: PieceMovementPawn())
}
func testWhitePawnCannotTakePieceByMovingForwardOneSpace() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- p - - - - - -" +
"- P - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "P", to: "p", movement: PieceMovementPawn()) == false)
}
func testBlackPawnCannotTakePieceByMovingForwardOneSpace() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- p - - - - - -" +
"- P - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "p", to: "P", movement: PieceMovementPawn()) == false)
}
func testWhitePawnCannotTakePieceByMovingForwardTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- p - - - - - -" +
"- - - - - - - -" +
"- P - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "P", to: "p", movement: PieceMovementPawn()) == false)
}
func testBlackPawnCannotTakePieceByMovingForwardTwoSpaces() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- p - - - - - -" +
"- - - - - - - -" +
"- P - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "p", to: "P", movement: PieceMovementPawn()) == false)
}
func testWhitePawnCanTakePieceDiagonallyToLeft() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - p - - - - -" +
"- - - P - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "P", to: "p", movement: PieceMovementPawn()))
}
func testWhitePawnCanTakePieceDiagonallyToRight() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - p - - -" +
"- - - P - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "P", to: "p", movement: PieceMovementPawn()))
}
func testBlackPawnCanTakePieceDiagonallyToLeft() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - p - - - -" +
"- - P - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "p", to: "P", movement: PieceMovementPawn()))
}
func testBlackPawnCanTakePieceDiagonallyToRight() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - p - - - -" +
"- - - - P - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
XCTAssert(canMakeMove(board: board, from: "p", to: "P", movement: PieceMovementPawn()))
}
func testPawnMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - g - - -" +
"- - - P - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("P")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementPawn()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Test pawn En Passant
func makeGame(board: Board, colorToMove: Color) -> Game {
let whitePlayer = Human(color: .white)
let blackPlayer = Human(color: .black)
let game = Game(firstPlayer: whitePlayer, secondPlayer: blackPlayer, board: board, colorToMove: colorToMove)
return game
}
func testPawnEnPassantFlagIsTrueAfterMoveTwoSpaces() {
let board = Board(state: .newGame)
let startLocation = BoardLocation(x: 0, y: 1)
let targetLocation = BoardLocation(x: 0, y: 3)
let game = makeGame(board: board, colorToMove: .white)
guard let whitePlayer = game.currentPlayer as? Human else {
fatalError()
}
do {
try whitePlayer.movePiece(from: startLocation, to: targetLocation)
} catch {
fatalError()
}
guard let piece = game.board.getPiece(at: targetLocation) else {
fatalError()
}
XCTAssertTrue(piece.color == .white)
XCTAssertTrue(piece.type == .pawn)
XCTAssertTrue(piece.canBeTakenByEnPassant == true)
}
func testPawnEnPassantFlagIsFalseAfterMoveOneSpace() {
let board = Board(state: .newGame)
let startLocation = BoardLocation(x: 0, y: 1)
let targetLocation = BoardLocation(x: 0, y: 2)
let game = makeGame(board: board, colorToMove: .white)
guard let whitePlayer = game.currentPlayer as? Human else {
fatalError()
}
do {
try whitePlayer.movePiece(from: startLocation, to: targetLocation)
} catch {
fatalError()
}
guard let piece = game.board.getPiece(at: targetLocation) else {
fatalError()
}
XCTAssertTrue(piece.color == .white)
XCTAssertTrue(piece.type == .pawn)
XCTAssertTrue(piece.canBeTakenByEnPassant == false)
}
func testPawnEnPassantFlagIsResetAfterSubsequentMove() {
// White moves pawn
let board = Board(state: .newGame)
let startLocation = BoardLocation(x: 0, y: 1)
let targetLocation = BoardLocation(x: 0, y: 2)
let game = makeGame(board: board, colorToMove: .white)
guard let whitePlayer = game.currentPlayer as? Human else {
fatalError()
}
do {
try whitePlayer.movePiece(from: startLocation, to: targetLocation)
} catch {
fatalError()
}
// Black moves pawn
guard let blackPlayer = game.currentPlayer as? Human else {
fatalError()
}
guard blackPlayer.color == .black else {
fatalError()
}
do {
try blackPlayer.movePiece(from: BoardLocation(x: 0, y: 6), to: BoardLocation(x: 0, y: 5))
} catch {
fatalError()
}
// Check white pawn flag is false
guard let piece = game.board.getPiece(at: targetLocation) else {
fatalError()
}
XCTAssertTrue(piece.color == .white)
XCTAssertTrue(piece.type == .pawn)
XCTAssertTrue(piece.canBeTakenByEnPassant == false)
}
func testWhitePawnCanTakeOpponentUsingEnPassant() {
let board = ASCIIBoard(pieces: "- - - - - - - g" +
"p - - - - - - -" +
"+ - - - - - - -" +
"* P - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - G" )
let game = makeGame(board: board.board, colorToMove: .black)
let blackPlayer = game.blackPlayer as! Human
let whitePlayer = game.whitePlayer as! Human
// Black move two spaces
do {
try blackPlayer.movePiece(from: board.locationOfCharacter("p"),
to: board.locationOfCharacter("*"))
} catch {
fatalError()
}
// White should be able to take the black pawn using the en passant rule
let pieceMovement = PieceMovementPawn()
XCTAssertTrue(pieceMovement.canPieceMove(from: board.locationOfCharacter("P"),
to: board.locationOfCharacter("+"),
board: game.board),
"Expected white to be able to make en passant move")
do {
try whitePlayer.movePiece(from: board.locationOfCharacter("P"),
to: board.locationOfCharacter("+"))
} catch {
XCTFail("Expected white to be able to execute en passant move")
}
XCTAssertTrue(game.board.getPiece(at: board.locationOfCharacter("*")) == nil,
"Expected black pawn to be removed from board")
}
func testBlackPawnCanTakeOpponentUsingEnPassant() {
let board = ASCIIBoard(pieces: "- - - - - - - g" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"* p - - - - - -" +
"+ - - - - - - -" +
"P - - - - - - -" +
"- - - - - - - G" )
let game = makeGame(board: board.board, colorToMove: .white)
let whitePlayer = game.whitePlayer as! Human
let blackPlayer = game.blackPlayer as! Human
// White move two spaces
do {
try whitePlayer.movePiece(from: board.locationOfCharacter("P"),
to: board.locationOfCharacter("*"))
} catch {
fatalError()
}
// Black should be able to take the white pawn using the en passant rule
let pieceMovement = PieceMovementPawn()
XCTAssertTrue(pieceMovement.canPieceMove(from: board.locationOfCharacter("p"),
to: board.locationOfCharacter("+"),
board: game.board),
"Expected black to be able to make en passant move")
do {
try blackPlayer.movePiece(from: board.locationOfCharacter("p"),
to: board.locationOfCharacter("+"))
} catch {
XCTFail("Expected black to be able to execute en passant move")
}
XCTAssertTrue(game.board.getPiece(at: board.locationOfCharacter("*")) == nil,
"Expected white pawn to be removed from board")
}
func testWhitePawnCannotTakeOpponentUsingEnPassantIfMoveNotMadeImmediately() {
let board = ASCIIBoard(pieces: "- - - - - - - g" +
"p - - - - - - %" +
"+ - - - - - - -" +
"* P - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - &" +
"- - - - - - - G" )
let game = makeGame(board: board.board, colorToMove: .black)
let whitePlayer = game.whitePlayer as! Human
let blackPlayer = game.blackPlayer as! Human
// Black move two spaces
do {
try blackPlayer.movePiece(from: board.locationOfCharacter("p"),
to: board.locationOfCharacter("*"))
} catch {
fatalError()
}
// White moves king
do {
try whitePlayer.movePiece(from: board.locationOfCharacter("G"),
to: board.locationOfCharacter("&"))
} catch {
fatalError()
}
// Black moves king
do {
try blackPlayer.movePiece(from: board.locationOfCharacter("g"),
to: board.locationOfCharacter("%"))
} catch {
fatalError()
}
// White should not be able to take the black pawn using the en passant rule
let pieceMovement = PieceMovementPawn()
XCTAssertFalse(pieceMovement.canPieceMove(from: board.locationOfCharacter("P"),
to: board.locationOfCharacter("+"),
board: game.board))
}
func testBlackPawnCannotTakeOpponentUsingEnPassantIfMoveNotMadeImmediately() {
let board = ASCIIBoard(pieces: "- - - - - - - g" +
"- - - - - - - %" +
"- - - - - - - -" +
"- - - - - - - -" +
"* p - - - - - -" +
"+ - - - - - - -" +
"P - - - - - - &" +
"- - - - - - - G" )
let game = makeGame(board: board.board, colorToMove: .white)
let whitePlayer = game.whitePlayer as! Human
let blackPlayer = game.blackPlayer as! Human
// White moves pawn two spaces
do {
try whitePlayer.movePiece(from: board.locationOfCharacter("P"),
to: board.locationOfCharacter("*"))
} catch {
fatalError()
}
// Black moves king
do {
try blackPlayer.movePiece(from: board.locationOfCharacter("g"),
to: board.locationOfCharacter("%"))
} catch {
fatalError()
}
// White moves king
do {
try whitePlayer.movePiece(from: board.locationOfCharacter("G"),
to: board.locationOfCharacter("&"))
} catch {
fatalError()
}
// Black should not be able to take the white pawn using the en passant rule
let pieceMovement = PieceMovementPawn()
XCTAssertFalse(pieceMovement.canPieceMove(from: board.locationOfCharacter("p"),
to: board.locationOfCharacter("+"),
board: game.board))
}
// MARK: - Queen movement
func testQueenCannotMoveToInvalidPositionFromCentre() {
let board = ASCIIBoard(colors: "! ! ! * ! ! ! *" +
"* ! ! * ! ! * !" +
"! * ! * ! * ! !" +
"! ! * * * ! ! !" +
"* * * W * * * *" +
"! ! * * * ! ! !" +
"! * ! * ! * ! !" +
"* ! ! * ! ! * !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementQueen())
}
func testQueenCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W * * * * * * *" +
"* * ! ! ! ! ! !" +
"* ! * ! ! ! ! !" +
"* ! ! * ! ! ! !" +
"* ! ! ! * ! ! !" +
"* ! ! ! ! * ! !" +
"* ! ! ! ! ! * !" +
"* ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementQueen())
}
func testQueenCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "* * * * * * * W" +
"! ! ! ! ! ! * *" +
"! ! ! ! ! * ! *" +
"! ! ! ! * ! ! *" +
"! ! ! * ! ! ! *" +
"! ! * ! ! ! ! *" +
"! * ! ! ! ! ! *" +
"* ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementQueen())
}
func testQueenCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! *" +
"* ! ! ! ! ! * !" +
"* ! ! ! ! * ! !" +
"* ! ! ! * ! ! !" +
"* ! ! * ! ! ! !" +
"* ! * ! ! ! ! !" +
"* * ! ! ! ! ! !" +
"W * * * * * * *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementQueen())
}
func testQueenCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! *" +
"! * ! ! ! ! ! *" +
"! ! * ! ! ! ! *" +
"! ! ! * ! ! ! *" +
"! ! ! ! * ! ! *" +
"! ! ! ! ! * ! *" +
"! ! ! ! ! ! * *" +
"* * * * * * * W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementQueen())
}
func testQueenMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .queen, color: .white), at: location)
let movement = PieceMovementQueen()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testQueenMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"W - - - B - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementQueen()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testQueenMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"Q - - - g - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("Q")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementQueen()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Rook Movement
func testRookCannotMoveToInvalidPositionFromCentre() {
let board = ASCIIBoard(colors: "! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"* * * W * * * *" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! * ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementRook())
}
func testRookCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W * * * * * * *" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementRook())
}
func testRookCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "* * * * * * * W" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementRook())
}
func testRookCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" +
"W * * * * * * *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementRook())
}
func testRookCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"! ! ! ! ! ! ! *" +
"* * * * * * * W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementRook())
}
func testRookMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .rook, color: .white), at: location)
let movement = PieceMovementRook()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testRookMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"W - - - B - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementRook()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testRookMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"R - - - g - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" )
let pieceIndex = board.indexOfCharacter("R")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementRook()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
// MARK: - Bishop movement
func testBishopCannotMoveToInvalidPositionFromCentre() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"* ! ! ! ! ! * !" +
"! * ! ! ! * ! !" +
"! ! * ! * ! ! !" +
"! ! ! W ! ! ! !" +
"! ! * ! * ! ! !" +
"! * ! ! ! * ! !" +
"* ! ! ! ! ! * !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementBishop())
}
func testBishopCannotMoveToInvalidPositionFromTopLeft() {
let board = ASCIIBoard(colors: "W ! ! ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! * ! ! !" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! ! ! *" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementBishop())
}
func testBishopCannotMoveToInvalidPositionFromTopRight() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! W" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! * ! !" +
"! ! ! ! * ! ! !" +
"! ! ! * ! ! ! !" +
"! ! * ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"* ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementBishop())
}
func testBishopCannotMoveToInvalidPositionFromBottomLeft() {
let board = ASCIIBoard(colors: "! ! ! ! ! ! ! *" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! * ! !" +
"! ! ! ! * ! ! !" +
"! ! ! * ! ! ! !" +
"! ! * ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"W ! ! ! ! ! ! !" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementBishop())
}
func testBishopCannotMoveToInvalidPositionFromBottomRight() {
let board = ASCIIBoard(colors: "* ! ! ! ! ! ! !" +
"! * ! ! ! ! ! !" +
"! ! * ! ! ! ! !" +
"! ! ! * ! ! ! !" +
"! ! ! ! * ! ! !" +
"! ! ! ! ! * ! !" +
"! ! ! ! ! ! * !" +
"! ! ! ! ! ! ! W" )
testBoard(board: board, movingPiece: "W", movement: PieceMovementBishop())
}
func testBishopMovementCannotMoveToCurrentPosition() {
let location = BoardLocation(x: 3, y: 3)
var board = Board(state: .empty)
board.setPiece(Piece(type: .bishop, color: .white), at: location)
let movement = PieceMovementBishop()
XCTAssert(movement.canPieceMove(from: location, to: location, board: board) == false,
"Expected piece could not move to its current position")
}
func testBishopMovementCanTakeOpponent() {
let board = ASCIIBoard(colors: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - B - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- W - - - - - -" )
let whiteIndex = board.indexOfCharacter("W")
let blackIndex = board.indexOfCharacter("B")
let movement = PieceMovementBishop()
XCTAssertTrue(movement.canPieceMove(from: BoardLocation(index: whiteIndex),
to: BoardLocation(index: blackIndex),
board: board.board))
}
func testBishopMovementCannotTakeKing() {
let board = ASCIIBoard(pieces: "- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- - - - g - - -" +
"- - - - - - - -" +
"- - - - - - - -" +
"- B - - - - - -" )
let pieceIndex = board.indexOfCharacter("B")
let kingIndex = board.indexOfCharacter("g")
let movement = PieceMovementBishop()
XCTAssertFalse(movement.canPieceMove(from: BoardLocation(index: pieceIndex),
to: BoardLocation(index: kingIndex),
board: board.board))
}
}
| 42.369022 | 116 | 0.283521 |
2216f525708c98ebeaafdf1ea5904f904dc8cde0 | 372 | //
// UNTableHeaderView.swift
// SwiftUNTest
//
// Created by open-roc on 2020/11/13.
//
import UIKit
class UNTableHeaderView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 17.714286 | 78 | 0.645161 |
e4bb65c5c4dbd9eb9c81d57bb278069218baa204 | 581 | //
// Copyright © 2017 Dailymotion. All rights reserved.
//
import UIKit
final class ShareActivityItemProvider: UIActivityItemProvider {
let title: String
let url: URL
init(title: String, url: URL) {
self.title = title
self.url = url
super.init(placeholderItem: url)
}
override var item: Any {
return url
}
override func activityViewController(_ activityViewController: UIActivityViewController,
subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return title
}
}
| 20.75 | 113 | 0.662651 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.