label
int64 0
1
| text
stringlengths 0
2.8M
|
---|---|
0 | //
// ContentView.swift
// Gumball_StateMachine
//
// Created by Gorker Alp Malazgirt on 11/24/20.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var model: GumballModel
var body: some View {
ScrollView{
VStack(alignment: .leading, spacing: 25) {
HStack {
Text("Current State:")
Text(String(describing: model.currentState.description))
.foregroundColor(Color.red)
.font(.headline)
}
GumballButton(text: String(describing: Action.insertsQuarter.description)) {
model.actionTaken(action: .insertsQuarter)
}
GumballButton(text: String(describing:Action.turnCrank.description)) {
model.actionTaken(action: .turnCrank)
}
GumballButton(text: String(Action.dispenseGumball.description)) {
model.actionTaken(action: .dispenseGumball)
}
GumballButton(text: String(Action.ejectsQuarter.description)) {
model.actionTaken(action: .ejectsQuarter)
}
Image("gumball_sm")
.resizable()
.aspectRatio(contentMode: .fit)
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var model: GumballModel = GumballModel()
static var previews: some View {
ContentView().environmentObject(model)
}
}
}
struct GumballButton: View {
var text: String = ""
var action: () -> Void
var body: some View {
Button(action: action) {
Text(text)
}
.foregroundColor(Color.primary)
.padding()
.background(Color.secondary)
}
}
|
0 | //
// FutureExtensions.swift
// OrgNoteApp
//
// Created by Vijaya Prakash Kandel on 22.10.18.
// Copyright © 2018 com.kandelvijaya. All rights reserved.
//
import Foundation
import Kekka
/// FIXME: This is a pure hack. Nasty one.
fileprivate class _LocalCapture {
static var value: Any? = nil
}
public extension Future {
/// Provides a helper accessor to get the result immediately
/// NOTE:- call this only when you are sure this is a synchronous task
public var resultingValueIfSynchornous: T? {
guard Thread.isMainThread else {
return nil
}
self.then { res in
if Thread.isMainThread {
_LocalCapture.value = res
} else {
NSLog("%@ doesnot work when running asynchronously or other thread than main.", #function)
}
}.execute()
let lastExecutedResult = _LocalCapture.value as? T
defer {
_LocalCapture.value = nil
}
return lastExecutedResult
}
}
|
0 | //
// NSThread+BFKit.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
// MARK: - Global functions -
/**
Runs a block in the main thread
:param: block Block to be executed
*/
public func runOnMainThread(block: () -> ())
{
dispatch_async(dispatch_get_main_queue(), {
block()
})
}
/**
Runs a block in background
:param: block Block to be executed
*/
public func runInBackground(block: () -> ())
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
block()
}
}
/// This extesion adds some useful functions to NSThread
public extension NSThread
{
/**
Exectute a selector asyncronously after a delay
:param: selector Selector to be executed
:param: target Target (Usually "self")
:param: delay Delay to excute the selector
:returns: Return an NSTimer who handle the execution of the selector
*/
public static func callSelectorAsync(selector: Selector, target: AnyObject, delay: NSTimeInterval = 0.0) -> NSTimer
{
return NSTimer.scheduledTimerWithTimeInterval(delay, target: target, selector: selector, userInfo: nil, repeats: false)
}
/**
Exetute a selector
:param: selector Selector to be executed
:param: target Target (Usually "self")
:param: object Object to pass to the selector
:param: delay Delay to excute the selector
*/
public static func callSelector(selector: Selector, target: AnyObject, object: AnyObject? = nil, delay: NSTimeInterval = 0.0)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
NSThread.detachNewThreadSelector(selector, toTarget: target, withObject: object)
})
}
}
|
0 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g {
var d = >Bool
class A {
var f = c<Int
protocol c : A {
func a
struct A : a
|
0 | //
// SalesTaxItemCell.swift
// SalesTaxUSA
//
// Created by Nagarjuna Madamanchi on 08/05/2019.
// Copyright © 2019 Nagarjuna Madamanchi Ltd. All rights reserved.
//
import UIKit
class SalesTaxItemCell: UITableViewCell {
@IBOutlet weak var item: UILabel!
@IBOutlet weak var quantity: UILabel!
@IBOutlet weak var unitprice: UILabel!
@IBOutlet weak var totalprice: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
0 | extension NumberFormatter {
func string(from double: Double) -> String {
string(from: NSNumber(value: double))!
}
#if os(iOS) || os(macOS)
func double(from string: String) -> Double? {
number(from: string)?.doubleValue
}
#endif
}
|
0 | //
// EosioTransactionTests.swift
// EosioSwiftTests
//
// Created by Farid Rahmani on 3/8/19.
// Copyright (c) 2017-2019 block.one and its contributors. All rights reserved.
//
import XCTest
@testable import EosioSwift
@testable import PromiseKit
#if canImport(Combine)
import Combine
#endif
class EosioTransactionTests: XCTestCase {
var transaction = EosioTransaction()
var rpcProvider: RPCProviderMock!
override func setUp() {
transaction = EosioTransaction()
let url = URL(string: "http://example.com")
rpcProvider = RPCProviderMock(endpoint: url!)
rpcProvider.getInfoCalled = false
rpcProvider.getInfoReturnsfailure = false
rpcProvider.getRequiredKeysReturnsfailure = false
transaction.rpcProvider = rpcProvider
transaction.serializationProvider = SerializationProviderMock()
transaction.signatureProvider = SignatureProviderMock()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_prepare_shouldSetExpirationDateCorrectly() {
transaction.prepare { (_) in
XCTAssert(self.transaction.expiration >= Date(timeIntervalSince1970: 0))
}
}
func test_prepare_withRPCProviderNotSet_shouldReturnError() {
transaction.rpcProvider = nil
transaction.prepare { (result) in
if case .success = result {
XCTFail("Succeeded to prepare transaction despite rpc provider not being set")
}
}
}
func test_prepare_shouldCallGetInfoFunctionOnRPCProvider() {
transaction.prepare { (_) in
XCTAssertTrue(self.rpcProvider.getInfoCalled)
}
}
func test_prepare_whenGetInfoMethodOfRPCProviderReturnsSuccess_shouldReturnSuccess() {
transaction.prepare { (result) in
guard case .success = result else {
XCTFail("Succeeded to prepare get_info transaction despite being malformed")
return
}
}
}
func test_prepare_whenGetInfoMethodOfRPCProviderReturnsFailure_shouldReturnFailure() {
rpcProvider.getInfoReturnsfailure = true
transaction.prepare { (result) in
guard case .failure = result else {
XCTFail("Succeeded to prepare get_info transaction despite being malformed")
return
}
}
}
func test_prepare_shouldSetChainIdProperty() {
transaction.prepare { (_) in
XCTAssertEqual(self.transaction.chainId, self.rpcProvider.rpcInfo.chainId)
}
}
func test_prepare_shouldCallGetBlockFunctionOfRPCProvider() {
transaction.prepare { (_) in
XCTAssertTrue(self.rpcProvider.getBlockInfoCalled)
}
}
func test_prepare_shouldCallGetBlockFunctionOfRPCProviderWithCorrectBlockNumber() {
var blockNum = rpcProvider.rpcInfo.lastIrreversibleBlockNum.value
if transaction.config.useLastIrreversible == false {
blockNum = rpcProvider.rpcInfo.headBlockNum.value - UInt64(transaction.config.blocksBehind)
if blockNum <= 0 {
blockNum = 1
}
}
transaction.prepare { (result) in
switch result {
case .failure:
XCTFail("Prepare should not fail")
case .success:
XCTAssertEqual(self.rpcProvider.blockNumberRequested, blockNum)
}
}
}
func test_prepare_shouldCallGetBlockFunctionOfRPCProviderWithCorrectBlockNumberBlocksBehind() {
// Set the transaction to use blocks behind rather than the last irreversible block.
transaction.config.useLastIrreversible = false
var blockNum = rpcProvider.rpcInfo.headBlockNum.value - UInt64(transaction.config.blocksBehind)
if blockNum <= 0 {
blockNum = 1
}
transaction.prepare { (result) in
switch result {
case .failure:
XCTFail("Prepare should not fail")
case .success:
XCTAssertEqual(self.rpcProvider.blockNumberRequested, blockNum)
}
}
}
func test_getBlockAndSetTapos_shouldCallGetBlockFunctionOfRPCProvider() {
transaction.getBlockAndSetTapos(blockNum: 324) { (_) in
XCTAssertTrue(self.rpcProvider.getBlockInfoCalled)
}
}
func test_getBlockAndSetTapos_shouldCallGetBlockFunctionOfRPCProviderWithCorrectBlockNumber() {
let blockNumber: UInt64 = 234
transaction.getBlockAndSetTapos(blockNum: blockNumber) { (_) in
XCTAssertEqual(self.rpcProvider.blockNumberRequested, blockNumber)
}
}
func test_getBlockAndSetTapos_shouldSetRefBlockNum() {
transaction.getBlockAndSetTapos(blockNum: 345) { (_) in
XCTAssertEqual(self.transaction.refBlockNum, UInt16(self.rpcProvider.block.blockNum.value & 0xffff))
}
}
func test_getBlockAndSetTapos_shouldSetRefBlockPrefix() {
transaction.getBlockAndSetTapos(blockNum: 345) { (_) in
XCTAssertEqual(self.transaction.refBlockPrefix, self.rpcProvider.block.refBlockPrefix.value)
}
}
func test_getBlockAndSetTapos_whenRefBlockPrefixAndRefBlockNumAreNotZero_shouldNotCallGetBlockOnRPCProvider() {
transaction.refBlockNum = 9879
transaction.refBlockPrefix = 213
transaction.getBlockAndSetTapos(blockNum: 879) { (_) in
XCTAssertFalse(self.rpcProvider.getBlockInfoCalled)
}
}
func test_getBlockAndSetTapos_whenGetBlockMethodOfRPCProviderReturnsFailure_shouldReturnFailure() {
rpcProvider.getBlockReturnsFailure = true
transaction.getBlockAndSetTapos(blockNum: 8678) { (result) in
guard case .failure = result else {
XCTFail("Failed get_block_info")
return
}
}
}
func test_sign_publicKeys_shouldSucceed() {
transaction.sign(publicKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"]) { (_) in
XCTAssertEqual(self.transaction.signatures, ["jqiti9s31nqr1gu8rlvok38ynum1779l"])
}
}
func test_sign_publicKeys_shouldFail() {
transaction.sign(publicKeys: ["PUB_K1_badkey"]) { (result) in
guard case .failure = result else {
return XCTFail("Succeeded to sign transaction with K1 public key despite having a bad key")
}
}
}
func test_sign_availableKeys_shouldSucceed() {
transaction.sign(availableKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"]) { (_) in
XCTAssertEqual(self.transaction.signatures, ["jqiti9s31nqr1gu8rlvok38ynum1779l"])
}
}
func test_sign_availableKeys_shouldFail() {
rpcProvider.getRequiredKeysReturnsfailure = true
transaction.sign(availableKeys: ["PUB_K1_badkey"]) { (result) in
guard case .failure = result else {
return XCTFail("Succeeded to sign transaction despite having a bad key")
}
}
}
func test_sign_shouldSucceed() {
transaction.sign { (_) in
XCTAssertEqual(self.transaction.signatures, ["jqiti9s31nqr1gu8rlvok38ynum1779l"])
}
}
func test_signAndbroadcast_shouldSucceed() {
transaction.signAndBroadcast { (_) in
XCTAssertEqual(self.transaction.signatures, ["jqiti9s31nqr1gu8rlvok38ynum1779l"])
XCTAssertEqual(self.transaction.transactionId, "mocktransactionid")
}
}
// MARK: - EosioTransaction extension tests using Promises
func test_signAndbroadcastPromise_shouldSucceed() {
let expect = expectation(description: "signAndbroadcastPromise_shouldSucceed")
let promise = self.transaction.signAndBroadcast(.promise)
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_signAndbroadcastPromise_shouldFail() {
let expect = expectation(description: "test_signAndbroadcastPromise_shouldFail")
let signatureProvider = SignatureProviderMock()
signatureProvider.getAvailableKeysShouldReturnFailure = true
self.transaction.signatureProvider = signatureProvider
let promise = self.transaction.signAndBroadcast(.promise)
promise.done { (value) in
print(value)
XCTFail("Should have throw error!")
}.catch { (error) in
print(error)
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_signPromise_shouldSucceed() {
let expect = expectation(description: "signPromise_shouldSucceed")
let promise = self.transaction.sign(.promise)
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_signPromise_shouldFail() {
let expect = expectation(description: "signPromise_shouldFail")
self.transaction.signatureProvider = nil
self.transaction.sign(.promise).done { (value) in
print(value)
XCTFail("Should have throw error!")
}.catch { _ in
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_broadcastPromise_shouldSucceed() {
let expect = expectation(description: "broadcastPromise_shouldSucceed")
firstly {
self.transaction.sign(.promise)
}.then { (value: Bool) -> Promise<Bool> in
print(value)
return self.transaction.broadcast(.promise)
}.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_broadcastPromise_shouldFail() {
let expect = expectation(description: "test_broadcastPromise_shouldFail")
//broadcast should fail as transaction needs to be signed first
firstly {
self.transaction.broadcast(.promise)
}.done { (value) in
print(value)
XCTFail("Should have throw error!")
}.catch { _ in
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_signWithAvailableKeys_shouldSucceed() {
let expect = expectation(description: "test_signWithAvailableKeys_shouldSucceed")
let promise = self.transaction.sign(.promise, availableKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"])
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_signWithAvailableKeys_shouldFail() {
let expect = expectation(description: "test_signWithAvailableKeys_shouldFail")
rpcProvider.getRequiredKeysReturnsfailure = true
let promise = self.transaction.sign(.promise, availableKeys: ["bad_key"])
promise.done { (value) in
print(value)
XCTFail("Should have throw error!)")
}.catch { (error) in
print(error)
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_signWithPublicKeys_shouldSucceed() {
let expect = expectation(description: "test_signWithPublicKeys_shouldSucceed")
let promise = self.transaction.sign(.promise, publicKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"])
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_signWithPublicKeys_shouldFail() {
let expect = expectation(description: "test_signWithPublicKeys_shouldFail")
let promise = self.transaction.sign(.promise, publicKeys: ["bad_key"])
promise.done { (value) in
print(value)
XCTFail("Should have throw error!)")
}.catch { (error) in
print(error)
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_serializeTransaction_shouldSucceed() {
let expect = expectation(description: "test_serializeTransaction_shouldSucceed")
let promise = self.transaction.serializeTransaction(.promise)
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_serializeTransaction_shouldFail() {
let expect = expectation(description: "test_serializeTransaction_shouldFail")
let serializationProvider = SerializationProviderMock()
serializationProvider.serializeTransactionReturnsfailure = true
self.transaction.serializationProvider = serializationProvider
let promise = self.transaction.serializeTransaction(.promise)
promise.done { (value) in
print(value)
XCTFail("Should have throw error!)")
}.catch { (error) in
print(error)
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_prepare_shouldSucceed() {
let expect = expectation(description: "test_prepare_shouldSucceed")
let promise = self.transaction.prepare(.promise)
promise.done { (value) in
print(value)
expect.fulfill()
}.catch { (error) in
XCTFail("Should not have throw error: \(error.localizedDescription)")
}
waitForExpectations(timeout: 10)
}
func test_prepare_shouldFail() {
let expect = expectation(description: "test_prepare_shouldFail")
rpcProvider.getInfoReturnsfailure = true
let promise = self.transaction.prepare(.promise)
promise.done { (value) in
print(value)
XCTFail("Should have throw error!)")
}.catch { (error) in
print(error)
expect.fulfill()
}
waitForExpectations(timeout: 10)
}
func test_add_action_shouldSucceed() {
let transaction = EosioTransaction()
guard let action = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
transaction.add(action: action)
XCTAssertEqual(transaction.actions.count, 1)
XCTAssertEqual(transaction.actions[0].data["from"] as? String, "todd")
}
func test_add_actions_shouldSucceed() {
let transaction = EosioTransaction()
guard let action1 = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
guard let action2 = try? makeTransferAction(from: EosioName("brandon"), to: EosioName("todd")) else { return XCTFail("Invalid Action") }
transaction.add(actions: [action1, action2])
XCTAssertEqual(transaction.actions.count, 2)
XCTAssertEqual(transaction.actions[0].data["from"] as? String, "todd")
XCTAssertEqual(transaction.actions[1].data["from"] as? String, "brandon")
}
func test_add_action_at_index_shouldSucceed() {
let transaction = EosioTransaction()
guard let action1 = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
guard let action2 = try? makeTransferAction(from: EosioName("brandon"), to: EosioName("todd")) else { return XCTFail("Invalid Action") }
transaction.add(action: action1)
transaction.add(action: action2, at: 0)
XCTAssertEqual(transaction.actions.count, 2)
XCTAssertEqual(transaction.actions[0].data["from"] as? String, "brandon")
}
func test_add_context_free_action_shouldSucceed() {
let transaction = EosioTransaction()
guard let action = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
transaction.add(contextFreeAction: action)
XCTAssertEqual(transaction.contextFreeActions.count, 1)
XCTAssertEqual(transaction.contextFreeActions[0].data["from"] as? String, "todd")
}
func test_add_context_free_actions_shouldSucceed() {
let transaction = EosioTransaction()
guard let action1 = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
guard let action2 = try? makeTransferAction(from: EosioName("brandon"), to: EosioName("todd")) else { return XCTFail("Invalid Action") }
transaction.add(contextFreeActions: [action1, action2])
XCTAssertEqual(transaction.contextFreeActions.count, 2)
XCTAssertEqual(transaction.contextFreeActions[0].data["from"] as? String, "todd")
XCTAssertEqual(transaction.contextFreeActions[1].data["from"] as? String, "brandon")
}
func test_add_context_free_action_at_index_shouldSucceed() {
let transaction = EosioTransaction()
guard let action1 = try? makeTransferAction(from: EosioName("todd"), to: EosioName("brandon")) else { return XCTFail("Invalid Action") }
guard let action2 = try? makeTransferAction(from: EosioName("brandon"), to: EosioName("todd")) else { return XCTFail("Invalid Action") }
transaction.add(contextFreeAction: action1)
transaction.add(contextFreeAction: action2, at: 0)
XCTAssertEqual(transaction.contextFreeActions.count, 2)
XCTAssertEqual(transaction.contextFreeActions[0].data["from"] as? String, "brandon")
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension EosioTransactionTests {
// MARK: - EosioTransaction extension tests using Combine Publishers
func test_signAndBroadcastPublisher_shouldSucceed() {
let expect = expectation(description: "signAndBroadcastPublisher_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.signAndBroadcastPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signAndbroadcastPublisher_shouldFail() {
let expect = expectation(description: "test_signAndbroadcastPublisher_shouldFail")
let signatureProvider = SignatureProviderMock()
signatureProvider.getAvailableKeysShouldReturnFailure = true
self.transaction.signatureProvider = signatureProvider
var cancellable: AnyCancellable? = self.transaction.signAndBroadcastPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisher_shouldSucceed() {
let expect = expectation(description: "test_signPublisher_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.signPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisher_shouldFail() {
let expect = expectation(description: "test_signPublisher_shouldFail")
self.transaction.signatureProvider = nil
var cancellable: AnyCancellable? = self.transaction.signPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_broadcastPublisher_shouldSucceed() {
let expect = expectation(description: "test_broadcastPublisher_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.signPublisher()
.flatMap { value -> AnyPublisher<Bool, EosioError> in
print(value)
return self.transaction.broadcastPublisher()
}
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_broadcastPublisher_shouldFail() {
let expect = expectation(description: "test_broadcastPublisher_shouldFail")
//broadcast should fail as transaction needs to be signed first
var cancellable: AnyCancellable? = self.transaction.broadcastPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisherWithAvailableKeys_shouldSucceed() {
let expect = expectation(description: "test_signPublisherWithAvailableKeys_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.signPublisher(availableKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"])
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisherWithAvailableKeys_shouldFail() {
let expect = expectation(description: "test_signPublisherWithAvailableKeys_shouldFail")
rpcProvider.getRequiredKeysReturnsfailure = true
var cancellable: AnyCancellable? = self.transaction.signPublisher(availableKeys: ["bad_key"])
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisherWithPublicKeys_shouldSucceed() {
let expect = expectation(description: "test_signPublisherWithPublicKeys_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.signPublisher(publicKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"])
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_signPublisherWithPublicKeys_shouldFail() {
let expect = expectation(description: "test_signPublisherWithPublicKeys_shouldFail")
var cancellable: AnyCancellable? = self.transaction.signPublisher(publicKeys: ["bad_key"])
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_serializeTransactionPublisher_shouldSucceed() {
let expect = expectation(description: "test_serializeTransactionPublisher_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.serializeTransactionPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_serializeTransactionPublisher_shouldFail() {
let expect = expectation(description: "test_serializeTransactionPublisher_shouldFail")
let serializationProvider = SerializationProviderMock()
serializationProvider.serializeTransactionReturnsfailure = true
self.transaction.serializationProvider = serializationProvider
var cancellable: AnyCancellable? = self.transaction.serializeTransactionPublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_preparePublisher_shouldSucceed() {
let expect = expectation(description: "test_preparePublisher_shouldSucceed")
var cancellable: AnyCancellable? = self.transaction.preparePublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
XCTFail("Should not have thrown an error: \(error.localizedDescription)")
case .finished:
break
}
}, receiveValue: { value in
print(value)
expect.fulfill()
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
func test_preparePublisher_shouldFail() {
let expect = expectation(description: "test_preparePublisher_shouldFail")
rpcProvider.getInfoReturnsfailure = true
var cancellable: AnyCancellable? = self.transaction.preparePublisher()
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print(error)
expect.fulfill()
case .finished:
break
}
}, receiveValue: { _ in
XCTFail("Should have thrown an error!")
})
waitForExpectations(timeout: 10)
cancellable?.cancel()
cancellable = nil
}
}
class RPCProviderMock: EosioRpcProviderProtocol {
var url: URL
required init(endpoint: URL) {
self.url = endpoint
}
var getInfoCalled = false
var getInfoReturnsfailure = false
var getRequiredKeysReturnsfailure = false
var getRawAbiReturnsfailure = false
let rpcInfo = EosioRpcInfoResponse(
serverVersion: "verion",
chainId: "chainId",
headBlockNum: EosioUInt64.uint64(234),
lastIrreversibleBlockNum: EosioUInt64.uint64(2342),
lastIrreversibleBlockId: "lastIrversible",
headBlockId: "headBlockId",
headBlockTime: "2009-01-03T18:15:05.000",
headBlockProducer: "producer",
virtualBlockCpuLimit: EosioUInt64.uint64(234),
virtualBlockNetLimit: EosioUInt64.uint64(234),
blockCpuLimit: EosioUInt64.uint64(334),
blockNetLimit: EosioUInt64.uint64(897),
serverVersionString: "server version")
func getInfoBase(completion: @escaping (EosioResult<EosioRpcInfoResponseProtocol, EosioError>) -> Void) {
getInfoCalled = true
if getInfoReturnsfailure {
let error = EosioError(.getInfoError, reason: "Failed for test propose")
completion(.failure(error))
} else {
completion(.success(rpcInfo))
}
}
var getBlockInfoCalled = false
var getBlockReturnsFailure = false
var blockNumberRequested: UInt64!
let block = EosioRpcBlockInfoResponse(
timestamp: "timestatmp",
producer: "producer",
confirmed: 8,
previous: "prev",
transactionMroot: "root",
actionMroot: "action",
scheduleVersion: 9,
producerSignature: "signature",
id: "klj",
blockNum: EosioUInt64.uint64(89),
refBlockNum: EosioUInt64.uint64(89),
refBlockPrefix: EosioUInt64.uint64(0980)
)
func getBlockInfoBase(requestParameters: EosioRpcBlockInfoRequest, completion: @escaping (EosioResult<EosioRpcBlockInfoResponseProtocol, EosioError>) -> Void) {
getBlockInfoCalled = true
blockNumberRequested = requestParameters.blockNum
let result: EosioResult<EosioRpcBlockInfoResponseProtocol, EosioError>
if getBlockReturnsFailure {
result = EosioResult.failure(EosioError(.getBlockError, reason: "Some reason"))
} else {
result = EosioResult.success(block)
}
completion(result)
}
public func getRawAbiBase(requestParameters: EosioRpcRawAbiRequest, completion: @escaping
(EosioResult<EosioRpcRawAbiResponseProtocol, EosioError>) -> Void) {
var result: EosioResult<EosioRpcRawAbiResponseProtocol, EosioError> =
EosioResult.failure(EosioError(.rpcProviderError, reason: "Abi response conversion error."))
if getRawAbiReturnsfailure {
result = EosioResult.failure(EosioError(.rpcProviderError, reason: "No abis found."))
} else {
let decoder = JSONDecoder()
if let rawAbiResponse = RpcTestConstants.createRawApiResponseJson(account: requestParameters.accountName),
let resp = try? decoder.decode(EosioRpcRawAbiResponse.self, from: rawAbiResponse.data(using: .utf8)!) {
result = EosioResult.success(resp)
}
}
completion(result)
}
public func getRequiredKeysBase(requestParameters: EosioRpcRequiredKeysRequest, completion: @escaping (EosioResult<EosioRpcRequiredKeysResponseProtocol, EosioError>) -> Void) {
let result: EosioResult<EosioRpcRequiredKeysResponseProtocol, EosioError>
if getRequiredKeysReturnsfailure {
result = EosioResult.failure(EosioError(.rpcProviderError, reason: "No required keys found."))
} else {
let requredKeysResponse = EosioRpcRequiredKeysResponse(requiredKeys: ["4j8gu659bcivhjl290igsqx2n622ss6r"])
result = EosioResult.success(requredKeysResponse)
}
completion(result)
}
public func pushTransactionBase(requestParameters: EosioRpcPushTransactionRequest, completion: @escaping (EosioResult<EosioRpcTransactionResponseProtocol, EosioError>) -> Void) {
let pushTransactionResponse = EosioRpcTransactionResponse(transactionId: "mocktransactionid")
let result: EosioResult<EosioRpcTransactionResponseProtocol, EosioError> = EosioResult.success(pushTransactionResponse)
completion(result)
}
func sendTransactionBase(requestParameters: EosioRpcSendTransactionRequest, completion: @escaping (EosioResult<EosioRpcTransactionResponseProtocol, EosioError>) -> Void) {
let response = EosioRpcTransactionResponse(transactionId: "mocktransactionid")
let result: EosioResult<EosioRpcTransactionResponseProtocol, EosioError> = EosioResult.success(response)
completion(result)
}
}
final class SerializationProviderMock: EosioSerializationProviderProtocol {
var error: String?
var serializeTransactionReturnsfailure = false
func serializeAbi(json: String) throws -> String {
return ""
}
func serializeTransaction(json: String) throws -> String {
if serializeTransactionReturnsfailure {
throw EosioError(EosioErrorCode.serializeError, reason: "Test should have expected this failure.")
} else {
return ""
}
}
func serialize(contract: String?, name: String, type: String?, json: String, abi: String) throws -> String {
return ""
}
func deserializeAbi(hex: String) throws -> String {
return ""
}
func deserializeTransaction(hex: String) throws -> String {
return ""
}
func deserialize(contract: String?, name: String, type: String?, hex: String, abi: String) throws -> String {
return ""
}
}
class AbiProviderMockup: EosioAbiProviderProtocol {
var getAbisCalled = false
func getAbis(chainId: String, accounts: [EosioName], completion: @escaping (EosioResult<[EosioName: Data], EosioError>) -> Void) {
getAbisCalled = true
}
var getAbiCalled = false
func getAbi(chainId: String, account: EosioName, completion: @escaping (EosioResult<Data, EosioError>) -> Void) {
getAbiCalled = true
}
}
class SignatureProviderMock: EosioSignatureProviderProtocol {
var getAvailableKeysShouldReturnFailure = false
// The tests will run correctly without this implemented as well showing that
// the default implementation in the protocol is functioning properly.
func signTransaction(request: EosioTransactionSignatureRequest,
prompt: String,
completion: @escaping (EosioTransactionSignatureResponse) -> Void) {
return self.signTransaction(request: request, completion: completion)
}
func signTransaction(request: EosioTransactionSignatureRequest, completion: @escaping (EosioTransactionSignatureResponse) -> Void) {
var transactionSignatureResponse = EosioTransactionSignatureResponse()
if request.publicKeys.contains("4j8gu659bcivhjl290igsqx2n622ss6r") {
var signedTransaction = EosioTransactionSignatureResponse.SignedTransaction()
signedTransaction.signatures = ["jqiti9s31nqr1gu8rlvok38ynum1779l"]
transactionSignatureResponse.signedTransaction = signedTransaction
} else {
transactionSignatureResponse.signedTransaction = nil
transactionSignatureResponse.error = EosioError(EosioErrorCode.signatureProviderError, reason: "Key not available")
}
completion(transactionSignatureResponse)
}
func getAvailableKeys(completion: @escaping (EosioAvailableKeysResponse) -> Void) {
var availableKeysResponse = EosioAvailableKeysResponse()
if getAvailableKeysShouldReturnFailure == true {
availableKeysResponse.error = EosioError(EosioErrorCode.signatureProviderError, reason: "Expected error for testing.")
} else {
availableKeysResponse.keys = ["4j8gu659bcivhjl290igsqx2n622ss6r"]
}
completion(availableKeysResponse)
}
}
struct Transfer: Codable {
var from: EosioName
var to: EosioName // swiftlint:disable:this identifier_name
var quantity: String
var memo: String
}
func makeTransferAction(from: EosioName, to: EosioName) throws -> EosioTransaction.Action { // swiftlint:disable:this identifier_name
let action = try EosioTransaction.Action(
account: EosioName("eosio.token"),
name: EosioName("transfer"),
authorization: [EosioTransaction.Action.Authorization(
actor: from,
permission: EosioName("active"))
],
data: Transfer(
from: from,
to: to,
quantity: "42.0000 SYS",
memo: "Grasshopper Rocks")
)
return action
}
|
0 | //
// UIViewControllerExtension.swift
// RPChatUIKit
//
// Created by rp.wang on 2020/7/14.
// Copyright © 2020 Beijing Physical Fitness Sport Science and Technology Co.,Ltd. All rights reserved.
//
import UIKit
import RPChatDataKit
extension UIViewController {
/// 当前windows上显示的最上层UIViewController
public class func fetchCurrentViewController(baseVC: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
guard let baseVC = baseVC else {
return nil
}
if let nav = baseVC as? UINavigationController {
return fetchCurrentViewController(baseVC: nav.visibleViewController)
}
if let tab = baseVC as? UITabBarController {
return fetchCurrentViewController(baseVC: tab.selectedViewController)
}
if let presented = baseVC.presentedViewController {
return fetchCurrentViewController(baseVC: presented)
}
return baseVC
}
public func hiddenBackTitle() {
view.backgroundColor = .darkModeViewColor
navigationItem.backBarButtonItem = UIBarButtonItem()
navigationItem.backBarButtonItem?.title = ""
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = false
}
}
extension UIViewController {
public func add(asChildViewController viewController: UIViewController,to parentView:UIView) {
// Add Child View Controller
addChild(viewController)
// Add Child View as Subview
parentView.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = parentView.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParent: self)
}
public func remove(asChildViewController viewController: UIViewController) {
// Notify Child View Controller
viewController.willMove(toParent: nil)
// Remove Child View From Superview
viewController.view.removeFromSuperview()
// Notify Child View Controller
viewController.removeFromParent()
}
}
|
0 | //
// ChatCell.swift
// ParseChatApp
//
// Created by paul on 9/22/18.
// Copyright © 2018 PoHung Wang. All rights reserved.
//
import UIKit
class ChatCell: UITableViewCell {
@IBOutlet weak var chatMessage: UILabel!
@IBOutlet weak var username: 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
}
}
|
0 | //
// DJsSearchCell.swift
// InRoZe
//
// Created by Erick Olibo on 23/11/2017.
// Copyright © 2017 Erick Olibo. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class DJsSearchCell: UITableViewCell
{
// properties
static var identifier: String { return String(describing: self) }
var deejay: Artist? { didSet { configureCell() } }
var searchText: String?
// context & container
//var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
var container: NSPersistentContainer? = AppDelegate.appDelegate.persistentContainer
// OUTlets
@IBOutlet weak var deejayName: UILabel!
@IBOutlet weak var gigsMixesList: UILabel!
@IBOutlet weak var followButton: UIButton!
@IBAction func followTouched(_ sender: UIButton) {
pressedFollowed()
}
private func configureCell() {
selectionStyle = .none
clearText()
guard let name = deejay?.name else { return }
//print("[\(tag)] - \(name)")
deejayName.text = name
updateFollowedButton()
}
@objc private func pressedFollowed() {
guard let djID = deejay?.id else { return }
// print("Cell [\(tag)] - pressed: [\(deejay?.name ?? "NOT HERE")]")
if let context = container?.viewContext {
context.perform {
if let artistState = Artist.currentIsFollowedState(for: djID, in: context) {
self.deejay!.isFollowed = !artistState
self.updateFollowedButton()
self.changeState()
}
}
}
}
private func clearText() {
deejayName.text = ""
gigsMixesList.text = ""
}
private func updateFollowedButton() {
guard let currentIsFollow = deejay?.isFollowed else { return }
// Line to change
//deejayName.textColor = currentIsFollow ? .black : Colors.isNotFollowed
deejayNameAttributed()
// define later the number of mixtapes
setSubtitleText(currentIsFollow)
if (currentIsFollow) {
followButton.tintColor = Colors.isFollowed
followButton.setImage((UIImage(named: "2_FollowsFilled")?.withRenderingMode(.alwaysTemplate))!, for: .normal)
followButton.tintColor = Colors.isFollowed
} else {
followButton.tintColor = Colors.isNotFollowed
followButton.setImage((UIImage(named: "2_Follows")?.withRenderingMode(.alwaysTemplate))!, for: .normal)
followButton.tintColor = Colors.isNotFollowed
}
}
// Attribute substring that match searchtext
private func deejayNameAttributed() {
guard let currentIsFollow = deejay?.isFollowed else { return }
guard let text = searchText, text.count > 0 else {
//print("[deejayNameAttributed] - SearchText Count: [NIL]")
deejayName.textColor = currentIsFollow ? .black : Colors.isNotFollowed
return
}
//print("[deejayNameAttributed] - SearchText Count: [\(text.count)]")
attributedDJName()
}
private func attributedDJName() {
//print("attributedDJName")
guard let currentIsFollow = deejay?.isFollowed else { return }
guard let name = deejay?.name else { return }
guard let text = searchText else { return }
let searchTxt = text.uppercased()
var attrName = NSMutableAttributedString(string: name)
attrName = color(attributedString: attrName, color: currentIsFollow ? .black : Colors.isNotFollowed)
let nameLength = attrName.string.count
let searchTxtLength = searchTxt.count
var range = NSRange(location: 0, length: attrName.length)
while (range.location != NSNotFound) {
range = (attrName.string as NSString).range(of: searchTxt, options: [], range: range)
if (range.location != NSNotFound) {
attrName.addAttribute(NSAttributedStringKey.foregroundColor, value: Colors.logoRed, range: NSRange(location: range.location, length: searchTxtLength))
range = NSRange(location: range.location + range.length, length: nameLength - (range.location + range.length))
}
}
deejayName.attributedText = attrName
}
private func changeState() {
guard let djID = deejay?.id else { return }
// Change state of isFollowed
container?.performBackgroundTask{ context in
_ = Artist.changeIsFollowed(for: djID, in: context)
// if (success) {
// print("Changed isFollowed State for id: ", djID)
// } else {
// print("[pressedFollowed] in DJsSearchCell Failed")
// }
}
}
private func setSubtitleText(_ status: Bool) {
gigsMixesList.textColor = status ? .black : Colors.isNotFollowed
if let context = container?.viewContext {
context.perform {
var subtitle = ""
let mixesList = Artist.findPerformingMixtapes(for: self.deejay!, in: context)
let gigsList = Artist.findPerformingEvents(for: self.deejay!, in: context)
let combi = (gig: gigsList?.count ?? 0, mix: mixesList?.count ?? 0)
switch combi {
case (0, 0):
subtitle = ""
case (0, 1):
subtitle = "\(combi.mix) mixtape"
case (0, 2...):
subtitle = "\(combi.mix) mixtapes"
case (1, 0):
subtitle = "\(combi.gig) gig"
case (1, 1):
subtitle = "\(combi.gig) gig - \(combi.mix) mixtape"
case (1, 2...):
subtitle = "\(combi.gig) gig - \(combi.mix) mixtapes"
case (2..., 0):
subtitle = "\(combi.gig) gigs"
case (2..., 1):
subtitle = "\(combi.gig) gigs - \(combi.mix) mixtape"
case (2..., 2...):
subtitle = "\(combi.gig) gigs - \(combi.mix) mixtapes"
case (_, _):
subtitle = ""
}
self.gigsMixesList.text = subtitle
}
}
}
}
|
0 | //
// WaitListPresenterTest.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 27/02/2019.
//
import AptoSDK
@testable import AptoUISDK
import XCTest
class WaitListPresenterTest: XCTestCase {
private var sut: WaitListPresenter! // swiftlint:disable:this implicitly_unwrapped_optional
// Collaborators
private let router = WaitListModuleSpy(serviceLocator: ServiceLocatorFake())
private let interactor = WaitListInteractorFake()
private let dataProvider = ModelDataProvider.provider
private let config = WaitListActionConfiguration(asset: "asset", backgroundImage: "image", backgroundColor: "color",
darkBackgroundColor: "color")
private let analyticsManager = AnalyticsManagerSpy()
private let notificationHandler = NotificationHandlerFake()
override func setUp() {
super.setUp()
sut = WaitListPresenter(config: config, notificationHandler: notificationHandler)
sut.interactor = interactor
sut.router = router
sut.analyticsManager = analyticsManager
}
func testViewLoadedUpdateViewModel() {
// When
sut.viewLoaded()
// Then
XCTAssertEqual(config.asset, sut.viewModel.asset.value)
XCTAssertEqual(config.backgroundImage, sut.viewModel.backgroundImage.value)
XCTAssertEqual(config.backgroundColor, sut.viewModel.backgroundColor.value)
XCTAssertEqual(config.darkBackgroundColor, sut.viewModel.darkBackgroundColor.value)
}
func testViewLoadedObserveApplicationDidBecomeActiveNotification() {
// When
sut.viewLoaded()
// Then
XCTAssertTrue(notificationHandler.addObserverCalled)
XCTAssertTrue(notificationHandler.lastAddObserverObserver === sut)
XCTAssertEqual(UIApplication.didBecomeActiveNotification, notificationHandler.lastAddObserverName)
}
func testWillEnterForegroundNotificationReceivedRefreshDataFromServer() {
// When
notificationHandler.postNotification(UIApplication.didBecomeActiveNotification)
// Then
XCTAssertTrue(interactor.reloadApplicationCalled)
}
func testReloadApplicationFailsDoNotCallRouter() {
// Given
interactor.nextReloadApplicationResult = .failure(BackendError(code: .other))
// When
notificationHandler.postNotification(UIApplication.didBecomeActiveNotification)
// Then
XCTAssertFalse(router.applicationStatusChangedCalled)
}
func testReloadApplicationReturnsWaitListActionDoNotCallRouter() {
// Given
interactor.nextReloadApplicationResult = .success(dataProvider.waitListCardApplication)
// When
notificationHandler.postNotification(UIApplication.didBecomeActiveNotification)
// Then
XCTAssertFalse(router.applicationStatusChangedCalled)
}
func testReloadApplicationReturnsNoWaitListActionCallRouter() {
// Given
interactor.nextReloadApplicationResult = .success(dataProvider.cardApplication)
// When
notificationHandler.postNotification(UIApplication.didBecomeActiveNotification)
// Then
XCTAssertTrue(router.applicationStatusChangedCalled)
XCTAssertTrue(notificationHandler.removeObserverCalled)
XCTAssertTrue(notificationHandler.lastRemoveObserverObserver === sut)
}
func testViewLoadedLogWaitlistEvent() {
// When
sut.viewLoaded()
// Then
XCTAssertTrue(analyticsManager.trackCalled)
XCTAssertEqual(analyticsManager.lastEvent, Event.workflowWaitlist)
}
}
|
0 | import Cocoa
@testable import Element
@testable import Utils
/*Panning controller*/
extension Graph9{
override func scrollWheel(with event:NSEvent) {
//Swift.print("Graph9.scrollWheel()")
//super.scrollWheel(with:event)
timeBar!.adHockScrollWheel(event)
if(event.phase == .changed || event.phase == NSEventPhase(rawValue:0)){
if(hasPanningChanged(&prevRangeScrollChange)){
updateDateText()
}
}
}
}
|
0 | import Foundation
public enum LocationPermissionStatus {
case notDetermined
case denied
case authorized
}
|
0 | //
// MoviesListView.swift
//
// Created by AhmedFitoh on 7/27/21.
//
//
import UIKit
class MoviesListView: UIViewController {
@IBOutlet weak var moviesTableView: UITableView!
// MARK: - VIPER Stack
var presenter: MoviesListViewToPresenterProtocol!
// MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
presenter?.viewDidFinishLoading()
}
private func setupUI(){
setupMoviesTableView()
}
private func setupMoviesTableView(){
moviesTableView.tableFooterView = UIView()
moviesTableView.register(UINib(nibName: "\(MoviesListCell.self)", bundle: nil),
forCellReuseIdentifier: "\(MoviesListCell.self)")
moviesTableView.register(UINib(nibName: "\(LoadingCell.self)", bundle: nil),
forCellReuseIdentifier: "\(LoadingCell.self)")
}
}
// MARK: - TableView delegates
extension MoviesListView: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return presenter?.moviesList.count ?? 0
} else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "\(LoadingCell.self)") as? LoadingCell
return cell ?? UITableViewCell()
}
let cell = tableView.dequeueReusableCell(withIdentifier: "\(MoviesListCell.self)") as? MoviesListCell
if let movie = presenter?.moviesList [indexPath.row] {
cell?.setupCellWith(movie: movie, indexPath: indexPath)
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if presenter?.moviesList.isEmpty == true {
return
}
guard let lastMovieIndex = presenter?.lastMovieIndex else {
return
}
if lastMovieIndex == indexPath.row {
presenter?.requestNewPage()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
return
}
presenter?.userDidSelectMovieAt(index: indexPath.row)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return UITableView.automaticDimension
} else {
return presenter?.requestOnProgress == true ? UITableView.automaticDimension : 0
}
}
}
// MARK: - Presenter to View Protocol
extension MoviesListView: MoviesListPresenterToViewProtocol {
func addCellsAt(rows: ClosedRange<Int>) {
let indexPaths = rows.map {IndexPath(row: $0, section: 0)}
moviesTableView.insertRows(at: indexPaths, with: .bottom)
}
func updateLoadingView(){
if view.window == nil {
return
}
moviesTableView.reloadSections(IndexSet(integer: 1), with: .bottom)
}
}
|
0 | //
// Created by Niil Öhlin on 2018-12-05.
// Copyright (c) 2018 Niil Öhlin. All rights reserved.
//
import Foundation
protocol Testable {
var isSuccessful: Bool { get }
}
extension Bool: Testable {
var isSuccessful: Bool {
self
}
}
extension TestResult: Testable {
var isSuccessful: Bool {
switch self {
case .succeeded:
return true
case .failed:
return false
}
}
}
|
0 | //
// Created by Justin Guedes on 2016/09/11.
//
import Foundation
// swiftlint:disable line_length
extension R {
/**
Applies the function with the argument list and returns the result.
- parameter function: The function to apply with the argument list.
- parameter collection: A collection of values to pass into the function.
- returns: The result of the function with the arguments passed in.
*/
public class func apply<A, B, C: CollectionType where C.Generator.Element == A>(function: (A...) -> B, with collection: C) -> B {
typealias Function = C -> B
let newFunction = unsafeBitCast(function, Function.self)
return newFunction(collection)
}
/**
Applies the function with the argument list and returns the result.
- parameter function: The function to apply with the argument list.
- returns: A curried function that accepts an array and returns the result
of the function with the arguments passed in.
*/
public class func apply<A, B>(function: (A...) -> B) -> (with: [A]) -> B {
return curry(apply)(function)
}
}
// swiftlint:enable line_length
|
0 | //
// UIColourPickerViewAppUITests.swift
// UIColourPickerViewAppUITests
//
// Created by Gerry on 03/05/2019.
// Copyright © 2019 jameschip. All rights reserved.
//
import XCTest
class UIColourPickerViewAppUITests: XCTestCase {
override func 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.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
|
0 | //
// ActionSheets.swift
// Example
//
// Created by Alex.M on 20.05.2022.
//
import SwiftUI
#if os(iOS)
struct ActionSheetView<Content: View>: View {
let content: Content
let topPadding: CGFloat
let fixedHeight: Bool
let bgColor: Color
init(topPadding: CGFloat = 100, fixedHeight: Bool = false, bgColor: Color = .white, @ViewBuilder content: () -> Content) {
self.content = content()
self.topPadding = topPadding
self.fixedHeight = fixedHeight
self.bgColor = bgColor
}
var body: some View {
ZStack {
bgColor.cornerRadius(40, corners: [.topLeft, .topRight])
VStack {
Color.black
.opacity(0.2)
.frame(width: 30, height: 6)
.clipShape(Capsule())
.padding(.top, 15)
.padding(.bottom, 10)
content
.padding(.bottom, 30)
.applyIf(fixedHeight) {
$0.frame(height: UIScreen.main.bounds.height - topPadding)
}
.applyIf(!fixedHeight) {
$0.frame(maxHeight: UIScreen.main.bounds.height - topPadding)
}
}
}
.fixedSize(horizontal: false, vertical: true)
}
}
private struct ActivityView: View {
let emoji: String
let name: String
let isSelected: Bool
var body: some View {
HStack(spacing: 12) {
Text(emoji)
.font(.system(size: 24))
Text(name.uppercased())
.font(.system(size: 13, weight: isSelected ? .regular : .light))
Spacer()
if isSelected {
Image(systemName: "checkmark")
.foregroundColor(Color(hex: "9265F8"))
}
}
.opacity(isSelected ? 1.0 : 0.8)
}
}
struct ActionSheetFirst: View {
var body: some View {
ActionSheetView(bgColor: .white) {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
ActivityView(emoji: "🤼♂️", name: "Sparring", isSelected: true)
ActivityView(emoji: "🧘", name: "Yoga", isSelected: false)
ActivityView(emoji: "🚴", name: "cycling", isSelected: false)
ActivityView(emoji: "🏊", name: "Swimming", isSelected: false)
ActivityView(emoji: "🏄", name: "Surfing", isSelected: false)
ActivityView(emoji: "🤸", name: "Fitness", isSelected: false)
ActivityView(emoji: "⛹️", name: "Basketball", isSelected: true)
ActivityView(emoji: "🏋️", name: "Lifting Weights", isSelected: false)
ActivityView(emoji: "⚽️", name: "Football", isSelected: false)
}
.padding(.horizontal, 20)
}
}
}
}
struct ActionSheetSecond: View {
var body: some View {
ActionSheetView(bgColor: .white) {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Text("Privacy Policy")
.font(.system(size: 24))
Text(Constants.privacyPolicy)
.font(.system(size: 14))
.opacity(0.6)
}
.padding(.horizontal, 24)
}
}
}
}
struct ActionSheets_Previews: PreviewProvider {
static var previews: some View {
ZStack {
Rectangle()
.ignoresSafeArea()
ActionSheetFirst()
}
ZStack {
Rectangle()
.ignoresSafeArea()
ActionSheetSecond()
}
}
}
#endif
|
0 | //
// CGFloat.swift
// jsearch-ios
//
// Created by Ruchira on 2021-09-14.
//
import UIKit
extension CGFloat {
static var smallMargin: CGFloat {
return 8.0
}
static var largeMargin: CGFloat {
return 16.0
}
}
|
0 | //
// SX_PageTitleView.swift
// ShixiUS
//
// Created by Michael 柏 on 2018/9/3.
// Copyright © 2018年 Shixi (Beijing) Tchnology Limited. All rights reserved.
/*
我爱你
在我身上投下的时间与汗水
我都记在心里
刚好此生别无他求
只想永生相伴
慢慢还你
*/
protocol SXPageTitleViewDelegate: NSObjectProtocol {
func selectedIndexInPageTitleView(pageTitleView: SX_PageTitleView, selectedIndex: Int)
}
import UIKit
class SX_PageTitleView: UIView {
var config: SX_PageTitleViewConfig?
//选中标题按钮下标,默认为 0
var selectedIndex: Int = 0 {
didSet {
self.btnDidClick(sender: btnArr[selectedIndex])
}
}
//scrollView
private lazy var scrollView: UIScrollView = {
let scrollV = UIScrollView(frame: self.bounds)
scrollV.showsHorizontalScrollIndicator = false
return scrollV
}()
//底部分隔线
private lazy var line: UIView = {
let lineV = UIView(frame: CGRect(x: 0, y: self.height-1, width: self.width, height: 1))
lineV.backgroundColor = UIColor.colorWithRGB(r: 244, g: 244, b: 244)
return lineV
}()
//指示器
private lazy var indicatorView: UIView = {
let indicatorView = UIView(frame: CGRect(x: 0, y: scrollView.height-3, width: 0, height: 2))
indicatorView.backgroundColor = self.config?.indicatorColor
return indicatorView
}()
//标题数组
var titles = [String]()
//存储标题按钮的数组
private var btnArr = [UIButton]()
//标记按钮下标
private var signBtnIndex: Int = 0
//按钮的总宽度
private var allBtnWidth: CGFloat = 0
private var lastBtn: UIButton?
private var totalExtraWidth: CGFloat = 0
weak var pageTitleViewDelegate: SXPageTitleViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, titles: [String], config: SX_PageTitleViewConfig) {
self.init()
self.backgroundColor = UIColor.white
self.frame = frame
if titles.count < 1 {
NSException(name: NSExceptionName(rawValue: "SXPagingView"), reason: "标题数组元素不能为0", userInfo: nil).raise()
}
self.titles = titles
self.config = config
setupUI()
}
deinit {
print("deinit")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//选中按钮下标初始值
let lastBtn: UIButton = self.btnArr.last!
if lastBtn.tag >= selectedIndex && selectedIndex >= 0 {
btnDidClick(sender: self.btnArr[selectedIndex])
}else {
return
}
}
}
// ========================================================================
// MARK: - Private func
// ========================================================================
extension SX_PageTitleView {
private func setupUI() {
//处理偏移量
let tempView = UIView(frame: CGRect.zero)
self.addSubview(tempView)
self.addSubview(scrollView)
if let showBottomSeparator = self.config?.showBottomSeparator {
if showBottomSeparator {
self.addSubview(line)
}
}
scrollView.insertSubview(indicatorView, at: 0)
setupButtons()
}
private func setupButtons() {
var totalTextWidth: CGFloat = 0
for title in self.titles {
// 计算所有按钮的文字宽度
if let titleFont = self.config?.titleFont {
let tempWidth = title.SX_widthWithString(font: titleFont, size: CGSize(width: 0, height: 0))
totalTextWidth += tempWidth
}
}
// 所有按钮文字宽度 + 按钮之间的间隔
self.allBtnWidth = (self.config?.spacingBetweenButtons)! * (CGFloat)(self.titles.count + 1) + totalTextWidth
let count: CGFloat = CGFloat(self.titles.count)
if self.allBtnWidth <= self.bounds.width {
var btnX: CGFloat = 0
let btnY: CGFloat = 0
let btnH: CGFloat = self.bounds.height
for (index, title) in self.titles.enumerated() {
var btnW: CGFloat = self.bounds.width / count
let tempWidth = title.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize(width: 0, height: 0)) + (self.config?.spacingBetweenButtons)!
if tempWidth > btnW {
let extraWidth = tempWidth - btnW
btnW = tempWidth
totalExtraWidth += extraWidth
}
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
btnX += btnW
btn.tag = index
btn.setTitle(title, for: .normal)
btn.setTitleColor(self.config?.titleColor, for: .normal)
btn.setTitleColor(self.config?.titleSelectedColor, for: .selected)
btn.titleLabel?.font = self.config?.titleFont
btn.addTarget(self, action: #selector(btnDidClick(sender:)), for: .touchUpInside)
scrollView.addSubview(btn)
btnArr.append(btn)
}
scrollView.contentSize = CGSize(width: self.bounds.width + totalExtraWidth, height: 0)
}else {
var btnX: CGFloat = 0
let btnY: CGFloat = 0
let btnH: CGFloat = self.bounds.height
for (index, title) in self.titles.enumerated() {
let btnW = title.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize(width: 0, height: 0)) + (self.config?.spacingBetweenButtons)!
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
btnX += btnW
btn.tag = index
btn.setTitle(title, for: .normal)
btn.setTitleColor(self.config?.titleColor, for: .normal)
btn.setTitleColor(self.config?.titleSelectedColor, for: .selected)
btn.titleLabel?.font = self.config?.titleFont
btn.addTarget(self, action: #selector(btnDidClick(sender:)), for: .touchUpInside)
scrollView.addSubview(btn)
btnArr.append(btn)
}
let scrollViewWidth = scrollView.subviews.last?.frame.maxX
scrollView.contentSize = CGSize(width: scrollViewWidth!, height: 0)
}
}
//滚动标题选中按钮居中
private func scrollCenter(selectedBtn: UIButton) {
var offsetX = selectedBtn.centerX - self.width * 0.5
if offsetX < 0 {
offsetX = 0
}
let maxOffsetX = scrollView.contentSize.width - self.width
if offsetX > maxOffsetX {
offsetX = maxOffsetX
}
scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
//改变按钮的选择状态
private func changeSelectedButton(button: UIButton) {
if self.lastBtn == nil {
button.isSelected = true
self.lastBtn = button
} else if self.lastBtn != nil && self.lastBtn == button {
button.isSelected = true
} else if self.lastBtn != button && self.lastBtn != nil {
self.lastBtn?.isSelected = false
button.isSelected = true
self.lastBtn = button
}
}
}
// ========================================================================
// MARK: - @objc
// ========================================================================
extension SX_PageTitleView {
@objc func btnDidClick(sender:UIButton) {
self.changeSelectedButton(button: sender)
scrollCenter(selectedBtn: sender)
if self.allBtnWidth > self.width || totalExtraWidth > 0 {
scrollCenter(selectedBtn: sender)
}
UIView.animate(withDuration: 0.1) {
self.indicatorView.width = sender.currentTitle!.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize(width: 0, height: 0))
self.indicatorView.center.x = sender.centerX
}
pageTitleViewDelegate?.selectedIndexInPageTitleView(pageTitleView: self, selectedIndex: sender.tag)
self.signBtnIndex = sender.tag
}
}
// ==============================================================
// MARK: - 给外界提供的方法
// ==============================================================
extension SX_PageTitleView {
func setPageTitleView(progress: CGFloat, originalIndex: Int, targetIndex: Int) {
let originalBtn: UIButton = self.btnArr[originalIndex]
let targetBtn: UIButton = self.btnArr[targetIndex]
self.signBtnIndex = targetBtn.tag
scrollCenter(selectedBtn: targetBtn)
//处理指示器的逻辑
if self.allBtnWidth <= self.bounds.width {
if totalExtraWidth > 0 {
indicatorScrollAtScroll(progress: progress, originalBtn: originalBtn, targetBtn: targetBtn)
}else {
indicatorScrollAtStatic(progress: progress, originalBtn: originalBtn, targetBtn: targetBtn)
}
}else {
indicatorScrollAtScroll(progress: progress, originalBtn: originalBtn, targetBtn: targetBtn)
}
}
private func indicatorScrollAtStatic(progress: CGFloat, originalBtn: UIButton, targetBtn: UIButton) {
if (progress >= 0.8) {
changeSelectedButton(button: targetBtn)
}
/// 计算 indicatorView 偏移量
let targetBtnTextWidth: CGFloat = (targetBtn.currentTitle?.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize.zero))!
let targetBtnIndicatorX: CGFloat = targetBtn.frame.maxX - targetBtnTextWidth - 0.5 * (self.width / CGFloat(self.titles.count) - targetBtnTextWidth)
let originalBtnTextWidth: CGFloat = (originalBtn.currentTitle?.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize.zero))!
let originalBtnIndicatorX: CGFloat = originalBtn.frame.maxX - originalBtnTextWidth - 0.5 * (self.width / CGFloat(self.titles.count) - originalBtnTextWidth)
let totalOffsetX: CGFloat = targetBtnIndicatorX - originalBtnIndicatorX
let btnWidth: CGFloat = self.width / CGFloat(self.titles.count)
let targetBtnRightTextX: CGFloat = targetBtn.frame.maxX - 0.5 * (btnWidth - targetBtnTextWidth)
let originalBtnRightTextX: CGFloat = originalBtn.frame.maxX - 0.5 * (btnWidth - originalBtnTextWidth)
let totalRightTextDistance: CGFloat = targetBtnRightTextX - originalBtnRightTextX
let offsetX: CGFloat = totalOffsetX * progress
let distance: CGFloat = progress * (totalRightTextDistance - totalOffsetX)
self.indicatorView.x = originalBtnIndicatorX + offsetX
let tempIndicatorWidth: CGFloat = originalBtnTextWidth + distance
if tempIndicatorWidth >= targetBtn.width {
let moveTotalX: CGFloat = targetBtn.x - originalBtn.x
let moveX: CGFloat = moveTotalX * progress
self.indicatorView.center.x = originalBtn.centerX + moveX
}else{
self.indicatorView.width = tempIndicatorWidth
}
}
private func indicatorScrollAtScroll(progress: CGFloat, originalBtn: UIButton, targetBtn: UIButton) {
if (progress >= 0.8) {
changeSelectedButton(button: targetBtn)
}
let totalOffsetX: CGFloat = targetBtn.x - originalBtn.x
let totalDistance: CGFloat = targetBtn.frame.maxX - originalBtn.frame.maxX
var offsetX: CGFloat = 0
var distance: CGFloat = 0
let targetBtnTextWidth: CGFloat = (targetBtn.currentTitle?.SX_widthWithString(font: (self.config?.titleFont)!, size: CGSize.zero))!
let tempIndicatorWidth: CGFloat = targetBtnTextWidth
if tempIndicatorWidth >= targetBtn.width {
offsetX = totalOffsetX * progress
distance = progress * totalDistance - totalOffsetX
self.indicatorView.x = originalBtn.x + offsetX
self.indicatorView.width = originalBtn.width + distance
}else{
offsetX = totalOffsetX * progress + 0.5 * (self.config?.spacingBetweenButtons)!
distance = progress * (totalDistance - totalOffsetX) - (self.config?.spacingBetweenButtons)!
self.indicatorView.x = originalBtn.x + offsetX;
self.indicatorView.width = originalBtn.width + distance
}
}
}
|
0 | import Foundation
typealias FetchMoviesCompletionHandler = (_ movies: Result<[Movie]>) -> Void
protocol MovieGateway {
func fetchMovies(in page: Int, completion: @escaping FetchMoviesCompletionHandler)
func searchMovies(by name: String, completion: @escaping FetchMoviesCompletionHandler)
}
|
0 | //
// ConversationViewModelListener.swift
// ConversationsApp
//
// Copyright © Twilio, Inc. All rights reserved.
//
import Foundation
protocol ConversationViewModelDelegate: AnyObject {
func onConversationUpdated()
func messageListUpdated(from: [MessageListItemCell], to: [MessageListItemCell])
func onDisplayReactionList(forReaction: String, onMessage: String)
func onMessageLongPressed(_ message: MessageDataListItem)
func onDisplayError(_ error: Error)
func showFullScreenImage(mediaSid: String, imageUrl: URL)
}
|
0 | import EosKit
import RxSwift
class EosAdapter {
private let irreversibleThreshold = 330
private let eosKit: EosKit
private let asset: Asset
init(eosKit: EosKit, token: String, symbol: String, decimal: Int) {
self.eosKit = eosKit
asset = eosKit.register(token: token, symbol: symbol, decimalCount: decimal)
}
private func transactionRecord(fromTransaction transaction: Transaction) -> TransactionRecord {
var type: TransactionType
if transaction.from == eosKit.account {
type = .outgoing
} else if transaction.to == eosKit.account {
type = .incoming
} else {
// EOS funds cannot be sent to self, so this is practically impossible
type = .sentToSelf
}
return TransactionRecord(
uid: transaction.id,
transactionHash: transaction.id,
transactionIndex: 0,
interTransactionIndex: transaction.actionSequence,
type: type,
blockHeight: transaction.blockNumber,
amount: transaction.quantity.amount,
fee: nil,
date: transaction.date,
failed: false,
from: transaction.from,
to: transaction.to,
lockInfo: nil,
conflictingHash: nil,
showRawTransaction: false
)
}
static func validate(account: String) throws {
//regex taken from here: https://github.com/EOSIO/eos/issues/955#issuecomment-351866599
let regex = try! NSRegularExpression(pattern: "^[a-z][a-z1-5\\.]{0,10}([a-z1-5]|^\\.)[a-j1-5]?$")
guard regex.firstMatch(in: account, range: NSRange(location: 0, length: account.count)) != nil else {
throw ValidationError.invalidAccount
}
}
static func validate(privateKey: String) throws {
try EosKit.validate(privateKey: privateKey)
}
}
extension EosAdapter {
enum ValidationError: Error {
case invalidAccount
}
static func clear(except excludedWalletIds: [String]) throws {
try EosKit.clear(exceptFor: excludedWalletIds)
}
}
extension EosAdapter: IAdapter {
func start() {
// started via EosKitManager
}
func stop() {
// stopped via EosKitManager
}
func refresh() {
// refreshed via EosKitManager
}
var debugInfo: String {
return ""
}
}
extension EosAdapter: IBalanceAdapter {
var state: AdapterState {
switch asset.syncState {
case .synced: return .synced
case .notSynced(let error): return .notSynced(error: error.convertedError)
case .syncing: return .syncing(progress: 50, lastBlockDate: nil)
}
}
var stateUpdatedObservable: Observable<Void> {
asset.syncStateObservable.map { _ in () }
}
var balance: Decimal {
asset.balance
}
var balanceUpdatedObservable: Observable<Void> {
asset.balanceObservable.map { _ in () }
}
}
extension EosAdapter: ISendEosAdapter {
var availableBalance: Decimal {
asset.balance
}
func validate(account: String) throws {
try EosAdapter.validate(account: account)
}
func sendSingle(amount: Decimal, account: String, memo: String?) -> Single<Void> {
eosKit.sendSingle(asset: asset, to: account, amount: amount, memo: memo ?? "")
.map { _ in () }
}
}
extension EosAdapter: ITransactionsAdapter {
var confirmationsThreshold: Int {
irreversibleThreshold
}
var lastBlockInfo: LastBlockInfo? {
eosKit.irreversibleBlockHeight.map { LastBlockInfo(height: $0 + irreversibleThreshold, timestamp: nil) }
}
var lastBlockUpdatedObservable: Observable<Void> {
eosKit.irreversibleBlockHeightObservable.map { _ in () }
}
var transactionRecordsObservable: Observable<[TransactionRecord]> {
asset.transactionsObservable.map { [weak self] in
$0.compactMap { self?.transactionRecord(fromTransaction: $0) }
}
}
func transactionsSingle(from: TransactionRecord?, limit: Int) -> Single<[TransactionRecord]> {
eosKit.transactionsSingle(asset: asset, fromActionSequence: from?.interTransactionIndex, limit: limit)
.map { [weak self] transactions -> [TransactionRecord] in
transactions.compactMap { self?.transactionRecord(fromTransaction: $0) }
}
}
func rawTransaction(hash: String) -> String? {
nil
}
}
extension EosAdapter: IDepositAdapter {
var receiveAddress: String {
eosKit.account
}
}
extension EosAdapter.ValidationError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidAccount: return "error.invalid_eos_account".localized
}
}
}
|
0 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/opaque_result_type.swift
// RUN: %target-swift-frontend -enable-experimental-named-opaque-types -enable-implicit-dynamic -disable-availability-checking -emit-ir %t/opaque_result_type.swift | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-NODEBUG %t/opaque_result_type.swift
// rdar://76863553
// UNSUPPORTED: OS=watchos && CPU=x86_64
public protocol O {
func bar()
}
public protocol O2 {
func baz()
}
protocol P {
associatedtype A: O
func poo() -> A
}
protocol Q: AnyObject {
associatedtype B: O, O2
func qoo() -> B
}
extension Int: O, O2 {
public func bar() {}
public func baz() {}
}
@_marker protocol Marker { }
extension Int: Marker { }
extension String: P {
// CHECK-LABEL: @"$sSS18opaque_result_typeE3pooQryFQOMQ" = {{.*}}constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000)
// CHECK-SAME: <i32 0x2_00c4>,
// -- parent context: module, or anon context for function
// CHECK-SAME: @"$s18opaque_result_typeMXM"
// -- mangled underlying type
// CHECK-SAME: @"symbolic Si"
// -- conformance to O
// CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC
// CHECK-SAME: }>
func poo() -> some O {
return 0
}
// CHECK-LABEL: @"$sSS18opaque_result_typeE4propQrvpQOMQ" = {{.*}}constant
public var prop: some O {
return 0
}
// CHECK-LABEL: @"$sSS18opaque_result_typeEQrycipQOMQ" = {{.*}}constant
public subscript() -> some O {
return 0
}
}
// CHECK-LABEL: @"$s18opaque_result_type10globalPropQrvpQOMQ" = {{.*}}constant
public var globalProp: some O {
return 0
}
public class C: P, Q, Marker {
// CHECK-LABEL: @"$s18opaque_result_type1CC3pooQryFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000)
// CHECK-SAME: <i32 0x2_00c4>
// -- parent context: module, or anon context for function
// CHECK-SAME: @"$s18opaque_result_typeMXM"
// -- mangled underlying type
// CHECK-SAME: @"symbolic Si"
// -- conformance to O
// CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC
// CHECK-SAME: }>
func poo() -> some O {
return 0
}
// CHECK-LABEL: @"$s18opaque_result_type1CC3qooQryFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000)
// CHECK-SAME: <i32 0x3_00c4>
// -- parent context: module, or anon context for function
// CHECK-SAME: @"$s18opaque_result_typeMXM"
// -- mangled underlying type
// CHECK-SAME: @"symbolic Si"
// -- conformance to O
// CHECK-SAME: @"get_witness_table Si18opaque_result_type1OHpyHC
// -- conformance to O2
// CHECK-SAME: @"get_witness_table Si18opaque_result_type2O2HpyHC
// CHECK-SAME: }>
func qoo() -> some O & O2 {
return 0
}
}
// CHECK-LABEL: @"$s18opaque_result_type3foo1xQrSS_tFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000)
// CHECK-SAME: <i32 0x2_00c4>
// -- parent context: module, or anon context for function
// CHECK-SAME: @"$s18opaque_result_typeMXM"
// -- mangled underlying type
// CHECK-SAME: @"symbolic SS"
// -- conformance to P
// CHECK-SAME: @"get_witness_table SS18opaque_result_type1PHpyHC
// CHECK-SAME: }>
func foo(x: String) -> some P {
return x
}
// CHECK-LABEL: @"$s18opaque_result_type3bar1yQrAA1CC_tFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), two entries (0x2_0000)
// CHECK-SAME: <i32 0x2_00c4>
// -- parent context: module, or anon context for function
// CHECK-SAME: @"$s18opaque_result_typeMXM"
// -- mangled underlying type
// CHECK-SAME: @"symbolic _____ 18opaque_result_type1CC"
// -- conformance to Q
// CHECK-SAME: @"get_witness_table 18opaque_result_type1CCAA1QHPyHC
// CHECK-SAME: }>
func bar(y: C) -> some Q {
return y
}
// CHECK-LABEL: @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000)
// CHECK-SAME: <i32 0x3_00c4>
// -- parent context: anon context for function
// CHECK-SAME: @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFMXX"
// -- mangled underlying type
// CHECK-SAME: @"symbolic x"
// -- conformance to P
// CHECK-SAME: @"get_witness_table 18opaque_result_type1PRzAA1QRzlxAaB
// -- conformance to Q
// CHECK-SAME: @"get_witness_table 18opaque_result_type1PRzAA1QRzlxAaC
// CHECK-SAME: }>
func baz<T: P & Q>(z: T) -> some P & Q {
return z
}
// CHECK-LABEL: @"$s18opaque_result_type4fizz1zQrx_tAA6MarkerRzAA1PRzAA1QRzlFQOMQ" = {{.*}} constant <{ {{.*}} }> <{
// -- header: opaque type context (0x4), generic (0x80), unique (0x40), three entries (0x3_0000)
// CHECK-SAME: <i32 0x3_00c4>
// -- parent context: anon context for function
// CHECK-SAME: @"$s18opaque_result_type4fizz1zQrx_tAA6MarkerRzAA1PRzAA1QRzlFMXX"
// -- mangled underlying type
// CHECK-SAME: @"symbolic x"
// -- conformance to P
// CHECK-SAME: @"get_witness_table 18opaque_result_type6MarkerRzAA1PRzAA1QRzlxAaCHD2_
// -- conformance to Q
// CHECK-SAME: @"get_witness_table 18opaque_result_type6MarkerRzAA1PRzAA1QRzlxAaDHD3_
// CHECK-SAME: }>
func fizz<T: P & Q & Marker>(z: T) -> some P & Q & Marker {
return z
}
func bauble<T: P & Q & Marker, U: Q>(z: T, u: U) -> [(some P & Q & Marker, (some Q)?)] {
return [(z, u)]
}
// Ensure the local type's opaque descriptor gets emitted.
// CHECK-LABEL: @"$s18opaque_result_type11localOpaqueQryF0D0L_QryFQOMQ" =
func localOpaque() -> some P {
func local() -> some P {
return "local"
}
return local()
}
public func useFoo(x: String, y: C) {
let p = foo(x: x)
let pa = p.poo()
pa.bar()
let q = bar(y: y)
let qb = q.qoo()
qb.bar()
qb.baz()
let pq = baz(z: y)
let pqa = pq.poo()
pqa.bar()
let pqb = pq.qoo()
pqb.bar()
pqb.baz()
let _ = bauble(z: y, u: y)
}
// CHECK-LABEL: define {{.*}} @"$s18opaque_result_type6bauble1z1uSayQr_QR_SgtGx_q_tAA6MarkerRzAA1PRzAA1QRzAaIR_r0_lF"
// CHECK-LABEL: define {{.*}} @"$s18opaque_result_type6useFoo1x1yySS_AA1CCtF"
// CHECK: [[OPAQUE:%.*]] = call {{.*}} @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOMg"
// CHECK: [[CONFORMANCE:%.*]] = call swiftcc i8** @swift_getOpaqueTypeConformance(i8* {{.*}}, %swift.type_descriptor* [[OPAQUE]], [[WORD:i32|i64]] 1)
// CHECK: [[TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s18opaque_result_type3baz1zQrx_tAA1PRzAA1QRzlFQOyAA1CCQo_MD")
// CHECK: call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** [[CONFORMANCE]], %swift.type* [[TYPE]]
// Make sure we can mangle named opaque result types
struct Boom<T: P> {
var prop1: Int = 5
var prop2: <U, V> (U, V) = ("hello", 5)
}
// CHECK-LABEL: define {{.*}} @"$s18opaque_result_type9gimmeBoomypyF
// CHECK: call swiftcc void @"$s18opaque_result_type4BoomV5prop15prop2ACyxGSi_AcEQr_QR_tvpQOyx_Qo__AcEQr_QR_tvpQOyx_Qo0_ttcfcfA0_"
public func gimmeBoom() -> Any {
Boom<String>(prop1: 5)
}
// CHECK-LABEL: define {{.*}} @"$sSS18opaque_result_type1PAA1AAaBP_AA1OPWT"
// CHECK: [[OPAQUE:%.*]] = call {{.*}} @"$sSS18opaque_result_typeE3pooQryFQOMg"
// CHECK: call swiftcc i8** @swift_getOpaqueTypeConformance(i8* {{.*}}, %swift.type_descriptor* [[OPAQUE]], [[WORD]] 1)
// rdar://problem/49585457
protocol R {
associatedtype A: R
func getA() -> A
}
struct Wrapper<T: R>: R {
var wrapped: T
func getA() -> some R {
return wrapped.getA()
}
}
struct X<T: R, U: R>: R {
var t: T
var u: U
func getA() -> some R {
return Wrapper(wrapped: u)
}
}
var globalOProp: some O = 0
public struct OpaqueProps {
static var staticOProp: some O = 0
var instanceOProp: some O = 0
}
// Make sure we don't recurse indefinitely on recursive enums.
public enum RecursiveEnum {
case a(Int)
case b(String)
indirect case c(RecursiveEnum)
}
public enum EnumWithTupleWithOpaqueField {
case a(Int)
case b((OpaqueProps, String))
}
// rdar://86800325 - Make sure we don't crash on result builders.
@resultBuilder
struct Builder {
static func buildBlock(_: Any...) -> Int { 5 }
}
protocol P2 {
associatedtype A: P2
@Builder var builder: A { get }
}
extension Int: P2 {
var builder: some P2 { 5 }
}
struct UseBuilder: P2 {
var builder: some P2 {
let extractedExpr: some P2 = 5
}
}
|
0 | //
// Copyright © 2019 Frollo. 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
/// API Group Report Response
public struct APIGroupReport: Codable {
internal enum CodingKeys: String, CodingKey {
case income
case id
case name
case transactionIDs = "transaction_ids"
case value
}
/// API ID Property
public let id: Int64
/// API Income Property
public let income: Bool
/// API Name Property
public let name: String
/// API Transaction IDs Property
public let transactionIDs: [Int64]
/// API Value Property
public let value: String
}
internal struct APIReportsResponse: Codable {
internal struct Report: Codable {
internal let groups: [APIGroupReport]
internal let income: Bool
internal let date: String
internal let value: String
}
internal let data: [Report]
}
|
0 | //
// JWTMocks.swift
// ff_ios_client_sdkTests
//
// Created by Dusan Juranovic on 3.2.21..
//
struct JWTMocks {
static let stringMock = """
2e7qj23ecjvg4qmgj2qudctfvjab25a4SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
"""
static let token =
"""
"ydqezob1svrgxb36voi7p3by1xrvd60tuSN83JSNOV27g6Dfx5DUpStyvnYflLKjtGAw1sIgrSE"
"""
}
|
0 | //
// SettingNodeView.swift
// fxWallet
//
// Created by Pundix54 on 2021/1/27.
// Copyright © 2021 Andy.Chan 6K. All rights reserved.
//
import Foundation
import UIKit
import WKKit
import RxSwift
import RxCocoa
extension SettingNodesController {
class TopHeaderCell: FxTableViewCell {
override class func height(model: Any?) -> CGFloat { return 28.auto() }
lazy var titleLabel: UILabel = {
let v = UILabel()
v.font = XWallet.Font(ofSize: 16)
v.textColor = COLOR.subtitle
v.autoFont = true
v.backgroundColor = .clear
return v
}()
override func layoutUI() {
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(24.auto())
make.right.equalTo(-51.auto())
make.bottom.equalTo(-8.auto())
make.height.equalTo(20.auto())
}
}
}
class FxChianHeaderCell: TopHeaderCell {
lazy var addButton: UIButton = {
let v = UIButton(type:.system)
v.setImage(IMG("Wallet.Add"), for: .normal)
v.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
v.tintColor = .black
return v
}()
override func layoutUI() {
super.layoutUI()
contentView.addSubview(addButton)
addButton.snp.makeConstraints { (make) in
make.centerY.equalTo(titleLabel.snp.centerY)
make.right.equalToSuperview().inset(24.auto())
make.size.equalTo(CGSize(width: 44, height: 24).auto())
}
}
}
class PanelCell: FxTableViewCell {
lazy var pannel: UIView = {
let v = UIView(COLOR.settingbc)
return v
}()
override class func height(model: Any?) -> CGFloat {
return 14.auto()
}
override func layoutUI() {
contentView.addView(pannel)
contentView.clipsToBounds = true
pannel.snp.makeConstraints { (make) in
make.left.right.equalToSuperview().inset(24.auto())
make.top.bottom.equalToSuperview()
}
}
}
class TopSpaceCell: PanelCell {
override func layoutUI() {
super.layoutUI()
pannel.snp.remakeConstraints { (make) in
make.left.right.equalToSuperview().inset(24.auto())
make.top.equalToSuperview()
make.bottom.equalToSuperview().offset(16.auto())
}
pannel.autoCornerRadius = 16
pannel.layer.maskedCorners = [CACornerMask.layerMinXMinYCorner, CACornerMask.layerMaxXMinYCorner]
}
}
class BotSpaceCell: PanelCell {
override func layoutUI() {
super.layoutUI()
pannel.snp.remakeConstraints { (make) in
make.left.right.equalToSuperview().inset(24.auto())
make.bottom.equalToSuperview()
make.top.equalToSuperview().offset(-16.auto())
}
pannel.autoCornerRadius = 16
pannel.layer.maskedCorners = [CACornerMask.layerMinXMaxYCorner, CACornerMask.layerMaxXMaxYCorner]
}
}
class BaseCell: PanelCell {
override class func height(model: Any?) -> CGFloat {
return 40.auto()
}
lazy var titleLabel: UILabel = {
let v = UILabel()
v.font = XWallet.Font(ofSize: 18)
v.textColor = COLOR.title
v.autoFont = true
v.backgroundColor = .clear
return v
}()
lazy var subTitleLabel: UILabel = {
let v = UILabel()
v.font = XWallet.Font(ofSize: 14)
v.textColor = COLOR.subtitle
v.autoFont = true
v.backgroundColor = .clear
return v
}()
lazy var unAbleLabel: UILabel = {
let v = UILabel()
v.font = XWallet.Font(ofSize: 14)
v.textColor = COLOR.subtitle
v.autoFont = true
v.backgroundColor = .clear
return v
}()
lazy var selectedBt: UIButton = {
let v = UIButton()
v.isUserInteractionEnabled = false
v.setImage(IMG("ic_check"), for: UIControl.State.selected)
v.setImage(UIImage() , for: .normal)
return v
}()
override func layoutUI() {
super.layoutUI()
pannel.addSubviews([titleLabel, subTitleLabel, unAbleLabel,selectedBt])
titleLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalTo(24.auto())
}
subTitleLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalTo(-24.auto())
make.left.equalTo(titleLabel.snp.right).offset(20.auto())
}
unAbleLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalTo(-24.auto())
make.left.equalTo(titleLabel.snp.right).offset(20.auto())
}
selectedBt.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 24, height: 24).auto())
make.centerY.equalToSuperview()
make.right.equalTo(-24.auto())
}
}
}
class SingleCell: BaseCell {
var enableBehavior = BehaviorRelay<Bool>(value: true)
var selectedBehavior = BehaviorRelay<Bool>(value: false)
override class func height(model: Any?) -> CGFloat {
return 50.auto()
}
override func configuration() {
super.configuration()
self.unAbleLabel.text = TR("Setting.Newtrok.Unavailable")
enableBehavior.asDriver().drive(onNext: {[weak self] enable in
self?.titleLabel.alpha = enable ? 1 : 0.5
self?.subTitleLabel.isHidden = enable ? false : true
self?.unAbleLabel.isHidden = enable ? true : false
self?.selectedBt.isHidden = enable ? false : true
}).disposed(by: defaultBag)
selectedBehavior.asDriver().drive(selectedBt.rx.isSelected)
.disposed(by: defaultBag)
}
}
}
|
1 |
import DistributedActorsTestKit
@testable import DistributedCluster
import XCTest
/// Internal testing extensions allowing inspecting behavior internals
extension _Behavior {
/// Similar to canonicalize but counts the nesting depth, be it in setup calls or interceptors.
///
// TODO: Implemented recursively and may stack overflow on insanely deep structures.
// TODO: not all cases are covered, only enough to implement specific tests currently is.
internal func nestingDepth(context: _ActorContext<Message>) throws -> Int {
func nestingDepth0(_ b: _Behavior<Message>) throws -> Int {
switch b.underlying {
case .setup(let onStart):
return try 1 + nestingDepth0(onStart(context))
case .intercept(let inner, _):
return try 1 + nestingDepth0(inner)
case .signalHandling(let onMessage, _),
.signalHandlingAsync(let onMessage, _):
return try 1 + nestingDepth0(onMessage)
case .orElse(let first, let other):
return 1 + max(try nestingDepth0(first), try nestingDepth0(other))
case .suspended(let previousBehavior, _):
return try 1 + nestingDepth0(previousBehavior)
case .same,
.receive, .receiveAsync,
.receiveMessage, .receiveMessageAsync,
.stop, .failed, .unhandled, .ignore, .suspend:
return 1
}
}
return try nestingDepth0(self)
}
/// Pretty prints current behavior, unwrapping and executing any deferred wrappers such as `.setup`.
/// The output is multi line "pretty" string representation of all the nested behaviors, e.g.:
///
/// intercept(interceptor:DistributedCluster.StoppingSupervisor<Swift.String>
// receiveMessage((Function))
// )
// TODO: Implemented recursively and may stack overflow on insanely deep structures.
// TODO: not all cases are covered, only enough to implement specific tests currently is.
internal func prettyFormat(context: _ActorContext<Message>, padWith padding: String = " ") throws -> String {
func prettyFormat0(_ b: _Behavior<Message>, depth: Int) throws -> String {
let pad = String(repeating: padding, count: depth)
switch b.underlying {
case .setup(let onStart):
return "\(pad)setup(\n" +
(try prettyFormat0(onStart(context), depth: depth + 1)) +
"\(pad))\n"
case .intercept(let inner, let interceptor):
return "\(pad)intercept(interceptor:\(interceptor)\n" +
(try prettyFormat0(inner, depth: depth + 1)) +
"\(pad))\n"
case .signalHandling(let handleMessage, let handleSignal):
return "\(pad)signalHandling(handleSignal:\(String(describing: handleSignal))\n" +
(try prettyFormat0(handleMessage, depth: depth + 1)) +
"\(pad))\n"
case .signalHandlingAsync(let handleMessage, let handleSignalAsync):
return "\(pad)signalHandlingAsync(handleSignal:\(String(describing: handleSignalAsync))\n" +
(try prettyFormat0(handleMessage, depth: depth + 1)) +
"\(pad))\n"
case .orElse(let first, let second):
return "\(pad)orElse(\n" +
(try prettyFormat0(first, depth: depth + 1)) +
(try prettyFormat0(second, depth: depth + 1)) +
"\(pad))\n"
case .suspended(let previousBehavior, _):
return "\(pad)suspended(\n" +
(try prettyFormat0(previousBehavior, depth: depth + 1)) +
"\(pad))\n"
case .same,
.receive, .receiveAsync,
.receiveMessage, .receiveMessageAsync,
.stop, .failed, .unhandled, .ignore, .suspend:
return "\(pad)\(b)\n"
}
}
return try prettyFormat0(self, depth: 0)
}
} |
0 | //
// Board+PatternTests.swift
// Life
//
// Created by Brian Partridge on 11/1/15.
// Copyright © 2015 PearTreeLabs. All rights reserved.
//
@testable import Life
import XCTest
class Board_PatternTests: XCTestCase {
// MARK: - Tests
func test_boardByInsertingPattern() {
let pattern = TestPattern()
let board = Board.emptyBoard(Size(width: 10, height: 10))
do {
let newBoard = board.boardByInsertingPattern(pattern, atCoordinate: Coordinate(x: 0, y: 0))
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 0, y: 0)), Cell.Alive)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 1, y: 0)), Cell.Dead)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 0, y: 1)), Cell.Dead)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 1, y: 1)), Cell.Alive)
}
do {
let newBoard = board.boardByInsertingPattern(pattern, atCoordinate: Coordinate(x: 3, y: 4))
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 3, y: 4)), Cell.Alive)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 4, y: 4)), Cell.Dead)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 3, y: 5)), Cell.Dead)
XCTAssertEqual(newBoard.cellAtCoordinate(Coordinate(x: 4, y: 5)), Cell.Alive)
}
}
// MARK: - Fixtures
struct TestPattern: Pattern {
// MARK: - Pattern
var size: Size {
return Size(width: 2, height: 2)
}
var coordinates: [Coordinate] {
return [
Coordinate(x: 0, y: 0),
Coordinate(x: 1, y: 1)
]
}
}
}
|
0 | //
// RGBController.swift
// RGBController
//
// Created by Maxim Orlovsky on 12/16/20.
//
import Foundation
import rgblib
public struct RGBError: Error {
let message: String
init!(_ res: CResult) {
guard res.result.rawValue != 0 else {
return nil
}
let cstr = res.inner.ptr.load(as: UnsafePointer<CChar>.self)
self.message = String(cString: cstr)
}
init!(_ res: CResultString) {
guard res.result.rawValue != 0 else {
return nil
}
self.message = String(cString: res.inner)
}
init(_ msg: String) {
self.message = msg
}
}
public enum Verbosity: UInt8 {
case Error = 0
case Warning = 1
case Info = 2
case Debug = 3
case Trace = 4
}
open class RGB20Controller {
private var client: COpaqueStruct
let network: String
let dataDir: String
public init(network: String = "testnet", electrum: String = "pandora.network:60001", verbosity: Verbosity = .Info) throws {
self.network = network
self.dataDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.path
let client = rgb_node_run(self.dataDir, self.network, electrum, verbosity.rawValue)
guard client.result.rawValue == 0 else {
throw RGBError(client)
}
self.client = client.inner
}
open func createAsset(ticker: String, name: String, description: String? = nil, precision: UInt8 = 8, allocations: String = "[]") throws {
// let allocations = String(data: try JSONEncoder().encode(allocations), encoding: .utf8)
try withUnsafePointer(to: self.client) { client in
let res = rgb_node_fungible_issue(
client,
network,
ticker,
name,
description,
precision,
allocations,
"[]", "null", "null")
guard res.result.rawValue == 0 else {
throw RGBError(res)
}
}
}
open func listAssets() throws -> String {
try withUnsafePointer(to: self.client) { client in
let res = rgb_node_fungible_list_assets(client)
guard res.result.rawValue == 0 else {
throw RGBError(res)
}
guard let jsonString = String(utf8String: res.inner) else {
throw RGBError("Wrong node response (not JSON string)")
}
//try JSONSerialization.jsonObject(with: jsonString.data(using: .utf8), options: [])
return jsonString
}
}
}
|
0 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
// Crash type: memory error ("Invalid read of size 4")
class n{protocol a:d var d={class b:a
|
0 | //
// HMViewController.swift
// HandyMan
//
// Created by Don Johnson on 12/9/15.
// Copyright © 2015 Don Johnson. All rights reserved.
//
import UIKit
class HMViewController: UIViewController {
let configurer = HMControllerConfigurer()
override func viewDidLoad() {
super.viewDidLoad()
// initial configuration
configurer.setUpNavigationController(self.navigationController)
}
}
extension UIViewController: HMBusinessServiceUIDelegate {
// MARK: HMBusinessService UIDelegate
// this seems to be locked and cannot be over written due to being in an extension of the main class ??? static dispatch rules...
func willCallBlockingBusinessService(_ businessService: HMBusinessService) {
self.view.showLoading()
}
func didCompleteBlockingBusinessService(_ businessService: HMBusinessService) {
self.view.hideLoading()
}
}
|
0 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T{
func b:a
func a:a
func a
|
0 | // Copyright 2019 Algorand, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ActionableWarningAlertViewController.swift
import UIKit
class ActionableWarningAlertViewController: BaseViewController {
override var shouldShowNavigationBar: Bool {
return false
}
weak var delegate: ActionableWarningAlertViewControllerDelegate?
private lazy var actionableWarningAlertView = ActionableWarningAlertView()
private let warningAlert: WarningAlert
init(warningAlert: WarningAlert, configuration: ViewControllerConfiguration) {
self.warningAlert = warningAlert
super.init(configuration: configuration)
}
override func configureAppearance() {
super.configureAppearance()
actionableWarningAlertView.bind(WarningAlertViewModel(warningAlert: warningAlert))
view.backgroundColor = Colors.Background.secondary
}
override func linkInteractors() {
super.linkInteractors()
actionableWarningAlertView.delegate = self
}
override func prepareLayout() {
prepareWholeScreenLayoutFor(actionableWarningAlertView)
}
}
extension ActionableWarningAlertViewController: ActionableWarningAlertViewDelegate {
func actionableWarningAlertViewDidTakeAction(_ actionableWarningAlertView: ActionableWarningAlertView) {
delegate?.actionableWarningAlertViewControllerDidTakeAction(self)
}
func actionableWarningAlertViewDidCancel(_ actionableWarningAlertView: ActionableWarningAlertView) {
dismissScreen()
}
}
protocol ActionableWarningAlertViewControllerDelegate: AnyObject {
func actionableWarningAlertViewControllerDidTakeAction(_ actionableWarningAlertViewController: ActionableWarningAlertViewController)
}
|
0 | class Solution {
func accountsMerge(_ accounts: [[String]]) -> [[String]] {
var map = [String:[Int]]()
for (accountIndex,account) in accounts.enumerated() {
for i in 1..<account.count {
let mail = account[i]
var mailToIndexMap = map[mail] ?? [Int]()
mailToIndexMap.append(accountIndex)
map[mail] = mailToIndexMap
}
}
var accountVisited = [Int:Bool]()
func dfs(_ accountIndex: Int,_ mails: [String]) -> [String] {
if accountVisited[accountIndex] == true {
return mails
}
accountVisited[accountIndex] = true
var mails = mails
let account = accounts[accountIndex]
for i in 1..<account.count {
let mail = account[i]
if mails.contains(mail) {
continue
}
mails.append(mail)
for neighborIndex in map[mail] ?? [] {
mails = dfs(neighborIndex, mails)
}
}
return mails
}
var result = [[String]]()
for (accountIndex, account) in accounts.enumerated() {
if accountVisited[accountIndex] == true {
continue
}
let name = account.first!
let emails = dfs(accountIndex, [String]())
var aResult = [String]()
aResult.append(name)
aResult.append(contentsOf: emails.sorted())
result.append(aResult)
}
// print(map)
return result
}
}
let result = Solution().accountsMerge([["John","[email protected]","[email protected]"],["John","[email protected]","[email protected]"],["Mary","[email protected]"],
["John","[email protected]"]
])
print(result)
|
0 | /*
Copyright (c) 2021 Swift Models Generated from JSON powered by http://www.json4swift.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar
*/
import Foundation
struct Matters : Codable {
let name : String?
let agentDetails : AgentDetails?
enum CodingKeys: String, CodingKey {
case name = "name"
case agentDetails = "agent_details"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decodeIfPresent(String.self, forKey: .name)
agentDetails = try values.decodeIfPresent(AgentDetails.self, forKey: .agentDetails)
}
}
|
0 | //
// Count.swift
// SwiftFHIR
//
// Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/Count) on 2017-03-22.
// 2017, SMART Health IT.
//
import Foundation
/**
A measured or measurable amount.
A measured amount (or an amount that can potentially be measured). Note that measured amounts include amounts that are
not precisely quantified, including amounts involving arbitrary units and floating currencies.
*/
open class Count: Quantity {
override open class var resourceType: String {
get { return "Count" }
}
}
|
0 | /*
* Copyright 2015-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import NIOCore
public class CoreClient: Client {
public let requester: RSocketCore.RSocket
// Channel reference to handle channel state
public let channel: Channel
public init(requester: RSocketCore.RSocket, channel: Channel) {
self.requester = requester
self.channel = channel
}
/// This method help to close channel connection.
/// - Returns: EventLoopFuture<Void> as a closeFuture
public func shutdown() -> EventLoopFuture<Void> {
return channel.close()
}
deinit {
// if chanel is active Need to close channel manually
assert(!channel.isActive, "Channel is active close channel manually")
}
}
|
0 | //
//
// Copyright (c) 2018 Marco Conti
//
// 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
private let bitmapSelectionNotificationName = NSNotification.Name(rawValue: "Foil.bitmapSelectionNotification")
private let selectedBitmapsNotificationKey = "Foil.selectedBitmapsNotificationKey"
private let bitmapSpacing: CGFloat = 10
extension ImageLayers: AbstractBitmapContainer {
public func placeNewBitmaps(_ definitions: [BitmapDefinition<Reference>]) {
let width = self.renderedImage.size.width
let bitmaps = definitions.map { (definition: BitmapDefinition<Reference>) -> Bitmap<Reference> in
return Bitmap(
image: definition.image,
centerPosition: NSPoint.zero,
scale: definition.scale,
label: definition.label,
reference: definition.reference)
}
var x: CGFloat = 0
var rows = [[Bitmap<Reference>]]()
var currentRow = [Bitmap<Reference>]()
// line up in rows that are not too wide
bitmaps.forEach { bmp in
x += bmp.size.width / 2
if x > width {
if !currentRow.isEmpty {
rows.append(currentRow)
currentRow = []
x = bmp.halfSize.width + bitmapSpacing
}
}
currentRow.append(bmp.moving(by: NSPoint(x: x, y: 0)))
x += (bmp.size.width / 2) + bitmapSpacing
}
if !currentRow.isEmpty {
rows.append(currentRow)
currentRow = []
}
// decide row height
var y: CGFloat = self.renderedImage.size.height
rows = rows.map { row in
let maxHeight = row.reduce(CGFloat(0)) { max, bmp in
return Swift.max(CGFloat(bmp.size.height), max)
}
y -= maxHeight / 2
let moved = row.map { bmp in
bmp.moving(by: NSPoint(x: 0, y: y))
}
y -= (maxHeight / 2) - bitmapSpacing
return moved
}
// add bitmaps
rows.flatMap { $0 }.forEach {
self.bitmaps.insert($0)
}
}
public func selectBitmapsByReference(_ references: Set<Reference>, extendSelection: Bool) {
let previous = extendSelection ? self.selectedBitmaps : Set()
let selected = self.bitmaps.filter {
guard let ref = $0.reference else { return false }
return references.contains(ref)
}
self.selectedBitmaps = previous.union(selected)
}
public func addBitmapSelectionObserver(block: @escaping (Set<Bitmap<Reference>>) -> ()) -> Any {
return NotificationCenter.default.addObserver(
forName: bitmapSelectionNotificationName,
object: self,
queue: nil)
{ notification in
guard let bitmaps = notification.userInfo?[selectedBitmapsNotificationKey] as? Set<Bitmap<Reference>> else {
return
}
block(bitmaps)
}
}
func notifySelectionChange() {
NotificationCenter.default.post(
name: bitmapSelectionNotificationName,
object: self,
userInfo: [selectedBitmapsNotificationKey: self.selectedBitmaps])
}
}
|
0 | //
// HomeView.swift
// SwiftUI-WeChat
//
// Created by Gesen on 2019/7/20.
// Copyright © 2019 Gesen. All rights reserved.
//
import SwiftUI
struct HomeView : View {
let chats: [Chat] = mock(name: "chats")
var body: some View {
ZStack {
VStack {
Color("light_gray").frame(height: 300) // 下拉时露出的灰色背景
Spacer() // 避免到底部上拉出现背景
}
List {
Group {
SearchEntryView()
ForEach(chats) { chat in
Cell(chat: chat)
}
}
.listRowInsets(.zero)
}
}
.onAppear {
self.root.tabNavigationHidden = false
self.root.tabNavigationTitle = "微信"
self.root.tabNavigationBarTrailingItems = .init(Image(systemName: "plus.circle"))
}
}
@EnvironmentObject var root: RootViewModel
}
#if DEBUG
struct HomeView_Previews : PreviewProvider {
static var previews: some View {
HomeView()
.environmentObject(RootViewModel())
}
}
#endif
private struct Cell: View {
let chat: Chat
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 12) {
Image(chat.icon)
.renderingMode(.original)
.resizable()
.frame(width: 48, height: 48)
.cornerRadius(8)
VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .top) {
Text(chat.name)
.font(.system(size: 16, weight: .regular))
.foregroundColor(.primary)
Spacer()
Text(chat.time)
.font(.system(size: 10))
.foregroundColor(.secondary)
}
Text(chat.desc)
.lineLimit(1)
.font(.system(size: 15))
.foregroundColor(.secondary)
}
}
.padding(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16))
Separator().padding(.leading, 76)
}
.navigationLink(destination: ChatView())
}
}
|
0 | //
// GenericMultipleSelectorRow.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
/// Generic options selector row that allows multiple selection.
public class GenericMultipleSelectorRow<T: Hashable, Cell: CellType, VCType: TypedRowControllerType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == Set<T>, VCType: UIViewController, VCType.RowValue == Set<T>>: Row<Set<T>, Cell>, PresenterRowType {
/// Defines how the view controller will be presented, pushed, etc.
public var presentationMode: PresentationMode<VCType>?
/// Will be called before the presentation occurs.
public var onPresentCallback : ((FormViewController, VCType)->())?
/// Title to be displayed for the options
public var selectorTitle: String?
/// Options from which the user will choose
public var options: [T] {
get { return self.dataProvider?.arrayData?.map({ $0.first! }) ?? [] }
set { self.dataProvider = DataProvider(arrayData: newValue.map({ Set<T>(arrayLiteral: $0) })) }
}
required public init(tag: String?) {
super.init(tag: tag)
presentationMode = .Show(controllerProvider: ControllerProvider.Callback { return VCType() }, completionCallback: { vc in vc.navigationController?.popViewControllerAnimated(true) })
}
public required convenience init(_ tag: String, @noescape _ initializer: (GenericMultipleSelectorRow<T, Cell, VCType> -> ()) = { _ in }) {
self.init(tag:tag)
RowDefaults.rowInitialization["\(self.dynamicType)"]?(self)
initializer(self)
}
/**
Extends `didSelect` method
*/
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
if let presentationMode = presentationMode {
if let controller = presentationMode.createController(){
controller.row = self
if let title = selectorTitle {
controller.title = title
}
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.presentViewController(controller, row: self, presentingViewController: self.cell.formViewController()!)
}
else{
presentationMode.presentViewController(nil, row: self, presentingViewController: self.cell.formViewController()!)
}
}
}
}
/**
Prepares the pushed row setting its title and completion callback.
*/
public override func prepareForSegue(segue: UIStoryboardSegue) {
super.prepareForSegue(segue)
guard let rowVC = segue.destinationViewController as? VCType else {
return
}
if let title = selectorTitle {
rowVC.title = title
}
if let callback = self.presentationMode?.completionHandler{
rowVC.completionCallback = callback
}
onPresentCallback?(cell.formViewController()!, rowVC)
rowVC.row = self
}
}
|
0 | import XCTest
extension CoreTests {
static let __allTests = [
("testFullRun", testFullRun),
("testFullRunWithEmptyOutput", testFullRunWithEmptyOutput),
("testSwiftCArgs", testSwiftCArgs),
]
}
extension FileUtilsTests {
static let __allTests = [
("testBuildLogs", testBuildLogs),
("testInfofileFinder", testInfofileFinder),
("testLastOutput", testLastOutput),
("testSaveOutput", testSaveOutput),
("testTestLogs", testTestLogs),
]
}
extension ProviderTests {
static let __allTests = [
("testIPASize", testIPASize),
("testTargetCount", testTargetCount),
("testTestCount", testTestCount),
("testWarningCount", testWarningCount),
]
}
extension SlackFormatterTests {
static let __allTests = [
("testFormatter", testFormatter),
]
}
#if !os(macOS)
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(CoreTests.__allTests),
testCase(FileUtilsTests.__allTests),
testCase(ProviderTests.__allTests),
testCase(SlackFormatterTests.__allTests),
]
}
#endif
|
0 | //
// String+AffixOperations.swift
//
//
// Created by Christopher Weems on 9/27/21.
//
extension String {
@discardableResult
public mutating func replaceSuffix(_ suffix: String, with newSuffix: String) -> Bool {
guard hasSuffix(suffix) else { return false }
self.removeLast(suffix.count)
self.append(newSuffix)
return true
}
public func replacingSuffix(_ suffix: String, with replacement: String) -> String? {
var result = self
let didReplace = result.replaceSuffix(suffix, with: replacement)
return didReplace ? result : nil
}
}
|
0 | //
// ViewControllerAppearance.swift
// Example
//
// Created by incetro on 6/3/21.
//
import UIKit
// MARK: - ViewControllerAppearance
struct ViewControllerAppearance {
let backgroundColor: UIColor
}
|
0 | public class BlockQuote : BlockElement {
override public func accept(renderer : Renderer) {
renderer.visitBlockQuote(node: self)
}
}
|
0 | //
// ActionSheetItem.swift
// Sheeeeeeeeet
//
// Created by Daniel Saidi on 2017-11-24.
// Copyright © 2017 Daniel Saidi. All rights reserved.
//
/*
This class represents a regular action sheet item, like the
ones used in UIAlertController. It has a title, an optional
value and an optional image. All other item classes inherit
this class.
The default tap behavior of action sheet items is "dismiss",
which means that the action sheet is told that the item was
tapped and is then dismissed. If you don't want the item to
dismiss the action sheet, set `tapBehavior` to `.none`.
An action sheet item's appearance is set by the sheet, when
it is presented. To use custom appearances for single items,
just modify the item's `appearance` property.
*/
import UIKit
open class ActionSheetItem: NSObject {
// MARK: - Initialization
public init(title: String, subtitle: String? = nil, value: Any? = nil, image: UIImage? = nil) {
let appearance = ActionSheetAppearance.standard.item
self.title = title
self.subtitle = subtitle
self.value = value
self.image = image
self.appearance = ActionSheetItemAppearance(copy: appearance)
super.init()
}
// MARK: - Tap Behavior
public enum TapBehavior {
case dismiss, none
}
// MARK: - Properties
open var image: UIImage?
open var subtitle: String?
open var title: String
open var value: Any?
open var appearance: ActionSheetItemAppearance
open var cellStyle: UITableViewCell.CellStyle = .default
open var tapBehavior = TapBehavior.dismiss
// MARK: - Functions
open func applyAppearance(_ appearance: ActionSheetAppearance) {
// self.appearance = ActionSheetItemAppearance(copy: appearance.item)
}
open func applyAppearance(to cell: UITableViewCell) {
cell.imageView?.image = image
cell.textLabel?.text = title
cell.textLabel?.numberOfLines = 0
cell.selectionStyle = .default
cell.separatorInset = appearance.separatorInsets
cell.tintColor = appearance.tintColor
cell.textLabel?.textAlignment = .center
cell.textLabel?.textColor = appearance.textColor
cell.textLabel?.font = appearance.font
cell.detailTextLabel?.text = subtitle
cell.detailTextLabel?.font = appearance.subtitleFont
cell.detailTextLabel?.textColor = appearance.subtitleTextColor
}
open func cell(for tableView: UITableView) -> UITableViewCell {
let id = type(of: self).className
let cell = tableView.dequeueReusableCell(withIdentifier: id) as? ActionSheetItemCell
?? ActionSheetItemCell(style: cellStyle, reuseIdentifier: id)
applyAppearance(to: cell)
return cell
}
open func handleTap(in actionSheet: ActionSheet?) {}
open func handleTap(in cell: UITableViewCell?) {}
}
extension ActionSheetItem {
func multiHeightSheetItem(size:CGSize) {
let nsString = title as NSString
let height = nsString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : self.appearance.font ?? UIFont.systemFont(ofSize: 17)], context: nil).height + 10
let stadarHeight = ActionSheetItemAppearance.init().height
self.appearance.height = height > stadarHeight ? height : ActionSheetItemAppearance.init().height
}
}
|
0 | //
// LPButton.swift
// LPInputBarAccessoryView
//
// Created by pengli on 2019/8/9.
// Copyright © 2019 pengli. All rights reserved.
//
import UIKit
class LPButton: UIButton {
deinit {
#if DEBUG
print("\(self) release memory.")
#endif
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(_ image: UIImage?, _ selImage: UIImage? = nil, target: Any?, action: Selector) {
super.init(frame: .zero)
self.setImage(image, for: .normal)
self.addTarget(target, action: action, for: .touchUpInside)
}
}
|
0 | ////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Viacom Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////
import UIKit
public typealias RouteHandler = (_ req: Request) -> Void
open class Router {
fileprivate var orderedRoutes = [Route]()
fileprivate var routes = [Route: RouteHandler]()
public init() {}
/**
Binds a route to a router
- parameter aRoute: A string reprsentation of the route. It can include url params, for example id in /video/:id
- parameter callback: Triggered when a route is matched
*/
open func bind(_ aRoute: String, callback: @escaping RouteHandler) {
do {
let route = try Route(aRoute: aRoute)
orderedRoutes.append(route)
routes[route] = callback
} catch let error as Route.RegexResult {
print(error.debugDescription)
} catch {
fatalError("[\(aRoute)] unknown bind error")
}
}
/**
Matches an incoming URL to a route present in the router. Returns nil if none are matched.
- parameter url: An URL of an incoming request to the router
- returns: The matched route or nil
*/
open func match(_ url: URL) -> Route? {
guard let routeComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
// form the host/path url
let host = routeComponents.host.flatMap({"/\($0)"}) ?? ""
let path = routeComponents.path
let routeToMatch = "\(host)\(path)"
let queryParams = routeComponents.queryItems
var urlParams = [URLQueryItem]()
// match the route!
for route in orderedRoutes {
guard let pattern = route.routePattern else {
continue
}
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
let matches = regex.matches(in: routeToMatch, options: [],
range: NSMakeRange(0, routeToMatch.characters.count))
// check if routeToMatch has matched
if matches.count > 0 {
let match = matches[0]
// gather url params
for i in 1 ..< match.numberOfRanges {
let name = route.urlParamKeys[i-1]
let value = (routeToMatch as NSString).substring(with: match.range(at: i))
urlParams.append(URLQueryItem(name: name, value: value))
}
// fire callback
if let callback = routes[route] {
callback(Request(aRoute: route, urlParams: urlParams, queryParams: queryParams))
}
// return route that was matched
return route
}
}
// nothing matched
return nil
}
}
|
0 | //
// PieItemView.swift
// SmartTeaGarden
//
// Created by jiaerdong on 2017/3/14.
// Copyright © 2017年 tianciqinyun. All rights reserved.
//
import UIKit
class PieItemView: UIView {
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var waveIndicator: WaveLoadingIndicator!
override func awakeFromNib() {
super.awakeFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialFromXib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialFromXib()
}
convenience init() {
self.init(frame: CGRect.zero)
}
func initialFromXib() {
let contentView = Bundle.main.loadNibNamed(
"PieItemView", owner: self, options: nil)?.first as! UIView
contentView.frame = bounds
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(contentView)
}
}
|
0 | //
// IndexedSet.swift
// CollectionView
//
// Created by Wes Byrne on 1/20/17.
// Copyright © 2017 Noun Project. All rights reserved.
//
import Foundation
public struct IndexedSet<Index: Hashable, Value: Hashable> : Sequence, CustomDebugStringConvertible, ExpressibleByDictionaryLiteral {
// var table = MapTab
fileprivate var byValue = [Value:Index]()
fileprivate var byIndex = [Index:Value]()
// fileprivate var _sequenced = OrderedSet<Value>()
public var indexes : [Index] {
return Array(byIndex.keys)
}
public var indexSet : Set<Index> {
return Set(byIndex.keys)
}
public var dictionary : [Index:Value] {
return byIndex
}
public var values : [Value] {
return Array(byIndex.values)
}
public var valuesSet : Set<Value> {
return Set(byIndex.values)
}
public var count : Int {
return byValue.count
}
public var isEmpty : Bool {
return byValue.isEmpty
}
public func value(for index: Index) -> Value? {
return byIndex[index]
}
public func index(of value: Value) -> Index? {
return byValue[value]
}
public init() { }
public init(dictionaryLiteral elements: (Index, Value)...) {
for e in elements {
self.insert(e.1, for: e.0)
}
}
public init(_ dictionary: Dictionary<Index, Value>) {
for e in dictionary {
self.insert(e.1, for: e.0)
}
}
public subscript(index: Index) -> Value? {
get { return value(for: index) }
set(newValue) {
if let v = newValue { insert(v, for: index) }
else { _ = removeValue(for: index) }
}
}
public var debugDescription: String {
var str = "\(type(of: self)) [\n"
for i in self {
str += "\(i.index) : \(i.value)\n"
}
str += "]"
return str
}
public func contains(_ object: Value) -> Bool {
return byValue[object] != nil
}
public func containsValue(for index: Index) -> Bool {
return byIndex[index] != nil
}
/**
Set the value-index pair removing any existing entries for either
- Parameter value: The value
- Parameter index: The index
*/
public mutating func set(_ value: Value, for index: Index) {
self.removeValue(for: index)
self.remove(value)
byValue[value] = index
byIndex[index] = value
}
/**
Insert value for the given index if the value does not exist.
- Parameter value: A value
- Parameter index: An index
*/
public mutating func insert(_ value: Value, for index: Index) {
self.set(value, for: index)
// guard byValue[value] == nil else { return }
// if let object = self.byIndex.removeValue(forKey: index) {
// byValue.removeValue(forKey: object)
// }
//
// byValue[value] = index
// byIndex[index] = value
// assert(byIndex.count == byValue.count)
}
@discardableResult public mutating func removeValue(for index: Index) -> Value? {
guard let value = byIndex.removeValue(forKey: index) else {
return nil
}
byValue.removeValue(forKey: value)
return value
}
@discardableResult public mutating func remove(_ value: Value) -> Index? {
guard let index = byValue.removeValue(forKey: value) else {
return nil
}
byIndex.removeValue(forKey: index)
return index
}
public mutating func removeAll() {
byValue.removeAll()
byIndex.removeAll()
}
public typealias Iterator = AnyIterator<(index: Index, value: Value)>
public func makeIterator() -> Iterator {
var it = byIndex.makeIterator()
return AnyIterator {
if let val = it.next() {
return (val.key, val.value)
}
return nil
}
}
}
extension IndexedSet {
func union(_ other: IndexedSet) -> IndexedSet {
var new = self
for e in other.byIndex {
new.insert(e.value, for: e.key)
}
return new
}
}
extension Array where Element:Hashable {
public var indexedSet : IndexedSet<Int, Element> {
var set = IndexedSet<Int, Element>()
for (idx, v) in self.enumerated() {
set.insert(v, for: idx)
}
return set
}
}
extension Collection where Iterator.Element:Hashable {
public var indexedSet : IndexedSet<Int, Iterator.Element> {
var set = IndexedSet<Int, Iterator.Element>()
for (idx, v) in self.enumerated() {
set.insert(v, for: idx)
}
return set
}
}
extension IndexedSet where Index:Comparable {
var orderedIndexes : [Index] {
return self.byIndex.keys.sorted()
}
func ordered() -> [Iterator.Element] {
return self.makeIterator().sorted { (a, b) -> Bool in
return a.index < b.index
}
}
func orderedLog() -> String {
var str = "\(type(of: self)) [\n"
for i in self.ordered() {
str += "\(i.index) : \(i.value)\n"
}
str += "]"
return str
}
var orderedValues : [Value] {
let sorted = self.byIndex.sorted(by: { (v1, v2) -> Bool in
return v1.key < v2.key
})
var res = [Value]()
for element in sorted {
res.append(element.value)
}
return res
}
}
|
0 | //
// PrototypeByXcode12App.swift
// PrototypeByXcode12
//
// Created by TakahiroTsuchiya on 2020/09/20.
//
import SwiftUI
@main
struct PrototypeByXcode12App: App {
var body: some Scene {
WindowGroup {
RootView()
}
}
}
|
0 | import Foundation
import XCTest
@testable import Models
final class PBXShellScriptBuildPhaseSpec: XCTestCase {
var subject: PBXShellScriptBuildPhase!
override func setUp() {
super.setUp()
self.subject = PBXShellScriptBuildPhase(reference: "reference", files: ["file"], inputPaths: ["input"], outputPaths: ["output"], shellPath: "shell", shellScript: "script")
}
func test_init_initializesTheBuildPhaseWithTheCorrectValues() {
XCTAssertEqual(subject.reference, "reference")
XCTAssertEqual(subject.files, ["file"])
XCTAssertEqual(subject.inputPaths, ["input"])
XCTAssertEqual(subject.outputPaths, ["output"])
XCTAssertEqual(subject.shellPath, "shell")
XCTAssertEqual(subject.shellScript, "script")
}
func test_returnsTheCorrectIsa() {
XCTAssertEqual(PBXShellScriptBuildPhase.isa, "PBXShellScriptBuildPhase")
}
func test_initFails_whenTheFilesAreMissing() {
var dictionary = testDictionary()
dictionary.removeValue(forKey: "files")
do {
_ = try PBXShellScriptBuildPhase(reference: "reference", dictionary: dictionary)
XCTAssertTrue(false, "Expected to throw an error but it didnt'")
} catch {}
}
func test_initFails_whenShellPathIsMissing() {
var dictionary = testDictionary()
dictionary.removeValue(forKey: "shellPath")
do {
_ = try PBXShellScriptBuildPhase(reference: "reference", dictionary: dictionary)
XCTAssertTrue(false, "Expected to throw an error but it didnt'")
} catch {}
}
func test_addingFile_returnsABuildPhaseWithTheFileAdded() {
let got = subject.adding(file: "file2")
XCTAssertTrue(got.files.contains("file2"))
}
func test_removingFile_returnsABuildPhaseWithTheFileRemoved() {
let got = subject.removing(file: "file")
XCTAssertFalse(got.files.contains("file"))
}
func test_addingInputFile_returnsABuildPhaseAddingTheInputFile() {
let got = subject.adding(inputPath: "input2")
XCTAssertTrue(got.inputPaths.contains("input2"))
}
func test_removingInputFile_returnsABuildPhaseRemovingTheInputFile() {
let got = subject.removing(inputPath: "input")
XCTAssertFalse(got.inputPaths.contains("input"))
}
func test_addingOutputFile_returnsABuildPhaseAddingTheOutputFile() {
let got = subject.adding(outputPath: "output2")
XCTAssertTrue(got.outputPaths.contains("output2"))
}
func test_removingOutputFile_returnsABuildPhaseRemovingTheOutputFile() {
let got = subject.removing(outputPath: "output")
XCTAssertFalse(got.outputPaths.contains("output"))
}
func test_equals_returnsTheCorrectValue() {
let one = PBXShellScriptBuildPhase(reference: "reference", files: ["file"], inputPaths: ["input"], outputPaths: ["output"], shellPath: "shell", shellScript: "script")
let another = PBXShellScriptBuildPhase(reference: "reference", files: ["file"], inputPaths: ["input"], outputPaths: ["output"], shellPath: "shell", shellScript: "script")
XCTAssertEqual(one, another)
}
func test_hashValue_returnsTheReferenceHashValue() {
XCTAssertEqual(subject.hashValue, subject.reference.hashValue)
}
private func testDictionary() -> [String: Any] {
return [
"files": ["files"],
"inputPaths": ["input"],
"outputPaths": ["output"],
"shellPath": "shellPath",
"shellScript": "shellScript"
]
}
}
|
0 | //
// AKTimePitch.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// AudioKit version of Apple's TimePitch Audio Unit
///
open class AKTimePitch: AKNode, AKToggleable, AKInput {
fileprivate let timePitchAU = AVAudioUnitTimePitch()
/// Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
@objc open dynamic var rate: Double = 1.0 {
didSet {
rate = (0.031_25...32).clamp(rate)
timePitchAU.rate = Float(rate)
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return !timePitchAU.bypass
}
/// Pitch (Cents) ranges from -2400 to 2400 (Default: 0.0)
@objc open dynamic var pitch: Double = 0.0 {
didSet {
pitch = (-2_400...2_400).clamp(pitch)
timePitchAU.pitch = Float(pitch)
}
}
/// Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
@objc open dynamic var overlap: Double = 8.0 {
didSet {
overlap = (3...32).clamp(overlap)
timePitchAU.overlap = Float(overlap)
}
}
/// Initialize the time pitch node
///
/// - Parameters:
/// - input: Input node to process
/// - rate: Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
/// - pitch: Pitch (Cents) ranges from -2400 to 2400 (Default: 1.0)
/// - overlap: Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
///
@objc public init(
_ input: AKNode? = nil,
rate: Double = 1.0,
pitch: Double = 0.0,
overlap: Double = 8.0) {
self.rate = rate
self.pitch = pitch
self.overlap = overlap
super.init()
self.avAudioNode = timePitchAU
AudioKit.engine.attach(self.avAudioNode)
input?.connect(to: self)
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
timePitchAU.bypass = false
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
timePitchAU.bypass = true
}
}
|
1 |
// RUN: not %target-swift-frontend %s -typecheck
let a{{func a<g{{func b{func b{y=C |
0 | //
// WebViewController+FinishLine.swift
// MultiTabBrowserApp
//
// Created by King on 2019/12/27.
// Copyright © 2019 AJB. All rights reserved.
//
/// Finishline.com autofill
import Foundation
import UIKit
import WebKit
extension WebViewController {
func autofillFinishLine(_ webView: WKWebView) {
if let url = webView.url?.absoluteString {
if url.contains("/checkout/") {
injectFinishLineCheckout(webView)
}
}
}
// auto fill for delivery information
func injectFinishLineCheckout(_ webView: WKWebView) {
guard let currentProfile = selectedProfile else {
return
}
let expValues = currentProfile.expDate.split(separator: "/")
let expMonth = expValues[0]
let expYear = expValues.count == 2 ? "20\(expValues[1])" : "2020"
let phone = currentProfile.phone.replacingOccurrences(of: "+1", with: "")
let formatedPhoneNumber = phone.formattedNumber(pattern: "###-###-####")
let injectString = """
javascript:(function() {
try {
function autofillSelect(selector, value) {
if (selector && value) {
var elements = document.querySelectorAll(selector);
if (elements && elements[0]) {
elements[0].value = value;
elements[0].dispatchEvent(new Event('change', { bubbles: true}));
}
}
};
var objs = [
{property: '#firstName', value: '\(currentProfile.firstName)'},
{property: '#shippingLastName', value: '\(currentProfile.lastName)'},
{property: '#shippingAddress1', value: '\(currentProfile.addressOne)'},
{property: '#shippingZip', value: '\(currentProfile.zipCode)'},
{property: '#shippingCity', value: '\(currentProfile.city)'},
{property: '#shippingPhone', value: '\(formatedPhoneNumber)'},
{property: '#email', value: '\(currentProfile.email)'},
{property: '#billingCardNumber', value: '\(currentProfile.cardNumber)'},
{property: '#billingSecurityCode', value: '\(currentProfile.cvv)'}
];
if ("\(currentProfile.addressTwo)") {
objs.push({property: '#shippingAddress2', value: '\(currentProfile.addressTwo)'});
}
objs.forEach(function(obj) {
var setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
var elements = document.querySelectorAll(obj.property);
if (elements && elements[0]) {
setter.call(elements[0], obj.value);
elements[0].dispatchEvent(new Event('input', {bubbles:true}));
elements[0].dispatchEvent(new Event('blur', {bubbles:true}));
}
});
autofillSelect('#shippingState', "\(currentProfile.stateCode)");
autofillSelect('#billingExpirationMonth', "\(expMonth)");
autofillSelect('#billingExpirationYear', "\(expYear)");
} catch (e) {
window.errStash = e;
}
})();
"""
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
webView.evaluateJavaScript(injectString) { (result, error) in
print(error ?? "result")
}
}
}
}
|
0 | //
// Locations.swift
// ZeroTrust FW
//
// Created by Alex Lisle on 3/18/20.
// Copyright © 2020 Alex Lisle. All rights reserved.
//
import Foundation
import Logging
class Locations : ObservableObject, EventListener {
private let logger = Logger(label: "com.zerotrust.client.States.Locations")
private let map : Map = Map.shared
private var shadowPoints : [UUID : MapPoint] = [:]
@Published var points : [MapPoint] = []
init() {
EventManager.shared.addListener(type: .OpenedConnection, listener: self)
EventManager.shared.addListener(type: .ClosedConnection, listener: self)
self.updatePublishedValues()
}
private func updatePublishedValues() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [ weak self ] in
guard let self = self else {
return
}
var points : Set<MapPoint> = []
Array(self.shadowPoints.values).forEach {
if points.contains($0) {
let point = MapPoint(
latitude: $0.latitude,
longitude: $0.longitude,
translated: $0.translated,
count: $0.count + 1
)
points.insert(point)
} else {
points.insert($0)
}
}
self.points = Array(points).sorted(by: { (lhs, rhs) -> Bool in
return lhs.count > rhs.count
})
self.updatePublishedValues()
}
}
func eventTriggered(event: BaseEvent) {
switch event.type {
case .OpenedConnection:
let event = event as! OpenedConnectionEvent
// This is a private network, we can't get the location.
if event.connection.remoteSocket.address.isPrivate {
return
}
if let location = event.connection.location {
guard let latitude = location.latitude else {
return
}
guard let longitude = location.longitude else {
return
}
let point = map.createPoint(latitude: Double(latitude), longitude: Double(longitude))
self.shadowPoints.updateValue(point, forKey: event.connection.tag)
}
case .ClosedConnection:
let event = event as! ClosedConnectionEvent
self.shadowPoints.removeValue(forKey: event.connection.tag)
default:
return
}
}
}
|
0 | public class DateFormatter {
private static let hourInSeconds:Double = 1 * 60 * 60
public class func formatSeconds(totalSeconds: NSTimeInterval) -> String {
let date = NSDate(timeIntervalSince1970: totalSeconds)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = totalSeconds < hourInSeconds ? "mm:ss" : "HH:mm:ss"
return formatter.stringFromDate(date)
}
} |
0 | //
// Entity+DummyDataProvider.swift
// APITesting
//
// Created by Susmita Horrow on 04/04/18.
// Copyright © 2018 hsusmita. All rights reserved.
//
import Foundation
extension Restaurant: DummyDataProvider {
static var dummyObject: Restaurant {
return dummyCollection.first!
}
static var dummyCollection: [Restaurant] {
let data = Bundle.main.loadData(fileName: "Restaurant", type: "txt")!
let root = try! JSONDecoder().decode(Root<SuggestedRestaurants>.self, from: data)
return root.value.list
}
}
extension SuggestedRestaurants: DummyDataProvider {
static var dummyObject: SuggestedRestaurants {
return SuggestedRestaurants(list: Restaurant.dummyCollection)
}
static var dummyCollection: [SuggestedRestaurants] {
return [dummyObject]
}
}
|
0 | //
// TypeAlias.swift
// EaseMobPremium
//
// Created by GongYuhua on 4/11/16.
// Copyright © 2016 EaseMob. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
//MARK: - Image
#if os(iOS)
public typealias AGEImage = UIImage
#else
public typealias AGEImage = NSImage
#endif
//MARK: - View
#if os(iOS)
public typealias ALView = UIView
#else
public typealias ALView = NSView
#endif
|
0 | //
// AppDelegate.swift
// test
//
// Created by HuXuPeng on 2018/5/15.
// Copyright © 2018年 njhu. All rights reserved.
//
import UIKit
import NJMediator
import NJKit
@UIApplicationMain
class NJAppDelegate: UIResponder, UIApplicationDelegate {
lazy var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 设置入口
window?.makeKeyAndVisible()
window?.rootViewController = NJTabBarController()
// 设置监控
NJDebugTool.defaultTool.show()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
var shouldOpen = false
let resultObj = NJMediator.sharedMediator.perform(url: url) { (result: [String: AnyObject]?) in
if result?["result"] != nil {
}
}
shouldOpen = resultObj?.boolValue ?? false;
return shouldOpen
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return window?.rootViewController?.supportedInterfaceOrientations ?? UIInterfaceOrientationMask.allButUpsideDown;
}
}
|
0 | //
// RepositoryListViewModel.swift
// RepoSearcher
//
// Created by Taeyoun Lee on 2019/09/05.
// Copyright © 2019 Taeyoun Lee. All rights reserved.
//
import Foundation
import RxSwift
class RepositoryListViewModel {
// MARK: - Inputs
/// Call to update current language. Causes reload of the repositories.
let setCurrentLanguage: AnyObserver<String>
/// Call to show language list screen.
let chooseLanguage: AnyObserver<Void>
/// Call to open repository page.
let selectRepository: AnyObserver<RepositoryViewModel>
/// Call to reload repositories.
let reload: AnyObserver<Void>
// MARK: - Outputs
/// Emits an array of fetched repositories.
let repositories: Observable<[RepositoryViewModel]>
/// Emits a formatted title for a navigation item.
let title: Observable<String>
/// Emits an error messages to be shown.
let alertMessage: Observable<String>
/// Emits an url of repository page to be shown.
let showRepository: Observable<URL>
/// Emits when we should show language list.
let showLanguageList: Observable<Void>
init(initialLanguage: String, githubService: GithubService = GithubService()) {
let _reload = PublishSubject<Void>()
self.reload = _reload.asObserver()
let _currentLanguage = BehaviorSubject<String>(value: initialLanguage)
self.setCurrentLanguage = _currentLanguage.asObserver()
self.title = _currentLanguage.asObservable()
.map { "\($0)" }
let _alertMessage = PublishSubject<String>()
self.alertMessage = _alertMessage.asObservable()
self.repositories = Observable.combineLatest( _reload, _currentLanguage) { _, language in language }
.flatMapLatest { language in
githubService.getMostPopularRepositories(byLanguage: language)
.catchError { error in
_alertMessage.onNext(error.localizedDescription)
return Observable.empty()
}
}
.map { repositories in repositories.map(RepositoryViewModel.init) }
let _selectRepository = PublishSubject<RepositoryViewModel>()
self.selectRepository = _selectRepository.asObserver()
self.showRepository = _selectRepository.asObservable()
.map { $0.url }
let _chooseLanguage = PublishSubject<Void>()
self.chooseLanguage = _chooseLanguage.asObserver()
self.showLanguageList = _chooseLanguage.asObservable()
}
}
|
0 | //
// LPGroupedDataCollection.swift
// LPIM
//
// Created by lipeng on 2017/6/27.
// Copyright © 2017年 lipeng. All rights reserved.
//
import Foundation
import NIMSDK
private class LPPair {
var first: String
var second: NSMutableArray
init(first: String, second: [LPGroupMemberProtocol]) {
self.first = first
self.second = NSMutableArray(array: second)
}
}
class LPGroupedDataCollection {
private lazy var specialGroupTitles = NSMutableOrderedSet()
private lazy var specialGroups = NSMutableOrderedSet()
private lazy var groupTitles: NSMutableOrderedSet = NSMutableOrderedSet()
private lazy var groups = NSMutableOrderedSet()
var groupTitleComparator: Comparator
var groupMemberComparator: Comparator
var sortedGroupTitles: [String] {
return groupTitles.array as? [String] ?? []
}
init() {
groupTitleComparator = { (title1, title2) -> ComparisonResult in
if let title1 = title1 as? String, let title2 = title2 as? String {
if title1 == "#" {
return .orderedDescending
}
if title2 == "#" {
return .orderedDescending
}
return title1.compare(title2)
}
return .orderedAscending
}
groupMemberComparator = { (key1, key2) -> ComparisonResult in
if let key1 = key1 as? String, let key2 = key2 as? String {
return key1.compare(key2)
}
return .orderedAscending
}
}
func setupMembers(_ members: [LPGroupMemberProtocol]) {
var tmp: [String: [LPGroupMemberProtocol]] = [:]
let me = NIMSDK.shared().loginManager.currentAccount()
for member in members {
if member.memberId == me {
continue
}
let groupTitle = member.groupTitle
var groupedMembers = tmp[groupTitle]
if groupedMembers == nil {
groupedMembers = []
}
groupedMembers?.append(member)
tmp[groupTitle] = groupedMembers
}
groupTitles.removeAllObjects()
groups.removeAllObjects()
for item in tmp where item.key.characters.count > 0 {
let character = item.key[item.key.startIndex]
if character >= "A" && character <= "Z" {
groupTitles.add(item.key)
} else {
groupTitles.add("#")
}
groups.add(LPPair(first: item.key, second: item.value))
}
sort()
}
func addGroupMember(_ member: LPGroupMemberProtocol) {
let groupTitle = member.groupTitle
let groupIndex = groupTitles.index(of: groupTitle)
var tmpPair: LPPair
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
tmpPair = pair
} else {
tmpPair = LPPair(first: groupTitle, second: [])
}
} else {
tmpPair = LPPair(first: groupTitle, second: [])
}
tmpPair.second.add(member)
groupTitles.add(groupTitle)
groups.add(tmpPair)
sort()
}
func removeGroupMember(_ member: LPGroupMemberProtocol) {
let groupTitle = member.groupTitle
let groupIndex = groupTitles.index(of: groupTitle)
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
pair.second.remove(member)
if pair.second.count == 0 {
groups.remove(pair)
}
sort()
}
}
}
func addGroupAbove(withTitle title: String, members: [LPGroupMemberProtocol]) {
let pair = LPPair(first: title, second: members)
specialGroupTitles.add(title)
specialGroups.add(pair)
}
func title(ofGroup index: Int) -> String? {
var index = index
if index >= 0 && index < specialGroupTitles.count {
return specialGroupTitles.object(at: index) as? String
}
index -= specialGroupTitles.count
if index >= 0 && index < groupTitles.count {
return groupTitles.object(at: index) as? String
}
return nil
}
func members(ofGroup index: Int) -> [LPGroupMemberProtocol]? {
var index = index
if index >= 0 && index < specialGroups.count {
if let pair = specialGroups.object(at: index) as? LPPair {
return pair.second as? [LPGroupMemberProtocol]
}
}
index -= specialGroups.count
if index >= 0 && index < groups.count {
if let pair = groups.object(at: index) as? LPPair {
return pair.second as? [LPGroupMemberProtocol]
}
}
return nil
}
func member(ofIndex indexPath: IndexPath) -> LPGroupMemberProtocol? {
var members: NSArray?
var groupIndex = indexPath.section
if groupIndex >= 0 && groupIndex < specialGroups.count {
if let pair = specialGroups.object(at: groupIndex) as? LPPair {
members = pair.second
}
}
groupIndex -= specialGroups.count
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
members = pair.second
}
}
let memberIndex = indexPath.row
if let members = members {
if memberIndex >= 0 && memberIndex < members.count {
return members.object(at: memberIndex) as? LPGroupMemberProtocol
}
}
return nil
}
func member(ofId uid: String) -> LPGroupMemberProtocol? {
for pair in groups {
if let pair = pair as? LPPair {
for member in pair.second {
if let member = member as? LPGroupMemberProtocol, member.memberId == uid {
return member
}
}
}
}
return nil
}
func groupCount() -> Int {
return specialGroupTitles.count + groupTitles.count
}
func memberCount(ofGroup index: Int) -> Int {
var index = index
var members: NSArray?
if index >= 0 && index < specialGroups.count {
if let pair = specialGroups.object(at: index) as? LPPair {
members = pair.second
}
}
index -= specialGroups.count
if index >= 0 && index < groups.count {
if let pair = groups.object(at: index) as? LPPair {
members = pair.second
}
}
return members?.count ?? 0
}
private func sort() {
sortGroupTitle()
sortGroupMember()
}
private func sortGroupTitle() {
groupTitles.sortedArray(comparator: groupTitleComparator)
groups.sortedArray(comparator: { (pair1, pair2) -> ComparisonResult in
if let pair1 = pair1 as? LPPair, let pair2 = pair2 as? LPPair {
return groupTitleComparator(pair1.first, pair2.first)
}
return .orderedAscending
})
}
private func sortGroupMember() {
groups.enumerateObjects({ (obj, idx, stop) in
if let pair = obj as? LPPair {
let groupedMembers = pair.second
groupedMembers.sortedArray(comparator: { (member1, member2) -> ComparisonResult in
if let member1 = member1 as? LPGroupMemberProtocol, let member2 = member2 as? LPGroupMemberProtocol {
return groupMemberComparator(member1.sortKey, member2.sortKey)
}
return .orderedAscending
})
}
})
}
}
|
0 | //
// NavigatoSourceApp.swift
// Navigato
//
// Created by Anatoliy Voropay on 10/26/17.
//
import Foundation
import CoreLocation
/// Protocol to describe Source App behaviour for Navigato
public protocol NavigatoSourceAppProtocol {
/// Source app name
var name: String { get }
/// Return `true` if source app is available
var isAvailable: Bool { get }
/// Open source app with address String
func open(withAddress address: String)
/// Open source app with `CLLocation`
func open(withLocation location: CLLocation)
/// Open source app with search query
func open(withQuery query: String)
// MARK: Low-level interface
/// Return path for request
func path(forRequest request: Navigato.RequestType) -> String
/// Open source app with specific `Navigato.RequestType`
func open(withRequest request: Navigato.RequestType, value: Any)
}
/// Base class for all Source App subclasses
public class NavigatoSourceApp: NavigatoSourceAppProtocol {
public var name: String {
assertionFailure("Implementation required")
return ""
}
public func path(forRequest request: Navigato.RequestType) -> String {
assertionFailure("Implementation required")
return ""
}
/// Return `true` if source app is available
public var isAvailable: Bool {
let path = self.path(forRequest: .address)
guard let url = URL(string: path) else { return false }
return UIApplication.shared.canOpenURL(url)
}
/// Open source app with address String
public func open(withAddress address: String) {
open(withRequest: .search, value: address as Any)
}
/// Open source app with `CLLocation`
public func open(withLocation location: CLLocation) {
open(withRequest: .location, value: location as Any)
}
/// Open source app with search query
public func open(withQuery query: String) {
open(withRequest: .search, value: query as Any)
}
public func open(withRequest request: Navigato.RequestType, value: Any) {
let path = self.path(forRequest: request)
var destinationURL: URL?
switch request {
case .address, .search:
guard let string = (value as? String)?.addingPercentEncoding(withAllowedCharacters: queryCharacterSet) else { return }
destinationURL = URL(string: path + string)
case .location:
guard let location = value as? CLLocation else { return }
let string = [location.coordinate.latitude, location.coordinate.longitude].map({ String($0) }).joined(separator: ",")
destinationURL = URL(string: path + string)
}
guard let url = destinationURL else { return }
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.openURL(url)
}
private var queryCharacterSet: CharacterSet {
let characterSet = NSMutableCharacterSet()
characterSet.formUnion(with: CharacterSet.urlQueryAllowed)
characterSet.removeCharacters(in: "&")
return characterSet as CharacterSet
}
}
|
0 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind 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.
*/
public struct Stack<Element>: CustomStringConvertible, Sequence {
public typealias Iterator = AnyIterator<Element>
/// Underlying data structure.
private var list: DoublyLinkedList<Element>
/// Total number of items in the Stack.
public var count: Int {
return list.count
}
/// Get the latest element at the top of the Stack and do not remove it.
public var top: Element? {
return list.front
}
/// A boolean of whether the Stack is empty.
public var isEmpty: Bool {
return list.isEmpty
}
/// Conforms to the Printable Protocol.
public var description: String {
return list.description
}
/// Initializer.
public init() {
list = DoublyLinkedList<Element>()
}
/**
Conforms to the SequenceType Protocol. Returns the next value in the
sequence of nodes.
- Returns: Stack.Generator
*/
public func makeIterator() -> Stack.Iterator {
return list.makeIterator()
}
/**
Insert a new element at the top of the Stack.
- Parameter _ element: An Element type.
*/
mutating public func push(_ element: Element) {
list.insert(atFront: element)
}
/**
Get the latest element at the top of the Stack and remove it from
the Stack.
- Returns: Element?
*/
mutating public func pop() -> Element? {
return list.removeAtFront()
}
/// Remove all elements from the Stack.
mutating public func removeAll() {
list.removeAll()
}
}
public func +<Element>(lhs: Stack<Element>, rhs: Stack<Element>) -> Stack<Element> {
var s = Stack<Element>()
for x in lhs {
s.push(x)
}
for x in rhs {
s.push(x)
}
return s
}
public func +=<Element>(lhs: inout Stack<Element>, rhs: Stack<Element>) {
for x in rhs {
lhs.push(x)
}
}
|
0 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
extension Array {
func f<d, b {
}(Any, U)(b() {
return [""")
}
protocol b {
func b<T>(c() {
class b: A"ab""
func c<h: c(
|
0 | //
// BoardData.swift
// Teamwork
//
// Create by Lucas Correa on 14/9/2017
// Copyright © 2017 SiriusCode. All rights reserved.
import Foundation
struct BoardData{
init(fromDictionary dictionary: [String:Any]) {
}
func toDictionary() -> [String:Any] {
let dictionary = [String:Any]()
return dictionary
}
}
|
0 | //
// BTHotView.swift
// BanTang
//
// Created by 张灿 on 16/5/29.
// Copyright © 2016年 张灿. All rights reserved.
//
import UIKit
import AFNetworking
import MJExtension
protocol BTHotViewDelegate: class {
func BTHotViewLastCellWillAppear()
}
//列
private let cols: CGFloat = 3
//间距
private let margin: CGFloat = 2
private let wh = (UIScreen.mainScreen().bounds.width - (cols - 1) * margin) / cols
private let footCellID = "footCellID"
class BTHotView: UIView {
@IBOutlet weak var collectionV: UICollectionView!
weak var delegate: BTHotViewDelegate?
var hotItems: [BTHotItem]? {
didSet {
guard hotItems != nil else {
return
}
//重新设置collectionView高度
// let maxRows = (hotItems.count - 1) / 3 + 1
// let h: CGFloat = CGFloat(maxRows) * wh + CGFloat(maxRows) * margin
//
// self.collectionV?.frame.size.height = h
//
// print("有计算了一遍collectionview高度")
self.collectionV.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setCollectionView()
}
}
extension BTHotView {
func setCollectionView() {
//创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: wh, height: wh)
layout.minimumLineSpacing = margin
layout.minimumInteritemSpacing = margin
collectionV.collectionViewLayout = layout
//注册cell
collectionV.registerNib(UINib.init(nibName: "BTHotCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: footCellID)
collectionV.backgroundColor = UIColor.whiteColor()
collectionV.dataSource = self
collectionV.delegate = self
//取消多余的scrollsToTop,使得只有一个tableView拥有触顶返回功能
collectionV.scrollsToTop = false
}
}
extension BTHotView: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hotItems?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(footCellID, forIndexPath: indexPath) as! BTHotCollectionViewCell
if hotItems?.count > 0 {
cell.hotItem = hotItems![indexPath.row]
}
//判断是否是最后一个cell即将出现
if indexPath.row == hotItems!.count - 1 {
//发送通知给单品控制器,让他去加载更多数据
// NSNotificationCenter.defaultCenter().postNotificationName("reloadHotData", object: self)
// self.delegate?.BTHotViewLastCellWillAppear()
// print("发送了通知")
}
return cell
}
}
|
0 | import Foundation
import SwiftProtobuf
import NIO
import NIOHTTP1
/// Provides a means for decoding incoming gRPC messages into protobuf objects.
///
/// Calls through to `processMessage` for individual messages it receives, which needs to be implemented by subclasses.
public class BaseCallHandler<RequestMessage: Message, ResponseMessage: Message>: GRPCCallHandler {
public func makeGRPCServerCodec() -> ChannelHandler { return GRPCServerCodec<RequestMessage, ResponseMessage>() }
/// Called whenever a message has been received.
///
/// Overridden by subclasses.
public func processMessage(_ message: RequestMessage) {
fatalError("needs to be overridden")
}
/// Called when the client has half-closed the stream, indicating that they won't send any further data.
///
/// Overridden by subclasses if the "end-of-stream" event is relevant.
public func endOfStreamReceived() { }
}
extension BaseCallHandler: ChannelInboundHandler {
public typealias InboundIn = GRPCServerRequestPart<RequestMessage>
public typealias OutboundOut = GRPCServerResponsePart<ResponseMessage>
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head: preconditionFailure("should not have received headers")
case .message(let message): processMessage(message)
case .end: endOfStreamReceived()
}
}
}
|
0 | //
// ScrollingView.swift
// LayersAnimation
//
// Created by Mazy on 2017/5/24.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class ScrollingView: UIView {
/// 重写 layerClass 方法,获取 UIView 的子 layer
override class var layerClass: AnyClass {
return CAScrollLayer.self
}
}
|
0 | //
// SampleDogma.swift
// SimpleClient
//
// Created by Tae Hyun Na on 2019. 5. 2.
// Copyright (c) 2014, P9 SOFT, Inc. All rights reserved.
//
// Licensed under the MIT license.
import UIKit
import ObjectMapper
class SampleDogma: HJRestClientDogma {
fileprivate func modelFromObject(object:[String:Any], responseModelRefer: Any?) -> Any? {
if let jsonModelClass = responseModelRefer as? JSONModel.Type {
if let model = try? jsonModelClass.init(dictionary: object) {
return model
}
} else if let jsonModelClass = responseModelRefer as? Mappable.Type {
if let model = jsonModelClass.init(JSON: object) {
return model
}
}
return object
}
func bodyFromRequestModel(_ requestModel:Any?) -> Data? {
if let jsonModel = requestModel as? JSONModel {
return jsonModel.toJSONData()
} else if let jsonModel = requestModel as? Mappable, let jsonString = jsonModel.toJSONString() {
return jsonString.data(using: .utf8)
}
return requestModel as? Data
}
func contentTypeFromRequestModel(_ requestModel:Any?) -> String? {
if ((requestModel as? JSONModel) != nil) || ((requestModel as? Mappable) != nil) {
return "application/json"
}
return "application/octet-stream"
}
func responseModel(fromData data: Data, serverAddress: String, endpoint: String?, contentType:String?, requestModel: Any?, responseModelRefer: Any?) -> Any? {
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
return nil
}
if let list = jsonObject as? [Any] {
var modelList:[Any] = []
for item in list {
if let item = item as? [String:Any], let model = modelFromObject(object: item, responseModelRefer: responseModelRefer) {
modelList.append(model)
}
}
return modelList
}
if let item = jsonObject as? [String:Any] {
return modelFromObject(object: item, responseModelRefer: responseModelRefer)
}
return data
}
func responseData(fromModel model: Any, serverAddress: String, endpoint: String?, requestModel: Any?) -> Data? {
if let jsonModel = model as? JSONModel {
return jsonModel.toJSONData()
} else if let jsonModel = model as? Mappable, let jsonString = jsonModel.toJSONString() {
return jsonString.data(using: .utf8)
}
return model as? Data
}
func didReceiveResponse(response: URLResponse, serverAddress: String, endpoint: String?) {
print("- did receive response from \(serverAddress)\(endpoint ?? "")")
}
}
|
0 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "MyVaporTest2",
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
// 🔵 Swift ORM (queries, models, relations, etc) built on SQLite 3.
.package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0"),
// postgreSQL
.package(url: "https://github.com/IBM-Swift/Swift-Kuery-ORM.git", from:"0.3.1"), // from: "2.0.0"
.package(url: "https://github.com/IBM-Swift/Swift-Kuery-PostgreSQL.git", from:"1.2.0"), //from: "1.2.0"
],
targets: [
.target(name: "App", dependencies: ["FluentSQLite", "Vapor", "SwiftKueryORM", "SwiftKueryPostgreSQL"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"])
]
)
|
0 | //
// ACButton.swift
// amidakuji
//
// Created by yrq_mac on 16/6/1.
// Copyright © 2016年 yrq_mac. All rights reserved.
//
import UIKit
class ACButton: UIButton {
var x:Int?
var y:Int?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
var scale = self.pop_animation(forKey: "scale") as? POPSpringAnimation
if scale != nil {
scale?.toValue = NSValue(cgPoint: CGPoint(x: 0.8, y: 0.8))
}else{
scale = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
scale?.toValue = NSValue(cgPoint:CGPoint(x: 0.8, y: 0.8))
scale?.springBounciness = 20
scale?.springSpeed = 18
self.pop_add(scale, forKey: "scale")
}
var rotate = self.layer.pop_animation(forKey: "rotate") as? POPSpringAnimation
if rotate != nil {
rotate?.toValue = M_PI/6
}else{
rotate = POPSpringAnimation(propertyNamed: kPOPLayerRotation)
rotate?.toValue = M_PI/6
rotate?.springBounciness = 20
rotate?.springSpeed = 18
self.layer.pop_add(rotate, forKey: "rotate")
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
var scale = self.pop_animation(forKey: "scale") as? POPSpringAnimation
if scale != nil {
scale?.toValue = NSValue(cgPoint: CGPoint(x: 1, y: 1))
}else{
scale = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
scale?.toValue = NSValue(cgPoint:CGPoint(x: 1, y: 1))
scale?.springBounciness = 20
scale?.springSpeed = 18
self.pop_add(scale, forKey: "scale")
}
var rotate = self.layer.pop_animation(forKey: "rotate") as? POPSpringAnimation
if rotate != nil {
rotate?.toValue = 0
}else{
rotate = POPSpringAnimation(propertyNamed: kPOPLayerRotation)
rotate?.toValue = 0
rotate?.springBounciness = 20
rotate?.springSpeed = 18
self.layer.pop_add(rotate, forKey: "rotate")
}
}
}
|
0 | //
// CollectionViewSampleTests.swift
// CollectionViewSampleTests
//
// Created by Hao on 2019/3/20.
// Copyright © 2019年 LIUHAO. All rights reserved.
//
import XCTest
@testable import CollectionViewSample
class CollectionViewSampleTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
0 |
/*
二分查找法
*/
import UIKit
var str = "Hello, man"
var list = [Int]()//待查随机模拟数组
var item = 0
//造一个有十个元素的模拟数据数组
for i in 0..<10 {
item = item + Int(arc4random_uniform(UInt32(20)));
list.append(item)
}
//随机一个元素
let targetNum = list[Int(arc4random_uniform(UInt32(10)))]
print("原始数组为: \(list) 目标数字为: \(targetNum)")
//compareTimes : 记录比较次数
var compareTimes = 0
//result : 记录结果
var result = binarySearch(targetNum,list)
print("搜索结果: \(result) 比较次数 : \(compareTimes)")
/// 二分查找法 时间复杂度: O(logN)---2为底,N的对数
///
/// - Parameters:
/// - targetNum: 目标数字
/// - sourceList: 原始数组
/// - Returns: 目标数值在原始数组中的位置
func binarySearch(_ targetNum:Int, _ sourceList:[Int]) -> Int{
var start = 0
var end = sourceList.count - 1
//只要没有指向同一个数,则继续查找
while start <= end {
compareTimes += 1
//取中值
var middle = (start + end)/2
print("----第\(compareTimes)次比较的中值为\(sourceList[middle])")
//如果中值等于目标值,直接返回中值index
if targetNum == sourceList[middle] {
return middle
}
//如果目标小于中值.说明在前半段
if targetNum < sourceList[middle] {
end = middle - 1
}
//如果目标大于中值.说明在后半段
if targetNum > sourceList[middle] {
start = middle + 1
}
}
//没有找到
return -1
}
|
0 | //
// MapSelectorViewController.swift
// AnyMap
//
// Created by Julian Caicedo on 30.08.18.
// Copyright © 2018 juliancadi.com. All rights reserved.
//
import UIKit
class MapSelectorViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var mapTypeSegmentedControl: UISegmentedControl!
@IBOutlet weak var mapContainer: UIView!
// MARK: - State
private lazy var stateViewController = ContentStateViewController()
private var mapDisplayViewController: MapDisplayViewController!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Rounded corners
mapTypeSegmentedControl.layer.cornerRadius = 4.0
add(viewController: stateViewController, to: mapContainer)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let intialMapable = mapable(for: MapType(rawValue: mapTypeSegmentedControl.selectedSegmentIndex)!)
mapDisplayViewController = MapDisplayViewController(mapable: intialMapable)
render(viewController: mapDisplayViewController)
}
@IBAction func segmentedValueChanged(_ sender: UISegmentedControl) {
let newMapable = mapable(for: MapType(rawValue: sender.selectedSegmentIndex)!)
mapDisplayViewController.transition(to: newMapable)
}
}
private extension MapSelectorViewController {
func render(viewController: MapDisplayViewController) {
stateViewController.transition(to: .render(viewController))
}
func mapable(for type: MapType) -> Mapable {
switch type {
case .mapbox:
return MapboxMapViewController()
case .mapKit:
return MapKitViewController()
case .googleMaps:
return GoogleMapsViewController()
}
}
}
extension MapSelectorViewController {
enum MapType: Int {
case mapbox
case mapKit
case googleMaps
}
}
|
0 | //
// ItemCell.swift
// Tablecloth
//
// Created by Erdem Turanciftci on 29/10/2016.
// Copyright © 2016 Erdem Turançiftçi. All rights reserved.
//
import Tablecloth
class ItemCell: TableViewCell {
fileprivate var itemTextLabel: UILabel!
func setItemText(_ itemText: String) {
itemTextLabel.text = itemText
}
class func cellFromTableView(
_ tableView: UITableView,
itemText: String)
-> TableViewCell {
return cellFromTableView(tableView) { (cell) -> Void in
if let cell = cell as? ItemCell {
cell.setItemText(itemText)
}
}
}
override class func cellHeight() -> CGFloat {
return 44.0
}
required init(reuseIdentifier: String) {
super.init(reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.white
selectionColor = UIColor.gray
let width = ItemCell.cellWidth()
let height = ItemCell.cellHeight()
itemTextLabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: height))
itemTextLabel.textColor = UIColor.darkText
itemTextLabel.textAlignment = .center
itemTextLabel.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
contentView.addSubview(itemTextLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | import Foundation
import Logging
import os
public struct LoggingOSLog: LogHandler {
public var logLevel: Logger.Level = .info
public let label: String
private let oslogger: OSLog
public init(label: String) {
self.label = label
self.oslogger = OSLog(subsystem: label, category: "")
}
public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) {
var combinedPrettyMetadata = self.prettyMetadata
if let metadataOverride = metadata, !metadataOverride.isEmpty {
combinedPrettyMetadata = self.prettify(
self.metadata.merging(metadataOverride) {
return $1
}
)
}
var formedMessage = message.description
if combinedPrettyMetadata != nil {
formedMessage += " -- " + combinedPrettyMetadata!
}
if let str = formedMessage as? NSString {
os_log("%{public}@", log: self.oslogger, type: OSLogType.from(loggerLevel: level), str)
}
}
private var prettyMetadata: String?
public var metadata = Logger.Metadata() {
didSet {
self.prettyMetadata = self.prettify(self.metadata)
}
}
/// Add, remove, or change the logging metadata.
/// - parameters:
/// - metadataKey: the key for the metadata item.
public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {
get {
return self.metadata[metadataKey]
}
set {
self.metadata[metadataKey] = newValue
}
}
private func prettify(_ metadata: Logger.Metadata) -> String? {
if metadata.isEmpty {
return nil
}
return metadata.map {
"\($0)=\($1)"
}.joined(separator: " ")
}
}
extension OSLogType {
static func from(loggerLevel: Logger.Level) -> Self {
switch loggerLevel {
case .trace:
/// `OSLog` doesn't have `trace`, so use `debug`
return .debug
case .debug:
return .debug
case .info:
return .info
case .notice:
/// `OSLog` doesn't have `notice`, so use `info`
return .info
case .warning:
/// `OSLog` doesn't have `warning`, so use `info`
return .info
case .error:
return .error
case .critical:
return .fault
}
}
}
|
0 | import StorybookKit
import StorybookUI
import UIKit
final class RootContainerViewController: UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
let child = StorybookViewController(
book: book,
dismissHandler: nil
)
addChild(child)
view.addSubview(child.view)
child.view.frame = view.bounds
child.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | //
// BasicAnimator.swift
// HKAnimatedTabBar
//
// Created by Kyryl Horbushko on 15.11.2019.
// Copyright © 2019 - present. All rights reserved.
//
import UIKit
final class BasicAnimator {
public enum Defaults {
static let AnimationDuration: TimeInterval = 0.3
}
class func colorsAnimation(_ newColors: [UIColor], oldColors: [UIColor], duration: TimeInterval) -> CABasicAnimation {
let animation: CABasicAnimation = CABasicAnimation(keyPath: "colors")
animation.fromValue = oldColors.compactMap({ $0.cgColor })
animation.toValue = newColors.compactMap({ $0.cgColor })
animation.duration = duration
animation.isRemovedOnCompletion = true
animation.fillMode = CAMediaTimingFillMode.forwards
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
return animation
}
class func borderColorAnimation(_ fromColor: CGColor, newColor: CGColor, duration: TimeInterval) -> CABasicAnimation {
let animation: CABasicAnimation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = fromColor
animation.toValue = newColor
animation.duration = duration
animation.isRemovedOnCompletion = true
animation.fillMode = CAMediaTimingFillMode.forwards
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
return animation
}
}
|
0 | //
// AppDelegate.swift
// Example
//
// Created by Yuya Oka on 2021/08/09.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
|
0 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class EmptyFeedCollectionViewCell: UICollectionViewCell {
//label that informs the user that there are no images in the feed
@IBOutlet weak var userHasNoImagesLabel: UILabel!
//message that is shown in the userHasNoImagesLabel
private let kUserHasNoImagesLabelText = NSLocalizedString("Snap a pic or select one from your library!", comment: "message that describes to the user to upload a picture to begin")
/**
Method is called when the view wakes from nib
*/
override func awakeFromNib() {
super.awakeFromNib()
userHasNoImagesLabel.text = kUserHasNoImagesLabelText
}
}
|
0 | //
// SpectraView.swift
// Spectra
//
// Created by David Conner on 9/27/15.
// Copyright © 2015 Spectra. All rights reserved.
//
import MetalKit
// create a notion of a scene renderer
// GOAL: TOTALLY abstract game state from rendering
//TODO: differentiate SpectraBaseView for ios & osx
// - using extension & available keywords?
// - need to override layoutSubviews() on iOS
// - need to override setFrameSize() on OSX
// - or let the user of the lib override this?
public protocol RenderDelegate: class {
var pipelineStateMap: RenderPipelineStateMap { get set }
var depthStencilStateMap: DepthStencilStateMap { get set }
var rendererMap: RendererMap { get set }
func renderObjects(drawable: CAMetalDrawable, renderPassDescriptor: MTLRenderPassDescriptor, commandBuffer: MTLCommandBuffer, inflightResourcesIndex: Int)
}
public protocol UpdateDelegate: class {
func updateObjects(timeSinceLastUpdate: CFTimeInterval, inflightResourcesIndex: Int)
}
//TODO: MUST IMPLEMENT NSCODER & deinit to dealloc
public class BaseView: MTKView {
public var defaultLibrary: MTLLibrary!
public var commandQueue: MTLCommandQueue!
public var renderPassDescriptor: MTLRenderPassDescriptor?
public var inflightResources: InflightResourceManager
public var startTime: CFAbsoluteTime!
public var lastFrameStart: CFAbsoluteTime!
public var thisFrameStart: CFAbsoluteTime!
public weak var renderDelegate: RenderDelegate?
public weak var updateDelegate: UpdateDelegate?
override public init(frame frameRect:CGRect, device:MTLDevice?) {
inflightResources = InflightResourceManager()
super.init(frame: frameRect, device: device)
configureGraphics()
}
required public init(coder: NSCoder) {
inflightResources = InflightResourceManager()
super.init(coder: coder)
configureGraphics()
}
public func configureGraphics() {
mtkViewDefaults()
beforeSetupMetal()
setupMetal()
afterSetupMetal()
// move to scene renderer?
// setupRenderPipeline()
}
public func beforeSetupMetal() {
//override in subclass
}
public func afterSetupMetal() {
//override in subclass
}
public func mtkViewDefaults() {
//TODO: framebufferOnly might be why particleLab failed on OSX!
framebufferOnly = false
preferredFramesPerSecond = 60
colorPixelFormat = MTLPixelFormat.BGRA8Unorm
sampleCount = 1
}
public func metalUnavailable() {
//override in subclass
}
public func setupMetal() {
guard let device = MTLCreateSystemDefaultDevice() else {
self.metalUnavailable()
return
}
self.device = device
defaultLibrary = device.newDefaultLibrary()
commandQueue = device.newCommandQueue()
}
public func render() {
inflightResources.wait()
let cmdBuffer = commandQueue.commandBuffer()
cmdBuffer.addCompletedHandler { (cmdBuffer) in
self.inflightResources.next()
}
guard let drawable = currentDrawable else
{
Swift.print("currentDrawable returned nil")
return
}
//N.B. the app does not necessarily need to use currentRenderPassDescriptor
var renderPassDescriptor = setupRenderPassDescriptor(drawable, renderPassDescriptor: currentRenderPassDescriptor!)
self.renderDelegate?.renderObjects(drawable, renderPassDescriptor: renderPassDescriptor, commandBuffer: cmdBuffer, inflightResourcesIndex: inflightResources.index)
cmdBuffer.presentDrawable(drawable)
cmdBuffer.commit()
}
public func setupRenderPipeline() {
//move to scene renderer?
}
public func setupRenderPassDescriptor(drawable: CAMetalDrawable, renderPassDescriptor: MTLRenderPassDescriptor) -> MTLRenderPassDescriptor {
return renderPassDescriptor
}
public func reshape(view:MTKView, drawableSizeWillChange size: CGSize) {
}
override public func drawRect(dirtyRect: CGRect) {
lastFrameStart = thisFrameStart
thisFrameStart = CFAbsoluteTimeGetCurrent()
self.updateDelegate?.updateObjects(CFTimeInterval(thisFrameStart - lastFrameStart), inflightResourcesIndex: inflightResources.index)
autoreleasepool { () -> () in
self.render()
}
}
} |
0 | //
// ViewController.swift
// Wayconomy
//
// Created by Erick Almeida on 02/03/20.
// Copyright © 2020 Erick Almeida. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var distanceTraveledTextField: UITextField!
@IBOutlet var spentFuelTextField: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBOutlet var calcHelpLabel: UILabel!
@IBOutlet var efficiencyResultView: UIView!
@IBOutlet var calcTitleLabel: UILabel!
@IBOutlet var calcTypeSegmentedControl: UISegmentedControl!
@IBOutlet var efficiencyView: UIView!
@IBOutlet var pricePerKmView: UIView!
@IBOutlet var changeCalcTypeButton: UIButton!
@IBOutlet var efficiencyTextField: UITextField!
@IBOutlet var fuelPriceTextField: UITextField!
@IBOutlet var backgroundImage: UIImageView!
let calculator: Calculator = Calculator()
override func viewDidLoad() {
super.viewDidLoad()
setCalcType(type: 0)
toggleResultStatus(viewable: false)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
if #available(iOS 13.0, *) {
calcTypeSegmentedControl.layer.borderColor = UIColor.white.cgColor
calcTypeSegmentedControl.selectedSegmentTintColor = UIColor.white
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
calcTypeSegmentedControl.setTitleTextAttributes(titleTextAttributes, for:.normal)
let titleTextAttributes1 = [NSAttributedString.Key.foregroundColor: UIColor.black]
calcTypeSegmentedControl.setTitleTextAttributes(titleTextAttributes1, for:.selected)
}
UIApplication.shared.statusBarStyle = .lightContent
// Do any additional setup after loading the view.
}
func readTextFieldAsDouble(textField: UITextField!) -> Double? {
if (textField.text!.contains(",")) {
return Double(textField.text!.replacingOccurrences(of: ",", with: "."))
}
return Double(textField.text!)
}
func toggleResultStatus(viewable: Bool) {
if (viewable) {
efficiencyResultView.isHidden = false
calcHelpLabel.isHidden = true
} else {
efficiencyResultView.isHidden = true
calcHelpLabel.isHidden = false
}
}
@IBAction func onPressChangeCalcTypeButton() {
calcTypeSegmentedControl.selectedSegmentIndex = 1
setCalcType(type: 1)
}
@IBAction func calcTypeSelectorChanged() {
setCalcType(type: calcTypeSegmentedControl.selectedSegmentIndex)
}
func setCalcType(type: Int) {
if (type == 0) {
// Rendimento
efficiencyView.isHidden = false;
pricePerKmView.isHidden = true;
calcTitleLabel.text = "Rendimento"
changeCalcTypeButton.isHidden = false;
backgroundImage.image = UIImage(named: "Background")
onUpdateEfficiencyTextFields()
} else if (type == 1) {
// Preço por km
if (calculator.efficiency != 0) {
efficiencyTextField.text = calculator.formatNumber(number: calculator.efficiency)
}
efficiencyView.isHidden = true;
pricePerKmView.isHidden = false;
calcTitleLabel.text = "Preço por km"
changeCalcTypeButton.isHidden = true;
backgroundImage.image = UIImage(named: "Background Alternative")
onUpdatePricePerKmTextFields()
}
}
func setCalcHelpText(calcTypeIndex: Int, isTextFieldEmpty: Bool = false, isTextFieldEqualOrSmallerThanZero: Bool = false) {
let calcTypeName: String
if (calcTypeIndex == 0) {
calcTypeName = "rendimento"
} else {
calcTypeName = "preço por km"
}
if (isTextFieldEmpty) {
calcHelpLabel.text = "Quando você inserir os dados, o \(calcTypeName) calculado aparecerá aqui."
} else if (isTextFieldEqualOrSmallerThanZero) {
calcHelpLabel.text = "Por favor, insira um valor maior que zero nos campos para calcular o \(calcTypeName)."
}
}
@IBAction func onUpdateEfficiencyTextFields() {
guard let distanceTraveled = readTextFieldAsDouble(textField: distanceTraveledTextField) else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 0, isTextFieldEmpty: true)
return
}
guard let spentFuel = readTextFieldAsDouble(textField: spentFuelTextField) else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 0, isTextFieldEmpty: true)
return
}
calculator.distanceTraveled = distanceTraveled
calculator.spentFuel = spentFuel
guard let result = calculator.getFormattedEfficiency() else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 0, isTextFieldEqualOrSmallerThanZero: true)
return
}
toggleResultStatus(viewable: true)
resultLabel.text = result
}
@IBAction func onUpdatePricePerKmTextFields() {
guard let efficiency = readTextFieldAsDouble(textField: efficiencyTextField) else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 1, isTextFieldEmpty: true)
return
}
guard let fuelPrice = readTextFieldAsDouble(textField: fuelPriceTextField) else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 1, isTextFieldEmpty: true)
return
}
calculator.efficiency = efficiency
calculator.fuelPrice = fuelPrice
guard let result = calculator.getFormattedPricePerKm() else {
toggleResultStatus(viewable: false)
setCalcHelpText(calcTypeIndex: 1, isTextFieldEqualOrSmallerThanZero: true)
return
}
toggleResultStatus(viewable: true)
resultLabel.text = result
}
@IBAction func onPressShareButton() {
shareResult()
}
func shareResult() {
let shareText: [String];
if (calcTypeSegmentedControl.selectedSegmentIndex == 0) {
shareText = [ "O rendimento calculado é de \(resultLabel.text!)." ]
} else {
shareText = [ "O preço por km calculado é de \(resultLabel.text!)." ]
}
let activityViewController = UIActivityViewController(activityItems: shareText, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
|
0 | //
// ThermometerView.swift
// bleEnvironmentScanner
//
// Created by Thomas Petz, Jr. on 10/24/20.
//
import SwiftUI
struct Gauge: View {
var value: Float
var minRange: Float
var maxRange: Float
private func scaleValue() -> CGFloat {
if value <= minRange {
return CGFloat(0)
} else if value >= maxRange {
return CGFloat(1.0)
} else {
return CGFloat((value - minRange) / (maxRange - minRange))
}
}
var body: some View {
ZStack {
Rectangle()
.scale(x: scaleValue(), anchor: .leading)
.foregroundColor(.red)
.opacity(0.70)
Rectangle()
.inset(by: inset)
.stroke(lineWidth: 2)
.foregroundColor(.black)
Text(String(format: "%0.1f C", value))
}.frame(height: 20)
}
private let cornerRadius = CGFloat(8.0)
private let inset = CGFloat(2.0)
}
struct Gauge_Previews: PreviewProvider {
static var previews: some View {
Group {
Gauge(value: 15.0, minRange: -20.0, maxRange: 100.0)
Gauge(value: 90.0, minRange: 10.0, maxRange: 100.0)
}
}
}
|
0 | //
// ProductIds.swift
// CoinbaseSocketSwift
//
// Created by Hani Shabsigh on 10/29/17.
// Copyright © 2017 Hani Shabsigh. All rights reserved.
//
import Foundation
public enum ProductIds: String, CaseIterable {
case BTCUSD = "BTC-USD"
case BTCEUR = "BTC-EUR"
case BTCGBP = "BTC-GBP"
case ETHUSD = "ETH-USD"
case ETHBTC = "ETH-BTC"
case ETHEUR = "ETH-EUR"
case ETHGBP = "ETH-GBP"
case LTCUSD = "LTC-USD"
case LTCBTC = "LTC-BTC"
case LTCEUR = "LTC-EUR"
case LTCGBP = "LTC-GBP"
case BCHUSD = "BCH-USD"
case BCHBTC = "BCH-BTC"
case BCHEUR = "BCH-EUR"
case BCHGBP = "BCH-GBP"
case ETCUSD = "ETC-USD"
case ETCBTC = "ETC-BTC"
case ETCEUR = "ETC-EUR"
case ETCGBP = "ETC-GBP"
case ZRXUSD = "ZRX-USD"
case ZRXBTC = "ZRX-BTC"
case ZRXEUR = "ZRX-EUR"
case BTCUSDC = "BTC-USDC"
case ETHUSDC = "ETH-USDC"
case BATUSDC = "BAT-USDC"
case BATETH = "BAT-ETH"
case ZECUSDC = "ZEC-USDC"
case ZECBTC = "ZEC-BTC"
case REPUSD = "REP-USD"
case EOSUSD = "EOS-USD"
case ETHDAI = "ETH-DAI"
case XRPUSD = "XRP-USD"
case XRPEUR = "XRP-EUR"
case XRPBTC = "XRP-BTC"
case DAIUSDC = "DAI-USDC"
case LOOMUSDC = "LOOM-USDC"
case GNTUSDC = "GNT-USDC"
case MANAUSDC = "MANA-USDC"
case CVCUSDC = "CVC-USDC"
case DNTUSDC = "DNT-USDC"
case EOSEUR = "EOS-EUR"
case REPBTC = "REP-BTC"
case XLMEUR = "XLM-EUR"
case XLMBTC = "XLM-BTC"
case XLMUSD = "XLM-USD"
case EOSBTC = "EOS-BTC"
}
public struct DefaultProductIds {
public static func allCases() -> [String] {
return ProductIds.allCases.map { $0.rawValue }
}
}
|
0 | //
// CLLocationCoordinate2D.swift
// UStudy
//
// Created by Jann Schafranek on 09.02.20.
// Copyright © 2020 Jann Thomas. All rights reserved.
//
import Foundation
import CoreLocation
extension CLLocationCoordinate2D: Codable {
private enum CodingKeys: String, CodingKey {
case latitude, longitude
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(latitude, forKey: .latitude)
try container.encode(longitude, forKey: .longitude)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init()
self.latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude)
self.longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude)
}
}
|
0 | //
// DataConvertibleTests.swift
// DataConvertibleTests
//
// Created by Tatsuya Tanaka on 20180203.
// Copyright © 2018年 tattn. All rights reserved.
//
import XCTest
import DataConvertible
class DataConvertibleTests: XCTestCase {
struct Model: Codable, DataConvertible {
let string: String
let int: Int
}
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testEncodeAndDecode() throws {
let model = Model(string: "abc", int: 123)
let data = try model.convertToData()
let decoded = try Model(data: data)
XCTAssertEqual(model.string, decoded.string)
XCTAssertEqual(model.int, decoded.int)
}
}
|
0 | //
// CurrenciesRateAssembly.swift
// CurrencyRate
//
// Created by v.rusinov on 22/07/2019.
// Copyright © 2019 Vitaliy Rusinov. All rights reserved.
//
import UIKit
struct CurrenciesRateAssembly {
static func makeCurrenciesRateModule(rateServie: RateServiceInput, pairsStorage: PairsStorageServiceInput) -> CurrenciesRateModuleInput? {
guard let viewController = UIStoryboard(name: "CurrenciesRateStoryboard", bundle: nil).instantiateInitialViewController() as? CurrenciesRateViewController
else { return nil }
viewController.adapter = PairAdapter()
viewController.output = CurrenciesRatePresenter(view: viewController,
rateService: rateServie,
pairsStorage: ServiceLocator.sharedInstance.getService())
return viewController.output as? CurrenciesRateModuleInput
}
}
|
0 | //
// MetalFenceRegistry.swift
// MetalRenderer
//
// Created by Thomas Roughton on 20/07/19.
//
#if canImport(Metal)
@preconcurrency import Metal
import SubstrateUtilities
struct MetalFenceHandle : Equatable {
public var index : UInt32
init(index: UInt32) {
self.index = index
}
init(encoderIndex: Int, queue: Queue) {
self = MetalFenceRegistry.instance.allocate(queue: queue)
#if SUBSTRATE_DISABLE_AUTOMATIC_LABELS
_ = encoderIndex
#else
self.fence.label = "Encoder \(encoderIndex) Fence"
#endif
}
var isValid : Bool {
return self.index != .max
}
var fence : MTLFence {
get {
return MetalFenceRegistry.instance.fence(index: Int(self.index))
}
}
var commandBufferIndex : UInt64 {
get {
assert(self.isValid)
return MetalFenceRegistry.instance.commandBufferIndices[Int(self.index)].1
}
nonmutating set {
MetalFenceRegistry.instance.commandBufferIndices[Int(self.index)].1 = newValue
}
}
public static let invalid = MetalFenceHandle(index: .max)
}
final class MetalFenceRegistry {
public static var instance: MetalFenceRegistry! = nil
let lock = SpinLock()
public let allocator : ResizingAllocator
public var activeIndices = [UInt32]()
public var freeIndices = RingBuffer<UInt32>()
public var maxIndex : UInt32 = 0
public var device : MTLDevice
public var fences : UnsafeMutablePointer<Unmanaged<MTLFence>>
public var commandBufferIndices : UnsafeMutablePointer<(Queue, UInt64)> // On the queue
public init(device: MTLDevice) {
self.device = device
self.allocator = ResizingAllocator(allocator: .system)
(self.fences, self.commandBufferIndices) = allocator.reallocate(capacity: 256, initializedCount: 0)
}
deinit {
self.fences.deinitialize(count: Int(self.maxIndex))
}
public func allocate(queue: Queue) -> MetalFenceHandle {
self.lock.lock()
defer { self.lock.unlock() }
let index : UInt32
if let reusedIndex = self.freeIndices.popFirst() {
index = reusedIndex
} else {
index = self.maxIndex
self.ensureCapacity(Int(self.maxIndex + 1))
self.maxIndex += 1
self.fences.advanced(by: Int(index)).initialize(to: Unmanaged.passRetained(self.device.makeFence()!))
}
self.commandBufferIndices[Int(index)] = (queue, .max)
self.activeIndices.append(index)
return MetalFenceHandle(index: index)
}
// Work around Swift 5.5 compiler crash by providing a dedicated getter.
func fence(index: Int) -> MTLFence {
return self.lock.withLock { self.fences[index].takeUnretainedValue() }
}
func delete(at index: UInt32) {
self.freeIndices.append(index)
}
func clearCompletedFences() {
self.lock.withLock {
var i = 0
while i < self.activeIndices.count {
let index = self.activeIndices[i]
if self.commandBufferIndices[Int(index)].1 <= self.commandBufferIndices[Int(index)].0.lastCompletedCommand {
self.delete(at: index)
self.activeIndices.remove(at: i, preservingOrder: false)
} else {
i += 1
}
}
}
}
private func ensureCapacity(_ capacity: Int) {
if self.allocator.capacity < capacity {
let oldCapacity = self.allocator.capacity
let newCapacity = max(2 * oldCapacity, capacity)
(self.fences, self.commandBufferIndices) = allocator.reallocate(capacity: newCapacity, initializedCount: Int(self.maxIndex))
}
}
}
#endif // canImport(Metal)
|
0 | //
// CGFloatExtensionViewController.swift
// JKSwiftExtension_Example
//
// Created by IronMan on 2020/11/2.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class CGFloatExtensionViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
headDataArray = ["一、CGFloat 的基本转换", "二、角度和弧度相互转换"]
dataArray = [["转 Int", "转 CGFloat", "转 Int64", "转 Float", "转 String", "转 NSNumber", "转 Double"], ["角度转弧度", "弧度转角度"]]
}
}
// MARK:- 二、角度和弧度相互转换
extension CGFloatExtensionViewController {
// MARK: 2.1、角度转弧度
@objc func test21() {
let degrees: CGFloat = 90.0
JKPrint("角度转弧度", "角度: \(degrees) 转为弧度后为:\(degrees.degreesToRadians())")
}
// MARK: 2.2、弧度转角度
@objc func test22() {
let radians: CGFloat = .pi
JKPrint("角度转弧度", "弧度: \(radians) 转为角度后为:\(radians.radiansToDegrees())")
}
}
// MARK:- 一、基本的扩展
extension CGFloatExtensionViewController {
// MARK: 1.1、转 Int
@objc func test11() {
let value: CGFloat = 0.2
JKPrint("转 Int", "\(value) 转 Int 后为 \(value.int)")
}
// MARK: 1.2、转 CGFloat
@objc func test12() {
let value: CGFloat = 0.2
JKPrint("转 CGFloat", "\(value) 转 CGFloat 后为 \(value.cgFloat)")
}
// MARK: 1.3、转 Int64
@objc func test13() {
let value: CGFloat = 0.2
JKPrint("转 Int64", "\(value) 转 Int64 后为 \(value.int64)")
}
// MARK: 1.4、转 Float
@objc func test14() {
let value: CGFloat = 0.2
JKPrint("转 Float", "\(value) 转 Float 后为 \(value.float)")
}
// MARK: 1.5、转 String
@objc func test15() {
let value: CGFloat = 0.2
JKPrint("转 String", "\(value) 转 String 后为 \(value.string)")
}
// MARK: 1.6、转 NSNumber
@objc func test16() {
let value: CGFloat = 0.2
JKPrint("转 NSNumber", "\(value) 转 NSNumber 后为 \(value.number)")
}
// MARK: 1.7、转 Double
@objc func test17() {
let value: CGFloat = 0.2
JKPrint("转 Double", "\(value) 转 Double 后为 \(value.double)")
}
}
|
0 | // Copyright (c) 2017-2018 Han Sang-jin
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// This is a sample program using wxSwift and provides a simple user interface.
// Compile:
// windres --preprocessor=mcpp -i Application.rc -o Application.obj
// swiftc.exe SwiftForWindows.swift -o SwiftForWindows.exe -Xlinker
// --subsystem -Xlinker windows -Xlinker Application.obj
// strip SwiftForWindows.exe
import Foundation
import wx
//////////////////////////////////
// Build Configuration Structure
//////////////////////////////////
struct BuildConf : Codable {
var sfwbuild_version : String
var executable_name : String
var sources : [String]
var subsystem : String?
var strip : Bool?
}
//////////////////////////////
// Utility
//////////////////////////////
func quotedForCmd(_ path: String) -> String {
return path.replacingOccurrences(of:"\"", with:"\"\"\"").replacingOccurrences(of:" ", with:"\" \"")
}
class SfwController {
var view : SfwView?
var frame : wx.Frame?
init() {}
///////////////////////
// Callbacks
///////////////////////
func onSelectFile(_ event: Event) {
let openFileDialog = wx.FileDialog((view?.panel)!, "Select a source code file...", swift_src_dir, "",
"All files (*.swift;*.json)|*.swift;*.json|Swift files (*.swift)|*.swift|Build Configuration (*.json)|*.json",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if (openFileDialog.showModal() == wx.ID_CANCEL) {
return
}
swift_source = openFileDialog.getPath()
view?.selected_file?.clear()
view?.selected_file?.appendText(swift_source)
if swift_source.hasSuffix(".swift") {
let swift_source_name = URL(fileURLWithPath: swift_source).lastPathComponent
swift_out_exe = runtime_env_dir + "\\" + swift_source_name.replacingOccurrences(of:".swift", with:".exe")
// Show subsystem
view?.subsystem_static?.setLabel("console")
// Show strip job
view?.strip_static?.setLabel("No")
} else if swift_source.hasSuffix(".json") {
let configPath = swift_source
// Read config build file
guard let data = try? Data(contentsOf:URL(fileURLWithPath: configPath), options: .mappedIfSafe) else {
_ = wx.MessageDialog(frame!, "Error: Failed to read \(configPath)", "Select File", style:wx.OK).showModal()
return
}
// Decode json format
let decoder = JSONDecoder()
guard let build_conf = try? decoder.decode(BuildConf.self, from: data) else {
_ = wx.MessageDialog(frame!, "Error: Build configuration could not be parsed", "Select File", style:wx.OK).showModal()
return
}
// Check sfwbuild version
if !build_conf.sfwbuild_version.hasPrefix("0.1") {
_ = wx.MessageDialog(frame!, "Error: Build configuration for sfwbuild v\(build_conf.sfwbuild_version) is not supported", "Select File", style:wx.OK).showModal()
return
}
// Build executable path
let executable_name = build_conf.executable_name
let target_dir = installed_dir + "\\" + "RuntimeEnv"
swift_out_exe = target_dir + "\\" + executable_name + ".exe"
// Show subsystem
if build_conf.subsystem == "console" {
view?.subsystem_static?.setLabel(build_conf.subsystem!)
} else if build_conf.subsystem == "windows" {
view?.subsystem_static?.setLabel(build_conf.subsystem!)
} else if build_conf.subsystem == nil {
view?.subsystem_static?.setLabel("console")
} else {
_ = wx.MessageDialog(frame!, "Error: Unknown subsystem \(build_conf.subsystem!)", "Select File", style:wx.OK).showModal()
return
}
// Show strip job
if build_conf.strip != nil && build_conf.strip! {
view?.strip_static?.setLabel("Yes")
} else {
view?.strip_static?.setLabel("No")
}
}
}
func onProjectLatestNews(_ event: Event) {
_ = wx.launchDefaultBrowser("https://swiftforwindows.github.io/news")
}
func onHelp(_ event: Event) {
_ = wx.launchDefaultBrowser("https://swiftforwindows.github.io/help")
}
func onProjectWebsite(_ event: Event) {
_ = wx.launchDefaultBrowser("https://swiftforwindows.github.io/")
}
func onEnterLinkButton(_ event: Event) {
if let evtobj = event.EventObject as? Window {
evtobj.setBackgroundColour(wx.NullColour)
evtobj.setWindowStyle(wx.BORDER_DEFAULT)
}
}
func onLeaveLinkButton(_ event: Event) {
if let evtobj = event.EventObject as? Window {
evtobj.setBackgroundColour(wx.Colour(0xFFFFFF))
evtobj.setWindowStyle(wx.BORDER_NONE)
}
}
func onCompile(_ event: Event) {
if !swift_source.hasSuffix(".swift") && !swift_source.hasSuffix(".json") {
_ = wx.MessageDialog(frame!, "Select a *.swift or *.json file", "Compile", style:wx.OK).showModal()
return
}
if swift_source.hasSuffix(".json") {
// Building *.json
// Change current directory
let fileMgr = FileManager.default
let source_dir = URL(fileURLWithPath: swift_source, relativeTo:nil)
.deletingLastPathComponent()
.path
let _ = fileMgr.changeCurrentDirectoryPath(source_dir)
view?.log_textctrl?.clear()
let compiler_command = "\"\(sfwbuild_path)\" -f \"\(swift_source)\""
var message = compiler_command + "\n\n"
view?.log_textctrl?.appendText(message)
let exec_output = wx.executeOutErr(compiler_command)
message = exec_output + "\n\n"
if exec_output.contains("error:") || exec_output.contains("failed") {
message += "Compilation Failed" + "\n"
} else {
message += "Successfully compiled" + "\n"
}
view?.log_textctrl?.appendText(message)
return
}
if swift_source.hasSuffix(".swift") {
// Compiling *.swift
if !wx.fileExists(swift_compiler_exe) {
_ = wx.MessageDialog(frame!, "Compiler is not found.", "Compile", style:wx.OK).showModal()
return
}
view?.log_textctrl?.clear()
let compiler_command = "\"\(swift_compiler_exe)\" -swift-version 4 \"\(swift_source)\" -o \"\(swift_out_exe)\""
var message = compiler_command + "\n\n"
view?.log_textctrl?.appendText(message)
let exec_output = wx.executeOutErr(compiler_command)
message = exec_output + "\n\n"
if exec_output.contains("error:") || exec_output.contains("failed") {
message += "Compilation Failed" + "\n"
} else {
message += "Successfully compiled" + "\n"
}
view?.log_textctrl?.appendText(message)
}
}
func onRun(_ event: Event) {
if !swift_source.hasSuffix(".swift") && !swift_source.hasSuffix(".json") {
_ = wx.MessageDialog(frame!, "Select a *.swift or *.json file", "Compile", style:wx.OK).showModal()
return
}
view?.log_textctrl?.appendText("\n\(swift_out_exe)")
if !wx.fileExists(swift_out_exe) {
_ = wx.MessageDialog(frame!, "Compile first", "Run", style:wx.OK).showModal()
return
}
view?.log_textctrl?.clear()
if run_in_new_window {
let directory_of_swift_out_exe = String(describing: NSString(string: swift_out_exe).deletingLastPathComponent) + "\\"
let run_command = "cmd /C start /wait cmd /K \"" +
"cd \(directory_of_swift_out_exe) &" +
"\"\(run_path)\" \"\(swift_out_exe)\" &" +
"pause &" +
"exit" +
"\""
_ = wx.executeOutErr(run_command)
} else {
let run_command = "cmd /C \"\(swift_out_exe)\""
let exec_output = wx.executeOutErr(run_command)
let message = exec_output
view?.log_textctrl?.appendText(message)
}
}
func onCmd(_ event: Event) {
var cmd_start_dir = installed_dir
if swift_source.hasSuffix(".swift") || swift_source.hasSuffix(".json") {
cmd_start_dir = URL(fileURLWithPath: swift_source, relativeTo:nil)
.deletingLastPathComponent()
.path
}
let run_command = "cmd /K \" cd \(quotedForCmd(cmd_start_dir)) & \(quotedForCmd(swift_cmd))\""
_ = wx.execute(run_command, EXEC_ASYNC, nil)
}
func binding() {
guard let view = view else { return }
view.select_file_btn?.bind(wx.EVT_BUTTON, onSelectFile)
view.compile_button?.bind(wx.EVT_BUTTON, onCompile)
view.run_button?.bind(wx.EVT_BUTTON, onRun)
view.cmd_button?.bind(wx.EVT_BUTTON, onCmd)
view.news_button?.bind(wx.EVT_BUTTON, onProjectLatestNews)
view.help_button?.bind(wx.EVT_BUTTON, onHelp)
view.project_button?.bind(wx.EVT_BUTTON, onProjectWebsite)
}
func showFrame() {
view = SfwView()
guard let view = view else { return }
frame = view.buildFrame()
guard let frame = frame else { return }
// Output compiler setting
view.compiler_static?.setLabel(swift_compiler_exe)
view.version_static?.setLabel(swift_version_string)
view.subsystem_static?.setLabel(config_subsystem)
view.strip_static?.setLabel(binary_strip)
view.target_static?.setLabel(compile_target)
binding()
frame.show()
}
}
|
0 | ////
/// UIWebView.swift
//
public extension UIWebView {
func windowContentSize() -> CGSize? {
if let jsWidth = self.stringByEvaluatingJavaScriptFromString("(document.getElementById('post-container') || document.getElementByTagName('div')[0] || document.body).offsetWidth")
where !jsWidth.isEmpty
{
if let jsHeight = self.stringByEvaluatingJavaScriptFromString("(document.getElementById('post-container') || document.getElementByTagName('div')[0] || document.body).offsetHeight + 15")
where !jsHeight.isEmpty
{
let width = CGFloat((jsWidth as NSString).doubleValue)
let height = CGFloat((jsHeight as NSString).doubleValue)
return CGSize(width: width, height: height)
}
}
return nil
}
}
|
0 | //
// EndTutorialViewController.swift
// NWMuseumAR
//
// Created by Harrison Milbradt on 2018-02-15.
// Copyright © 2018 NWMuseumAR. All rights reserved.
//
import UIKit
class EndTutorialViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func navigate(_ sender: UIButton) {
// This instantiates a page viewcontroller for the main pages, and inits the transition style to not look bad
let viewController = NavigationViewController.init()
// .instantiatViewControllerWithIdentifier() returns AnyObject! this must be downcast to utilize it
// Present our viewcontroller to the screen
self.present(viewController, animated: false, completion: nil)
}
@IBAction func buttonPressed(_ sender: UIButton) {
// This instantiates a page viewcontroller for the main pages, and inits the transition style to not look bad
let viewController = MainPageViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
// .instantiatViewControllerWithIdentifier() returns AnyObject! this must be downcast to utilize it
// Present our viewcontroller to the screen
self.present(viewController, animated: false, completion: nil)
}
}
|
0 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Bond",
products: [
.library(name: "Bond", targets: ["Bond"])
],
dependencies: [
.package(url: "https://github.com/ReactiveKit/ReactiveKit.git", .upToNextMajor(from: "3.7.4")),
.package(url: "https://github.com/tonyarnold/Differ.git", .upToNextMajor(from: "1.0.0"))
],
targets: [
.target(name: "BNDProtocolProxyBase"),
.target(name: "Bond", dependencies: ["BNDProtocolProxyBase", "ReactiveKit", "Differ"]),
.testTarget(name: "BondTests", dependencies: ["Bond"])
]
)
|
0 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
`Schema` instances represent collections of model object schemas managed by a Realm.
When using Realm, `Schema` instances allow performing migrations and introspecting the database's schema.
Schemas map to collections of tables in the core database.
*/
public final class Schema: CustomStringConvertible {
// MARK: Properties
internal let rlmSchema: RLMSchema
/**
An array of `ObjectSchema`s for all object types in the Realm.
This property is intended to be used during migrations for dynamic introspection.
*/
public var objectSchema: [ObjectSchema] {
return rlmSchema.objectSchema.map(ObjectSchema.init)
}
/// A human-readable description of the object schemas contained within.
public var description: String { return rlmSchema.description }
// MARK: Initializers
internal init(_ rlmSchema: RLMSchema) {
self.rlmSchema = rlmSchema
}
// MARK: ObjectSchema Retrieval
/// Looks up and returns an `ObjectSchema` for the given class name in the Realm, if it exists.
public subscript(className: String) -> ObjectSchema? {
if let rlmObjectSchema = rlmSchema.schema(forClassName: className) {
return ObjectSchema(rlmObjectSchema)
}
return nil
}
}
// MARK: Equatable
extension Schema: Equatable {
/// Returns whether the two schemas are equal.
public static func == (lhs: Schema, rhs: Schema) -> Bool {
return lhs.rlmSchema.isEqual(to: rhs.rlmSchema)
}
}
|
0 | //
// URL+PropertyListDecoder.swift
// NetworkInfrastructure
//
// Created by Alonso on 5/25/20.
// Copyright © 2020 Alonso. All rights reserved.
//
import Foundation
extension URL {
func decodePropertyList<T: Decodable>() throws -> T {
let data = try Data(contentsOf: self)
let decoder = PropertyListDecoder()
return try decoder.decode(T.self, from: data)
}
}
|
0 | //
// BaseNC.swift
// NavigationTransitions
//
// Copyright © 2018 Chili. All rights reserved.
//
import UIKit
public class BaseNC: UINavigationController {
public enum NavigationTransitionStyle {
case sideBySide
}
private var backgroundStartOffset: CGFloat = 0
private var scrollableBackground: UIScrollView?
fileprivate var interactors: [NavigationInteractionProxy?] = []
private var transitionStyle: NavigationTransitionStyle?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public init(rootViewController: UIViewController, transitionStyle: NavigationTransitionStyle? = nil) {
super.init(rootViewController: rootViewController)
self.transitionStyle = transitionStyle
self.addBackground()
}
required init?(coder aDecoder: NSCoder) {
transitionStyle = .sideBySide
super.init(coder: aDecoder)
self.addUniversalBackground()
}
public override func viewDidLoad() {
super.viewDidLoad()
delegate = self
self.makeNavigationBarTransparent()
}
}
extension BaseNC: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController,
interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
let interactor = interactors.last
return interactor??.isPerforming == true ? (interactor as? UIViewControllerInteractiveTransitioning) : nil
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if viewController == navigationController.viewControllers.first {
interactors.removeAll()
}
}
public func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
initializeInteractorFor(toVC)
return pushOperationTransitionAnimator(for: toVC)
default:
return defaultAnimator(for: fromVC)
}
}
func initializeInteractorFor(_ vc: UIViewController) {
guard let style = transitionStyle else { return }
switch style {
case .sideBySide: addSideBySideInteractorFor(vc)
}
}
private func addSideBySideInteractorFor(_ vc: UIViewController) {
let interactor = SideBySidePushInteractor(attachTo: vc)
interactor?.completion = { [weak self] in
self?.interactors.removeLast()
}
interactors.append(interactor)
}
private func pushOperationTransitionAnimator(for vc: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let style = transitionStyle else { return nil }
switch style {
case .sideBySide: return SideBySidePushTransitionAnimator(direction: .left, navigationControl: self)
}
}
private func defaultAnimator(for vc: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let style = transitionStyle else { return nil }
switch style {
case .sideBySide: return SideBySidePushTransitionAnimator(direction: .right, navigationControl: self)
}
}
var bgMovementValue: CGFloat {
return view.frame.width / 2
// return 100
}
/// MARK: turn increase offset.x to negative for reverse scroll effect
func increaseBackgroundOffset() {
guard var offset = scrollableBackground?.contentOffset else { return }
offset.x -= bgMovementValue
scrollableBackground?.contentOffset = offset
}
/// MARK: turn decrease offset.x to positive for reverse scroll effect
func decreaseBackgroundOffset() {
guard var offset = scrollableBackground?.contentOffset else { return }
offset.x += bgMovementValue
scrollableBackground?.contentOffset = offset
}
func resetBackgroundOffset() {
guard var offset = scrollableBackground?.contentOffset else { return }
offset.x = backgroundStartOffset
scrollableBackground?.contentOffset = offset
}
}
extension BaseNC {
func addUniversalBackground() {
let scrollView = UIScrollView(frame: view.frame)
let img = #imageLiteral(resourceName: "main_bg")
let imgView = UIImageView(image: img.resizedImageWithinRect(rectSize: CGSize(width: img.size.width, height: UIScreen.main.bounds.height + 200)))
imgView.contentMode = .center
scrollView.addSubview(imgView)
scrollView.isUserInteractionEnabled = false
let offset = 0.2 * (imgView.image?.size.width ?? 0)
backgroundStartOffset = offset
scrollView.setContentOffset(CGPoint(x: offset, y: 0), animated: false)
self.view.insertSubview(scrollView, at: 0)
scrollableBackground = scrollView
}
func addBackground() {
let leftBackgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.red
return view
}()
let rightBackgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}()
let scrollView = UIScrollView(frame: view.frame)
leftBackgroundView.frame = CGRect(x: -(view.bounds.width), y: 0, width: view.bounds.width + (view.bounds.width/2), height: view.bounds.height)
rightBackgroundView.frame = CGRect(x: view.bounds.width/2, y: 0, width: view.bounds.width + 300, height: view.bounds.height)
scrollView.addSubview(leftBackgroundView)
scrollView.addSubview(rightBackgroundView)
scrollView.isUserInteractionEnabled = false
let offset = 0.2 * (leftBackgroundView.frame.size.width)
backgroundStartOffset = offset
scrollView.setContentOffset(CGPoint(x: offset, y: 0), animated: false)
self.view.insertSubview(scrollView, at: 0)
scrollableBackground = scrollView
}
}
extension UIImage {
func resizedImageWithinRect(rectSize: CGSize) -> UIImage? {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width: size.width / resizeFactor, height: size.height / resizeFactor)
let resized = scaleDown(to: newSize)
return resized
}
func scaleDown(to size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
draw(in: CGRect(origin: CGPoint.zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
extension UINavigationController {
func makeNavigationBarTransparent() {
self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
}
func resetNavigationBar() {
self.navigationBar.setBackgroundImage(nil, for: UIBarMetrics.default)
self.navigationBar.shadowImage = nil
self.navigationBar.isTranslucent = false
}
}
|
0 | //
// CoronavirusTrackerTests.swift
// CoronavirusTrackerTests
//
// Created by Александр Федоров on 25.04.2020.
// Copyright © 2020 Personal. All rights reserved.
//
import XCTest
@testable import CoronavirusTracker
final class CoronavirusTrackerTests: XCTestCase {
private var webservice = WebService()
private var dateFormatter = DateFormatter()
override func setUpWithError() throws {
webservice = WebService()
dateFormatter.dateFormat = "M/dd/yy"
}
func testCountryStatsRequest() throws {
let expectation = self.expectation(description: "load country stats")
let url = URL(string: "https://corona.lmao.ninja/v2/countries/ru")!
let resource = Resource<CountryStats>(url: url) { (data) -> CountryStats? in
return try? JSONDecoder().decode(CountryStats.self, from: data)
}
let result = CountryStats(country: "Russia", cases: 0, todayCases: 0, deaths: 0, todayDeaths: 0, recovered: 0)
var countryStats: CountryStats?
webservice.load(resource) { stats in
countryStats = stats
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(countryStats?.country, result.country)
}
func testParseDateString() {
let date = dateFormatter.date(from: "4/25/20")!
let result = DateHelper.dateString(date: date)
XCTAssertEqual("4/25/20", result)
}
func testParseDate() {
let date = dateFormatter.date(from: "4/25/20")
let result = DateHelper.date(dateString: "4/25/20")
XCTAssertEqual(date, result)
}
func testDayBeforeToday() {
let yesterdayDateString = "4/25/20"
let yesterdayDate = dateFormatter.date(from: yesterdayDateString)!
let result = DateHelper.dayBeforToday(count: 1)!
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .day))
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .month))
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .year))
}
func testPositiveTrend() {
let cases = [
"4/24/20": 10,
"4/25/20": 20]
let timeline = HistoryData.Timeline(cases: cases,
deaths: [:],
recovered: [:])
let history = HistoryData(country: "", timeline: timeline)
let stats = CountryStats(country: "",
cases: 0,
todayCases: 15,
deaths: 0,
todayDeaths: 0,
recovered: 0)
let result = TrendHelper.calculateTrend(history, stats)
XCTAssertEqual(result, "📈")
}
func testNegativeTrend() {
let cases = [
"4/24/20": 10,
"4/25/20": 20]
let timeline = HistoryData.Timeline(cases: cases,
deaths: [:],
recovered: [:])
let history = HistoryData(country: "", timeline: timeline)
let stats = CountryStats(country: "",
cases: 0,
todayCases: 5,
deaths: 0,
todayDeaths: 0,
recovered: 0)
let result = TrendHelper.calculateTrend(history, stats)
XCTAssertEqual(result, "📉")
}
}
|
0 | //
// MineVC.swift
// Wreath
//
// Created by 杨引 on 2018/10/9.
// Copyright © 2018 Y. All rights reserved.
//
import UIKit
class MineVC: BaseVC {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
let scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 0, width:UIScreen.screenWidth , height: UIScreen.screenHeight)
scrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: SCREEN_HEIGH)
self.view.addSubview(scrollView)
let topImageView = UIImageView()
topImageView.image = UIImage.init(named: "个人中心-背景")
scrollView.addSubview(topImageView)
topImageView.snp.makeConstraints { (make) in
make.centerX.equalTo(scrollView)
make.top.equalTo(scrollView)
}
}
func getData(name:String) {
mineProvider.request(.url3(name,["param1":"param1111","param2":"param22222"])) { result in
do {
let response = try result.dematerialize()
print("成功"+"\(response)")
//let value = try response.mapNSArray()
//print("成功"+"\(value)")
} catch {
let printableError = error as CustomStringConvertible
print("失败"+"\(printableError.description)")
}
}
}
}
|
0 | @objc
protocol NotificationManagerDelegate {
func didOpenNotification(_ notification: Notification)
}
@objc
final class NotificationManager: NSObject {
@objc var delegate: NotificationManagerDelegate?
@objc
func showNotification(_ notification: Notification) {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = notification.title
notificationContent.body = notification.text
notificationContent.sound = UNNotificationSound.default
notificationContent.userInfo = notification.userInfo
let notificationRequest = UNNotificationRequest(identifier: notification.identifier,
content: notificationContent,
trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1,
repeats: false))
UNUserNotificationCenter.current().add(notificationRequest)
}
}
extension NotificationManager: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if Notification.fromUserInfo(notification.request.content.userInfo) != nil {
completionHandler([.sound, .alert])
} else {
MWMPushNotifications.userNotificationCenter(center,
willPresent: notification,
withCompletionHandler: completionHandler)
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if let n = Notification.fromUserInfo(response.notification.request.content.userInfo) {
delegate?.didOpenNotification(n)
} else {
MWMPushNotifications.userNotificationCenter(center,
didReceive: response,
withCompletionHandler: completionHandler)
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.