hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
26eab6eb760e9610f571003f137b1012a59d9fb6 | 57,651 | //
// SnapCompilerTests.swift
// SnapCoreTests
//
// Created by Andrew Fox on 5/17/20.
// Copyright ยฉ 2020 Andrew Fox. All rights reserved.
//
import XCTest
import SnapCore
import TurtleCore
import TurtleSimulatorCore
class SnapCompilerTests: XCTestCase {
let kStaticStorageStartAddress = SnapCompilerMetrics.kStaticStorageStartAddress
func testCompileFailsDuringLexing() {
let compiler = SnapCompiler()
compiler.compile("@")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "@")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "unexpected character: `@'")
}
func testCompileFailsDuringParsing() {
let compiler = SnapCompiler()
compiler.compile(":")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, ":")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "operand type mismatch: `:'")
}
func testCompileFailsDuringCodeGeneration() {
let compiler = SnapCompiler()
compiler.compile("foo")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "use of unresolved identifier: `foo'")
}
func testEnsureDisassemblyWorks() {
let compiler = SnapCompiler()
compiler.compile("")
XCTAssertFalse(compiler.hasError)
XCTAssertGreaterThan(compiler.instructions.count, 0)
XCTAssertEqual(compiler.instructions.first?.disassembly, "LI UV, 0xff")
}
func test_EndToEndIntegration_SimplestProgram() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let a = 42
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 42)
}
func test_EndToEndIntegration_ForIn_Range_1() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a: u16 = 255
for i in 0..10 {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU16("a"), 9)
}
func test_EndToEndIntegration_ForIn_Range_2() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a: u16 = 255
let range = 0..10
for i in range {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU16("a"), 9)
}
func test_EndToEndIntegration_ForIn_Range_SingleStatement() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a: u16 = 255
for i in 0..10
a = i
""")
XCTAssertEqual(computer.loadSymbolU16("a"), 9)
}
func test_EndToEndIntegration_ForIn_String() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a = 255
for i in "hello" {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU8("a"), UInt8("o".utf8.first!))
}
func test_EndToEndIntegration_ForIn_ArrayOfU16() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a: u16 = 0xffff
for i in [_]u16{0x1000, 0x2000, 0x3000, 0x4000, 0x5000} {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU16("a"), UInt16(0x5000))
}
func test_EndToEndIntegration_ForIn_DynamicArray_1() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a: u16 = 0xffff
let arr = [_]u16{0x1000, 0x2000, 0x3000, 0x4000, 0x5000}
let slice: []u16 = arr
for i in slice {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU16("a"), UInt16(0x5000))
}
// TODO: This test fails. The problem seems to be binding the dynamic array to a temporary literal array. Is the failure expected, or is there a problem here?
func DISABLED_test_EndToEndIntegration_ForIn_DynamicArray_2() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a: u16 = 0xffff
let slice: []u16 = [_]u16{0x1000, 0x2000, 0x3000, 0x4000, 0x5000}
for i in slice {
a = i
}
""")
XCTAssertEqual(computer.loadSymbolU16("a"), UInt16(0x5000))
}
func test_EndToEndIntegration_Fibonacci() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a = 1
var b = 1
var fib = 0
for i in 0..10 {
fib = b + a
a = b
b = fib
}
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 89)
XCTAssertEqual(computer.loadSymbolU8("b"), 144)
}
func test_EndToEndIntegration_Fibonacci_ExercisingStaticKeyword() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a = 1
var b = 1
for i in 0..10 {
static var fib = b + a
a = b
b = fib
}
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 89)
XCTAssertEqual(computer.loadSymbolU8("b"), 144)
}
func testLocalVariablesDoNotSurviveTheLocalScope() {
let compiler = SnapCompiler()
compiler.compile("""
{
var a = 1
a = 2
}
a = 3
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "a")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 4..<5)
XCTAssertEqual(compiler.errors.first?.message, "use of unresolved identifier: `a'")
}
func testLocalVariablesDoNotSurviveTheLocalScope_ForLoop() {
let compiler = SnapCompiler()
compiler.compile("""
for i in 0..10 {
var a = i
}
i = 3
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "i")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 3..<4)
XCTAssertEqual(compiler.errors.first?.message, "use of unresolved identifier: `i'")
}
func test_EndToEndIntegration_StaticVarInAFunctionContextIsStoredInStaticDataArea() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() {
static var a = 0xaa
}
foo()
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress), 0xaa) // var a
}
// Local variables declared in a local scope are not necessarily associated
// with a new stack frame. In many cases, these variables are allocated in
// the same stack frame, or in the next slot of the static storage area.
func test_EndToEndIntegration_BlocksAreNotStackFrames_0() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a = 0xaa
{
var b = 0xbb
{
var c = 0xcc
}
}
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+0), 0xaa) // var a
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+1), 0xbb) // var b
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+2), 0xcc) // var c
}
// Local variables declared in a local scope are not necessarily associated
// with a new stack frame. In many cases, these variables are allocated in
// the same stack frame, or in the next slot of the static storage area.
func test_EndToEndIntegration_BlocksAreNotStackFrames_1() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var a = 0xaa
{
var b = a
{
{
{
var c = b
}
}
}
}
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+0), 0xaa) // var a
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+1), 0xaa) // var b
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress+2), 0xaa) // var c
}
func test_EndToEndIntegration_StoreLocalVariableDefinedSeveralScopesUp_StackFramesNotEqualToScopes() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u8 {
var b = 0xaa
func bar() -> u8 {
{
return b
}
}
return bar()
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 0xaa) // var a
}
func test_EndToEndIntegration_FunctionCall_NoArgs_ReturnU8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u8 {
return 0xaa
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 0xaa)
}
func test_EndToEndIntegration_FunctionCall_NoArgs_ReturnU16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u16 {
return 0xabcd
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU16("a"), 0xabcd)
}
func test_EndToEndIntegration_FunctionCall_NoArgs_ReturnU8PromotedToU16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u16 {
return 0xaa
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU16("a"), 0x00aa)
}
func test_EndToEndIntegration_NestedFunctionDeclarations() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u8 {
let val = 0xaa
func bar() -> u8 {
return val
}
return bar()
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 0xaa)
}
func test_EndToEndIntegration_ReturnFromInsideIfStmt() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u8 {
if 1 + 1 == 2 {
return 0xaa
} else {
return 0xbb
}
}
let a = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 0xaa)
}
func testMissingReturn_1() {
let compiler = SnapCompiler()
compiler.compile("""
func foo() -> u8 {
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "missing return in a function expected to return `u8'")
}
func testMissingReturn_2() {
let compiler = SnapCompiler()
compiler.compile("""
func foo() -> u8 {
if false {
return 1
}
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "missing return in a function expected to return `u8'")
}
func testUnexpectedNonVoidReturnValueInVoidFunction() {
let compiler = SnapCompiler()
compiler.compile("""
func foo() {
return 1
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "1")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 1..<2)
XCTAssertEqual(compiler.errors.first?.message, "unexpected non-void return value in void function")
}
func test_EndToEndIntegration_PromoteInAssignmentStatement() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var result = 0xabcd
result = 42
""")
XCTAssertEqual(computer.loadSymbolU16("result"), 42)
}
func test_EndToEndIntegration_PromoteParameterInCall() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var result = 0xabcd
func foo(n: u16) {
result = n
}
foo(42)
""")
XCTAssertEqual(computer.loadSymbolU16("result"), 42)
}
func test_EndToEndIntegration_PromoteReturnValue() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo(n: u8) -> u16 {
return n
}
let result = foo(42)
""")
XCTAssertEqual(computer.loadSymbolU16("result"), 42)
}
func test_EndToEndIntegration_MutuallyRecursiveFunctions() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func isEven(n: u8) -> bool {
if n == 0 {
return true
} else {
return isOdd(n - 1)
}
}
func isOdd(n: u8) -> bool {
if n == 0 {
return false
} else {
return isEven(n - 1)
}
}
let a = isOdd(7)
""")
XCTAssertEqual(computer.loadSymbolBool("a"), true)
}
func test_EndToEndIntegration_MutuallyRecursiveFunctions_u16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func isEven(n: u16) -> bool {
if n == 0 {
return true
} else {
return isOdd(n - 1)
}
}
func isOdd(n: u16) -> bool {
if n == 0 {
return false
} else {
return isEven(n - 1)
}
}
let a = isOdd(3)
""")
XCTAssertEqual(computer.loadSymbolBool("a"), true)
}
func test_EndToEndIntegration_RecursiveFunctions_u8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var count = 0
func foo(n: u8) {
if n > 0 {
count = count + 1
foo(n - 1)
}
}
foo(10)
""")
XCTAssertEqual(computer.loadSymbolU8("count"), 10)
}
func test_EndToEndIntegration_RecursiveFunctions_u16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var count = 0
func foo(n: u16) {
if n > 0 {
count = count + 1
foo(n - 1)
}
}
foo(10)
""")
XCTAssertEqual(computer.loadSymbolU8("count"), 10)
}
func test_EndToEndIntegration_FunctionCallsInExpression() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo(n: u8) -> u8 {
return n
}
let r = foo(2) + 1
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 3)
}
func test_EndToEndIntegration_RecursiveFunctions_() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo(n: u8) -> u8 {
if n == 0 {
return 0
}
return foo(n - 1) + 1
}
let count = foo(1)
""")
XCTAssertEqual(computer.loadSymbolU8("count"), 1)
}
func test_EndToEndIntegration_ReturnInVoidFunction() {
let executor = SnapExecutor()
let _ = try! executor.execute(program: """
func foo() {
return
}
foo()
""")
}
func test_EndToEndIntegration_DeclareVariableWithExplicitType_Let() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let foo: u16 = 0xffff
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 0xffff)
}
func test_EndToEndIntegration_DeclareVariableWithExplicitType_Var() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var foo: u16 = 0xffff
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 0xffff)
}
func test_EndToEndIntegration_DeclareVariableWithExplicitType_PromoteU8ToU16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let foo: u16 = 10
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 10)
}
func test_EndToEndIntegration_DeclareVariableWithExplicitType_Bool() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let foo: bool = true
""")
XCTAssertEqual(computer.loadSymbolBool("foo"), true)
}
func test_EndToEndIntegration_DeclareVariableWithExplicitType_CannotConvertU16ToBool() {
let compiler = SnapCompiler()
compiler.compile("""
let foo: bool = 0xffff
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "0xffff")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "cannot assign value of type `integer constant 65535' to type `const bool'")
}
func test_EndToEndIntegration_CastU16DownToU8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var foo: u16 = 1
let bar: u8 = foo as u8
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 1)
XCTAssertEqual(computer.loadSymbolU8("bar"), 1)
}
func test_EndToEndIntegration_PokeMemory() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
pokeMemory(0xab, \(kStaticStorageStartAddress))
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress), 0xab)
}
func test_EndToEndIntegration_PeekMemory() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let a = 0xab
let b = peekMemory(\(kStaticStorageStartAddress))
""")
XCTAssertEqual(computer.loadSymbolU8("a"), 0xab)
XCTAssertEqual(computer.loadSymbolU8("b"), 0xab)
}
func test_EndToEndIntegration_PokePeripheral() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
pokePeripheral(0xab, 0xffff, 1)
pokePeripheral(0xcd, 0xffff, 0)
""")
// There's a hardware bug in Rev 2 where the bits of the instruction
// RAM port connected to the data bus are in reverse order.
XCTAssertEqual(computer.lowerInstructionRAM.load(from: 0xffff), UInt8(0xab).reverseBits())
XCTAssertEqual(computer.upperInstructionRAM.load(from: 0xffff), UInt8(0xcd).reverseBits())
}
func test_EndToEndIntegration_PeekPeripheral() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let a = peekPeripheral(0, 0)
let b = peekPeripheral(0, 1)
""")
XCTAssertEqual(computer.lowerInstructionRAM.load(from: 0), 0)
XCTAssertEqual(computer.upperInstructionRAM.load(from: 0), 0)
XCTAssertEqual(computer.loadSymbolU8("a"), 0)
XCTAssertEqual(computer.loadSymbolU8("b"), 0)
}
func test_EndToEndIntegration_Hlt() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
pokeMemory(0xab, \(kStaticStorageStartAddress))
hlt()
pokeMemory(0xcd, \(kStaticStorageStartAddress))
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress), 0xab)
}
func test_EndToEndIntegration_DeclareArrayType_InferredType() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let arr = [_]u8{1, 2, 3}
""")
XCTAssertEqual(computer.loadSymbolArrayOfU8(3, "arr"), [1, 2, 3])
}
func test_EndToEndIntegration_DeclareArrayType_ExplicitType() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let arr: [_]u8 = [_]u8{1, 2, 3}
""")
XCTAssertEqual(computer.loadSymbolArrayOfU8(3, "arr"), [1, 2, 3])
}
func test_EndToEndIntegration_FailToAssignScalarToArray() {
let compiler = SnapCompiler()
compiler.compile("""
let arr: [_]u8 = 1
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "1")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "cannot assign value of type `integer constant 1' to type `[_]const u8'")
}
func test_EndToEndIntegration_FailToAssignFunctionToArray() {
let compiler = SnapCompiler()
compiler.compile("""
func foo(bar: u8, baz: u16) -> bool {
return false
}
let arr: [_]u16 = foo
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 3..<4)
XCTAssertEqual(compiler.errors.first?.message, "inappropriate use of a function type (Try taking the function's address instead.)")
}
func test_EndToEndIntegration_CannotAddArrayToInteger() {
let compiler = SnapCompiler()
compiler.compile("""
let foo = [_]u8{1, 2, 3}
let bar = 1 + foo
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "1 + foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 1..<2)
XCTAssertEqual(compiler.errors.first?.message, "binary operator `+' cannot be applied to operands of types `integer constant 1' and `[3]const u8'")
}
func test_EndToEndIntegration_ArrayOfIntegerConstantsConvertedToArrayOfU16OnInitialAssignment() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let arr: [_]u16 = [_]u16{100, 101, 102, 103, 104, 105, 106, 107, 108, 109}
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(10, "arr"), [100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
}
func test_EndToEndIntegration_ArrayOfU8ConvertedToArrayOfU16OnInitialAssignment() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let arr: [_]u16 = [_]u16{42 as u8}
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(1, "arr"), [42])
}
func test_EndToEndIntegration_ReadArrayElement_U16() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var result: u16 = 0
let arr: [_]u16 = [_]u16{100, 101, 102, 103, 104, 105, 106, 107, 108, 109}
result = arr[0]
""")
XCTAssertEqual(computer.loadSymbolU16("result"), 100)
}
func test_EndToEndIntegration_CastArrayLiteralFromArrayOfU8ToArrayOfU16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let foo = [_]u8{1, 2, 3} as [_]u16
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(3, "foo"), [1, 2, 3])
}
func test_EndToEndIntegration_FailToCastIntegerLiteralToArrayOfU8BecauseOfOverflow() {
let compiler = SnapCompiler()
compiler.compile("""
let foo = [_]u8{0x1001, 0x1002, 0x1003} as [_]u8
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "0x1001")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "integer constant `4097' overflows when stored into `u8'")
}
func test_EndToEndIntegration_CastArrayOfU16ToArrayOfU8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
let foo = [_]u16{0x1001 as u16, 0x1002 as u16, 0x1003 as u16} as [_]u8
""")
XCTAssertEqual(computer.loadSymbolArrayOfU8(3, "foo"), [1, 2, 3])
}
func test_EndToEndIntegration_ReassignArrayContentsWithLiteralArray() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var arr: [_]u16 = [_]u16{0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}
arr = [_]u16{100, 101, 102, 103, 104, 105, 106, 107, 108, 109}
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(10, "arr"), [100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
}
func test_EndToEndIntegration_ReassignArrayContentsWithArrayIdentifier() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a: [_]u16 = [_]u16{0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}
let b: [_]u16 = [_]u16{100, 101, 102, 103, 104, 105, 106, 107, 108, 109}
a = b
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(10, "a"), [100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
}
func test_EndToEndIntegration_ReassignArrayContents_ConvertingFromArrayOfU8ToArrayOfU16() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var a: [_]u16 = [_]u16{0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}
let b = [_]u8{100, 101, 102, 103, 104, 105, 106, 107, 108, 109}
a = b
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(10, "a"), [100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
}
func test_EndToEndIntegration_AccessVariableInFunction_U8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u8 {
let result: u8 = 42
return result
}
let bar = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("bar"), 42)
}
func test_EndToEndIntegration_AccessVariableInFunction_U16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u16 {
let result: u16 = 42
return result
}
let bar: u16 = foo()
""")
XCTAssertEqual(computer.loadSymbolU16("bar"), 42)
}
func test_EndToEndIntegration_SumLoop() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func sum() -> u8 {
var accum = 0
for i in 0..3 {
accum = accum + 1
}
return accum
}
let foo = sum()
""")
XCTAssertEqual(computer.loadSymbolU8("foo"), 3)
}
func test_EndToEndIntegration_PassArrayAsFunctionParameter_1() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
func sum(a: [3]u16) -> u16 {
return a[0] + a[1] + a[2]
}
let foo = sum([3]u16{1, 2, 3})
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 6)
}
func test_EndToEndIntegration_PassArrayAsFunctionParameter_2() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
func sum(a: [3]u16) -> u16 {
var accum: u16 = 0
for i in 0..3 {
accum = accum + a[i]
}
return accum
}
let foo = sum([_]u16{1, 2, 3})
""")
XCTAssertEqual(computer.loadSymbolU16("foo"), 6)
}
func test_EndToEndIntegration_ReturnArrayByValue_U8() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func makeArray() -> [3]u8 {
return [_]u8{1, 2, 3}
}
let foo = makeArray()
""")
XCTAssertEqual(computer.loadSymbolArrayOfU8(3, "foo"), [1, 2, 3])
}
func test_EndToEndIntegration_ReturnArrayByValue_U16() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func makeArray() -> [3]u16 {
return [_]u16{0x1234, 0x5678, 0x9abc}
}
let foo = makeArray()
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(3, "foo"), [0x1234, 0x5678, 0x9abc])
}
func test_EndToEndIntegration_PassTwoArraysAsFunctionParameters_1() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
func sum(a: [3]u8, b: [3]u8, c: u8) -> u8 {
return (a[0] + b[0] + a[1] + b[1] + a[2] + b[2]) * c
}
let foo = sum([_]u8{1, 2, 3}, [_]u8{4, 5, 6}, 2)
""")
XCTAssertEqual(computer.loadSymbolU8("foo"), 42)
}
func test_EndToEndIntegration_PassArraysAsFunctionArgumentsAndReturnArrayValue() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
func sum(a: [3]u8, b: [3]u8, c: u8) -> [3]u8 {
var result = [_]u8{0, 0, 0}
for i in 0..3 {
result[i] = (a[i] + b[i]) * c
}
return result
}
let foo = sum([_]u8{1, 2, 3}, [_]u8{4, 5, 6}, 2)
""")
XCTAssertEqual(computer.loadSymbolArrayOfU8(3, "foo"), [10, 14, 18])
}
func test_EndToEndIntegration_PassArraysAsFunctionArgumentsAndReturnArrayValue_U16() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
func sum(a: [3]u16, b: [3]u16, c: u16) -> [3]u16 {
var result = [_]u16{0, 0, 0}
for i in 0..3 {
result[i] = (a[i] + b[i]) * c
}
return result
}
let foo = sum([_]u8{1, 2, 3}, [_]u8{4, 5, 6}, 2)
""")
XCTAssertEqual(computer.loadSymbolArrayOfU16(3, "foo"), [10, 14, 18])
}
func test_EndToEndIntegration_BugWhenStackVariablesAreDeclaredAfterForLoop() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> u16 {
for i in 0..3 {
}
let a = 42
return a
}
let b = foo()
""")
XCTAssertEqual(computer.loadSymbolU16("b"), 42)
}
func testSerialOutput_HelloWorld() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
let computer = try! executor.execute(program: """
puts("Hello, World!")
""")
XCTAssertEqual(serialOutput, "Hello, World!")
print("total running time: \(computer.cpuState.uptime) cycles")
}
func testSerialOutput_Panic() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
panic("oops!")
puts("Hello, World!")
""")
XCTAssertEqual(serialOutput, "PANIC: oops!\n")
}
func testArrayOutOfBoundsError() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
let arr = "Hello"
let foo = arr[10]
""")
XCTAssertEqual(serialOutput, "PANIC: array access is out of bounds\n")
}
func test_EndToEndIntegration_ReadAndWriteToStructMember() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var result: u8 = 0
struct Foo {
bar: u8
}
var foo: Foo = undefined
foo.bar = 42
result = foo.bar
""")
XCTAssertEqual(computer.loadSymbolU8("result"), 42)
}
func test_EndToEndIntegration_StructInitialization() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo {
bar: u8
}
let foo = Foo { .bar = 42 }
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress), 42)
}
func test_EndToEndIntegration_AssignStructInitializerToStructInstance() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo {
bar: u8
}
var foo: Foo = undefined
foo = Foo { .bar = 42 }
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress), 42)
}
func test_EndToEndIntegration_ReadStructMembersThroughPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var r: u8 = 0
var foo = Foo { .x = 1, .y = 2, .z = 3 }
var bar = &foo
r = bar.x
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress + 0), 1)
}
func test_EndToEndIntegration_WriteStructMembersThroughPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var foo = Foo { .x = 1, .y = 2, .z = 3 }
var bar = &foo
bar.x = 2
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress + 0), 2)
}
func test_EndToEndIntegration_PassPointerToStructAsFunctionParameter() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var r: u8 = 0
var bar = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *Foo) -> u8 {
return foo.x + foo.y + foo.z
}
r = doTheThing(&bar)
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 6)
}
func test_EndToEndIntegration_CannotMakeMutatingPointerFromConstant_1() {
let compiler = SnapCompiler()
let program = """
let foo: u16 = 0xabcd
var bar: *u16 = &foo
"""
compiler.compile(program: program, base: 0)
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.first?.message, "cannot assign value of type `*const u16' to type `*u16'")
}
func test_EndToEndIntegration_CannotMakeMutatingPointerFromConstant_2() {
let compiler = SnapCompiler()
let program = """
struct Foo { x: u8, y: u8, z: u8 }
let bar = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *Foo) {
foo.x = foo.y * foo.z
}
doTheThing(&bar)
"""
compiler.compile(program: program, base: 0)
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.first?.message, "cannot convert value of type `*const Foo' to expected argument type `*Foo' in call to `doTheThing'")
}
func test_EndToEndIntegration_MutateThePointeeThroughAPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var bar = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *Foo) {
foo.x = foo.y * foo.z
}
doTheThing(&bar)
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress + 0), 6)
}
func test_EndToEndIntegration_FunctionReturnsPointerToStruct_Right() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var r: u8 = 0
var foo = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *Foo) -> *Foo {
return foo
}
r = doTheThing(&foo).x
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 1)
}
func test_EndToEndIntegration_FunctionReturnsPointerToStruct_Left() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var foo = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *Foo) -> *Foo {
return foo
}
doTheThing(&foo).x = 42
""")
XCTAssertEqual(computer.dataRAM.load(from: kStaticStorageStartAddress + 0), 42)
}
func test_EndToEndIntegration_GetArrayCountThroughAPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u16 = 0
let arr = [_]u8{ 1, 2, 3, 4 }
let ptr = &arr
r = ptr.count
""")
XCTAssertEqual(computer.loadSymbolU16("r"), 4)
}
func test_EndToEndIntegration_GetDynamicArrayCountThroughAPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u16 = 0
let arr = [_]u8{ 1, 2, 3, 4 }
let dyn: []u8 = arr
let ptr = &dyn
r = ptr.count
""")
XCTAssertEqual(computer.loadSymbolU16("r"), 4)
}
func test_EndToEndIntegration_GetPointeeOfAPointerThroughAPointer() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u16 = 0
let foo: u16 = 0xcafe
let bar = &foo
let baz = &bar
r = baz.pointee.pointee
""")
XCTAssertEqual(computer.loadSymbolU16("r"), 0xcafe)
}
func test_EndToEndIntegration_FunctionParameterIsPointerToConstType() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
struct Foo { x: u8, y: u8, z: u8 }
var r = 0
var foo = Foo { .x = 1, .y = 2, .z = 3 }
func doTheThing(foo: *const Foo) -> *const Foo {
return foo
}
r = doTheThing(&foo).x
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 1)
}
func test_EndToEndIntegration_CallAStructMemberFunction_1() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u8 = 0
struct Foo {
}
impl Foo {
func bar() -> u8 {
return 42
}
}
r = Foo.bar()
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 42)
}
func test_EndToEndIntegration_CallAStructMemberFunction_2() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u8 = 0
struct Foo {
aa: u8
}
impl Foo {
func bar(self: *const Foo, offset: u8) -> u8 {
return self.aa + offset
}
}
let foo = Foo {
.aa = 41
}
r = foo.bar(1)
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 42)
}
func test_EndToEndIntegration_CallAStructMemberFunction_3() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var r: u8 = 0
struct Foo {
aa: u8
}
impl Foo {
func bar(offset: u8) -> u8 {
return offset
}
}
let foo = Foo {
.aa = 41
}
r = foo.bar(42)
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 42)
}
func test_EndToEndIntegration_LinkedList() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
let computer = try! executor.execute(program: """
var r: u8 | None = none
struct LinkedList {
next: *const LinkedList | None,
key: u8,
value: u8
}
let c = LinkedList {
.next = none,
.key = 2,
.value = 42
}
let b = LinkedList {
.next = &c,
.key = 1,
.value = 0
}
let a = LinkedList {
.next = &b,
.key = 0,
.value = 0
}
impl LinkedList {
func lookup(self: *const LinkedList, key: u8) -> u8 | None {
if self.key == key {
return self.value
}
else match self.next {
(next: *const LinkedList) -> {
return next.lookup(key)
},
else -> {
return none
}
}
}
}
r = a.lookup(2)
""")
guard let symbol = computer.lookupSymbol("r") else {
XCTFail()
return
}
XCTAssertEqual(computer.dataRAM.load16(from: symbol.offset), 0x002a)
}
func test_EndToEndIntegration_Match_WithExtraneousClause() {
let compiler = SnapCompiler()
compiler.compile("""
var r: u8 = 0
var a: u8 = 0
match a {
(foo: u8) -> {
a = 1
},
(foo: bool) -> {
a = 2
},
else -> {
a = 3
}
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "foo: bool")
XCTAssertEqual(compiler.errors.first?.message, "extraneous clause in match statement: bool")
}
func test_EndToEndIntegration_Match_WithMissingClause() {
let compiler = SnapCompiler()
compiler.compile("""
var r: u8 = 0
var a: u8 | bool = 0
match a {
(foo: u8) -> {
a = 1
}
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "a")
XCTAssertEqual(compiler.errors.first?.message, "match statement is not exhaustive. Missing clause: bool")
}
func testFunctionReturnsConstValue() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
func foo() -> const u8 {
return 42
}
let r = foo()
""")
XCTAssertEqual(computer.loadSymbolU8("r"), 42)
}
func testAssignmentExpressionItselfHasAValue() {
let executor = SnapExecutor()
let computer = try! executor.execute(program: """
var foo: u8 = 0
var bar: u8 = (foo = 42)
""")
XCTAssertEqual(computer.loadSymbolU8("foo"), 42)
XCTAssertEqual(computer.loadSymbolU8("bar"), 42)
}
func testArraySlice() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
let helloWorld = "Hello, World!"
let helloComma = helloWorld[0..6]
let hello = helloComma[0..(helloComma.count-1)]
puts(hello)
""")
XCTAssertEqual(serialOutput, "Hello")
}
func testArraySlice_PanicDueToArrayBoundsException() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
let helloWorld = "Hello, World!"
let helloComma = helloWorld[0..6]
let hello = helloComma[0..1000]
puts(hello)
""")
XCTAssertEqual(serialOutput, "PANIC: array access is out of bounds\n")
}
func testAssertionFailed() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
assert(1 == 2)
""")
XCTAssertEqual(serialOutput, "PANIC: assertion failed: `1 == 2' on line 1\n")
}
func testRunTests_AllTestsPassed() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.shouldRunSpecificTest = "foo"
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
test "foo" {
}
""")
XCTAssertEqual(serialOutput, "passed\n")
}
func testRunTests_FailingAssertMentionsFailingTestByName() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.shouldRunSpecificTest = "foo"
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
test "foo" {
assert(1 == 2)
}
""")
XCTAssertEqual(serialOutput, "PANIC: assertion failed: `1 == 2' on line 2 in test \"foo\"\n")
}
func testImportModule() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
executor.injectModule(name: "MyModule", sourceCode: """
public func foo() {
puts("Hello, World!")
}
""")
_ = try! executor.execute(program: """
import MyModule
foo()
""")
XCTAssertEqual(serialOutput, "Hello, World!")
}
func testBasicFunctionPointerDemonstration() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
let ptr = &puts
ptr("Hello, World!")
""")
XCTAssertEqual(serialOutput, "Hello, World!")
}
func testRebindAFunctionPointerAtRuntime() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
public func fakePuts(s: []const u8) {
puts("fake")
}
var ptr = &puts
ptr = &fakePuts
ptr("Hello, World!")
""")
XCTAssertEqual(serialOutput, "fake")
}
func testFunctionPointerStructMemberCanBeCalledLikeAFunctionMemberCanBeCalled_1() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
struct Serial {
puts: func ([]const u8) -> void
}
let serial = Serial {
.puts = &puts
}
serial.puts("Hello, World!")
""")
XCTAssertEqual(serialOutput, "Hello, World!")
}
func testFunctionPointerStructMemberCanBeCalledLikeAFunctionMemberCanBeCalled_2() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
struct Foo {
bar: func (*const Foo, []const u8) -> void
}
func baz(self: *const Foo, s: []const u8) -> void {
puts(s)
}
let foo = Foo {
.bar = &baz
}
foo.bar("Hello, World!")
""")
XCTAssertEqual(serialOutput, "Hello, World!")
}
func testStructInitializerCanHaveExplicitUndefinedValue() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
var computer: Computer? = nil
XCTAssertNoThrow(computer = try executor.execute(program: """
struct Foo {
arr: [64]u8
}
var foo = Foo {
.arr = undefined
}
"""))
let arr = computer?.lookupSymbol("foo")
XCTAssertNotNil(arr)
}
func testSubscriptStructMemberThatIsAnArray() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
var computer: Computer? = nil
XCTAssertNoThrow(computer = try executor.execute(program: """
struct Foo {
arr: [64]u8
}
var foo: Foo = undefined
foo.arr[0] = 42
let baz = foo.arr[0]
"""))
XCTAssertEqual(computer?.loadSymbolU8("baz"), 42)
}
func testSubscriptStructMemberThatIsADynamicArray() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
var computer: Computer? = nil
XCTAssertNoThrow(computer = try executor.execute(program: """
let backing: [64]u8 = undefined
struct Foo {
arr: []u8
}
var foo = Foo {
.arr = backing
}
foo.arr[0] = 42
let baz = foo.arr[0]
"""))
XCTAssertEqual(computer?.loadSymbolU8("baz"), 42)
}
func testBugWithCompilerTemporaryPushedTwiceInDynamicArrayBoundsCheck() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.shouldRunSpecificTest = "foo"
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
XCTAssertNoThrow(try executor.execute(program: """
let slice: []const u8 = "test"
test "foo" {
assert(slice[0] == 't')
}
"""))
XCTAssertEqual(serialOutput, "passed\n")
}
func testBugWhenConvertingStringLiteralToDynamicArrayInFunctionParameter() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
var computer: Computer? = nil
XCTAssertNoThrow(computer = try executor.execute(program: """
public struct Foo {
}
impl Foo {
func bar(self: *Foo, s: []const u8) -> u8 {
return s[0]
}
}
var foo: Foo = undefined
let baz = foo.bar("t")
"""))
XCTAssertEqual(computer?.loadSymbolU8("baz"), 116)
}
func testVtableDemo() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.shouldRunSpecificTest = "call through vtable pseudo-interface"
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
XCTAssertNoThrow(try executor.execute(program: """
public struct Serial {
print: func (*Serial, []const u8) -> void
}
public struct SerialFake {
vtable: Serial,
buffer: [64]u8,
cursor: u16
}
impl SerialFake {
func init() -> SerialFake {
var serial: SerialFake = undefined
serial.cursor = 0
for i in 0..(serial.buffer.count) {
serial.buffer[i] = 0
}
serial.vtable.print = &serial.print_ bitcastAs func (*Serial, []const u8) -> void
return serial
}
func asSerial(self: *SerialFake) -> *Serial {
return self bitcastAs *Serial
}
func print_(self: *SerialFake, s: []const u8) {
for i in 0..(s.count) {
self.buffer[self.cursor + i] = s[i]
}
self.cursor = self.cursor + s.count
}
}
test "call through vtable pseudo-interface" {
var serialFake = SerialFake.init()
let serial = serialFake.asSerial()
serial.print("test")
assert(serialFake.cursor == 4)
assert(serialFake.buffer[0] == 't')
assert(serialFake.buffer[1] == 'e')
assert(serialFake.buffer[2] == 's')
assert(serialFake.buffer[3] == 't')
}
"""))
XCTAssertEqual(serialOutput, "passed\n")
}
func testTraitsDemo() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.shouldRunSpecificTest = "call through trait interface"
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
XCTAssertNoThrow(try executor.execute(program: """
trait Serial {
func puts(self: *Serial, s: []const u8)
}
struct SerialFake {
buffer: [64]u8,
cursor: u16
}
impl SerialFake {
func init() -> SerialFake {
var serial: SerialFake = undefined
serial.cursor = 0
for i in 0..(serial.buffer.count) {
serial.buffer[i] = 0
}
return serial
}
}
impl Serial for SerialFake {
func puts(self: *SerialFake, s: []const u8) {
for i in 0..(s.count) {
self.buffer[self.cursor + i] = s[i]
}
self.cursor = self.cursor + s.count
}
}
test "call through trait interface" {
var serialFake = SerialFake.init()
let serial: Serial = &serialFake
serial.puts("test")
assert(serialFake.cursor == 4)
assert(serialFake.buffer[0] == 't')
assert(serialFake.buffer[1] == 'e')
assert(serialFake.buffer[2] == 's')
assert(serialFake.buffer[3] == 't')
}
"""))
XCTAssertEqual(serialOutput, "passed\n")
}
func testTraitsFailToCompileBecauseTraitNotImplementedAppropriately() {
let compiler = SnapCompiler()
compiler.isUsingStandardLibrary = true
compiler.compile("""
trait Serial {
func puts(self: *Serial, s: []const u8)
}
struct SerialFake {
buffer: [64]u8,
cursor: u16
}
impl SerialFake {
func init() -> SerialFake {
var serial: SerialFake = undefined
serial.cursor = 0
for i in 0..(serial.buffer.count) {
serial.buffer[i] = 0
}
return serial
}
}
impl Serial for SerialFake {
func puts(self: *SerialFake) {
}
}
test "call through trait interface" {
var serialFake = SerialFake.init()
let serial: Serial = &serialFake
serial.puts("test")
assert(serialFake.cursor == 4)
assert(serialFake.buffer[0] == 't')
assert(serialFake.buffer[1] == 'e')
assert(serialFake.buffer[2] == 's')
assert(serialFake.buffer[3] == 't')
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "impl Serial for SerialFake {")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 20..<21)
XCTAssertEqual(compiler.errors.first?.message, "`SerialFake' method `puts' has 1 parameter but the declaration in the `Serial' trait has 2.")
}
func DISABLED_testBugWhereUnableToAllocateTemporaryWhenReturningLargeStructByValue() {
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
XCTAssertNoThrow(try executor.execute(program: """
struct Foo {
buffer: [1000]u8
}
var foo: Foo = undefined
func init() -> Foo {
return foo
}
"""))
}
func testBugWhereConstRangeCannotBeUsedToSubscriptAString() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
let helloWorld = "Hello, World!"
let range = 0..6
let helloComma = helloWorld[range]
let hello = helloComma[0..(helloComma.count-1)]
puts(hello)
""")
XCTAssertEqual(serialOutput, "Hello")
}
func testBugSymbolResolutionInStructMethodsPutsMembersInScopeWithBrokenOffsets() {
let compiler = SnapCompiler()
compiler.compile("""
struct Foo {
bar: u8
}
impl Foo {
func init() -> Foo {
var foo: Foo = undefined
bar = 42
return foo
}
}
let foo = Foo.init()
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "bar")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 7..<8)
XCTAssertEqual(compiler.errors.first?.message, "use of unresolved identifier: `bar'")
}
func testBugWhereRangeInSubscriptCausesUnsupportedExpressionError() {
var serialOutput = ""
let executor = SnapExecutor()
executor.isUsingStandardLibrary = true
executor.configure = { computer in
computer.didUpdateSerialOutput = {
serialOutput = $0
}
}
_ = try! executor.execute(program: """
struct Foo {
buffer: []const u8
}
let foo = Foo {
.buffer = "Hello, World!"
}
foo.buffer = foo.buffer[0..5]
puts(foo.buffer)
""")
XCTAssertEqual(serialOutput, "Hello")
}
func testBugWhereImplErrorIsMissingSourceAnchor() {
let compiler = SnapCompiler()
compiler.compile("""
impl Foo {
}
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "Foo")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 0..<1)
XCTAssertEqual(compiler.errors.first?.message, "use of undeclared type `Foo'")
}
func testBugWhereConstSelfPointerInTraitCausesCompilerCrash() {
let compiler = SnapCompiler()
compiler.compile("""
trait Serial {
func print(self: *const Serial, s: []const u8)
}
""")
XCTAssertFalse(compiler.hasError)
}
func testCrashWhenReturningAZeroSizeStruct() {
let compiler = SnapCompiler()
compiler.compile("""
struct Empty {}
func init() -> Empty {
return Empty {}
}
let foo = init()
""")
XCTAssertFalse(compiler.hasError)
}
func testBugWhereCompilerPermitsImplicitConversionFromUnionToMemberType() {
let compiler = SnapCompiler()
compiler.compile("""
var a: u8 | bool = 42
var b: u8 = a
""")
XCTAssertTrue(compiler.hasError)
XCTAssertEqual(compiler.errors.count, 1)
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.text, "a")
XCTAssertEqual(compiler.errors.first?.sourceAnchor?.lineNumbers, 1..<2)
XCTAssertEqual(compiler.errors.first?.message, "cannot implicitly convert a union type `u8 | bool' to `u8'; use an explicit conversion instead")
}
func testBugWhereCompilerDoesNotConvertUnionValuesOfDifferentConstness() {
let compiler = SnapCompiler()
compiler.compile("""
var a: u8 | bool = 42
let b: u8 | bool = a
""")
XCTAssertFalse(compiler.hasError)
}
func testWeCannotUseVariableBeforeItIsDeclared() {
let compiler = SnapCompiler()
compiler.compile("""
func main() {
a = 1
var a: u16 = 0
}
""")
XCTAssertTrue(compiler.hasError)
}
}
| 29.625385 | 162 | 0.6224 |
71c503fb1f5b45be410f5c69b6720e584010bd24 | 536 | import GfxMath
import Foundation
import Drawing
// TODO: actually these are MaterialDESIGNIcons (not from google) --> use the google ones
public class MaterialDesignIcon: ComposedWidget {
private let identifier: Identifier
public init(_ identifier: Identifier) {
self.identifier = identifier
super.init()
}
@Compose override public var content: ComposedContent {
Text(String(Unicode.Scalar(identifier.code)!))/*.with(styleProperties: {
//(\.$fontFamily, MaterialDesignIcon.materialFontFamily)
})*/
}
} | 28.210526 | 89 | 0.73694 |
9c607b1ad2c140d55e1e70cc8b68891f8b4c89bf | 16,682 | //
// SBATrackedItemsLoggingStepObject.swift
// BridgeApp
//
// Copyright ยฉ 2018-2021 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
import JsonModel
import Research
import BridgeApp
import BridgeSDK
/// `SBATrackedItemsLoggingStepObject` is a custom table step that can be used to log the same
/// information about a list of tracked items for each one.
open class SBATrackedItemsLoggingStepObject : SBATrackedSelectionStepObject {
open override class func defaultType() -> RSDStepType {
.logging
}
#if !os(watchOS)
/// Implement the view controller vending in the model with compile flag. This is required so that
/// subclasses can override this method to return a different implementation of the view controller.
/// Note: The task delegate can also override this to return a different view controller.
open func instantiateViewController(with parent: RSDPathComponent?) -> (UIViewController & RSDStepController)? {
return SBATrackedLoggingStepViewController(step: self, parent: parent)
}
#endif
/// Override to add the "submit" button for the action.
override open func action(for actionType: RSDUIActionType, on step: RSDStep) -> RSDUIAction? {
// If the dictionary includes an action then return that.
if let action = self.actions?[actionType] { return action }
// Only special-case for the goForward action.
guard actionType == .navigation(.goForward) else { return nil }
// If this is the goForward action then special-case to use the "Submit" button
// if there isn't a button in the dictionary.
let goForwardAction = RSDUIActionObject(buttonTitle: Localization.localizedString("BUTTON_SUBMIT"))
var actions = self.actions ?? [:]
actions[actionType] = goForwardAction
self.actions = actions
return goForwardAction
}
/// Override to return an instance of `SBATrackedLoggingDataSource`.
override open func instantiateDataSource(with parent: RSDPathComponent?, for supportedHints: Set<RSDFormUIHint>) -> RSDTableDataSource? {
return SBATrackedLoggingDataSource(step: self, parent: parent)
}
/// Override to return a collection result that is pre-populated with the a new set of logging objects.
override open func instantiateStepResult() -> ResultData {
var collectionResult = SBATrackedLoggingCollectionResultObject(identifier: self.identifier)
collectionResult.updateSelected(to: self.result?.selectedAnswers.map { $0.identifier }, with: self.items)
return collectionResult
}
}
extension SerializableResultType {
public static let loggingItem: SerializableResultType = "loggingItem"
public static let loggingCollection: SerializableResultType = "loggingCollection"
public static let symptom: SerializableResultType = "symptom"
public static let symptomCollection: SerializableResultType = "symptomCollection"
public static let trigger: SerializableResultType = "trigger"
public static let triggerCollection: SerializableResultType = "triggerCollection"
}
/// `SBATrackedLoggingCollectionResultObject` is used include multiple logged items in a single logging result.
public struct SBATrackedLoggingCollectionResultObject : SerializableResultData, RSDCollectionResult, Codable, SBATrackedItemsCollectionResult, RSDNavigationResult {
private enum CodingKeys : String, CodingKey {
case identifier, serializableType = "type", startDate, endDate, loggingItems = "items"
}
/// The identifier associated with the task, step, or asynchronous action.
public let identifier: String
/// A String that indicates the type of the result. This is used to decode the result using a `RSDFactory`.
public var serializableType: SerializableResultType
/// The start date timestamp for the result.
public var startDate: Date = Date()
/// The end date timestamp for the result.
public var endDate: Date = Date()
/// The list of logging results associated with this result.
public var loggingItems: [SBATrackedLoggingResultObject]
// The input results are the logging items.
public var children: [ResultData] {
get {
return loggingItems
}
set {
loggingItems = newValue.compactMap { $0 as? SBATrackedLoggingResultObject }
}
}
/// The step identifier to skip to after this result.
public var skipToIdentifier: String?
/// Default initializer for this object.
///
/// - parameters:
/// - identifier: The identifier string.
public init(identifier: String) {
self.identifier = identifier
self.serializableType = .loggingCollection
self.loggingItems = []
}
public func copy(with identifier: String) -> SBATrackedLoggingCollectionResultObject {
var copy = SBATrackedLoggingCollectionResultObject(identifier: identifier)
copy.startDate = self.startDate
copy.endDate = self.endDate
copy.serializableType = self.serializableType
copy.loggingItems = self.loggingItems
return copy
}
/// Returns the subset of selected answers that conform to the tracked item answer.
public var selectedAnswers: [SBATrackedItemAnswer] {
return self.loggingItems
}
/// Adds a `SBATrackedLoggingResultObject` for each identifier.
public mutating func updateSelected(to selectedIdentifiers: [String]?, with items: [SBATrackedItem]) {
let results = sort(selectedIdentifiers, with: items).map { (identifier) -> SBATrackedLoggingResultObject in
if let result = self.loggingItems.first(where: { $0.identifier == identifier }) {
return result
}
let item = items.first(where: { $0.identifier == identifier })
return SBATrackedLoggingResultObject(identifier: identifier, text: item?.text, detail: item?.detail)
}
self.loggingItems = results
}
/// Update the details to the new value. This is only valid for a new value that is an `ResultData`.
public mutating func updateDetails(from result: ResultData) {
if let loggingResult = result as? SBATrackedLoggingResultObject {
self.appendInputResults(with: loggingResult)
}
else if let collectionResult = result as? SBATrackedLoggingCollectionResultObject {
self.loggingItems = collectionResult.loggingItems
}
else {
assertionFailure("This is not a valid tracked item answer type. Cannot map to a result.")
}
}
/// Build the client data for this result.
public func dataScore() throws -> JsonSerializable? {
// Only include the client data for the logging result and not the selection result.
guard identifier == RSDIdentifier.trackedItemsResult.stringValue
else {
return nil
}
return try self.rsd_jsonEncodedDictionary().jsonObject()
}
/// Update the selection from the client data.
mutating public func updateSelected(from clientData: SBBJSONValue, with items: [SBATrackedItem]) throws {
guard let dictionary = (clientData as? NSDictionary) ?? (clientData as? [NSDictionary])?.last
else {
throw RSDValidationError.invalidType("\(clientData)")
}
// When coming from clientData, the report data might include additional results, in which
// case the scoring for *this* result will be included as a key/value dictionary within
// another dictionary.
let previousData: NSDictionary = {
if let trackedItems = dictionary["trackedItems"] as? NSDictionary,
let type = trackedItems[CodingKeys.serializableType.rawValue] as? String,
self.serializableType.rawValue == type {
return trackedItems
}
else {
return dictionary
}
}()
let decoder = SBAFactory.shared.createJSONDecoder()
let result = try decoder.decode(SBATrackedLoggingCollectionResultObject.self, from: previousData)
self.loggingItems = result.loggingItems.map {
return SBATrackedLoggingResultObject(identifier: $0.identifier, text: $0.text, detail: $0.detail)
}
}
public func deepCopy() -> SBATrackedLoggingCollectionResultObject {
self.copy(with: self.identifier)
}
}
/// `SBATrackedLoggingResultObject` is used include multiple results associated with a tracked item.
public struct SBATrackedLoggingResultObject : SerializableResultData, RSDCollectionResult, Codable {
private enum CodingKeys : String, CodingKey {
case identifier, text, detail, loggedDate, itemIdentifier, timingIdentifier, timeZone
}
/// The identifier associated with the task, step, or asynchronous action.
public let identifier: String
/// The identifier that maps to the `SBATrackedItem`.
public var itemIdentifier: String?
/// The timing identifier to map to a schedule.
public var timingIdentifier: String?
/// The title for the tracked item.
public var text: String?
/// A detail string for the tracked item.
public var detail: String?
/// The marker for when the tracked item was logged.
public var loggedDate: Date?
/// The time zone to use for the loggedDate.
public let timeZone: TimeZone
/// A String that indicates the type of the result. This is used to decode the result using a `RSDFactory`.
public var serializableType: SerializableResultType = .loggingItem
/// The start date timestamp for the result.
public var startDate: Date = Date()
/// The end date timestamp for the result.
public var endDate: Date = Date()
/// The list of input results associated with this step. These are generally assumed to be answers to
/// field inputs, but they are not required to implement the `RSDAnswerResult` protocol.
public var children: [ResultData]
/// Default initializer for this object.
///
/// - parameters:
/// - identifier: The identifier string.
public init(identifier: String, text: String? = nil, detail: String? = nil) {
self.identifier = identifier
self.text = text
self.detail = detail
self.children = []
self.timeZone = TimeZone.current
}
internal init(identifier: String, text: String?, detail: String?, loggedDate: Date?, timeZone: TimeZone, children: [ResultData]) {
self.identifier = identifier
self.text = text
self.detail = detail
self.children = children
self.timeZone = timeZone
self.loggedDate = loggedDate
}
/// Initialize from a `Decoder`. This decoding method will use the `RSDFactory` instance associated
/// with the decoder to decode the `children`.
///
/// - parameter decoder: The decoder to use to decode this instance.
/// - throws: `DecodingError`
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.identifier = try container.decode(String.self, forKey: .identifier)
self.itemIdentifier = try container.decodeIfPresent(String.self, forKey: .itemIdentifier)
self.timingIdentifier = try container.decodeIfPresent(String.self, forKey: .timingIdentifier)
self.text = try container.decodeIfPresent(String.self, forKey: .text)
self.detail = try container.decodeIfPresent(String.self, forKey: .detail)
self.loggedDate = try container.decodeIfPresent(Date.self, forKey: .loggedDate)
if let tzIdentifier = try container.decodeIfPresent(String.self, forKey: .timeZone) {
self.timeZone = TimeZone(identifier: tzIdentifier) ?? TimeZone.current
}
else {
self.timeZone = TimeZone.current
}
// TODO: syoung 05/30/2018 Decode the answers.
self.children = []
}
/// Encode the result to the given encoder.
/// - parameter encoder: The encoder to use to encode this instance.
/// - throws: `EncodingError`
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(identifier, forKey: .identifier)
try container.encodeIfPresent(itemIdentifier, forKey: .itemIdentifier)
try container.encodeIfPresent(timingIdentifier, forKey: .timingIdentifier)
try container.encodeIfPresent(text, forKey: .text)
try container.encodeIfPresent(detail, forKey: .detail)
guard let loggedDate = self.loggedDate else { return }
let formatter = encoder.factory.timestampFormatter.copy() as! DateFormatter
formatter.timeZone = self.timeZone
let loggingString = formatter.string(from: loggedDate)
try container.encode(loggingString, forKey: .loggedDate)
try container.encode(self.timeZone.identifier, forKey: .timeZone)
var anyContainer = encoder.container(keyedBy: AnyCodingKey.self)
try children.forEach { result in
let key = AnyCodingKey(stringValue: result.identifier)!
guard let answerResult = result as? RSDAnswerResult
else {
var codingPath = encoder.codingPath
codingPath.append(key)
let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Result does not conform to RSDAnswerResult protocol")
throw EncodingError.invalidValue(result, context)
}
guard let value = answerResult.value
else {
return
}
let nestedEncoder = anyContainer.superEncoder(forKey: key)
try answerResult.answerType.encode(value, to: nestedEncoder)
}
}
public func deepCopy() -> SBATrackedLoggingResultObject {
self
}
}
extension SBATrackedLoggingResultObject : SBATrackedItemAnswer {
public var hasRequiredValues: Bool {
if self.serializableType == .symptom {
// For a symptom result, need to have a severity.
return (self.findAnswerResult(with: SBASymptomTableItem.ResultIdentifier.severity.stringValue)?.value != nil)
}
else {
// otherwise, just marking the logged date is enough.
return self.loggedDate != nil
}
}
public var answerValue: Codable? {
return self.identifier
}
public var isExclusive: Bool {
return false
}
public var imageData: RSDImageData? {
return nil
}
public func isEqualToResult(_ result: ResultData?) -> Bool {
return self.identifier == result?.identifier
}
}
| 44.015831 | 164 | 0.683791 |
ed1ddedf6c6a729061607ab67b8f5d1e158942d6 | 1,988 | // Copyright ยฉ 2016 JABT Labs. All rights reserved.
import C4
class WhatViewController: CanvasController {
let ฯ = M_PI
let radius = 200.0
let font = Font(name: "Avenir", size: 30)!
var wedges = [Wedge]()
override func setup() {
buildWedges()
let codeTitle = TextShape(text: "Code", font: font)
codeTitle?.fillColor = black
codeTitle?.center = canvas.center + Vector(x: radius, y: radius)
canvas.add(codeTitle)
let designTitle = TextShape(text: "Design", font: font)
designTitle?.fillColor = black
designTitle?.center = canvas.center + Vector(x: radius, y: -radius)
canvas.add(designTitle)
reset()
canvas.addTapGestureRecognizer { _,_,_ in
self.animate()
}
}
func reset() {
let codeRange = 0..<240
let designRange = 240..<360
for wedge in wedges[codeRange] {
wedge.fillColor = C4Blue
}
for wedge in wedges[designRange] {
wedge.fillColor = C4Pink
}
}
func buildWedges() {
let wedgeAngle = ฯ / 180.0
for a in 0.0.stride(to: 2 * ฯ, by: wedgeAngle) {
let wedge = Wedge(center: canvas.center, radius: radius, start: a, end: a + wedgeAngle * 1.5)
wedge.lineWidth = 0.0
wedge.strokeColor = C4Blue
wedge.fillColor = C4Blue
wedges.append(wedge)
canvas.add(wedge)
}
}
func animate() {
var animations = [ViewAnimation]()
let changeRange = 120..<240
let duration = 0.5 / Double(changeRange.count)
for wedge in wedges[changeRange].reverse() {
animations.append(ViewAnimation(duration: duration) { wedge.fillColor = C4Pink })
}
ViewAnimationSequence(animations: animations).animate()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
reset()
}
}
| 28 | 105 | 0.579477 |
18233a9035cb7eebcd12ca655364f17c4a6d7775 | 288 | //
// Player.swift
// Generic_Timer_Game
//
// Created by Christopher Moore on 3/13/18.
// Copyright ยฉ 2018 Christopher Moore. All rights reserved.
//
import Foundation
class Player {
public static let shared = Player()
var level = 1
var experience = 0
}
| 15.157895 | 60 | 0.638889 |
28ed007e37e0e6f7263412ca90975b80aad56d1d | 752 | // - Since: 01/20/2018
// - Author: Arkadii Hlushchevskyi
// - Copyright: ยฉ 2020. Arkadii Hlushchevskyi.
// - Seealso: https://github.com/adya/TSKit.Networking/blob/master/LICENSE.md
import Foundation
public typealias EmptyResponse = Result<Void, NetworkServiceError>
public typealias AnyResponseCompletion = (AnyResponse) -> Void
public typealias ResponseCompletion<ResponseType> = (ResponseType) -> Void where ResponseType: AnyResponse
public typealias AnyErrorCompletion = (AnyNetworkServiceError) -> Void
public typealias ErrorCompletion<ErrorType> = (ErrorType) -> Void where ErrorType: AnyNetworkServiceBodyError
public typealias RequestCompletion = (EmptyResponse) -> Void
public typealias RequestProgressCompletion = (Progress) -> Void
| 35.809524 | 109 | 0.792553 |
2092cf043ab2fe638e45fa4273f14f4dfd58896c | 464 | //
// VersionViewModel.swift
// Notissu
//
// Copyright ยฉ 2021 Notissu. All rights reserved.
//
import Foundation
class VersionViewModel {
// MARK: - OUTPUT
var text: String {
isRecentVersion
? "์ต์ ๋ฒ์ ์ ์ฌ์ฉํ๊ณ ์์ต๋๋ค."
: "์
๋ฐ์ดํธ๊ฐ ํ์ํฉ๋๋ค."
}
// MARK: - Property
private let isRecentVersion: Bool
// MARK: - Init
init(isRecentVersion: Bool) {
self.isRecentVersion = isRecentVersion
}
}
| 17.185185 | 50 | 0.579741 |
39d2606986bd69934f5ac78c4d71defcfef91c92 | 1,797 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
import SnapKit
import UIKit
protocol RootPresentableListener: class {
// TODO: Declare properties and methods that the view controller can invoke to perform
// business logic, such as signIn(). This protocol is implemented by the corresponding
// interactor class.
}
final class RootViewController: UIViewController, RootPresentable, RootViewControllable {
weak var listener: RootPresentableListener?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Method is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
// MARK: - RootViewControllable
func present(viewController: ViewControllable) {
present(viewController.uiviewController, animated: true, completion: nil)
}
func dismiss(viewController: ViewControllable) {
if presentedViewController === viewController.uiviewController {
dismiss(animated: true, completion: nil)
}
}
}
// MARK: LoggedInViewControllable
extension RootViewController: LoggedInViewControllable {
}
| 28.52381 | 90 | 0.714524 |
acf44437040929deca59eec62777139ba3d25787 | 554 | import Example
import SwiftAssert
import XCTest
class XCTestFailureReporterTests: XCTestCase {
override func setUp() {
FailureReporterHolder.sharedReporter = XCTestFailureReporter(testCase: self)
}
func test() {
assertThat(Example.add(x: 2, y: 2)).isEqualTo(5)
}
}
class XCTObserverFailureReporterTests: XCTestCase {
override func setUp() {
FailureReporterHolder.sharedReporter = XCTObserverFailureReporter()
}
func test() {
assertThat(Example.add(x: 2, y: 2)).isEqualTo(5)
}
}
| 23.083333 | 84 | 0.6787 |
6745caa21848f69c23a05803ff5db43f15e0db5b | 2,372 | import UIKit
class SerifModalWebNavigationController: UINavigationController, UINavigationControllerDelegate {
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
(rootViewController as? ARExternalWebBrowserViewController)?.statusBarStyle = .lightContent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.layer.cornerRadius = 0
view.superview?.layer.cornerRadius = 0
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = UIRectEdge()
setNavigationBarHidden(true, animated: false)
let dimension = 40
let closeButton = ARMenuButton()
closeButton.setBorderColor(.artsyGrayRegular(), for: UIControl.State(), animated: false)
closeButton.setBackgroundColor(.white, for: UIControl.State(), animated: false)
closeButton.setImage(UIImage(named:"serif_modal_close"), for: UIControl.State())
closeButton.addTarget(self, action: #selector(dismissMe), for: .touchUpInside)
view.addSubview(closeButton)
closeButton.alignTrailingEdge(withView: view, predicate: "-20")
closeButton.alignTopEdge(withView: view, predicate: "20")
closeButton.constrainWidth("\(dimension)", height: "\(dimension)")
self.delegate = self
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return traitDependentSupportedInterfaceOrientations
}
override var shouldAutorotate : Bool {
return traitDependentAutorotateSupport
}
@objc func dismissMe() {
presentingViewController?.dismiss(animated: true, completion: nil)
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
viewController.automaticallyAdjustsScrollViewInsets = false
(viewController as? ARExternalWebBrowserViewController)?.statusBarStyle = .lightContent
}
}
| 37.650794 | 138 | 0.718381 |
76e8ebd42d8650baa2b5697701f8dbb4fa27f98a | 3,576 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
The `UIViewController+Convenience` methods allow for easy presentation of common views.
*/
import HomeKit
import UIKit
extension UIViewController {
/**
Displays a `UIAlertController` on the main thread with the error's `localizedDescription` at the body.
- parameter error: The error to display.
*/
func displayError(error: NSError) {
if let errorCode = HMErrorCode(rawValue: error.code) {
if self.presentedViewController != nil || errorCode == .OperationCancelled || errorCode == .UserDeclinedAddingUser {
print(error.localizedDescription)
}
else {
self.displayErrorMessage(error.localizedDescription)
}
}
else {
self.displayErrorMessage(error.description)
}
}
/**
Displays a collection of errors, separated by newlines.
- parameter errors: An array of `NSError`s to display.
*/
func displayErrors(errors: [NSError]) {
var messages = [String]()
for error in errors {
if let errorCode = HMErrorCode(rawValue: error.code) {
if self.presentedViewController != nil || errorCode == .OperationCancelled || errorCode == .UserDeclinedAddingUser {
print(error.localizedDescription)
}
else {
messages.append(error.localizedDescription)
}
}
else {
messages.append(error.description)
}
}
if messages.count > 0 {
// There were errors in the list, reduce the messages into a single one.
let collectedMessage = messages.reduce("", combine: { (accumulator, message) -> String in
return accumulator + "\n" + message
})
self.displayErrorMessage(collectedMessage)
}
}
/// Displays a `UIAlertController` with the passed-in text and an 'Okay' button.
func displayMessage(title: String, message: String) {
dispatch_async(dispatch_get_main_queue()) {
let alert = UIAlertController(title: title, body: message)
self.presentViewController(alert, animated: true, completion: nil)
}
}
/**
Displays `UIAlertController` with a message and a localized "Error" title.
- parameter message: The message to display.
*/
private func displayErrorMessage(message: String) {
let errorTitle = NSLocalizedString("Error", comment: "Error")
displayMessage(errorTitle, message: message)
}
/**
Presents a simple `UIAlertController` with a textField, set up to
accept a name. Once the name is entered, the completion handler will
be called and the name will be passed in.
- parameter attributeType: The kind of object being added
- parameter completion: The block to run when the user taps the add button.
*/
func presentAddAlertWithAttributeType(type: String, placeholder: String? = nil, shortType: String? = nil, completion: (String) -> Void) {
let alertController = UIAlertController(attributeType: type, completionHandler: completion, placeholder: placeholder, shortType: shortType)
self.presentViewController(alertController, animated: true, completion: nil)
}
} | 38.042553 | 147 | 0.616051 |
90b7be6075eca6fdbffdaa1d0af2070d8cfda36e | 1,007 | //
// UIView+LZ.swift
// LemoniOS
//
// Created by lucas on 16/7/9.
// Copyright ยฉ 2016ๅนด ไธๅชๅฐ็ช. All rights reserved.
//
import UIKit
extension UIView {
func lz_pinAllEdgesOfSubView(subView: UIView) {
self.lz_pinSubview(subView: subView, toEdge: .top)
self.lz_pinSubview(subView: subView, toEdge: .leading)
self.lz_pinSubview(subView: subView, toEdge: .bottom)
self.lz_pinSubview(subView: subView, toEdge: .trailing)
}
func lz_pinSubview(subView: UIView, toEdge attribute: NSLayoutAttribute) {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: subView,
attribute: attribute,
multiplier: 1.0,
constant: 0.0))
}
}
| 33.566667 | 78 | 0.500497 |
db8f8bbe60e849fc3f803b90f43cb0b1baac6eec | 1,668 | import Foundation
import UIKit
public class NSLayoutConstraintSet {
public var top: NSLayoutConstraint?
public var bottom: NSLayoutConstraint?
public var left: NSLayoutConstraint?
public var right: NSLayoutConstraint?
public var centerX: NSLayoutConstraint?
public var centerY: NSLayoutConstraint?
public var width: NSLayoutConstraint?
public var height: NSLayoutConstraint?
public init(top: NSLayoutConstraint? = nil,
bottom: NSLayoutConstraint? = nil,
left: NSLayoutConstraint? = nil,
right: NSLayoutConstraint? = nil,
centerX: NSLayoutConstraint? = nil,
centerY: NSLayoutConstraint? = nil,
width: NSLayoutConstraint? = nil,
height: NSLayoutConstraint? = nil) {
self.top = top
self.bottom = bottom
self.left = left
self.right = right
self.centerX = centerX
self.centerY = centerY
self.width = width
self.height = height
}
private var availableConstraints: [NSLayoutConstraint] {
#if swift(>=4.1)
return [top, bottom, left, right, centerX, centerY, width, height].compactMap {$0}
#else
return [top, bottom, left, right, centerX, centerY, width, height].flatMap {$0}
#endif
}
@discardableResult
public func activate() -> Self {
NSLayoutConstraint.activate(availableConstraints)
return self
}
@discardableResult
public func deactivate() -> Self {
NSLayoutConstraint.deactivate(availableConstraints)
return self
}
}
| 31.471698 | 94 | 0.619904 |
6aa16d7750c153b79e655a6021c72834eb692d65 | 4,206 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// TutorialStepsView.swift
import MacaroonUIKit
import UIKit
final class TutorialStepsView: View {
weak var delegate: TutorialStepsViewDelegate?
private lazy var verticalStackView = UIStackView()
var troubleshoots: [Troubleshoot] = [] {
didSet {
customize(TutorialStepsViewTheme())
}
}
func customize(_ theme: TutorialStepsViewTheme) {
customizeBaseAppearance(backgroundColor: theme.backgroundColor)
addVerticalStackView(theme)
for (index, step) in troubleshoots.enumerated() {
let horizontalStackView = UIStackView()
horizontalStackView.spacing = theme.horizontalSpacing
horizontalStackView.distribution = .fillProportionally
horizontalStackView.alignment = .top
let numberView = TutorialNumberView()
numberView.customize(TutorialNumberViewTheme())
numberView.bindData(TutorialNumberViewModel(index + 1))
let textView = UITextView()
textView.backgroundColor = theme.backgroundColor.uiColor
textView.isEditable = false
textView.isScrollEnabled = false
textView.dataDetectorTypes = .link
textView.textContainerInset = .zero
textView.linkTextAttributes = theme.textViewLinkAttributes.asSystemAttributes()
textView.delegate = self
textView.attributedText = bindHTML(step.explanation)
horizontalStackView.addArrangedSubview(numberView)
horizontalStackView.addArrangedSubview(textView)
verticalStackView.addArrangedSubview(horizontalStackView)
}
}
func prepareLayout(_ layoutSheet: NoLayoutSheet) {}
func customizeAppearance(_ styleSheet: NoStyleSheet) {}
}
extension TutorialStepsView {
func addVerticalStackView(_ theme: TutorialStepsViewTheme) {
addSubview(verticalStackView)
verticalStackView.axis = .vertical
verticalStackView.spacing = theme.verticalSpacing
verticalStackView.snp.makeConstraints {
$0.top.equalToSuperview().inset(theme.topPadding)
$0.leading.trailing.equalToSuperview().inset(theme.horizontalPadding)
}
}
}
extension TutorialStepsView: UITextViewDelegate {
func textView(
_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction
) -> Bool {
delegate?.tutorialStepsView(self, didTapURL: URL)
return false
}
}
extension TutorialStepsView {
func bindHTML(_ HTML: String?) -> NSAttributedString? {
guard let data = HTML?.data(using: .unicode),
let attributedString = try? NSMutableAttributedString(
data: data,
options: [.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else {
return nil
}
attributedString.addAttributes(
[
NSAttributedString.Key.font: Fonts.DMSans.regular.make(15).uiFont,
NSAttributedString.Key.foregroundColor: AppColors.Components.Text.main.uiColor
],
range: NSRange(location: 0, length: attributedString.string.count)
)
return attributedString
}
}
extension TutorialStepsView: ViewModelBindable {
func bindData(_ viewModel: TutorialStepViewModel?) {
self.troubleshoots = viewModel?.steps ?? []
}
}
protocol TutorialStepsViewDelegate: AnyObject {
func tutorialStepsView(_ view: TutorialStepsView, didTapURL URL: URL)
}
| 34.195122 | 94 | 0.683547 |
9bc6afa400a1020f784a8729df43d3b37bd4f5fd | 579 | //
// Model.swift
// Data
//
// Created by Daniel Brooker on 16/03/15.
// Copyright (c) 2015 Nocturnal Code. All rights reserved.
//
/// Data.Archive
public typealias Archive = [String: AnyObject]
/// Data.Model
public protocol Model : Equatable {
/// Unique identifier
var uid : String { get }
init(archive: Archive)
var archive : Archive { get }
func indexes() -> [Index]
}
public extension Model {
func indexes() -> [Index] {
return []
}
}
func ==<T: Model>(lhs: T, rhs: T) -> Bool {
return lhs.uid == rhs.uid
}
| 17.029412 | 59 | 0.587219 |
0178ac4496f12906d0ac00a0aedc55a88723c614 | 2,138 | //
// UIButton+Extension.swift
// FocusFoodie
//
// Created by Allie T on 2021/10/25.
//
import UIKit
import Foundation
extension UIButton {
@objc var substituteFontName: String {
get { return (self.titleLabel?.font.fontName)! }
set {
if self.titleLabel?.font.fontName.range(of: "-Bd") == nil {
self.titleLabel?.font = UIFont(
name: newValue,
size: (self.titleLabel?.font.pointSize)!)
}
}
}
@objc var substituteFontNameBold: String {
get { return (self.titleLabel?.font.fontName)! }
set {
if self.titleLabel?.font.fontName.range(of: "-Bd") == nil {
self.titleLabel?.font = UIFont(
name: newValue,
size: (self.titleLabel?.font.pointSize)!)
}
}
}
}
public class GradientButton: UIButton {
public override class var layerClass: AnyClass {
CAGradientLayer.self
}
private var gradientLayer: CAGradientLayer {
// swiftlint:disable force_cast
layer as! CAGradientLayer
// swiftlint:enable force_cast
}
public var startColor: UIColor = .white {
didSet {
updateColors()
}
}
public var endColor: UIColor = .red {
didSet {
updateColors()
}
}
public var startPoint: CGPoint {
get { gradientLayer.startPoint }
set { gradientLayer.startPoint = newValue }
}
public var endPoint: CGPoint {
get { gradientLayer.endPoint }
set { gradientLayer.endPoint = newValue }
}
public override init(frame: CGRect = .zero) {
super.init(frame: frame)
updateColors()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
updateColors()
}
}
private extension GradientButton {
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
}
| 20.169811 | 71 | 0.531805 |
89d0b1a827bb01eb10ee502cf5747de0e7269e61 | 3,059 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
The test case class for the `ListItem` class.
*/
import ListerKit
import XCTest
class ListItemTests: XCTestCase {
// MARK: Properties
// `item` is initialized again in setUp().
var item: ListItem!
// MARK: Setup
override func setUp() {
super.setUp()
item = ListItem(text: "foo")
}
// MARK: Initializers
func testConvenienceTextAndCompleteInit() {
let text = "foo"
let complete = true
let item = ListItem(text: text, complete: complete)
XCTAssertEqual(item.text, text)
XCTAssertEqual(item.isComplete, complete)
}
func testConvenienceTextInit() {
let text = "foo"
let item = ListItem(text: text)
XCTAssertEqual(item.text, text)
// The default value for the complete state should be `false`.
XCTAssertFalse(item.isComplete)
}
// MARK: NSCopying
func testCopyingListItems() {
let itemCopy = item.copy() as? ListItem
XCTAssertNotNil(itemCopy)
if itemCopy != nil {
XCTAssertEqual(item, itemCopy!)
}
}
// MARK: NSCoding
func testEncodingListItems() {
let archivedListItemData = NSKeyedArchiver.archivedDataWithRootObject(item)
XCTAssertTrue(archivedListItemData.length > 0)
}
func testDecodingListItems() {
let archivedListItemData = NSKeyedArchiver.archivedDataWithRootObject(item)
let unarchivedListItem = NSKeyedUnarchiver.unarchiveObjectWithData(archivedListItemData) as? ListItem
XCTAssertNotNil(unarchivedListItem)
if unarchivedListItem != nil {
XCTAssertEqual(item, unarchivedListItem!)
}
}
// MARK: refreshIdentity()
func testRefreshIdentity() {
let itemCopy = item.copy() as ListItem
XCTAssertEqual(item, itemCopy)
item.refreshIdentity()
XCTAssertNotEqual(itemCopy, item)
}
// MARK: isEqual(_:)
func testIsEqual() {
// isEqual(_:) should be strictly based of the underlying UUID of the list item.
let itemTwo = ListItem(text: "foo")
XCTAssertFalse(item.isEqual(nil))
XCTAssertEqual(item!, item!)
XCTAssertNotEqual(item, itemTwo)
}
// MARK: Archive Compatibility
/**
Ensure that the runtime name of the `ListItem` class is "AAPLListItem". This is to ensure
compatibility with the Objective-C version of the app that archives its data with the
`AAPLListItem` class.
*/
func testClassRuntimeNameForArchiveCompatibility() {
let classRuntimeName = NSStringFromClass(ListItem.self)!
XCTAssertEqual(classRuntimeName, "AAPLListItem", "ListItem should be archivable with the Objective-C version of Lister.")
}
}
| 25.923729 | 129 | 0.621118 |
4861d9b4634c8a0cb3bef1df301efdced10f59a9 | 1,914 | //
// StudentLocation.swift
// On The Map
//
// Created by Rajanikant Deshmukh on 26/03/18.
// Copyright ยฉ 2018 Rajanikant Deshmukh. All rights reserved.
//
import Foundation
class StudentLocation {
var objectId : String
var uniqueKey : String
var firstName : String
var lastName : String
var latitude : Double
var longitude : Double
var mapString : String
var mediaURL : String
var createdAt : Date
var updatedAt : Date
let dateFormatter = ISO8601DateFormatter()
init?(_ dictionary: NSDictionary) {
// These keys are compulsory for Parse and every object will have it
self.objectId = (dictionary["objectId"] as! String)
self.uniqueKey = (dictionary["uniqueKey"] as! String)
// TODO Parse Date
self.createdAt = dateFormatter.date(from: dictionary["createdAt"] as! String) ?? Date()
self.updatedAt = Date()
// Since the Parse data is not being validated on ServerSide
// We implemement sanity checks on our side
// Sanity check for name
if dictionary["firstName"] == nil || dictionary["lastName"] == nil {
return nil
}
self.firstName = dictionary["firstName"] as! String
self.lastName = (dictionary["lastName"] as! String)
// Sanity check for locations
if dictionary["latitude"] == nil || dictionary["longitude"] == nil {
return nil
}
self.latitude = (dictionary["latitude"] as! Double)
self.longitude = (dictionary["longitude"] as! Double)
// Sanity check for address and media URL
if dictionary["mapString"] == nil || dictionary["mediaURL"] == nil {
return nil
}
self.mapString = (dictionary["mapString"] as! String)
self.mediaURL = (dictionary["mediaURL"] as! String)
}
}
| 31.377049 | 96 | 0.606061 |
1cf38143b5c8a13f5f97492c4801c790fc99cc85 | 802 | #if os(iOS)
import UIKit
import AVFoundation
public class PlayerView: UIView {
override public class var layerClass: AnyClass {
return AVPlayerLayer.self
}
public var _playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
lazy private var _player: Player = Player()
public var player: Player {
return _player
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
public convenience init(player: Player) {
self.init(frame: CGRect.zero)
self._player = player
setup()
}
func setup() {
_playerLayer.player = _player.player
}
}
#endif
| 18.651163 | 52 | 0.587282 |
7105486280b1a2d64815738eb867dd24b938d7f4 | 1,455 | //
// Copyright ยฉ 2020 Jesรบs Alfredo Hernรกndez Alarcรณn. All rights reserved.
//
import EssentialFeed
import UIKit
public final class FeedUIComposer {
private init() {}
public static func feedComposedWith(feedLoader: FeedLoader, imageLoader: FeedImageDataLoader) -> FeedViewController {
let presentationAdapter = FeedLoaderPresentationAdapter(feedLoader: MainQueueDispatchDecorator(decoratee: feedLoader))
let feedController = makeFeedViewController(
delegate: presentationAdapter,
title: FeedPresenter.title
)
presentationAdapter.presenter = FeedPresenter(
feedView: FeedViewAdapter(
controller: feedController,
imageLoader: MainQueueDispatchDecorator(decoratee: imageLoader)
),
loadingView: WeakRefVirtualProxy(feedController),
errorView: WeakRefVirtualProxy(feedController)
)
return feedController
}
private static func makeFeedViewController(delegate: FeedViewControllerDelegate, title _: String) -> FeedViewController {
let bundle = Bundle(for: FeedViewController.self)
let storyboard = UIStoryboard(name: "Feed", bundle: bundle)
let feedController = storyboard.instantiateInitialViewController() as! FeedViewController
feedController.delegate = delegate
feedController.title = FeedPresenter.title
return feedController
}
}
| 37.307692 | 126 | 0.707216 |
5030e4d48ca290ac97232e371718b71f1d21f77d | 3,937 | //
// SentButtonsView.swift
// ApplozicSwift
//
// Created by Shivam Pokhriyal on 23/09/19.
//
import Foundation
public class SentButtonsCell: UITableViewCell {
// MARK: - Public properties
public struct Config {
public static var buttonTopPadding: CGFloat = 4
public static var padding = Padding(left: 60, right: 10, top: 10, bottom: 10)
public static var maxWidth = UIScreen.main.bounds.width
public static var buttonWidth = maxWidth - (padding.left + padding.right)
}
// MARK: - Fileprivate properties
fileprivate lazy var buttons = SuggestedReplyView()
fileprivate lazy var messageView = SentMessageView(
frame: .zero,
padding: messageViewPadding,
maxWidth: Config.maxWidth
)
fileprivate lazy var messageViewHeight = messageView.heightAnchor.constraint(equalToConstant: 0)
fileprivate var messageViewPadding: Padding
// MARK: - Initializer
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
messageViewPadding = Padding(left: Config.padding.left,
right: Config.padding.right,
top: Config.padding.top,
bottom: Config.buttonTopPadding)
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupConstraints()
backgroundColor = .clear
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Updates the `SentButtonsCell`.
///
/// - Parameter model: object that conforms to `SuggestedReplyMessage`
public func update(model: SuggestedReplyMessage) {
guard model.message.isMyMessage else {
print("๐ฑ๐ฑ๐ฑInconsistent information passed to the view.๐ฑ๐ฑ๐ฑ")
print("For SentMessage value of isMyMessage should be true")
return
}
messageView.update(model: model.message)
messageViewHeight.constant = SentMessageView.rowHeight(
model: model.message,
maxWidth: Config.maxWidth,
padding: messageViewPadding
)
buttons.update(model: model, maxWidth: Config.buttonWidth)
}
/// It is used to get exact height of `SentButtonsCell` using messageModel, width and padding
///
/// - Parameters:
/// - model: object that conforms to `SuggestedReplyMessage`
/// - Returns: exact height of the view.
public static func rowHeight(model: SuggestedReplyMessage) -> CGFloat {
let messageViewPadding = Padding(left: Config.padding.left,
right: Config.padding.right,
top: Config.padding.top,
bottom: Config.buttonTopPadding)
let messageHeight = SentMessageView.rowHeight(model: model.message, maxWidth: Config.maxWidth, padding: messageViewPadding)
let buttonHeight = SuggestedReplyView.rowHeight(model: model, maxWidth: Config.buttonWidth)
return messageHeight + buttonHeight + Config.padding.bottom
}
private func setupConstraints() {
addViewsForAutolayout(views: [messageView, buttons])
NSLayoutConstraint.activate([
messageView.topAnchor.constraint(equalTo: topAnchor),
messageView.leadingAnchor.constraint(equalTo: leadingAnchor),
messageView.trailingAnchor.constraint(equalTo: trailingAnchor),
messageViewHeight,
buttons.topAnchor.constraint(equalTo: messageView.bottomAnchor, constant: 0),
buttons.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Config.padding.right),
buttons.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor),
buttons.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -1 * Config.padding.bottom),
])
}
}
| 41.010417 | 131 | 0.650241 |
715826daf70b3d53304fb0b22c8a869da1a677fe | 3,647 | //
// CBWorksCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/22.
// Copyright ยฉ 2016ๅนด qianfeng. All rights reserved.
//
import UIKit
class CBWorksCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBAction func clickBtn(sender: UIButton) {
}
@IBAction func clickUserBtn(sender: UIButton) {
}
var model:CBRecommendWidgetListModel?{
didSet{
showData()
}
}
func showData(){
for i in 0..<3{
if model?.widget_data?.count>i*3{
let imageModel = model?.widget_data![i*3]
if imageModel?.type == "image" {
let subView = contentView.viewWithTag(100+i)
if subView?.isKindOfClass(UIButton.self) == true {
let btn = subView as! UIButton
let url = NSURL(string: imageModel!.content!)
btn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
if model?.widget_data?.count>i*3+1{
let imageModel = model?.widget_data![i*3+1]
if imageModel?.type == "image" {
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIButton.self) == true {
let btn = subView as! UIButton
btn.layer.cornerRadius = 20
btn.layer.masksToBounds = true
let url = NSURL(string: imageModel!.content!)
btn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
if model?.widget_data?.count>i*3+2{
let nameModel = model?.widget_data![i*3+2]
if nameModel?.type == "text" {
let subView = contentView.viewWithTag(300+i)
if subView?.isKindOfClass(UILabel.self) == true {
let nameLabel = subView as! UILabel
nameLabel.text = nameModel?.content
}
}
}
}
let subView = contentView.viewWithTag(400)
if subView?.isKindOfClass(UILabel.self) == true {
let descLabel = subView as! UILabel
descLabel.text = model?.desc
}
}
class func createWorksCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBWorksCell{
let cellId = "worksCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBWorksCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBWorksCell", owner:nil , options: nil).last as? CBWorksCell
}
cell?.model = listModel
return cell!
}
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
}
}
| 31.17094 | 193 | 0.528654 |
4af57466299d9084c4302cf9e896249227c8a089 | 6,112 | //
// IMCreateGroupViewController.swift
// Coffchat
//
// Created by fei.xu on 2020/10/30.
// Copyright ยฉ 2020 Coffeechat Inc. All rights reserved.
//
import Chrysan
import UIKit
/// ๅๅปบ็พค็ปๆงๅถๅจ
class IMCreateGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var userTabView: UITableView!
var userList: [PeopleUserModel] = []
var group: [Character] = []
var selectMemberCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
title = "้ๆฉ่็ณปไบบ"
// ๆณจๅ่ชๅฎไน็Cell็ๅฎ้
็ฑปๅ
userTabView.register(UINib(nibName: "IMPeopleViewCell", bundle: nil), forCellReuseIdentifier: "IMPeopleViewCell")
userTabView.estimatedRowHeight = 65
userTabView.tableFooterView = UIView() // ่ฎพ็ฝฎไนๅๅฏไปฅๅป้ค็ฉบ่กๅๅ
ๆ ผไน้ด็็ฉบ็ฝ็บฟ
userTabView.dataSource = self
userTabView.delegate = self
// Do any additional setup after loading the view.
// ๅทฆไธ่งๅๆถๆ้ฎ
let cancel = UIBarButtonItem(title: "ๅๆถ", style: .done, target: self, action: #selector(titleBarCancelButtonClick))
navigationItem.leftBarButtonItem = cancel
let ok = UIBarButtonItem(title: "็กฎๅฎ", style: .done, target: self, action: #selector(titleBarOkButtonClick))
ok.isEnabled = false
navigationItem.rightBarButtonItem = ok
IMManager.singleton.friendManager.queryUserList(callback: { rsp in
// ๅ ่ฝฝ็จๆทๅ่กจ
for item in rsp.userInfoList {
let model = PeopleUserModel(user: item)
self.userList.append(model)
}
// ่ฎก็ฎ้ฆๅญๆฏๅ็ป
for item in self.userList {
// ๅป้ๅคๆญ
if self.group.firstIndex(of: item.nameFirstCharacter) == nil {
self.group.append(item.nameFirstCharacter)
}
}
// ๆๅบ
self.group = self.group.sorted(by: { (caracter0, character1) -> Bool in
caracter0 < character1
})
// ๅทๆฐtabview
DispatchQueue.main.async {
self.userTabView.reloadData()
}
}) {
IMLog.warn(item: "IMCreateGroupViewController queryUserList timeout!")
}
}
@objc
func titleBarCancelButtonClick() {
navigationController?.popViewController(animated: true)
}
@objc
func titleBarOkButtonClick() {
// ่่ฑ
chrysan.show()
// ้ๆฉ็็พคๆๅ
var ids: [UInt64] = []
for item in userList {
if item.check == true {
ids.append(item.userInfo.userID)
}
}
// ๅๅปบ็พค็ป
IMManager.singleton.groupManager.createGroup(memberIdList: ids, groupName: "", callback: { _ in
// ๆๅ๏ผ่ทณ่ฝฌ่ๅคฉ็้ข
// FIXME
self.chrysan.hide()
self.navigationController?.popViewController(animated: true)
}) {
self.chrysan.hide()
IMLog.warn(item: "titleBarOkButtonClick createGroup timeout")
}
}
}
// MARK: UITableViewDelegate
extension IMCreateGroupViewController {
// ่ก้ซ
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// ่ชๅจ่ฎก็ฎ่ก้ซ๏ผ้่ฆๅ
่ฎพ็ฝฎestimatedRowHeight ๆ่
ๅๆญป return 65.0
return userTabView.estimatedRowHeight
}
// ้ไธญไธ่ก
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// ๅๆถ้ๆฉ
userTabView.deselectRow(at: indexPath, animated: true)
// ็นๅปๆไธ่ก๏ผ้ไธญๆๅ้
let cell = userTabView.cellForRow(at: indexPath)
let cell2 = cell as? IMPeopleViewCell
if cell2 != nil {
cell2?.on(on: !cell2!.cb.on)
onTabViewCellSelectChanged(isSelect: cell2!.cb.on)
}
// let user = userList[indexPath.row]
// let chatContentView = IMChatContentViewController(session: sessionInfo)
}
func onTabViewCellSelectChanged(isSelect: Bool) {
if isSelect {
selectMemberCount += 1
} else {
selectMemberCount -= 1
}
if selectMemberCount < 0 {
selectMemberCount = 0
}
if selectMemberCount == 0 {
title = "้ๆฉ่็ณปไบบ"
navigationItem.rightBarButtonItem?.isEnabled = false
} else {
title = "้ๆฉ่็ณปไบบ(\(selectMemberCount))"
navigationItem.rightBarButtonItem?.isEnabled = true
}
}
}
// MARK: UITableViewDataSource
extension IMCreateGroupViewController {
// ๅ็ป
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return group.count
// }
// ๆๅ ็ป๏ผ
func numberOfSections(in tableView: UITableView) -> Int {
return group.count
}
// ๆฏ็ปๅคๅฐไบบ
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.filter { (emp) -> Bool in emp.nameFirstCharacter == group[section] }.count
}
// ็ปๅ
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if group.count > 0 {
return String(group[section])
}
return nil
}
// ๅฆๆไธ้่ฆๅ็ป๏ผ็ดๆฅ่ฟๅๅ่กจ็ๅคงๅฐ
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return userList.count
// }
// ่ฟๅไธไธชTabViewCellๅฎไพ๏ผTabViewCellๅฐฑๆฏไธ่กๆฐๆฎ๏ผ็ๆญฃ็จๆฅๆพ็คบ็
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// cellIdๆฏ็ฑปๅ
let classType = IMPeopleViewCell.self
let cellId = String(describing: classType)
// ๆพๅฐๅฝๅ็ป่ฆๆพ็คบ็็จๆท
let showUsers: [PeopleUserModel] = userList.filter { (emp) -> Bool in
emp.nameFirstCharacter == group[indexPath.section]
}
// ่ทๅไธไธชๅฏ้ๅคไฝฟ็จ็Cell๏ผๆฒกๆๅฐฑๆถๅฐๅๅปบ
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? IMPeopleViewCell
if cell == nil {
cell = IMPeopleViewCell(style: .default, reuseIdentifier: cellId)
}
// ๆธฒๆไธ่ก
cell!.setContent(user: showUsers[indexPath.row])
return cell!
}
}
| 30.40796 | 123 | 0.60733 |
76847b0e5ca3930d8dddba4465c2bd6c48ed544b | 4,428 | //
// CBPasswordInputView.swift
// CBPasswordField
//
// Created by ็ณ็ฅ on 2017/12/4.
// Copyright ยฉ 2017ๅนด CBcc. All rights reserved.
//
import UIKit
struct pwdConfiguration {
static public var squareWidth : CGFloat = 45.0
static public var passWordNum : CGFloat = 6.0
static public var rectLineColor : UIColor = UIColor.init(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1.0)
static public var pointColor : UIColor = UIColor.black
static public var pointRadius : CGFloat = 6
}
protocol CBPasswordInputViewDelegate {
func CBPasswordInputViewDelegatePasswordCallback(pwd:String)
}
class CBPasswordInputView: UIView {
var delegate : CBPasswordInputViewDelegate!
lazy var textInputFiled : UITextField = {
let textFiled = UITextField()
textFiled.backgroundColor = .white
textFiled.keyboardType = .numberPad
textFiled.becomeFirstResponder()
textFiled.borderStyle = .none
textFiled.addTarget(self, action: #selector(textChange), for: UIControlEvents.editingChanged)
return textFiled
}()
fileprivate var contenView : CBContenView = {
let view = CBContenView()
view.backgroundColor = .white
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.insertSubview(textInputFiled, at: 0)
contenView.frame = self.bounds
self.addSubview(contenView)
contenView.layer.borderColor = UIColor.black.cgColor
contenView.layer.borderWidth = 1
let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapGesClick))
contenView.addGestureRecognizer(tapGes)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tapGesClick(){
cb_becomeFirstResponder()
}
func cb_becomeFirstResponder(){
textInputFiled.becomeFirstResponder()
}
func cb_resignFirstResponder() {
textInputFiled.resignFirstResponder()
}
@objc func textChange(textField:UITextField){
let textCount = textField.text!.count
if textCount > 6 {
textInputFiled.text = cb_subString(start: 0, length: 6, str: textField.text!)
delegate.CBPasswordInputViewDelegatePasswordCallback(pwd: textInputFiled.text!)
return
}
if textCount == 6 {
delegate.CBPasswordInputViewDelegatePasswordCallback(pwd: textInputFiled.text!)
}
contenView.textStr = textInputFiled.text!
}
//ๆ นๆฎๅผๅงไฝ็ฝฎๅ้ฟๅบฆๆชๅๅญ็ฌฆไธฒ
func cb_subString(start:Int, length:Int = -1,str:String) -> String {
var len = length
if len == -1 {
len = str.count - start
}
let st = str.index(str.startIndex, offsetBy:start)
let en = str.index(st, offsetBy:len)
return String(str[st ..< en])
}
}
class CBContenView: UIView {
var textStr : String = "" {
didSet {
textNumber = textStr.count
self.setNeedsDisplay()
}
}
var textNumber : NSInteger = 0
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let height = rect.size.height
let width = rect.size.width
guard let context = UIGraphicsGetCurrentContext() else {
return
}
for i in 0..<Int(pwdConfiguration.passWordNum) {
context.move(to: CGPoint(x: (width / pwdConfiguration.passWordNum) * CGFloat(i), y: 0))
context.addLine(to: CGPoint(x: (width / pwdConfiguration.passWordNum) * CGFloat(i), y: height))
context.closePath()
}
context.drawPath(using: .stroke)
context.setFillColor(pwdConfiguration.pointColor.cgColor)
for i in 0..<textNumber{
context.addArc(center: CGPoint(x: CGFloat(i + 1) * (pwdConfiguration.squareWidth / 2) + CGFloat(i) * (pwdConfiguration.squareWidth / 2), y: pwdConfiguration.squareWidth / 2), radius: pwdConfiguration.pointRadius, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
context.drawPath(using: .fill)
}
}
}
| 30.965035 | 290 | 0.628726 |
9c1bf43d1be14520c8c44c1f35e774930513851a | 3,824 | //
// chartView.swift
// wp
//
// Created by sum on 2017/1/17.
// Copyright ยฉ 2017ๅนด com.yundian. All rights reserved.
//
import UIKit
class ChartView: UIView {
@IBOutlet weak var line: UILabel!
@IBOutlet weak var first: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
func setupSubviews(){
initUI()
reloadData(dic: ["":"" as AnyObject])
// self.addSubview(view)
}
//MARK-่ฎพ็ฝฎUIๆฐๆฎ
func initUI(){
//็งป้คๆๆ็ๆงไปถ้ฒๆญข้ๅคๆทปๅ
//ไธญ้ดๅๅฒ็บฟ
let line : UILabel = UILabel.init(frame: CGRect.init(x: 17, y: self.frame.size.height/2 - 10, width: UIScreen.main.bounds.size.width - 34, height: 0.5))
self.addSubview(line)
line.backgroundColor = UIColor.init(hexString: "666666")
// ่ฎพ็ฝฎframe -ๆฏไธ้ข็็บฟ
// ๅไธไธ็จๅ ๅไธ ้่ฆๅ lab็้ซๅบฆ 70 ไธบๆ้ซ ๆไปฅๆฏไธช้ซๅบฆไธบ 70*็พๅๆฏ
for index in 0...5{
let float : CGFloat = CGFloat.init(index)
// let oringnWith = ((UIScreen.main.bounds.size.width - 5*30)/6.0) * float + 30 * float - 30
//่ฎพ็ฝฎ็ปๆฑ็ถๅพ
let tree = UILabel.init()
let amount = UILabel.init()
tree.frame = CGRect.zero
tree.tag = index + 100
// if index == 2 {
// tree.frame = CGRect.init(x: oringnWith , y: self.frame.size.height/2.0 - 10*float-20, width: 30, height: 10*float+20)
// }else{
// ๆถจ็
tree.backgroundColor = UIColor.init(hexString: "E9573E")
amount.frame = CGRect.init(x: tree.frame.origin.x - 5 , y: self.frame.size.height/2.0 - 10 * float - 20 - 50 , width: 40, height: 20)
amount.tag = index + 1000
amount.textAlignment = .center
amount.font = UIFont.systemFont(ofSize: 10)
addSubview(tree)
backgroundColor = UIColor.clear
addSubview(amount)
}
}
func reloadData(dic : [String : AnyObject]) {
// initUI()
//ๆฅไฟฎๆน่ฎพ็ฝฎframe
for index in 0...5{
let float : CGFloat = CGFloat.init(index)
let oringnWith = ((UIScreen.main.bounds.size.width - 5*30)/6.0) * float + 30 * float - 30
let tag : Int = index + 100
let amounttag : Int = index + 1000
let tree : UILabel = self.viewWithTag(tag) as! UILabel
let amount : UILabel = self.viewWithTag(amounttag) as! UILabel
// if index == 2 {
tree.frame = CGRect.init(x: oringnWith , y: self.frame.size.height/2.0 - 10*float-30-10, width: 30, height: 10*float+30)
amount.frame = CGRect.init(x: tree.frame.origin.x - 5 , y: self.frame.size.height/2.0 - 10 * float - 20 - 30 , width: 40, height: 20)
amount.frame = CGRect.init(x: tree.frame.origin.x - 5 , y: tree.frame.origin.y - 20, width: 40, height: 20)
// }else
// {
// tree.frame = CGRect.init(x: oringnWith , y: self.frame.size.height/2.0-10 , width: 30, height: 10*float+20)
//
// amount.frame = CGRect.init(x: tree.frame.origin.x - 5 , y: tree.frame.origin.y + tree.frame.size.height , width: 40, height: 20)
// }
// amount.frame = CGRect.init(x: tree.frame.origin.x - 5 , y: self.frame.size.height/2.0 - 10 * float - 20 - 30 , width: 40, height: 20)
amount.text = "56.7%"
}
}
}
| 34.142857 | 161 | 0.495554 |
7118fb7c310e1d0cb178f5360bdc1867a9692982 | 2,217 | // Copyright ยฉ 2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import XCTest
import TrustWalletCore
class NebulasTests: XCTestCase {
func testAddressFromPublicKey() {
let privateKey = PrivateKey(data: Data(hexString: "d2fd0ec9f6268fc8d1f563e3e976436936708bdf0dc60c66f35890f5967a8d2b")!)!
let publicKey = privateKey.getPublicKeySecp256k1(compressed: false)
let address = NebulasAddress(publicKey: publicKey)
XCTAssertEqual(address.description, "n1V5bB2tbaM3FUiL4eRwpBLgEredS5C2wLY")
}
func testSigner() {
let input = NebulasSigningInput.with {
$0.chainID = Data(hexString: "01")!
$0.fromAddress = "n1V5bB2tbaM3FUiL4eRwpBLgEredS5C2wLY"
$0.nonce = Data(hexString: "07")!
$0.gasPrice = Data(hexString: "0f4240")! //1000000
$0.gasLimit = Data(hexString: "030d40")! //200000
$0.toAddress = "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17"
$0.amount = Data(hexString: "98a7d9b8314c0000")! //11000000000000000000ULL
$0.payload = ""
$0.timestamp = Data(hexString: "5cfc84ca")! //1560052938
$0.privateKey = PrivateKey(data: Data(hexString: "d2fd0ec9f6268fc8d1f563e3e976436936708bdf0dc60c66f35890f5967a8d2b")!)!.data
}
let output = NebulasSigner.sign(input: input)
XCTAssertEqual(output.algorithm, 1)
//swiftlint:disable:next line_length
XCTAssertEqual(output.signature.hexString, "f53f4a9141ff8e462b094138eccd8c3a5d7865f9e9ab509626c78460a9e0b0fc35f7ed5ba1795ceb81a5e46b7580a6f7fb431d44fdba92515399cf6a8e47e71500")
//swiftlint:disable:next line_length
XCTAssertEqual(output.raw, "CiBQXdR2neMqnEu21q/U+OHqZHSBX9Q0hNiRfL2eCZO4hRIaGVefwtw23wEobqA40/7aIwQHghETxH4r+50aGhlXf89CeLWgHFjKu9/6tn4KNbelsMDAIIi2IhAAAAAAAAAAAJin2bgxTAAAKAcwyony5wU6CAoGYmluYXJ5QAFKEAAAAAAAAAAAAAAAAAAPQkBSEAAAAAAAAAAAAAAAAAADDUBYAWJB9T9KkUH/jkYrCUE47M2MOl14Zfnpq1CWJseEYKngsPw19+1boXlc64Gl5Gt1gKb3+0MdRP26klFTmc9qjkfnFQA=")
}
}
| 54.073171 | 350 | 0.739287 |
ac56d6a21f23687b1b01525d2a2f7d410e679b93 | 1,637 | //
// GroupsRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class GroupsRequest: Request {
override var method: RequestMethod { return .get }
override var parameters: Dictionary<String, AnyObject> { return Dictionary<String, AnyObject>() }
override var endpoint: String {
if let identifier = identifier { return "groups/\(identifier)" }
return "groups"
}
let identifier: String?
init(groupId: String? = nil) {
identifier = groupId
}
}
| 38.97619 | 101 | 0.725107 |
29b5c759ac564e3adcbe5cebe76880ed59823931 | 958 | //
// SettingsViewSection.swift
// Drrrible
//
// Created by Suyeol Jeon on 10/03/2017.
// Copyright ยฉ 2017 Suyeol Jeon. All rights reserved.
//
import RxDataSources
enum SettingsViewSection {
case about([SettingsViewSectionItem])
case logout([SettingsViewSectionItem])
}
extension SettingsViewSection: SectionModelType {
var items: [SettingsViewSectionItem] {
switch self {
case .about(let items): return items
case .logout(let items): return items
}
}
init(original: SettingsViewSection, items: [SettingsViewSectionItem]) {
switch original {
case .about: self = .about(items)
case .logout: self = .logout(items)
}
}
}
enum SettingsViewSectionItem {
case version(SettingItemCellReactor)
case github(SettingItemCellReactor)
case icons(SettingItemCellReactor)
case openSource(SettingItemCellReactor)
case logout(SettingItemCellReactor)
}
| 24.564103 | 75 | 0.691023 |
fc0d73e10b9b6a9d91377c0d3d5f21cc66bf68fd | 11,275 | import Glibc //wow also just for credits
import Foundation //just for the credits lol
/*
* This file contains only the TankWorld class.
*
*
*/
class TankWorld {
// -------------------------------------
// Properties
// -------------------------------------
//these govern the dimensions of the grid. Must be the same as the ones in grid.swift!
private let GRID_WIDTH = 15
private let GRID_HEIGHT = 15
//an instance of Grid.
var grid:[[GameObject?]]
//governs what turn the game is currently on
var turn:Int = 0
//is the game over? Also, should this var be here? It is not in the specs.
var gameOver:Bool = false
//another one of those vars IDK if I should make. It is referenced in the code, but I see no declaration.
var lastLivingTank:GameObject?//change to Tank type once implemented!
var livingTanks:Int = 0
//the logger and the messageCenter specific to this running of TankWorld
var logger = Logger()
var messageCenter = MessageCenter()
// -------------------------------------
// Initializer
// -------------------------------------
init() {
self.grid = Array(repeating: Array(repeating: nil, count: GRID_WIDTH), count: GRID_HEIGHT) //create a grid
self.turn = 0
populateTankWorld()
}
// -------------------------------------
// Methods
// -------------------------------------
//sets the winner of the game
func setWinner(lastTankStanding:GameObject) {//change to Tank type once implemented
gameOver = true
lastLivingTank = lastTankStanding
}
func populateTankWorld() {
//our tanks
var randEmpty = getRandomEmptyPosition()
addGameObject(OurTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"SHEE", instructions:"THIS TANK SUCKS"))
randEmpty = getRandomEmptyPosition()
addGameObject(OurTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"DION", instructions:"THIS TANK SUCKS"))
randEmpty = getRandomEmptyPosition()
addGameObject(OurTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"OTHE", instructions:"THIS TANK SUCKS"))
//jtanks
randEmpty = getRandomEmptyPosition()
addGameObject(JTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"PALT", instructions:"THIS TANK SUCKS"))
randEmpty = getRandomEmptyPosition()
addGameObject(JTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"TLAP", instructions:"THIS TANK SUCKS"))
randEmpty = getRandomEmptyPosition()
addGameObject(JTank(row:randEmpty.row, col:randEmpty.col, energy:100000, id:"LAPT", instructions:"THIS TANK SUCKS"))
livingTanks = findAllTanks().count
}
//adds an object to the grid.
//uses the position stored in the object as the inital position.
//assumes that all positions are valid
func addGameObject(_ object:GameObject) {
assert(object.position.row < GRID_HEIGHT, "Row is out of bounds for placing of GameObject: \(object)")
assert(object.position.col < GRID_WIDTH, "Column is out of bounds for placing of GameObject: \(object)")
assert(grid[object.position.row][object.position.col] == nil, "There is already an object: \(String(describing:grid[object.position.row][object.position.col]))")
grid[object.position.row][object.position.col] = object
}
//moves object to a Position
func moveObject(_ object:GameObject, toRow:Int, toCol:Int) {
//delete the current space
grid[object.position.row][object.position.col] = nil
//add the object to the new space.
grid[toRow][toCol] = object
object.position = [toRow, toCol] //give the info back to the GO
}
//exactly what it sounds like
//prints the grid. Does not return values.
func displayGrid() {
Grid(grid:grid).displayGrid()
}
//sees if thank dea,d the n do the ded messgae
func doDeathStuff(_ tank:GameObject) {
if isDead(tank) {
logger.addLog(tank, "\u{001B}[7;33m THE GameObject HAS DIED REEEEEEEEEEEEEEEEEEEEEEEEE \u{001B}[0;00m")
grid[tank.position.row][tank.position.col] = nil
if tank.objectType == .Tank {
livingTanks -= 1
}
}
if findAllTanks().count == 1 {
setWinner(lastTankStanding: findAllTanks()[0])
}
}
//Computes a single turn of the game,
//DOES NOT print the grid.
func doTurn() {
livingTanks = findAllTanks().count
var allObjects = findAllGameObjects() //get all the objects
allObjects = randomizeGameObjects(gameObjects: allObjects) //randomize, this will be order of execution
var n = 0 //iterator for while loop
//does life support
while n < allObjects.count {
let go = allObjects[n]
logger.addLog(go, "is being charged life support")
switch go.objectType {
case .Tank: applyCost(go, amount:Constants.costLifeSupportTank)
case .Mine: applyCost(go, amount:Constants.costLifeSupportMine)
case .Rover: applyCost(go,amount:Constants.costLifeSupportRover)
}
if isDead(go) || go.energy < 1 {
doDeathStuff(go)
allObjects.remove(at: n)
continue //go to the start without iterating n
}
if findAllTanks().count == 1 {
setWinner(lastTankStanding: go)
print(logger.getTurnLog())
return //end the turn early
}
n += 1
}
var tanks = randomizeGameObjects(gameObjects: findAllGameObjects())//.map {$0 as! Tank}
n = 0
while n < tanks.count {
if(tanks[n].objectType == .Mine || tanks[n].objectType == .Rover) {
tanks.remove(at: n)
continue
}
n += 1
}
var rovers = randomizeGameObjects(gameObjects: findAllGameObjects())
n = 0
while n < rovers.count {
if (rovers[n].objectType == .Tank || rovers[n].objectType == .Mine) {
rovers.remove(at: n)
continue
}
n += 1
}
for tank in tanks {
let t = tank as! Tank
t.computePreActions()
t.computePostActions()
}
//rovers move
for rover in rovers {
guard let rover = rover as? Mine else {
print("not a mine")
break
}
//find a position to move rover
var position:Position = getLegalSurroundingPositions(rover.position)[Int.random(in: 0..<getLegalSurroundingPositions(rover.position).count)]
if rover.roverMovementType == "direction" {
let temp = newPosition(position: rover.position, direction: rover.roverMovementDirection!, magnitude:1)
if isValidPosition(temp) {
position = temp
} else {
position = [-1,-1] //out of bounds
}
}
//if there is a position to move to...
if isValidPosition(position) && rover.energy >= Constants.costOfMovingRover {
//if there is an object at the position
rover.energy -= Constants.costOfMovingRover
if let killObj = grid[position.row][position.col] {
grid[rover.position.row][rover.position.col] = nil //remove rover
if killObj.objectType != .Tank {
killObj.energy -= rover.energy //take away energy
} else {
let obj = killObj as! Tank
let minus = rover.energy
if obj.shields < minus {
let o = obj.shields
obj.shields = 0
obj.energy -= minus - o
} else {
obj.shields -= minus
}
}
doDeathStuff(killObj) //see if ded. will remove if ded
} else {
//nothing, so move.
grid[rover.position.row][rover.position.col] = nil
grid[position.row][position.col] = rover
rover.position = position
}
}
//just in case??
doDeathStuff(rover)
//in case this mine just killed the last tank
if gameOver {
print(logger.getTurnLog())
return
}
}
for tank in tanks {
handleRadar(tank:tank as! Tank)
}
for tank in tanks {
handleSendMessage(tank:tank as! Tank)
}
for tank in tanks {
handleReceiveMessage(tank:tank as! Tank)
}
for tank in tanks {
handleShields(tank:tank as! Tank)
}
for tank in tanks {
handleDropMine(tank:tank as! Tank)
handleMissile(tank:tank as! Tank)
handleMove(tank:tank as! Tank)
if gameOver {
print(logger.getTurnLog())
return
}
}
for tank in tanks {
let t = tank as! Tank
t.preActions = [:]
t.postActions = [:]
t.shields = 0
}
print(logger.getTurnLog())
if gameOver {
return
}
self.turn += 1 //iterates the turn counter
logger.nextTurn() //iterates the logger turn counter
}
//this is the driving method. The main method.
//will run your commands until a single tank remains.
func driver() {
displayGrid() //display the starting grid.
repeat { //same as a while loop, makes sure there is at least one execution of loop body.
//get user command first:
print(">", terminator:"")
let input = readLine()!
switch input { //handle user input
case "win":
while livingTanks > 1 {
doTurn()
displayGrid()
}
guard findAllTanks().count == 1 else {
fatalError("no or too many living tanks at the end: \(findAllTanks().count)")
}
lastLivingTank = findAllTanks()[0] as GameObject
gameOver = true
case "quit":
print("exiting interactive")
return
case "d":
print("running until die")
let alive = livingTanks
while livingTanks >= alive {
doTurn()
displayGrid()
}
default:
if let d = Int(input) {
print("running one turn...")
for _ in 0..<Int(d) {
doTurn()
displayGrid()
}
}
doTurn()
displayGrid()
} //end of input handling switch
//the idea with gameOver is that it will be set in doTurn(), so we need the loop to check. Otherwise we could do while(true)
} while !gameOver
print("\n\u{001B}[7;34m** WINNER IS \(lastLivingTank!) **\u{001B}[0;00m")
// :) a treat if you run the executable
let commands = CommandLine.arguments
guard commands.count > 1 else {
print(":)")
return
}
func swish() {
print("\u{001B}[1;35;104m#####################\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
print("\u{001B}[1;35;104m-########---########-\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
print("\u{001B}[1;35;104m--######-----######--\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
print("\u{001B}[1;35;104m---####-------####---\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
print("\u{001B}[1;35;104m----##---------##----\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
print("\u{001B}[1;35;104m---------------------\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(1)
}
if commands[1] == "exec" {
//do the cool stuff
print("\n\n\u{001B}[2A",terminator:"")
print("\u{001B}[1;93;104m CREDITS \u{001B}[0m")
print("\u{001B}[1;93;104m \u{001B}[0m")
print("\u{001B}[1;93;104m \u{001B}[0m",terminator:"")
print("\u{001B}[1A\u{001B}[25D",terminator:"")
swish()
for _ in 0..<1 {
print("\u{001B}[1;35;104m Sheen Patel \u{001B}[0m",terminator:"")
print("\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(3)
swish()
print("\u{001B}[1;35;104m Deon Chan \u{001B}[0m",terminator:"")
print("\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(3)
swish()
print("\u{001B}[1;35;104m Mr. Pali - debugger \u{001B}[0m",terminator:"")
print("\u{001B}[25D",terminator:"")
fflush(stdout)
sleep(3)
swish()
}
}
print("\u{001B}[1A",terminator:"")
print("\u{001B}[1;37;3m HAVE A GREAT SUMMER!\u{001B}[0m")
print("\u{001B}[1;30;104m :) \u{001B}[0m\u{001B}[1B\u{001B}[21C")
}
}
| 28.689567 | 163 | 0.635388 |
bf4026da482aebef7125f075aecb7372d5f9296c | 3,687 | /* Copyright 2017 Tua Rua Ltd.
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.
Additional Terms
No part, or derivative of this Air Native Extensions's code is permitted
to be sold as the basis of a commercially packaged Air Native Extension which
undertakes the same purpose as this software. That is an ARKit wrapper for iOS.
All Rights Reserved. Tua Rua Ltd.
*/
import Foundation
import ARKit
public extension SCNTube {
convenience init?(_ freObject: FREObject?) {
guard
let rv = freObject,
let innerRadius = CGFloat(rv["innerRadius"]),
let outerRadius = CGFloat(rv["outerRadius"]),
let height = CGFloat(rv["height"]),
let radialSegmentCount = Int(rv["radialSegmentCount"]),
let subdivisionLevel = Int(rv["subdivisionLevel"]),
let heightSegmentCount = Int(rv["heightSegmentCount"])
else {
return nil
}
self.init()
self.height = height
self.innerRadius = innerRadius
self.outerRadius = outerRadius
self.radialSegmentCount = radialSegmentCount
self.heightSegmentCount = heightSegmentCount
self.subdivisionLevel = subdivisionLevel
applyMaterials(rv["materials"])
}
func applyMaterials(_ value: FREObject?) {
guard let freMaterials = value else { return }
let freArray: FREArray = FREArray(freMaterials)
guard freArray.length > 0 else { return }
var mats = [SCNMaterial](repeating: SCNMaterial(), count: Int(freArray.length))
for i in 0..<freArray.length {
if let mat = SCNMaterial(freArray[i]) {
mats[Int(i)] = mat
}
}
self.materials = mats
}
func setProp(name: String, value: FREObject) {
switch name {
case "innerRadius":
self.innerRadius = CGFloat(value) ?? self.innerRadius
case "outerRadius":
self.outerRadius = CGFloat(value) ?? self.outerRadius
case "height":
self.height = CGFloat(value) ?? self.height
case "radialSegmentCount":
self.radialSegmentCount = Int(value) ?? self.radialSegmentCount
case "heightSegmentCount":
self.heightSegmentCount = Int(value) ?? self.heightSegmentCount
case "subdivisionLevel":
self.subdivisionLevel = Int(value) ?? self.subdivisionLevel
case "materials":
applyMaterials(value)
default:
break
}
}
@objc override func toFREObject(nodeName: String?) -> FREObject? {
guard let fre = FreObjectSwift(className: "com.tuarua.arkit.shapes.Tube") else {
return nil
}
fre.innerRadius = innerRadius
fre.outerRadius = outerRadius
fre.height = height
fre.radialSegmentCount = radialSegmentCount
fre.heightSegmentCount = heightSegmentCount
fre.subdivisionLevel = subdivisionLevel
if materials.count > 0 {
fre.materials = materials.toFREObject(nodeName: nodeName)
}
fre.nodeName = nodeName
return fre.rawValue
}
}
| 36.147059 | 88 | 0.638188 |
9b5b9b20aa356432d162727941ec6a823bb3cf15 | 574 | //
// BlockStatement.swift
// Hermes
//
// Created by Franklin Cruz on 04-01-21.
//
import Foundation
import Hermes
/// Represent expressions in the form of:
/// `{ <statement> }`
/// where we can have any number of statements
struct BlockStatement: Statement {
var token: Token
var statements: [Statement] = []
var description: String {
var output = "{\n"
for stmt in statements {
output += "\t"
output += stmt.description
output += ";\n"
}
output += "}\n"
return output
}
}
| 19.793103 | 46 | 0.56446 |
debbd70445191799134175e55c53613055b4a2f7 | 845 | //
// Post.swift
// BloodDonation
//
// Created by Abdulrhman Abuhyyh on 23/05/1443 AH.
//
import Foundation
import Firebase
struct Post {
var id = ""
var date = ""
var location = ""
var note = ""
var donate = ""
var user:User
var createdAt:Timestamp?
init(dict:[String:Any],id:String,user:User) {
if let date = dict["date"] as? String,
let location = dict["location"] as? String,
let note = dict["note"] as? String,
let donate = dict["donate"] as? String,
let createdAt = dict["createdAt"] as? Timestamp {
self.date = date
self.location = location
self.note = note
self.donate = donate
self.createdAt = createdAt
}
self.id = id
self.user = user
}
}
| 23.472222 | 61 | 0.530178 |
fe336c83e59e838af1b608930f9b144af1fa2141 | 1,675 | //
// PoseLifting+Pose.swift
// FritzVision
//
// Created by Christopher Kelly on 3/27/19.
// Copyright ยฉ 2019 Fritz Labs Incorporated. All rights reserved.
//
import Foundation
@available(iOS 11.0, *)
extension Pose where Skeleton == HumanSkeleton {
public func getHipCenter() -> CGPoint? {
guard let leftHip = getKeypoint(for: .leftHip),
let rightHip = getKeypoint(for: .rightHip)
else {
return nil
}
return (leftHip.position + rightHip.position) / 2.0
}
public func translate() -> [CGPoint]? {
guard let hipCenter = getHipCenter() else { return nil }
return keypoints.map { $0.position - hipCenter }
}
public func translateKeypoint() -> [Keypoint<Skeleton>]? {
guard let hipCenter = getHipCenter() else { return nil }
return keypoints.map {
Keypoint(index: $0.index, position: $0.position - hipCenter, score: $0.score, part: $0.part)
}
}
public func getInputKeypoints(translate: Bool = true) -> [Keypoint<Skeleton>]? {
guard let hipCenter = getHipCenter() else { return nil }
var modelInputs: [Keypoint<Skeleton>] = []
for modelPart in PosePreprocessing.modelInputPartOrder {
guard let keypoint = getKeypoint(for: modelPart) else {
print("No keypoint for \(modelPart), not using this pose.")
return nil
}
if translate {
let translated = Keypoint(
index: keypoint.index,
position: keypoint.position - hipCenter,
score: keypoint.score,
part: keypoint.part
)
modelInputs.append(translated)
} else {
modelInputs.append(keypoint)
}
}
return modelInputs
}
}
| 27.916667 | 98 | 0.640597 |
0a1b9ac5327f293b9df122162550936c373fba49 | 898 | //
// AirplaneTests.swift
// AirplaneTests
//
// Created by Chris Eidhof on 08.02.21.
//
import XCTest
@testable import Airplane
class AirplaneTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.411765 | 111 | 0.663697 |
29d77e592bee7f46d300c935552ebb26f8c9338e | 1,623 | //
// ArticleDetailViewController.swift
// SocialAppCleanSwift
//
// Created by Christian Slanzi on 08.12.20.
// Copyright (c) 2020 Christian Slanzi. All rights reserved.
import UIKit
import WebKit
protocol IArticleDetailViewController: class {
// do someting...
}
class ArticleDetailViewController: UIViewController {
var interactor: IArticleDetailInteractor!
var router: IArticleDetailRouter!
let webView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
let view = WKWebView(frame: .zero, configuration: webConfiguration)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// do someting...
setupViews()
setupConstraints()
if let urlString = interactor.parameters?["url"] as? String, let url = URL(string: urlString) {
webView.load(URLRequest(url: url))
}
}
}
extension ArticleDetailViewController: IArticleDetailViewController {
// do someting...
}
extension ArticleDetailViewController {
// do someting...
func setupViews() {
self.view.addSubview(webView)
}
func setupConstraints() {
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.leftAnchor.constraint(equalTo: view.leftAnchor),
webView.rightAnchor.constraint(equalTo: view.rightAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
extension ArticleDetailViewController {
// do someting...
}
| 26.606557 | 103 | 0.683303 |
111723984188f255631f07886c1f93fdbeb50d68 | 207 | //
// CMForeignName+CoreDataClass.swift
// Pods
//
// Created by Jovito Royeca on 15/04/2017.
//
//
import Foundation
import CoreData
@objc(CMForeignName)
open class CMForeignName: NSManagedObject {
}
| 12.9375 | 43 | 0.724638 |
0146785c4dbbfb390374dbbd120de81ccfcf2d27 | 280 | // Auto-generated code. Do not edit.
import Foundation
import DLJSONAPI
// MARK: - EffectWithdrawnResource
open class EffectWithdrawnResource: EffectBalanceChangeResource {
open override class var resourceType: String {
return "effects-withdrawn"
}
}
| 18.666667 | 65 | 0.725 |
3aad729ada8e8a55e3ee949c8011a8bc6e27b530 | 3,619 | ๏ปฟpublic typealias ExpressibleByArrayLiteral = IExpressibleByArrayLiteral
public typealias ExpressibleByBooleanLiteral = IExpressibleByBooleanLiteral
public typealias ExpressibleByDictionaryLiteral = IExpressibleByDictionaryLiteral
//public typealias ExpressibleByExtendedGraphemeClusterLiteral = IExpressibleByExtendedGraphemeClusterLiteral
public typealias ExpressibleByFloatLiteral = IExpressibleByFloatLiteral
public typealias ExpressibleByIntegerLiteral = IExpressibleByIntegerLiteral
public typealias ExpressibleByNilLiteral = IExpressibleByNilLiteral
public typealias ExpressibleByStringLiteral = IExpressibleByStringLiteral
public typealias ExpressibleByStringInterpolation = IExpressibleByStringInterpolation
public typealias ExpressibleByUnicodeScalarLiteral = IExpressibleByUnicodeScalarLiteral
public typealias NilLiteralConvertible = ExpressibleByNilLiteral
public typealias BooleanLiteralConvertible = ExpressibleByBooleanLiteral
public typealias FloatLiteralConvertible = ExpressibleByFloatLiteral
public typealias IntegerLiteralConvertible = ExpressibleByIntegerLiteral
public typealias UnicodeScalarLiteralConvertible = ExpressibleByUnicodeScalarLiteral
//public typealias ExtendedGraphemeClusterLiteralConvertible = ExpressibleByExtendedGraphemeClusterLiteral
public typealias StringLiteralConvertible = ExpressibleByStringLiteral
public typealias StringInterpolationConvertible = ExpressibleByStringInterpolation
public typealias ArrayLiteralConvertible = ExpressibleByArrayLiteral
public typealias DictionaryLiteralConvertible = ExpressibleByDictionaryLiteral
public protocol IExpressibleByArrayLiteral {
associatedtype Element
init(arrayLiteral elements: Element...)
}
public protocol IExpressibleByBooleanLiteral {
associatedtype BooleanLiteralType
init(booleanLiteral value: BooleanLiteralType)
}
public protocol IExpressibleByDictionaryLiteral {
associatedtype Key
associatedtype Value
init(dictionaryLiteral elements: (Key, Value)...)
}
//73998: Silver: compiler crash in base library
public protocol IExpressibleByExtendedGraphemeClusterLiteral /*: ExpressibleByUnicodeScalarLiteral*/ {
associatedtype ExtendedGraphemeClusterLiteralType
/// Create an instance initialized to `value`.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
public protocol IExpressibleByFloatLiteral {
associatedtype FloatLiteralType
init(floatLiteral value: FloatLiteralType)
}
public protocol IExpressibleByIntegerLiteral {
associatedtype IntegerLiteralType
init(integerLiteral value: IntegerLiteralType)
}
public protocol IExpressibleByNilLiteral {
//init(nilLiteral: ())
}
public protocol IExpressibleByStringLiteral /*: ExpressibleByExtendedGraphemeClusterLiteral*/ {
associatedtype StringLiteralType
init(stringLiteral value: StringLiteralType)
}
public protocol IExpressibleByStringInterpolation /*: ExpressibleByExtendedGraphemeClusterLiteral*/ {
associatedtype StringInterpolationType
init(stringInterpolation value: StringInterpolationType)
}
public protocol IExpressibleByUnicodeScalarLiteral {
associatedtype UnicodeScalarLiteralType
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
#if COCOA
public extension NSURL/*: ExpressibleByStringLiteral*/ {
//typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public class func convertFromExtendedGraphemeClusterLiteral(value: String) -> Self {
return self(string: value)
}
init(stringLiteral value: String) {
return NSURL(string: value)
}
}
#endif
| 36.555556 | 110 | 0.847472 |
1d7b3d97e377e267b927a459ab4a4724f74d8ccd | 5,459 | //
// SFTPHelper.swift
// BLE-Swift
//
// Created by Kevin Chen on 2020/1/7.
// Copyright ยฉ 2020 ss. All rights reserved.
//
import UIKit
public typealias ConnectCallBack = (Bool, Error?)->()
public typealias DownloadCallBack = (Bool, Error?)->()
public typealias ProgressCallBack = (Progress)->()
class SFTPHelper: NSObject, NMSSHSessionDelegate {
static let shared = SFTPHelper()
// private let session = NMSSHSession.init(host: "ftp://172.16.0.5/", andUsername: "chenyanlin")
private let session = NMSSHSession.connect(toHost: "ftp://172.16.0.5/", withUsername: "chenyanlin")
var isConnecting = false
var connectCallbacks = Array<ConnectCallBack>()
override init() {
super.init()
session.delegate = self
}
public func asynDownloadFile(localPath:String, sftpPath:String, progress:ProgressCallBack?, callback:DownloadCallBack?) -> Void {
DispatchQueue.global().async {
if self.sftpIsConnected() {
let file:NMSFTPFile? = self.session.sftp.infoForFile(atPath: sftpPath)
if (file == nil) {
if (callback != nil) {
callback!(false, nil);
}
return
}
else {
let success = self.syncDownloadFile(localPath: localPath, sftpPath: sftpPath) { (pro) in
DispatchQueue.main.async {
if progress != nil {
progress!(pro)
}
}
}
if (callback != nil) {
callback!(success, nil)
}
}
}
else {
self.syncConnect { (connectSuccess, error) in
if connectSuccess {
let success = self.syncDownloadFile(localPath: localPath, sftpPath: sftpPath) { (pro) in
DispatchQueue.main.async {
if progress != nil {
progress!(pro)
}
}
}
if (callback != nil) {
callback!(success, nil)
}
}
else {
if (callback != nil) {
callback!(connectSuccess, nil)
}
}
}
}
}
}
private func sftpIsConnected() -> Bool {
if (!session.sftp.isConnected) {
return false;
}
return true;
}
private func syncConnect(callBack:ConnectCallBack?) -> Void {
if (callBack != nil) {
connectCallbacks.append(callBack!)
}
var success = false
if sftpIsConnected() == false {
if isConnecting {
return
}
isConnecting = true
// let connectSuccess = self.session.connect()
// let session1 = NMSSHSession.connect(toHost: "172.16.0.5:21", withUsername: "chenyanlin")
let session1 = NMSSHSession.connect(toHost: "172.16.0.5:21", port: 21, withUsername: "chenyanlin")
let connectSuccess = session1.isConnected
if connectSuccess {
let authenticateSuccess = self.session.authenticate(byPassword: "cyl551")
success = authenticateSuccess
}
else {
success = connectSuccess
}
}
else {
success = true
}
if success {
for cb:ConnectCallBack in self.connectCallbacks {
cb(true, nil)
}
}
else {
for cb:ConnectCallBack in self.connectCallbacks {
cb(false, nil)
}
}
self.connectCallbacks.removeAll()
isConnecting = false
}
private func syncDownloadFile(localPath:String, sftpPath:String, progressCallback:ProgressCallBack?) -> Bool {
let stream:OutputStream = OutputStream.init(toFileAtPath: localPath, append: true)!
var pro:Progress? = nil
let success = session.sftp.contents(atPath: sftpPath, to: stream) { (received, total) -> Bool in
if pro == nil {
pro = Progress.init(totalUnitCount: Int64(total))
}
pro!.completedUnitCount = Int64(received)
if progressCallback != nil {
progressCallback!(pro!)
}
return true
}
return success
}
// MARK: - NMSSHSessionDelegate
func session(_ session: NMSSHSession, keyboardInteractiveRequest request: String) -> String {
return ""
}
func session(_ session: NMSSHSession, didDisconnectWithError error: Error) {
print("error = \(error)")
}
func session(_ session: NMSSHSession, shouldConnectToHostWithFingerprint fingerprint: String) -> Bool {
return true
}
}
| 31.554913 | 133 | 0.474995 |
6461b8648e56dff2882f2026dda1f82869bd6623 | 1,910 | //
// DownloadInfoViewController.swift
// Protein
//
// Created by Lakr Aream on 2020/8/1.
// Copyright ยฉ 2020 Lakr Aream. All rights reserved.
//
import UIKit
class DownloadInfoViewController: UIViewControllerWithCustomizedNavBar {
private var textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
defer {
setupNavigationBar()
textView.snp.makeConstraints { (x) in
x.top.equalTo(self.SimpleNavBar.snp.bottom).offset(25)
x.bottom.equalTo(self.view.snp.bottom).offset(-25)
x.left.equalTo(self.view.snp.left).offset(25)
x.right.equalTo(self.view.snp.right).offset(-25)
}
}
view.backgroundColor = UIColor(named: "G-ViewController-Background")
let size = CGSize(width: 600, height: 600)
preferredContentSize = size
hideKeyboardWhenTappedAround()
view.insetsLayoutMarginsFromSafeArea = false
isModalInPresentation = true
textView.clipsToBounds = true
textView.textColor = UIColor(named: "G-TextSubTitle")
textView.backgroundColor = .clear
textView.isEditable = false
#if targetEnvironment(macCatalyst)
textView.font = .monospacedSystemFont(ofSize: 24, weight: .bold)
preferredContentSize = CGSize(width: 700, height: 555)
#else
textView.font = .monospacedSystemFont(ofSize: 14, weight: .bold)
preferredContentSize = CGSize(width: 700, height: 555)
#endif
view.addSubview(textView)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.reloadData()
}
}
func reloadData() {
textView.text = TaskManager.shared.downloadManager.reportDownloadLogsAndRecords()
}
}
| 30.806452 | 89 | 0.608901 |
de88252a07e973014c7f675392521315adb7f725 | 2,924 | //
// Bitmark+Rx.swift
// RxBitmarkSDK
//
// Created by Anh Nguyen on 7/17/19.
// Copyright ยฉ 2019 Bitmark. All rights reserved.
//
import Foundation
import RxSwift
import BitmarkSDK
public extension BitmarkSDK.Bitmark {
static func rxGet(bitmarkID: String) -> Single<Bitmark> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.get(bitmarkID: bitmarkID)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
static func rxGetWithAsset(bitmarkID: String) -> Single<(Bitmark, Asset)> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.getWithAsset(bitmarkID: bitmarkID)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
static func rxList(params: Bitmark.QueryParam) -> Single<([Bitmark]?, [Asset]?)> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.list(params: params)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
static func rxIssue(_ params: IssuanceParams) -> Single<[String]> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.issue(params)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
static func rxTransfer(_ params: TransferParams) -> Single<String> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.transfer(withTransferParams: params)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
static func rxOffer(_ params: OfferParams) -> Completable {
return Completable.create { (completable) -> Disposable in
do {
try Bitmark.offer(withOfferParams: params)
completable(.completed)
} catch let error {
completable(.error(error))
}
return Disposables.create()
}
}
static func rxRespond(_ params: OfferResponseParams) -> Single<String?> {
return Single.create { (single) -> Disposable in
do {
single(.success(try Bitmark.respond(withResponseParams: params)))
} catch let error {
single(.error(error))
}
return Disposables.create()
}
}
}
| 29.24 | 86 | 0.515732 |
dbc63c49e3ed4f5d4f089f1c76499b5b1cc9c56e | 2,859 | /// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
// note: no AlertTests because alert is a pure data object
class Alert {
enum Severity {
case good, bad
}
let text: String
let severity: Severity
var cleared: Bool = false
init(_ text: String, severity: Severity = .bad) {
self.text = text
self.severity = severity
}
}
extension Alert {
static var caughtByNessie = Alert("Caught By Nessie!")
static var reachedGoal = Alert("You reached your goal!", severity: .good)
static var noPedometer = Alert("Unable to load pedometer")
static var notAuthorized = Alert("Alert Not Authorized. Fix in Settings")
static var milestone25Percent = Alert("You are 25% to goal. Keep going!", severity: .good)
static var milestone50Percent = Alert("Woohoo! You're halfway there!", severity: .good)
static var milestone75Percent = Alert("Almost there, you can do it!", severity: .good)
static var goalComplete = Alert("Amazing, you did it! Have some ๐ฅง.", severity: .good)
}
extension Alert: Equatable {
static func == (lhs: Alert, rhs: Alert) -> Bool {
return lhs.text == rhs.text
}
}
extension Alert: CustomStringConvertible {
var description: String {
return "Alert: '\(text)'"
}
}
| 39.708333 | 92 | 0.731375 |
1623316da94cdded9bd10c8c56771c930c9d7c19 | 297 | //
// DebugDataFileName.swift
// Marvel
//
// Created by Diego Rogel on 19/1/22.
//
import Foundation
enum DebugDataFileName: String {
case charactersFileName = "CharactersResponse"
case characterDetailFileName = "CharacterDetailResponse"
case comicsFileName = "ComicsResponse"
}
| 19.8 | 60 | 0.737374 |
89f5d2406b0753acc9d3afceff099e128ba0b4e4 | 410 | // Copyright ยฉ 2019 Stormbird PTE. LTD.
import Foundation
struct GetInterfaceSupported165Encode {
let abi = "[{ \"constant\": true, \"inputs\": [ { \"name\": \"interfaceID\", \"type\": \"bytes4\" } ], \"name\": \"supportsInterface\", \"outputs\": [ { \"name\": \"\", \"type\": \"bool\" } ], \"payable\": false, \"stateMutability\": \"view\", \"type\": \"function\" }]"
let name = "supportsInterface"
} | 58.571429 | 274 | 0.57561 |
e21f22b613c7cb6d38fe3048aad50555961b6acc | 504 | //
// ViewController.swift
// iBeaconDemo
//
// Created by Dipang Sheth on 01/04/18.
// Copyright ยฉ 2018 Dipang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.384615 | 80 | 0.668651 |
56a8cbd62cad5f047ca1549e802772ef5ec1395b | 407 | import Vapor
import PennyConnector
import Mint
import Penny
extension ValidationWebHookHandler {
static func handle(_ req: Request) throws -> Future<HTTPStatus> {
let hook = try req.webhook(secret: GITHUB_VALIDATION_WEBHOOK_SECRET)
return hook.flatMap {
let handler = ValidationWebHookHandler(worker: req, hook: $0)
return try handler.handle()
}
}
}
| 27.133333 | 76 | 0.685504 |
e8e3a894db6b102762bd62cad6a1a2c12c0bfd9a | 1,761 | //
// WAVFileGenerator.swift
// YandexSpeechKit
//
// Created by Vladislav Popovich on 31.01.2020.
// Copyright ยฉ 2020 Just Ai. All rights reserved.
//
import Foundation
final
class WAVFileGenerator {
func createWAVFile(using rawData: Data) -> Data {
createWaveHeader(data: rawData) + rawData
}
/** http://soundfile.sapp.org/doc/WaveFormat/
*/
private
func createWaveHeader(data: Data) -> Data {
let sampleRate: Int32 = 48_000
let dataSize = Int32(data.count)
let chunkSize: Int32 = 36 + dataSize
let subChunkSize: Int32 = 16
let format: Int16 = 1
let channels: Int16 = 1
let bitsPerSample: Int16 = 16
let byteRate: Int32 = sampleRate * Int32(channels * bitsPerSample / 8)
let blockAlign: Int16 = channels * bitsPerSample / 8
var header = Data()
header.append([UInt8]("RIFF".utf8), count: 4)
header.append(byteArray(chunkSize), count: 4)
header.append([UInt8]("WAVE".utf8), count: 4)
header.append([UInt8]("fmt ".utf8), count: 4)
header.append(byteArray(subChunkSize), count: 4)
header.append(byteArray(format), count: 2)
header.append(byteArray(channels), count: 2)
header.append(byteArray(sampleRate), count: 4)
header.append(byteArray(byteRate), count: 4)
header.append(byteArray(blockAlign), count: 2)
header.append(byteArray(bitsPerSample), count: 2)
header.append([UInt8]("data".utf8), count: 4)
header.append(byteArray(dataSize), count: 4)
return header
}
private
func byteArray<T>(_ value: T) -> [UInt8] where T: FixedWidthInteger {
withUnsafeBytes(of: value.littleEndian) { Array($0) }
}
}
| 30.362069 | 78 | 0.630324 |
2027dc507456216a745763a3d7c2fbfd87193ce4 | 494 | //
// UniqueNode.swift
// Edgy
//
// Created by Jaden Geller on 12/29/15.
// Copyright ยฉ 2015 Jaden Geller. All rights reserved.
//
public class UniqueNode<Element>: Hashable {
public let element: Element
public init(_ element: Element) {
self.element = element
}
public var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
}
public func ==<Element>(lhs: UniqueNode<Element>, rhs: UniqueNode<Element>) -> Bool {
return lhs === rhs
} | 21.478261 | 85 | 0.645749 |
113825a9add9b3203d4dbfd4e3706b3bb69d43a0 | 6,151 | //
// CollectionViewController.swift
// Pager
//
// Created by Furuyama Takeshi on 2015/06/19.
// Copyright ยฉ 2015ๅนด Furuyama Takeshi. All rights reserved.
//
import UIKit
protocol CollectionViewControllerDelegate {
func collectionViewAddPage(collectionview: UICollectionView)
}
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
var pageNumber:Int?
var identifier: String?
var delegate: CollectionViewControllerDelegate?
var dataSource = ["a", "b", "c", "d", "f", "g", "h", "i", "j", "k", "l", "add"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.identifier
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView!.registerNib(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCell")
self.collectionView!.registerNib(UINib(nibName: "MyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")
self.collectionView!.registerNib(UINib(nibName: "AddCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "AddCell")
// Do any additional setup after loading the view.
self.configureBackgroundColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configureBackgroundColor() {
let colorNumber = self.pageNumber! % 3
let colors = [UIColor.lightGrayColor(), UIColor.lightTextColor(), UIColor.blackColor()]
self.collectionView?.backgroundColor = colors[colorNumber]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.dataSource.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell?
if indexPath.row == self.dataSource.count - 1 {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("AddCell", forIndexPath: indexPath) as? AddCollectionViewCell
return cell!
} else {
if indexPath.row%2 == 0 {
var customCell: CustomCollectionViewCell?
customCell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath) as? CustomCollectionViewCell
customCell?.titleLabel.text = "\(indexPath.row)"
cell?.backgroundColor = UIColor.whiteColor()
return customCell!
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as? MyCollectionViewCell
return cell!
}
}
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//
if indexPath.row == self.dataSource.count - 1 {
self.delegate?.collectionViewAddPage(collectionView)
}
}
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(108.0, 108.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 12.0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(20.0, 20.0, 5.0, 20.0)
}
}
| 40.467105 | 185 | 0.702813 |
bf84ab59ff553b6178839797f0147993875147cd | 2,191 | //
// File.swift
// Popcorn NightTests
//
// Created by Michael Isaakidis on 20/09/2018.
// Copyright ยฉ 2018 Michael Isaakidis. All rights reserved.
//
@testable import Popcorn_Night
import Foundation
class TestHelper {
// MARK: - Movies
class func generateMovie() -> Movie? {
if let movies = generateMovieArray(numberOfItems: 1) {
return movies.first
}
return nil
}
class func generateMovieArray(numberOfItems: Int) -> [Movie]? {
let data = loadDataFromFile(fileName: "Movies")
do {
let movies = try JSONDecoder().decode([Movie].self, from: data)
return Array(movies[0...(numberOfItems - 1)])
} catch {
return nil
}
}
// MARK: - Genres
class func generateGenre() -> Genre? {
if let genres = generateGenreArray(numberOfItems: 1) {
return genres.first
}
return nil
}
class func generateGenreArray(numberOfItems: Int) -> [Genre]? {
let data = loadDataFromFile(fileName: "Genres")
do {
let genres = try JSONDecoder().decode([Genre].self, from: data)
return Array(genres[0...(numberOfItems - 1)])
} catch {
return nil
}
}
// MARK: - Config
class func generateConfig() -> APIConfig? {
let data = loadDataFromFile(fileName: "Config")
do {
let config = try JSONDecoder().decode(APIConfig.self, from: data)
return config
} catch {
return nil
}
}
// MARK: - Loading Files
class func pathForFile(fileName: String, type: String) -> String? {
return Bundle(for: self).path(forResource: fileName, ofType: type)
}
class func loadDataFromFile(fileName: String) -> Data {
if let path = pathForFile(fileName: fileName, type: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
return data
} catch {
return Data()
}
}
return Data()
}
}
| 26.719512 | 99 | 0.547239 |
76692b676139aee54ae601ec62359766ec2eac64 | 2,546 | //
// ImageBannerViewController.swift
// Keyman
//
// Created by Joshua Horton on 2/4/20.
// Copyright ยฉ 2020 SIL International. All rights reserved.
//
import Foundation
import UIKit
import KeymanEngine // for log commands
/**
* Takes in a XIB spec for an image banner and makes it renderable, applying size constraints when rendered
* to ensure proper scale. Note that the loaded UIView will never be displayed in the view hierarchy.
*/
class ImageBannerViewController: UIViewController {
// Since we never actually put this UIView into the view hierarchy, we need controlled constraints
// to control the actual frame size.
var widthConstraint: NSLayoutConstraint?
var heightConstraint: NSLayoutConstraint?
init(nibName: String, bundle: Bundle) {
super.init(nibName: nibName, bundle: bundle)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
view.translatesAutoresizingMaskIntoConstraints = false
view.clipsToBounds = true
// Usually these would be in viewDidLoad, but they need to be redone with our manual-reload,
// and that method doesn't retrigger.
widthConstraint = view.widthAnchor.constraint(equalToConstant: 0)
widthConstraint!.isActive = true
heightConstraint = view.heightAnchor.constraint(equalToConstant: 0)
heightConstraint!.isActive = true
}
func renderToImage(size: CGSize) -> UIImage? {
if size.width == 0 || size.height == 0 {
return nil
}
let frame = CGRect(origin: self.view.frame.origin, size: size)
log.debug("Rendering banner image of size \(size)")
self.view.frame = frame
widthConstraint?.constant = size.width
heightConstraint?.constant = size.height
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
// Many thanks to https://stackoverflow.com/a/4334902
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
if let ctx = UIGraphicsGetCurrentContext() {
view.layer.render(in: ctx)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
}
public func renderAsBase64(size: CGSize) -> String? {
if let image = renderToImage(size: size), let data = image.pngData() {
// Thanks to https://stackoverflow.com/a/38748135
let base64 = data.base64EncodedString(options: [])
let url = "data:application/png;base64," + base64
return url
} else {
return nil
}
}
}
| 31.04878 | 107 | 0.709348 |
7acf89bca626d3408a8165ee5611df22cfb55854 | 11,320 | //
// Device.swift
// Hexadecimals
//
// Created by Naruki Chigira on 2021/08/22.
//
import Foundation
final class Device {
enum Model: String {
case iPhone6_1 = "iPhone6,1"
case iPhone6_2 = "iPhone6,2"
case iPhone7_1 = "iPhone7,1"
case iPhone7_2 = "iPhone7,2"
case iPhone8_1 = "iPhone8,1"
case iPhone8_2 = "iPhone8,2"
case iPhone8_4 = "iPhone8,4"
case iPhone9_1 = "iPhone9,1"
case iPhone9_2 = "iPhone9,2"
case iPhone9_3 = "iPhone9,3"
case iPhone9_4 = "iPhone9,4"
case iPhone10_1 = "iPhone10,1"
case iPhone10_2 = "iPhone10,2"
case iPhone10_3 = "iPhone10,3"
case iPhone10_4 = "iPhone10,4"
case iPhone10_5 = "iPhone10,5"
case iPhone10_6 = "iPhone10,6"
case iPhone11_2 = "iPhone11,2"
case iPhone11_4 = "iPhone11,4"
case iPhone11_6 = "iPhone11,6"
case iPhone11_8 = "iPhone11,8"
case iPhone12_1 = "iPhone12,1"
case iPhone12_3 = "iPhone12,3"
case iPhone12_5 = "iPhone12,5"
case iPhone12_8 = "iPhone12,8"
case iPhone13_1 = "iPhone13,1"
case iPhone13_2 = "iPhone13,2"
case iPhone13_3 = "iPhone13,3"
case iPhone13_4 = "iPhone13,4"
case iPad4_1 = "iPad4,1"
case iPad4_2 = "iPad4,2"
case iPad4_3 = "iPad4,3"
case iPad4_4 = "iPad4,4"
case iPad4_5 = "iPad4,5"
case iPad4_6 = "iPad4,6"
case iPad4_7 = "iPad4,7"
case iPad4_8 = "iPad4,8"
case iPad4_9 = "iPad4,9"
case iPad5_1 = "iPad5,1"
case iPad5_2 = "iPad5,2"
case iPad5_3 = "iPad5,3"
case iPad5_4 = "iPad5,4"
case iPad6_3 = "iPad6,3"
case iPad6_4 = "iPad6,4"
case iPad6_7 = "iPad6,7"
case iPad6_8 = "iPad6,8"
case iPad6_11 = "iPad6,11"
case iPad6_12 = "iPad6,12"
case iPad7_1 = "iPad7,1"
case iPad7_2 = "iPad7,2"
case iPad7_3 = "iPad7,3"
case iPad7_4 = "iPad7,4"
case iPad7_5 = "iPad7,5"
case iPad7_6 = "iPad7,6"
case iPad7_11 = "iPad7,11"
case iPad7_12 = "iPad7,12"
case iPad8_1 = "iPad8,1"
case iPad8_2 = "iPad8,2"
case iPad8_3 = "iPad8,3"
case iPad8_4 = "iPad8,4"
case iPad8_5 = "iPad8,5"
case iPad8_6 = "iPad8,6"
case iPad8_7 = "iPad8,7"
case iPad8_8 = "iPad8,8"
case iPad8_9 = "iPad8,9"
case iPad8_10 = "iPad8,10"
case iPad8_11 = "iPad8,11"
case iPad8_12 = "iPad8,12"
case iPad11_1 = "iPad11,1"
case iPad11_2 = "iPad11,2"
case iPad11_3 = "iPad11,3"
case iPad11_4 = "iPad11,4"
case iPad11_6 = "iPad11,6"
case iPad11_7 = "iPad11,7"
case iPad13_1 = "iPad13,1"
case iPad13_2 = "iPad13,2"
case simulator_32bit = "i386"
case simulator_64bit = "x86_64"
case simulator_arm = "arm64"
case undefined = "undefined"
var name: String {
switch self {
case .iPhone6_1:
return "iPhone 5S (GSM)"
case .iPhone6_2:
return "iPhone 5S (Global)"
case .iPhone7_1:
return "iPhone 6 Plus"
case .iPhone7_2:
return "iPhone 6"
case .iPhone8_1:
return "iPhone 6s"
case .iPhone8_2:
return "iPhone 6s Plus"
case .iPhone8_4:
return "iPhone SE (GSM)"
case .iPhone9_1:
return "iPhone 7"
case .iPhone9_2:
return "iPhone 7 Plus"
case .iPhone9_3:
return "iPhone 7"
case .iPhone9_4:
return "iPhone 7 Plus"
case .iPhone10_1:
return "iPhone 8"
case .iPhone10_2:
return "iPhone 8 Plus"
case .iPhone10_3:
return "iPhone X Global"
case .iPhone10_4:
return "iPhone 8"
case .iPhone10_5:
return "iPhone 8 Plus"
case .iPhone10_6:
return "iPhone X GSM"
case .iPhone11_2:
return "iPhone XS"
case .iPhone11_4:
return "iPhone XS Max"
case .iPhone11_6:
return "iPhone XS Max Global"
case .iPhone11_8:
return "iPhone XR"
case .iPhone12_1:
return "iPhone 11"
case .iPhone12_3:
return "iPhone 11 Pro"
case .iPhone12_5:
return "iPhone 11 Pro Max"
case .iPhone12_8:
return "iPhone SE 2nd Gen"
case .iPhone13_1:
return "iPhone 12 Mini"
case .iPhone13_2:
return "iPhone 12"
case .iPhone13_3:
return "iPhone 12 Pro"
case .iPhone13_4:
return "iPhone 12 Pro Max"
case .iPad4_1:
return "iPad Air (WiFi)"
case .iPad4_2:
return "iPad Air (GSM+CDMA)"
case .iPad4_3:
return "1st Gen iPad Air (China)"
case .iPad4_4:
return "iPad mini Retina (WiFi)"
case .iPad4_5:
return "iPad mini Retina (GSM+CDMA)"
case .iPad4_6:
return "iPad mini Retina (China)"
case .iPad4_7:
return "iPad mini 3 (WiFi)"
case .iPad4_8:
return "iPad mini 3 (GSM+CDMA)"
case .iPad4_9:
return "iPad Mini 3 (China)"
case .iPad5_1:
return "iPad mini 4 (WiFi)"
case .iPad5_2:
return "4th Gen iPad mini (WiFi+Cellular)"
case .iPad5_3:
return "iPad Air 2 (WiFi)"
case .iPad5_4:
return "iPad Air 2 (Cellular)"
case .iPad6_3:
return "iPad Pro (9.7 inch, WiFi+LTE)"
case .iPad6_4:
return "iPad Pro (9.7 inch, WiFi+LTE)"
case .iPad6_7:
return "iPad Pro (12.9 inch, WiFi)"
case .iPad6_8:
return "iPad Pro (12.9 inch, WiFi+LTE)"
case .iPad6_11:
return "iPad (2017)"
case .iPad6_12:
return "iPad (2017)"
case .iPad7_1:
return "iPad Pro 2nd Gen (WiFi)"
case .iPad7_2:
return "iPad Pro 2nd Gen (WiFi+Cellular)"
case .iPad7_3:
return "iPad Pro 10.5-inch"
case .iPad7_4:
return "iPad Pro 10.5-inch"
case .iPad7_5:
return "iPad 6th Gen (WiFi)"
case .iPad7_6:
return "iPad 6th Gen (WiFi+Cellular)"
case .iPad7_11:
return "iPad 7th Gen 10.2-inch (WiFi)"
case .iPad7_12:
return "iPad 7th Gen 10.2-inch (WiFi+Cellular)"
case .iPad8_1:
return "iPad Pro 11 inch 3rd Gen (WiFi)"
case .iPad8_2:
return "iPad Pro 11 inch 3rd Gen (1TB, WiFi)"
case .iPad8_3:
return "iPad Pro 11 inch 3rd Gen (WiFi+Cellular)"
case .iPad8_4:
return "iPad Pro 11 inch 3rd Gen (1TB, WiFi+Cellular)"
case .iPad8_5:
return "iPad Pro 12.9 inch 3rd Gen (WiFi)"
case .iPad8_6:
return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi)"
case .iPad8_7:
return "iPad Pro 12.9 inch 3rd Gen (WiFi+Cellular)"
case .iPad8_8:
return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi+Cellular)"
case .iPad8_9:
return "iPad Pro 11 inch 4th Gen (WiFi)"
case .iPad8_10:
return "iPad Pro 11 inch 4th Gen (WiFi+Cellular)"
case .iPad8_11:
return "iPad Pro 12.9 inch 4th Gen (WiFi)"
case .iPad8_12:
return "iPad Pro 12.9 inch 4th Gen (WiFi+Cellular)"
case .iPad11_1:
return "iPad mini 5th Gen (WiFi)"
case .iPad11_2:
return "iPad mini 5th Gen"
case .iPad11_3:
return "iPad Air 3rd Gen (WiFi)"
case .iPad11_4:
return "iPad Air 3rd Gen"
case .iPad11_6:
return "iPad 8th Gen (WiFi)"
case .iPad11_7:
return "iPad 8th Gen (WiFi+Cellular)"
case .iPad13_1:
return "iPad air 4th Gen (WiFi)"
case .iPad13_2:
return "iPad air 4th Gen (WiFi+Celular)"
case .simulator_32bit:
return "i386"
case .simulator_64bit:
return "x86_64"
case .simulator_arm:
return "arm64"
case .undefined:
return "undefined"
}
}
var architecture: String {
switch self {
case .iPhone6_1, .iPhone6_2, .iPhone7_1, .iPhone7_2, .iPhone8_1,
.iPhone8_2, .iPhone8_4, .iPhone9_1, .iPhone9_2, .iPhone9_3,
.iPhone9_4, .iPhone10_1, .iPhone10_2, .iPhone10_3, .iPhone10_4,
.iPhone10_5, .iPhone10_6:
return "arm64"
case .iPhone11_2, .iPhone11_4, .iPhone11_6, .iPhone11_8, .iPhone12_1,
.iPhone12_3, .iPhone12_5, .iPhone12_8, .iPhone13_1, .iPhone13_2,
.iPhone13_3, .iPhone13_4:
return "arm64e"
case .iPad4_1, .iPad4_2, .iPad4_3, .iPad4_4, .iPad4_5,
.iPad4_6, .iPad4_7, .iPad4_8, .iPad4_9, .iPad5_1,
.iPad5_2, .iPad5_3, .iPad5_4, .iPad6_3, .iPad6_4,
.iPad6_7, .iPad6_8, .iPad6_11, .iPad6_12, .iPad7_1,
.iPad7_2, .iPad7_3, .iPad7_4, .iPad7_5, .iPad7_6,
.iPad7_11, .iPad7_12, .iPad8_1, .iPad8_2, .iPad8_3,
.iPad8_4, .iPad8_5, .iPad8_6, .iPad8_7, .iPad8_8:
return "arm64"
case .iPad8_9, .iPad8_10, .iPad8_11, .iPad8_12:
return "arm64e"
case .iPad11_1, .iPad11_2, .iPad11_3, .iPad11_4:
return "arm64"
case .iPad11_6, .iPad11_7, .iPad13_1, .iPad13_2:
return "arm64e"
case .simulator_32bit, .simulator_64bit, .simulator_arm:
return "Simulator"
case .undefined:
return "undefined"
}
}
}
let model: Model
private init(identifier: String) {
let model = Model(rawValue: identifier) ?? .undefined
self.model = model
}
static var current: Device {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else {
return identifier
}
return identifier + String(UnicodeScalar(UInt8(value)))
}
return .init(identifier: identifier)
}
}
| 36.398714 | 83 | 0.50053 |
56f4b93f9ba2e4be6b02bdb63ddab1de7a477c7b | 921 | //
// LanguagePickerV.swift
// PYN
//
// Created by awaleh moussa hassan on 23/12/2020.
//
import SwiftUI
public struct LanguagePickerV: View{
@Environment(\.colorScheme) var colorScheme
@Binding var index: Int
public var body: some View {
VStack{
Text("Please choose a language")
.font(Font.headline.bold())
.padding(.top, 10)
Picker("", selection: self.$index){
ForEach(0 ..< Language.allCases.count){
Text(Language[$0])
.foregroundColor((colorScheme == .dark ? .yellow : .green))
.fontWeight(.bold)
}
}
}
}
}
struct LanguagePickerV_Previews: PreviewProvider {
static var previews: some View {
LanguagePickerV(index: .constant(0))
.previewLayout(.sizeThatFits)
}
}
| 24.891892 | 83 | 0.528773 |
1c618441fd040704dc7dd67d49b039aadbe4ee26 | 18,520 | import Foundation
import XCTest
import VisaCheckoutSDK
class BTVisaCheckout_Tests: XCTestCase {
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
func testCreateProfile_whenConfigurationFetchErrorOccurs_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseError = NSError(domain: "MyError", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile error")
client.createProfile { (profile, error) in
let err = error! as NSError
XCTAssertNil(profile)
XCTAssertEqual(err.domain, "MyError")
XCTAssertEqual(err.code, 123)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCreateProfile_whenVisaCheckoutIsNotEnabled_callsBackWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: {})
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile error")
client.createProfile { (profile, error) in
let err = error! as NSError
XCTAssertNil(profile)
XCTAssertEqual(err.domain, BTVisaCheckoutErrorDomain)
XCTAssertEqual(err.code, BTVisaCheckoutErrorType.unsupported.rawValue)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCreateProfile_whenSuccessful_returnsProfileWithArgs() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "profile success")
client.createProfile { (profile, error) in
guard let visaProfile = profile as Profile? else {
XCTFail()
return
}
XCTAssertNil(error)
XCTAssertEqual(visaProfile.apiKey, "API Key")
XCTAssertEqual(visaProfile.environment, .sandbox)
XCTAssertEqual(visaProfile.datalevel, DataLevel.full)
XCTAssertEqual(visaProfile.clientId, "clientExternalId")
if let acceptedCardBrands = visaProfile.acceptedCardBrands {
XCTAssertTrue(acceptedCardBrands.count == 4)
} else {
XCTFail()
}
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenMalformedCheckoutResult_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectedErr = NSError(domain: BTVisaCheckoutErrorDomain, code: BTVisaCheckoutErrorType.integration.rawValue, userInfo: [NSLocalizedDescriptionKey: "A valid VisaCheckoutResult is required."])
let malformedCheckoutResults : [(String?, String?, String?)] = [
(callId: nil, encryptedKey: "a", encryptedPaymentData: "b"),
(callId: "a", encryptedKey: nil, encryptedPaymentData: "b"),
(callId: "a", encryptedKey: "b", encryptedPaymentData: nil)
]
malformedCheckoutResults.forEach { (callId, encryptedKey, encryptedPaymentData) in
let expecation = expectation(description: "tokenization error due to malformed CheckoutResult")
client.tokenize(.statusSuccess, callId: callId, encryptedKey: encryptedKey, encryptedPaymentData: encryptedPaymentData) { (nonce, err) in
if nonce != nil {
XCTFail()
return
}
guard let err = err as NSError? else {
XCTFail()
return
}
XCTAssertEqual(err, expectedErr)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenStatusCodeIndicatesCancellation_callsCompletionWithNilNonceAndError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Callback invoked")
client.tokenize(.statusUserCancelled, callId: "", encryptedKey: "", encryptedPaymentData: "") { (tokenizedCheckoutResult, error) in
XCTAssertNil(tokenizedCheckoutResult)
XCTAssertNil(error)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenStatusCodeIndicatesError_callsCompletionWitheError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let statusCodes = [
CheckoutResultStatus.statusDuplicateCheckoutAttempt,
CheckoutResultStatus.statusNotConfigured,
CheckoutResultStatus.statusInternalError
]
statusCodes.forEach { statusCode in
let expectation = self.expectation(description: "Callback invoked")
client.tokenize(statusCode, callId: "", encryptedKey: "", encryptedPaymentData: "") { (_, error) in
guard let error = error as NSError? else {
XCTFail()
return
}
XCTAssertEqual(error.domain, BTVisaCheckoutErrorDomain)
XCTAssertEqual(error.code, BTVisaCheckoutErrorType.checkoutUnsuccessful.rawValue)
XCTAssertEqual(error.localizedDescription, "Visa Checkout failed with status code \(statusCode.rawValue)")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenStatusCodeIndicatesCancellation_callsAnalyticsWithCancelled() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Analytic sent")
client.tokenize(.statusUserCancelled, callId: "", encryptedKey: "", encryptedPaymentData: "") { _ in
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last!, "ios.visacheckout.result.cancelled")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenStatusCodeIndicatesError_callsAnalyticsWitheError() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let statusCodes = [
(statusCode: CheckoutResultStatus.statusDuplicateCheckoutAttempt, analyticEvent: "ios.visacheckout.result.failed.duplicate-checkouts-open"),
(statusCode: CheckoutResultStatus.statusNotConfigured, analyticEvent: "ios.visacheckout.result.failed.not-configured"),
(statusCode: CheckoutResultStatus.statusInternalError, analyticEvent: "ios.visacheckout.result.failed.internal-error"),
]
statusCodes.forEach { (statusCode, analyticEvent) in
let expectation = self.expectation(description: "Analytic sent")
client.tokenize(statusCode, callId: "", encryptedKey: "", encryptedPaymentData: "") { _ in
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last!, analyticEvent)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1, handler: nil)
}
}
func testTokenize_whenTokenizationErrorOccurs_callsCompletionWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
mockAPIClient.cannedHTTPURLResponse = HTTPURLResponse(url: URL(string: "any")!, statusCode: 503, httpVersion: nil, headerFields: nil)
mockAPIClient.cannedResponseError = NSError(domain: "foo", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization error")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, err) in
if nonce != nil {
XCTFail()
return
}
guard let err = err as NSError? else {
XCTFail()
return
}
XCTAssertEqual(err, self.mockAPIClient.cannedResponseError)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationErrorOccurs_sendsAnalyticsEvent() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"environment": "sandbox",
"visaCheckout": [
"apikey": "API Key",
"externalClientId": "clientExternalId",
"supportedCardTypes": [
"Visa",
"MasterCard",
"American Express",
"Discover"
]
]
])
mockAPIClient.cannedHTTPURLResponse = HTTPURLResponse(url: URL(string: "any")!, statusCode: 503, httpVersion: nil, headerFields: nil)
mockAPIClient.cannedResponseError = NSError(domain: "foo", code: 123, userInfo: nil)
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization error")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last, "ios.visacheckout.tokenize.failed")
}
func testTokenize_whenCalled_makesPOSTRequestToTokenizationEndpoint() {
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "callId", encryptedKey: "encryptedKey", encryptedPaymentData: "encryptedPaymentData") { _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.lastPOSTPath, "v1/payment_methods/visa_checkout_cards")
if let visaCheckoutCard = self.mockAPIClient.lastPOSTParameters?["visaCheckoutCard"] as? [String: String] {
XCTAssertEqual(visaCheckoutCard, [
"callId": "callId",
"encryptedKey": "encryptedKey",
"encryptedPaymentData": "encryptedPaymentData"
])
} else {
XCTFail()
return
}
}
func testTokenize_whenMissingPhoneNumber_returnsNilForBothAddresses() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[
"type": "VisaCheckoutCard",
"nonce": "123456-12345-12345-a-adfa",
"description": "ending in โขโข11",
"default": false,
"details": [
"cardType": "Visa",
"lastTwo": "11"
],
"shippingAddress": [
"firstName": "BT - shipping",
"lastName": "Test - shipping",
"streetAddress": "123 Townsend St Fl 6 - shipping",
"locality": "San Francisco - shipping",
"region": "CA - shipping",
"postalCode": "94107 - shipping",
"countryCode": "US - shipping"
],
"billingAddress": [
"firstName": "BT - billing",
"lastName": "Test - billing",
"streetAddress": "123 Townsend St Fl 6 - billing",
"locality": "San Francisco - billing",
"region": "CA - billing",
"postalCode": "94107 - billing",
"countryCode": "US - billing"
]
]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, error) in
if (error != nil) {
XCTFail()
return
}
guard let nonce = nonce else {
XCTFail()
return
}
XCTAssertNil(nonce.shippingAddress!.phoneNumber)
XCTAssertNil(nonce.billingAddress!.phoneNumber)
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationSuccess_callsAPIClientWithVisaCheckoutCard() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[
"type": "VisaCheckoutCard",
"nonce": "123456-12345-12345-a-adfa",
"description": "ending in โขโข11",
"default": false,
"details": [
"cardType": "Visa",
"lastTwo": "11"
],
"shippingAddress": [
"firstName": "BT - shipping",
"lastName": "Test - shipping",
"streetAddress": "123 Townsend St Fl 6 - shipping",
"extendedAddress": "Unit 123 - shipping",
"locality": "San Francisco - shipping",
"region": "CA - shipping",
"postalCode": "94107 - shipping",
"countryCode": "US - shipping",
"phoneNumber": "1234567890 - shipping"
],
"billingAddress": [
"firstName": "BT - billing",
"lastName": "Test - billing",
"streetAddress": "123 Townsend St Fl 6 - billing",
"extendedAddress": "Unit 123 - billing",
"locality": "San Francisco - billing",
"region": "CA - billing",
"postalCode": "94107 - billing",
"countryCode": "US - billing",
"phoneNumber": "1234567890 - billing"
],
"userData": [
"userFirstName": "userFirstName",
"userLastName": "userLastName",
"userFullName": "userFullName",
"userName": "userUserName",
"userEmail": "userEmail"
]
]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { (nonce, error) in
if (error != nil) {
XCTFail()
return
}
guard let nonce = nonce else {
XCTFail()
return
}
XCTAssertEqual(nonce.type, "VisaCheckoutCard")
XCTAssertEqual(nonce.nonce, "123456-12345-12345-a-adfa")
XCTAssertEqual(nonce.localizedDescription, "ending in โขโข11")
XCTAssertTrue(nonce.cardNetwork == BTCardNetwork.visa)
XCTAssertEqual(nonce.lastTwo, "11")
[(nonce.shippingAddress!, "shipping"), (nonce.billingAddress!, "billing")].forEach { (address, type) in
XCTAssertEqual(address.firstName, "BT - " + type)
XCTAssertEqual(address.lastName, "Test - " + type)
XCTAssertEqual(address.streetAddress, "123 Townsend St Fl 6 - " + type)
XCTAssertEqual(address.extendedAddress, "Unit 123 - " + type)
XCTAssertEqual(address.locality, "San Francisco - " + type)
XCTAssertEqual(address.region, "CA - " + type)
XCTAssertEqual(address.postalCode, "94107 - " + type)
XCTAssertEqual(address.countryCode, "US - " + type)
XCTAssertEqual(address.phoneNumber, "1234567890 - " + type)
}
XCTAssertEqual(nonce.userData!.firstName, "userFirstName")
XCTAssertEqual(nonce.userData!.lastName, "userLastName")
XCTAssertEqual(nonce.userData!.fullName, "userFullName")
XCTAssertEqual(nonce.userData!.username, "userUserName")
XCTAssertEqual(nonce.userData!.email, "userEmail")
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTokenize_whenTokenizationSuccess_sendsAnalyticEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"visaCheckoutCards":[[:]]
])
let client = BTVisaCheckoutClient(apiClient: mockAPIClient)
let expecation = expectation(description: "tokenization success")
client.tokenize(.statusSuccess, callId: "", encryptedKey: "", encryptedPaymentData: "") { _ in
expecation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(self.mockAPIClient.postedAnalyticsEvents.last!, "ios.visacheckout.tokenize.succeeded")
}
}
| 41.247216 | 202 | 0.577646 |
67b1f5c6e1316b4d5fc88a1ee0dfb964a27e70a8 | 3,756 | // swiftlint:disable all
// Generated using SwiftGen, by O.Halligon โ https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSImage
internal typealias AssetColorTypeAlias = NSColor
internal typealias AssetImageTypeAlias = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
internal typealias AssetColorTypeAlias = UIColor
internal typealias AssetImageTypeAlias = UIImage
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal static let button = ImageAsset(name: "button")
internal static let buttonDown = ImageAsset(name: "button_down")
internal static let buttonTemplate = ImageAsset(name: "button_template")
internal static let dance = ImageAsset(name: "dance")
internal static let danceDown = ImageAsset(name: "dance_down")
internal static let doggo = ImageAsset(name: "doggo")
internal static let doggoDown = ImageAsset(name: "doggo_down")
internal static let hungry = ImageAsset(name: "hungry")
internal static let hungryDown = ImageAsset(name: "hungry_down")
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
// MARK: - Implementation Details
internal struct ColorAsset {
internal fileprivate(set) var name: String
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
internal var color: AssetColorTypeAlias {
return AssetColorTypeAlias(asset: self)
}
}
internal extension AssetColorTypeAlias {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
convenience init!(asset: ColorAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct DataAsset {
internal fileprivate(set) var name: String
#if os(iOS) || os(tvOS) || os(OSX)
@available(iOS 9.0, tvOS 9.0, OSX 10.11, *)
internal var data: NSDataAsset {
return NSDataAsset(asset: self)
}
#endif
}
#if os(iOS) || os(tvOS) || os(OSX)
@available(iOS 9.0, tvOS 9.0, OSX 10.11, *)
internal extension NSDataAsset {
convenience init!(asset: DataAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(name: asset.name, bundle: bundle)
#elseif os(OSX)
self.init(name: NSDataAsset.Name(asset.name), bundle: bundle)
#endif
}
}
#endif
internal struct ImageAsset {
internal fileprivate(set) var name: String
internal var image: AssetImageTypeAlias {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
let image = AssetImageTypeAlias(named: name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
let image = bundle.image(forResource: NSImage.Name(name))
#elseif os(watchOS)
let image = AssetImageTypeAlias(named: name)
#endif
guard let result = image else { fatalError("Unable to load image named \(name).") }
return result
}
}
internal extension AssetImageTypeAlias {
@available(iOS 1.0, tvOS 1.0, watchOS 1.0, *)
@available(OSX, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init!(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = Bundle(for: BundleToken.self)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSImage.Name(asset.name))
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
private final class BundleToken {}
| 32.102564 | 93 | 0.715655 |
b99d70577d6f5307ba421053401b85ec2d61d884 | 97 | import Foundation
protocol DateRepository {
func save(date: Date)
func load() -> Date
}
| 13.857143 | 25 | 0.680412 |
d926bd15441b47d6bb3ad1f132a511b87a4143f1 | 1,198 | //
// GameOver.swift
// Orbit 7
//
// Created by Aaron Ackerman on 1/17/15.
// Copyright (c) 2015 Mav3r1ck. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene: SKScene {
init(size: CGSize, won:Bool) {
super.init(size: size)
backgroundColor = SKColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
var message = won ? "You Won!" : "You Lost, Try again!"
let label = SKLabelNode(fontNamed: "DIN Condensed")
label.text = message
label.fontSize = 40
label.fontColor = SKColor.whiteColor()
label.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(label)
runAction(SKAction.sequence([
SKAction.waitForDuration(5.0),
SKAction.runBlock() {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = Menu(size: size)
self.view?.presentScene(scene, transition:reveal)
}
]))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | 27.227273 | 82 | 0.56177 |
cc4fe926a5671fdb11792e9909f083ae83a8568a | 4,302 | //
// PicturesCollectionViewDataSource.swift
// Pictures
//
// Created by Wipoo Shinsirikul on 12/28/16.
// Copyright ยฉ 2016 Wipoo Shinsirikul. All rights reserved.
//
import UIKit
class PicturesCollectionViewDataSource<T: UICollectionViewCell>: NSObject, UICollectionViewDataSource where T: PicturesImageProviderType
{
weak var collectionView: UICollectionView? { didSet { didSetCollectionView(oldValue) } }
weak var picturesCollectionViewDelegate: PicturesCollectionViewDelegate<T>?
var pictures: [Any] = []
var isLoading = false
var isLoadAll = false { didSet { didSetIsLoadAll(oldValue) } }
// MARK: - Setter
private func didSetCollectionView(_ oldValue: UICollectionView?)
{
collectionView?.register(T.self, forCellWithReuseIdentifier: NSStringFromClass(T.self))
collectionView?.register(LoadingCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: NSStringFromClass(LoadingCollectionReusableView.self))
}
private func didSetIsLoadAll(_ oldValue: Bool)
{
if isLoadAll == oldValue
{
// ;
}
else
{
collectionView?.collectionViewLayout.invalidateLayout()
}
}
// MARK: -
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return pictures.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard 0..<pictures.count ~= indexPath.item else
{
fatalError()
}
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(T.self), for: indexPath) as? T else
{
fatalError()
}
if let pictures = self.pictures as? [URL]
{
let picture = pictures[indexPath.item]
cell.isSelected = picturesCollectionViewDelegate.map { $0.selectedPictures.contains(picture) } ?? false
cell.imageURL = picture
if cell.isSelected
{
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition())
(cell as? SelectedIndexCellType)?.index = picturesCollectionViewDelegate?.selectedPictures.index(of: picture).map { UInt($0) + 1 } ?? 1
}
else
{
collectionView.deselectItem(at: indexPath, animated: false)
}
}
else if let pictures = self.pictures as? [UIImage]
{
let picture = pictures[indexPath.item]
cell.isSelected = picturesCollectionViewDelegate.map { $0.selectedImagePictures.contains(picture) } ?? false
cell.image = picture
if cell.isSelected
{
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition())
(cell as? SelectedIndexCellType)?.index = picturesCollectionViewDelegate?.selectedImagePictures.index(of: picture).map { UInt($0) + 1 } ?? 1
}
else
{
collectionView.deselectItem(at: indexPath, animated: false)
}
}
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
if isLoadAll
{
return UICollectionReusableView(frame: .zero)
}
else
{
guard let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: NSStringFromClass(LoadingCollectionReusableView.self), for: indexPath) as? LoadingCollectionReusableView else
{
fatalError()
}
view.startAnimating()
return view
}
}
}
| 34.416 | 253 | 0.620177 |
1d2312712fcf0c0849681d931b612a5515b1eec1 | 2,289 | //
// GATTIndoorPositioningConfiguration.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/2/18.
// Copyright ยฉ 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Indoor Positioning Configuration
The Indoor Positioning Configuration describes the set of characteristic values included in the Indoor Positioning Service AD type.
- SeeAlso: [Indoor Positioning Configuration](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.indoor_positioning_configuration.xml)
*/
@frozen
public struct GATTIndoorPositioningConfiguration: GATTCharacteristic {
public static var uuid: BluetoothUUID { return .indoorPositioningConfiguration }
internal static let length = MemoryLayout<UInt8>.size
public var configurations: BitMaskOptionSet<Configuration>
public init(configurations: BitMaskOptionSet<Configuration>) {
self.configurations = configurations
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.init(configurations: BitMaskOptionSet<Configuration>(rawValue: data[0]))
}
public var data: Data {
return Data([configurations.rawValue])
}
}
extension GATTIndoorPositioningConfiguration {
public enum Configuration: UInt8, BitMaskOption {
/// Presence of coordinates in advertising packets
case coordinates = 0b01
/// Coordinate system used in advertising packets
case coordinateSystemUsed = 0b10
/// Presence of Tx Power field in advertising packets
case txPowerField = 0b100
/// Presence of Altitude field in advertising packets
case altitudeField = 0b1000
/// Presence of Floor Number in advertising packets
case floorNumber = 0b10000
//Location Name available in the GATT database
case locationName = 0b100000
public static let allCases: [Configuration] = [
.coordinates,
.coordinateSystemUsed,
.txPowerField,
.altitudeField,
.floorNumber,
.locationName
]
}
}
| 28.974684 | 183 | 0.657492 |
f87934778d5d01078d180ec23d1dbabcace3b992 | 3,292 | //
// JsonPropertyLoader.swift
// Swinject
//
// Created by mike.owens on 12/6/15.
// Copyright ยฉ 2015 Swinject Contributors. All rights reserved.
//
import Foundation
/// The JsonPropertyLoader will load properties from JSON resources
final public class JsonPropertyLoader {
/// the bundle where the resource exists (defualts to mainBundle)
private let bundle: NSBundle
/// the name of the JSON resource. For example, if your resource is "properties.json" then this value will be set to "properties"
private let name: String
///
/// Will create a JSON property loader
///
/// - parameter bundle: the bundle where the resource exists (defaults to mainBundle)
/// - parameter name: the name of the JSON resource. For example, if your resource is "properties.json"
/// then this value will be set to "properties"
///
public init(bundle: NSBundle? = .mainBundle(), name: String) {
self.bundle = bundle!
self.name = name
}
/// Will strip the provide string of comments. This allows JSON property files to contain comments as it
/// is valuable to provide more context to a property then just its key-value and comments are not valid JSON
/// so this will process the JSON string before we attempt to parse the JSON into objects
///
/// Implementation influence by Typhoon:
/// https://github.com/appsquickly/Typhoon/blob/master/Source/Configuration/ConfigPostProcessor/TyphoonConfiguration/TyphoonJsonStyleConfiguration.m#L30
///
/// - Parameter str: the string to strip of comments
///
/// - Returns: the json string stripper of comments
private func stringWithoutComments(str: String) -> String {
let pattern = "(([\"'])(?:\\\\\\2|.)*?\\2)|(\\/\\/[^\\n\\r]*(?:[\\n\\r]+|$)|(\\/\\*(?:(?!\\*\\/).|[\\n\\r])*\\*\\/))"
let expression = try? NSRegularExpression(pattern: pattern, options: .AnchorsMatchLines)
let matches = expression!.matchesInString(str, options: NSMatchingOptions(rawValue: 0),
range: NSMakeRange(0, str.characters.count))
guard !matches.isEmpty else {
return str
}
let ret = NSMutableString(string: str)
for match in matches.reverse() {
let character = String(str[str.startIndex.advancedBy(match.range.location)])
if character != "\'" && character != "\"" {
ret.replaceCharactersInRange(match.range, withString: "")
}
}
return ret as String
}
}
// MARK: - PropertyLoadable
extension JsonPropertyLoader: PropertyLoaderType {
public func load() throws -> [String : AnyObject] {
let contents = try loadStringFromBundle(bundle, withName: name, ofType: "json")
let jsonWithoutComments = stringWithoutComments(contents)
let data = jsonWithoutComments.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
guard let props = json as? [String:AnyObject] else {
throw PropertyLoaderError.InvalidJSONFormat(bundle: bundle, name: name)
}
return props
}
}
| 40.641975 | 156 | 0.641555 |
56c12e4daeb28e61ff486259d68b590448f7743e | 3,697 | //
// MIT License
//
// Copyright (c) 2018-2019 Open Zesame (https://github.com/OpenZesame)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import RxCocoa
import RxSwift
// MARK: - RemovePincodeUserAction
enum RemovePincodeUserAction {
case cancelPincodeRemoval
case removePincode
}
// MARK: - RemovePincodeViewModel
private typealias โฌ = L10n.Scene.RemovePincode
final class RemovePincodeViewModel: BaseViewModel<
RemovePincodeUserAction,
RemovePincodeViewModel.InputFromView,
RemovePincodeViewModel.Output
> {
private let useCase: PincodeUseCase
private let pincode: Pincode
init(useCase: PincodeUseCase) {
self.useCase = useCase
guard let pincode = useCase.pincode else {
incorrectImplementation("Should have pincode set")
}
self.pincode = pincode
}
// swiftlint:disable:next function_body_length
override func transform(input: Input) -> RemovePincodeViewModel.Output {
func userDid(_ userAction: NavigationStep) {
navigator.next(userAction)
}
let validator = InputValidator(existingPincode: pincode)
let pincodeValidationValue: Driver<PincodeValidator.ValidationResult> = input.fromView.pincode.map {
return validator.validate(unconfirmedPincode: $0)
}
bag <~ [
input.fromController.leftBarButtonTrigger
.do(onNext: { userDid(.cancelPincodeRemoval) })
.drive(),
pincodeValidationValue.filter { $0.isValid }
.mapToVoid()
.do(onNext: { [unowned useCase] in
useCase.deletePincode()
userDid(.removePincode)
})
.drive()
]
return Output(
inputBecomeFirstResponder: input.fromController.viewDidAppear,
pincodeValidation: pincodeValidationValue.map { $0.validation }
)
}
}
extension RemovePincodeViewModel {
struct InputFromView {
let pincode: Driver<Pincode?>
}
struct Output {
let inputBecomeFirstResponder: Driver<Void>
let pincodeValidation: Driver<AnyValidation>
}
struct InputValidator {
private let existingPincode: Pincode
private let pincodeValidator = PincodeValidator(settingNew: false)
init(existingPincode: Pincode) {
self.existingPincode = existingPincode
}
func validate(unconfirmedPincode: Pincode?) -> PincodeValidator.ValidationResult {
return pincodeValidator.validate(input: (unconfirmedPincode, existingPincode))
}
}
}
| 33.306306 | 108 | 0.68488 |
764df1a1f2e9a34e5c4978643aa3dbb420abcbd9 | 2,285 | //
// AppDelegate.swift
// newsApp
//
// Created by Miguel Gutiรฉrrez Moreno on 22/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
struct MainStoryboard {
static let name = "Main"
}
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
StoreNewsApp.defaultStore().graba() // por seguridad
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 43.942308 | 285 | 0.742232 |
1c04309edc5f29296a5db74ef96e6ff80e64299d | 3,230 | //
// BookmarksViewModel.swift
// iOSEngineerCodeCheck
//
// Created by Yoshihisa Masaki on 2021/04/02.
// Copyright ยฉ 2021 YUMEMI Inc. All rights reserved.
//
import Foundation
import CoreData
import Combine
// Core Data ใฎ NSManagedObject ใฎ้
ๅปถใงใใผใฟใใญใผใใใ fault ใๆๅนใซไฝฟใใใใซ plain data object ใจใไฝฟใใใซใใฎใพใพ NSManagedObject ใไฝฟใๆนใใกใขใชๅน็ใใใใฎใงใชใใธใใชใใฟใผใณใจใไฝฟใฃใฆใใชใใ
// Core Data ใธใฎๅผทใไพๅญใใใใใใในใใใใฅใใใฎใ่ชฒ้กใ
final class BookmarksViewModel {
weak var fetchedResultsControllerDelegate: NSFetchedResultsControllerDelegate? {
didSet {
fetchedResultsController.delegate = fetchedResultsControllerDelegate
}
}
@Published var state: BookmarksViewModelState = .none
private let persistent: Persistent
private lazy var fetchedResultsController: NSFetchedResultsController<RepositoryBookmark> = {
let request: NSFetchRequest<RepositoryBookmark> = RepositoryBookmark.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "bookmarkCreationDate", ascending: false)]
request.fetchBatchSize = 50
let context = persistent.viewContext
let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = fetchedResultsControllerDelegate
return controller
}()
var repositories: [RepositoryEntity] {
fetchedResultsController.fetchedObjects?.compactMap { $0.repositoryEntity } ?? []
}
var lastSelectedItemIndexPath: IndexPath = IndexPath(item: 0, section: 0)
var lastSelectedRepository: RepositoryEntity? {
fetchedResultsController.object(at: lastSelectedItemIndexPath).repositoryEntity
}
init(persistent: Persistent = Persistent.shared) {
self.persistent = persistent
}
func populateData() {
do {
try fetchedResultsController.performFetch()
} catch {
print("Failed to fetch \(fetchedResultsController.fetchRequest)")
}
}
func numberOfItems(in seciton: Int) -> Int {
fetchedResultsController.fetchedObjects?.count ?? 0
}
func repositoryEntity(for indexPath: IndexPath) -> RepositoryEntity? {
fetchedResultsController.object(at: indexPath).repositoryEntity
}
// MARK: - Search Repository Bookmark
func searchRepository(by searchTerm: String) {
if searchTerm.isEmpty {
fetchedResultsController.fetchRequest.predicate = nil
} else {
fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "fullName CONTAINS[cd] %@", searchTerm)
}
populateData()
state = .repositoriesUpdated
}
func cancelSearch() {}
func indexPath(for repository: RepositoryEntity) -> IndexPath? {
guard let index = repositories.firstIndex(where: { $0.fullName == repository.fullName }) else {
return nil
}
return IndexPath(item: index, section: 0)
}
func deleteBookmark(at indexPath: IndexPath) {
let context = persistent.viewContext
let bookmark = fetchedResultsController.object(at: indexPath)
context.delete(bookmark)
persistent.saveContext()
}
}
| 31.980198 | 146 | 0.702477 |
71742e2fe8a1dfeb27225ad725591b437892a693 | 635 | //
// AddExpenseTypeTVCell.swift
// XM_Infor
//
// Created by ไฝๅ
ตๅ
ต on 2017/7/8.
// Copyright ยฉ 2017ๅนด Robin He. All rights reserved.
//
import UIKit
class AddExpenseTypeTVCell: UITableViewCell {
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var allocationTypeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
allocationTypeLabel.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.678571 | 65 | 0.67874 |
fc4383cc1d74650152d340964400182df65ab961 | 712 | import Postbox
public final class SynchronizeGroupedPeersOperation: PostboxCoding {
public let peerId: PeerId
public let groupId: PeerGroupId
public init(peerId: PeerId, groupId: PeerGroupId) {
self.peerId = peerId
self.groupId = groupId
}
public init(decoder: PostboxDecoder) {
self.peerId = PeerId(decoder.decodeInt64ForKey("peerId", orElse: 0))
self.groupId = PeerGroupId.init(rawValue: decoder.decodeInt32ForKey("groupId", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.peerId.toInt64(), forKey: "peerId")
encoder.encodeInt32(self.groupId.rawValue, forKey: "groupId")
}
}
| 32.363636 | 98 | 0.683989 |
01c64508ed188e276e441c54437a8d0fd7408f5b | 2,348 | //
// DCCServiceMock.swift
//
//
// ยฉ Copyright IBM Deutschland GmbH 2021
// SPDX-License-Identifier: Apache-2.0
//
import CertLogic
import CovPassCommon
import Foundation
import PromiseKit
public enum DCCServiceMockError: Error {
case invalidURL
}
class DCCServiceMock: DCCServiceProtocol {
var loadDomesticDCCRulesResult: Promise<[RuleSimple]>?
func loadDomesticRules() -> Promise<[RuleSimple]> {
loadDomesticDCCRulesResult ?? Promise.value([])
}
var loadDomesticDCCRuleResult: Promise<Rule>?
func loadDomesticRule(hash: String) -> Promise<Rule> {
loadDomesticDCCRuleResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
var loadDCCRulesResult: Promise<[RuleSimple]>?
func loadDCCRules() -> Promise<[RuleSimple]> {
loadDCCRulesResult ?? Promise.value([])
}
var loadDCCRuleResult: Promise<Rule>?
func loadDCCRule(country _: String, hash _: String) -> Promise<Rule> {
loadDCCRuleResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
var loadValueSetsResult: Promise<[[String: String]]>?
func loadValueSets() -> Promise<[[String: String]]> {
loadValueSetsResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
var loadValueSetResult: Promise<CovPassCommon.ValueSet>?
func loadValueSet(id _: String, hash _: String) -> Promise<CovPassCommon.ValueSet> {
loadValueSetResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
var loadBoosterRulesResult: Promise<[RuleSimple]>?
func loadBoosterRules() -> Promise<[RuleSimple]> {
loadBoosterRulesResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
var loadBoosterRuleResult: Promise<Rule>?
func loadBoosterRule(hash _: String) -> Promise<Rule> {
loadBoosterRuleResult ?? Promise(error: DCCServiceMockError.invalidURL)
}
func loadCountryList() -> Promise<[Country]> {
let json =
"""
["IT","LT","DK","GR","CZ","HR","IS","PT","PL","BE","BG","DE","LU","EE","CY","ES","NL","AT","LV","LI","FI","SE","SI","RO","NO","SK","FR","MT","HU","IE","CH","VA","SM","UA","TR","MK","AD","MC","FO","MA","AL","IL","PA"]
"""
let countries: [Country] = try! JSONDecoder().decode([String].self, from: json.data(using: .utf8)!).map({.init($0)})
return Promise.value(countries)
}
}
| 34.028986 | 224 | 0.663969 |
6a893ab4a84a293a8ccef1a54e3d5bfd3cb4feaa | 782 | // ()ๆฏ็ฉบๅ
็ป
//func sum(v1: Int, v2: Int) -> Int { v1 + v2 }
//sum(v1: 10, v2: 20)
//func goToWork(time: String) {
// print("this time is \(time)")
//}
//goToWork(time: "08:00")
//func goToWork(at: String) {
// print("this time is \(at)")
//}
//goToWork(at: "08:00")
//
//func goToWork(at time: String) {
// print("this time is \(time)")
//}
//goToWork(at: "08:00")
// go to work at 08:00
var number = 10
func add(_ num: inout Int) {
num = 20
}
add(&number)
print(number)
//func sum(v1: Int, v2: Int) -> Int {
// v1 + v2
//}
func sum(_ v1: Int, _ v2: Int) -> Int {
v1 + v2
}
func sum(_ numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
// error: ambiguous use of 'sum'
sum(10, 20)
| 15.038462 | 47 | 0.539642 |
fe397db89803f57ee85d8a53040bf2c0d48ef024 | 1,613 | //
// Created by Eugene Kazaev on 22/02/2018.
//
import Foundation
import UIKit
/// Helper protocol to `Factory` that is also a `Container`. If it supports only one type of actions to build its
/// children `UIViewControllers` - use this protocol. It contains default merge function implementation.
public protocol SimpleContainerFactory: Container {
/// Type of supported `Action` instances
associatedtype SupportedAction
/// Factories that will build children view controllers when it will be needed.
var factories: [ChildFactory<Context>] { get set }
}
public extension SimpleContainerFactory {
public mutating func merge<C>(_ factories: [ChildFactory<C>]) -> [ChildFactory<C>] {
var otherFactories: [ChildFactory<C>] = []
self.factories = factories.compactMap { factory -> ChildFactory<Context>? in
guard let _ = factory.action as? SupportedAction else {
otherFactories.append(factory)
return nil
}
return factory as? ChildFactory<Context>
}
return otherFactories
}
/// This function contains default implementation how Container should create its children view controller
/// before built them into itself.
///
/// - Parameters:
/// - context: A `Context` instance if any
/// - Returns: An array of build view controllers
/// - Throws: RoutingError
public func buildChildrenViewControllers(with context: Context) throws -> [UIViewController] {
return try buildChildrenViewControllers(from: factories, with: context)
}
}
| 34.319149 | 113 | 0.680099 |
7af61a8a457d976b6047ac05d0eb42960cebb86b | 1,899 | //
// ThumbnailsViewControllerTest.swift
// PhotoViewerTests
//
// Created by Slobodan Kovrlija on 5/29/19.
// Copyright ยฉ 2019 Slobodan Kovrlija. All rights reserved.
//
import XCTest
@testable import PhotoViewer
class ThumbnailsViewControllerTest: XCTestCase {
var sut: ThumbnailsViewController!
var tableView: UITableView!
override func setUp() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "ThumbnailsVC")
sut = (viewController as! ThumbnailsViewController)
_ = sut.view
tableView = UITableView()
tableView.dataSource = sut
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_TableViewIsNotNilAfterViewDidLoad() {
XCTAssertNotNil(sut.tableView)
}
func test_LoadingViewSetsTableViewDataSource() {
XCTAssertTrue(sut.tableView.dataSource is ThumbnailsViewController)
}
func test_LoadingViewSetsTableViewDelegate() {
XCTAssertTrue(sut.tableView.delegate is ThumbnailsViewController)
}
func test_LoadingViewSetsDataSourceAndDelegateToSameObject() {
XCTAssertEqual(sut.tableView.dataSource as? ThumbnailsViewController, sut.tableView.delegate as? ThumbnailsViewController)
}
func test_NumberOfRowsInFirstSectionIsArrayOfThumbnailsCount() {
sut.arrayOfThumbnails.append(Photo(url: "https://via.placeholder.com/600/24f355"))
XCTAssertEqual(tableView.numberOfRows(inSection: 0), 1)
sut.arrayOfThumbnails.append(Photo(url: "https://via.placeholder.com/600/d32776"))
tableView.reloadData()
XCTAssertEqual(tableView.numberOfRows(inSection: 0), 2)
}
}
| 31.65 | 130 | 0.699842 |
e2b002320517b8a2f8c3e998dabd9380eba3907c | 226 | //
// OrderItem.swift
// foodTruck
//
// Created by Ruicong Xie on 12/20/16.
// Copyright ยฉ 2016 ruicong xie. All rights reserved.
//
import Foundation
import UIKit
class OrderItem: MenuItem{
var quantity: Int = 0
}
| 15.066667 | 54 | 0.681416 |
e962c61691cd8c03b94a2fec3198234ac283521b | 3,800 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public struct VariableMap<Value>: Sequence {
public typealias Element = (Variable, Value)
private var elements: [Value?]
public init() {
self.elements = []
// Reserve capacity for roughly as many elements as the average number of variables in generated Programs
elements.reserveCapacity(128)
}
public init(_ elementsMap: [Int: Value]) {
self.init()
for (varNumber, value) in elementsMap {
self[Variable(number: varNumber)] = value
}
}
init(_ elements: [Value?]) {
self.elements = elements
}
public var isEmpty: Bool {
return elements.isEmpty
}
public subscript(variable: Variable) -> Value? {
get {
let index = variable.number
if index >= elements.count {
return nil
}
return elements[index]
}
mutating set(newValue) {
let index = variable.number
growIfNecessary(to: index + 1)
elements[index] = newValue
}
}
public func contains(_ variable: Variable) -> Bool {
return elements.count > variable.number && elements[variable.number] != nil
}
public func hasHoles() -> Bool {
return elements.contains(where: {$0 == nil})
}
public mutating func removeValue(forKey variable: Variable) {
if elements.count > variable.number {
elements[variable.number] = nil
shrinkIfNecessary()
}
}
public mutating func removeAll() {
elements = []
}
public func makeIterator() -> VariableMap<Value>.Iterator {
return Iterator(elements: elements)
}
public struct Iterator: IteratorProtocol {
public typealias Element = (Variable, Value)
private let elements: [Value?]
private var idx = 0
init(elements: [Value?]) {
self.elements = elements
}
public mutating func next() -> Element? {
while idx < elements.count {
idx += 1
if let elem = elements[idx - 1] {
return (Variable(number: idx - 1), elem)
}
}
return nil
}
}
private mutating func growIfNecessary(to newLen: Int) {
if newLen < elements.count {
return
}
for _ in 0..<newLen - elements.count {
elements.append(nil)
}
}
private mutating func shrinkIfNecessary() {
while elements.count > 0 && elements.last! == nil {
elements.removeLast()
}
}
}
// VariableMaps can be compared for equality if their elements can.
extension VariableMap: Equatable where Value: Equatable {
public static func == (lhs: VariableMap<Value>, rhs: VariableMap<Value>) -> Bool {
return lhs.elements == rhs.elements
}
}
// VariableMaps can be hashed if their elements can.
extension VariableMap: Hashable where Value: Hashable {}
// VariableMaps can be encoded and decoded if their elements can.
extension VariableMap: Codable where Value: Codable {}
| 29.457364 | 113 | 0.593421 |
9c891228ad11c99dd902f7639d3f088c3157e97a | 578 | //
// FZRouterDataPacket.swift
// FZRouterSwift
//
// Created by FranZhou on 2020/8/4.
//
import Foundation
/// Its purpose is to pass the parameter and receive the return value in the target-action call
open class FZRouterDataPacket: NSObject, FZRouterDataPacketProtocol {
/// passing parameters into the target action
@objc public var parameters: [String: Any]?
/// receive return result
@objc public var returnValue: Any?
@objc required public init(parameters: [String: Any]?) {
self.parameters = parameters
super.init()
}
}
| 22.230769 | 95 | 0.693772 |
1d10021647303c47e75260edd2269f3f3cb249dc | 737 | //
// RSRPIntermediateResult.swift
// Pods
//
// Created by James Kizer on 2/10/17.
//
//
import UIKit
open class RSRPIntermediateResult: NSObject {
public let type: String
open var uuid: UUID
open var taskIdentifier: String
open var taskRunUUID: UUID
open var startDate: Date?
open var endDate: Date?
//note that userInfo MUST be JSON serializable
open var userInfo: [String: Any]?
public init(
type: String,
uuid: UUID,
taskIdentifier: String,
taskRunUUID: UUID
) {
self.type = type
self.uuid = uuid
self.taskIdentifier = taskIdentifier
self.taskRunUUID = taskRunUUID
super.init()
}
}
| 19.394737 | 50 | 0.602442 |
f98d0e9e35d3480844b9ca299d095e3a2cbd493b | 1,071 | //
// NSManagedObjectContext+Extensions.swift
// SwiftWeather
//
// Created by Mykhailo Vorontsov on 13/04/2016.
// Copyright ยฉ 2016 Mykhailo Vorontsov. All rights reserved.
//
import CoreData
extension NSManagedObjectContext {
/**
Flush changes in givven context thtough all parent context to persistent store.
*/
public func save (recursive:Bool) {
if self.hasChanges {
do {
try self.save()
if let parentContext = parent, true == recursive {
parentContext.save(recursive:true)
}
} catch {
var dict = [String: AnyObject]()
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: CoreDataManager.errorDomain, code: CoreDataError.storeCoordinatorCreation.rawValue, userInfo: dict)
print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
assert(false)
}
}
}
public func deleteObjects(_ arrayOfObjects:[NSManagedObject]) {
for managedObject in arrayOfObjects {
self.delete(managedObject)
}
}
}
| 26.775 | 142 | 0.670401 |
4bc568198ffb4d19a2aed80a98d42b847d328407 | 11,055 | /*
* Copyright 2021, gRPC Authors 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 NIO
import NIOHPACK
public final class ServerStreamingServerHandler<
Serializer: MessageSerializer,
Deserializer: MessageDeserializer
>: GRPCServerHandlerProtocol {
public typealias Request = Deserializer.Output
public typealias Response = Serializer.Input
/// A response serializer.
@usableFromInline
internal let serializer: Serializer
/// A request deserializer.
@usableFromInline
internal let deserializer: Deserializer
/// A pipeline of user provided interceptors.
@usableFromInline
internal var interceptors: ServerInterceptorPipeline<Request, Response>!
/// The context required in order create the function.
@usableFromInline
internal let context: CallHandlerContext
/// A reference to a `UserInfo`.
@usableFromInline
internal let userInfoRef: Ref<UserInfo>
/// The user provided function to execute.
@usableFromInline
internal let userFunction: (Request, StreamingResponseCallContext<Response>)
-> EventLoopFuture<GRPCStatus>
/// The state of the handler.
@usableFromInline
internal var state: State = .idle
@usableFromInline
internal enum State {
// Initial state. Nothing has happened yet.
case idle
// Headers have been received and now we're holding a context with which to invoke the user
// function when we receive a message.
case createdContext(_StreamingResponseCallContext<Request, Response>)
// The user function has been invoked, we're waiting for the status promise to be completed.
case invokedFunction(_StreamingResponseCallContext<Request, Response>)
// The function has completed or we are no longer proceeding with execution (because of an error
// or unexpected closure).
case completed
}
@inlinable
public init(
context: CallHandlerContext,
requestDeserializer: Deserializer,
responseSerializer: Serializer,
interceptors: [ServerInterceptor<Request, Response>],
userFunction: @escaping (Request, StreamingResponseCallContext<Response>)
-> EventLoopFuture<GRPCStatus>
) {
self.serializer = responseSerializer
self.deserializer = requestDeserializer
self.context = context
self.userFunction = userFunction
let userInfoRef = Ref(UserInfo())
self.userInfoRef = userInfoRef
self.interceptors = ServerInterceptorPipeline(
logger: context.logger,
eventLoop: context.eventLoop,
path: context.path,
callType: .serverStreaming,
remoteAddress: context.remoteAddress,
userInfoRef: userInfoRef,
interceptors: interceptors,
onRequestPart: self.receiveInterceptedPart(_:),
onResponsePart: self.sendInterceptedPart(_:promise:)
)
}
// MARK: Public API; gRPC to Handler
@inlinable
public func receiveMetadata(_ headers: HPACKHeaders) {
self.interceptors.receive(.metadata(headers))
}
@inlinable
public func receiveMessage(_ bytes: ByteBuffer) {
do {
let message = try self.deserializer.deserialize(byteBuffer: bytes)
self.interceptors.receive(.message(message))
} catch {
self.handleError(error)
}
}
@inlinable
public func receiveEnd() {
self.interceptors.receive(.end)
}
@inlinable
public func receiveError(_ error: Error) {
self.handleError(error)
self.finish()
}
@inlinable
public func finish() {
switch self.state {
case .idle:
self.interceptors = nil
self.state = .completed
case let .createdContext(context),
let .invokedFunction(context):
context.statusPromise.fail(GRPCStatus(code: .unavailable, message: nil))
case .completed:
self.interceptors = nil
}
}
// MARK: - Interceptors to User Function
@inlinable
internal func receiveInterceptedPart(_ part: GRPCServerRequestPart<Request>) {
switch part {
case let .metadata(headers):
self.receiveInterceptedMetadata(headers)
case let .message(message):
self.receiveInterceptedMessage(message)
case .end:
self.receiveInterceptedEnd()
}
}
@inlinable
internal func receiveInterceptedMetadata(_ headers: HPACKHeaders) {
switch self.state {
case .idle:
// Make a context to invoke the observer block factory with.
let context = _StreamingResponseCallContext<Request, Response>(
eventLoop: self.context.eventLoop,
headers: headers,
logger: self.context.logger,
userInfoRef: self.userInfoRef,
compressionIsEnabled: self.context.encoding.isEnabled,
closeFuture: self.context.closeFuture,
sendResponse: self.interceptResponse(_:metadata:promise:)
)
// Move to the next state.
self.state = .createdContext(context)
// Register a callback on the status future.
context.statusPromise.futureResult.whenComplete(self.userFunctionCompletedWithResult(_:))
// Send response headers back via the interceptors.
self.interceptors.send(.metadata([:]), promise: nil)
case .createdContext, .invokedFunction:
self.handleError(GRPCError.InvalidState("Protocol violation: already received headers"))
case .completed:
// We may receive headers from the interceptor pipeline if we have already finished (i.e. due
// to an error or otherwise) and an interceptor doing some async work later emitting headers.
// Dropping them is fine.
()
}
}
@inlinable
internal func receiveInterceptedMessage(_ request: Request) {
switch self.state {
case .idle:
self.handleError(GRPCError.ProtocolViolation("Message received before headers"))
case let .createdContext(context):
self.state = .invokedFunction(context)
// Complete the status promise with the function outcome.
context.statusPromise.completeWith(self.userFunction(request, context))
case .invokedFunction:
let error = GRPCError.ProtocolViolation("Multiple messages received on server streaming RPC")
self.handleError(error)
case .completed:
// We received a message but we're already done: this may happen if we terminate the RPC
// due to a channel error, for example.
()
}
}
@inlinable
internal func receiveInterceptedEnd() {
switch self.state {
case .idle:
self.handleError(GRPCError.ProtocolViolation("End received before headers"))
case .createdContext:
self.handleError(GRPCError.ProtocolViolation("End received before message"))
case .invokedFunction, .completed:
()
}
}
// MARK: - User Function To Interceptors
@inlinable
internal func interceptResponse(
_ response: Response,
metadata: MessageMetadata,
promise: EventLoopPromise<Void>?
) {
switch self.state {
case .idle:
// The observer block can't send responses if it doesn't exist.
preconditionFailure()
case .createdContext, .invokedFunction:
// The user has access to the response context before returning a future observer,
// so 'createdContext' is valid here (if a little strange).
self.interceptors.send(.message(response, metadata), promise: promise)
case .completed:
promise?.fail(GRPCError.AlreadyComplete())
}
}
@inlinable
internal func userFunctionCompletedWithResult(_ result: Result<GRPCStatus, Error>) {
switch self.state {
case .idle:
// Invalid state: the user function can only completed if it was created.
preconditionFailure()
case let .createdContext(context),
let .invokedFunction(context):
switch result {
case let .success(status):
// We're sending end back, we're done.
self.state = .completed
self.interceptors.send(.end(status, context.trailers), promise: nil)
case let .failure(error):
self.handleError(error, thrownFromHandler: true)
}
case .completed:
// We've already completed. Ignore this.
()
}
}
@inlinable
internal func sendInterceptedPart(
_ part: GRPCServerResponsePart<Response>,
promise: EventLoopPromise<Void>?
) {
switch part {
case let .metadata(headers):
self.context.responseWriter.sendMetadata(headers, flush: true, promise: promise)
case let .message(message, metadata):
do {
let bytes = try self.serializer.serialize(message, allocator: self.context.allocator)
self.context.responseWriter.sendMessage(bytes, metadata: metadata, promise: promise)
} catch {
// Serialization failed: fail the promise and send end.
promise?.fail(error)
let (status, trailers) = ServerErrorProcessor.processLibraryError(
error,
delegate: self.context.errorDelegate
)
// Loop back via the interceptors.
self.interceptors.send(.end(status, trailers), promise: nil)
}
case let .end(status, trailers):
self.context.responseWriter.sendEnd(status: status, trailers: trailers, promise: promise)
}
}
@inlinable
internal func handleError(_ error: Error, thrownFromHandler isHandlerError: Bool = false) {
switch self.state {
case .idle:
assert(!isHandlerError)
self.state = .completed
// We don't have a promise to fail. Just send back end.
let (status, trailers) = ServerErrorProcessor.processLibraryError(
error,
delegate: self.context.errorDelegate
)
self.interceptors.send(.end(status, trailers), promise: nil)
case let .createdContext(context),
let .invokedFunction(context):
// We don't have a promise to fail. Just send back end.
self.state = .completed
let status: GRPCStatus
let trailers: HPACKHeaders
if isHandlerError {
(status, trailers) = ServerErrorProcessor.processObserverError(
error,
headers: context.headers,
trailers: context.trailers,
delegate: self.context.errorDelegate
)
} else {
(status, trailers) = ServerErrorProcessor.processLibraryError(
error,
delegate: self.context.errorDelegate
)
}
self.interceptors.send(.end(status, trailers), promise: nil)
// We're already in the 'completed' state so failing the promise will be a no-op in the
// callback to 'userFunctionCompletedWithResult' (but we also need to avoid leaking the
// promise.)
context.statusPromise.fail(error)
case .completed:
()
}
}
}
| 31.495726 | 100 | 0.695613 |
22fcafd3d1a32aea156c483fd4bb01d9b4399751 | 558 | //
// ProductsList.swift
// Stripe
//
// Created by Andrew Edwards on 8/22/17.
//
//
/**
Products List
https://stripe.com/docs/api/curl#list_products
*/
public struct ProductsList: List, StripeModel {
public var object: String?
public var hasMore: Bool?
public var totalCount: Int?
public var url: String?
public var data: [StripeProduct]?
public enum CodingKeys: CodingKey, String {
case object
case hasMore = "has_more"
case totalCount = "total_count"
case url
case data
}
}
| 19.241379 | 47 | 0.630824 |
4b4f1756a3cda7b44da654e4ffc3988e5e770510 | 6,600 | // Copyright 2016 The Tulsi Authors. 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 XCTest
@testable import TulsiGenerator
// Base class for end-to-end tests that generate xcodeproj bundles and validate them against golden
// versions.
class EndToEndIntegrationTestCase : BazelIntegrationTestCase {
enum Error: Swift.Error {
/// A subdirectory for the Xcode project could not be created.
case testSubdirectoryNotCreated
/// The Xcode project could not be generated.
case projectGenerationFailure(String)
}
let fakeBazelURL = URL(fileURLWithPath: "/fake/tulsi_test_bazel", isDirectory: false)
let testTulsiVersion = "9.99.999.9999"
final func validateDiff(_ diffLines: [String], file: StaticString = #file, line: UInt = #line) {
for diff in diffLines {
XCTFail(diff, file: file, line: line)
}
}
final func diffProjectAt(_ projectURL: URL,
againstGoldenProject resourceName: String,
file: StaticString = #file,
line: UInt = #line) -> [String] {
let bundle = Bundle(for: type(of: self))
guard let goldenProjectURL = bundle.url(forResource: resourceName,
withExtension: "xcodeproj",
subdirectory: "GoldenProjects") else {
assertionFailure("Missing required test resource file \(resourceName).xcodeproj")
XCTFail("Missing required test resource file \(resourceName).xcodeproj",
file: file,
line: line)
return []
}
var diffOutput = [String]()
let semaphore = DispatchSemaphore(value: 0)
let process = ProcessRunner.createProcess("/usr/bin/diff",
arguments: ["-rq",
// For the sake of simplicity in
// maintaining the golden data, copied
// Tulsi artifacts are assumed to have
// been installed correctly.
"--exclude=.tulsi",
projectURL.path,
goldenProjectURL.path]) {
completionInfo in
defer {
semaphore.signal()
}
if let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) {
diffOutput = stdout.components(separatedBy: "\n").filter({ !$0.isEmpty })
} else {
XCTFail("No output received for diff command", file: file, line: line)
}
}
process.currentDirectoryPath = workspaceRootURL.path
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return diffOutput
}
final func generateProjectNamed(_ projectName: String,
buildTargets: [RuleInfo],
pathFilters: [String],
additionalFilePaths: [String] = [],
outputDir: String,
options: TulsiOptionSet = TulsiOptionSet()) throws -> URL {
if !bazelStartupOptions.isEmpty {
options[.BazelBuildStartupOptionsDebug].projectValue =
bazelStartupOptions.joined(separator: " ")
}
let debugBuildOptions = ["--define=TULSI_TEST=dbg"] + bazelBuildOptions
let releaseBuildOptions = ["--define=TULSI_TEST=rel"] + bazelBuildOptions
options[.BazelBuildOptionsDebug].projectValue = debugBuildOptions.joined(separator: " ")
options[.BazelBuildOptionsRelease].projectValue = releaseBuildOptions.joined(separator: " ")
let bazelURLParam = TulsiParameter(value: fakeBazelURL, source: .explicitlyProvided)
let config = TulsiGeneratorConfig(projectName: projectName,
buildTargets: buildTargets,
pathFilters: Set<String>(pathFilters),
additionalFilePaths: additionalFilePaths,
options: options,
bazelURL: bazelURLParam)
guard let outputFolderURL = makeTestSubdirectory(outputDir) else {
throw Error.testSubdirectoryNotCreated
}
let projectGenerator = TulsiXcodeProjectGenerator(workspaceRootURL: workspaceRootURL,
config: config,
extractorBazelURL: bazelURL,
tulsiVersion: testTulsiVersion)
// Bazel built-in preprocessor defines are suppressed in order to prevent any
// environment-dependent variables from mismatching the golden data.
projectGenerator.xcodeProjectGenerator.suppressCompilerDefines = true
// Output directory generation is suppressed in order to prevent having to whitelist diffs of
// empty directories.
projectGenerator.xcodeProjectGenerator.suppressGeneratedArtifactFolderCreation = true
// The username is forced to a known value.
projectGenerator.xcodeProjectGenerator.usernameFetcher = { "_TEST_USER_" }
// The workspace symlink is forced to a known value.
projectGenerator.xcodeProjectGenerator.redactWorkspaceSymlink = true
let errorInfo: String
do {
return try projectGenerator.generateXcodeProjectInFolder(outputFolderURL)
} catch TulsiXcodeProjectGenerator.GeneratorError.unsupportedTargetType(let targetType) {
errorInfo = "Unsupported target type: \(targetType)"
} catch TulsiXcodeProjectGenerator.GeneratorError.serializationFailed(let details) {
errorInfo = "General failure: \(details)"
} catch let error {
errorInfo = "Unexpected failure: \(error)"
}
throw Error.projectGenerationFailure(errorInfo)
}
}
| 48.175182 | 104 | 0.60697 |
71361738408149911acc74c08ae1a39900fc0a24 | 1,701 | //
// AllDetailDiyButton.swift
// SwiftWallet
//
// Created by Avazu Holding on 2018/4/12.
// Copyright ยฉ 2018ๅนด DotC United Group. All rights reserved.
//
import UIKit
class AllDetailDiyButton: UIButton {
var isNeedShowMore = false
var isShowMore = false
override init(frame: CGRect) {
super.init(frame: frame)
self.setTitleColor(UIColor.init(hexColor: "356AF6"), for: .selected)
self.setTitleColor(UIColor.init(hexColor: "999999"), for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 10)
self.layer.cornerRadius = 4
self.layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// override func draw(_ rect: CGRect) {
// super.draw(rect)
//
//// let image:UIImage = UIImage.init(color: UIColor.init(hexColor: "356AF6"))!
//// let normalImage:UIImage = UIImage.init(color: UIColor.init(hexColor: "F2F2F2"))!
//// self.setBackgroundImage(image, for: .selected)
//// self.setBackgroundImage(image, for: .highlighted)
//// self.setBackgroundImage(normalImage, for: .normal)
// self.setTitleColor(UIColor.init(hexColor: "356AF6"), for: .selected)
// self.setTitleColor(UIColor.init(hexColor: "999999"), for: .normal)
//
// self.titleLabel?.font = UIFont.systemFont(ofSize: 10)
// self.layer.cornerRadius = 4
// self.layer.masksToBounds = true
// }
override var isSelected: Bool{
didSet {
self.titleLabel?.font = isSelected ? UIFont.boldSystemFont(ofSize: 10) : UIFont.systemFont(ofSize: 10)
}
}
}
| 30.927273 | 105 | 0.637272 |
01e63c76b90490b263d24184ad405a392ba3a2b9 | 2,902 | //
// MainAdapter.swift
// TextFieldsCatalog
//
// Created by ะะปะตะบัะฐะฝะดั ะงะฐััะพะฒ on 23/01/2019.
// Copyright ยฉ 2019 ะะปะตะบัะฐะฝะดั ะงะฐััะพะฒ. All rights reserved.
//
import UIKit
final class MainAdapter: NSObject {
// MARK: - Properties
var onScrolled: CGFloatClosure?
var onFieldTypeSelect: TextFieldTypeClosure?
// MARK: - Private Properties
private var items: [MainModuleViewModel]
private let tableView: UITableView
// MARK: - Initialization
init(tableView: UITableView, items: [MainModuleViewModel]) {
self.tableView = tableView
self.items = items
super.init()
configureTableView()
}
// MARK: - Internal Methods
}
// MARK: - Configure
private extension MainAdapter {
func configureTableView() {
registerCells()
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
func registerCells() {
tableView.registerNib(MainFieldTableViewCell.self)
tableView.registerNib(MainMessageTableViewCell.self)
}
}
// MARK: - UITableViewDelegate
extension MainAdapter: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = items[indexPath.row]
switch item {
case .field(let fieldType):
onFieldTypeSelect?(fieldType)
case .message(_):
break
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
onScrolled?(scrollView.contentOffset.y)
}
}
// MARK: - UITableViewDataSource
extension MainAdapter: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
switch item {
case .field(let fieldType):
return fieldCell(for: fieldType, indexPath: indexPath)
case .message(let message):
return messageCell(for: message, indexPath: indexPath)
}
}
}
// MARK: - Private Methods
private extension MainAdapter {
func fieldCell(for fieldType: TextFieldType, indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(MainFieldTableViewCell.self, indexPath: indexPath) else {
return UITableViewCell()
}
cell.configure(with: fieldType)
return cell
}
func messageCell(for message: String, indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(MainMessageTableViewCell.self, indexPath: indexPath) else {
return UITableViewCell()
}
cell.configure(with: message)
return cell
}
}
| 25.017241 | 114 | 0.664714 |
5d56310e609c6c1493b93d8f70d57271455a2fda | 2,742 | import Foundation
public enum HTTPMethod: String {
case GET
// other http methods are not required for the task
}
public protocol APIRequestorProtocol: AnyObject {
func dataTask(path: String,
method: HTTPMethod,
parameters: [String: String]?,
completion: @escaping (Result<Data, APIError>) -> Void) -> URLSessionDataTask?
}
public final class APIRequestor: APIRequestorProtocol {
private enum Constants {
static let basePath = "https://www.rijksmuseum.nl/api/"
}
fileprivate let apiKey: String
fileprivate let language: APIService.Language
init(apiKey: String, language: APIService.Language) {
self.apiKey = apiKey
self.language = language
}
public func dataTask(path: String,
method: HTTPMethod,
parameters: [String: String]?,
completion: @escaping (Result<Data, APIError>) -> Void) -> URLSessionDataTask? {
let urlString = Constants.basePath + language.rawValue + path + "/"
guard var components = URLComponents(string: urlString) else {
completion(Result.failure(APIError.invalidRequest))
return nil
}
var requestParameters: [String: String] = {
if let parameters = parameters {
return parameters
} else {
return [String: String]()
}
}()
requestParameters["key"] = apiKey
components.queryItems = requestParameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
guard let url = components.url else {
completion(Result.failure(APIError.invalidRequest))
return nil
}
let request = URLRequest(url: url)
let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if let error = error as NSError? {
switch error.code {
case -999:
completion(Result.failure(APIError.canceled))
case -1009:
completion(Result.failure(APIError.noInternet))
default:
completion(Result.failure(APIError.invalidResponse))
}
return
}
guard let data = data else {
completion(Result.failure(APIError.invalidResponse))
return
}
completion(Result.success(data))
}
return dataTask
}
}
| 31.517241 | 122 | 0.570751 |
0a198a90e2af87e2bcdcb2ab9c3eb32f17d89427 | 411 | //
// VGSShowBaseTestCase.swift
// VGSShowSDKTests
//
// Created on 22.02.2021.
//
import Foundation
import XCTest
@testable import VGSShowSDK
/// Base VGSShow test case for common setup.
class VGSShowBaseTestCase: XCTestCase {
/// Setup collect before tests.
override func setUp() {
super.setUp()
// Disable analytics in unit tests.
VGSAnalyticsClient.shared.shouldCollectAnalytics = false
}
}
| 17.869565 | 58 | 0.737226 |
8f1dd347b009e8c9f972daf4b004041b09475a20 | 585 | /*:
[Previous](@previous) [Next](@next)
# Model-view-controller (MVC)
- - - - - - - - - -

The model-view-controller (MVC) pattern separates objects into three types: models, views and controllers.
**Models** hold onto application data. They are usually structs or simple classes.
**Views** display visual elements and controls on screen. They are usually subclasses of `UIView`.
**Controllers** coordinate between models and views. They are usually subclasses of `UIViewController`.
## Code Example
*/
| 32.5 | 107 | 0.707692 |
5b53ffb050f5d248d14d9eca728a82933dcad0ca | 3,904 | //
// Corona-Warn-App
//
// SAP SE and all other contributors /
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import UIKit
class HomeRiskLevelCellConfigurator: HomeRiskCellConfigurator {
let identifier = UUID()
// MARK: Properties
var buttonAction: (() -> Void)?
var isLoading: Bool
var isButtonEnabled: Bool
var isButtonHidden: Bool
var isCounterLabelHidden: Bool
var startDate: Date?
var releaseDate: Date?
var lastUpdateDate: Date?
private let calendar = Calendar.current
private static let lastUpdateDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.doesRelativeDateFormatting = true
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
return dateFormatter
}()
var lastUpdateDateString: String {
if let lastUpdateDate = lastUpdateDate {
return Self.lastUpdateDateFormatter.string(from: lastUpdateDate)
} else {
return " - "
}
}
// MARK: Creating a Home Risk Cell Configurator
init(isLoading: Bool, isButtonEnabled: Bool, isButtonHidden: Bool, isCounterLabelHidden: Bool, startDate: Date?, releaseDate: Date?, lastUpdateDate: Date?) {
self.isLoading = isLoading
self.isButtonEnabled = isButtonEnabled
self.isButtonHidden = isButtonHidden
self.isCounterLabelHidden = isCounterLabelHidden
self.startDate = startDate
self.releaseDate = releaseDate
self.lastUpdateDate = lastUpdateDate
}
// MARK: Loading
func startLoading() {
isLoading = true
}
func stopLoading() {
isLoading = false
}
// MARK: Counter
func updateCounter(startDate: Date, releaseDate: Date) {
self.startDate = startDate
self.releaseDate = releaseDate
}
func removeCounter() {
startDate = nil
releaseDate = nil
}
// MARK: Button
func updateButtonEnabled(_ enabled: Bool) {
isButtonEnabled = enabled
}
func counterTouple() -> (minutes: Int, seconds: Int)? {
guard let startDate = startDate else { return nil }
guard let releaseDate = releaseDate else { return nil }
let dateComponents = calendar.dateComponents([.minute, .second], from: startDate, to: releaseDate)
guard let minutes = dateComponents.minute else { return nil }
guard let seconds = dateComponents.second else { return nil }
return (minutes: minutes, seconds: seconds)
}
func configureCounter(buttonTitle: String, cell: RiskLevelCollectionViewCell) {
if let (minutes, seconds) = counterTouple() {
let counterLabelText = String(format: AppStrings.Home.riskCardStatusCheckCounterLabel, minutes, seconds)
cell.configureCounterLabel(text: counterLabelText, isHidden: isCounterLabelHidden)
let formattedTime = String(format: "(%02u:%02u)", minutes, seconds)
let updateButtonText = "\(buttonTitle) \(formattedTime)"
cell.configureUpdateButton(
title: updateButtonText,
isEnabled: isButtonEnabled,
isHidden: isButtonHidden
)
} else {
cell.configureCounterLabel(text: "", isHidden: isCounterLabelHidden)
cell.configureUpdateButton(
title: buttonTitle,
isEnabled: isButtonEnabled,
isHidden: isButtonHidden
)
}
}
// MARK: Configuration
func configure(cell _: RiskLevelCollectionViewCell) {
fatalError("implement this method in children")
}
}
extension HomeRiskLevelCellConfigurator: RiskLevelCollectionViewCellDelegate {
func updateButtonTapped(cell _: RiskLevelCollectionViewCell) {
buttonAction?()
}
}
| 28.086331 | 158 | 0.747695 |
f8746fb6d0f7d116418b81f5b38d027166cd9003 | 7,116 | import Foundation
public struct TargetAction: Codable {
/// Order when the action gets executed.
///
/// - pre: Before the sources and resources build phase.
/// - post: After the sources and resources build phase.
enum Order: String, Codable {
case pre
case post
}
/// Name of the build phase when the project gets generated.
private let name: String
/// Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
private let tool: String?
/// Path to the script to execute.
private let path: String?
/// Target action order.
private let order: Order
/// Arguments that to be passed.
private let arguments: [String]
public enum CodingKeys: String, CodingKey {
case name
case tool
case path
case order
case arguments
}
/// Initializes the target action with its attributes.
///
/// - Parameters:
/// - name: Name of the build phase when the project gets generated.
/// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
/// - path: Path to the script to execute.
/// - order: Target action order.
/// - arguments: Arguments that to be passed.
init(name: String, tool: String?, path: String?, order: Order, arguments: [String]) {
self.name = name
self.path = path
self.tool = tool
self.order = order
self.arguments = arguments
}
/// Returns a target action that gets executed before the sources and resources build phase.
///
/// - Parameters:
/// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func pre(tool: String, arguments: String..., name: String) -> TargetAction {
return TargetAction(name: name, tool: tool, path: nil, order: .pre, arguments: arguments)
}
/// Returns a target action that gets executed before the sources and resources build phase.
///
/// - Parameters:
/// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func pre(tool: String, arguments: [String], name: String) -> TargetAction {
return TargetAction(name: name, tool: tool, path: nil, order: .pre, arguments: arguments)
}
/// Returns a target action that gets executed before the sources and resources build phase.
///
/// - Parameters:
/// - path: Path to the script to execute.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func pre(path: String, arguments: String..., name: String) -> TargetAction {
return TargetAction(name: name, tool: nil, path: path, order: .pre, arguments: arguments)
}
/// Returns a target action that gets executed before the sources and resources build phase.
///
/// - Parameters:
/// - path: Path to the script to execute.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func pre(path: String, arguments: [String], name: String) -> TargetAction {
return TargetAction(name: name, tool: nil, path: path, order: .pre, arguments: arguments)
}
/// Returns a target action that gets executed after the sources and resources build phase.
///
/// - Parameters:
/// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func post(tool: String, arguments: String..., name: String) -> TargetAction {
return TargetAction(name: name, tool: tool, path: nil, order: .post, arguments: arguments)
}
/// Returns a target action that gets executed after the sources and resources build phase.
///
/// - Parameters:
/// - tool: Name of the tool to execute. Tuist will look up the tool on the environment's PATH.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func post(tool: String, arguments: [String], name: String) -> TargetAction {
return TargetAction(name: name, tool: tool, path: nil, order: .post, arguments: arguments)
}
/// Returns a target action that gets executed after the sources and resources build phase.
///
/// - Parameters:
/// - path: Path to the script to execute.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func post(path: String, arguments: String..., name: String) -> TargetAction {
return TargetAction(name: name, tool: nil, path: path, order: .post, arguments: arguments)
}
/// Returns a target action that gets executed after the sources and resources build phase.
///
/// - Parameters:
/// - path: Path to the script to execute.
/// - arguments: Arguments that to be passed.
/// - name: Name of the build phase when the project gets generated.
/// - Returns: Target action.
public static func post(path: String, arguments: [String], name: String) -> TargetAction {
return TargetAction(name: name, tool: nil, path: path, order: .post, arguments: arguments)
}
// MARK: - Codable
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
order = try container.decode(Order.self, forKey: .order)
arguments = try container.decode([String].self, forKey: .arguments)
if let path = try container.decodeIfPresent(String.self, forKey: .path) {
self.path = path
tool = nil
} else {
path = nil
tool = try container.decode(String.self, forKey: .tool)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(order, forKey: .order)
try container.encode(arguments, forKey: .arguments)
if let tool = tool {
try container.encode(tool, forKey: .tool)
}
if let path = path {
try container.encode(path, forKey: .path)
}
}
}
| 41.614035 | 101 | 0.635891 |
ab04e869ff7c06862ab0a606a275fded7c6d491d | 1,138 | //
// Xcore
// Copyright ยฉ 2021 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
public struct LoadingSwitchToggleStyle: ToggleStyle {
public init() {}
public func makeBody(configuration: Self.Configuration) -> some View {
EnvironmentReader(\.isLoading) { isLoading in
HStack {
configuration.label
Spacer()
if isLoading {
ProgressView()
// 50 points is the width of Switch control.
// Width is set to 50 to avoid content shifting when changing state between
// loading.
.frame(width: 50, alignment: .trailing)
} else {
Toggle(isOn: configuration.$isOn) {
EmptyView()
}
.labelsHidden()
}
}
.animation(.default, value: isLoading)
}
}
}
// MARK: - Dot Syntax Support
extension ToggleStyle where Self == LoadingSwitchToggleStyle {
public static var loadingSwitch: Self { .init() }
}
| 27.095238 | 95 | 0.52109 |
648bad034bee1a74f57f8133e1a828393cdc800a | 18,936 | //
// Poly+AllTypesTests.swift
//
//
// Created by Mathew Polzin on 3/5/20.
//
import XCTest
import Poly
final class PolyAllTypesTests: XCTestCase {
func test_poly0() {
XCTAssertTrue(Poly0.allTypes.isEmpty)
}
func test_poly1() {
XCTAssert(Poly1<TestType1>.allTypes[0] == TestType1.self)
}
func test_poly2() {
XCTAssert(Poly2<TestType1, TestType2>.allTypes[0] == TestType1.self)
XCTAssert(Poly2<TestType1, TestType2>.allTypes[1] == TestType2.self)
}
func test_poly3() {
XCTAssert(Poly3<TestType1, TestType2, TestType3>.allTypes[0] == TestType1.self)
XCTAssert(Poly3<TestType1, TestType2, TestType3>.allTypes[1] == TestType2.self)
XCTAssert(Poly3<TestType1, TestType2, TestType3>.allTypes[2] == TestType3.self)
}
func test_poly4() {
XCTAssert(Poly4<TestType1, TestType2, TestType3, TestType4>.allTypes[0] == TestType1.self)
XCTAssert(Poly4<TestType1, TestType2, TestType3, TestType4>.allTypes[1] == TestType2.self)
XCTAssert(Poly4<TestType1, TestType2, TestType3, TestType4>.allTypes[2] == TestType3.self)
XCTAssert(Poly4<TestType1, TestType2, TestType3, TestType4>.allTypes[3] == TestType4.self)
}
func test_poly5() {
XCTAssert(Poly5<TestType1, TestType2, TestType3, TestType4, TestType5>.allTypes[0] == TestType1.self)
XCTAssert(Poly5<TestType1, TestType2, TestType3, TestType4, TestType5>.allTypes[1] == TestType2.self)
XCTAssert(Poly5<TestType1, TestType2, TestType3, TestType4, TestType5>.allTypes[2] == TestType3.self)
XCTAssert(Poly5<TestType1, TestType2, TestType3, TestType4, TestType5>.allTypes[3] == TestType4.self)
XCTAssert(Poly5<TestType1, TestType2, TestType3, TestType4, TestType5>.allTypes[4] == TestType5.self)
}
func test_poly6() {
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[0] == TestType1.self)
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[1] == TestType2.self)
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[2] == TestType3.self)
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[3] == TestType4.self)
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[4] == TestType5.self)
XCTAssert(Poly6<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6>.allTypes[5] == TestType6.self)
}
func test_poly7() {
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[0] == TestType1.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[1] == TestType2.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[2] == TestType3.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[3] == TestType4.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[4] == TestType5.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[5] == TestType6.self)
XCTAssert(Poly7<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7>.allTypes[6] == TestType7.self)
}
func test_poly8() {
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[0] == TestType1.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[1] == TestType2.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[2] == TestType3.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[3] == TestType4.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[4] == TestType5.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[5] == TestType6.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[6] == TestType7.self)
XCTAssert(Poly8<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8>.allTypes[7] == TestType8.self)
}
func test_poly9() {
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[0] == TestType1.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[1] == TestType2.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[2] == TestType3.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[3] == TestType4.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[4] == TestType5.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[5] == TestType6.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[6] == TestType7.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[7] == TestType8.self)
XCTAssert(Poly9<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9>.allTypes[8] == TestType9.self)
}
func test_poly10() {
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[0] == TestType1.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[1] == TestType2.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[2] == TestType3.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[3] == TestType4.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[4] == TestType5.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[5] == TestType6.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[6] == TestType7.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[7] == TestType8.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[8] == TestType9.self)
XCTAssert(Poly10<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10>.allTypes[9] == TestType10.self)
}
func test_poly11() {
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[0] == TestType1.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[1] == TestType2.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[2] == TestType3.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[3] == TestType4.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[4] == TestType5.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[5] == TestType6.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[6] == TestType7.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[7] == TestType8.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[8] == TestType9.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[9] == TestType10.self)
XCTAssert(Poly11<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11>.allTypes[10] == TestType11.self)
}
func test_poly12() {
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[0] == TestType1.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[1] == TestType2.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[2] == TestType3.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[3] == TestType4.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[4] == TestType5.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[5] == TestType6.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[6] == TestType7.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[7] == TestType8.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[8] == TestType9.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[9] == TestType10.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[10] == TestType11.self)
XCTAssert(Poly12<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12>.allTypes[11] == TestType12.self)
}
func test_poly13() {
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[0] == TestType1.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[1] == TestType2.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[2] == TestType3.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[3] == TestType4.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[4] == TestType5.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[5] == TestType6.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[6] == TestType7.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[7] == TestType8.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[8] == TestType9.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[9] == TestType10.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[10] == TestType11.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[11] == TestType12.self)
XCTAssert(Poly13<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13>.allTypes[12] == TestType13.self)
}
func test_poly14() {
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[0] == TestType1.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[1] == TestType2.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[2] == TestType3.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[3] == TestType4.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[4] == TestType5.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[5] == TestType6.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[6] == TestType7.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[7] == TestType8.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[8] == TestType9.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[9] == TestType10.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[10] == TestType11.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[11] == TestType12.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[12] == TestType13.self)
XCTAssert(Poly14<TestType1, TestType2, TestType3, TestType4, TestType5, TestType6, TestType7, TestType8, TestType9, TestType10, TestType11, TestType12, TestType13, TestType14>.allTypes[13] == TestType14.self)
}
}
// MARK: - Test types
extension PolyAllTypesTests {
struct TestType1: Codable, Equatable {
let a: Int
}
struct TestType2: Codable, Equatable {
let b: Int
}
struct TestType3: Codable, Equatable {
let c: Int
}
struct TestType4: Codable, Equatable {
let d: Int
}
struct TestType5: Codable, Equatable {
let e: Int
}
struct TestType6: Codable, Equatable {
let f: Int
}
struct TestType7: Codable, Equatable {
let g: Int
}
struct TestType8: Codable, Equatable {
let h: Int
}
struct TestType9: Codable, Equatable {
let i: Int
}
struct TestType10: Codable, Equatable {
let j: Int
}
struct TestType11: Codable, Equatable {
let k: Int
}
struct TestType12: Codable, Equatable {
let l: Int
}
struct TestType13: Codable, Equatable {
let m: Int
}
struct TestType14: Codable, Equatable {
let n: Int
}
}
| 85.297297 | 216 | 0.745775 |
670c9626f96f152636f9a206fa94151ed5043952 | 2,879 | //
// JMSeatchMainCell.swift
// SReader
//
// Created by JunMing on 2021/8/10.
//
import UIKit
class JMSeatchMainCell: SRComp_BaseCell {
private var cover = SRImageView()
private var title = UILabel()
private var author = UILabel()
private var indexL = UILabel()
private var tagL = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.white
contentView.addSubview(cover)
contentView.addSubview(title)
contentView.addSubview(author)
contentView.addSubview(indexL)
contentView.addSubview(tagL)
tagL.text = "็ญ"
tagL.layer.cornerRadius = 2
tagL.layer.masksToBounds = true
tagL.backgroundColor = UIColor.baseRed
tagL.jmConfigLabel(alig: .center, font: UIFont.jmMedium(10.round), color: UIColor.white)
title.jmConfigLabel(font: UIFont.jmMedium(15.round), color: UIColor.black)
author.jmConfigLabel(font: UIFont.jmRegular(13.round))
indexL.jmConfigLabel(alig: .center, font: UIFont.jmMedium(15.round))
layoutViews()
}
// ๅทๆฐๆฐๆฎ
func refresh(model: SRBook, index: Int) {
title.text = model.title
author.text = model.author
indexL.text = "\(index)"
cover.setImage(url: model.coverurl())
tagL.isHidden = index > 3
}
private func layoutViews() {
indexL.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(10.round)
make.centerY.equalTo(contentView.snp.centerY)
make.height.equalTo(40.round)
make.width.equalTo(20.round)
}
cover.snp.makeConstraints { (make) in
make.left.equalTo(indexL.snp.right).offset(10.round)
make.width.equalTo(34.round)
make.top.equalTo(contentView).offset(10.round)
make.bottom.equalTo(contentView).offset(-10.round)
}
title.snp.makeConstraints { (make) in
make.left.equalTo(cover.snp.right).offset(10.round)
make.top.equalTo(cover.snp.top)
make.right.equalTo(contentView.snp.right).offset(-40.round)
make.height.equalTo(20.round)
}
author.snp.makeConstraints { (make) in
make.left.equalTo(title)
make.top.equalTo(title.snp.bottom).offset(5.round)
make.height.equalTo(20.round)
}
tagL.snp.makeConstraints { (make) in
make.right.equalTo(self).offset(-20.round)
make.centerY.equalTo(self.snp.centerY)
make.height.width.equalTo(16.round)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError(" implemented")
}
}
| 32.715909 | 96 | 0.609587 |
e45d7d9879cd42d8308c3f1b5eef8870b93c8813 | 450 | //
// ProfileProducer.swift
// Radishing
//
// Created by Nathaniel Dillinger on 4/25/18.
// Copyright ยฉ 2018 Nathaniel Dillinger. All rights reserved.
//
import Foundation
enum ProfileProducer: AuthProducerSetupable {
static var authenticator: Authenticatable.Type?
static var presenter: Presentable.Type?
static func fetchWork(_ work: Work) {
self.authenticator = CurrentServices.authenticator
}
}
| 20.454545 | 62 | 0.697778 |
62c203774cb3eb2f1a9ad9f1907f1e1a2f7aae42 | 432 | //
// Paginable.swift
// NetworkInfrastructure
//
// Created by Alonso on 11/10/19.
// Copyright ยฉ 2019 Alonso. All rights reserved.
//
protocol Paginable {
var currentPage: Int { get set }
var totalPages: Int { get set }
}
extension Paginable {
var hasMorePages: Bool {
return currentPage < totalPages
}
var nextPage: Int {
return hasMorePages ? currentPage + 1 : currentPage
}
}
| 16 | 59 | 0.636574 |
dd5e823b8c503acf51532fed02e50ef04dd24700 | 538 | //
// ShopItemPresenter.swift
// Castles
//
// Created by Tomas Trujillo on 2021-01-12.
//
import UIKit
final class ShopItemPresenter {
func viewModel(for shopItem: ShopItem) -> ShopItemViewModel {
return shopItem.wrappedItem.accept(visitor: self, data: shopItem)
}
}
extension ShopItemPresenter: ItemVisitor {
func visit(castleItem: CastleItem, data shopItem: ShopItem) -> ShopItemViewModel {
let castlePresenter = CastleItemPresenter()
return castlePresenter.viewModel(for: castleItem, shopItem: shopItem)
}
}
| 24.454545 | 84 | 0.745353 |
90fced355f7cc2abe54f3a7f96d49984a4d5292f | 774 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -target x86_64-apple-macosx10.50 -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -target x86_64-apple-macosx10.50 -dump-ast > %t.ast
// RUN: %FileCheck %s < %t.ast
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
import Foundation
// Nested classes that aren't available in our deployment target.
@available(OSX 10.51, *)
class CodingI : NSObject, NSCoding {
required init(coder: NSCoder) { }
func encode(coder: NSCoder) { }
}
@available(OSX 10.51, *)
class OuterCodingJ {
// CHECK-NOT: class_decl{{.*}}"NestedJ"{{.*}}@_staticInitializeObjCMetadata
class NestedJ : CodingI { }
}
| 33.652174 | 162 | 0.713178 |
fb9caf5aa48a1a60b1b0f93bda31c4527f754e4f | 3,713 | //
// AlamoVC.swift
// Login_Photo_Server
//
// Created by photypeta-junha on 2021/08/27.
//
import Foundation
import UIKit
import Alamofire
class AlamoVC: UIViewController {
// let url = "https://ptsv2.com/t/nppsl-1630637392/post"
// let url = "https://httpbin.org/post"
let url = "http://127.0.0.1:8000/auth/signup"
let image1 = UIImage(named: "NaverLogo")
let image2 = UIImage(named: "ip")
// let headers: HTTPHeaders = ["Content-type": "multipart/form-data", "Content-Disposition" : "form-data"]
override func viewDidLoad() {
super.viewDidLoad()
// getTest()
postTest()
// uploadPhoto(media: image2!, params: ["1": "2"], fileName: "df")
// upload1()
}
/*method ์ ์ด๋ค ํต์ ๋ฐฉ์ ์ฌ์ฉํ ๊ฑด์ง ๋ฃ๊ณ
parameters ๋ ๋ฐ์์ post ํต์ ํ ๋ ๋ณด๋ด๋ณผ๊ฑฐ๊ณ ์
encoding ์ URL ์ด๋๊น URLEncoding ์ ์ด์ฃผ์๊ณ ์
headers ๋ json ํ์์ผ๋ก ๋ฐ๊ฒ๋ ์จ์ค๋๋ค.
validate ๋ ํ์ธ ์ฝ๋์
๋๋ค.
responseJSON ์ด ์ ๋ณด๋ฅผ ๋ฐ๋ ๋ถ๋ถ์
๋๋ค.*/
func getTest() {
AF.request(url,
//์ด๋ค ๋ฐฉ์์ผ๋ก ํต์ ์ ํ๋
method: .get,
parameters: nil,
//url์ด๋๊น urlencoging
encoding: URLEncoding.default,
//jsonํ์์ผ๋ก ๋ฐ๊ฒ๋
headers: ["Content-Type":"application/json", "Accept":"application/json"])
//ํ์ธ ์ฝ๋ ์ ๋ณด ๋ฐ๋ ๋ถ๋ถ
.validate(statusCode: 200..<300).responseJSON { (json) in
//๊ฐ์ ธ์จ ๋ฐ์ดํฐ ํ์ฉ
print("AlamoVC")
print(json)
print("AlamoVC")
}
}
func postTest() {
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10
//POST๋ก ๋ณด๋ผ ์ ๋ณด
let params = ["id": "์์ด๋", "pw": "ํจ์ค์๋"] as Dictionary
// httpBody ์ parameters ์ถ๊ฐ
do {
try request.httpBody = JSONSerialization.data(withJSONObject: params, options: [])
} catch {
print("http Body Error")
}
AF.request(request).responseString { (response) in
switch response.result {
case .success:
print("์ฑ๊ณต")
case .failure:
print("error")
}
}
}
func uploadPhoto(media: UIImage,params: [String:String],fileName: String){
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(media.jpegData(
compressionQuality: 1)!,
withName: "1",
fileName: "\(fileName).jpeg", mimeType: "image/jpeg"
)
for param in params {
let value = param.value.data(using: String.Encoding.utf8)!
multipartFormData.append(value, withName: param.key)
}
},
to: url,
method: .post ,
headers: headers
)
.response { response in
print(response)
}
}
// func upload1() {
// let headers: HTTPHeaders = ["Content-type": "multipart/form-data"]
//
// AF.upload(multipartFormData: { (multipartFormData) in
// multipartFormData.append(Data("photo".utf8), withName: "iphonePhoto")
// multipartFormData.append(self.image2!.jpegData(compressionQuality: 1)!, withName: "iphone", fileName: "ip", mimeType: "image/jpeg")
// }, to: url,
// headers: headers)
// }
}
| 33.151786 | 145 | 0.526528 |
48df2307f90bc178f766c2a9ad5053ccd86fc5e5 | 2,717 | //
// PageControllerTests.swift
// PageControllerTests
//
// Created by Hirohisa Kawasaki on 6/24/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
import XCTest
import PageController
class PageControllerTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testReloadPages() {
var result: [UIViewController]!
var valid: [UIViewController]!
let pageController = PageController()
pageController.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
let viewControllers = [
UIViewController(),
UIViewController(),
UIViewController(),
UIViewController(),
]
pageController.viewControllers = viewControllers
pageController.loadView()
XCTAssertNotEqual(pageController.view.frame, CGRect.zero)
result = pageController.childViewControllerOrderedByX(true)
valid = [
viewControllers[3],
viewControllers[0],
viewControllers[1],
]
XCTAssertEqual(result, valid)
pageController.reloadPages(at: 0)
result = pageController.childViewControllerOrderedByX(true)
valid = [
viewControllers[3],
viewControllers[0],
viewControllers[1],
]
XCTAssertEqual(result, valid)
XCTAssertEqual(result[0].view.frame.origin.x, 0)
XCTAssertEqual(result[1].view.frame.origin.x, pageController.view.frame.width)
XCTAssertEqual(result[2].view.frame.origin.x, pageController.view.frame.width * 2)
pageController.reloadPages(at: 1)
result = pageController.childViewControllerOrderedByX(true)
valid = [
viewControllers[0],
viewControllers[1],
viewControllers[2],
]
XCTAssertEqual(result, valid)
XCTAssertEqual(result[0].view.frame.origin.x, 0)
XCTAssertEqual(result[1].view.frame.origin.x, pageController.view.frame.width)
XCTAssertEqual(result[2].view.frame.origin.x, pageController.view.frame.width * 2)
pageController.reloadPages(at: 3)
result = pageController.childViewControllerOrderedByX(true)
valid = [
viewControllers[2],
viewControllers[3],
viewControllers[0],
]
XCTAssertEqual(result, valid)
XCTAssertEqual(result[0].view.frame.origin.x, 0)
XCTAssertEqual(result[1].view.frame.origin.x, pageController.view.frame.width)
XCTAssertEqual(result[2].view.frame.origin.x, pageController.view.frame.width * 2)
}
}
| 29.215054 | 90 | 0.633419 |
d6282dc6ce1f5503e8cc71f6444f128c93ffaa95 | 3,445 | //
// SettingViewController.swift
// JSONConverter
//
// Created by DevYao on 2020/8/28.
// Copyright ยฉ 2020 Yao. All rights reserved.
//
import Cocoa
class SettingViewController: NSViewController {
@IBOutlet weak var prefixKeyLab: NSTextField!
@IBOutlet weak var prefixField: NSTextField!
@IBOutlet weak var rootClassKeyLab: NSTextField!
@IBOutlet weak var rootClassField: NSTextField!
@IBOutlet weak var parentClassKeyLab: NSTextField!
@IBOutlet weak var parentClassField: NSTextField!
@IBOutlet weak var customHeaderKeyLab: NSTextField!
@IBOutlet weak var customHeaderSwitch: NSSwitch!
@IBOutlet weak var headerKeyLab: NSTextField!
@IBOutlet weak var headerField: NSTextField!
@IBOutlet weak var autoHumpKeyLab: NSTextField!
@IBOutlet weak var autoHumpSwitch: NSSwitch!
@IBOutlet weak var saveBtn: NSButton!
var fileConfigChangedClosure:(() -> ())?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
updateCacheConfigUI()
}
private func setupUI() {
title = "parameter_setting_title".localized
prefixKeyLab.stringValue = "parameter_classes_prefix".localized
rootClassKeyLab.stringValue = "parameter_root_class_title".localized
parentClassKeyLab.stringValue = "parameter_parent_class_title".localized
customHeaderKeyLab.stringValue = "parameter_custom_file_header_title".localized
autoHumpKeyLab.stringValue = "parameter_auto_case_underline_hump".localized
headerKeyLab.stringValue = "parameter_file_header_title".localized
saveBtn.title = "parameter_save_title".localized
headerField.textColor = NSColor.hexInt(hex: 0x3ab54a)
headerField.font = NSFont(name: "Menlo", size: 14)!
}
private func updateCacheConfigUI() {
let configFile = FileConfigBuilder.shared.currentConfigFile()
prefixField.stringValue = configFile.prefix ?? ""
rootClassField.stringValue = configFile.rootName
parentClassField.stringValue = configFile.parentName ?? ""
autoHumpSwitch.state = configFile.autoCaseUnderline ? .on : .off
customHeaderSwitch.state = configFile.isCustomHeader ? .on : .off
headerField.isEditable = customHeaderSwitch.state == .on
headerField.stringValue = configFile.header ?? ""
}
@IBAction func saveConfigAction(_ sender: NSButton) {
let configFile = FileConfigBuilder.shared.currentConfigFile()
configFile.prefix = prefixField.stringValue
configFile.rootName = rootClassField.stringValue
configFile.parentName = parentClassField.stringValue
configFile.header = headerField.stringValue
configFile.isCustomHeader = customHeaderSwitch.state.rawValue == 1
configFile.autoCaseUnderline = autoHumpSwitch.state.rawValue == 1
FileConfigBuilder.shared.updateConfigWithFile(configFile)
fileConfigChangedClosure?()
dismiss(nil)
}
@IBAction func customFileHeaderSwitch(_ sender: NSSwitch) {
let configFile = FileConfigBuilder.shared.currentConfigFile()
configFile.isCustomHeader = customHeaderSwitch.state.rawValue == 1
configFile.autoCaseUnderline = autoHumpSwitch.state.rawValue == 1
FileConfigBuilder.shared.updateConfigWithFile(configFile)
updateCacheConfigUI()
}
}
| 39.147727 | 87 | 0.710885 |
386d430f8dbf17fa8a79a26103ecf37aae823bc8 | 847 | //
// Models.swift
// InfinityNote
//
// Created by Diego Bustamante on 2/12/18.
// Copyright ยฉ 2018 Diego Bustamante. All rights reserved.
//
import Foundation
import UIKit
import Firebase
// Locks view orientation
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
/// OPTIONAL Added method to adjust lock and rotate to the desired orientation
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
| 27.322581 | 130 | 0.704841 |
d6d023b1e9f3665c1bbb073e850ce532afe9e222 | 2,348 | //
// Iconset.swift
// Iconset
//
// Created by Aarnav Tale on 11/11/21.
// Copyright (c) 2021 Aerum LLC. All rights reserved.
//
import Chalk
import Foundation
import ArgumentParser
@available(macOS 10.15.4, *)
struct Iconset: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A nifty command line tool to manage macOS icons",
subcommands: [Iconset.Folder.self, Iconset.Single.self, Iconset.Revert.self]
)
struct Options: ParsableArguments {
@Option(name: .shortAndLong, help: "The path to the applications to theme")
var applicationsPath = "/Applications"
}
public static func purge(passphrase: Data? = nil) throws {
var password = passphrase
if password == nil {
// All of these operations require sudo so let's store the password first if it's not already passed in
// We can't use getpass() because it doesn't support passwords longer than 128 chars
var buffer = [CChar](repeating: 0, count: 8192) // This size is overkill but better safe than sorry
guard let passphrase = readpassphrase(Log.prompt("Password (required to purge cache): "), &buffer, buffer.count, RPP_ECHO_OFF) else {
print("No password supplied")
throw ExitCode.failure
}
password = (String(cString: passphrase) + "\n").data(using: .utf8)
}
let sudo = Process()
let input = Pipe()
sudo.standardInput = input
sudo.standardOutput = nil
sudo.standardError = nil
sudo.executableURL = URL(fileURLWithPath: "/usr/bin/sudo")
sudo.arguments = [
"-S",
"/bin/rm", "-rf",
"/Library/Caches/com.apple.iconservices.store"
]
sudo.launch() // This is deprecated, but the replacement run() doesn't wait for us to pass input
try input.fileHandleForWriting.write(contentsOf: password!)
try input.fileHandleForWriting.close()
sudo.waitUntilExit()
guard sudo.terminationStatus == 0 else {
Log.error("Failed to purge icon cache")
throw ExitCode.failure
}
let task = Process()
task.standardOutput = nil
task.launchPath = "/usr/bin/killall"
task.arguments = ["Dock"]
try task.run()
task.waitUntilExit()
guard task.terminationStatus == 0 else {
Log.error("Failed to restart Dock")
throw ExitCode.failure
}
Log.info("Cache purged successfully. \(ck.dim.on("New icons may not show till the Application is launched"))")
}
}
| 30.102564 | 136 | 0.7023 |
de92326f54422c7dd234f0a5e9a9fd3f85e052cb | 580 | //
// GameModel.swift
// CherryBombSweeper
//
// Created by Duy Nguyen on 1/10/18.
// Copyright ยฉ 2018 Duy.Ninja. All rights reserved.
//
import Foundation
enum GameState {
case new
case loaded
case inProgress
case paused
case lost
case win
}
class Game {
var mineField: MineField
var state: GameState = .new
var minesRemaining: Int
var flaggedCellIndices: Set<Int> = []
init(mineField: MineField = MineField()) {
self.mineField = mineField
self.minesRemaining = mineField.bombCellIndices.count
}
}
| 18.125 | 61 | 0.648276 |
e09f9c94ea7e764f26279b3b457ecb8b4ee6e0e1 | 1,974 | //
// ProjectTests.swift
// Sonar
//
// Created by NHSX on 01/04/2020.
// Copyright ยฉ 2020 NHSX. All rights reserved.
//
import XCTest
class ProjectTests: XCTestCase {
func testWeHaveALaunchStoryboard() {
let info = Bundle.app.infoDictionary
XCTAssertNotNil(info?["UILaunchStoryboardName"])
}
func testThereAreNoOverridesForATS() {
let info = Bundle.app.infoDictionary
XCTAssertNil(info?["NSAppTransportSecurity"], "There should be no overrides for App Transport Security.")
}
#if targetEnvironment(simulator)
func testThatProjectFileHasNoEmbeddedBuildConfigurations() {
guard let projectFilePath = Bundle(for: ProjectTests.self).infoDictionary?["projectFilePath"] as? String else {
XCTFail("The project file path should be specified in the info.plist file.")
return
}
let url = URL(fileURLWithPath: "\(projectFilePath)/project.pbxproj")
guard let project = try? String(contentsOf: url) else {
XCTFail("Failed to read project file. Maybe path is incorrect or we donโt have permission.")
return
}
if let range = project.range(of: "buildSettings\\s*=\\s*\\{[^\\}]*?=[^\\}]*?\\}", options: .regularExpression) {
let buildSettings = project[range]
.replacingOccurrences(of: "\n", with: " ")
XCTFail("There should be no build settings in the project file. Please move all settings to .xcconfig files. Found: \(buildSettings)")
}
}
#endif
}
private extension Bundle {
// An alias to indicate that we should running as part of the main app in order for these tests to function
// properly.
// Some tests failing (like `testWeHaveAStoryboard`) helps detect if weโve moved this class to, say, a framework
// or swift pacakge tests.
static var app: Bundle { Bundle.main }
}
| 34.034483 | 146 | 0.635258 |
dd2cc4329f20007fbe71cf43b55ee6f23203eaf3 | 6,858 | //
// Repository+Preview.swift
// MusicshotCore
//
// Created by ๆ้ไน on 2018/03/28.
// Copyright ยฉ 2018ๅนด ๆ้ไน. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
import RxCocoa
private let diskCache = DiskCacheImpl()
extension Repository {
final class Preview {
enum Error: Swift.Error {
case unknownState
}
private let id: Entity.Song.Identifier
convenience init(song: Entity.Song) {
self.init(id: song.id)
}
init(id: Entity.Song.Identifier) {
self.id = id
}
func fetch() -> Single<(URL, Int)> {
enum State {
case cache(URL, Int)
case download(Int, URL, Entity.Song.Ref)
}
let id = self.id
func getState() throws -> State {
let realm = try Realm()
let song = realm.object(ofType: Entity.Song.self, forPrimaryKey: id)
switch (song, song?.preview) {
case (nil, _):
throw Error.unknownState
case (_?, let preview?):
if let url = preview.localURL, diskCache.exists(url) {
return .cache(url, preview.duration)
} else {
return .cache(preview.remoteURL, preview.duration)
}
case (let song?, _):
guard let id = Int(id.rawValue) else { throw Error.unknownState }
return .download(id, song.url, song.ref)
}
}
do {
switch try getState() {
case .cache(let args):
return .just(args)
case .download(let id, let url, let ref):
return NetworkSession.shared.rx.send(GetPreviewURL(id: id, url: url))
.do(onSuccess: { url, duration in
let realm = try Realm()
guard let song = realm.resolve(ref) else { return }
try realm.write {
realm.add(Entity.Preview(song: song, url: url, duration: duration), update: true)
}
})
.subscribeOn(SerialDispatchQueueScheduler(qos: .background))
}
} catch {
return .error(error)
}
}
func download() -> Single<Void> {
enum State {
case notReady, onlyRemote(URL), downloaded
}
let id = self.id
return Single<State>
.just {
let realm = try Realm()
let preview = realm.object(ofType: Entity.Preview.self, forPrimaryKey: id)
if let url = preview?.localURL, diskCache.exists(url) {
return .downloaded
}
if let url = preview?.remoteURL {
return .onlyRemote(url)
}
return .notReady
}
.flatMap { state -> Single<Void> in
switch state {
case .notReady, .downloaded:
return .just(())
case .onlyRemote(let url):
return URLSession.shared.rx.download(with: url)
.map { src in
guard let src = src else { return }
let filename = url.lastPathComponent
let realm = try Realm()
guard let preview = realm.object(ofType: Entity.Preview.self, forPrimaryKey: id) else { return }
try realm.write {
let dst = diskCache.dir.appendingPathComponent(filename)
try diskCache.move(from: src, to: dst)
preview.localURL = dst
}
}
.subscribeOn(SerialDispatchQueueScheduler(qos: .background))
}
}
}
}
}
// MARK: - private
private enum Cache {
static let directory: URL = {
let base = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let dir = URL(fileURLWithPath: base).appendingPathComponent("tracks", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
return dir
}()
}
private final class DiskCacheImpl: NSObject, NSFilePresenter {
private lazy var _diskSizeInBytes = BehaviorRelay<Int>(value: self.diskSizeInBytes)
let dir: URL
var presentedItemURL: URL? { return dir }
let presentedItemOperationQueue = OperationQueue()
init(dir: URL = Cache.directory) {
self.dir = dir
super.init()
NSFileCoordinator.addFilePresenter(self)
}
func presentedSubitemDidChange(at url: URL) {
_diskSizeInBytes.accept(diskSizeInBytes)
}
var diskSizeInBytes: Int {
do {
let paths = try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.fileSizeKey])
let sizes = try paths.compactMap {
try $0.resourceValues(forKeys: [.fileSizeKey]).fileSize
}
return sizes.reduce(0, +)
} catch {
print(error)
return 0
}
}
func exists(_ url: URL) -> Bool {
return FileManager.default.fileExists(atPath: url.path)
}
func move(from src: URL, to dst: URL) throws {
try? FileManager.default.removeItem(at: dst)
try FileManager.default.moveItem(at: src, to: dst)
}
func removeAll() -> Single<Void> {
let dir = self.dir
return Single.just {
try FileManager.default.removeItem(at: dir)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
}.subscribeOn(SerialDispatchQueueScheduler(qos: .background))
}
}
private extension Reactive where Base: URLSession {
func download(with url: URL) -> Single<URL?> {
return Single.create(subscribe: { event in
let task = URLSession.shared.downloadTask(with: url, completionHandler: { (url, _, error) in
if let error = error {
event(.error(error))
} else {
event(.success(url))
}
})
task.resume()
return Disposables.create {
task.cancel()
}
})
}
}
| 34.989796 | 128 | 0.501604 |
acb07b99de348e1893c38963b2ee488a29e5bee2 | 479 | import XCTest
import LocalShell
import NIO
class Tests: XCTestCase {
var shell: LocalExecutor!
override func setUp() {
super.setUp()
let e = EmbeddedEventLoop()
shell = LocalExecutor(currentDirectoryPath: "/", on: e)
}
func testLocalCommand() {
let out = try! shell.run(bash: "cd /tmp && pwd").future.wait().trimmingCharacters(in: .whitespacesAndNewlines)
XCTAssertEqual(out, "/tmp")
}
}
| 20.826087 | 118 | 0.601253 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.