repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
Antondomashnev/Sourcery | SourceryTests/Stub/Performance-Code/Kiosk/Admin/PasswordAlertViewController.swift | 2 | 1210 | import UIKit
class PasswordAlertViewController: UIAlertController {
class func alertView(completion: @escaping () -> ()) -> PasswordAlertViewController {
let alertController = PasswordAlertViewController(title: "Exit Kiosk", message: nil, preferredStyle: .alert)
let exitAction = UIAlertAction(title: "Exit", style: .default) { (_) in
completion()
return
}
if detectDevelopmentEnvironment() {
exitAction.isEnabled = true
} else {
exitAction.isEnabled = false
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "Exit Password"
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
// compiler crashes when using weak
exitAction.isEnabled = textField.text == "Genome401"
}
}
alertController.addAction(exitAction)
alertController.addAction(cancelAction)
return alertController
}
}
| mit |
AlexSeverinov/Bond | BondTests/DisposableTests.swift | 1 | 2740 | //
// DisposableTests.swift
// Bond
//
// Created by Srđan Rašić on 16/08/15.
// Copyright © 2015 Bond. All rights reserved.
//
import XCTest
@testable import Bond
private class CountingDisposable: DisposableType {
var isDisposed: Bool = false
var disposeCallCount = 0
func dispose() {
disposeCallCount += 1
isDisposed = true
}
init() {}
}
class DisposableTests: XCTestCase {
func testBlockDisposableDisposesAndDisposesOnlyOnce() {
var executedCount: Int = 0
let d = BlockDisposable { executedCount += 1 }
XCTAssertFalse(d.isDisposed)
XCTAssertEqual(executedCount, 0)
d.dispose()
XCTAssertTrue(d.isDisposed)
XCTAssertEqual(executedCount, 1)
d.dispose()
XCTAssertTrue(d.isDisposed)
XCTAssertEqual(executedCount, 1)
}
func testSerialDisposableDisposesAndDisposesOnlyOnceAndDisposedImmediatelyIfAlreadyDisposed() {
let c = CountingDisposable()
let s = SerialDisposable(otherDisposable: c)
XCTAssertFalse(c.isDisposed)
XCTAssertFalse(s.isDisposed)
XCTAssertEqual(c.disposeCallCount, 0)
s.dispose()
XCTAssertTrue(s.isDisposed)
XCTAssertTrue(c.isDisposed)
XCTAssertEqual(c.disposeCallCount, 1)
s.dispose()
XCTAssertTrue(s.isDisposed)
XCTAssertTrue(c.isDisposed)
XCTAssertEqual(c.disposeCallCount, 1)
let c2 = CountingDisposable()
s.otherDisposable = c2
XCTAssertTrue(s.isDisposed)
XCTAssertTrue(c2.isDisposed, "Should have been immediately disposed.")
XCTAssertEqual(c2.disposeCallCount, 1)
}
func testCompositeDisposableDisposesAndDisposesOnlyOnceAndDisposedImmediatelyIfAlreadyDisposed() {
let c = CountingDisposable()
let d = CompositeDisposable([c])
XCTAssertFalse(c.isDisposed)
XCTAssertFalse(d.isDisposed)
XCTAssertEqual(c.disposeCallCount, 0)
d.dispose()
XCTAssertTrue(c.isDisposed)
XCTAssertTrue(d.isDisposed)
XCTAssertEqual(c.disposeCallCount, 1)
d.dispose()
XCTAssertTrue(c.isDisposed)
XCTAssertTrue(d.isDisposed)
XCTAssertEqual(c.disposeCallCount, 1)
let c2 = CountingDisposable()
d.addDisposable(c2)
XCTAssertTrue(d.isDisposed)
XCTAssertTrue(c2.isDisposed, "Should have been immediately disposed.")
XCTAssertEqual(c2.disposeCallCount, 1)
d.addDisposable(c2)
XCTAssertTrue(c2.isDisposed, "Should have been immediately disposed.")
XCTAssertEqual(c2.disposeCallCount, 2)
}
func testCompositeDisposableChainDoesNotDeadLock() {
let d1 = CompositeDisposable()
let d2 = CompositeDisposable()
d1.addDisposable(d2)
d1.dispose()
XCTAssert(true, "If we got here, everything is OK!")
}
} | mit |
smartmobilefactory/SMF-iOS-CommonProjectSetupFiles | Plist2swift/Sources/Plist2.swift | 1 | 19626 | #!/usr/bin/env xcrun --sdk macosx swift
//
// main.swift
// plist2swift
//
// Created by Bartosz Swiatek on 12.09.18.
// Copyright © 2018 Bartosz Swiatek. All rights reserved.
//
// Note: Currently Date is not supported
import Foundation
// MARK: Defaults
let configurationKeyName: String = "configurationName"
var output: FileHandle? = FileHandle.standardOutput
var countOfTabs = 0
// MARK: Helper
private func usage() {
let executableName = URL(fileURLWithPath: CommandLine.arguments[0]).lastPathComponent
print("""
plist2swift code generator
Usage: \(executableName) -e enumName [-o outputFile] plist1 plist2 ...
i.e. \(executableName) -e Api /path/to/production-configuration.plist /path/to/development-configuration.plist > generated.swift
i.e. \(executableName) -e Api -o generated.swift /path/to/production-configuration.plist /path/to/development-configuration.plist
""")
exit(1)
}
private func tabs(indentBy: Int = 0) -> String {
var tabsString = ""
indent(by: indentBy)
for _ in 0..<countOfTabs {
tabsString += "\t"
}
return tabsString
}
private func indent(by indentationLevel: Int = 1) {
countOfTabs += indentationLevel
}
/**
Given path to .plist file, it returns a sorted array of tuples
- Parameter fromPath: Path to the .plist file
- Returns: sorted array of tuples of type (key: String, value: Any)
*/
private func readPlist(fromPath: String) -> KeyValueTuples? {
var format = PropertyListSerialization.PropertyListFormat.xml
guard
let plistData = FileManager.default.contents(atPath: fromPath),
let plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String: Any] else {
return nil
}
let tupleArray = plistDict.sorted { (pairOne, pairTwo) -> Bool in
return pairOne.key < pairTwo.key
}
return KeyValueTuples(tuples: tupleArray)
}
/**
Generates the Swift header with date
*/
private func generateHeader() {
print("""
//
// Generated by plist2swift - Swift code from plists generator
//
import Foundation
""")
}
private func isKeyPresentInOptionalDictionary(keyToSearch: String, tupleKey: String, optionalDictionary: [String: [String: String]]) -> Bool {
guard let optionalKeysAndTypes = optionalDictionary[keyToSearch] else {
return false
}
let optionalArray = optionalKeysAndTypes.keys
return optionalArray.contains(tupleKey)
}
private func isKeyAvailableInAllPlists(keyToSearch: String, tupleKey: String, tuplesForPlists: [String: KeyValueTuples]) -> Bool {
for plistPath in tuplesForPlists.keys {
if
let tuples = tuplesForPlists[plistPath],
let dictionary = tuples[tupleKey] as? Dictionary<String, Any> {
if (dictionary.keys.contains(keyToSearch) == false) {
return false
}
}
}
return true
}
private func generateProtocol(tuplesForPlists: [String: KeyValueTuples], allKeyValueTuples: [(String, KeyValueTuples)]) -> [String: [String: String]] {
var dictionaryWithOptionalValues = [String: [String: String]]()
for (tupleKey, tuples) in allKeyValueTuples {
let name = tupleKey.uppercaseFirst()
let protocolName = name.appending("Protocol")
print("protocol \(protocolName) {")
indent()
var optionalKeysAndTypes = [String: String]()
for tuple in tuples.tuples {
let isKeyPresentInAllPlists = isKeyAvailableInAllPlists(keyToSearch: tuple.key, tupleKey: tupleKey, tuplesForPlists: tuplesForPlists)
var type = typeForValue(tuple.value as Any)
if (isKeyPresentInAllPlists == false) {
type = "\(type)?"
optionalKeysAndTypes[tuple.key] = type
}
print("\(tabs())var \(tuple.key.lowercaseFirst()): \(type) { get }")
}
dictionaryWithOptionalValues[tupleKey] = optionalKeysAndTypes
print("\(tabs(indentBy: -1))}\n")
}
return dictionaryWithOptionalValues
}
/**
Generates a protocol with public instance properties. Used to generate protocols that internal structs conform to.
- Parameter name: Name of the protocol; "Protocol" will be added to the name as suffix
- Parameter tuples: Key Value Tuples to create protocol from
- Returns: Protocol name, in case it's needed to be saved for further use
*/
private func generateProtocol(name: String, tuples: KeyValueTuples) -> String {
let protocolName = name.appending("Protocol")
print("protocol \(protocolName) {")
indent()
for tuple in tuples.tuples {
let type = typeForValue(tuple.value as Any)
print("\(tabs())var \(tuple.key.lowercaseFirst()): \(type) { get }")
}
print("\(tabs(indentBy: -1))}\n")
return protocolName
}
/**
Generate the general protocol with class properties.
- Parameter name: Name of the protocol; "Protocol" will be added to the name as suffix
- Parameter commonKeys: Keys to generate non-Optional properties from
- Parameter oddKeys: Keys to generate Optional properties from
- Parameter keysAndTypes: Map with keys and their types
*/
private func generateProtocol(name: String, commonKeys: [String], oddKeys: [String], keysAndTypes: [String:String]) {
print("\(tabs())protocol \(name) {")
indent()
print("\(tabs())// Common Keys")
for commonKey in commonKeys {
guard let type = keysAndTypes[commonKey] else {
return
}
print("\(tabs())var \(commonKey.lowercaseFirst()): \(type) { get }")
}
if (!oddKeys.isEmpty) {
print("\n\(tabs())// Optional Keys")
for oddKey in oddKeys {
guard let type = keysAndTypes[oddKey] else {
return
}
print("\(tabs())var \(oddKey.lowercaseFirst()): \(type)? { get }")
}
}
print("\(tabs(indentBy: -1))}\n")
}
/**
Generate structs out of Dictionaries and make them conform to a given protocol.
- Parameters:
- name: Name of the struct. Default is 'nil' - the configurationName key will be used to generate the name
- tuples: Key Value Tuples to create protocol from
- keysAndTypes: Map with keys and their types; Default is 'nil' - A new protocol will be created, the generated struct will conform to this new protocol
- oddKeys: Keys to generate Optional properties from
- protocolName: Name of the protocol; It has to end with a "Protocol" suffix; Default is 'nil' - the new generated protocol will be used
*/
private func generateStructs(name key: String? = nil, tuples: KeyValueTuples, keysAndTypes: [String: String]? = nil, oddKeys: [String], protocolName: String? = nil, optionalDictionary: [String: [String: String]]) {
var configName: String? = tuples[configurationKeyName] as? String
if (configName == nil && key != nil) {
configName = key
}
guard var structName = configName else {
return
}
structName = structName.uppercaseFirst()
var localKeysAndTypes = keysAndTypes
if (localKeysAndTypes == nil) {
localKeysAndTypes = [:]
for tuple in tuples.tuples {
let key = tuple.key
let value = tuple.value
if (localKeysAndTypes?[key] == nil) {
let type = typeForValue(value)
localKeysAndTypes?[key] = type
// Generate protocols for Dictionary entries
if (type == "Dictionary<String, Any>") {
let dictionary = tuples[key] as? Dictionary<String, Any>
let sortedDictionary = dictionary?.sorted { (pairOne, pairTwo) -> Bool in
return pairOne.key < pairTwo.key
}
let protocolName = generateProtocol(name: key.uppercaseFirst(), tuples: KeyValueTuples(tuples: sortedDictionary ?? []))
// override type with new protocol
localKeysAndTypes?[key] = protocolName
}
}
}
}
var conformingToProtocol: String = ""
if (protocolName != nil) {
conformingToProtocol = ": ".appending(protocolName!)
}
print("\n\(tabs())internal struct \(structName)\(conformingToProtocol) {")
indent()
var availableKeys = [String]()
for tuple in tuples.tuples {
let tupleKey = tuple.key
let tupleValue = tuple.value
availableKeys.append(tupleKey)
if (oddKeys.contains(tupleKey)) {
continue
}
guard let type = localKeysAndTypes?[tupleKey] else {
return
}
let isOptional: Bool = {
guard let key = key else {
return false
}
return isKeyPresentInOptionalDictionary(keyToSearch: key, tupleKey: tupleKey, optionalDictionary: optionalDictionary)
}()
switch type {
case "String" where (isOptional == false):
print("\(tabs())internal let \(tupleKey.lowercaseFirst()): \(type) = \"\(tupleValue)\"")
case "String" where (isOptional == true):
print("\(tabs())internal var \(tupleKey.lowercaseFirst()): \(type)? = \"\(tupleValue)\"")
case "Int" where (isOptional == false):
print("\(tabs())internal let \(tupleKey.lowercaseFirst()): \(type) = \(tupleValue)")
case "Int" where (isOptional == true):
print("\(tabs())internal var \(tupleKey.lowercaseFirst()): \(type)? = \(tupleValue)")
case "Bool" where (isOptional == false):
let boolString = (((tupleValue as? Bool) == true) ? "true" : "false")
print("\(tabs())internal let \(tupleKey.lowercaseFirst()): \(type) = \(boolString)")
case "Bool" where (isOptional == true):
let boolString = (((tupleValue as? Bool) == true) ? "true" : "false")
print("\(tabs())internal var \(tupleKey.lowercaseFirst()): \(type)? = \(boolString)")
case "Array<Any>" where (isOptional == false):
if let arrayValue = tupleValue as? Array<String> {
print("\(tabs())internal let \(tupleKey.lowercaseFirst()): \(type) = \(arrayValue)")
}
case "Array<Any>" where (isOptional == true):
if let arrayValue = tupleValue as? Array<String> {
print("\(tabs())internal var \(tupleKey.lowercaseFirst()): \(type)? = \(arrayValue)")
}
default:
// default is a struct
// Generate struct from the Dictionaries and Protocols
if (type.contains("Protocol")) {
let dictionary = tuples[tupleKey] as? Dictionary<String, Any>
let sortedDictionary = dictionary?.sorted { (pairOne, pairTwo) -> Bool in
return pairOne.key < pairTwo.key
}
generateStructs(name: tupleKey, tuples: KeyValueTuples(tuples: sortedDictionary ?? []), oddKeys: oddKeys, protocolName: type, optionalDictionary: optionalDictionary)
print("\(tabs())internal let \(tupleKey.lowercaseFirst()): \(type) = \(tupleKey.uppercaseFirst())()")
}
}
}
guard
let key = key,
let optionalKeysAndTypes = optionalDictionary[key] else {
print("\(tabs(indentBy: -1))}\n")
return
}
let keysAndTypesToAdd = optionalKeysAndTypes.filter { (key: String, type: String) in
return (availableKeys.contains(key) == false)
}
for (key, type) in keysAndTypesToAdd {
print("\(tabs())internal var \(key.lowercaseFirst()): \(type) = nil")
}
print("\(tabs(indentBy: -1))}\n")
}
/**
Generates extensions to structs, conforming to protocol
- Parameters:
- enumName: Name of the enum containing structs that need to conform to given protocol
- protocolName: Name of the protocol to conform to
- allTuples: List of Key Value Tuples serialized from plist files
- keysAndTypes: Map with keys and their types
- oddKeys: Keys to generate Optional properties from
*/
private func generateExtensions(enumName: String, protocolName: String, allTuples: [KeyValueTuples], keysAndTypes: Dictionary<String, String>, oddKeys: [String], optionalDictionary: [String: [String: String]]) {
for tuples in allTuples {
guard let caseName = tuples[configurationKeyName] as? String else {
return
}
let structName = caseName.uppercaseFirst()
print("\(tabs())extension \(enumName).\(structName): \(protocolName) {")
indent()
for oddKey in oddKeys {
guard let type = keysAndTypes[oddKey] else {
return
}
if (type == "Array<Any>") {
print("\(tabs())var \(oddKey.lowercaseFirst()): \(type)? {")
let returnValue = tuples[oddKey] as? Array<String>
((returnValue != nil) ? print("\(tabs())return \(returnValue!)") : print("\t\treturn nil"))
print("\(tabs())}")
} else if (type.contains("Protocol")){
guard tuples[oddKey] != nil else {
print("\(tabs())var \(oddKey.lowercaseFirst()): \(type)? {")
print("\(tabs(indentBy: 1))return nil")
print("\(tabs(indentBy: -1))}")
continue
}
let dictionary = tuples[oddKey] as? Dictionary<String, Any>
let sortedDictionary = dictionary?.sorted { (pairOne, pairTwo) -> Bool in
return pairOne.key < pairTwo.key
}
generateStructs(name: oddKey, tuples: KeyValueTuples(tuples: sortedDictionary ?? []), oddKeys: oddKeys, protocolName: type, optionalDictionary: optionalDictionary)
print("\(tabs())var \(oddKey.lowercaseFirst()): \(type)? {")
print("\(tabs(indentBy: 1))return \(oddKey.uppercaseFirst())()")
print("\(tabs(indentBy: -1))}")
} else { // String
print("\(tabs())var \(oddKey.lowercaseFirst()): \(type)? {")
indent()
let returnValue = tuples[oddKey] as? String
returnValue != nil ? print("\(tabs())return \"\(returnValue!)\"") : print("\(tabs())return nil")
print("\(tabs(indentBy: -1))}")
}
}
print("\(tabs(indentBy: -1))}\n")
}
}
/**
Generate an enum with structs and properties.
- Parameters:
- name: Name of the enum
- protocolName: Name of the protocol that extensions should conform to
- allTuples: List of Key Value Tuples serialized from plist files
- keysAndTypes: Map with keys and their types
- oddKeys: Keys to generate Optional properties from
*/
private func generateEnum(name enumName: String, protocolName: String, allTuples: [KeyValueTuples], keysAndTypes: Dictionary<String, String>, oddKeys: [String], optionalDictionary: [String: [String: String]]) {
let cases: [String] = allTuples.map { (tuples: KeyValueTuples) in
return (tuples[configurationKeyName] as? String ?? "")
}
print("\(tabs())internal enum \(enumName) {")
indent()
for caseName in cases {
print("\(tabs())case \(caseName.lowercaseFirst())")
}
for tuples in allTuples {
generateStructs(tuples: tuples, keysAndTypes: keysAndTypes, oddKeys: oddKeys, optionalDictionary: optionalDictionary)
}
print("""
\(tabs())var configuration: \(protocolName) {
\(tabs(indentBy: 1))switch self {
""")
for caseName in cases {
let structName = caseName.uppercaseFirst()
print("\(tabs())case .\(caseName.lowercaseFirst()):")
print("\(tabs())\treturn \(structName)()")
}
print("\(tabs())}")
print("\(tabs(indentBy: -1))}")
print("\(tabs(indentBy: -1))}\n")
generateExtensions(enumName: enumName, protocolName: protocolName, allTuples: allTuples, keysAndTypes: keysAndTypes, oddKeys: oddKeys, optionalDictionary: optionalDictionary)
}
/**
Map the type of a value to its string representation
- Parameter value: Any object you want to get the string type equivalent from; default is "String". Supported types are: String, Bool, Int, Array<Any> and Dictionary<String, Any>
- Returns: String that reflects the type of given value
*/
private func typeForValue(_ value: Any) -> String {
switch value {
case is String:
return "String"
case is Bool:
return "Bool"
case is Int:
return "Int"
case is Array<Any>:
return "Array<Any>"
case is Dictionary<String, Any>:
return "Dictionary<String, Any>"
default:
return "String"
}
}
// MARK: Logging
extension FileHandle: TextOutputStream {
public func write(_ string: String) {
guard let data = string.data(using: .utf8) else {
return
}
self.write(data)
}
}
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
let localOutput = items.map { "\($0)" }.joined(separator: separator)
guard var output = output else {
return
}
Swift.print(localOutput, separator: separator, terminator: terminator, to: &output)
}
// MARK: String
extension String {
func uppercaseFirst() -> String {
return prefix(1).uppercased() + dropFirst()
}
func lowercaseFirst() -> String {
return prefix(1).lowercased() + dropFirst()
}
mutating func uppercaseFirst() {
self = self.uppercaseFirst()
}
mutating func lowercaseFirst() {
self = self.lowercaseFirst()
}
}
// MARK: - Tuples
class KeyValueTuples {
var tuples: [(key: String, value: Any)]
var keys: [String] {
let keys = self.tuples.map { (tuple: (key: String, value: Any)) in
return tuple.key
}
return keys
}
init(tuples: [(key: String, value: Any)]) {
self.tuples = tuples
}
subscript(_ key: String) -> Any? {
get {
let tuple = self.tuples.first { (tuple: (key: String, value: Any)) -> Bool in
return tuple.key == key
}
return tuple?.value
}
}
}
// MARK: Main
let args = CommandLine.arguments
var plists = [String]()
var enumName: String = ""
if (args.count < 4) {
usage()
}
if (args.count >= 6 && args[1] == "-e" && args[3] == "-o") {
enumName = args[2]
let fileManager = FileManager.default
if (fileManager.fileExists(atPath: args[4]) == true) {
try? fileManager.removeItem(atPath: args[4])
}
fileManager.createFile(atPath: args[4], contents: nil, attributes: nil)
output = FileHandle(forWritingAtPath: args[4])
for i in 5...args.count-1 {
plists.append(args[i])
}
} else if (args.count >= 4 && args[1] == "-e") {
enumName = args[2]
for i in 3...args.count-1 {
plists.append(args[i])
}
} else {
usage()
}
let shouldGenerateOddKeys: Bool = CommandLine.arguments.count >= 5
var commonKeys = [String]()
var oddKeys = [String]()
var keysAndTypes = [String:String]()
var allTuples = [KeyValueTuples]()
var protocolName: String = enumName.appending("Protocol")
var tuplesForPlists = [String: KeyValueTuples]()
var allKeyValueTuples = [String: KeyValueTuples]()
generateHeader()
// gather keys and values... and types
for plistPath in plists {
guard let tuples = readPlist(fromPath: plistPath) else {
print("Couldn't read plist at \(plistPath)")
exit(1)
}
tuplesForPlists[plistPath] = tuples
allTuples.append(tuples)
let allKeys = tuples.keys
if (allKeys.contains(configurationKeyName) == false) {
print("Plist doesn't contain \(configurationKeyName) key. Please add it and run the script again")
exit(1)
}
if (commonKeys.count == 0) {
commonKeys = allKeys
}
if (oddKeys.count == 0 && shouldGenerateOddKeys) {
oddKeys = allKeys
}
for key in allKeys {
guard let tuple = tuples[key] else {
continue
}
let type = typeForValue(tuple)
if (type != "Dictionary<String, Any>") { // Just register the existence of primitive types
keysAndTypes[key] = type
} else { // Generate protocols for Dictionary entries
var dictionary = tuples[key] as? Dictionary<String, Any> ?? [:]
// Merge sub-keys in dictionaries from current property list with already known sub-keys from dictionaries
// with the same name.
if let keyValueTuples = allKeyValueTuples[key] {
for knownKey in Set<String>(keyValueTuples.keys).subtracting(Set(dictionary.keys)) {
for (tupleKey, tupleValue) in keyValueTuples.tuples {
if (tupleKey == knownKey) {
dictionary[tupleKey] = tupleValue
}
}
}
}
allKeyValueTuples[key] = KeyValueTuples(tuples: dictionary.sorted { $0.key < $1.key })
// Generate protocol name
keysAndTypes[key] = key.uppercaseFirst().appending("Protocol")
}
}
commonKeys = Array(Set(commonKeys).intersection(allKeys)).sorted()
oddKeys = Array(Set(oddKeys).union(allKeys)).sorted()
oddKeys = Array(Set(oddKeys).subtracting(commonKeys)).sorted()
if (oddKeys.count == 0 && shouldGenerateOddKeys && plists.count > 1 && plists.firstIndex(of: plistPath) == 0) {
oddKeys = allKeys
}
}
let allKeyValueTuplesSorted = allKeyValueTuples.sorted(by: { $0.0 < $1.0 })
let optionalDictionary = generateProtocol(tuplesForPlists: tuplesForPlists, allKeyValueTuples: allKeyValueTuplesSorted)
generateProtocol(name: protocolName, commonKeys: commonKeys, oddKeys: oddKeys, keysAndTypes: keysAndTypes)
generateEnum(name: enumName, protocolName: protocolName, allTuples: allTuples, keysAndTypes: keysAndTypes, oddKeys: oddKeys, optionalDictionary: optionalDictionary)
| mit |
silence0201/Swift-Study | Learn/05.控制语句/guard语句.playground/Contents.swift | 1 | 1964 |
//定义一个Blog(博客)结构体
struct Blog {
let name: String?
let URL: String?
let Author: String?
}
func ifStyleBlog(blog: Blog) {
if let blogName = blog.name {
print("博客名:\(blogName)")
} else {
print("这篇博客没有名字!")
}
}
func guardStyleBlog(blog: Blog) {
guard let blogName = blog.name else {
print("这篇博客没有名字!")
return
}
print("这篇博客名:\(blogName)")
}
func ifLongStyleBlog(blog: Blog) {
if let blogName = blog.name {
print("这篇博客名:\(blogName)")
if let blogAuthor = blog.Author {
print("这篇博客由\(blogAuthor)写的")
if let blogURL = blog.URL {
print("这篇博客网址:\(blogURL)")
} else {
print("这篇博客没有网址!")
}
} else {
print("这篇博客没有作者!")
}
} else {
print("这篇博客没有名字!")
}
}
func guardLongStyleBlog(blog: Blog) {
guard let blogName = blog.name else {
print("这篇博客没有名字!")
return
}
print("这篇博客名:\(blogName)")
guard let blogAuthor = blog.Author else {
print("这篇博客没有作者")
return
}
print("这篇博客由\(blogAuthor)写的")
guard let blogURL = blog.URL else {
print("这篇博客没有网址!")
return
}
print("这篇博客网址:\(blogURL)")
}
let blog1 = Blog(name: nil, URL: "51work6.com", Author: "Tom")
let blog2 = Blog(name: "Tony'Blog", URL: "51work6.com", Author: "Tony")
let blog3 = Blog(name: nil, URL: nil, Author: "Tom")
let blog4 = Blog(name: "Tony'Blog", URL: "51work6.com", Author: nil)
guardStyleBlog(blog: blog1)
guardStyleBlog(blog: blog2)
guardLongStyleBlog(blog: blog3)
guardLongStyleBlog(blog: blog4)
| mit |
edmw/Volumio_ios | Pods/Eureka/Source/Rows/TextAreaRow.swift | 4 | 12326 | // AlertRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum TextAreaHeight {
case fixed(cellHeight: CGFloat)
case dynamic(initialTextViewHeight: CGFloat)
}
protocol TextAreaConformance: FormatterConformance {
var placeholder : String? { get set }
var textAreaHeight : TextAreaHeight { get set }
}
/**
* Protocol for cells that contain a UITextView
*/
public protocol AreaCell : TextInputCell {
var textView: UITextView { get }
}
extension AreaCell {
public var textInput: UITextInput {
return textView
}
}
open class _TextAreaCell<T> : Cell<T>, UITextViewDelegate, AreaCell where T: Equatable, T: InputTypeInitiable {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open lazy var placeholderLabel : UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.numberOfLines = 0
v.textColor = UIColor(white: 0, alpha: 0.22)
return v
}()
open lazy var textView : UITextView = {
let v = UITextView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
open var dynamicConstraints = [NSLayoutConstraint]()
open override func setup() {
super.setup()
let textAreaRow = row as! TextAreaConformance
switch textAreaRow.textAreaHeight {
case .dynamic(_):
height = { UITableViewAutomaticDimension }
textView.isScrollEnabled = false
case .fixed(let cellHeight):
height = { cellHeight }
}
textView.keyboardType = .default
textView.delegate = self
textView.font = .preferredFont(forTextStyle: .body)
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = UIEdgeInsets.zero
placeholderLabel.font = textView.font
selectionStyle = .none
contentView.addSubview(textView)
contentView.addSubview(placeholderLabel)
imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
setNeedsUpdateConstraints()
}
deinit {
textView.delegate = nil
imageView?.removeObserver(self, forKeyPath: "image")
}
open override func update() {
super.update()
textLabel?.text = nil
detailTextLabel?.text = nil
textView.isEditable = !row.isDisabled
textView.textColor = row.isDisabled ? .gray : .black
textView.text = row.displayValueFor?(row.value)
placeholderLabel.text = (row as? TextAreaConformance)?.placeholder
placeholderLabel.sizeToFit()
placeholderLabel.isHidden = textView.text.characters.count != 0
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textView.canBecomeFirstResponder
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textView.becomeFirstResponder()
}
open override func cellResignFirstResponder() -> Bool {
return textView.resignFirstResponder()
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey], obj === imageView && keyPathValue == "image" && (changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
//Mark: Helpers
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textView.isFirstResponder ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
//MARK: TextFieldDelegate
open func textViewDidBeginEditing(_ textView: UITextView) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textView, cell: self)
if let textAreaConformance = (row as? TextAreaConformance), let _ = textAreaConformance.formatter, textAreaConformance.useFormatterOnDidBeginEditing ?? textAreaConformance.useFormatterDuringInput {
textView.text = self.displayValue(useFormatter: true)
}
else {
textView.text = self.displayValue(useFormatter: false)
}
}
open func textViewDidEndEditing(_ textView: UITextView) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textView, cell: self)
textViewDidChange(textView)
textView.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textViewDidChange(_ textView: UITextView) {
if let textAreaConformance = row as? TextAreaConformance, case .dynamic = textAreaConformance.textAreaHeight, let tableView = formViewController()?.tableView {
let currentOffset = tableView.contentOffset
UIView.setAnimationsEnabled(false)
tableView.beginUpdates()
tableView.endUpdates()
UIView.setAnimationsEnabled(true)
tableView.setContentOffset(currentOffset, animated: false)
}
placeholderLabel.isHidden = textView.text.characters.count != 0
guard let textValue = textView.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textView.selectedTextRange?.start else { return }
let oldVal = textView.text
textView.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textView, oldValue: oldVal, newValue: textView.text) ?? selStartPos
textView.selectedTextRange = textView.textRange(from: selStartPos, to: selStartPos)
return
}
}
else {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
}
}
}
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return formViewController()?.textInput(textView, shouldChangeCharactersInRange: range, replacementString: text, cell: self) ?? true
}
open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textView, cell: self) ?? true
}
open func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return formViewController()?.textInputShouldEndEditing(textView, cell: self) ?? true
}
open override func updateConstraints(){
customConstraints()
super.updateConstraints()
}
open func customConstraints() {
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views : [String: AnyObject] = ["textView": textView, "label": placeholderLabel]
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]", options: [], metrics: nil, views: views))
if let textAreaConformance = row as? TextAreaConformance, case .dynamic(let initialTextViewHeight) = textAreaConformance.textAreaHeight {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textView(>=initialHeight@800)]-|", options: [], metrics: ["initialHeight": initialTextViewHeight], views: views))
}
else {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textView]-|", options: [], metrics: nil, views: views))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textView]-|", options: [], metrics: nil, views: views))
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-|", options: [], metrics: nil, views: views))
}
else {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textView]-|", options: [], metrics: nil, views: views))
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-|", options: [], metrics: nil, views: views))
}
contentView.addConstraints(dynamicConstraints)
}
}
open class TextAreaCell : _TextAreaCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
open class AreaRow<Cell: CellType>: FormatteableRow<Cell>, TextAreaConformance where Cell: BaseCell, Cell: AreaCell {
open var placeholder : String?
open var textAreaHeight = TextAreaHeight.fixed(cellHeight: 110)
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _TextAreaRow: AreaRow<TextAreaCell> {
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with a UITextView where the user can enter large text.
public final class TextAreaRow: _TextAreaRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| gpl-3.0 |
stripe/stripe-ios | Tests/Tests/STPPaymentMethodUSBankAccountParamsStubbedTest.swift | 1 | 11814 | //
// STPPaymentMethodUSBankAccountParamsStubbedTest.swift
// StripeiOS Tests
//
// Created by John Woo on 3/24/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import OHHTTPStubs
import OHHTTPStubsSwift
import StripeCoreTestUtils
import XCTest
@testable@_spi(STP) import Stripe
@testable@_spi(STP) import StripeApplePay
@testable@_spi(STP) import StripeCore
@testable@_spi(STP) import StripePaymentSheet
class STPPaymentMethodUSBankAccountParamsStubbedTest: APIStubbedTestCase {
func testus_bank_account_withoutNetworks() {
let stubbedApiClient = stubbedAPIClient()
stub { urlRequest in
return urlRequest.url?.absoluteString.contains("/payment_methods") ?? false
} response: { urlRequest in
let jsonText = """
{
"id": "pm_1KgvOfFY0qyl6XeW7RfvDvxE",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": "tester@example.com",
"name": "iOS CI Tester",
"phone": null
},
"created": 1648146513,
"customer": null,
"livemode": false,
"type": "us_bank_account",
"us_bank_account": {
"account_holder_type": "individual",
"account_type": "checking",
"bank_name": "STRIPE TEST BANK",
"fingerprint": "ickfX9sbxIyAlbuh",
"last4": "6789",
"linked_account": null,
"routing_number": "110000000"
}
}
"""
return HTTPStubsResponse(
data: jsonText.data(using: .utf8)!,
statusCode: 200,
headers: nil
)
}
let usBankAccountParams = STPPaymentMethodUSBankAccountParams()
usBankAccountParams.accountType = .checking
usBankAccountParams.accountHolderType = .individual
usBankAccountParams.accountNumber = "000123456789"
usBankAccountParams.routingNumber = "110000000"
let billingDetails = STPPaymentMethodBillingDetails()
billingDetails.name = "iOS CI Tester"
billingDetails.email = "tester@example.com"
let params = STPPaymentMethodParams(
usBankAccount: usBankAccountParams,
billingDetails: billingDetails,
metadata: nil
)
let exp = expectation(description: "Payment Method US Bank Account create")
stubbedApiClient.createPaymentMethod(with: params) {
(paymentMethod: STPPaymentMethod?, error: Error?) in
XCTAssertNil(error)
XCTAssertNotNil(paymentMethod, "Payment method should be populated")
XCTAssertEqual(paymentMethod?.type, .USBankAccount, "Incorrect PaymentMethod type")
XCTAssertNotNil(
paymentMethod?.usBankAccount,
"The `usBankAccount` property must be populated"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountHolderType,
.individual,
"`accountHolderType` should be individual"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountType,
.checking,
"`accountType` should be checking"
)
XCTAssertEqual(paymentMethod?.usBankAccount?.last4, "6789", "`last4` should be 6789")
XCTAssertNil(paymentMethod?.usBankAccount?.networks)
exp.fulfill()
}
self.waitForExpectations(timeout: STPTestingNetworkRequestTimeout)
}
func testus_bank_account_networksInPayloadWithPreferred() {
let stubbedApiClient = stubbedAPIClient()
stub { urlRequest in
return urlRequest.url?.absoluteString.contains("/payment_methods") ?? false
} response: { urlRequest in
let jsonText = """
{
"id": "pm_1KgvOfFY0qyl6XeW7RfvDvxE",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": "tester@example.com",
"name": "iOS CI Tester",
"phone": null
},
"created": 1648146513,
"customer": null,
"livemode": false,
"type": "us_bank_account",
"us_bank_account": {
"account_holder_type": "individual",
"account_type": "checking",
"bank_name": "STRIPE TEST BANK",
"fingerprint": "ickfX9sbxIyAlbuh",
"last4": "6789",
"linked_account": null,
"networks": {
"preferred": "ach",
"supported": [
"ach"
]
},
"routing_number": "110000000"
}
}
"""
return HTTPStubsResponse(
data: jsonText.data(using: .utf8)!,
statusCode: 200,
headers: nil
)
}
let usBankAccountParams = STPPaymentMethodUSBankAccountParams()
usBankAccountParams.accountType = .checking
usBankAccountParams.accountHolderType = .individual
usBankAccountParams.accountNumber = "000123456789"
usBankAccountParams.routingNumber = "110000000"
let billingDetails = STPPaymentMethodBillingDetails()
billingDetails.name = "iOS CI Tester"
billingDetails.email = "tester@example.com"
let params = STPPaymentMethodParams(
usBankAccount: usBankAccountParams,
billingDetails: billingDetails,
metadata: nil
)
let exp = expectation(description: "Payment Method US Bank Account create")
stubbedApiClient.createPaymentMethod(with: params) {
(paymentMethod: STPPaymentMethod?, error: Error?) in
XCTAssertNil(error)
XCTAssertNotNil(paymentMethod, "Payment method should be populated")
XCTAssertEqual(paymentMethod?.type, .USBankAccount, "Incorrect PaymentMethod type")
XCTAssertNotNil(
paymentMethod?.usBankAccount,
"The `usBankAccount` property must be populated"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountHolderType,
.individual,
"`accountHolderType` should be individual"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountType,
.checking,
"`accountType` should be checking"
)
XCTAssertEqual(paymentMethod?.usBankAccount?.last4, "6789", "`last4` should be 6789")
XCTAssertEqual(paymentMethod?.usBankAccount?.networks?.preferred, "ach")
XCTAssertEqual(paymentMethod?.usBankAccount?.networks?.supported.count, 1)
XCTAssertEqual(paymentMethod?.usBankAccount?.networks?.supported.first, "ach")
exp.fulfill()
}
self.waitForExpectations(timeout: STPTestingNetworkRequestTimeout)
}
func testus_bank_account_networksInPayloadWithoutPreferred() {
let stubbedApiClient = stubbedAPIClient()
stub { urlRequest in
return urlRequest.url?.absoluteString.contains("/payment_methods") ?? false
} response: { urlRequest in
let jsonText = """
{
"id": "pm_1KgvOfFY0qyl6XeW7RfvDvxE",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": "tester@example.com",
"name": "iOS CI Tester",
"phone": null
},
"created": 1648146513,
"customer": null,
"livemode": false,
"type": "us_bank_account",
"us_bank_account": {
"account_holder_type": "individual",
"account_type": "checking",
"bank_name": "STRIPE TEST BANK",
"fingerprint": "ickfX9sbxIyAlbuh",
"last4": "6789",
"linked_account": null,
"networks": {
"supported": [
"ach"
]
},
"routing_number": "110000000"
}
}
"""
return HTTPStubsResponse(
data: jsonText.data(using: .utf8)!,
statusCode: 200,
headers: nil
)
}
let usBankAccountParams = STPPaymentMethodUSBankAccountParams()
usBankAccountParams.accountType = .checking
usBankAccountParams.accountHolderType = .individual
usBankAccountParams.accountNumber = "000123456789"
usBankAccountParams.routingNumber = "110000000"
let billingDetails = STPPaymentMethodBillingDetails()
billingDetails.name = "iOS CI Tester"
billingDetails.email = "tester@example.com"
let params = STPPaymentMethodParams(
usBankAccount: usBankAccountParams,
billingDetails: billingDetails,
metadata: nil
)
let exp = expectation(description: "Payment Method US Bank Account create")
stubbedApiClient.createPaymentMethod(with: params) {
(paymentMethod: STPPaymentMethod?, error: Error?) in
XCTAssertNil(error)
XCTAssertNotNil(paymentMethod, "Payment method should be populated")
XCTAssertEqual(paymentMethod?.type, .USBankAccount, "Incorrect PaymentMethod type")
XCTAssertNotNil(
paymentMethod?.usBankAccount,
"The `usBankAccount` property must be populated"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountHolderType,
.individual,
"`accountHolderType` should be individual"
)
XCTAssertEqual(
paymentMethod?.usBankAccount?.accountType,
.checking,
"`accountType` should be checking"
)
XCTAssertEqual(paymentMethod?.usBankAccount?.last4, "6789", "`last4` should be 6789")
XCTAssertNil(paymentMethod?.usBankAccount?.networks?.preferred)
XCTAssertEqual(paymentMethod?.usBankAccount?.networks?.supported.count, 1)
XCTAssertEqual(paymentMethod?.usBankAccount?.networks?.supported.first, "ach")
exp.fulfill()
}
self.waitForExpectations(timeout: STPTestingNetworkRequestTimeout)
}
}
| mit |
OatmealCode/Oatmeal | Example/Pods/PiedPiper/PiedPiper/Result+Map.swift | 1 | 1809 | /// Errors that can arise when mapping Results
public enum ResultMappingError: ErrorType {
/// When the boxed value can't be mapped
case CantMapValue
}
extension Result {
func _map<U>(handler: (T, Promise<U>) -> Void) -> Future<U> {
let mapped = Promise<U>()
switch self {
case .Success(let value):
handler(value, mapped)
case .Error(let error):
mapped.fail(error)
case .Cancelled:
mapped.cancel()
}
return mapped.future
}
func _map<U>(handler: T -> Result<U>) -> Result<U> {
switch self {
case .Success(let value):
return handler(value)
case .Error(let error):
return .Error(error)
case .Cancelled:
return .Cancelled
}
}
/**
Maps this Result using a simple transformation closure
- parameter handler: The closure to use to map the boxed value of this Result
- returns: A new Result that will behave as this Result w.r.t. cancellation and failure, but will succeed with a value of type U obtained through the given closure
*/
public func map<U>(handler: T -> U) -> Result<U> {
return _map {
.Success(handler($0))
}
}
/**
Maps this Result using a simple transformation closure
- parameter handler: The closure to use to map the boxed value of this Result
- returns: A new Result that will behave as this Result w.r.t. cancellation and failure, but will succeed with a value of type U obtained through the given closure, unless the latter throws. In this case, the new Result will fail
*/
public func map<U>(handler: T throws -> U) -> Result<U> {
return _map { value in
do {
let mappedValue = try handler(value)
return .Success(mappedValue)
} catch {
return .Error(error)
}
}
}
} | mit |
ntwf/TheTaleClient | TheTale/Stores/RequestAuthorisation/RequestAuthorisation.swift | 1 | 454 | //
// RequestAuthorisation.swift
// TheTaleClient
//
// Created by Mikhail Vospennikov on 20/08/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
struct RequestAuthorisation {
var urlPath: String
}
extension RequestAuthorisation {
init?(jsonObject: JSON) {
guard let urlPath = jsonObject["authorisation_page"] as? String else {
return nil
}
self.urlPath = urlPath
}
}
| mit |
hetefe/EmotionalKeyBoard | EmotionalKeyBoard/EmotionalKeyBoard/Extension/UIView+ViewController.swift | 1 | 733 | //
// UIView+ViewController.swift
// sina_htf
//
// Created by 赫腾飞 on 15/12/23.
// Copyright © 2015年 hetefe. All rights reserved.
//
import UIKit
//通过响应者链条 将视图的导航视图控制 找到
extension UIView {
func navController() -> UINavigationController? {
//获取 当前控制器的下一个响应者
var next = nextResponder()
//遍历响应者链条
repeat {
if let nextObj = next as? UINavigationController {
return nextObj
}
//获取下一个响应者的下一个响应者
next = next?.nextResponder()
} while (next != nil)
return nil
}
} | mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11446-swift-sourcemanager-getmessage.swift | 11 | 204 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for in a {
case
let {
class
case ,
| mit |
tbaranes/SwiftyUtils | Tests/Extensions/UIKit/UIViewController/UIViewControllerExtensionTests.swift | 1 | 2842 | //
// UIViewControllerTests.swift
// SwiftyUtils
//
// Created by Tom Baranes on 11/04/2017.
// Copyright © 2017 Tom Baranes. All rights reserved.
//
import XCTest
// MARK: Life cycle
final class UIViewControllerExtensionTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
// MARK: - Remove
extension UIViewControllerExtensionTests {
func testRemovePreviousControllers() {
let navController = UINavigationController()
let lastVC = UIViewController()
navController.pushViewController(UIViewController(), animated: true)
navController.pushViewController(UIViewController(), animated: true)
navController.pushViewController(lastVC, animated: true)
lastVC.removePreviousControllers()
XCTAssertEqual(navController.viewControllers.count, 1)
}
}
// MARK: - Misc
extension UIViewControllerExtensionTests {
func testIsVisible() {
let viewController = UIViewController()
XCTAssertFalse(viewController.isVisible)
}
}
// MARK: - Modal
extension UIViewControllerExtensionTests {
func testIsModal_false() {
let vc = UIViewController()
_ = UINavigationController(rootViewController: vc)
XCTAssertFalse(vc.isModal)
}
func testIsModal_true() {
let vc = UIViewController()
let vcModal = UIViewController()
vc.present(vcModal, animated: false, completion: nil)
XCTAssertTrue(vcModal.isModal)
}
func testIsModal_embedNav_true() {
let vc = UIViewController()
let navController = UINavigationController(rootViewController: vc)
navController.pushViewController(vc, animated: true)
let vcModal = UIViewController()
navController.present(vcModal, animated: false, completion: nil)
XCTAssertTrue(vcModal.isModal)
}
}
// MARK: - SwiftUI
#if canImport(SwiftUI) && (arch(arm64) || arch(x86_64))
import SwiftUI
@available(iOS 13.0, tvOS 13.0, *)
extension UIViewControllerExtensionTests {
struct SwiftUIView: View {
var body: some View { EmptyView() }
}
func testAddSubSwiftUIView() {
let viewController = UIViewController()
let view = viewController.view
viewController.addSubSwiftUIView(SwiftUIView(), to: viewController.view)
let hostingController = viewController.children.first
XCTAssertEqual(viewController.children.count, 1)
XCTAssertTrue(hostingController is UIHostingController<SwiftUIView>)
let hostingView = view?.subviews.first
XCTAssertEqual(hostingView?.backgroundColor, .clear)
XCTAssertEqual(view?.constraints.count, 4)
XCTAssertTrue(hostingView?.parentViewController is UIHostingController<SwiftUIView>)
}
}
#endif
| mit |
oscarfuentes/Architecture | Pods/Bond/Bond/Extensions/Shared/NSLock+Bond.swift | 26 | 1426 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension NSLock {
public convenience init(name: String) {
self.init()
self.name = name
}
}
public extension NSRecursiveLock {
public convenience init(name: String) {
self.init()
self.name = name
}
}
| mit |
debugsquad/metalic | metalic/Model/Filters/Basic/MFiltersItemBasicRembrandt.swift | 1 | 461 | import Foundation
class MFiltersItemBasicRembrandt:MFiltersItem
{
private let kImageName:String = "assetFilterRembrandt"
private let kCommitable:Bool = true
required init()
{
let name:String = NSLocalizedString("MFiltersItemBasicRembrandt_name", comment:"")
let filter:MetalFilter.Type = MetalFilterBasicRembrandt.self
super.init(name:name, asset:kImageName, filter:filter, commitable:kCommitable)
}
}
| mit |
creisterer-db/SwiftCharts | SwiftCharts/AxisValues/ChartAxisValue.swift | 2 | 1461 | //
// ChartAxisValue.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
An axis value, which is represented internally by a double and provides the label which is displayed in the chart (or labels, in the case of working with multiple labels per axis value).
This class is not meant to be instantiated directly. Use one of the existing subclasses or create a new one.
*/
public class ChartAxisValue: Equatable {
public let scalar: Double
public var text: String {
fatalError("Override")
}
/**
Labels that will be displayed on the chart. How this is done depends on the implementation of ChartAxisLayer.
In the most common case this will be an array with only one element.
*/
public var labels: [ChartAxisLabel] {
fatalError("Override")
}
public var hidden: Bool = false {
didSet {
for label in self.labels {
label.hidden = self.hidden
}
}
}
public init(scalar: Double) {
self.scalar = scalar
}
public var copy: ChartAxisValue {
return self.copy(self.scalar)
}
public func copy(scalar: Double) -> ChartAxisValue {
return ChartAxisValue(scalar: scalar)
}
}
public func ==(lhs: ChartAxisValue, rhs: ChartAxisValue) -> Bool {
return lhs.scalar == rhs.scalar
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/12180-swift-sourcemanager-getmessage.swift | 11 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S {
var T = [ I :
var {
{
let : {
class A {
{
}
class
case ,
| mit |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetryApi/Trace/Tracer.swift | 1 | 609 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
/// Tracer is a simple, protocol for Span creation and in-process context interaction.
/// Users may choose to use manual or automatic Context propagation. Because of that this class
/// offers APIs to facilitate both usages.
/// The automatic context propagation is done using os.activity
public protocol Tracer: AnyObject {
/// Returns a SpanBuilder to create and start a new Span
/// - Parameter spanName: The name of the returned Span.
func spanBuilder(spanName: String) -> SpanBuilder
}
| apache-2.0 |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/Parking/view/VehicleTextFieldTableViewCell.swift | 2 | 557 | //
// VehicleTextFieldTableViewCell.swift
// byuSuite
//
// Created by Erik Brady on 11/21/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
class VehicleTextFieldTableViewCell: UITableViewCell {
//MARK: IBOutlets
@IBOutlet private weak var label: UILabel!
@IBOutlet private (set) weak var textField: UITextField!
//MARK: Methods
func set(labelText: String?, delegate: UITextFieldDelegate, defaultText: String? = nil) {
label.text = labelText
textField.delegate = delegate
textField.text = defaultText
}
}
| apache-2.0 |
maail/MMImageLoader | MMImageLoader/Model.swift | 1 | 409 | //
// Model.swift
// MMImageLoader
//
// Created by Mohamed Maail on 5/29/16.
// Copyright © 2016 Mohamed Maail. All rights reserved.
//
import Foundation
struct UnsplashModel{
let Format : String
let Width : Int
let Height : Int
let FileName : String
let ID : Int
let Author : String
let AuthorURL : String
let PostURL : String
} | mit |
CodePath2017Group4/travel-app | RoadTripPlanner/PendingInvitationTableViewCell.swift | 1 | 2325 | //
// PendingInvitationTableViewCell.swift
// RoadTripPlanner
//
// Created by Nanxi Kang on 10/28/17.
// Copyright © 2017 RoadTripPlanner. All rights reserved.
//
import UIKit
class PendingInvitationTableViewCell: UITableViewCell {
@IBOutlet weak var tripLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var ownerLabel: UILabel!
@IBOutlet weak var acceptButton: UIButton!
@IBOutlet weak var rejectButton: UIButton!
var index: Int = 0
var delegate: InvitationDelegate?
func displayInvitaion(tripMember: TripMember) {
let trip = tripMember.trip
tripLabel.text = trip.name
dateLabel.text = Utils.formatDate(date: trip.date)
ownerLabel.text = trip.creator.username
if (tripMember.status == InviteStatus.Pending.hashValue) {
acceptButton.setImage(UIImage(named: "check-pending"), for: .normal)
rejectButton.setImage(UIImage(named: "reject-pending"), for: .normal)
} else if (tripMember.status == InviteStatus.Confirmed.hashValue) {
acceptButton.setImage(UIImage(named: "check"), for: .normal)
rejectButton.setImage(UIImage(named: "reject-pending"), for: .normal)
} else if (tripMember.status == InviteStatus.Rejected.hashValue) {
acceptButton.setImage(UIImage(named: "check-pending"), for: .normal)
rejectButton.setImage(UIImage(named: "reject"), for: .normal)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func confirmButtonTapped(_ sender: Any) {
acceptButton.setImage(UIImage(named: "check"), for: .normal)
rejectButton.setImage(UIImage(named: "reject-pending"), for: .normal)
if let delegate = self.delegate {
delegate.confirmInvitation(index: self.index)
}
}
@IBAction func rejectButtonTapped(_ sender: Any) {
acceptButton.setImage(UIImage(named: "check-pending"), for: .normal)
rejectButton.setImage(UIImage(named: "reject"), for: .normal)
if let delegate = self.delegate {
delegate.rejectInvitation(index: self.index)
}
}
}
| mit |
AxziplinLib/TabNavigations | TabNavigations/Classes/Generals/Cells/TableViewCell.swift | 1 | 585 | //
// TableViewCell.swift
// AxReminder
//
// Created by devedbox on 2017/6/28.
// Copyright © 2017年 devedbox. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
@objc
dynamic
public class var reusedIdentifier: String { return "_TableViewCell" }
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
}
}
| apache-2.0 |
bitcrowd/tickety-tick | safari/tickety-tick/ViewController.swift | 1 | 1480 | //
// ViewController.swift
//
import Cocoa
import SafariServices.SFSafariApplication
import SafariServices.SFSafariExtensionManager
let appName = "tickety-tick"
let extensionBundleIdentifier = "net.bitcrowd.tickety-tick.Extension"
class ViewController: NSViewController {
@IBOutlet var appNameLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
appNameLabel.stringValue = appName
SFSafariExtensionManager
.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { state, error in
guard let state = state, error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
if state.isEnabled {
self.appNameLabel.stringValue = "\(appName)'s extension is currently on."
} else {
self.appNameLabel
.stringValue =
"\(appName)'s extension is currently off. You can turn it on in Safari Extensions preferences."
}
}
}
}
@IBAction func openSafariExtensionPreferences(_: AnyObject?) {
SFSafariApplication
.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
guard error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
NSApplication.shared.terminate(nil)
}
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/05129-swift-sourcemanager-getmessage.swift | 11 | 274 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
extension NSData {
}
case c,
{
class B<T where g: P {
func b
{
protocol c {
class
case c,
case
| mit |
qianqian2/ocStudy1 | weibotext/weibotext/Class/Tools/Category/UIButton+Extension.swift | 1 | 1462 | //
// UIButton+Extension.swift
// weiboText
//
// Created by arang on 16/12/2.
// Copyright © 2016年 arang. All rights reserved.
//
import UIKit
extension UIButton {
// class func creatButton(imageName:String, bgImageName: String) -> UIButton {
//
// let btn = UIButton()
// btn.setImage(UIImage(named:imageName), for: .normal)
// btn.setImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
// btn.setBackgroundImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
//
// btn.setBackgroundImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
//
// btn.sizeToFit()
//
// return btn
// convenience : 便利,使用convenience修饰的构造函数叫做便利构造函数
/*
遍历构造函数的特点
1.遍历构造函数通常都是写在extension里面
2.遍历构造函数init前面需要加载convenience
3.在遍历构造函数中需要明确的调用self.init()
*/
convenience init ( imageName:String,bgImageName:String ){
self.init()
setImage(UIImage(named:imageName), for: .normal)
setImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
setBackgroundImage(UIImage(named:bgImageName), for: .normal)
setBackgroundImage(UIImage(named:bgImageName + "_highlighted"), for: .highlighted)
sizeToFit()
}
}
| apache-2.0 |
iCodesign/ICSTable | Carthage/Checkouts/Snap/Source/ConstraintRelation.swift | 1 | 1745 | //
// Snap
//
// Copyright (c) 2011-2014 Masonry Team - https://github.com/Masonry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/**
* ConstraintRelation is an Int enum that maps to NSLayoutRelation.
*/
internal enum ConstraintRelation: Int {
case Equal = 1, LessThanOrEqualTo, GreaterThanOrEqualTo
internal var layoutRelation: NSLayoutRelation {
get {
switch(self) {
case .LessThanOrEqualTo:
return .LessThanOrEqual
case .GreaterThanOrEqualTo:
return .GreaterThanOrEqual
default:
return .Equal
}
}
}
} | mit |
twostraws/HackingWithSwift | SwiftUI/project14/Bucketlist/ContentView.swift | 1 | 2513 | //
// ContentView.swift
// Bucketlist
//
// Created by Paul Hudson on 08/12/2021.
//
import MapKit
import SwiftUI
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
if viewModel.isUnlocked {
ZStack {
Map(coordinateRegion: $viewModel.mapRegion, annotationItems: viewModel.locations) { location in
MapAnnotation(coordinate: location.coordinate) {
VStack {
Image(systemName: "star.circle")
.resizable()
.foregroundColor(.red)
.frame(width: 44, height: 44)
.background(.white)
.clipShape(Circle())
Text(location.name)
.fixedSize()
}
.onTapGesture {
viewModel.selectedPlace = location
}
}
}
.ignoresSafeArea()
Circle()
.fill(.blue)
.opacity(0.3)
.frame(width: 32, height: 32)
VStack {
Spacer()
HStack {
Spacer()
Button {
viewModel.addLocation()
} label: {
Image(systemName: "plus")
}
.padding()
.background(.black.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.padding(.trailing)
}
}
}
.sheet(item: $viewModel.selectedPlace) { place in
EditView(location: place) { newLocation in
viewModel.update(location: newLocation)
}
}
} else {
Button("Unlock Places") {
viewModel.authenticate()
}
.padding()
.background(.blue)
.foregroundColor(.white)
.clipShape(Capsule())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| unlicense |
qutheory/vapor | Sources/Vapor/Error/ErrorSource.swift | 2 | 1274 | /// A source-code location.
public struct ErrorSource {
/// File in which this location exists.
public var file: String
/// Function in which this location exists.
public var function: String
/// Line number this location belongs to.
public var line: UInt
/// Number of characters into the line this location starts at.
public var column: UInt
/// Optional start/end range of the source.
public var range: Range<UInt>?
/// Creates a new `SourceLocation`
public init(
file: String,
function: String,
line: UInt,
column: UInt,
range: Range<UInt>? = nil
) {
self.file = file
self.function = function
self.line = line
self.column = column
self.range = range
}
}
extension ErrorSource {
/// Creates a new `ErrorSource` for the current call site.
public static func capture(
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column,
range: Range<UInt>? = nil
) -> Self {
return self.init(
file: file,
function: function,
line: line,
column: column,
range: range
)
}
}
| mit |
igorkos/BRTV | appleBRTVTests/BRTVAPITests.swift | 1 | 3806 | //
// BRTVAPITests.swift
// appleBRTV
//
// Created by Aleksandr Kelbas on 10/10/2015.
// Copyright © 2015 Aleksandr Kelbas. All rights reserved.
//
import XCTest
@testable import appleBRTV
class BRTVAPITests: XCTestCase {
var sessionID: String? = nil
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBRTVAPISetup()
{
XCTAssertNotNil(BRTVAPI.sharedInstance, "Cannot find BRTVAPI's shared instace")
}
func testBRTVAPILogin()
{
let expectation = expectationWithDescription("Connected to BRTV server")
let username = ""
let password = ""
BRTVAPI.sharedInstance.login(username, password: password, completion: {
(response: AnyObject?, error: NSError?) in
XCTAssertNil(error, "There was an error returned by the API handler")
XCTAssertNotNil(response, "Response object is nil")
XCTAssert(response is NSDictionary, "Response format is incorrect")
XCTAssertNotNil(response!["clientCredentials"], "Response doesn't contain client credentials information")
XCTAssertNotNil(response!["clientCredentials"]!!["sessionID"], "Response doesn't containc client session ID")
let res = (response as! NSDictionary)
let cred = res["clientCredentials"] as! NSDictionary
self.sessionID = (cred["sessionID"] as! String)
print("SessionID: \(self.sessionID)")
expectation.fulfill()
})
waitForExpectationsWithTimeout(30, handler: { (error: NSError?) in
XCTAssertNil(error, "Failed to connect to BRTV server")
})
}
func testBRTVAPIGetChannels()
{
let expectation = expectationWithDescription("Did get channels")
BRTVAPI.sharedInstance.getClientChannels("bd0320a5d0131fa3fe1899f7d1feef2d", completion: { (response: AnyObject?, error: NSError?) in
XCTAssertNil(error, "There was an error returned by the API handler")
XCTAssertNotNil(response, "Response object is nil")
XCTAssert(response is NSDictionary, "Response format is incorrect")
XCTAssertNotNil(response!["items"], "Response doesn't contain channel items")
expectation.fulfill()
})
waitForExpectationsWithTimeout(30, handler: { (error: NSError?) in
XCTAssertNil(error, "Failed to connect to BRTV server")
})
}
func testBRTVAPIGetURI()
{
let expectation = expectationWithDescription("did get uri")
BRTVAPI.sharedInstance.getStreamURI(24, sessionID: "bd0320a5d0131fa3fe1899f7d1feef2d", completion: { (response: AnyObject?, error: NSError?) in
XCTAssertNil(error, "There was an error returned by the API handler")
XCTAssertNotNil(response, "Response object is nil")
XCTAssert(response is NSDictionary, "Response format is incorrect")
XCTAssertNotNil(response!["URL"], "Response doesn't contain channel items")
print("response: \(response!)")
expectation.fulfill()
})
waitForExpectationsWithTimeout(30, handler: { (error: NSError?) in
XCTAssertNil(error, "Failed to connect to BRTV server")
})
}
}
| gpl-2.0 |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/BadgesDescription/HLDistanceBadge.swift | 1 | 405 | import UIKit
@objc enum DistancePointType: Int {
case customLocation
case userLocation
}
class HLDistanceBadge: HLPopularHotelBadge {
let distance: Double
let pointType: DistancePointType
init(distance: Double, pointType: DistancePointType) {
self.pointType = pointType
self.distance = distance
super.init()
self.systemName = "distanceBadge"
}
}
| mit |
auth0/Lock.swift | LockTests/AuthCollectionViewSpec.swift | 1 | 6088 | // AuthCollectionViewSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Quick
import Nimble
@testable import Lock
class AuthCollectionViewSpec: QuickSpec {
override func spec() {
context("expanded") {
describe("height") {
it("should return 0 when there are no buttons") {
let view = AuthCollectionView(connections: [], mode: .expanded(isLogin: true), insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
expect(view.height) == 0
}
it("should just use the button size if there is only one button") {
let view = AuthCollectionView(connections: [SocialConnection(name: "social", style: .Facebook)], mode: .expanded(isLogin: true), insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
expect(view.height) == 50
}
it("should add padding") {
let max = Int(arc4random_uniform(15)) + 2
let connections = mockConnections(count: max)
let view = AuthCollectionView(connections: connections, mode: .expanded(isLogin: true), insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
let expected = (max * 50) + (max * 8) - 8
expect(view.height) == CGFloat(expected)
}
}
}
context("compact") {
describe("height") {
it("should return 0 when there are no buttons") {
let view = AuthCollectionView(connections: [], mode: .compact, insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
expect(view.height) == 0
}
it("should just use the button size if there is only one button") {
let view = AuthCollectionView(connections: [SocialConnection(name: "social", style: .Facebook)], mode: .compact, insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
expect(view.height) == 50
}
it("should just use the button size for less than 6 buttons") {
let connections: [OAuth2Connection] = mockConnections(count: 5)
let view = AuthCollectionView(connections: connections, mode: .compact, insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
expect(view.height) == 50
}
it("should add padding per row") {
let count = Int(arc4random_uniform(15)) + 2
let rows = Int(ceil(Double(count) / 5))
let connections = mockConnections(count: count)
let view = AuthCollectionView(connections: connections, mode: .compact, insets: UIEdgeInsets.zero, customStyle: [:]) { _ in }
let expected = (rows * 50) + (rows * 8) - 8
expect(view.height) == CGFloat(expected)
}
}
}
describe("styling") {
func styleButton(_ style: AuthStyle, isLogin: Bool = true) -> AuthButton {
return oauth2Buttons(forConnections: [SocialConnection(name: "social0", style: style)], customStyle: [:], isLogin: isLogin, onAction: {_ in }).first!
}
it("should set proper title") {
let button = styleButton(.Facebook)
expect(button.title) == "Sign in with Facebook"
}
it("should set proper title") {
let button = styleButton(.Facebook, isLogin: false)
expect(button.title) == "Sign up with Facebook"
}
it("should set color") {
let style = AuthStyle.Facebook
let button = styleButton(style)
expect(button.normalColor) == style.normalColor
expect(button.highlightedColor) == style.highlightedColor
}
it("should set border color") {
let style = AuthStyle.Google
let button = styleButton(style)
expect(button.borderColor) == style.borderColor
}
it("should set icon") {
let style = AuthStyle.Facebook
let button = styleButton(style)
expect(button.icon).toNot(beNil())
}
it("should use custom style") {
let style = ["steam": AuthStyle(name: "Steam", color: .white)]
let button = oauth2Buttons(forConnections: [SocialConnection(name: "steam", style: AuthStyle(name: "steam"))], customStyle: style, isLogin: true, onAction: {_ in }).first!
expect(button.title) == "Sign in with Steam"
expect(button.color) == UIColor.white
}
}
}
}
func mockConnections(count: Int) -> [OAuth2Connection] {
return (1...count).map { _ -> OAuth2Connection in return SocialConnection(name: "social", style: .Facebook) }
}
| mit |
s0mmer/TodaysReactiveMenu | TodaysReactiveMenuTests/TodaysReactiveMenuTests.swift | 1 | 612 | //
// TodaysReactiveMenuTests.swift
// TodaysReactiveMenuTests
//
// Created by Steffen Damtoft Sommer on 24/05/15.
// Copyright (c) 2015 steffendsommer. All rights reserved.
//
import UIKit
import XCTest
class TodaysReactiveMenuTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| mit |
bencallis/PMKVObserver | PMKVObserverTests/KVOHelper.swift | 1 | 1296 | //
// KVOHelper.swift
// PMKVObserver
//
// Created by Kevin Ballard on 11/19/15.
// Copyright © 2015 Postmates. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
import Foundation
public final class KVOHelper: NSObject {
public dynamic var str: String = ""
public dynamic var optStr: String?
public dynamic var int: Int = 0
public dynamic var bool: Bool = false
public dynamic var num: NSNumber = 0
public dynamic var optNum: NSNumber?
public dynamic var ary: [String] = []
public dynamic var optAry: [String]?
public dynamic var firstName: String?
public dynamic var lastName: String?
@objc public var computed: String? {
switch (firstName, lastName) {
case let (a?, b?): return "\(a) \(b)"
case let (a?, nil): return a
case let (nil, b?): return b
case (nil, nil): return nil
}
}
@objc public static let keyPathsForValuesAffectingComputed: Set<String> = ["firstName", "lastName"]
}
| apache-2.0 |
cheebow/PlaceholderTextView | Example/PlaceholderTextViewTests/PlaceholderTextViewTests.swift | 1 | 929 | //
// PlaceholderTextViewTests.swift
// PlaceholderTextViewTests
//
// Created by CHEEBOW on 2015/07/24.
// Copyright (c) 2015年 CHEEBOW. All rights reserved.
//
import UIKit
import XCTest
class PlaceholderTextViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
delba/Sorry | Source/Supporting Files/Utilities.swift | 2 | 4472 | //
// Utilities.swift
//
// Copyright (c) 2015-2019 Damien (http://delba.io)
//
// 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.
//
extension UIApplication {
private var topViewController: UIViewController? {
var vc = keyWindow?.rootViewController
while let presentedVC = vc?.presentedViewController {
vc = presentedVC
}
return vc
}
func present(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
topViewController?.present(viewController, animated: animated, completion: completion)
}
}
extension Bundle {
var name: String {
return object(forInfoDictionaryKey: "CFBundleName") as? String ?? ""
}
}
extension UIControl.State: Hashable {
public var hashValue: Int { return Int(rawValue) }
}
@propertyWrapper
struct UserDefault<T> {
let key: String
let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}
set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
struct Defaults {
@UserDefault("permission.requestedNotifications", defaultValue: false)
static var requestedNotifications: Bool
@UserDefault("permission.requestedLocationAlwaysWithWhenInUse", defaultValue: false)
static var requestedLocationAlwaysWithWhenInUse: Bool
@UserDefault("permission.requestedMotion", defaultValue: false)
static var requestedMotion: Bool
@UserDefault("permission.requestedBluetooth", defaultValue: false)
static var requestedBluetooth: Bool
@UserDefault("permission.statusBluetooth", defaultValue: nil)
static var statusBluetooth: PermissionStatus?
@UserDefault("permission.stateBluetoothManagerDetermined", defaultValue: false)
static var stateBluetoothManagerDetermined: Bool
}
extension String {
static let locationWhenInUseUsageDescription = "NSLocationWhenInUseUsageDescription"
static let locationAlwaysUsageDescription = "NSLocationAlwaysUsageDescription"
static let microphoneUsageDescription = "NSMicrophoneUsageDescription"
static let speechRecognitionUsageDescription = "NSSpeechRecognitionUsageDescription"
static let photoLibraryUsageDescription = "NSPhotoLibraryUsageDescription"
static let cameraUsageDescription = "NSCameraUsageDescription"
static let mediaLibraryUsageDescription = "NSAppleMusicUsageDescription"
static let siriUsageDescription = "NSSiriUsageDescription"
}
extension Selector {
static let tapped = #selector(PermissionButton.tapped(_:))
static let highlight = #selector(PermissionButton.highlight(_:))
static let settingsHandler = #selector(DeniedAlert.settingsHandler)
}
extension OperationQueue {
convenience init(_ qualityOfService: QualityOfService) {
self.init()
self.qualityOfService = qualityOfService
}
}
extension NotificationCenter {
func addObserver(_ observer: AnyObject, selector: Selector, name: NSNotification.Name?) {
addObserver(observer, selector: selector, name: name!, object: nil)
}
func removeObserver(_ observer: AnyObject, name: NSNotification.Name?) {
removeObserver(observer, name: name, object: nil)
}
}
| mit |
zqqf16/SYM | SYM/Convertor.swift | 1 | 10857 | // The MIT License (MIT)
//
// Copyright (c) 2022 zqqf16
//
// 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 SwiftyJSON
protocol Convertor {
static func match(_ content: String) -> Bool
func convert(_ content: String) -> String
}
func convertor(for content: String) -> Convertor? {
if AppleJsonConvertor.match(content) {
return AppleJsonConvertor()
}
if KeepJsonConvertor.match(content) {
return KeepJsonConvertor()
}
return nil
}
extension String {
func format(_ json: JSON...) -> Self {
return String(format: self, arguments: json.map { $0.stringValue })
}
}
extension Line {
func format(_ json: JSON...) -> Self {
let value = String(format: self.value, arguments: json.map { $0.stringValue })
return Line(value)
}
}
struct AppleJsonConvertor: Convertor {
static func match(_ content: String) -> Bool {
let components = split(content)
guard components.header != nil,
let payload = components.payload
else {
return false
}
return payload["coalitionName"].string != nil
|| payload["crashReporterKey"].string != nil
}
private static func split(_ content: String) -> (header: JSON?, payload: JSON?) {
var header: JSON?
var payload: JSON?
var lines = content.components(separatedBy: "\n")
if let headerData = lines.removeFirst().data(using: .utf8) {
header = try? JSON(data: headerData)
}
if let payloadData = lines.joined(separator: "\n").data(using: .utf8) {
payload = try? JSON(data: payloadData)
}
return (header, payload)
}
struct Frame: ContentComponent {
var string: String
init(_ frame: JSON, index: Int, binaryImages: JSON) {
let image = binaryImages[frame["imageIndex"].intValue]
let address = frame["imageOffset"].intValue + image["base"].intValue
// 0 Foundation 0x182348144 xxx + 200
string = Line {
String(index).padding(length: 4)
image["name"].stringValue.padding(length: 39)
"0x%llx ".format(address)
if let symbol = frame["symbol"].string, let symbolLocation = frame["symbolLocation"].int {
"\(symbol) + \(symbolLocation)"
} else {
"0x%llx + %d".format(image["base"].int64Value, frame["imageOffset"].intValue)
}
if let sourceFile = frame["sourceFile"].string, let sourceLine = frame["sourceLine"].int {
" (\(sourceFile):\(sourceLine))"
}
}.string
}
}
struct Thread: ContentComponent {
var string: String
init(_ thread: JSON, index: Int, binaryImages: JSON) {
string = String(builder: {
if thread["name"].string != nil {
Line {
"Thread \(index) name: \(thread["name"].stringValue)"
if let queue = thread["queue"].string {
" Dispatch queue: \(queue)"
}
}
} else if let queue = thread["queue"].string {
Line("Thread \(index) name: Dispatch queue: \(queue)")
}
if thread["triggered"].boolValue {
Line("Thread \(index) Crashed:")
} else {
Line("Thread \(index):")
}
for (frameIndex, frame) in thread["frames"].arrayValue.enumerated() {
Frame(frame, index: frameIndex, binaryImages: binaryImages)
}
Line.empty
})
}
}
struct Image: ContentComponent {
var string: String
init(_ image: JSON) {
string = Line {
"0x%llx - 0x%llx "
.format(image["base"].intValue, image["base"].intValue + image["size"].intValue - 1)
"%@ %@ "
.format(image["name"].stringValue, image["arch"].stringValue)
"<%@> %@"
.format(image["uuid"].stringValue.replacingOccurrences(of: "-", with: ""), image["path"].stringValue)
}.string
}
}
struct Registers: ContentComponent {
var string: String
init(_ payload: JSON) {
let threads = payload["threads"].arrayValue
let triggeredThread = threads.first { thread in
thread["triggered"].boolValue
}
if triggeredThread == nil {
string = ""
return
}
let triggeredIndex = payload["faultingThread"].intValue
let cpu = payload["cpuType"].stringValue
var content = "Thread \(triggeredIndex) crashed with ARM Thread State (\(cpu)):\n"
let threadState = triggeredThread!["threadState"]
let x = threadState["x"].arrayValue
for (index, reg) in x.enumerated() {
let id = "x\(index)".padding(length: 6, atLeft: true)
content.append("\(id): 0x%016X".format(reg["value"].int64Value))
if index % 4 == 3 {
content.append("\n")
}
}
var index = x.count % 4
for name in ["fp", "lr", "sp", "pc", "cpsr", "far", "esr"] {
let value = threadState[name]["value"].int64Value
let desc = threadState[name]["description"].stringValue
let id = "\(name)".padding(length: 6, atLeft: true)
content.append("\(id): 0x%016X".format(value))
if desc.count > 0 {
content.append(" \(desc)")
}
if index % 3 == 2 {
content.append("\n")
}
index += 1
}
content.append("\n")
string = content
}
}
func convert(_ content: String) -> String {
let components = Self.split(content)
guard let header = components.header,
let payload = components.payload
else {
return content
}
let _P: (String) -> String = { key in
payload[key].stringValue
}
let _H: (String) -> String = { key in
header[key].stringValue
}
return String(builder: {
Line("Incident Identifier: %@").format(_H("incident_id"))
Line("CrashReporter Key: %@").format(_P("crashReporterKey"))
Line("Hardware Model: %@").format(_P("modelCode"))
Line("Process: %@ [%@]").format(_P("procName"), _P("pid"))
Line("Path: %@").format(_P("procPath"))
Line("Identifier: %@").format(_P("coalitionName"))
Line("Version: %@ (%@)").format(_H("app_version"), _H("build_version"))
Line("Code Type: %@").format(_P("cpuType"))
Line("Role: %@").format(_P("procRole"))
Line("Parent Process: %@ [%@]").format(_P("parentProc"), _P("parentPid"))
Line("Coalition: %@ [%@]").format(_P("coalitionName"), _P("coalitionID"))
Line.empty
Line("Date/Time: %@").format(_P("captureTime"))
Line("Launch Time: %@").format(_P("procLaunch"))
Line("OS Version: %@").format(_H("os_version"))
Line("Release Type: %@").format(payload["osVersion"]["releaseType"].stringValue)
Line("Baseband Version: %@").format(_P("basebandVersion"))
Line("Report Version: 104")
Line.empty
Line("Exception Type: %@ (%@)")
.format(payload["exception"]["type"].stringValue, payload["exception"]["signal"].stringValue)
Line("Exception Codes: %@").format(payload["exception"]["codes"].stringValue)
if payload["isCorpse"].boolValue {
Line("Exception Note: EXC_CORPSE_NOTIFY")
}
Line("Termination Reason: %@ %@")
.format(payload["termination"]["namespace"].stringValue, payload["termination"]["code"].stringValue)
Line(payload["termination"]["details"][0].stringValue)
Line("Triggered by Thread: %@".format(_P("faultingThread")))
if let asi = payload["asi"].dictionary {
Line.empty
Line("Application Specific Information:")
for (_, value) in asi {
for item in value.arrayValue {
Line(item.stringValue)
}
}
}
if let ktriageinfo = payload["ktriageinfo"].string {
Line.empty
Line("Kernel Triage: \n\(ktriageinfo)")
}
Line.empty
let binaryImages = payload["usedImages"]
let threads = payload["threads"].arrayValue
for (index, thread) in threads.enumerated() {
Thread(thread, index: index, binaryImages: binaryImages)
}
Line.empty
Registers(payload)
Line.empty
if payload["vmSummary"].string != nil {
Line.empty
Line("VM Region Info: \n\(_P("vmSummary"))")
}
Line.empty
Line("Binary Images:")
for image in binaryImages.arrayValue {
Image(image)
}
Line.empty
Line("EOF")
Line.empty
})
}
}
| mit |
Viddi/ios-process-button | ProcessButton/ProcessButton/ProcessButton.swift | 1 | 1112 | //
// ProcessButton.swift
// ProcessButton
//
// Created by Vidar Ottosson on 2/7/15.
// Copyright (c) 2015 Vidar Ottosson. All rights reserved.
//
import UIKit
class ProcessButton: FlatButton, FlatButtonDelegate {
let LineHeight: CGFloat = 4.0
var processView: ProcessView!
override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
override func layoutSubviews() {
super.layoutSubviews()
processView.frame = CGRect(x: 0, y: frame.height - LineHeight, width: frame.width, height: LineHeight)
}
private func prepareView() {
delegate = self
processView = ProcessView(frame: CGRect(x: 0, y: frame.height - LineHeight, width: frame.width, height: LineHeight))
addSubview(processView)
}
func animate(shouldAnimate: Bool) {
if shouldAnimate {
enabled = false
} else {
enabled = true
}
processView.animate(shouldAnimate)
}
func showSuccess() {
animate(false)
}
func showError() {
animate(false)
}
}
| mit |
HongliYu/firefox-ios | ClientTests/ActivityStreamTests.swift | 1 | 1740 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import XCTest
@testable import Client
import Shared
import Storage
import Deferred
import SyncTelemetry
class ActivityStreamTests: XCTestCase {
var profile: MockProfile!
var panel: ActivityStreamPanel!
override func setUp() {
super.setUp()
self.profile = MockProfile()
self.panel = ActivityStreamPanel(profile: profile)
}
func testDeletionOfSingleSuggestedSite() {
let siteToDelete = panel.defaultTopSites()[0]
panel.hideURLFromTopSites(siteToDelete)
let newSites = panel.defaultTopSites()
XCTAssertFalse(newSites.contains(siteToDelete, f: { (a, b) -> Bool in
return a.url == b.url
}))
}
func testDeletionOfAllDefaultSites() {
let defaultSites = panel.defaultTopSites()
defaultSites.forEach({
panel.hideURLFromTopSites($0)
})
let newSites = panel.defaultTopSites()
XCTAssertTrue(newSites.isEmpty)
}
}
fileprivate class MockTopSitesHistory: MockableHistory {
let mockTopSites: [Site]
init(sites: [Site]) {
mockTopSites = sites
}
override func getTopSitesWithLimit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return deferMaybe(ArrayCursor(data: mockTopSites))
}
override func getPinnedTopSites() -> Deferred<Maybe<Cursor<Site>>> {
return deferMaybe(ArrayCursor(data: []))
}
override func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
}
| mpl-2.0 |
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind | MiprimeraApp 1.3/MiprimeraApp/AppDelegate.swift | 4 | 2152 | //
// AppDelegate.swift
// MiprimeraApp
//
// Created by Miguel Gutiérrez Moreno on 9/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
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.
}
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:.
}
}
| mit |
tomburns/ios | FiveCalls/FiveCalls/ReportOutcomeOperation.swift | 1 | 1572 | //
// ReportOutcomeOperation.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/4/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class ReportOutcomeOperation : BaseOperation {
//Input properties
var log: ContactLog
//Output properties
var httpResponse: HTTPURLResponse?
var error: Error?
init(log: ContactLog) {
self.log = log
}
override func execute() {
let config = URLSessionConfiguration.default
let session = URLSessionProvider.buildSession(configuration: config)
let url = URL(string: "https://5calls.org/report")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let query = "result=\(log.outcome)&contactid=\(log.contactId)&issueid=\(log.issueId)&phone=\(log.phone)"
guard let data = query.data(using: .utf8) else {
print("error creating HTTP POST body")
return
}
request.httpBody = data
let task = session.dataTask(with: request) { (data, response, error) in
if let e = error {
self.error = e
} else {
let http = response as! HTTPURLResponse
self.httpResponse = http
if let _ = data, http.statusCode == 200 {
print("sent report successfully")
}
}
self.finish()
}
task.resume()
}
}
| mit |
lorentey/swift | test/Migrator/fixit_flatMap.swift | 19 | 693 | // RUN: %target-swift-frontend -typecheck %s -swift-version 4
// RUN: %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t.result -swift-version 4
// RUN: diff -u %s.expected %t.result
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos
func migrate<T, U: Sequence, V: Collection>(lseq: LazySequence<T>, lcol: LazyCollection<T>, seq: U, col: V, test: Bool) {
_ = lseq.flatMap { test ? nil : $0 }
_ = lcol.flatMap { test ? nil : $0 }
_ = seq.flatMap { test ? nil : $0 }
_ = col.flatMap { test ? nil : "\($0)" }
_ = lseq.flatMap { [$0, $0] }
_ = lcol.flatMap { [$0, $0] }
_ = seq.flatMap { [$0, $0] }
_ = col.flatMap { "\($0)" }
}
| apache-2.0 |
narner/AudioKit | Examples/macOS/AudioUnitManager/AudioUnitManager/AudioUnitGenericView.swift | 1 | 2322 | //
// GenericAudioUnitView.swift
//
// Created by Ryan Francesconi on 6/27/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Cocoa
import AVFoundation
/// Creates a simple list of parameters linked to sliders
class AudioUnitGenericView: NSView {
open var name: String = ""
open var preferredWidth: CGFloat = 360
open var preferredHeight: CGFloat = 400
override var isFlipped: Bool {
return true
}
open var opaqueBackground: Bool = true
open var backgroundColor: NSColor = NSColor.darkGray {
didSet {
needsDisplay = true
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if opaqueBackground {
backgroundColor.setFill()
let rect = NSMakeRect(0, 0, bounds.width, bounds.height)
// let rectanglePath = NSBezierPath(roundedRect: rect, xRadius: 0, yRadius: 0)
// let rectanglePath =
rect.fill()
}
}
convenience init(au: AVAudioUnit) {
self.init()
wantsLayer = true
if let cname = au.auAudioUnit.componentName {
name = cname
}
let nameField = NSTextField()
nameField.isSelectable = false
nameField.isBordered = false
nameField.isEditable = false
nameField.alignment = .center
nameField.font = NSFont.boldSystemFont(ofSize: 12)
nameField.textColor = NSColor.white
nameField.backgroundColor = NSColor.white.withAlphaComponent(0)
nameField.stringValue = name
nameField.frame = NSRect(x: 0, y: 4, width: preferredWidth, height: 20)
addSubview(nameField)
guard let tree = au.auAudioUnit.parameterTree else { return }
var y = 5
for param in tree.allParameters {
y += 24
let slider = AudioUnitParamSlider(audioUnit: au, param: param )
slider.setFrameOrigin(NSPoint(x: 10, y: y))
addSubview(slider)
DispatchQueue.main.async {
slider.updateValue()
}
}
preferredHeight = CGFloat(y + 50)
frame.size = NSSize(width: preferredWidth, height: preferredHeight)
}
func handleChange(_ sender: NSSlider) {
//Swift.print(sender.doubleValue)
}
}
| mit |
hole19/media-viewer | H19MediaViewerTests/TapGestureRecognizerMock.swift | 1 | 589 | import UIKit
class TapGestureRecogniserMock: UITapGestureRecognizer {
// settable properties
var locationInViewToReturn = CGPoint.zero
override func location(in view: UIView?) -> CGPoint {
return locationInViewToReturn
}
var requireGestureRecognizerToFailCallCount = 0
var requireGestureRecognizerToFailRecogniser: UIGestureRecognizer?
override func require(toFail otherGestureRecognizer: UIGestureRecognizer) {
requireGestureRecognizerToFailCallCount += 1
requireGestureRecognizerToFailRecogniser = otherGestureRecognizer
}
}
| mit |
alblue/swift | test/SILOptimizer/exclusivity_static_diagnostics_inlined.swift | 2 | 1330 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enforce-exclusivity=none -emit-sil -Onone %s -o %t/Onone.sil
// RUN: %target-sil-opt %t/Onone.sil -inline -assume-parsing-unqualified-ownership-sil -o %t/inlined.sil
// RUN: %FileCheck %s --check-prefix=INLINE < %t/inlined.sil
// RUN: %target-sil-opt -enable-sil-verify-all %t/inlined.sil -enforce-exclusivity=unchecked -diagnose-static-exclusivity -assume-parsing-unqualified-ownership-sil -o /dev/null
public protocol SomeP {
var someV: Int { get set }
}
public func assignNonConflict(_ p: inout SomeP) {
p.someV = p.someV
}
struct Some : SomeP {
var someV = 0
}
// After inlining we have nested access to an existential property.
// The other access passes the existential @inout.
//
// The passed argument is accessed again inside assignNonConflict to unwrap the
// existential.
//
// INLINE-LABEL: $s5Onone16testNestedAccessyyF
// INLINE: [[OUTER:%.*]] = begin_access [modify] [static] %0 : $*SomeP
// INLINE: [[INNERREAD:%.*]] = begin_access [read] [static] [[OUTER]] : $*SomeP
// INLINE: [[INNERMOD:%.*]] = begin_access [modify] [static] [[OUTER]] : $*SomeP
// INLINE: %{{.*}} = open_existential_addr mutable_access [[INNERMOD]] : $*SomeP to $*@opened("{{.*}}") SomeP
//
public func testNestedAccess() {
var s: SomeP = Some()
assignNonConflict(&s)
}
| apache-2.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Settings/ChangingDetails/Views/AccessoryTextFieldCell.swift | 1 | 1839 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
final class AccessoryTextFieldCell: UITableViewCell {
let textField = ValidatedTextField()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setupViews()
createConstraints()
backgroundColor = .clear
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
contentView.addSubview(textField)
}
private func createConstraints() {
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
textField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
textField.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 8)
])
}
}
| gpl-3.0 |
benlangmuir/swift | test/multifile/default-arguments/two-modules/Inputs/library2.swift | 41 | 46 | public func hasDefaultArgument(x: Int = 0) {}
| apache-2.0 |
benlangmuir/swift | test/SILOptimizer/zeroInitializer.swift | 21 | 1116 | // RUN: %target-swift-frontend -O -parse-stdlib -emit-ir -module-name ZeroInit -verify %s | %FileCheck %s
import Swift
@frozen
public struct TestInt {
@usableFromInline
var _value : Builtin.Int32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
@frozen
public struct TestFloat {
@usableFromInline
var _value : Builtin.FPIEEE32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
@frozen
public struct TestVector {
@usableFromInline
var _value : Builtin.Vec4xFPIEEE32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
public struct Foo {
public static var x : TestInt = TestInt()
public static var y : TestFloat = TestFloat()
public static var z : TestVector = TestVector()
}
// CHECK: @"$s8ZeroInit3FooV1xAA7TestIntVvpZ" ={{.*}} global %T8ZeroInit7TestIntV zeroinitializer
// CHECK: @"$s8ZeroInit3FooV1yAA9TestFloatVvpZ" ={{.*}} global %T8ZeroInit9TestFloatV zeroinitializer
// CHECK: @"$s8ZeroInit3FooV1zAA10TestVectorVvpZ" ={{.*}} global %T8ZeroInit10TestVectorV zeroinitializer
// CHECK-NOT: swift_once
| apache-2.0 |
benlangmuir/swift | test/IRGen/async/unreachable.swift | 12 | 418 | // RUN: %target-swift-frontend -primary-file %s -g -emit-ir -disable-availability-checking -disable-llvm-optzns -disable-swift-specific-llvm-optzns | %FileCheck %s
// REQUIRES: concurrency
// CHECK: call i1 (i8*, i1, ...) @llvm.coro.end.async
func foo() async -> Never {
await bar()
fatalError()
}
// CHECK: call i1 (i8*, i1, ...) @llvm.coro.end.async
func bar() async -> Never {
await foo()
fatalError()
}
| apache-2.0 |
PureSwift/Cacao | Sources/Cacao/UIControl.swift | 1 | 8251 | //
// UIControl.swift
// Cacao
//
// Created by Alsey Coleman Miller on 6/7/17.
//
import class Foundation.NSNull
/// The base class for controls, which are visual elements that convey
/// a specific action or intention in response to user interactions.
open class UIControl: UIView {
// MARK: - Configuring the Control’s Attributes
/// The state of the control, specified as a bitmask value.
///
/// The value of this property is a bitmask of the constants in the UIControlState type.
/// A control can be in more than one state at a time.
/// For example, it can be focused and highlighted at the same time.
/// You can also get the values for individual states using the properties of this class.
open var state: UIControlState { return .normal }
// MARK: - Accessing the Control’s Targets and Actions
/// Target-Action pairs
private var targetActions = [Target: [UIControlEvents: [Selector]]]()
/// Associates a target object and action method with the control.
public func addTarget(_ target: AnyHashable?, action: Selector, for controlEvents: UIControlEvents) {
let target = Target(target)
targetActions[target, default: [:]][controlEvents, default: []].append(action)
}
/// Stops the delivery of events to the specified target object.
public func removeTarget(_ target: AnyHashable?, action: Selector, for controlEvents: UIControlEvents) {
let target = Target(target)
guard let index = targetActions[target, default: [:]][controlEvents, default: []].index(of: action)
else { return }
targetActions[target, default: [:]][controlEvents, default: []].remove(at: index)
}
/// Returns the actions performed on a target object when the specified event occurs.
///
/// - Parameter target: The target object—that is, an object that has an action method associated with this control.
/// You must pass an explicit object for this method to return a meaningful result.
/// Specifying `nil` always returns `nil`.
/// - Parameter controlEvent: A single control event constant representing the event
/// for which you want the list of action methods.
/// For a list of possible constants, see `UIControlEvents`.
public func actions(forTarget target: AnyHashable?, forControlEvent controlEvent: UIControlEvents) -> [Selector]? {
guard let targetValue = target
else { return nil }
let target = Target(targetValue)
return targetActions[target, default: [:]][controlEvent, default: []]
}
/// Returns the events for which the control has associated actions.
///
/// - Returns: A bitmask of constants indicating the events for which this control has associated actions.
public var allControlEvents: UIControlEvents {
return targetActions
.reduce([UIControlEvents](), { $0 + Array($1.value.keys) })
.reduce(UIControlEvents(), { $0.union($1) })
}
/// Returns all target objects associated with the control.
///
/// - Returns: A set of all target objects associated with the control.
/// The returned set may include one or more `NSNull` objects to indicate actions that are dispatched to the responder chain.
public var allTargets: Set<AnyHashable> {
let targets = targetActions.keys.map { $0.value ?? NSNull() as AnyHashable }
return Set(targets)
}
// MARK: - Triggering Actions
/// Calls the specified action method.
public func sendAction(_ action: Selector, to target: AnyHashable?, for event: UIEvent?) {
let target = target ?? (self.next ?? NSNull()) as AnyHashable
action.action(target, self, event)
}
/// Calls the action methods associated with the specified events.
public func sendActions(for controlEvents: UIControlEvents) {
for (target, eventActions) in targetActions {
let actions = eventActions[controlEvents, default: []]
for action in actions {
sendAction(action, to: target.value, for: nil)
}
}
}
}
private extension UIControl {
final class Target: Hashable {
let value: AnyHashable?
init(_ value: AnyHashable? = nil) {
self.value = value
}
var hashValue: Int {
return value?.hashValue ?? 0
}
static func == (lhs: Target, rhs: Target) -> Bool {
return lhs.value == rhs.value
}
}
}
/// Cacao extension since Swift doesn't support ObjC runtime (on non-Darwin platforms)
public struct Selector: Hashable {
public typealias Action = (_ target: AnyHashable, _ sender: AnyObject?, _ event: UIEvent?) -> ()
public let action: Action
public let name: String
public init(name: String, action: @escaping Action) {
self.name = name
self.action = action
}
public var hashValue: Int {
return name.hashValue
}
public static func == (lhs: Selector, rhs: Selector) -> Bool {
return lhs.name == rhs.name
}
}
/// Constants describing the state of a control.
///
/// A control can have more than one state at a time.
/// Controls can be configured differently based on their state.
/// For example, a `UIButton` object can be configured to display one image
/// when it is in its normal state and a different image when it is highlighted.
public struct UIControlState: OptionSet {
public let rawValue: Int
public init(rawValue: Int = 0) {
self.rawValue = rawValue
}
/// The normal, or default state of a control—that is, enabled but neither selected nor highlighted.
public static let normal = UIControlState(rawValue: 0)
public static let highlighted = UIControlState(rawValue: 1 << 0)
public static let disabled = UIControlState(rawValue: 1 << 1)
public static let selected = UIControlState(rawValue: 1 << 2)
public static let focused = UIControlState(rawValue: 1 << 3)
public static let application = UIControlState(rawValue: 0x00FF0000)
}
public struct UIControlEvents: OptionSet {
public let rawValue: Int
public init(rawValue: Int = 0) {
self.rawValue = rawValue
}
public static let touchDown = UIControlEvents(rawValue: 1 << 0)
public static let touchDownRepeat = UIControlEvents(rawValue: 1 << 1)
public static let touchDragInside = UIControlEvents(rawValue: 1 << 2)
public static let touchDragOutside = UIControlEvents(rawValue: 1 << 3)
public static let touchDragEnter = UIControlEvents(rawValue: 1 << 4)
public static let touchDragExit = UIControlEvents(rawValue: 1 << 5)
public static let touchUpInside = UIControlEvents(rawValue: 1 << 6)
public static let touchUpOutside = UIControlEvents(rawValue: 1 << 7)
public static let touchCancel = UIControlEvents(rawValue: 1 << 8)
public static let valueChanged = UIControlEvents(rawValue: 1 << 12)
public static let primaryActionTriggered = UIControlEvents(rawValue: 1 << 13)
public static let editingDidBegin = UIControlEvents(rawValue: 1 << 16)
public static let editingChanged = UIControlEvents(rawValue: 1 << 17)
public static let editingDidEnd = UIControlEvents(rawValue: 1 << 18)
public static let editingDidEndOnExit = UIControlEvents(rawValue: 1 << 19)
public static let allTouchEvents = UIControlEvents(rawValue: 0x00000FFF)
public static let allEditingEvents = UIControlEvents(rawValue: 0x000F0000)
public static let applicationReserved = UIControlEvents(rawValue: 0x0F000000)
public static let systemReserved = UIControlEvents(rawValue: 0xF0000000)
public static let allEvents = UIControlEvents(rawValue: 0xFFFFFFFF)
}
extension UIControlEvents: Hashable {
public var hashValue: Int {
return rawValue
}
}
| mit |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/UserData+CoreDataProperties.swift | 1 | 950 | //
// UserData+CoreDataProperties.swift
// Chula Expo 2017
//
// Created by NOT on 1/11/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
extension UserData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<UserData> {
return NSFetchRequest<UserData>(entityName: "UserData");
}
@NSManaged public var id: String?
@NSManaged public var token: String?
@NSManaged public var name: String?
@NSManaged public var type: String?
@NSManaged public var email: String?
@NSManaged public var gender: String?
@NSManaged public var age: Int16
@NSManaged public var profile: String?
@NSManaged public var school: String?
@NSManaged public var job: String?
@NSManaged public var level: String?
@NSManaged public var year: String?
}
| mit |
primetimer/PrimeFactors | Example/PrimeFactors/AppDelegate.swift | 1 | 2399 | //
// AppDelegate.swift
// PFactors
//
// Created by primetimer on 10/17/2017.
// Copyright (c) 2017 primetimer. All rights reserved.
//
import UIKit
import BigInt
import PrimeFactors
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// let n = BigUInt(1344)
// var d = FactorCache.shared.Divisors(p: n, cancel: nil)
// d.sort()
// for f in d {
// print(String(f))
// }
//
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
parkera/swift-corelibs-foundation | TestFoundation/TestProcess.swift | 1 | 23230 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2015 - 2016, 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestProcess : XCTestCase {
static var allTests: [(String, (TestProcess) -> () throws -> Void)] {
#if os(Android)
return []
#else
return [
("test_exit0" , test_exit0),
("test_exit1" , test_exit1),
("test_exit100" , test_exit100),
("test_sleep2", test_sleep2),
("test_sleep2_exit1", test_sleep2_exit1),
("test_terminationReason_uncaughtSignal", test_terminationReason_uncaughtSignal),
("test_pipe_stdin", test_pipe_stdin),
("test_pipe_stdout", test_pipe_stdout),
("test_pipe_stderr", test_pipe_stderr),
("test_current_working_directory", test_current_working_directory),
("test_pipe_stdout_and_stderr_same_pipe", test_pipe_stdout_and_stderr_same_pipe),
("test_file_stdout", test_file_stdout),
("test_passthrough_environment", test_passthrough_environment),
("test_no_environment", test_no_environment),
("test_custom_environment", test_custom_environment),
("test_run", test_run),
("test_preStartEndState", test_preStartEndState),
("test_interrupt", test_interrupt),
("test_terminate", test_terminate),
("test_suspend_resume", test_suspend_resume),
]
#endif
}
#if !os(Android)
func test_exit0() {
let process = Process()
let executablePath = "/bin/bash"
if #available(OSX 10.13, *) {
process.executableURL = URL(fileURLWithPath: executablePath)
} else {
// Fallback on earlier versions
process.launchPath = executablePath
}
XCTAssertEqual(executablePath, process.launchPath)
process.arguments = ["-c", "exit 0"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_exit1() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "exit 1"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_exit100() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "exit 100"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 100)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_sleep2() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "sleep 2"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_sleep2_exit1() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "sleep 2; exit 1"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_terminationReason_uncaughtSignal() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "kill -TERM $$"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 15)
XCTAssertEqual(process.terminationReason, .uncaughtSignal)
}
func test_pipe_stdin() {
let process = Process()
process.launchPath = "/bin/cat"
let outputPipe = Pipe()
process.standardOutput = outputPipe
let inputPipe = Pipe()
process.standardInput = inputPipe
process.launch()
inputPipe.fileHandleForWriting.write("Hello, 🐶.\n".data(using: .utf8)!)
// Close the input pipe to send EOF to cat.
inputPipe.fileHandleForWriting.closeFile()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
let data = outputPipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .utf8) else {
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string, "Hello, 🐶.\n")
}
func test_pipe_stdout() {
let process = Process()
process.launchPath = "/usr/bin/which"
process.arguments = ["which"]
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
let data = pipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
XCTAssertTrue(string.hasSuffix("/which\n"))
}
func test_pipe_stderr() {
let process = Process()
process.launchPath = "/bin/cat"
process.arguments = ["invalid_file_name"]
let errorPipe = Pipe()
process.standardError = errorPipe
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
let data = errorPipe.fileHandleForReading.availableData
guard let _ = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
// testing the return value of an external process does not port well, and may change.
// XCTAssertEqual(string, "/bin/cat: invalid_file_name: No such file or directory\n")
}
func test_pipe_stdout_and_stderr_same_pipe() {
let process = Process()
process.launchPath = "/bin/cat"
process.arguments = ["invalid_file_name"]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
// Clear the environment to stop the malloc debug flags used in Xcode debug being
// set in the subprocess.
process.environment = [:]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
let data = pipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
// Remove the leading '/bin/' since on macOS '/bin/cat' just outputs 'cat:'
let searchStr = "/bin/"
let errMsg = string.replacingOccurrences(of: searchStr, with: "", options: [.literal, .anchored],
range: searchStr.startIndex..<searchStr.endIndex)
XCTAssertEqual(errMsg, "cat: invalid_file_name: No such file or directory\n")
}
func test_file_stdout() {
let process = Process()
process.launchPath = "/usr/bin/which"
process.arguments = ["which"]
mkstemp(template: "TestProcess.XXXXXX") { handle in
process.standardOutput = handle
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
handle.seek(toFileOffset: 0)
let data = handle.readDataToEndOfFile()
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
XCTAssertTrue(string.hasSuffix("/which\n"))
}
}
func test_passthrough_environment() {
do {
let (output, _) = try runTask(["/usr/bin/env"], environment: nil)
let env = try parseEnv(output)
XCTAssertGreaterThan(env.count, 0)
} catch {
// FIXME: SR-9930 parseEnv fails if an environment variable contains
// a newline.
// XCTFail("Test failed: \(error)")
}
}
func test_no_environment() {
do {
let (output, _) = try runTask(["/usr/bin/env"], environment: [:])
let env = try parseEnv(output)
XCTAssertEqual(env.count, 0)
} catch {
XCTFail("Test failed: \(error)")
}
}
func test_custom_environment() {
do {
let input = ["HELLO": "WORLD", "HOME": "CUPERTINO"]
let (output, _) = try runTask(["/usr/bin/env"], environment: input)
let env = try parseEnv(output)
XCTAssertEqual(env, input)
} catch {
XCTFail("Test failed: \(error)")
}
}
func test_current_working_directory() {
let tmpDir = "/tmp".standardizingPath
let fm = FileManager.default
let previousWorkingDirectory = fm.currentDirectoryPath
// Test that getcwd() returns the currentDirectoryPath
do {
let (pwd, _) = try runTask([xdgTestHelperURL().path, "--getcwd"], currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), tmpDir)
} catch {
XCTFail("Test failed: \(error)")
}
// Test that $PWD by default is set to currentDirectoryPath
do {
let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), tmpDir)
} catch {
XCTFail("Test failed: \(error)")
}
// Test that $PWD can be over-ridden
do {
var env = ProcessInfo.processInfo.environment
env["PWD"] = "/bin"
let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], environment: env, currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), "/bin")
} catch {
XCTFail("Test failed: \(error)")
}
// Test that $PWD can be set to empty
do {
var env = ProcessInfo.processInfo.environment
env["PWD"] = ""
let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], environment: env, currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), "")
} catch {
XCTFail("Test failed: \(error)")
}
XCTAssertEqual(previousWorkingDirectory, fm.currentDirectoryPath)
}
func test_run() {
let fm = FileManager.default
let cwd = fm.currentDirectoryPath
do {
let process = try Process.run(URL(fileURLWithPath: "/bin/sh", isDirectory: false), arguments: ["-c", "exit 123"], terminationHandler: nil)
process.waitUntilExit()
XCTAssertEqual(process.terminationReason, .exit)
XCTAssertEqual(process.terminationStatus, 123)
} catch {
XCTFail("Cant execute /bin/sh: \(error)")
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
do {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/sh", isDirectory: false)
process.arguments = ["-c", "exit 0"]
process.currentDirectoryURL = URL(fileURLWithPath: "/.../_no_such_directory", isDirectory: true)
try process.run()
XCTFail("Executed /bin/sh with invalid currentDirectoryURL")
process.terminate()
process.waitUntilExit()
} catch {
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
do {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/..", isDirectory: false)
process.arguments = []
process.currentDirectoryURL = URL(fileURLWithPath: "/tmp")
try process.run()
XCTFail("Somehow executed a directory!")
process.terminate()
process.waitUntilExit()
} catch {
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
fm.changeCurrentDirectoryPath(cwd)
}
func test_preStartEndState() {
let process = Process()
XCTAssertNil(process.executableURL)
XCTAssertNotNil(process.currentDirectoryURL)
XCTAssertNil(process.arguments)
XCTAssertNil(process.environment)
XCTAssertFalse(process.isRunning)
XCTAssertEqual(process.processIdentifier, 0)
XCTAssertEqual(process.qualityOfService, .default)
process.executableURL = URL(fileURLWithPath: "/bin/cat", isDirectory: false)
_ = try? process.run()
XCTAssertTrue(process.isRunning)
XCTAssertTrue(process.processIdentifier > 0)
process.terminate()
process.waitUntilExit()
XCTAssertFalse(process.isRunning)
XCTAssertTrue(process.processIdentifier > 0)
XCTAssertEqual(process.terminationReason, .uncaughtSignal)
XCTAssertEqual(process.terminationStatus, SIGTERM)
}
func test_interrupt() {
let helper = _SignalHelperRunner()
do {
try helper.start()
} catch {
XCTFail("Cant run xdgTestHelper: \(error)")
return
}
if !helper.waitForReady() {
XCTFail("Didnt receive Ready from sub-process")
return
}
let now = DispatchTime.now().uptimeNanoseconds
let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000)
var count = 3
while count > 0 {
helper.process.interrupt()
guard helper.semaphore.wait(timeout: timeout) == .success else {
helper.process.terminate()
XCTFail("Timedout waiting for signal")
return
}
if helper.sigIntCount == 3 {
break
}
count -= 1
}
helper.process.terminate()
XCTAssertEqual(helper.sigIntCount, 3)
helper.process.waitUntilExit()
let terminationReason = helper.process.terminationReason
XCTAssertEqual(terminationReason, Process.TerminationReason.exit)
let status = helper.process.terminationStatus
XCTAssertEqual(status, 99)
}
func test_terminate() {
let cat = URL(fileURLWithPath: "/bin/cat", isDirectory: false)
guard let process = try? Process.run(cat, arguments: []) else {
XCTFail("Cant run /bin/cat")
return
}
process.terminate()
process.waitUntilExit()
let terminationReason = process.terminationReason
XCTAssertEqual(terminationReason, Process.TerminationReason.uncaughtSignal)
XCTAssertEqual(process.terminationStatus, SIGTERM)
}
func test_suspend_resume() {
let helper = _SignalHelperRunner()
do {
try helper.start()
} catch {
XCTFail("Cant run xdgTestHelper: \(error)")
return
}
if !helper.waitForReady() {
XCTFail("Didnt receive Ready from sub-process")
return
}
let now = DispatchTime.now().uptimeNanoseconds
let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000)
func waitForSemaphore() -> Bool {
guard helper.semaphore.wait(timeout: timeout) == .success else {
helper.process.terminate()
XCTFail("Timedout waiting for signal")
return false
}
return true
}
XCTAssertTrue(helper.process.isRunning)
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.isRunning)
XCTAssertTrue(helper.process.resume())
if waitForSemaphore() == false { return }
XCTAssertEqual(helper.sigContCount, 1)
XCTAssertTrue(helper.process.resume())
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
XCTAssertEqual(helper.sigContCount, 1)
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
if waitForSemaphore() == false { return }
helper.process.suspend()
helper.process.resume()
if waitForSemaphore() == false { return }
XCTAssertEqual(helper.sigContCount, 3)
helper.process.terminate()
helper.process.waitUntilExit()
XCTAssertFalse(helper.process.isRunning)
XCTAssertFalse(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
XCTAssertTrue(helper.process.resume())
}
#endif
}
private enum Error: Swift.Error {
case TerminationStatus(Int32)
case UnicodeDecodingError(Data)
case InvalidEnvironmentVariable(String)
}
// Run xdgTestHelper, wait for 'Ready' from the sub-process, then signal a semaphore.
// Read lines from a pipe and store in a queue.
class _SignalHelperRunner {
let process = Process()
let semaphore = DispatchSemaphore(value: 0)
private let outputPipe = Pipe()
private let sQueue = DispatchQueue(label: "signal queue")
private var gotReady = false
private var bytesIn = Data()
private var _sigIntCount = 0
private var _sigContCount = 0
var sigIntCount: Int { return sQueue.sync { return _sigIntCount } }
var sigContCount: Int { return sQueue.sync { return _sigContCount } }
init() {
process.executableURL = xdgTestHelperURL()
process.environment = ProcessInfo.processInfo.environment
process.arguments = ["--signal-test"]
process.standardOutput = outputPipe.fileHandleForWriting
outputPipe.fileHandleForReading.readabilityHandler = { [weak self] fh in
if let strongSelf = self {
let newLine = UInt8(ascii: "\n")
strongSelf.bytesIn.append(fh.availableData)
if strongSelf.bytesIn.isEmpty {
return
}
// Split the incoming data into lines.
while let index = strongSelf.bytesIn.firstIndex(of: newLine) {
if index >= strongSelf.bytesIn.startIndex {
// don't include the newline when converting to string
let line = String(data: strongSelf.bytesIn[strongSelf.bytesIn.startIndex..<index], encoding: String.Encoding.utf8) ?? ""
strongSelf.bytesIn.removeSubrange(strongSelf.bytesIn.startIndex...index)
if strongSelf.gotReady == false && line == "Ready" {
strongSelf.semaphore.signal()
strongSelf.gotReady = true;
}
else if strongSelf.gotReady == true {
if line == "Signal: SIGINT" {
strongSelf._sigIntCount += 1
strongSelf.semaphore.signal()
}
else if line == "Signal: SIGCONT" {
strongSelf._sigContCount += 1
strongSelf.semaphore.signal()
}
}
}
}
}
}
}
deinit {
process.terminate()
process.waitUntilExit()
}
func start() throws {
try process.run()
}
func waitForReady() -> Bool {
let now = DispatchTime.now().uptimeNanoseconds
let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000)
guard semaphore.wait(timeout: timeout) == .success else {
process.terminate()
return false
}
return true
}
}
#if !os(Android)
internal func runTask(_ arguments: [String], environment: [String: String]? = nil, currentDirectoryPath: String? = nil) throws -> (String, String) {
let process = Process()
var arguments = arguments
process.launchPath = arguments.removeFirst()
process.arguments = arguments
// Darwin Foundation doesnt allow .environment to be set to nil although the documentation
// says it is an optional. https://developer.apple.com/documentation/foundation/process/1409412-environment
if let e = environment {
process.environment = e
}
if let directoryPath = currentDirectoryPath {
process.currentDirectoryPath = directoryPath
}
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
var stdoutData = Data()
stdoutPipe.fileHandleForReading.readabilityHandler = { fh in
stdoutData.append(fh.availableData)
}
var stderrData = Data()
stderrPipe.fileHandleForReading.readabilityHandler = { fh in
stderrData.append(fh.availableData)
}
try process.run()
process.waitUntilExit()
stdoutPipe.fileHandleForReading.readabilityHandler = nil
stderrPipe.fileHandleForReading.readabilityHandler = nil
// Drain any data remaining in the pipes
#if DARWIN_COMPATIBILITY_TESTS
// Use old API for now
stdoutData.append(stdoutPipe.fileHandleForReading.availableData)
stderrData.append(stderrPipe.fileHandleForReading.availableData)
#else
if let d = try stdoutPipe.fileHandleForReading.readToEnd() {
stdoutData.append(d)
}
if let d = try stderrPipe.fileHandleForReading.readToEnd() {
stderrData.append(d)
}
#endif
guard process.terminationStatus == 0 else {
throw Error.TerminationStatus(process.terminationStatus)
}
guard let stdout = String(data: stdoutData, encoding: .utf8) else {
throw Error.UnicodeDecodingError(stdoutData)
}
guard let stderr = String(data: stderrData, encoding: .utf8) else {
throw Error.UnicodeDecodingError(stderrData)
}
return (stdout, stderr)
}
private func parseEnv(_ env: String) throws -> [String: String] {
var result = [String: String]()
for line in env.components(separatedBy: "\n") where line != "" {
guard let range = line.range(of: "=") else {
throw Error.InvalidEnvironmentVariable(line)
}
result[String(line[..<range.lowerBound])] = String(line[range.upperBound...])
}
return result
}
#endif
| apache-2.0 |
Mindera/Alicerce | Tests/AlicerceTests/Extensions/UIKit/UIViewControllerTestCase.swift | 1 | 1717 | import XCTest
import UIKit
@testable import Alicerce
final class UIViewControllerTestCase: XCTestCase {
func testEmbedIn_UsingAUIViewController_ItShouldReturnAUINavigationControllerWithSelfAsRoot() {
let rootViewController = UIViewController()
let navigationController = rootViewController.embedInNavigationController()
XCTAssertNotNil(navigationController.viewControllers.first)
XCTAssertEqual(navigationController.viewControllers.first!, rootViewController)
}
func testEmbedIn_WithAUINavigationControllerSubclass_ItShouldReturnTheSubclassNavigationControllerWithSelfAsRoot() {
class CustomNavigationController: UINavigationController {}
let viewController = UIViewController()
let navigationController = viewController.embedInNavigationController(withType: CustomNavigationController.self)
XCTAssertNotNil(navigationController.viewControllers.first)
XCTAssertEqual(navigationController.viewControllers.first!, viewController)
}
func testTabBarItem_WithTwoImages_ItShouldSetBothImages() {
let viewController = UIViewController()
let mrMinder = imageFromFile(withName: "mr-minder", type: "png")
viewController.tabBarItem(withSelectedImage: mrMinder, unselectedImage: mrMinder)
let mrMinderData = mrMinder.pngData()
XCTAssertNotNil(viewController.tabBarItem.image)
XCTAssertNotNil(viewController.tabBarItem.selectedImage)
XCTAssertEqual(viewController.tabBarItem.image!.pngData(), mrMinderData)
XCTAssertEqual(viewController.tabBarItem.selectedImage!.pngData(), mrMinderData)
}
}
| mit |
Ehrippura/firefox-ios | Storage/ThirdParty/SwiftData.swift | 1 | 61859 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* This is a heavily modified version of SwiftData.swift by Ryan Fowler
* This has been enhanced to support custom files, correct binding, versioning,
* and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and
* to force callers to request a connection before executing commands. Database creation helpers, savepoint
* helpers, image support, and other features have been removed.
*/
// SwiftData.swift
//
// Copyright (c) 2014 Ryan Fowler
//
// 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 UIKit
import Deferred
import Shared
import XCGLogger
private let DatabaseBusyTimeout: Int32 = 3 * 1000
private let log = Logger.syncLogger
enum SQLiteDBConnectionCreatedResult {
case success
case failure
case needsRecovery
}
// SQLite standard error codes when the DB file is locked, busy or the disk is
// full. These error codes indicate that any issues with writing to the database
// are temporary and we should not wipe out and re-create the database file when
// we encounter them.
enum SQLiteDBRecoverableError: Int {
case Busy = 5
case Locked = 6
case ReadOnly = 8
case IOErr = 10
case Full = 13
}
/**
* Handle to a SQLite database.
* Each instance holds a single connection that is shared across all queries.
*/
open class SwiftData {
let filename: String
let schema: Schema
let files: FileAccessor
static var EnableWAL = true
static var EnableForeignKeys = true
/// Used to keep track of the corrupted databases we've logged.
static var corruptionLogsWritten = Set<String>()
/// Used for testing.
static var ReuseConnections = true
/// For thread-safe access to the shared connection.
fileprivate let sharedConnectionQueue: DispatchQueue
/// Shared connection to this database.
fileprivate var sharedConnection: ConcreteSQLiteDBConnection?
fileprivate var key: String?
fileprivate var prevKey: String?
/// A simple state flag to track whether we should accept new connection requests.
/// If a connection request is made while the database is closed, a
/// FailedSQLiteDBConnection will be returned.
fileprivate(set) var closed = false
init(filename: String, key: String? = nil, prevKey: String? = nil, schema: Schema, files: FileAccessor) {
self.filename = filename
self.key = key
self.prevKey = prevKey
self.schema = schema
self.files = files
self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: [])
// Ensure that multi-thread mode is enabled by default.
// See https://www.sqlite.org/threadsafe.html
assert(sqlite3_threadsafe() == 2)
}
fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? {
var connection: ConcreteSQLiteDBConnection?
sharedConnectionQueue.sync {
if self.closed {
log.warning(">>> Database is closed for \(self.filename)")
return
}
if self.sharedConnection == nil {
log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).")
self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey, schema: self.schema, files: self.files)
}
connection = self.sharedConnection
}
return connection
}
/**
* The real meat of all the execute methods. This is used internally to open and
* close a database connection and run a block of code inside it.
*/
func withConnection<T>(_ flags: SwiftData.Flags, synchronous: Bool = false, _ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
/**
* We use a weak reference here instead of strongly retaining the connection because we don't want
* any control over when the connection deallocs. If the only owner of the connection (SwiftData)
* decides to dealloc it, we should respect that since the deinit method of the connection is tied
* to the app lifecycle. This is to prevent background disk access causing springboard crashes.
*/
weak var conn = getSharedConnection()
let queue = self.sharedConnectionQueue
func doWork() {
// By the time this dispatch block runs, it is possible the user has backgrounded the
// app and the connection has been dealloc'ed since we last grabbed the reference
guard let connection = SwiftData.ReuseConnections ? conn :
ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey, schema: self.schema, files: self.files) else {
do {
_ = try callback(FailedSQLiteDBConnection())
deferred.fill(Maybe(failure: NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"])))
} catch let err as NSError {
deferred.fill(Maybe(failure: DatabaseError(err: err)))
}
return
}
do {
let result = try callback(connection)
deferred.fill(Maybe(success: result))
} catch let err as NSError {
deferred.fill(Maybe(failure: DatabaseError(err: err)))
}
}
if synchronous {
queue.sync {
doWork()
}
} else {
queue.async {
doWork()
}
}
return deferred
}
/**
* Helper for opening a connection, starting a transaction, and then running a block of code inside it.
* The code block can return true if the transaction should be committed. False if we should roll back.
*/
func transaction<T>(synchronous: Bool = false, _ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> {
return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { connection in
try connection.transaction(transactionClosure)
}
}
/// Don't use this unless you know what you're doing. The deinitializer
/// should be used to achieve refcounting semantics.
func forceClose() {
sharedConnectionQueue.sync {
self.closed = true
self.sharedConnection = nil
}
}
/// Reopens a database that had previously been force-closed.
/// Does nothing if this database is already open.
func reopenIfClosed() {
sharedConnectionQueue.sync {
self.closed = false
}
}
public enum Flags {
case readOnly
case readWrite
case readWriteCreate
fileprivate func toSQL() -> Int32 {
switch self {
case .readOnly:
return SQLITE_OPEN_READONLY
case .readWrite:
return SQLITE_OPEN_READWRITE
case .readWriteCreate:
return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
}
}
}
}
/**
* Wrapper class for a SQLite statement.
* This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure
* the connection is never deinitialized while the statement is active. This class is responsible for
* finalizing the SQL statement once it goes out of scope.
*/
private class SQLiteDBStatement {
var pointer: OpaquePointer?
fileprivate let connection: ConcreteSQLiteDBConnection
init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws {
self.connection = connection
let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil)
if status != SQLITE_OK {
throw connection.createErr("During: SQL Prepare \(query)", status: Int(status))
}
if let args = args,
let bindError = bind(args) {
throw bindError
}
}
/// Binds arguments to the statement.
fileprivate func bind(_ objects: [Any?]) -> NSError? {
let count = Int(sqlite3_bind_parameter_count(pointer))
if count < objects.count {
return connection.createErr("During: Bind", status: 202)
}
if count > objects.count {
return connection.createErr("During: Bind", status: 201)
}
for (index, obj) in objects.enumerated() {
var status: Int32 = SQLITE_OK
// Doubles also pass obj as Int, so order is important here.
if obj is Double {
status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double)
} else if obj is Int {
status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int))
} else if obj is Bool {
status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0)
} else if obj is String {
typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void
let transient = unsafeBitCast(-1, to: CFunction.self)
status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient)
} else if obj is Data {
status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil)
} else if obj is Date {
let timestamp = (obj as! Date).timeIntervalSince1970
status = sqlite3_bind_double(pointer, Int32(index+1), timestamp)
} else if obj is UInt64 {
status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64))
} else if obj == nil {
status = sqlite3_bind_null(pointer, Int32(index+1))
}
if status != SQLITE_OK {
return connection.createErr("During: Bind", status: Int(status))
}
}
return nil
}
func close() {
if nil != self.pointer {
sqlite3_finalize(self.pointer)
self.pointer = nil
}
}
deinit {
if nil != self.pointer {
sqlite3_finalize(self.pointer)
}
}
}
public protocol SQLiteDBConnection {
var lastInsertedRowID: Int { get }
var numberOfRowsModified: Int { get }
var version: Int { get }
func executeChange(_ sqlStr: String) throws -> Void
func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T>
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T>
func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T>
func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T
func interrupt()
func checkpoint()
func checkpoint(_ mode: Int32)
func vacuum() throws -> Void
func setVersion(_ version: Int) throws -> Void
}
// Represents a failure to open.
class FailedSQLiteDBConnection: SQLiteDBConnection {
var lastInsertedRowID: Int = 0
var numberOfRowsModified: Int = 0
var version: Int = 0
fileprivate func fail(_ str: String) -> NSError {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str])
}
func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void {
throw fail("Non-open connection; can't execute change.")
}
func executeChange(_ sqlStr: String) throws -> Void {
throw fail("Non-open connection; can't execute change.")
}
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> {
return Cursor<T>(err: fail("Non-open connection; can't execute query."))
}
func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
return Cursor<T>(err: fail("Non-open connection; can't execute query."))
}
func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
return Cursor<T>(err: fail("Non-open connection; can't execute query."))
}
func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T {
throw fail("Non-open connection; can't start transaction.")
}
func interrupt() {}
func checkpoint() {}
func checkpoint(_ mode: Int32) {}
func vacuum() throws -> Void {
throw fail("Non-open connection; can't vacuum.")
}
func setVersion(_ version: Int) throws -> Void {
throw fail("Non-open connection; can't set user_version.")
}
}
open class ConcreteSQLiteDBConnection: SQLiteDBConnection {
open var lastInsertedRowID: Int {
return Int(sqlite3_last_insert_rowid(sqliteDB))
}
open var numberOfRowsModified: Int {
return Int(sqlite3_changes(sqliteDB))
}
open var version: Int {
return pragma("user_version", factory: IntFactory) ?? 0
}
fileprivate var sqliteDB: OpaquePointer?
fileprivate let filename: String
fileprivate let schema: Schema
fileprivate let files: FileAccessor
fileprivate let debug_enabled = false
init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil, schema: Schema, files: FileAccessor) {
log.debug("Opening connection to \(filename).")
self.filename = filename
self.schema = schema
self.files = files
func doOpen() -> Bool {
if let failure = openWithFlags(flags) {
log.warning("Opening connection to \(filename) failed: \(failure).")
return false
}
if key == nil && prevKey == nil {
do {
try self.prepareCleartext()
} catch {
return false
}
} else {
do {
try self.prepareEncrypted(flags, key: key, prevKey: prevKey)
} catch {
return false
}
}
return true
}
// If we cannot even open the database file, return `nil` to force SwiftData
// into using a `FailedSQLiteDBConnection` so we can retry opening again later.
if !doOpen() {
log.error("Cannot open a database connection to \(filename).")
SentryIntegration.shared.sendWithStacktrace(message: "Cannot open a database connection to \(filename).", tag: "SwiftData", severity: .error)
return nil
}
// Now that we've successfully opened a connection to the database file, call
// `prepareSchema()`. If it succeeds, our work here is done. If it returns
// `.failure`, this means there was a temporary error preventing us from initing
// the schema (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL); so we return `nil` to
// force SwiftData into using a `FailedSQLiteDBConnection` to retry preparing the
// schema again later. However, if it returns `.needsRecovery`, this means there
// was a permanent error preparing the schema and we need to move the current
// database file to a backup location and start over with a brand new one.
switch self.prepareSchema() {
case .success:
log.debug("Database succesfully created or updated.")
case .failure:
log.error("Failed to create or update the database schema.")
SentryIntegration.shared.sendWithStacktrace(message: "Failed to create or update the database schema.", tag: "SwiftData", severity: .error)
return nil
case .needsRecovery:
log.error("Database schema cannot be created or updated due to an unrecoverable error.")
SentryIntegration.shared.sendWithStacktrace(message: "Database schema cannot be created or updated due to an unrecoverable error.", tag: "SwiftData", severity: .error)
// We need to close this new connection before we can move the database file to
// its backup location. If we cannot even close the connection, something has
// gone really wrong. In that case, bail out and return `nil` to force SwiftData
// into using a `FailedSQLiteDBConnection` so we can retry again later.
if let error = self.closeCustomConnection(immediately: true) {
log.error("Cannot close the database connection to begin recovery. \(error.localizedDescription)")
SentryIntegration.shared.sendWithStacktrace(message: "Cannot close the database connection to begin recovery. \(error.localizedDescription)", tag: "SwiftData", severity: .error)
return nil
}
// Move the current database file to its backup location.
self.moveDatabaseFileToBackupLocation()
// If we cannot open the *new* database file (which shouldn't happen), return
// `nil` to force SwiftData into using a `FailedSQLiteDBConnection` so we can
// retry opening again later.
if !doOpen() {
log.error("Cannot re-open a database connection to the new database file to begin recovery.")
SentryIntegration.shared.sendWithStacktrace(message: "Cannot re-open a database connection to the new database file to begin recovery.", tag: "SwiftData", severity: .error)
return nil
}
// Notify the world that we re-created the database schema. This allows us to
// reset Sync and start over in the case of corruption.
defer {
let baseFilename = URL(fileURLWithPath: self.filename).lastPathComponent
NotificationCenter.default.post(name: NotificationDatabaseWasRecreated, object: baseFilename)
}
// Now that we've got a brand new database file, let's call `prepareSchema()` on
// it to re-create the schema. Again, if this fails (it shouldn't), return `nil`
// to force SwiftData into using a `FailedSQLiteDBConnection` so we can retry
// again later.
if self.prepareSchema() != .success {
log.error("Cannot re-create the schema in the new database file to complete recovery.")
SentryIntegration.shared.sendWithStacktrace(message: "Cannot re-create the schema in the new database file to complete recovery.", tag: "SwiftData", severity: .error)
return nil
}
}
}
deinit {
log.debug("deinit: closing connection on thread \(Thread.current).")
self.closeCustomConnection()
}
fileprivate func setKey(_ key: String?) -> NSError? {
sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count))
let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?)
if cursor.status != .success {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"])
}
return nil
}
fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? {
sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count))
sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count))
// Check that the new key actually works
sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count))
let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?)
if cursor.status != .success {
return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"])
}
return nil
}
public func setVersion(_ version: Int) throws -> Void {
try executeChange("PRAGMA user_version = \(version)")
}
public func interrupt() {
log.debug("Interrupt")
sqlite3_interrupt(sqliteDB)
}
fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws {
let cursorResult = self.pragma(pragma, factory: factory)
if cursorResult != expected {
log.error("\(message): \(cursorResult.debugDescription), \(expected.debugDescription)")
throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."])
}
}
fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? {
let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args)
defer { cursor.close() }
return cursor[0]
}
fileprivate func prepareShared() {
if SwiftData.EnableForeignKeys {
let _ = pragma("foreign_keys=ON", factory: IntFactory)
}
// Retry queries before returning locked errors.
sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout)
}
fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws {
// Setting the key needs to be the first thing done with the database.
if let _ = setKey(key) {
if let err = closeCustomConnection(immediately: true) {
log.error("Couldn't close connection: \(err). Failing to open.")
throw err
}
if let err = openWithFlags(flags) {
log.error("Error opening database with flags. Error code: \(err.code), \(err)")
SentryIntegration.shared.sendWithStacktrace(message: "Error opening database with flags. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error)
throw err
}
if let err = reKey(prevKey, newKey: key) {
// Note: Don't log the error here as it may contain sensitive data.
log.error("Unable to encrypt database.")
SentryIntegration.shared.sendWithStacktrace(message: "Unable to encrypt database.", tag: "SwiftData", severity: .error)
throw err
}
}
if SwiftData.EnableWAL {
log.info("Enabling WAL mode.")
try pragma("journal_mode=WAL", expected: "wal",
factory: StringFactory, message: "WAL journal mode set")
}
self.prepareShared()
}
fileprivate func prepareCleartext() throws {
// If we just created the DB -- i.e., no tables have been created yet -- then
// we can set the page size right now and save a vacuum.
//
// For where these values come from, see Bug 1213623.
//
// Note that sqlcipher uses cipher_page_size instead, but we don't set that
// because it needs to be set from day one.
let desiredPageSize = 32 * 1024
let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory)
let currentPageSize = pragma("page_size", factory: IntFactory)
// This has to be done without WAL, so we always hop into rollback/delete journal mode.
if currentPageSize != desiredPageSize {
try pragma("journal_mode=DELETE", expected: "delete",
factory: StringFactory, message: "delete journal mode set")
try pragma("page_size=\(desiredPageSize)", expected: nil,
factory: IntFactory, message: "Page size set")
log.info("Vacuuming to alter database page size from \(currentPageSize ?? 0) to \(desiredPageSize).")
do {
try vacuum()
log.debug("Vacuuming succeeded.")
} catch let err as NSError {
log.error("Vacuuming failed: \(err.localizedDescription).")
}
}
if SwiftData.EnableWAL {
log.info("Enabling WAL mode.")
let desiredPagesPerJournal = 16
let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize
let desiredJournalSizeLimit = 3 * desiredCheckpointSize
/*
* With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the
* compiler seems to eagerly discard these queries if they're simply
* inlined, causing a crash in `pragma`.
*
* Hackily hold on to them.
*/
let journalModeQuery = "journal_mode=WAL"
let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)"
let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)"
try withExtendedLifetime(journalModeQuery, {
try pragma(journalModeQuery, expected: "wal",
factory: StringFactory, message: "WAL journal mode set")
})
try withExtendedLifetime(autoCheckpointQuery, {
try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal,
factory: IntFactory, message: "WAL autocheckpoint set")
})
try withExtendedLifetime(journalSizeQuery, {
try pragma(journalSizeQuery, expected: desiredJournalSizeLimit,
factory: IntFactory, message: "WAL journal size limit set")
})
}
self.prepareShared()
}
// Creates the database schema in a new database.
fileprivate func createSchema() -> Bool {
log.debug("Trying to create schema \(self.schema.name) at version \(self.schema.version)")
if !schema.create(self) {
// If schema couldn't be created, we'll bail without setting the `PRAGMA user_version`.
log.debug("Creation failed.")
return false
}
do {
try setVersion(schema.version)
} catch let error as NSError {
log.error("Unable to set the schema version; \(error.localizedDescription)")
}
return true
}
// Updates the database schema in an existing database.
fileprivate func updateSchema() -> Bool {
log.debug("Trying to update schema \(self.schema.name) from version \(self.version) to \(self.schema.version)")
if !schema.update(self, from: self.version) {
// If schema couldn't be updated, we'll bail without setting the `PRAGMA user_version`.
log.debug("Updating failed.")
return false
}
do {
try setVersion(schema.version)
} catch let error as NSError {
log.error("Unable to set the schema version; \(error.localizedDescription)")
}
return true
}
// Drops the database schema from an existing database.
fileprivate func dropSchema() -> Bool {
log.debug("Trying to drop schema \(self.schema.name)")
if !self.schema.drop(self) {
// If schema couldn't be dropped, we'll bail without setting the `PRAGMA user_version`.
log.debug("Dropping failed.")
return false
}
do {
try setVersion(0)
} catch let error as NSError {
log.error("Unable to reset the schema version; \(error.localizedDescription)")
}
return true
}
// Checks if the database schema needs created or updated and acts accordingly.
// Calls to this function will be serialized to prevent race conditions when
// creating or updating the schema.
fileprivate func prepareSchema() -> SQLiteDBConnectionCreatedResult {
SentryIntegration.shared.addAttributes(["dbSchema.\(schema.name).version": schema.version])
// Get the current schema version for the database.
let currentVersion = self.version
// If the current schema version for the database matches the specified
// `Schema` version, no further action is necessary and we can bail out.
// NOTE: This assumes that we always use *ONE* `Schema` per database file
// since SQLite can only track a single value in `PRAGMA user_version`.
if currentVersion == schema.version {
log.debug("Schema \(self.schema.name) already exists at version \(self.schema.version). Skipping additional schema preparation.")
return .success
}
// Set an attribute for Sentry to include with any future error/crash
// logs to indicate what schema version we're coming from and going to.
SentryIntegration.shared.addAttributes(["dbUpgrade.\(self.schema.name).from": currentVersion, "dbUpgrade.\(self.schema.name).to": self.schema.version])
// This should not ever happen since the schema version should always be
// increasing whenever a structural change is made in an app update.
guard currentVersion <= schema.version else {
log.error("Schema \(self.schema.name) cannot be downgraded from version \(currentVersion) to \(self.schema.version).")
SentryIntegration.shared.sendWithStacktrace(message: "Schema \(self.schema.name) cannot be downgraded from version \(currentVersion) to \(self.schema.version).", tag: "SwiftData", severity: .error)
return .failure
}
log.debug("Schema \(self.schema.name) needs created or updated from version \(currentVersion) to \(self.schema.version).")
var success = true
do {
success = try transaction { connection -> Bool in
log.debug("Create or update \(self.schema.name) version \(self.schema.version) on \(Thread.current.description).")
// If `PRAGMA user_version` is zero, check if we can safely create the
// database schema from scratch.
if connection.version == 0 {
// Query for the existence of the `tableList` table to determine if we are
// migrating from an older DB version.
let sqliteMasterCursor = connection.executeQueryUnsafe("SELECT COUNT(*) AS number FROM sqlite_master WHERE type = 'table' AND name = 'tableList'", factory: IntFactory, withArgs: [] as Args)
let tableListTableExists = sqliteMasterCursor[0] == 1
sqliteMasterCursor.close()
// If the `tableList` table doesn't exist, we can simply invoke
// `createSchema()` to create a brand new DB from scratch.
if !tableListTableExists {
log.debug("Schema \(self.schema.name) doesn't exist. Creating.")
success = self.createSchema()
return success
}
}
log.info("Attempting to update schema from version \(currentVersion) to \(self.schema.version).")
SentryIntegration.shared.send(message: "Attempting to update schema from version \(currentVersion) to \(self.schema.version).", tag: "SwiftData", severity: .info)
// If we can't create a brand new schema from scratch, we must
// call `updateSchema()` to go through the update process.
if self.updateSchema() {
log.debug("Updated schema \(self.schema.name).")
success = true
return success
}
// If we failed to update the schema, we'll drop everything from the DB
// and create everything again from scratch. Assuming our schema upgrade
// code is correct, this *shouldn't* happen. If it does, log it to Sentry.
log.error("Update failed for schema \(self.schema.name) from version \(currentVersion) to \(self.schema.version). Dropping and re-creating.")
SentryIntegration.shared.sendWithStacktrace(message: "Update failed for schema \(self.schema.name) from version \(currentVersion) to \(self.schema.version). Dropping and re-creating.", tag: "SwiftData", severity: .error)
// If we can't even drop the schema here, something has gone really wrong, so
// return `false` which should force us into recovery.
if !self.dropSchema() {
log.error("Unable to drop schema \(self.schema.name) from version \(currentVersion).")
SentryIntegration.shared.sendWithStacktrace(message: "Unable to drop schema \(self.schema.name) from version \(currentVersion).", tag: "SwiftData", severity: .error)
success = false
return success
}
// Try to re-create the schema. If this fails, we are out of options and we'll
// return `false` which should force us into recovery.
success = self.createSchema()
return success
}
} catch let error as NSError {
// If we got an error trying to get a transaction, then we either bail out early and return
// `.failure` if we think we can retry later or return `.needsRecovery` if the error is not
// recoverable.
log.error("Unable to get a transaction: \(error.localizedDescription)")
SentryIntegration.shared.sendWithStacktrace(message: "Unable to get a transaction: \(error.localizedDescription)", tag: "SwiftData", severity: .error)
// Check if the error we got is recoverable (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL).
// If so, just return `.failure` so we can retry preparing the schema again later.
if let _ = SQLiteDBRecoverableError(rawValue: error.code) {
return .failure
}
// Otherwise, this is a non-recoverable error and we return `.needsRecovery` so the database
// file can be backed up and a new one will be created.
return .needsRecovery
}
// If any of our operations inside the transaction failed, this also means we need to go through
// the recovery process to re-create the database from scratch.
if !success {
return .needsRecovery
}
// No error means we're all good! \o/
return .success
}
fileprivate func moveDatabaseFileToBackupLocation() {
let baseFilename = URL(fileURLWithPath: filename).lastPathComponent
// Attempt to make a backup as long as the database file still exists.
if files.exists(baseFilename) {
log.warning("Couldn't create or update schema \(self.schema.name). Attempting to move \(baseFilename) to another location.")
SentryIntegration.shared.sendWithStacktrace(message: "Couldn't create or update schema \(self.schema.name). Attempting to move \(baseFilename) to another location.", tag: "SwiftData", severity: .warning)
// Note that a backup file might already exist! We append a counter to avoid this.
var bakCounter = 0
var bak: String
repeat {
bakCounter += 1
bak = "\(baseFilename).bak.\(bakCounter)"
} while files.exists(bak)
do {
try files.move(baseFilename, toRelativePath: bak)
let shm = baseFilename + "-shm"
let wal = baseFilename + "-wal"
log.debug("Moving \(shm) and \(wal)…")
if files.exists(shm) {
log.debug("\(shm) exists.")
try files.move(shm, toRelativePath: bak + "-shm")
}
if files.exists(wal) {
log.debug("\(wal) exists.")
try files.move(wal, toRelativePath: bak + "-wal")
}
log.debug("Finished moving database \(baseFilename) successfully.")
} catch let error as NSError {
log.error("Unable to move \(baseFilename) to another location. \(error)")
SentryIntegration.shared.sendWithStacktrace(message: "Unable to move \(baseFilename) to another location. \(error)", tag: "SwiftData", severity: .error)
}
} else {
// No backup was attempted since the database file did not exist.
log.error("The database file \(baseFilename) has been deleted while previously in use.")
SentryIntegration.shared.sendWithStacktrace(message: "The database file \(baseFilename) has been deleted while previously in use.", tag: "SwiftData", severity: .info)
}
}
public func checkpoint() {
self.checkpoint(SQLITE_CHECKPOINT_FULL)
}
/**
* Blindly attempts a WAL checkpoint on all attached databases.
*/
public func checkpoint(_ mode: Int32) {
guard sqliteDB != nil else {
log.warning("Trying to checkpoint a nil DB!")
return
}
log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).")
sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil)
log.debug("WAL checkpoint done on \(self.filename).")
}
public func vacuum() throws -> Void {
try executeChange("VACUUM")
}
/// Creates an error from a sqlite status. Will print to the console if debug_enabled is set.
/// Do not call this unless you're going to return this error.
fileprivate func createErr(_ description: String, status: Int) -> NSError {
var msg = SDError.errorMessageFromCode(status)
if debug_enabled {
log.debug("SwiftData Error -> \(description)")
log.debug(" -> Code: \(status) - \(msg)")
}
if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) {
msg += " " + errMsg
if debug_enabled {
log.debug(" -> Details: \(errMsg)")
}
}
return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg])
}
/// Open the connection. This is called when the db is created. You should not call it yourself.
fileprivate func openWithFlags(_ flags: Int32) -> NSError? {
let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
return createErr("During: Opening Database with Flags", status: Int(status))
}
return nil
}
/// Closes a connection. This is called via deinit. Do not call this yourself.
@discardableResult fileprivate func closeCustomConnection(immediately: Bool = false) -> NSError? {
log.debug("Closing custom connection for \(self.filename) on \(Thread.current).")
// TODO: add a lock here?
let db = self.sqliteDB
self.sqliteDB = nil
// Don't bother trying to call sqlite3_close multiple times.
guard db != nil else {
log.warning("Connection was nil.")
return nil
}
var status = sqlite3_close(db)
if status != SQLITE_OK {
log.error("Got status \(status) while attempting to close.")
SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close.", tag: "SwiftData", severity: .error)
if immediately {
return createErr("During: closing database with flags", status: Int(status))
}
// Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if
// there are outstanding prepared statements
status = sqlite3_close_v2(db)
if status != SQLITE_OK {
// Based on the above comment regarding sqlite3_close_v2, this shouldn't happen.
log.error("Got status \(status) while attempting to close_v2.")
SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close_v2.", tag: "SwiftData", severity: .error)
return createErr("During: closing database with flags", status: Int(status))
}
}
log.debug("Closed \(self.filename).")
return nil
}
open func executeChange(_ sqlStr: String) throws -> Void {
try executeChange(sqlStr, withArgs: nil)
}
/// Executes a change on the database.
open func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
}
// Close, not reset -- this isn't going to be reused.
defer { statement?.close() }
if let error = error {
// Special case: Write additional info to the database log in the case of a database corruption.
if error.code == Int(SQLITE_CORRUPT) {
writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger)
SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error)
}
let message = "SQL error. Error code: \(error.code), \(error) for SQL \(String(sqlStr.characters.prefix(500)))."
log.error(message)
SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error)
throw error
}
let status = sqlite3_step(statement!.pointer)
if status != SQLITE_DONE && status != SQLITE_OK {
throw createErr("During: SQL Step \(sqlStr)", status: Int(status))
}
}
public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> {
return self.executeQuery(sqlStr, factory: factory, withArgs: nil)
}
/// Queries the database.
/// Returns a cursor pre-filled with the complete result set.
public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
}
// Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor
// consumes everything.
defer { statement?.close() }
if let error = error {
// Special case: Write additional info to the database log in the case of a database corruption.
if error.code == Int(SQLITE_CORRUPT) {
writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger)
SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error)
}
let message = "SQL error. Error code: \(error.code), \(error) for SQL \(String(sqlStr.characters.prefix(500)))."
log.error(message)
SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error)
return Cursor<T>(err: error)
}
return FilledSQLiteCursor<T>(statement: statement!, factory: factory)
}
func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) {
DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync {
guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return }
logger.error("Corrupt DB detected! DB filename: \(dbFilename)")
let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0
logger.error("DB file size: \(dbFileSize) bytes")
logger.error("Integrity check:")
let args: [Any?]? = nil
let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args)
defer { messages.close() }
if messages.status == CursorStatus.success {
for message in messages {
logger.error(message)
}
logger.error("----")
} else {
logger.error("Couldn't run integrity check: \(messages.statusMessage).")
}
// Write call stack.
logger.error("Call stack: ")
for message in Thread.callStackSymbols {
logger.error(" >> \(message)")
}
logger.error("----")
// Write open file handles.
let openDescriptors = FSUtils.openFileDescriptors()
logger.error("Open file descriptors: ")
for (k, v) in openDescriptors {
logger.error(" \(k): \(v)")
}
logger.error("----")
SwiftData.corruptionLogsWritten.insert(dbFilename)
}
}
/**
* Queries the database.
* Returns a live cursor that holds the query statement and database connection.
* Instances of this class *must not* leak outside of the connection queue!
*/
public func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> {
var error: NSError?
let statement: SQLiteDBStatement?
do {
statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args)
} catch let error1 as NSError {
error = error1
statement = nil
}
if let error = error {
return Cursor(err: error)
}
return LiveSQLiteCursor(statement: statement!, factory: factory)
}
public func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T {
do {
try executeChange("BEGIN EXCLUSIVE")
} catch let err as NSError {
log.error("BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)")
SentryIntegration.shared.sendWithStacktrace(message: "BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error)
throw err
}
var result: T
do {
result = try transactionClosure(self)
} catch let err as NSError {
log.error("Op in transaction threw an error. Rolling back.")
SentryIntegration.shared.sendWithStacktrace(message: "Op in transaction threw an error. Rolling back.", tag: "SwiftData", severity: .error)
do {
try executeChange("ROLLBACK")
} catch let err as NSError {
log.error("ROLLBACK after errored op in transaction failed. Error code: \(err.code), \(err)")
SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after errored op in transaction failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error)
throw err
}
throw err
}
log.verbose("Op in transaction succeeded. Committing.")
do {
try executeChange("COMMIT")
} catch let err as NSError {
log.error("COMMIT failed. Rolling back. Error code: \(err.code), \(err)")
SentryIntegration.shared.sendWithStacktrace(message: "COMMIT failed. Rolling back. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error)
do {
try executeChange("ROLLBACK")
} catch let err as NSError {
log.error("ROLLBACK after failed COMMIT failed. Error code: \(err.code), \(err)")
SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after failed COMMIT failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error)
throw err
}
throw err
}
return result
}
}
/// Helper for queries that return a single integer result.
func IntFactory(_ row: SDRow) -> Int {
return row[0] as! Int
}
/// Helper for queries that return a single String result.
func StringFactory(_ row: SDRow) -> String {
return row[0] as! String
}
/// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing
/// and a generator for iterating over columns.
open class SDRow: Sequence {
// The sqlite statement this row came from.
fileprivate let statement: SQLiteDBStatement
// The columns of this database. The indices of these are assumed to match the indices
// of the statement.
fileprivate let columnNames: [String]
fileprivate init(statement: SQLiteDBStatement, columns: [String]) {
self.statement = statement
self.columnNames = columns
}
// Return the value at this index in the row
fileprivate func getValue(_ index: Int) -> Any? {
let i = Int32(index)
let type = sqlite3_column_type(statement.pointer, i)
var ret: Any? = nil
switch type {
case SQLITE_NULL, SQLITE_INTEGER:
//Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information.
ret = Int(truncatingBitPattern: sqlite3_column_int64(statement.pointer, i))
case SQLITE_TEXT:
if let text = sqlite3_column_text(statement.pointer, i) {
return String(cString: text)
}
case SQLITE_BLOB:
if let blob = sqlite3_column_blob(statement.pointer, i) {
let size = sqlite3_column_bytes(statement.pointer, i)
ret = Data(bytes: blob, count: Int(size))
}
case SQLITE_FLOAT:
ret = Double(sqlite3_column_double(statement.pointer, i))
default:
log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
}
return ret
}
// Accessor getting column 'key' in the row
subscript(key: Int) -> Any? {
return getValue(key)
}
// Accessor getting a named column in the row. This (currently) depends on
// the columns array passed into this Row to find the correct index.
subscript(key: String) -> Any? {
get {
if let index = columnNames.index(of: key) {
return getValue(index)
}
return nil
}
}
// Allow iterating through the row.
public func makeIterator() -> AnyIterator<Any> {
let nextIndex = 0
return AnyIterator() {
if nextIndex < self.columnNames.count {
return self.getValue(nextIndex)
}
return nil
}
}
}
/// Helper for pretty printing SQL (and other custom) error codes.
private struct SDError {
fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String {
switch errorCode {
case -1:
return "No error"
// SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html
case 0:
return "Successful result"
case 1:
return "SQL error or missing database"
case 2:
return "Internal logic error in SQLite"
case 3:
return "Access permission denied"
case 4:
return "Callback routine requested an abort"
case 5:
return "The database file is busy"
case 6:
return "A table in the database is locked"
case 7:
return "A malloc() failed"
case 8:
return "Attempt to write a readonly database"
case 9:
return "Operation terminated by sqlite3_interrupt()"
case 10:
return "Some kind of disk I/O error occurred"
case 11:
return "The database disk image is malformed"
case 12:
return "Unknown opcode in sqlite3_file_control()"
case 13:
return "Insertion failed because database is full"
case 14:
return "Unable to open the database file"
case 15:
return "Database lock protocol error"
case 16:
return "Database is empty"
case 17:
return "The database schema changed"
case 18:
return "String or BLOB exceeds size limit"
case 19:
return "Abort due to constraint violation"
case 20:
return "Data type mismatch"
case 21:
return "Library used incorrectly"
case 22:
return "Uses OS features not supported on host"
case 23:
return "Authorization denied"
case 24:
return "Auxiliary database format error"
case 25:
return "2nd parameter to sqlite3_bind out of range"
case 26:
return "File opened that is not a database file"
case 27:
return "Notifications from sqlite3_log()"
case 28:
return "Warnings from sqlite3_log()"
case 100:
return "sqlite3_step() has another row ready"
case 101:
return "sqlite3_step() has finished executing"
// Custom SwiftData errors
// Binding errors
case 201:
return "Not enough objects to bind provided"
case 202:
return "Too many objects to bind provided"
// Custom connection errors
case 301:
return "A custom connection is already open"
case 302:
return "Cannot open a custom connection inside a transaction"
case 303:
return "Cannot open a custom connection inside a savepoint"
case 304:
return "A custom connection is not currently open"
case 305:
return "Cannot close a custom connection inside a transaction"
case 306:
return "Cannot close a custom connection inside a savepoint"
// Index and table errors
case 401:
return "At least one column name must be provided"
case 402:
return "Error extracting index names from sqlite_master"
case 403:
return "Error extracting table names from sqlite_master"
// Transaction and savepoint errors
case 501:
return "Cannot begin a transaction within a savepoint"
case 502:
return "Cannot begin a transaction within another transaction"
// Unknown error
default:
return "Unknown error"
}
}
}
/// Provides access to the result set returned by a database query.
/// The entire result set is cached, so this does not retain a reference
/// to the statement or the database connection.
private class FilledSQLiteCursor<T>: ArrayCursor<T> {
fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) {
let (data, status, statusMessage) = FilledSQLiteCursor.getValues(statement, factory: factory)
super.init(data: data, status: status, statusMessage: statusMessage)
}
/// Return an array with the set of results and release the statement.
fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T) -> ([T], CursorStatus, String) {
var rows = [T]()
var status = CursorStatus.success
var statusMessage = "Success"
var count = 0
var columns = [String]()
let columnCount = sqlite3_column_count(statement.pointer)
for i in 0..<columnCount {
let columnName = String(cString: sqlite3_column_name(statement.pointer, i))
columns.append(columnName)
}
while true {
let sqlStatus = sqlite3_step(statement.pointer)
if sqlStatus != SQLITE_ROW {
if sqlStatus != SQLITE_DONE {
// NOTE: By setting our status to failure here, we'll report our count as zero,
// regardless of how far we've read at this point.
status = CursorStatus.failure
statusMessage = SDError.errorMessageFromCode(Int(sqlStatus))
}
break
}
count += 1
let row = SDRow(statement: statement, columns: columns)
let result = factory(row)
rows.append(result)
}
return (rows, status, statusMessage)
}
}
/// Wrapper around a statement to help with iterating through the results.
private class LiveSQLiteCursor<T>: Cursor<T> {
fileprivate var statement: SQLiteDBStatement!
// Function for generating objects of type T from a row.
fileprivate let factory: (SDRow) -> T
// Status of the previous fetch request.
fileprivate var sqlStatus: Int32 = 0
// Number of rows in the database
// XXX - When Cursor becomes an interface, this should be a normal property, but right now
// we can't override the Cursor getter for count with a stored property.
fileprivate var _count: Int = 0
override var count: Int {
get {
if status != .success {
return 0
}
return _count
}
}
fileprivate var position: Int = -1 {
didSet {
// If we're already there, shortcut out.
if oldValue == position {
return
}
var stepStart = oldValue
// If we're currently somewhere in the list after this position
// we'll have to jump back to the start.
if position < oldValue {
sqlite3_reset(self.statement.pointer)
stepStart = -1
}
// Now step up through the list to the requested position
for _ in stepStart..<position {
sqlStatus = sqlite3_step(self.statement.pointer)
}
}
}
init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) {
self.factory = factory
self.statement = statement
// The only way I know to get a count. Walk through the entire statement to see how many rows there are.
var count = 0
self.sqlStatus = sqlite3_step(statement.pointer)
while self.sqlStatus != SQLITE_DONE {
count += 1
self.sqlStatus = sqlite3_step(statement.pointer)
}
sqlite3_reset(statement.pointer)
self._count = count
super.init(status: .success, msg: "success")
}
// Helper for finding all the column names in this statement.
fileprivate lazy var columns: [String] = {
// This untangles all of the columns and values for this row when its created
let columnCount = sqlite3_column_count(self.statement.pointer)
var columns = [String]()
for i: Int32 in 0 ..< columnCount {
let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i))
columns.append(columnName)
}
return columns
}()
override subscript(index: Int) -> T? {
get {
if status != .success {
return nil
}
self.position = index
if self.sqlStatus != SQLITE_ROW {
return nil
}
let row = SDRow(statement: statement, columns: self.columns)
return self.factory(row)
}
}
override func close() {
statement = nil
super.close()
}
}
| mpl-2.0 |
sol/aeson | tests/JSONTestSuite/parsers/test_PMJSON_1_2_0/Parser.swift | 7 | 28248 | //
// Decoder.swift
// PMJSON
//
// Created by Kevin Ballard on 10/8/15.
// Copyright © 2016 Postmates.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// A streaming JSON parser that consumes a sequence of unicode scalars.
public struct JSONParser<Seq: Sequence>: Sequence where Seq.Iterator.Element == UnicodeScalar {
public init(_ seq: Seq, options: JSONParserOptions = []) {
base = seq
self.options = options
}
/// Options to apply to the parser.
/// See `JSONParserOptions` for details.
var options: JSONParserOptions
@available(*, deprecated, renamed: "options.strict")
public var strict: Bool {
get { return options.strict }
set { options.strict = newValue }
}
@available(*, deprecated, renamed: "options.streaming")
public var streaming: Bool {
get { return options.streaming }
set { options.streaming = newValue }
}
public func makeIterator() -> JSONParserIterator<Seq.Iterator> {
return JSONParserIterator(base.makeIterator(), options: options)
}
private let base: Seq
}
/// Options that can be used to configure a `JSONParser`.
public struct JSONParserOptions {
/// If `true`, the parser strictly conforms to RFC 7159.
/// If `false`, the parser accepts the following extensions:
/// - Trailing commas.
/// - Less restrictive about numbers, such as `-01` or `-.123`.
///
/// The default value is `false`.
public var strict: Bool = false
/// If `true`, the parser will parse a stream of json values with optional whitespace delimiters.
/// The default value of `false` makes the parser emit an error if there are any non-whitespace
/// characters after the first JSON value.
///
/// For example, with the input `"[1] [2,3]"`, if `streaming` is `true` the parser will emit
/// events for the second JSON array after the first one, but if `streaming` is `false` it will
/// emit an error upon encountering the second `[`.
///
/// - Note: If `streaming` is `true` and the input is empty (or contains only whitespace), the
/// parser will return `nil` instead of emitting an `.unexpectedEOF` error.
///
/// The default value is `false`.
public var streaming: Bool = false
/// Returns a new `JSONParserOptions` with default values.
public init() {}
/// Returns a new `JSONParserOptions`.
/// - Parameter strict: Whether the parser should be strict. Defaults to `false`.
/// - Parameter streaming: Whether the parser should operate in streaming mode. Defaults to `false`.
public init(strict: Bool = false, streaming: Bool = false) {
self.strict = strict
self.streaming = streaming
}
}
extension JSONParserOptions: ExpressibleByArrayLiteral {
public enum Element {
case strict
case streaming
}
public init(arrayLiteral elements: Element...) {
for elt in elements {
switch elt {
case .strict: strict = true
case .streaming: streaming = true
}
}
}
}
/// The iterator for `JSONParser`.
public struct JSONParserIterator<Iter: IteratorProtocol>: JSONEventIterator where Iter.Element == UnicodeScalar {
public init(_ iter: Iter, options: JSONParserOptions = []) {
base = PeekIterator(iter)
self.options = options
}
/// Options to apply to the parser.
/// See `JSONParserOptions` for details.
public var options: JSONParserOptions
@available(*, deprecated, renamed: "options.strict")
public var strict: Bool {
get { return options.strict }
set { options.strict = newValue }
}
@available(*, deprecated, renamed: "options.strict")
public var streaming: Bool {
get { return options.streaming }
set { options.streaming = newValue }
}
public mutating func next() -> JSONEvent? {
do {
// the only states that may loop are parseArrayComma, parseObjectComma, and (if streaming) parseEnd,
// which are all guaranteed to shift to other states (if they don't return) so the loop is finite
while true {
switch state {
case .parseArrayComma:
switch skipWhitespace() {
case ","?:
state = .parseArray(first: false)
continue
case "]"?:
try popStack()
return .arrayEnd
case .some:
throw error(.invalidSyntax)
case nil:
throw error(.unexpectedEOF)
}
case .parseObjectComma:
switch skipWhitespace() {
case ","?:
state = .parseObjectKey(first: false)
continue
case "}"?:
try popStack()
return .objectEnd
case .some:
throw error(.invalidSyntax)
case nil:
throw error(.unexpectedEOF)
}
case .initial:
guard let c = skipWhitespace() else {
if options.streaming {
state = .finished
return nil
} else {
throw error(.unexpectedEOF)
}
}
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseEnd
}
return evt
case .parseArray(let first):
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case "]":
if !first && options.strict {
throw error(.trailingComma)
}
try popStack()
return .arrayEnd
case ",":
throw error(.missingValue)
default:
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseArrayComma
}
return evt
}
case .parseObjectKey(let first):
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case "}":
if !first && options.strict {
throw error(.trailingComma)
}
try popStack()
return .objectEnd
case ",", ":":
throw error(.missingKey)
default:
let evt = try parseValue(c)
switch evt {
case .stringValue:
state = .parseObjectValue
default:
throw error(.nonStringKey)
}
return evt
}
case .parseObjectValue:
guard skipWhitespace() == ":" else { throw error(.expectedColon) }
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case ",", "}":
throw error(.missingValue)
default:
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseObjectComma
}
return evt
}
case .parseEnd:
if options.streaming {
state = .initial
} else if skipWhitespace() != nil {
throw error(.trailingCharacters)
} else {
state = .finished
return nil
}
case .finished:
return nil
}
}
} catch let error as JSONParserError {
state = .finished
return .error(error)
} catch {
fatalError("unexpected error \(error)")
}
}
private mutating func popStack() throws {
if stack.popLast() == nil {
fatalError("exhausted stack")
}
switch stack.last {
case .array?:
state = .parseArrayComma
case .object?:
state = .parseObjectComma
case nil:
state = .parseEnd
}
}
private mutating func parseValue(_ c: UnicodeScalar) throws -> JSONEvent {
switch c {
case "[":
state = .parseArray(first: true)
stack.append(.array)
return .arrayStart
case "{":
state = .parseObjectKey(first: true)
stack.append(.object)
return .objectStart
case "\"":
var scalars = String.UnicodeScalarView()
while let c = bump() {
switch c {
case "\"":
return .stringValue(String(scalars))
case "\\":
let c = try bumpRequired()
switch c {
case "\"", "\\", "/": scalars.append(c)
case "b": scalars.append(UnicodeScalar(0x8))
case "f": scalars.append(UnicodeScalar(0xC))
case "n": scalars.append("\n" as UnicodeScalar)
case "r": scalars.append("\r" as UnicodeScalar)
case "t": scalars.append("\t" as UnicodeScalar)
case "u":
let codeUnit = try parseFourHex()
if UTF16.isLeadSurrogate(codeUnit) {
guard try (bumpRequired() == "\\" && bumpRequired() == "u") else {
throw error(.invalidSurrogateEscape)
}
let trail = try parseFourHex()
if UTF16.isTrailSurrogate(trail) {
let lead = UInt32(codeUnit)
let trail = UInt32(trail)
// NB: The following is split up to avoid exponential time complexity in the type checker
let leadComponent: UInt32 = (lead - 0xD800) << 10
let trailComponent: UInt32 = trail - 0xDC00
let scalar = UnicodeScalar(leadComponent + trailComponent + 0x10000)!
scalars.append(scalar)
} else {
throw error(.invalidSurrogateEscape)
}
} else if let scalar = UnicodeScalar(codeUnit) {
scalars.append(scalar)
} else {
// Must be a lone trail surrogate
throw error(.invalidSurrogateEscape)
}
default:
throw error(.invalidEscape)
}
case "\0"..."\u{1F}":
throw error(.invalidSyntax)
default:
scalars.append(c)
}
}
throw error(.unexpectedEOF)
case "-", "0"..."9":
var tempBuffer: ContiguousArray<Int8>
if let buffer = replace(&self.tempBuffer, with: nil) {
tempBuffer = buffer
tempBuffer.removeAll(keepingCapacity: true)
} else {
tempBuffer = ContiguousArray()
tempBuffer.reserveCapacity(12)
}
defer { self.tempBuffer = tempBuffer }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
if options.strict {
let digit: UnicodeScalar
if c == "-" {
guard let c2 = bump(), case "0"..."9" = c2 else { throw error(.invalidNumber) }
digit = c2
tempBuffer.append(Int8(truncatingBitPattern: digit.value))
} else {
digit = c
}
if digit == "0", case ("0"..."9")? = base.peek() {
// In strict mode, you can't have numbers like 01
throw error(.invalidNumber)
}
}
/// Invoke this after parsing the "e" character.
@inline(__always) func parseExponent() throws -> Double {
let c = try bumpRequired()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
switch c {
case "-", "+":
guard let c = bump(), case "0"..."9" = c else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case "0"..."9": break
default: throw error(.invalidNumber)
}
loop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
default:
break loop
}
}
tempBuffer.append(0)
return tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)})
}
outerLoop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case ".":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
guard let c = bump(), case "0"..."9" = c else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
loop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case "e", "E":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
return try .doubleValue(parseExponent())
default:
break loop
}
}
tempBuffer.append(0)
return .doubleValue(tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)}))
case "e", "E":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
return try .doubleValue(parseExponent())
default:
break outerLoop
}
}
if tempBuffer.count == 1 && tempBuffer[0] == 0x2d /* - */ {
throw error(.invalidNumber)
}
tempBuffer.append(0)
let num = tempBuffer.withUnsafeBufferPointer({ ptr -> Int64? in
errno = 0
let n = strtoll(ptr.baseAddress, nil, 10)
if n == 0 && errno != 0 {
return nil
} else {
return n
}
})
if let num = num {
return .int64Value(num)
}
// out of range, fall back to Double
return .doubleValue(tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)}))
case "t":
let line = self.line, column = self.column
guard case "r"? = bump(), case "u"? = bump(), case "e"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .booleanValue(true)
case "f":
let line = self.line, column = self.column
guard case "a"? = bump(), case "l"? = bump(), case "s"? = bump(), case "e"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .booleanValue(false)
case "n":
let line = self.line, column = self.column
guard case "u"? = bump(), case "l"? = bump(), case "l"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .nullValue
default:
throw error(.invalidSyntax)
}
}
private mutating func skipWhitespace() -> UnicodeScalar? {
while let c = bump() {
switch c {
case " ", "\t", "\n", "\r": continue
default: return c
}
}
return nil
}
private mutating func parseFourHex() throws -> UInt16 {
var codepoint: UInt32 = 0
for _ in 0..<4 {
let c = try bumpRequired()
codepoint <<= 4
switch c {
case "0"..."9":
codepoint += c.value - 48
case "a"..."f":
codepoint += c.value - 87
case "A"..."F":
codepoint += c.value - 55
default:
throw error(.invalidEscape)
}
}
return UInt16(truncatingBitPattern: codepoint)
}
@inline(__always) @discardableResult private mutating func bump() -> UnicodeScalar? {
let c = base.next()
if c == "\n" {
line += 1
column = 0
} else {
column += 1
}
return c
}
@inline(__always) private mutating func bumpRequired() throws -> UnicodeScalar {
guard let c = bump() else { throw error(.unexpectedEOF) }
return c
}
private func error(_ code: JSONParserError.Code) -> JSONParserError {
return JSONParserError(code: code, line: line, column: column)
}
/// The line of the last emitted token.
public private(set) var line: UInt = 0
/// The column of the last emitted token.
public private(set) var column: UInt = 0
private var base: PeekIterator<Iter>
private var state: State = .initial
private var stack: [Stack] = []
private var tempBuffer: ContiguousArray<Int8>?
}
@available(*, renamed: "JSONParserIterator")
typealias JSONParserGenerator<Gen: IteratorProtocol> = JSONParserIterator<Gen> where Gen.Element == UnicodeScalar
private enum State {
/// Initial state
case initial
/// Parse an element or the end of the array
case parseArray(first: Bool)
/// Parse a comma or the end of the array
case parseArrayComma
/// Parse an object key or the end of the array
case parseObjectKey(first: Bool)
/// Parse a colon followed by an object value
case parseObjectValue
/// Parse a comma or the end of the object
case parseObjectComma
/// Parse whitespace or EOF
case parseEnd
/// Parsing has completed
case finished
}
private enum Stack {
case array
case object
}
/// A streaming JSON parser event.
public enum JSONEvent: Hashable {
/// The start of an object.
/// Inside of an object, each key/value pair is emitted as a
/// `StringValue` for the key followed by the `JSONEvent` sequence
/// that describes the value.
case objectStart
/// The end of an object.
case objectEnd
/// The start of an array.
case arrayStart
/// The end of an array.
case arrayEnd
/// A boolean value.
case booleanValue(Bool)
/// A signed 64-bit integral value.
case int64Value(Int64)
/// A double value.
case doubleValue(Double)
/// A string value.
case stringValue(String)
/// The null value.
case nullValue
/// A parser error.
case error(JSONParserError)
public var hashValue: Int {
switch self {
case .objectStart: return 1
case .objectEnd: return 2
case .arrayStart: return 3
case .arrayEnd: return 4
case .booleanValue(let b): return b.hashValue << 4 + 5
case .int64Value(let i): return i.hashValue << 4 + 6
case .doubleValue(let d): return d.hashValue << 4 + 7
case .stringValue(let s): return s.hashValue << 4 + 8
case .nullValue: return 9
case .error(let error): return error.hashValue << 4 + 10
}
}
public static func ==(lhs: JSONEvent, rhs: JSONEvent) -> Bool {
switch (lhs, rhs) {
case (.objectStart, .objectStart), (.objectEnd, .objectEnd),
(.arrayStart, .arrayStart), (.arrayEnd, .arrayEnd), (.nullValue, .nullValue):
return true
case let (.booleanValue(a), .booleanValue(b)):
return a == b
case let (.int64Value(a), .int64Value(b)):
return a == b
case let (.doubleValue(a), .doubleValue(b)):
return a == b
case let (.stringValue(a), .stringValue(b)):
return a == b
case let (.error(a), .error(b)):
return a == b
default:
return false
}
}
}
/// An iterator of `JSONEvent`s that records column/line info.
public protocol JSONEventIterator: IteratorProtocol {
/// The line of the last emitted token.
var line: UInt { get }
/// The column of the last emitted token.
var column: UInt { get }
}
@available(*, renamed: "JSONEventIterator")
public typealias JSONEventGenerator = JSONEventIterator
public struct JSONParserError: Error, Hashable, CustomStringConvertible {
/// A generic syntax error.
public static let invalidSyntax: Code = .invalidSyntax
/// An invalid number.
public static let invalidNumber: Code = .invalidNumber
/// An invalid string escape.
public static let invalidEscape: Code = .invalidEscape
/// A unicode string escape with an invalid code point.
public static let invalidUnicodeScalar: Code = .invalidUnicodeScalar
/// A unicode string escape representing a leading surrogate that wasn't followed
/// by a trailing surrogate, or a trailing surrogate that wasn't preceeded
/// by a leading surrogate.
public static let invalidSurrogateEscape: Code = .invalidSurrogateEscape
/// A control character in a string.
public static let controlCharacterInString: Code = .controlCharacterInString
/// A comma was found where a colon was expected in an object.
public static let expectedColon: Code = .expectedColon
/// A comma or colon was found in an object without a key.
public static let missingKey: Code = .missingKey
/// An object key was found that was not a string.
public static let nonStringKey: Code = .nonStringKey
/// A comma or object end was encountered where a value was expected.
public static let missingValue: Code = .missingValue
/// A trailing comma was found in an array or object. Only emitted when the parser is in strict mode.
public static let trailingComma: Code = .trailingComma
/// Trailing (non-whitespace) characters found after the close
/// of the root value.
/// - Note: This error cannot be thrown if the parser is in streaming mode.
public static let trailingCharacters: Code = .trailingCharacters
/// EOF was found before the root value finished parsing.
public static let unexpectedEOF: Code = .unexpectedEOF
@available(*, unavailable, renamed: "invalidSurrogateEscape")
public static let loneLeadingSurrogateInUnicodeEscape: Code = .invalidSurrogateEscape
public let code: Code
public let line: UInt
public let column: UInt
public init(code: Code, line: UInt, column: UInt) {
self.code = code
self.line = line
self.column = column
}
public var _code: Int { return code.rawValue }
public enum Code: Int {
/// A generic syntax error.
case invalidSyntax
/// An invalid number.
case invalidNumber
/// An invalid string escape.
case invalidEscape
/// A unicode string escape with an invalid code point.
case invalidUnicodeScalar
/// A unicode string escape representing a leading surrogate that wasn't followed
/// by a trailing surrogate, or a trailing surrogate that wasn't preceeded
/// by a leading surrogate.
case invalidSurrogateEscape
/// A control character in a string.
case controlCharacterInString
/// A comma was found where a colon was expected in an object.
case expectedColon
/// A comma or colon was found in an object without a key.
case missingKey
/// An object key was found that was not a string.
case nonStringKey
/// A comma or object end was encountered where a value was expected.
case missingValue
/// A trailing comma was found in an array or object. Only emitted when the parser is in strict mode.
case trailingComma
/// Trailing (non-whitespace) characters found after the close
/// of the root value.
/// - Note: This error cannot be thrown if the parser is in streaming mode.
case trailingCharacters
/// EOF was found before the root value finished parsing.
case unexpectedEOF
@available(*, unavailable, renamed: "invalidSurrogateEscape")
static let loneLeadingSurrogateInUnicodeEscape: Code = .invalidSurrogateEscape
public static func ~=(lhs: Code, rhs: Error) -> Bool {
if let error = rhs as? JSONParserError {
return lhs == error.code
} else {
return false
}
}
}
public var description: String {
return "JSONParserError(\(code), line: \(line), column: \(column))"
}
public var hashValue: Int {
return Int(bitPattern: line << 18) ^ Int(bitPattern: column << 4) ^ code.rawValue
}
public static func ==(lhs: JSONParserError, rhs: JSONParserError) -> Bool {
return (lhs.code, lhs.line, lhs.column) == (rhs.code, rhs.line, rhs.column)
}
}
private struct PeekIterator<Base: IteratorProtocol> {
init(_ base: Base) {
self.base = base
}
mutating func peek() -> Base.Element? {
if let elt = peeked {
return elt
}
let elt = base.next()
peeked = .some(elt)
return elt
}
mutating func next() -> Base.Element? {
if let elt = peeked {
peeked = nil
return elt
}
return base.next()
}
private var base: Base
private var peeked: Base.Element??
}
private func replace<T>(_ a: inout T, with b: T) -> T {
var b = b
swap(&a, &b)
return b
}
| bsd-3-clause |
slavapestov/swift | validation-test/compiler_crashers_fixed/28011-swift-typebase-getcanonicaltype.swift | 4 | 290 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T where g:a{func f{
{enum e{struct c{
class B<a{
let t:T.C
let:T.E
| apache-2.0 |
borglab/SwiftFusion | Sources/SwiftFusion/Probability/ProbabilityModel.swift | 1 | 1025 | // Copyright 2019 The SwiftFusion 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 TensorFlow
public protocol GenerativeDensity {
associatedtype HyperParameters
init(from data: Tensor<Double>, given: HyperParameters?)
@differentiable func negativeLogLikelihood(_ data: Tensor<Double>) -> Double
}
public extension GenerativeDensity {
/// Extension allows to have a default nil parameter
init(from data: Tensor<Double>) {
self.init(from: data, given: nil)
}
}
| apache-2.0 |
anirudh24seven/wikipedia-ios | Wikipedia/Code/PageHistorySection.swift | 1 | 300 | import Foundation
public class PageHistorySection: NSObject {
public let sectionTitle: String
public let items: [WMFPageHistoryRevision]
public init(sectionTitle: String, items: [WMFPageHistoryRevision]) {
self.sectionTitle = sectionTitle
self.items = items
}
} | mit |
sebcode/SwiftHelperKit | Source/File-Temp.swift | 1 | 457 | //
// File-Temp.swift
// SwiftHelperKit
//
// Copyright © 2015 Sebastian Volland. All rights reserved.
//
// File Extension to create temp files
import Foundation
extension FilePath {
public static func createTemp(_ prefix: String = "tmp") throws -> Self {
let tmpFile = Directory.tempDirectory().file("\(prefix)-\(UUID().uuidString)")
let new = self.init(name: tmpFile.name)
try new.create()
return new
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers/28450-underlyingty-gettype-isnull-getting-invalid-underlying-type-failed.swift | 2 | 479 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: asserts
class B{
typealias f:d typealias d:A
let d=c
protocol A
| apache-2.0 |
kstaring/swift | test/Parse/ConditionalCompilation/armAndroidTarget.swift | 7 | 455 | // RUN: %swift -parse %s -verify -D FOO -D BAR -target armv7-none-linux-androideabi -disable-objc-interop -D FOO -parse-stdlib
// RUN: %swift-ide-test -test-input-complete -source-filename=%s -target armv7-none-linux-androideabi
#if os(Linux)
// This block should not parse.
// os(Android) does not imply os(Linux).
let i: Int = "Hello"
#endif
#if arch(arm) && os(Android) && _runtime(_Native) && _endian(little)
class C {}
var x = C()
#endif
var y = x
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/00372-swift-declcontext-lookupqualified.swift | 11 | 429 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
enum S<T where g: c() -> {
var d = F
| apache-2.0 |
s-aska/Justaway-for-iOS | Justaway/HomeTimelineTableViewController.swift | 1 | 1980 | //
// SearchStatusTableViewController.swift
// Justaway
//
// Created by Shinichiro Aska on 1/25/15.
// Copyright (c) 2015 Shinichiro Aska. All rights reserved.
//
import Foundation
import KeyClip
import Async
class HomeTimelineTableViewController: StatusTableViewController {
override func saveCache() {
if self.adapter.rows.count > 0 {
let statuses = self.adapter.statuses
let dictionary = ["statuses": ( statuses.count > 100 ? Array(statuses[0 ..< 100]) : statuses ).map({ $0.dictionaryValue })]
_ = KeyClip.save("homeTimeline", dictionary: dictionary as NSDictionary)
NSLog("homeTimeline saveCache.")
}
}
override func loadCache(_ success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
Async.background {
if let cache = KeyClip.load("homeTimeline") as NSDictionary? {
if let statuses = cache["statuses"] as? [[String: AnyObject]] {
success(statuses.map({ TwitterStatus($0) }))
return
}
}
success([TwitterStatus]())
Async.background(after: 0.3, { () -> Void in
self.loadData(nil)
})
}
}
override func loadData(_ maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
Twitter.getHomeTimeline(maxID: maxID, success: success, failure: failure)
}
override func loadData(sinceID: String?, maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
Twitter.getHomeTimeline(maxID: maxID, sinceID: sinceID, success: success, failure: failure)
}
override func accept(_ status: TwitterStatus) -> Bool {
if status.event != nil {
return false
}
return true
}
}
| mit |
USAssignmentWarehouse/EnglishNow | EnglishNow/Model/Profile/Skill.swift | 1 | 317 | //
// skill.swift
// EnglishNow
//
// Created by Nha T.Tran on 6/12/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import Foundation
class Skill {
var level = 0 //0 / 5
var name = ""
var description = ""
init(name: String) {
self.name = name
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/20970-swift-nominaltypedecl-preparelookuptable.swift | 10 | 272 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c{
{
}class c{
class C{
struct B<T{
class d{protocol A:A
init(){
class b{struct A{
let a=
var b{ | mit |
huangboju/Moots | Examples/SwiftUI/SwiftUI-Apple/WorkingWithUIControls/StartingPoint/Landmarks/Landmarks/LandmarkDetail.swift | 10 | 2088 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view showing the details for a landmark.
*/
import SwiftUI
struct LandmarkDetail: View {
@EnvironmentObject var userData: UserData
var landmark: Landmark
var landmarkIndex: Int {
userData.landmarks.firstIndex(where: { $0.id == landmark.id })!
}
var body: some View {
VStack {
MapView(coordinate: landmark.locationCoordinate)
.edgesIgnoringSafeArea(.top)
.frame(height: 300)
CircleImage(image: landmark.image)
.offset(x: 0, y: -130)
.padding(.bottom, -130)
VStack(alignment: .leading) {
HStack {
Text(landmark.name)
.font(.title)
Button(action: {
self.userData.landmarks[self.landmarkIndex]
.isFavorite.toggle()
}) {
if self.userData.landmarks[self.landmarkIndex]
.isFavorite {
Image(systemName: "star.fill")
.foregroundColor(Color.yellow)
} else {
Image(systemName: "star")
.foregroundColor(Color.gray)
}
}
}
HStack(alignment: .top) {
Text(landmark.park)
.font(.subheadline)
Spacer()
Text(landmark.state)
.font(.subheadline)
}
}
.padding()
Spacer()
}
}
}
struct LandmarkDetail_Previews: PreviewProvider {
static var previews: some View {
let userData = UserData()
return LandmarkDetail(landmark: userData.landmarks[0])
.environmentObject(userData)
}
}
| mit |
huangboju/Moots | Examples/SwiftUI/Mac/YouTube-Downloader-for-macOS-master/Youtube Downloader/NSImageView_ScaleAspectFill.swift | 1 | 1327 | import Cocoa
@IBDesignable
class NSImageView_ScaleAspectFill: NSImageView {
@IBInspectable
var scaleAspectFill : Bool = false
override func awakeFromNib() {
// Scaling : .scaleNone mandatory
if scaleAspectFill { self.imageScaling = .scaleNone }
}
override func draw(_ dirtyRect: NSRect) {
if scaleAspectFill, let _ = self.image {
// Compute new Size
let imageViewRatio = self.image!.size.height / self.image!.size.width
let nestedImageRatio = self.bounds.size.height / self.bounds.size.width
var newWidth = self.image!.size.width
var newHeight = self.image!.size.height
if imageViewRatio > nestedImageRatio {
newWidth = self.bounds.size.width
newHeight = self.bounds.size.width * imageViewRatio
} else {
newWidth = self.bounds.size.height / imageViewRatio
newHeight = self.bounds.size.height
}
self.image!.size.width = newWidth
self.image!.size.height = newHeight
}
// Draw AFTER resizing
super.draw(dirtyRect)
}
}
| mit |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIToastContentView.swift | 1 | 9489 | //
// QMUIToastContentView.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
/**
* `QMUIToastView`默认使用的contentView。其结构是:customView->textLabel->detailTextLabel等三个view依次往下排列。其中customView可以赋值任意的UIView或者自定义的view。
*
* @TODO: 增加多种类型的progressView的支持。
*/
class QMUIToastContentView: UIView {
/**
* 设置一个UIView,可以是:菊花、图片等等
*/
var customView: UIView? {
willSet {
guard let notNilCustomView = customView else {
return
}
notNilCustomView.removeFromSuperview()
}
didSet {
guard let notNilCustomView = customView else {
return
}
addSubview(notNilCustomView)
updateCustomViewTintColor()
setNeedsLayout()
}
}
/**
* 设置第一行大文字label
*/
var textLabel: UILabel = UILabel()
/**
* 通过textLabelText设置可以应用textLabelAttributes的样式,如果通过textLabel.text设置则可能导致一些样式失效。
*/
var textLabelText: String = "" {
didSet {
textLabel.attributedText = NSAttributedString(string: textLabelText, attributes: textLabelAttributes)
textLabel.textAlignment = .center
setNeedsDisplay()
}
}
/**
* 设置第二行小文字label
*/
var detailTextLabel: UILabel = UILabel()
/**
* 通过detailTextLabelText设置可以应用detailTextLabelAttributes的样式,如果通过detailTextLabel.text设置则可能导致一些样式失效。
*/
var detailTextLabelText: String = "" {
didSet {
detailTextLabel.attributedText = NSAttributedString(string: detailTextLabelText, attributes: detailTextLabelAttributes)
detailTextLabel.textAlignment = .center
setNeedsDisplay()
}
}
/**
* 设置上下左右的padding。
*/
var insets: UIEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) {
didSet {
setNeedsLayout()
}
}
/**
* 设置最小size。
*/
var minimumSize: CGSize = .zero {
didSet {
setNeedsLayout()
}
}
/**
* 设置customView的marginBottom
*/
var customViewMarginBottom: CGFloat = 8 {
didSet {
setNeedsLayout()
}
}
/**
* 设置textLabel的marginBottom
*/
var textLabelMarginBottom: CGFloat = 4 {
didSet {
setNeedsLayout()
}
}
/**
* 设置detailTextLabel的marginBottom
*/
var detailTextLabelMarginBottom: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
/**
* 设置textLabel的attributes
*/
var textLabelAttributes = [NSAttributedString.Key.font: UIFontBoldMake(16), NSAttributedString.Key.foregroundColor: UIColorWhite, NSAttributedString.Key.paragraphStyle: NSMutableParagraphStyle(lineHeight: 22)] {
didSet {
if textLabelText.length > 0 {
// 刷新label的Attributes
let tmpStr = textLabelText
textLabelText = tmpStr
}
}
}
/**
* 设置detailTextLabel的attributes
*/
var detailTextLabelAttributes = [NSAttributedString.Key.font: UIFontBoldMake(12), NSAttributedString.Key.foregroundColor: UIColorWhite, NSAttributedString.Key.paragraphStyle: NSMutableParagraphStyle(lineHeight: 18)] {
didSet {
if detailTextLabelText.length > 0 {
// 刷新label的Attributes
let tmpStr = detailTextLabelText
detailTextLabelText = tmpStr
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubviews()
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let hasCustomeView = customView != nil
let hasTextLabel = textLabel.text?.length ?? 0 > 0
let hasDetailTextLabel = detailTextLabel.text?.length ?? 0 > 0
var width: CGFloat = 0
var height: CGFloat = 0
let maxContentWidth = size.width - insets.horizontalValue
let maxContentHeight = size.height - insets.verticalValue
if hasCustomeView {
width = max(width, customView?.bounds.width ?? 0)
height += (customView?.bounds.height ?? 0 + ((hasTextLabel || hasDetailTextLabel) ? customViewMarginBottom : 0))
}
if hasTextLabel {
let textLabelSize = textLabel.sizeThatFits(CGSize(width: maxContentWidth, height: maxContentHeight))
width = max(width, textLabelSize.width)
height += textLabelSize.height + (hasDetailTextLabel ? textLabelMarginBottom : 0)
}
if hasDetailTextLabel {
let detailTextLabelSize = detailTextLabel.sizeThatFits(CGSize(width: maxContentWidth, height: maxContentHeight))
width = max(width, detailTextLabelSize.width)
height += (detailTextLabelSize.height + detailTextLabelMarginBottom)
}
width += insets.horizontalValue
height += insets.verticalValue
if minimumSize != .zero {
width = max(width, minimumSize.width)
height = max(height, minimumSize.height)
}
return CGSize(width: min(size.width, width),
height: min(size.height, height))
}
override func layoutSubviews() {
super.layoutSubviews()
let hasCustomView = customView != nil
let hasTextLabel = textLabel.text?.length ?? 0 > 0
let hasDetailTextLabel = detailTextLabel.text?.length ?? 0 > 0
let contentWidth = bounds.width
let maxContentWidth = contentWidth - insets.horizontalValue
var minY = insets.top
if hasCustomView {
if !hasTextLabel && !hasDetailTextLabel {
// 处理有minimumSize的情况
minY = bounds.height.center(customView?.bounds.height ?? 0)
}
customView?.frame = CGRectFlat(contentWidth.center(customView?.bounds.width ?? 0),
minY,
customView?.bounds.width ?? 0,
customView?.bounds.height ?? 0)
minY = customView?.frame.maxY ?? 0 + customViewMarginBottom
}
if hasTextLabel {
let textLabelSize = textLabel.sizeThatFits(CGSize(width: maxContentWidth, height: .greatestFiniteMagnitude))
if !hasCustomView && !hasDetailTextLabel {
// 处理有minimumSize的情况
minY = bounds.height.center(textLabelSize.height)
}
textLabel.frame = CGRectFlat(contentWidth.center(maxContentWidth),
minY,
maxContentWidth,
textLabelSize.height)
minY = textLabel.frame.maxY + textLabelMarginBottom
}
if hasDetailTextLabel {
// 暂时没考虑剩余高度不够用的情况
let detailTextLabelSize = detailTextLabel.sizeThatFits(CGSize(width: maxContentWidth, height: .greatestFiniteMagnitude))
if !hasCustomView && !hasTextLabel {
// 处理有minimumSize的情况
minY = bounds.height.center(detailTextLabelSize.height)
}
detailTextLabel.frame = CGRectFlat(contentWidth.center(maxContentWidth),
minY,
maxContentWidth,
detailTextLabelSize.height)
}
}
override func tintColorDidChange() {
if customView != nil {
updateCustomViewTintColor()
}
textLabelAttributes[.foregroundColor] = tintColor
let tmpStr = textLabelText
textLabelText = tmpStr
detailTextLabelAttributes[.foregroundColor] = tintColor
let detailTmpStr = detailTextLabelText
detailTextLabelText = detailTmpStr
}
private func initSubviews() {
textLabel.numberOfLines = 0
textLabel.textAlignment = .center
textLabel.textColor = UIColorWhite
textLabel.font = UIFontBoldMake(16)
textLabel.isOpaque = false
addSubview(textLabel)
detailTextLabel.numberOfLines = 0
detailTextLabel.textAlignment = .center
detailTextLabel.textColor = UIColorWhite
detailTextLabel.font = UIFontBoldMake(12)
detailTextLabel.isOpaque = false
addSubview(detailTextLabel)
}
private func updateCustomViewTintColor() {
guard let notNilCustomView = customView else {
return
}
notNilCustomView.tintColor = tintColor
if let imageView = notNilCustomView as? UIImageView {
imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
}
if let activityView = notNilCustomView as? UIActivityIndicatorView {
activityView.color = tintColor
}
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/27348-swift-constraints-constraintsystem-solve.swift | 9 | 319 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{
struct B<T where g:A{
struct B{struct a{
}
class c{
struct B{
var d=f
var f:a{
{var _=f
| apache-2.0 |
felipecarreramo/R3LRackspace | Pod/Classes/CFContainer.swift | 1 | 606 | //
// CFContainer.swift
// Pods
//
// Created by Felipe Carrera on 30/12/15.
//
//
import Foundation
public struct CFContainer {
public var name: String?
public var uri: String?
public var objects: [CFObject]?
private let network: Network
init() {
network = Network(authURL: CFConstants.AuthURL)
}
public static func containerBy(name: String) -> CFContainer {
var container = CFContainer()
container.name = name
return container
}
public func sync(completion:(success: Bool)->()) {
}
} | mit |
Malibris/TheLoneWalker | TheLoneWalkerTests/TheLoneWalkerTests.swift | 1 | 1006 | //
// TheLoneWalkerTests.swift
// TheLoneWalkerTests
//
// Created by Robert Abramczyk on 01/10/2017.
// Copyright © 2017 Robert Abramczyk. All rights reserved.
//
import XCTest
@testable import TheLoneWalker
class TheLoneWalkerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| gpl-3.0 |
huonw/swift | test/SILGen/default_arguments_generic.swift | 1 | 3129 |
// RUN: %target-swift-emit-silgen -module-name default_arguments_generic -enable-sil-ownership -swift-version 3 %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name default_arguments_generic -enable-sil-ownership -swift-version 4 %s | %FileCheck %s
func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
struct Zim<T: ExpressibleByIntegerLiteral> {
init(x: T = 0) { }
init<U: ExpressibleByFloatLiteral>(_ x: T = 0, y: U = 0.5) { }
static func zim(x: T = 0) { }
static func zang<U: ExpressibleByFloatLiteral>(_: U.Type, _ x: T = 0, y: U = 0.5) { }
}
// CHECK-LABEL: sil hidden @$S25default_arguments_generic3baryyF : $@convention(thin) () -> () {
func bar() {
// CHECK: [[FOO_DFLT:%.*]] = function_ref @$S25default_arguments_generic3foo
// CHECK: apply [[FOO_DFLT]]<Int>
foo(Int.self)
// CHECK: [[ZIM_DFLT:%.*]] = function_ref @$S25default_arguments_generic3ZimV3zim
// CHECK: apply [[ZIM_DFLT]]<Int>
Zim<Int>.zim()
// CHECK: [[ZANG_DFLT_0:%.*]] = function_ref @$S25default_arguments_generic3ZimV4zang{{.*}}A0_
// CHECK: apply [[ZANG_DFLT_0]]<Int, Double>
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @$S25default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self)
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @$S25default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self, 22)
}
protocol Initializable {
init()
}
struct Generic<T: Initializable> {
init(_ value: T = T()) {}
}
struct InitializableImpl: Initializable {
init() {}
}
// CHECK-LABEL: sil hidden @$S25default_arguments_generic17testInitializableyyF
func testInitializable() {
// The ".init" is required to trigger the crash that used to happen.
_ = Generic<InitializableImpl>.init()
// CHECK: function_ref @$S25default_arguments_generic7GenericVyACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
// CHECK: [[INIT:%.+]] = function_ref @$S25default_arguments_generic7GenericVyACyxGxcfC
// CHECK: apply [[INIT]]<InitializableImpl>({{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : Initializable> (@in τ_0_0, @thin Generic<τ_0_0>.Type) -> Generic<τ_0_0>
} // CHECK: end sil function '$S25default_arguments_generic17testInitializableyyF'
// Local generic functions with default arguments
// CHECK-LABEL: sil hidden @$S25default_arguments_generic5outer1tyx_tlF : $@convention(thin) <T> (@in_guaranteed T) -> ()
func outer<T>(t: T) {
func inner1(x: Int = 0) {}
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @$S25default_arguments_generic5outer1tyx_tlF6inner1L_1xySi_tlFfA_ : $@convention(thin) () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]() : $@convention(thin) () -> Int
_ = inner1()
func inner2(x: Int = 0) { _ = T.self }
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @$S25default_arguments_generic5outer1tyx_tlF6inner2L_1xySi_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]<T>() : $@convention(thin) <τ_0_0> () -> Int
_ = inner2()
}
| apache-2.0 |
channelade/channelade-tvos | Channelade/Channelade/AppDelegate.swift | 1 | 3708 | /*
Channelade starter app for Apple TV
To get this app working for your channel,
make sure to do the following:
- Add your Channelade account key below
- Change the bundle identifier
- Add your own artwork (icons and shelf image)
*/
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
// MARK: Properties
///////////////////////////////////////////////////////
// Edit the following line with
// Your Channelade account key
///////////////////////////////////////////////////////
static let TVAccountKey = "PUT YOUR ACCOUNT KEY HERE"
///////////////////////////////////////////////////////
// That's it! Don't edit anything else below
///////////////////////////////////////////////////////
static let TVBaseURL = "https://tvos.channelade.com/"
static let TVBootURL = "\(AppDelegate.TVBaseURL)tvos/\(AppDelegate.TVAccountKey)/application.js"
var window: UIWindow?
var appController: TVApplicationController?
// MARK: UIApplication Overrides
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
/*
Create the TVApplicationControllerContext for this application
and set the properties that will be passed to the `App.onLaunch` function
in JavaScript.
*/
let appControllerContext = TVApplicationControllerContext()
/*
The JavaScript URL is used to create the JavaScript context for your
TVMLKit application. Although it is possible to separate your JavaScript
into separate files, to help reduce the launch time of your application
we recommend creating minified and compressed version of this resource.
This will allow for the resource to be retrieved and UI presented to
the user quickly.
*/
if let javaScriptURL = NSURL(string: AppDelegate.TVBootURL) {
appControllerContext.javaScriptApplicationURL = javaScriptURL
}
appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL
if let launchOptions = launchOptions as? [String: AnyObject] {
for (kind, value) in launchOptions {
appControllerContext.launchOptions[kind] = value
}
}
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
// MARK: TVApplicationControllerDelegate
func appController(appController: TVApplicationController, didFinishLaunchingWithOptions options: [String: AnyObject]?) {
print("\(__FUNCTION__) invoked with options: \(options)")
}
func appController(appController: TVApplicationController, didFailWithError error: NSError) {
print("\(__FUNCTION__) invoked with error: \(error)")
let title = "Error Launching Application"
let message = error.localizedDescription
let alertController = UIAlertController(title: title, message: message, preferredStyle:.Alert )
self.appController?.navigationController.presentViewController(alertController, animated: true, completion: { () -> Void in
// ...
})
}
func appController(appController: TVApplicationController, didStopWithOptions options: [String: AnyObject]?) {
print("\(__FUNCTION__) invoked with options: \(options)")
}
} | mit |
WEIHOME/SearchBarDemo-Swift | SearchBarDemoTests/SearchBarDemoTests.swift | 1 | 918 | //
// SearchBarDemoTests.swift
// SearchBarDemoTests
//
// Created by Weihong Chen on 30/04/2015.
// Copyright (c) 2015 Weihong. All rights reserved.
//
import UIKit
import XCTest
class SearchBarDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
csnu17/My-Swift-learning | MVVMSwiftExample/MVVMSwiftExample/GameLibrary.swift | 1 | 662 | //
// GameLibrary.swift
// MVVMExample
//
// Created by Dino Bartosak on 18/09/16.
// Copyright © 2016 Toptal. All rights reserved.
//
import Foundation
enum GameLibraryNotifications {
static let GameLibraryGameAdded = "GameLibraryGameAdded"
static let GameLibraryGameRemoved = "GameLibraryGameRemoved"
static let GameLibraryGameUpdated = "GameLibraryGameUpdated"
}
protocol GameLibrary {
func allGames() -> [Game]
func addGame(_ game: Game) // posts GameLibraryGameAdded notifications
func removeGame(_ game: Game) // posts GameLibraryGameRemoved notifications
func updateGame(_ game: Game) // posts GameLibraryGameUpdated notifications
}
| mit |
ryet231ere/DouYuSwift | douyu/douyu/Classes/Main/Controller/BaseAnchorViewController.swift | 1 | 4250 | //
// BaseAnchorViewController.swift
// douyu
//
// Created by 练锦波 on 2017/3/9.
// Copyright © 2017年 练锦波. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
let kPrettyCellID = "kPrettyCellID"
let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH = kNormalItemW * 3 / 4
let kPrettyItemH = kNormalItemW * 4 / 3
class BaseAnchorViewController: BassViewController {
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建uicollectionview
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
extension BaseAnchorViewController {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
extension BaseAnchorViewController {
func loadData() {
}
}
extension BaseAnchorViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
headerView.group = baseVM.anchorGroups[indexPath.section]
return headerView
}
}
extension BaseAnchorViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
anchor.isVertical == 0 ? pushNormalRoomVC() : presentShowRoomVC()
}
private func presentShowRoomVC() {
let showRoomVc = RoomShowViewController()
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVC() {
let normalRoomVc = RoomNormalViewController()
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
| mit |
cfraz89/RxSwift | scripts/package-spm.swift | 1 | 11618 | #!/usr/bin/swift
//
// package-spm.swift
// scripts
//
// Created by Krunoslav Zaher on 12/26/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
This script packages normal Rx* structure into `Sources` directory.
* creates and updates links to normal project structure
* builds unit tests `main.swift`
Unfortunately, Swift support for Linux, libdispatch and package manager are still quite unstable,
so certain class of unit tests is excluded for now.
*/
// It is kind of ironic that we need to additionally package for package manager :/
let fileManager = FileManager.default
let allowedExtensions = [
".swift",
".h",
".m",
]
// Those tests are dependent on conditional compilation logic and it's hard to handle them automatically
// They usually test some internal state, so it should be ok to exclude them for now.
let excludedTests: [String] = [
"testConcat_TailRecursionCollection",
"testConcat_TailRecursionSequence",
"testMapCompose_OptimizationIsPerformed",
"testMapCompose_OptimizationIsNotPerformed",
"testObserveOn_EnsureCorrectImplementationIsChosen",
"testObserveOnDispatchQueue_EnsureCorrectImplementationIsChosen",
"testResourceLeaksDetectionIsTurnedOn",
"testAnonymousObservable_disposeReferenceDoesntRetainObservable",
"testObserveOnDispatchQueue_DispatchQueueSchedulerIsSerial",
"ReleasesResourcesOn",
"testShareReplayLatestWhileConnectedDisposableDoesntRetainAnything",
"testSingle_DecrementCountsFirst",
"testSinglePredicate_DecrementCountsFirst",
"testLockUnlockCountsResources"
]
func excludeTest(_ name: String) -> Bool {
for exclusion in excludedTests {
if name.contains(exclusion) {
return true
}
}
return false
}
let excludedTestClasses: [String] = [
/*"ObservableConcurrentSchedulerConcurrencyTest",
"SubjectConcurrencyTest",
"VirtualSchedulerTest",
"HistoricalSchedulerTest"*/
"BagTest"
]
let throwingWordsInTests: [String] = [
/*"error",
"fail",
"throw",
"retrycount",
"retrywhen",*/
]
func isExtensionAllowed(_ path: String) -> Bool {
return (allowedExtensions.map { path.hasSuffix($0) }).reduce(false) { $0 || $1 }
}
func checkExtension(_ path: String) throws {
if !isExtensionAllowed(path) {
throw NSError(domain: "Security", code: -1, userInfo: ["path" : path])
}
}
func packageRelativePath(_ paths: [String], targetDirName: String, excluded: [String] = []) throws {
let targetPath = "Sources/\(targetDirName)"
print("Checking " + targetPath)
for file in try fileManager.contentsOfDirectory(atPath: targetPath) {
if file != "include" && file != ".DS_Store" {
print("Checking extension \(file)")
try checkExtension(file)
print("Cleaning \(file)")
try fileManager.removeItem(atPath: "\(targetPath)/\(file)")
}
}
for sourcePath in paths {
var isDirectory: ObjCBool = false
fileManager.fileExists(atPath: sourcePath, isDirectory: &isDirectory)
let files: [String] = isDirectory.boolValue ? fileManager.subpaths(atPath: sourcePath)!
: [sourcePath]
for file in files {
if !isExtensionAllowed(file) {
print("Skipping \(file)")
continue
}
if excluded.contains(file) {
print("Skipping \(file)")
continue
}
let fileRelativePath = isDirectory.boolValue ? "\(sourcePath)/\(file)" : file
let destinationURL = NSURL(string: "../../\(fileRelativePath)")!
let fileName = (file as NSString).lastPathComponent
let atURL = NSURL(string: "file:///\(fileManager.currentDirectoryPath)/\(targetPath)/\(fileName)")!
if fileName.hasSuffix(".h") {
let sourcePath = NSURL(string: "file:///" + fileManager.currentDirectoryPath + "/" + sourcePath + "/" + file)!
//throw NSError(domain: sourcePath.description, code: -1, userInfo: nil)
try fileManager.copyItem(at: sourcePath as URL, to: atURL as URL)
}
else {
print("Linking \(fileName) [\(atURL)] -> \(destinationURL)")
try fileManager.createSymbolicLink(at: atURL as URL, withDestinationURL: destinationURL as URL)
}
}
}
}
func buildAllTestsTarget(_ testsPath: String) throws {
let splitClasses = "(?:class|extension)\\s+(\\w+)"
let testMethods = "\\s+func\\s+(test\\w+)"
let splitClassesRegularExpression = try! NSRegularExpression(pattern: splitClasses, options:[])
let testMethodsExpression = try! NSRegularExpression(pattern: testMethods, options: [])
var reducedMethods: [String: [String]] = [:]
for file in try fileManager.contentsOfDirectory(atPath: testsPath) {
if !file.hasSuffix(".swift") || file == "main.swift" {
continue
}
let fileRelativePath = "\(testsPath)/\(file)"
let testContent = try String(contentsOfFile: fileRelativePath, encoding: String.Encoding.utf8)
print(fileRelativePath)
let classMatches = splitClassesRegularExpression.matches(in: testContent as String, options: [], range: NSRange(location: 0, length: testContent.characters.count))
let matchIndexes = classMatches
.map { $0.range.location }
let classNames = classMatches.map { (testContent as NSString).substring(with: $0.rangeAt(1)) as NSString }
let ranges = zip([0] + matchIndexes, matchIndexes + [testContent.characters.count]).map { NSRange(location: $0, length: $1 - $0) }
let classRanges = ranges[1 ..< ranges.count]
let classes = zip(classNames, classRanges.map { (testContent as NSString).substring(with: $0) as NSString })
for (name, classCode) in classes {
if excludedTestClasses.contains(name as String) {
print("Skipping \(name)")
continue
}
let methodMatches = testMethodsExpression.matches(in: classCode as String, options: [], range: NSRange(location: 0, length: classCode.length))
let methodNameRanges = methodMatches.map { $0.rangeAt(1) }
let testMethodNames = methodNameRanges
.map { classCode.substring(with: $0) }
.filter { !excludeTest($0) }
if testMethodNames.count == 0 {
continue
}
let existingMethods = reducedMethods[name as String] ?? []
reducedMethods[name as String] = existingMethods + testMethodNames
}
}
var mainContent = [String]()
mainContent.append("// this file is autogenerated using `./scripts/package-swift-manager.swift`")
mainContent.append("import XCTest")
mainContent.append("import RxSwift")
mainContent.append("")
mainContent.append("protocol RxTestCase {")
mainContent.append("#if os(macOS)")
mainContent.append(" init()")
mainContent.append(" static var allTests: [(String, (Self) -> () -> ())] { get }")
mainContent.append("#endif")
mainContent.append(" func setUp()")
mainContent.append(" func tearDown()")
mainContent.append("}")
mainContent.append("")
for (name, methods) in reducedMethods {
mainContent.append("")
mainContent.append("final class \(name)_ : \(name), RxTestCase {")
mainContent.append(" #if os(macOS)")
mainContent.append(" required override init() {")
mainContent.append(" super.init()")
mainContent.append(" }")
mainContent.append(" #endif")
mainContent.append("")
mainContent.append(" static var allTests: [(String, (\(name)_) -> () -> ())] { return [")
for method in methods {
// throwing error on Linux, you will crash
let isTestCaseHandlingError = throwingWordsInTests.map { (method as String).lowercased().contains($0) }.reduce(false) { $0 || $1 }
mainContent.append(" \(isTestCaseHandlingError ? "//" : "")(\"\(method)\", \(name).\(method)),")
}
mainContent.append(" ] }")
mainContent.append("}")
}
mainContent.append("#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)")
mainContent.append("")
mainContent.append("func testCase<T: RxTestCase>(_ tests: [(String, (T) -> () -> ())]) -> () -> () {")
mainContent.append(" return {")
mainContent.append(" for testCase in tests {")
mainContent.append(" print(\"Test \\(testCase)\")")
mainContent.append(" for test in T.allTests {")
mainContent.append(" let testInstance = T()")
mainContent.append(" testInstance.setUp()")
mainContent.append(" print(\" testing \\(test.0)\")")
mainContent.append(" test.1(testInstance)()")
mainContent.append(" testInstance.tearDown()")
mainContent.append(" }")
mainContent.append(" }")
mainContent.append(" }")
mainContent.append("}")
mainContent.append("")
mainContent.append("func XCTMain(_ tests: [() -> ()]) {")
mainContent.append(" for testCase in tests {")
mainContent.append(" testCase()")
mainContent.append(" }")
mainContent.append("}")
mainContent.append("")
mainContent.append("#endif")
mainContent.append("")
mainContent.append(" XCTMain([")
for testCase in reducedMethods.keys {
mainContent.append(" testCase(\(testCase)_.allTests),")
}
mainContent.append(" ])")
mainContent.append("//}")
mainContent.append("")
let serializedMainContent = mainContent.joined(separator: "\n")
try serializedMainContent.write(toFile: "\(testsPath)/main.swift", atomically: true, encoding: String.Encoding.utf8)
}
try packageRelativePath(["RxSwift"], targetDirName: "RxSwift")
//try packageRelativePath(["RxCocoa/Common", "RxCocoa/macOS", "RxCocoa/RxCocoa.h"], targetDirName: "RxCocoa")
try packageRelativePath([
"RxCocoa/RxCocoa.swift",
"RxCocoa/CocoaUnits",
"RxCocoa/Common",
"RxCocoa/Foundation",
"RxCocoa/iOS",
"RxCocoa/macOS",
"RxCocoa/Platform",
], targetDirName: "RxCocoa")
try packageRelativePath([
"RxCocoa/Runtime/include",
], targetDirName: "RxCocoaRuntime/include")
try packageRelativePath([
"RxCocoa/Runtime/_RX.m",
"RxCocoa/Runtime/_RXDelegateProxy.m",
"RxCocoa/Runtime/_RXKVOObserver.m",
"RxCocoa/Runtime/_RXObjCRuntime.m",
], targetDirName: "RxCocoaRuntime")
try packageRelativePath(["RxBlocking"], targetDirName: "RxBlocking")
try packageRelativePath(["RxTest"], targetDirName: "RxTest")
// It doesn't work under `Tests` subpath ¯\_(ツ)_/¯
try packageRelativePath([
"Tests/RxSwiftTests",
"Tests/RxBlockingTests",
"RxSwift/RxMutableBox.swift",
"Tests/RxTest.swift",
"Tests/Recorded+Timeless.swift",
"Tests/TestErrors.swift",
"Tests/XCTest+AllTests.swift",
"Platform",
"Tests/RxCocoaTests/Driver+Test.swift",
"Tests/RxCocoaTests/Driver+Extensions.swift",
"Tests/RxCocoaTests/NotificationCenterTests.swift",
],
targetDirName: "AllTestz",
excluded: [
"Tests/VirtualSchedulerTest.swift",
"Tests/HistoricalSchedulerTest.swift",
// @testable import doesn't work well in Linux :/
"BagTest.swift"
])
try buildAllTestsTarget("Sources/AllTestz")
| mit |
N26-OpenSource/bob | Sources/Bob/APIs/GitHub/GitHub.swift | 1 | 7171 | /*
* Copyright (c) 2017 N26 GmbH.
*
* This file is part of Bob.
*
* Bob is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bob is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bob. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import HTTP
import Vapor
enum GitHubError: LocalizedError {
case invalidBranch(name: String)
case invalidParam(String)
case invalidStatus(httpStatus: UInt, body: String?)
case decoding(String)
public var errorDescription: String? {
switch self {
case .decoding(let message):
return "Decoding error: \(message)"
case .invalidBranch(let name):
return "The branch '\(name)' does not exists"
case .invalidParam(let param):
return "Invalid parameter '\(param)'"
case .invalidStatus(let httpStatus, let body):
var message = "Invalid response status '\(httpStatus)')"
body.flatMap { message += " body: \($0)" }
return message
}
}
}
/// Used for communicating with the GitHub api
public class GitHub {
/// Configuration needed for authentication with the api
public struct Configuration {
public let username: String
public let personalAccessToken: String
public let repoUrl: String
/// Initializer for the configuration
///
/// - Parameters:
/// - username: Username of a user
/// - personalAccessToken: Personal access token for that user. Make sure it has repo read/write for the repo you intend to use
/// - repoUrl: Url of the repo. Alogn the lines of https://api.github.com/repos/{owner}/{repo}
public init(username: String, personalAccessToken: String, repoUrl: String) {
self.username = username
self.personalAccessToken = personalAccessToken
self.repoUrl = repoUrl
}
}
private let authorization: BasicAuthorization
private let repoUrl: String
private let container: Container
public var worker: Worker {
return container
}
public init(config: Configuration, container: Container) {
self.authorization = BasicAuthorization(username: config.username, password: config.personalAccessToken)
self.repoUrl = config.repoUrl
self.container = container
}
private func uri(at path: String) -> String {
return self.repoUrl + path
}
// MARK: Repository APIs
public func branches() throws -> Future<[GitHub.Repos.Branch]> {
return try get(uri(at: "/branches?per_page=100"))
}
public func branch(_ branch: GitHub.Repos.Branch.BranchName) throws -> Future<GitHub.Repos.BranchDetail> {
return try get(uri(at: "/branches/" + branch))
}
/// Lists the content of a directory
public func contents(at path: String, on branch: GitHub.Repos.Branch.BranchName) throws -> Future<[GitHub.Repos.GitContent]> {
return try get(uri(at: "/contents/\(path)?ref=" + branch))
}
/// Content of a single file
public func content(at path: String, on branch: GitHub.Repos.Branch.BranchName) throws -> Future<GitHub.Repos.GitContent> {
return try get(uri(at: "/contents/\(path)?ref=" + branch))
}
public func tags() throws -> Future<[GitHub.Repos.Tag]> {
return try get(uri(at: "/tags"))
}
/// Returns a list of commits in reverse chronological order
///
/// - Parameters:
/// - sha: Starting commit
/// - page: Index of the requested page
/// - perPage: Number of commits per page
/// - path: Directory within repository (optional). Only commits with files touched within path will be returned
public func commits(after sha: String? = nil, page: Int? = nil, perPage: Int? = nil, path: String? = nil) throws -> Future<[GitHub.Repos.Commit]> {
var components = URLComponents(string: "")!
var items = [URLQueryItem]()
components.path = "/commits"
if let sha = sha {
items.append(URLQueryItem(name: "sha", value: sha))
}
if let page = page {
items.append(URLQueryItem(name: "page", value: "\(page)"))
}
if let perPage = perPage {
items.append(URLQueryItem(name: "per_page", value: "\(perPage)"))
}
if let path = path {
items.append(URLQueryItem(name: "path", value: "\(path)"))
}
components.queryItems = items
guard let url = components.url else { throw GitHubError.invalidParam("Could not create commit URL") }
let uri = self.uri(at: url.absoluteString)
return try get(uri)
}
// MARK: - Git APIs
public func gitCommit(sha: GitHub.Git.Commit.SHA) throws -> Future<GitHub.Git.Commit> {
return try get(uri(at: "/git/commits/" + sha))
}
public func gitBlob(sha: Git.TreeItem.SHA) throws -> Future<GitHub.Git.Blob> {
return try get(uri(at: "/git/blobs/" + sha))
}
public func newBlob(data: String) throws -> Future<GitHub.Git.Blob.New.Response> {
let blob = GitHub.Git.Blob.New(content: data)
return try post(body: blob, to: uri(at: "/git/blobs"))
}
public func trees(for treeSHA: GitHub.Git.Tree.SHA) throws -> Future<GitHub.Git.Tree> {
return try self.get(uri(at: "/git/trees/" + treeSHA + "?recursive=1"))
}
public func newTree(tree: Tree.New) throws -> Future<Tree> {
return try post(body: tree, to: uri(at: "/git/trees"))
}
/// https://developer.github.com/v3/git/commits/#create-a-commit
public func newCommit(by author: Author, message: String, parentSHA: String, treeSHA: String) throws -> Future<GitHub.Git.Commit> {
let body = GitCommit.New(message: message, tree: treeSHA, parents: [parentSHA], author: author)
return try post(body: body, to: uri(at: "/git/commits"))
}
public func updateRef(to sha: GitHub.Git.Commit.SHA, on branch: GitHub.Repos.Branch.BranchName) throws -> Future<GitHub.Git.Reference> {
let body = GitHub.Git.Reference.Patch(sha: sha)
return try post(body: body, to: uri(at: "/git/refs/heads/" + branch), patch: true)
}
// MARK: - Private
private func get<T: Content>(_ uri: String) throws -> Future<T> {
return try container.client().get(uri, using: GitHub.decoder, authorization: authorization)
}
private func post<Body: Content, T: Content>(body: Body, to uri: String, patch: Bool = false ) throws -> Future<T> {
return try container.client().post(body: body, to: uri, encoder: GitHub.encoder, using: GitHub.decoder, method: patch ? .PATCH : .POST, authorization: authorization)
}
}
| gpl-3.0 |
february29/Learning | swift/Fch_Contact/Fch_Contact/AppClasses/ViewModel/MainViewModel.swift | 1 | 13341 | //
// MainViewModel.swift
// Fch_Contact
//
// Created by bai on 2017/11/30.
// Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import RxSwift
import RxDataSources
import BAlertView
import Alamofire
class MainViewModel: NSObject {
var loadData = PublishSubject<(Int,String)>();
public var result:Observable<[SectionModel<String, PersonModel>]>?
var checkAppShouldUpdateSubject = PublishSubject<Bool>();
public var checkAppShouldUpdateResult:Observable<Result<Any>>?
var telBookDBShouldUpDateSubject = PublishSubject<Int>();
public var telBookDBShouldUpDateResult:Observable<Result<Any>>?
var telBookListSubject = PublishSubject<Int>();
public var telBookListResult:Observable<Result<Any>>?
override init() {
super.init();
prepare();
}
func prepare(){
result = loadData.flatMapLatest({ (depId,seartchStr) -> Observable<[SectionModel<String, PersonModel>]> in
if depId == -1 {
return self.getPersonsSorted(deptId: -1);
}else if depId > 0{
return self.getPersonsNoSorted(deptId: depId);
}else{
return self.getSearchedPersons(searchString: seartchStr);
}
})
checkAppShouldUpdateResult = checkAppShouldUpdateSubject.flatMapLatest { (isTimeOut) -> Observable<Result<Any>> in
return BNetWorkingManager.shared.RxRequset(url: AppUpdate_URL, method: .get);
}
telBookDBShouldUpDateResult = telBookDBShouldUpDateSubject.flatMapLatest({ (telBookId) -> Observable<Result<Any>> in
return BNetWorkingManager.shared.RxRequset(url: "\(TelBook_Detail_URL)/\(telBookId)", method: .get);
})
telBookListResult = telBookListSubject.flatMapLatest({ (userId) -> Observable<Result<Any>> in
let par = ["userId":userId];
return BNetWorkingManager.shared.RxRequset(url: TelBooksList_URL, method: .post,parameters: par);
})
}
/// 模糊搜索获取人员
///
/// - Parameter searchString: 搜索字符
/// - Returns: 搜索结果
func getPersons(searchString:String)->Observable<[PersonModel]> {
return Observable.create({ (observer) -> Disposable in
let persons = DBHelper.sharedInstance.getPersons(searchString: searchString);
observer.onNext(persons);
observer.onCompleted();
return Disposables.create {
}
})
}
/// 获取整理数据后 将数据整理成列表可用数据 无排序
///
/// - Parameter searchString: 搜索字符
/// - Returns: 搜索结果
func getSearchedPersons(searchString:String)->Observable<[SectionModel<String, PersonModel>]> {
return self.getPersons(searchString:searchString).map({ (persons) -> [SectionModel<String, PersonModel>] in
return [SectionModel(model: "", items: persons)]
});
}
/// 根据部门ID 获取部门人员
///
/// - Parameter deptId: 部门ID -1表示全部
/// - Returns: 部门人员
func getPersons(deptId:Int)->Observable<[PersonModel]> {
return Observable.create({ (observer) -> Disposable in
let persons = DBHelper.sharedInstance.getPersonsFromDB(deptId: deptId);
observer.onNext(persons);
observer.onCompleted();
return Disposables.create {
}
})
}
/// 根据部门ID获取排序后的人员
///
/// - Parameter deptId: 部门ID -1表示全部
/// - Returns: 人员
func getPersonsSorted(deptId:Int) -> Observable<[SectionModel<String, PersonModel>]> {
return self.getPersons(deptId:deptId).map({ (persons) -> [SectionModel<String, PersonModel>] in
var dic = Dictionary<String,[PersonModel]>();
for model in persons{
let firstUInt8 = UInt8(pinyinFirstLetter((model.column1 as NSString).character(at: 0)))
let firstString = String(Character( UnicodeScalar(firstUInt8)));
let hasContains = dic.keys.contains(where: { (key) -> Bool in
return key == firstString;
});
if !hasContains{
var itemArray = [PersonModel]();
itemArray.append(model);
dic[firstString] = itemArray;
}else{
dic[firstString]?.append(model);
}
}
let sortedArray = dic.sorted(by: { (o1, o2) -> Bool in
return o1.key < o2.key;
});
var sections:[SectionModel<String,PersonModel>] = [];
for item in sortedArray{
sections.append(SectionModel<String, PersonModel>.init(model: item.key, items: item.value));
}
return sections;
});
}
/// 根据部门ID 获取无排序的人员
///
/// - Parameter deptId: 部门ID
/// - Returns: 人员
func getPersonsNoSorted(deptId:Int) -> Observable<[SectionModel<String, PersonModel>]> {
return self.getPersons(deptId:deptId).map({ (persons) -> [SectionModel<String, PersonModel>] in
return [SectionModel(model: "", items: persons)]
});
}
func reloadData(depId:Int) {
loadData.onNext((depId,""));
}
func reloadData(searchString:String) {
loadData.onNext((-2,searchString));
}
// MARK: 网络请求
/// 验证imei 是否可用
///
/// - Parameter successHandler: 验证回掉
func fchCheckImeiVerify(successHandler:@escaping (_ isVerify:Bool)->Void) {
let uuid = AppLoginHelper.uuidInKeyChain();
let par = ["imei":uuid];
BNetWorkingManager.shared.request(url: TestIMEIVerify_URL,method: .get, parameters:par) { (response) in
if let value = response.result.value as? Dictionary<String, Any> {
if let error = value["error"] {
let errorStr = error as! String;
if errorStr == "验证失败"{
// BAlertModal.sharedInstance().makeToast(errorStr);
successHandler(false);
self.clearDBAndPostNotification();
}else{
successHandler(true);
}
}else{
successHandler(true);
}
}else{
successHandler(true);
BAlertModal.sharedInstance().makeToast("网络异常");
}
}
}
/// 下载telBook对应的db文件
///
/// - Parameter telBook: telBook
func downLoadDB(telBook:TelBookModel?, finshedHandler:@escaping (_ isSuccess:Bool)->Void) {
print("开始下载数据库文件");
if let telBookModel = telBook {
let fileName = DBHelper.sharedInstance.getDBSaveName(telBook: telBookModel);
let url = "\(DownLoadDB_URL)/\(telBookModel.id!)"
BNetWorkingManager.shared.download(url:url, method: .get, parameters: nil, progress: { (progress) in
print("\(progress.completedUnitCount)/\(progress.totalUnitCount)");
}, toLocalPath: DBFileSavePath,fileName:fileName) { (response) in
if let data = response.result.value {
print("文件下载成功:\(String(describing: DBFileSavePath))\(fileName)\\n size:\(data.count)");
//下载成功后重新设置本地的telBook 防止重复提示新数据
UserDefaults.standard.setTelBookModel(model: telBookModel);
//发送通知 刷新数据
NotificationCenter.default.post(name:relodDataNotificationName, object: nil);
//更新来电提示数据
CallDirectoryExtensionHelper.sharedInstance.reloadExtension(completeHandler: { (supprot, error) in
if supprot && error == nil{
print("来电显示数据更新成功");
}else{
print("来电显示数据更新失败或者系统不支持");
}
})
finshedHandler(true);
}else{
finshedHandler(false);
BAlertModal.sharedInstance().makeToast("网络异常");
}
}
}else{
finshedHandler(false);
BAlertModal.sharedInstance().makeToast("数据异常");
}
}
/// 获取用户电话本列表
///风驰电话本
/// - Parameters:
/// - userId: 用户ID
/// - successHandler: 成功回掉
func getUserTelBooks(userId:Int,successHandler:@escaping ()->Void) {
print("获取用户电话本列表");
let par = ["userId":userId];
BNetWorkingManager.shared.request(url: TelBooksList_URL, method: .post,parameters:par, completionHandler: { (response) in
if let value = response.result.value as? Dictionary<String, Any> {
if let error = value["error"] {
let errorStr = error as! String;
if errorStr.components(separatedBy: "登录超时").count>1{
AppLoginHelper.loginForTimeOut(successHandler: {
self.getUserTelBooks(userId: userId, successHandler: successHandler);
})
}else{
BAlertModal.sharedInstance().makeToast("登录失败:\(error),请退出重新登录。");
}
}else{
let telbookArray = [TimeTelBookModel].deserialize(from:value["list"]as? NSArray);
if let telbooks = telbookArray {
if telbooks.count > 1{
//多个电话本
print("多个电话本 个数:\(telbooks.count)");
}else if telbooks.count == 1{
//一个电话本
if let telBook = telbooks[0]!.telBook{
UserDefaults.standard.setTelBookModel(model:telBook);
self.fchCheckImeiVerify(successHandler: { (isVerify) in
if isVerify {
self.downLoadDB(telBook: telBook,finshedHandler: { (isSuccessful) in
});
}else{
BAlertModal.sharedInstance().makeToast("客户端验证imei失败");
}
})
}
}else{
BAlertModal.sharedInstance().makeToast("您尚未创建电话本,请登录后台创建");
}
}else{
print("数据异常");
}
}
}else{
BAlertModal.sharedInstance().makeToast("网络异常");
}
});
}
// MARK: 本地方法
/// 清空数据库并且发送通知
func clearDBAndPostNotification() {
DBHelper.sharedInstance.clearDB();
NotificationCenter.default.post(name:relodDataNotificationName, object: nil);
}
/// 判断电话本是否过期,如果timeNow == ""则根据 days判断
///
/// - Parameters:
/// - expiredTime: 过期时间
/// - timeNow: 现在时间
/// - days: 剩余天数
/// - Returns: 是否过期
func checkTelBookExpired(expiredTime:TimeInterval,timeNow:String,days:Int) -> Bool {
if timeNow == "" {
if days <= 3{
BAlertModal.sharedInstance().makeToast("电话本使用即将到期,请您尽快续费!");
}
return days > 0;
}else{
let now = BDateTool.sharedInstance.dateFromGMTTimeString(timeString: timeNow);
let timeNowTimeInterval = BDateTool.sharedInstance.timeIntervalSince1970FromDate(date: now);
if expiredTime - timeNowTimeInterval < 3*24*60*60*1000 {
BAlertModal.sharedInstance().makeToast("电话本使用即将到期,请您尽快续费!");
}
return expiredTime - timeNowTimeInterval < 0;
}
}
}
| mit |
fitpay/fitpay-ios-sdk | FitpaySDK/Crypto/JWT/JWS.swift | 1 | 475 | import Foundation
struct JWS {
let header: JOSEHeader
let body: [String: Any]
let signature: String?
init(token: String) throws {
let parts = token.components(separatedBy: ".")
guard parts.count == 3 else {
throw JWTError.invalidPartCount
}
self.header = JOSEHeader(headerPayload: parts[0])
self.body = try JWTUtils.decodeJWTPart(parts[1])
self.signature = parts[2]
}
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/Classes/Services/RecentSitesService.swift | 2 | 2802 | import Foundation
/// Recent Sites Notifications
///
extension NSNotification.Name {
static let WPRecentSitesChanged = NSNotification.Name(rawValue: "RecentSitesChanged")
}
/// Keep track of recently used sites
///
class RecentSitesService: NSObject {
// We use the site's URL to identify a site
typealias SiteIdentifierType = String
// MARK: - Internal variables
private let database: KeyValueDatabase
private let databaseKey = "RecentSites"
private let legacyLastUsedBlogKey = "LastUsedBlogURLDefaultsKey"
/// The maximum number of recent sites (read only)
///
@objc let maxSiteCount = 3
// MARK: - Initialization
/// Initialize the service with the given database
///
/// This initializer was meant for testing. You probably want to use the convenience `init()` that uses the standard UserDefaults as the database.
///
init(database: KeyValueDatabase) {
self.database = database
super.init()
}
/// Initialize the service using the standard UserDefaults as the database.
///
convenience override init() {
self.init(database: UserDefaults() as KeyValueDatabase)
}
// MARK: - Public accessors
/// Returns a list of recently used sites, up to maxSiteCount.
///
@objc var recentSites: [SiteIdentifierType] {
return Array(allRecentSites.prefix(maxSiteCount))
}
/// Returns a list of all the recently used sites.
///
@objc var allRecentSites: [SiteIdentifierType] {
if let sites = database.object(forKey: databaseKey) as? [SiteIdentifierType] {
return sites
}
let initializedSites: [SiteIdentifierType]
// Migrate previously flagged last blog
if let lastUsedBlog = database.object(forKey: legacyLastUsedBlogKey) as? SiteIdentifierType {
initializedSites = [lastUsedBlog]
} else {
initializedSites = []
}
database.set(initializedSites, forKey: databaseKey)
return initializedSites
}
/// Marks a site identifier as recently used. We currently use URL as the identifier.
///
@objc(touchBlogWithIdentifier:)
func touch(site: SiteIdentifierType) {
var recent = [site]
for recentSite in recentSites
where recentSite != site {
recent.append(recentSite)
}
database.set(recent, forKey: databaseKey)
NotificationCenter.default.post(name: .WPRecentSitesChanged, object: nil)
}
/// Marks a Blog as recently used.
///
@objc(touchBlog:)
func touch(blog: Blog) {
guard let url = blog.url else {
assertionFailure("Tried to mark as used a Blog without URL")
return
}
touch(site: url)
}
}
| gpl-2.0 |
tianbinbin/DouYuShow | DouYuShow/DouYuShow/AppDelegate.swift | 1 | 762 | //
// AppDelegate.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/5/30.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 修改整个框架tabbar的tintcolor
UITabBar.appearance().tintColor = UIColor.orange
// 设置状态栏为白色 先在info.plist 添加 View controller-based status bar appearance 然后加上下面这行代码
application.statusBarStyle = .lightContent
return true
}
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/SiteCreation/SiteCreationRotatingMessageViewTests.swift | 2 | 2718 | import XCTest
@testable import WordPress
class SiteCreationRotatingMessageViewTests: XCTestCase {
private let testMessages = [
"Test Message 1",
"Test Message 2",
"Test Message 3"
]
private var rotatingMessageView: SiteCreationRotatingMessageView?
override func setUp() {
super.setUp()
self.rotatingMessageView = SiteCreationRotatingMessageView(messages: testMessages,
iconImage: UIImage())
}
override func tearDown() {
self.rotatingMessageView = nil
super.tearDown()
}
/// Test to make sure the statusLabel text and accesibility labels are being set correctly
func testSiteCreationRotatingMessageView_StatusUpdate() {
let message = "This is a test!"
rotatingMessageView?.updateStatus(message: message)
XCTAssertEqual(rotatingMessageView?.statusLabel.text, message)
}
/// Test to make sure the reset logic is working correctly
func testSiteCreationRotatingMessageView_Reset() {
rotatingMessageView?.reset()
XCTAssertEqual(rotatingMessageView?.visibleIndex, 0)
XCTAssertEqual(rotatingMessageView?.statusLabel.text, testMessages[0])
}
/// Test to make sure the start/stop animating methods create and teardown the timer
func testSiteCreationRotatingMessageView_Animating() {
rotatingMessageView?.startAnimating()
XCTAssertNotNil(rotatingMessageView?.animationTimer)
rotatingMessageView?.stopAnimating()
XCTAssertNil(rotatingMessageView?.animationTimer)
}
/// Test to make sure the message rotation logic is working correctly
func testSiteCreationRotatingMessageView_MessageRotation() {
rotatingMessageView?.reset()
rotatingMessageView?.updateStatusLabelWithNextMessage()
XCTAssertEqual(rotatingMessageView?.visibleIndex, 1)
XCTAssertEqual(rotatingMessageView?.statusLabel.text, testMessages[1])
}
/// Test to make sure when rotating through the messages we'll loop
/// back around to 0 when we exceed the message count
func testSiteCreationRotatingMessageView_OutOfBoundsMessageRotation() {
rotatingMessageView?.reset() //visibleIndex should be: 0
rotatingMessageView?.updateStatusLabelWithNextMessage() //visibleIndex should be: 1
rotatingMessageView?.updateStatusLabelWithNextMessage() //visibleIndex should be: 2
rotatingMessageView?.updateStatusLabelWithNextMessage() //visibleIndex should be: 0
XCTAssertEqual(rotatingMessageView?.visibleIndex, 0)
XCTAssertEqual(rotatingMessageView?.statusLabel.text, testMessages[0])
}
}
| gpl-2.0 |
zmeyc/GRDB.swift | Tests/SPM/Sources/main.swift | 1 | 302 | import GRDB
import CSQLite
let CVersion = String(cString: sqlite3_libversion())
print("SQLite version from C API: \(CVersion)")
let SQLVersion = try! DatabaseQueue().inDatabase { db in
try String.fetchOne(db, "SELECT sqlite_version()")!
}
print("SQLite version from SQL function: \(SQLVersion)")
| mit |
lorentey/GlueKit | Tests/GlueKitTests/MockSetObserver.swift | 1 | 1287 | //
// MockSetObserver.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-06.
// Copyright © 2015–2017 Károly Lőrentey.
//
import Foundation
import XCTest
import GlueKit
func describe<Element: Comparable>(_ update: SetUpdate<Element>) -> String {
switch update {
case .beginTransaction:
return "begin"
case .change(let change):
let removed = change.removed.sorted().map { "\($0)" }.joined(separator: ", ")
let inserted = change.inserted.sorted().map { "\($0)" }.joined(separator: ", ")
return "[\(removed)]/[\(inserted)]"
case .endTransaction:
return "end"
}
}
class MockSetObserver<Element: Hashable & Comparable>: MockSinkProtocol {
typealias Change = SetChange<Element>
let state: MockSinkState<SetUpdate<Element>, String>
init() {
state = .init({ describe($0) })
}
init<Source: SourceType>(_ source: Source) where Source.Value == Update<Change> {
state = .init({ describe($0) })
self.subscribe(to: source)
}
convenience init<Observable: ObservableSetType>(_ observable: Observable) where Observable.Change == Change {
self.init(observable.updates)
}
func receive(_ value: Update<Change>) {
state.receive(value)
}
}
| mit |
toineheuvelmans/Metron | Playground.playground/Sources/Playground.swift | 1 | 852 | import Metron // 🧨 If you get a build error on this line, try building for a Simulator device!
import UIKit
// MARK: Playgrounds
public extension Metron.Drawable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
if let path = self.path {
return .bezierPath(UIBezierPath(cgPath: path))
}
return PlaygroundQuickLook(reflecting: self)
}
}
//extension LineSegment : CustomPlaygroundQuickLookable {}
//extension Circle : CustomPlaygroundQuickLookable {}
//extension Triangle : CustomPlaygroundQuickLookable {}
//extension Square : CustomPlaygroundQuickLookable {}
extension Metron.Polygon : CustomPlaygroundQuickLookable {}
public extension Int {
public func `do`(_ block: () -> ()) {
guard self > 0 else { return }
for _ in 0..<self {
block()
}
}
}
| mit |
qianyu09/AppLove | App Love/Network/ReviewLoading/ReviewLoadManager.swift | 1 | 5565 | //
// ReviewLoadManager.swift
// App Love
//
// Created by Woodie Dovich on 2016-03-24.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Mass Multi-threaded page loader that can be safely canceled.
//
import UIKit
class ReviewLoadManager: NSObject, ProgressDelegate {
static let sharedInst = ReviewLoadManager()
private override init() {} // enforce singleton
var reviews = [ReviewModel]()
var loadStates = [String:LoadState]() // loading state for every territory.
var loadingQueue:NSOperationQueue?
var firstQuickUpdate:Bool = false
func initializeLoadingStates() {
self.loadStates.removeAll()
let territories = TerritoryMgr.sharedInst.getSelectedCountryCodes()
for code in territories {
self.loadStates[code] = LoadState(territory: code)
}
self.firstQuickUpdate = false
}
func loadReviews() {
clearReviews()
initializeLoadingStates()
self.loadingQueue = nil
self.loadingQueue = NSOperationQueue()
self.loadingQueue?.maxConcurrentOperationCount = 4
setNotifications()
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.loadStart, object: nil)
let countryCodes = TerritoryMgr.sharedInst.getSelectedCountryCodes()
let allOperationsFinishedOperation = NSBlockOperation() {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.allLoadingCompleted, object: self)
nc.postNotificationName(Const.displayToolbar, object: self)
}
if let appId = AppList.sharedInst.getSelectedModel()?.appId {
for code in countryCodes {
let pageInfo = PageInfo(appId: appId, territory: code)
let operation = TerritoryLoadOperation(pageInfo: pageInfo)
operation.delegate = self
allOperationsFinishedOperation.addDependency(operation)
self.loadingQueue?.addOperation(operation)
}
}
NSOperationQueue.mainQueue().addOperation(allOperationsFinishedOperation)
}
// ProgressDelegate - update bar territory
func territoryLoadCompleted(country:String) {
//print("territoryLoadCompleted "+country)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let data:[String:AnyObject] = ["territory":country]
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.territoryDone, object:nil, userInfo:data)
})
}
// ProgressDelegate - update bar territory
func territoryLoadStarted(country:String) {
//print("territoryLoadStarted "+country)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let data:[String:AnyObject] = ["territory":country]
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.territoryStart, object:nil, userInfo:data)
})
}
// ProgressDelegate - update bar territory
func pageLoaded(territory:String, reviews:[ReviewModel]?) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if reviews == nil {
if let loadState = self.loadStates[territory] {
loadState.error = true
}
let data:[String:AnyObject] = ["error":"error","territory":territory]
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.dataError, object:nil, userInfo:data)
}
if let newReviews = reviews {
if newReviews.count > 0 {
self.reviews.appendContentsOf(newReviews)
}
if let loadState = self.loadStates[territory] {
loadState.count += newReviews.count
loadState.error = false
}
if let loadState = self.loadStates[territory] {
loadState.error = false
let data:[String:AnyObject] = ["loadState":loadState,"territory":territory]
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.updateAmount, object:nil, userInfo:data)
}
if self.firstQuickUpdate == false && self.reviews.count > 99 {
self.updateTable()
}
}
})
}
func updateTable() {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.reloadData, object: self)
self.firstQuickUpdate = true
}
func setNotifications() {
let nc = NSNotificationCenter.defaultCenter()
nc.removeObserver(self)
nc.addObserver(self, selector: .updateTableData, name: Const.allLoadingCompleted, object: nil)
}
func updateTableData(notification: NSNotification) {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(Const.reloadData, object: self)
}
func clearReviews() {
reviews.removeAll()
loadStates.removeAll()
}
func cancelLoading() {
self.loadingQueue?.cancelAllOperations()
}
}
private extension Selector {
static let updateTableData = #selector(ReviewLoadManager.updateTableData(_:))
}
| mit |
quillford/OctoControl-iOS | OctoControl/TerminalViewController.swift | 1 | 1801 | //
// TerminalViewController.swift
// OctoControl
//
// Created by quillford on 2/6/15.
// Copyright (c) 2015 quillford. All rights reserved.
//
import UIKit
import Starscream
class TerminalViewController: UIViewController, WebSocketDelegate {
var socket = WebSocket(url: NSURL(scheme: "ws", host: "prusa.local", path: "/sockjs/websocket")!)
let ip = userDefaults.stringForKey("ip")
let apikey = userDefaults.stringForKey("apikey")
@IBOutlet weak var commandField: UITextField!
@IBOutlet weak var terminalOutput: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
socket.delegate = self
socket.connect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendCommand(sender: AnyObject) {
OctoPrint.sendGcode(commandField.text, ip: ip!, apikey: apikey!)
//dismiss keyboard
self.view.endEditing(true)
}
func updateTerminal(){
//get terminal output from websocket data
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func websocketDidConnect(ws: WebSocket) {
println("websocket is connected")
}
func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
if let e = error {
println("websocket is disconnected: \(e.localizedDescription)")
}
}
func websocketDidReceiveMessage(ws: WebSocket, text: String) {
println("Received text: \(text)")
}
func websocketDidReceiveData(ws: WebSocket, data: NSData) {
println("Received data: \(data.length)")
}
}
| gpl-2.0 |
amnuaym/TiAppBuilder | Day2/BMICalculator2/BMICalculator/AppDelegate.swift | 2 | 4595 | //
// AppDelegate.swift
// BMICalculator
//
// Created by Amnuay M on 8/21/17.
// Copyright © 2017 Amnuay M. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "BMICalculator")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| gpl-3.0 |
tomburns/ios | FiveCalls/FiveCalls/EditLocationViewController.swift | 2 | 4483 | //
// EditLocationViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/31/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import CoreLocation
import Crashlytics
protocol EditLocationViewControllerDelegate : NSObjectProtocol {
func editLocationViewController(_ vc: EditLocationViewController, didUpdateLocation location: UserLocation)
func editLocationViewControllerDidCancel(_ vc: EditLocationViewController)
}
class EditLocationViewController : UIViewController, CLLocationManagerDelegate {
weak var delegate: EditLocationViewControllerDelegate?
private var lookupLocation: CLLocation?
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
private lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
return manager
}()
@IBOutlet weak var useMyLocationButton: UIButton!
@IBOutlet weak var addressTextField: UITextField!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Answers.logCustomEvent(withName:"Screen: Edit Location")
addressTextField.becomeFirstResponder()
if case .address? = UserLocation.current.locationType {
addressTextField.text = UserLocation.current.locationValue
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
addressTextField.resignFirstResponder()
}
@IBAction func useMyLocationTapped(_ sender: Any) {
if CLLocationManager.authorizationStatus() == .denied {
Answers.logCustomEvent(withName:"Action: Denied Location")
informUserOfPermissions()
} else {
Answers.logCustomEvent(withName:"Action: Used Location")
locationManager.requestWhenInUseAuthorization()
}
}
@IBAction func cancelTapped(_ sender: Any) {
delegate?.editLocationViewControllerDidCancel(self)
}
@IBAction func submitAddressTapped(_ sender: Any) {
Answers.logCustomEvent(withName:"Action: Used Address")
UserLocation.current.setFrom(address: addressTextField.text ?? "") { [weak self] updatedLocation in
guard let strongSelf = self else {
return
}
strongSelf.delegate?.editLocationViewController(strongSelf, didUpdateLocation: updatedLocation)
}
}
//Mark: CLLocationManagerDelegate methods
func informUserOfPermissions() {
let alertController = UIAlertController(title: R.string.localizable.locationPermissionDeniedTitle(), message:
R.string.localizable.locationPermissionDeniedMessage(), preferredStyle: .alert)
let dismiss = UIAlertAction(title: R.string.localizable.dismissTitle(), style: .default ,handler: nil)
alertController.addAction(dismiss)
let openSettings = UIAlertAction(title: R.string.localizable.openSettingsTitle(), style: .default, handler: { action in
guard let url = URL(string: UIApplicationOpenSettingsURLString) else { return }
UIApplication.shared.fvc_open(url)
})
alertController.addAction(openSettings)
present(alertController, animated: true, completion: nil)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .denied {
informUserOfPermissions()
} else {
useMyLocationButton.isEnabled = false // prevent starting it twice...
activityIndicator.startAnimating()
manager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard lookupLocation == nil else { //only want to call delegate one time
return
}
if let location = locations.first {
locationManager.stopUpdatingLocation()
lookupLocation = location
let userLocation = UserLocation.current
userLocation.setFrom(location: location) {
self.delegate?.editLocationViewController(self, didUpdateLocation: userLocation)
}
}
}
}
| mit |
haddenkim/dew | Sources/App/Helpers/GeoJSONPoint.swift | 1 | 1123 | //
// GeoJSONPoint.swift
// dew
//
// Created by Hadden Kim on 4/26/17.
//
//
import MongoKitten
import GeoJSON
extension Point {
init?(_ value: Primitive?) {
guard
let document = Document(value),
let type = String(document["type"]),
type == "Point",
let coordinates = Array(document["coordinates"]),
let longitude = Double(coordinates[0]),
let latitudue = Double(coordinates[1])
else { return nil }
let position = Position(first: longitude, second: latitudue)
self.init(coordinate: position)
}
init(_ coordinate: Place.Coordinate) {
let geoPosition = Position(first: coordinate.longitude, second: coordinate.latitude)
self.init(coordinate: geoPosition)
}
func placeCoordinate() -> Place.Coordinate {
let longitude = self.coordinate.values[0]
let latitude = self.coordinate.values[1]
return (latitude: latitude, longitude: longitude)
}
}
| mit |
jarimartens10/wwdc-2015 | JMViewController.swift | 1 | 4457 | //
// JMViewController.swift
//
//
// Created by Jari Martens on 14-04-15.
//
//
import UIKit
import MessageUI
class JMViewController: UIViewController, JMImageViewDelegate, MFMailComposeViewControllerDelegate {
//MARK: - IBOutlets
//###########################################################
@IBOutlet weak var visualEffectView: UIVisualEffectView!
@IBOutlet weak var backgroundImageView: UIImageView!
//###########################################################
//MARK: - JMImageViewDelegate
//###########################################################
func didTapImageView(imageView: JMImageView) {
let imageInfo = JTSImageInfo()
imageInfo.image = imageView.image
imageInfo.referenceRect = imageView.frame
imageInfo.referenceView = imageView.superview
imageInfo.referenceContentMode = imageView.contentMode
imageInfo.referenceCornerRadius = imageView.layer.cornerRadius
let imageViewer = JTSImageViewController(
imageInfo: imageInfo,
mode: JTSImageViewControllerMode.Image,
backgroundStyle: JTSImageViewControllerBackgroundOptions.Blurred)
imageViewer.interactionsDelegate = self
imageViewer.showFromViewController(self, transition: JTSImageViewControllerTransition._FromOriginalPosition)
}
func imageViewerAllowCopyToPasteboard(imageViewer: JTSImageViewController!) -> Bool {
return true
}
func imageViewerDidLongPress(imageViewer: JTSImageViewController!, atRect rect: CGRect) {
let controller = UIAlertController(title: "Share", message: "Share this image", preferredStyle: UIAlertControllerStyle.ActionSheet)
controller.addAction(UIAlertAction(title: "Mail", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
if MFMailComposeViewController.canSendMail() {
let composer = MFMailComposeViewController(nibName: nil, bundle: nil)
composer.mailComposeDelegate = nil//self
composer.addAttachmentData(UIImageJPEGRepresentation(imageViewer.image, 0.9), mimeType: "image/jpeg", fileName: "image.jpg")
composer.setSubject("Image")
composer.mailComposeDelegate = self
imageViewer.presentViewController(composer, animated: true, completion: nil)
}
else {
let alert = UIAlertController(
title: "Cannot send email",
message: "This device cannot send an email, check your email settings in Preferences",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(
title: "OK",
style: UIAlertActionStyle.Default,
handler: nil))
imageViewer.presentViewController(alert,
animated: true,
completion: nil)
}
}))
controller.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
UIImageWriteToSavedPhotosAlbum(imageViewer.image, nil, nil, nil)
}))
controller.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
imageViewer.presentViewController(controller, animated: true, completion: nil)
}
//###########################################################
//MARK: - MFMailComposeViewControllerDelegate
//###########################################################
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
//###########################################################
//MARK: - Status bar
//###########################################################
override func preferredStatusBarStyle() -> UIStatusBarStyle {
//If not hidden, display status bar in white text
return UIStatusBarStyle.LightContent
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//###########################################################
}
| apache-2.0 |
harryzjm/SMWaterFlowLayout | Source/SMWaterFlowLayout.swift | 1 | 8414 | //
// SMWaterfallFlowLayout.swift
// SuperMe
//
// Created by Magic on 10/10/2017.
// Copyright © 2017 SuperMe. All rights reserved.
//
import Foundation
import UIKit
public protocol SMWaterFlowLayoutDelegate: class {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: SMWaterFlowLayout, constantLength: CGFloat, variableLengthForItemAt indexPath: IndexPath) -> CGFloat
}
public class SMWaterFlowLayout: UICollectionViewLayout {
private let keyPathCollection = #keyPath(UICollectionViewLayout.collectionView)
private let keyPathDelegate = #keyPath(UICollectionView.delegate)
fileprivate var didAddDelegate = false
fileprivate var attArr: [UICollectionViewLayoutAttributes] = []
fileprivate var supplementaryAtts: [UICollectionViewLayoutAttributes] = []
fileprivate var lineHeightArr: [CGFloat] = [0]
fileprivate var lineLength: CGFloat = 0
open var scrollDirection: UICollectionViewScrollDirection = .vertical
open var lineCount: Int = 3
open var lineSpacing: CGFloat = 0
open var interitemSpacing: CGFloat = 0
open var edgeInset: UIEdgeInsets = .zero
open var headerViewLength: CGFloat = 0
open var footerViewLength: CGFloat = 0
fileprivate weak var delegate: SMWaterFlowLayoutDelegate?
public override init() {
super.init()
addObserver(self, forKeyPath: keyPathCollection, options: [.new, .old], context: nil)
manage(collectionView: collectionView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeObserver(self, forKeyPath: keyPathCollection)
if didAddDelegate { collectionView?.removeObserver(self, forKeyPath: keyPathDelegate) }
}
override public func prepare() {
super.prepare()
resetLineInfo()
guard
let collectV = collectionView,
let dataSource = collectV.dataSource
else { return }
attArr.removeAll()
supplementaryAtts.removeAll()
let sectionCount = dataSource.numberOfSections?(in: collectV) ?? 1
for section in 0 ..< sectionCount {
let itemCount = dataSource.collectionView(collectV, numberOfItemsInSection: section)
for row in 0 ..< itemCount {
let att = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: row, section: section))
modify(layout: att)
attArr.append(att)
}
}
if headerViewLength > 0 {
let header = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: IndexPath(item: 0, section: 0))
header.frame.size = makeSize(length: headerViewLength)
supplementaryAtts.append(header)
}
if footerViewLength > 0 {
let footer = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: IndexPath(item: 0, section: 1))
footer.frame.size = makeSize(length: footerViewLength)
let length = caculateMaxLength() - footerViewLength
switch scrollDirection {
case .horizontal: footer.frame.origin = CGPoint(x: length, y: 0)
case .vertical: footer.frame.origin = CGPoint(x: 0, y: length)
}
supplementaryAtts.append(footer)
}
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let kp = keyPath else { return }
switch kp {
case keyPathCollection:
let new = change?[.newKey] as? UICollectionView
let old = change?[.oldKey] as? UICollectionView
if didAddDelegate, let v = old {
v.removeObserver(self, forKeyPath: keyPathDelegate)
didAddDelegate = false
}
manage(collectionView: new)
case keyPathDelegate: manage(delegate: change?[.newKey] as? UICollectionViewDelegate)
default: break
}
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attArr[indexPath.item]
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attArr + supplementaryAtts
}
override public var collectionViewContentSize: CGSize {
return makeSize(length: caculateMaxLength())
}
private var beforeSize: CGSize = .zero
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let size = newBounds.size
defer { beforeSize = size }
return size != beforeSize
}
}
extension SMWaterFlowLayout {
fileprivate func manage(collectionView view: UICollectionView?) {
guard let collectV = view else { return }
collectV.addObserver(self, forKeyPath: keyPathDelegate, options: .new, context: nil)
didAddDelegate = true
manage(delegate: collectV.delegate)
}
fileprivate func manage(delegate dg: UICollectionViewDelegate?) {
guard let nDelegate = dg as? SMWaterFlowLayoutDelegate else { return }
delegate = nDelegate
DispatchQueue.main.async { [weak self] in
self?.collectionView?.reloadData()
}
}
fileprivate func modify(layout attributes: UICollectionViewLayoutAttributes?) {
guard
let att = attributes,
let collectV = collectionView
else { return }
let (index, height) = lineHeightArr.enumerated().min { $0.1 < $1.1 } ?? (0, 0)
switch scrollDirection {
case .vertical:
let x = CGFloat(index) * (lineLength + interitemSpacing) + edgeInset.left
let y = height
let height = delegate?.collectionView(collectV, layout: self, constantLength: lineLength, variableLengthForItemAt: att.indexPath) ?? 0
att.frame = CGRect(x: x, y: y, width: lineLength, height: height)
lineHeightArr[index] = y + height + lineSpacing
case .horizontal:
let x = height
let y = CGFloat(index) * (lineLength + lineSpacing) + edgeInset.top
let width = delegate?.collectionView(collectV, layout: self, constantLength: lineLength, variableLengthForItemAt: att.indexPath) ?? 0
att.frame = CGRect(x: x, y: y, width: width, height: lineLength)
lineHeightArr[index] = x + width + interitemSpacing
}
}
fileprivate func makeSize(length: CGFloat) -> CGSize {
switch scrollDirection {
case .vertical:
return CGSize(width: collectionWidth, height: length)
case .horizontal:
return CGSize(width: length, height: collectionHeight)
}
}
fileprivate func caculateMaxLength() -> CGFloat {
let length = lineHeightArr.max() ?? 0
switch scrollDirection {
case .vertical:
return length - lineSpacing + edgeInset.bottom + footerViewLength
case .horizontal:
return length - interitemSpacing + edgeInset.right + footerViewLength
}
}
fileprivate var collectionWidth: CGFloat {
return collectionView?.bounds.width ?? 0
}
fileprivate var collectionHeight: CGFloat {
return collectionView?.bounds.height ?? 0
}
fileprivate func reset() {
resetLineInfo()
invalidateLayout()
}
fileprivate func resetLineInfo() {
lineHeightArr.removeAll()
switch scrollDirection {
case .vertical:
lineCount.forEach { _ in lineHeightArr.append(edgeInset.top + headerViewLength) }
lineLength = (collectionWidth - edgeInset.left - edgeInset.right - CGFloat(lineCount-1) * interitemSpacing) / CGFloat(lineCount)
case .horizontal:
lineCount.forEach { _ in lineHeightArr.append(edgeInset.left + headerViewLength) }
lineLength = (collectionHeight - edgeInset.top - edgeInset.bottom - CGFloat(lineCount-1) * lineSpacing) / CGFloat(lineCount)
}
}
}
extension Int {
fileprivate func forEach(_ body: (Int) -> Void) {
(0 ..< self).forEach { (i) in
body(i)
}
}
}
| mit |
vector-im/vector-ios | Riot/Modules/Spaces/SpaceMenu/SpaceMenuViewAction.swift | 1 | 824 | //
// Copyright 2021 New Vector 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.
//
import Foundation
/// `SpaceMenuViewController` view actions exposed to view model
enum SpaceMenuViewAction {
case selectRow(at: IndexPath)
case leaveSpaceAndKeepRooms
case leaveSpaceAndLeaveRooms
case dismiss
}
| apache-2.0 |
vector-im/vector-ios | Riot/Modules/DeepLink/CustomSchemeURLConstants.swift | 1 | 800 | //
// Copyright 2020 New Vector 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.
//
import Foundation
enum CustomSchemeURLConstants {
enum Parameters {
static let transactionId = "transaction_id"
}
enum Hosts {
static let connect = "connect"
}
}
| apache-2.0 |
abertelrud/swift-package-manager | Tests/WorkspaceTests/ToolsVersionSpecificationGenerationTests.swift | 2 | 2394 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file tests the generation of a Swift tools version specification from a known version.
///
import XCTest
import PackageModel
/// Test cases for the generation of Swift tools version specifications.
class ToolsVersionSpecificationGenerationTests: XCTestCase {
/// Tests the generation of Swift tools version specifications.
func testToolsVersionSpecificationGeneration() throws {
let versionWithNonZeroPatch = ToolsVersion(version: Version(4, 3, 2))
XCTAssertEqual(versionWithNonZeroPatch.specification(), "// swift-tools-version:4.3.2")
XCTAssertEqual(versionWithNonZeroPatch.specification(roundedTo: .automatic), "// swift-tools-version:4.3.2")
XCTAssertEqual(versionWithNonZeroPatch.specification(roundedTo: .minor), "// swift-tools-version:4.3")
XCTAssertEqual(versionWithNonZeroPatch.specification(roundedTo: .patch), "// swift-tools-version:4.3.2")
let versionWithZeroPatch = ToolsVersion.v5_3 // 5.3.0
XCTAssertEqual(versionWithZeroPatch.specification(), "// swift-tools-version:5.3")
XCTAssertEqual(versionWithZeroPatch.specification(roundedTo: .automatic), "// swift-tools-version:5.3")
XCTAssertEqual(versionWithZeroPatch.specification(roundedTo: .minor), "// swift-tools-version:5.3")
XCTAssertEqual(versionWithZeroPatch.specification(roundedTo: .patch), "// swift-tools-version:5.3.0")
let newMajorVersion = ToolsVersion.v5 // 5.0.0
XCTAssertEqual(newMajorVersion.specification(), "// swift-tools-version:5.0")
XCTAssertEqual(newMajorVersion.specification(roundedTo: .automatic), "// swift-tools-version:5.0")
XCTAssertEqual(newMajorVersion.specification(roundedTo: .minor), "// swift-tools-version:5.0")
XCTAssertEqual(newMajorVersion.specification(roundedTo: .patch), "// swift-tools-version:5.0.0")
}
}
| apache-2.0 |
kickstarter/ios-oss | KsApi/models/graphql/adapters/UserEnvelope+GraphUserEnvelopeTemplates.swift | 1 | 959 | @testable import KsApi
public struct GraphUserEnvelopeTemplates {
static let userJSONDict: [String: Any?] =
[
"me": [
"chosenCurrency": nil,
"email": "nativesquad@ksr.com",
"hasPassword": true,
"id": "VXNlci0xNDcwOTUyNTQ1",
"imageUrl": "https://ksr-qa-ugc.imgix.net/missing_user_avatar.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=&auto=format&frame=1&q=92&s=e17a7b6f853aa6320cfe67ee783eb3d8",
"isAppleConnected": false,
"isCreator": false,
"isDeliverable": true,
"isEmailVerified": true,
"name": "Hari Singh",
"storedCards": [
"nodes": [
[
"expirationDate": "2023-01-01",
"id": "6",
"lastFour": "4242",
"type": GraphAPI.CreditCardTypes(rawValue: "VISA") as Any
]
],
"totalCount": 1
],
"uid": "1470952545"
]
]
}
| apache-2.0 |
shopgun/shopgun-ios-sdk | Sources/TjekAPI/Utils/UIColor+Hex.swift | 1 | 1947 | ///
/// Copyright (c) 2018 Tjek. All rights reserved.
///
#if canImport(UIKit)
import UIKit
extension UIColor {
convenience init?(hex: String) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt64 = 0
guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { return nil }
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
let strLen = hexSanitized.count
if strLen == 6 {
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
b = CGFloat(rgb & 0x0000FF) / 255.0
} else if strLen == 8 {
r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0
g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0
b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0
a = CGFloat(rgb & 0x000000FF) / 255.0
} else {
return nil
}
self.init(red: r, green: g, blue: b, alpha: a)
}
var toHex: String? {
return toHex()
}
func toHex(alpha: Bool = false) -> String? {
guard let components = cgColor.components, components.count >= 3 else {
return nil
}
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
var a = Float(1.0)
if components.count >= 4 {
a = Float(components[3])
}
if alpha {
return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
}
#endif
| mit |
PerfectlySoft/Perfect-TensorFlow | Sources/PerfectTensorFlow/pb.model_flags.swift | 1 | 29604 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tensorflow/contrib/lite/toco/model_flags.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
/// Copyright 2017 The TensorFlow 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 Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct Toco_InputArrayShape: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".InputArrayShape"
public var dims: [Int32] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2: try decoder.decodeRepeatedInt32Field(value: &self.dims)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.dims.isEmpty {
try visitor.visitRepeatedInt32Field(value: self.dims, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// Next ID to USE: 7.
public struct Toco_InputArray: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".InputArray"
/// Name of the input arrays, i.e. the arrays from which input activations
/// will be read.
public var name: String {
get {return _storage._name ?? String()}
set {_uniqueStorage()._name = newValue}
}
/// Returns true if `name` has been explicitly set.
public var hasName: Bool {return _storage._name != nil}
/// Clears the value of `name`. Subsequent reads from it will return its default value.
public mutating func clearName() {_storage._name = nil}
/// Shape of the input. For many applications the dimensions are {batch,
/// height, width, depth}. Often the batch is left "unspecified" by providing
/// a value of -1.
///
/// The last dimension is typically called 'depth' or 'channels'. For example,
/// for an image model taking RGB images as input, this would have the value 3.
public var shape: Toco_InputArrayShape {
get {return _storage._shape ?? Toco_InputArrayShape()}
set {_uniqueStorage()._shape = newValue}
}
/// Returns true if `shape` has been explicitly set.
public var hasShape: Bool {return _storage._shape != nil}
/// Clears the value of `shape`. Subsequent reads from it will return its default value.
public mutating func clearShape() {_storage._shape = nil}
/// mean_value and std_value parameters control the interpretation of raw input
/// activation values (elements of the input array) as real numbers. The
/// mapping is given by:
///
/// real_value = (raw_input_value - mean_value) / std_value
///
/// In particular, the defaults (mean_value=0, std_value=1) yield
/// real_value = raw_input_value. Often, non-default values are used in image
/// models. For example, an image model taking uint8 image channel values as
/// its raw inputs, in [0, 255] range, may use mean_value=128, std_value=128 to
/// map them into the interval [-1, 1).
///
/// Note: this matches exactly the meaning of mean_value and std_value in
/// (TensorFlow via LegacyFedInput).
public var meanValue: Float {
get {return _storage._meanValue ?? 0}
set {_uniqueStorage()._meanValue = newValue}
}
/// Returns true if `meanValue` has been explicitly set.
public var hasMeanValue: Bool {return _storage._meanValue != nil}
/// Clears the value of `meanValue`. Subsequent reads from it will return its default value.
public mutating func clearMeanValue() {_storage._meanValue = nil}
public var stdValue: Float {
get {return _storage._stdValue ?? 1}
set {_uniqueStorage()._stdValue = newValue}
}
/// Returns true if `stdValue` has been explicitly set.
public var hasStdValue: Bool {return _storage._stdValue != nil}
/// Clears the value of `stdValue`. Subsequent reads from it will return its default value.
public mutating func clearStdValue() {_storage._stdValue = nil}
/// Data type of the input.
///
/// In many graphs, the input arrays already have defined data types,
/// e.g. Placeholder nodes in a TensorFlow GraphDef have a dtype attribute.
/// In those cases, it is not needed to specify this data_type flag.
/// The purpose of this flag is only to define the data type of input
/// arrays whose type isn't defined in the input graph file. For example,
/// when specifying an arbitrary (not Placeholder) --input_array into
/// a TensorFlow GraphDef.
///
/// When this data_type is quantized (e.g. QUANTIZED_UINT8), the
/// corresponding quantization parameters are the mean_value, std_value
/// fields.
///
/// It is also important to understand the nuance between this data_type
/// flag and the inference_input_type in TocoFlags. The basic difference
/// is that this data_type (like all ModelFlags) describes a property
/// of the input graph, while inference_input_type (like all TocoFlags)
/// describes an aspect of the toco transformation process and thus of
/// the output file. The types of input arrays may be different between
/// the input and output files if quantization or dequantization occurred.
/// Such differences can only occur for real-number data i.e. only
/// between FLOAT and quantized types (e.g. QUANTIZED_UINT8).
public var dataType: Tensorflow_DataType {
get {return _storage._dataType ?? .dtInvalid}
set {_uniqueStorage()._dataType = newValue}
}
/// Returns true if `dataType` has been explicitly set.
public var hasDataType: Bool {return _storage._dataType != nil}
/// Clears the value of `dataType`. Subsequent reads from it will return its default value.
public mutating func clearDataType() {_storage._dataType = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &_storage._name)
case 3: try decoder.decodeSingularFloatField(value: &_storage._meanValue)
case 4: try decoder.decodeSingularFloatField(value: &_storage._stdValue)
case 5: try decoder.decodeSingularEnumField(value: &_storage._dataType)
case 6: try decoder.decodeSingularMessageField(value: &_storage._shape)
default: break
}
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._name {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = _storage._meanValue {
try visitor.visitSingularFloatField(value: v, fieldNumber: 3)
}
if let v = _storage._stdValue {
try visitor.visitSingularFloatField(value: v, fieldNumber: 4)
}
if let v = _storage._dataType {
try visitor.visitSingularEnumField(value: v, fieldNumber: 5)
}
if let v = _storage._shape {
try visitor.visitSingularMessageField(value: v, fieldNumber: 6)
}
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _storage = _StorageClass.defaultInstance
}
public struct Toco_RnnState: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".RnnState"
public var stateArray: String {
get {return _stateArray ?? String()}
set {_stateArray = newValue}
}
/// Returns true if `stateArray` has been explicitly set.
public var hasStateArray: Bool {return self._stateArray != nil}
/// Clears the value of `stateArray`. Subsequent reads from it will return its default value.
public mutating func clearStateArray() {self._stateArray = nil}
public var backEdgeSourceArray: String {
get {return _backEdgeSourceArray ?? String()}
set {_backEdgeSourceArray = newValue}
}
/// Returns true if `backEdgeSourceArray` has been explicitly set.
public var hasBackEdgeSourceArray: Bool {return self._backEdgeSourceArray != nil}
/// Clears the value of `backEdgeSourceArray`. Subsequent reads from it will return its default value.
public mutating func clearBackEdgeSourceArray() {self._backEdgeSourceArray = nil}
public var discardable: Bool {
get {return _discardable ?? false}
set {_discardable = newValue}
}
/// Returns true if `discardable` has been explicitly set.
public var hasDiscardable: Bool {return self._discardable != nil}
/// Clears the value of `discardable`. Subsequent reads from it will return its default value.
public mutating func clearDiscardable() {self._discardable = nil}
/// TODO(benoitjacob): drop the 'size' field. Should be redundant with
/// --input_shapes and shapes propagation.
public var size: Int32 {
get {return _size ?? 0}
set {_size = newValue}
}
/// Returns true if `size` has been explicitly set.
public var hasSize: Bool {return self._size != nil}
/// Clears the value of `size`. Subsequent reads from it will return its default value.
public mutating func clearSize() {self._size = nil}
/// TODO(benoitjacob): manually_create is a temporary hack:
/// due to discrepancies between the current toco dims tracking and
/// TensorFlow shapes, for some models we need to manually create RNN state
/// arrays with a specified shape.
/// Maybe we should actually implement back-edges as operators of their own,
/// which would remove the need for much special-casing, including here,
/// we could probably consistently let PropagateFixedSizes handle state
/// arrays.
/// TODO(benoitjacob): should really drop manually_create now.
public var manuallyCreate: Bool {
get {return _manuallyCreate ?? false}
set {_manuallyCreate = newValue}
}
/// Returns true if `manuallyCreate` has been explicitly set.
public var hasManuallyCreate: Bool {return self._manuallyCreate != nil}
/// Clears the value of `manuallyCreate`. Subsequent reads from it will return its default value.
public mutating func clearManuallyCreate() {self._manuallyCreate = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self._stateArray)
case 2: try decoder.decodeSingularStringField(value: &self._backEdgeSourceArray)
case 3: try decoder.decodeSingularInt32Field(value: &self._size)
case 4: try decoder.decodeSingularBoolField(value: &self._manuallyCreate)
case 5: try decoder.decodeSingularBoolField(value: &self._discardable)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._stateArray {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = self._backEdgeSourceArray {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
}
if let v = self._size {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)
}
if let v = self._manuallyCreate {
try visitor.visitSingularBoolField(value: v, fieldNumber: 4)
}
if let v = self._discardable {
try visitor.visitSingularBoolField(value: v, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _stateArray: String? = nil
fileprivate var _backEdgeSourceArray: String? = nil
fileprivate var _discardable: Bool? = nil
fileprivate var _size: Int32? = nil
fileprivate var _manuallyCreate: Bool? = nil
}
/// ModelFlags encodes properties of a model that, depending on the file
/// format, may or may not be recorded in the model file. The purpose of
/// representing these properties in ModelFlags is to allow passing them
/// separately from the input model file, for instance as command-line
/// parameters, so that we can offer a single uniform interface that can
/// handle files from different input formats.
///
/// For each of these properties, and each supported file format, we
/// detail in comments below whether the property exists in the given file
/// format.
///
/// Obsolete flags that have been removed:
/// optional int32 input_depth = 3;
/// optional int32 input_width = 4;
/// optional int32 input_height = 5;
/// optional int32 batch = 6 [ default = 1];
/// optional float mean_value = 7;
/// optional float std_value = 8 [default = 1.];
/// optional int32 input_dims = 11 [ default = 4];
/// repeated int32 input_shape = 13;
///
/// Next ID to USE: 18.
public struct Toco_ModelFlags: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".ModelFlags"
/// Information about the input arrays, i.e. the arrays from which input
/// activations will be read.
public var inputArrays: [Toco_InputArray] = []
/// Name of the output arrays, i.e. the arrays into which output activations
/// will be written.
public var outputArrays: [String] = []
/// If true, the model accepts an arbitrary batch size. Mutually exclusive with
/// the 'batch' field: at most one of these two fields can be set.
public var variableBatch: Bool {
get {return _variableBatch ?? false}
set {_variableBatch = newValue}
}
/// Returns true if `variableBatch` has been explicitly set.
public var hasVariableBatch: Bool {return self._variableBatch != nil}
/// Clears the value of `variableBatch`. Subsequent reads from it will return its default value.
public mutating func clearVariableBatch() {self._variableBatch = nil}
public var rnnStates: [Toco_RnnState] = []
public var modelChecks: [Toco_ModelFlags.ModelCheck] = []
/// If true, will allow passing inexistent arrays in --input_arrays
/// and --output_arrays. This makes little sense, is only useful to
/// more easily get graph visualizations.
public var allowNonexistentArrays: Bool {
get {return _allowNonexistentArrays ?? false}
set {_allowNonexistentArrays = newValue}
}
/// Returns true if `allowNonexistentArrays` has been explicitly set.
public var hasAllowNonexistentArrays: Bool {return self._allowNonexistentArrays != nil}
/// Clears the value of `allowNonexistentArrays`. Subsequent reads from it will return its default value.
public mutating func clearAllowNonexistentArrays() {self._allowNonexistentArrays = nil}
/// If true, will allow passing non-ascii-printable characters in
/// --input_arrays and --output_arrays. By default (if false), only
/// ascii printable characters are allowed, i.e. character codes
/// ranging from 32 to 127. This is disallowed by default so as to
/// catch common copy-and-paste issues where invisible unicode
/// characters are unwittingly added to these strings.
public var allowNonasciiArrays: Bool {
get {return _allowNonasciiArrays ?? false}
set {_allowNonasciiArrays = newValue}
}
/// Returns true if `allowNonasciiArrays` has been explicitly set.
public var hasAllowNonasciiArrays: Bool {return self._allowNonasciiArrays != nil}
/// Clears the value of `allowNonasciiArrays`. Subsequent reads from it will return its default value.
public mutating func clearAllowNonasciiArrays() {self._allowNonasciiArrays = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
/// Checks applied to the model, typically after toco's comprehensive
/// graph transformations.
/// Next ID to USE: 4.
public struct ModelCheck: SwiftProtobuf.Message {
public static let protoMessageName: String = Toco_ModelFlags.protoMessageName + ".ModelCheck"
/// Use the name of a type of operator to check its counts.
/// Use "Total" for overall operator counts.
/// Use "Arrays" for overall array counts.
public var countType: String {
get {return _countType ?? "None"}
set {_countType = newValue}
}
/// Returns true if `countType` has been explicitly set.
public var hasCountType: Bool {return self._countType != nil}
/// Clears the value of `countType`. Subsequent reads from it will return its default value.
public mutating func clearCountType() {self._countType = nil}
/// A count of zero is a meaningful check, so negative used to mean disable.
public var countMin: Int32 {
get {return _countMin ?? -1}
set {_countMin = newValue}
}
/// Returns true if `countMin` has been explicitly set.
public var hasCountMin: Bool {return self._countMin != nil}
/// Clears the value of `countMin`. Subsequent reads from it will return its default value.
public mutating func clearCountMin() {self._countMin = nil}
/// If count_max < count_min, then count_min is only allowed value.
public var countMax: Int32 {
get {return _countMax ?? -1}
set {_countMax = newValue}
}
/// Returns true if `countMax` has been explicitly set.
public var hasCountMax: Bool {return self._countMax != nil}
/// Clears the value of `countMax`. Subsequent reads from it will return its default value.
public mutating func clearCountMax() {self._countMax = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self._countType)
case 2: try decoder.decodeSingularInt32Field(value: &self._countMin)
case 3: try decoder.decodeSingularInt32Field(value: &self._countMax)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._countType {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = self._countMin {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 2)
}
if let v = self._countMax {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _countType: String? = nil
fileprivate var _countMin: Int32? = nil
fileprivate var _countMax: Int32? = nil
}
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedMessageField(value: &self.inputArrays)
case 2: try decoder.decodeRepeatedStringField(value: &self.outputArrays)
case 10: try decoder.decodeSingularBoolField(value: &self._variableBatch)
case 12: try decoder.decodeRepeatedMessageField(value: &self.rnnStates)
case 14: try decoder.decodeRepeatedMessageField(value: &self.modelChecks)
case 16: try decoder.decodeSingularBoolField(value: &self._allowNonexistentArrays)
case 17: try decoder.decodeSingularBoolField(value: &self._allowNonasciiArrays)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.inputArrays.isEmpty {
try visitor.visitRepeatedMessageField(value: self.inputArrays, fieldNumber: 1)
}
if !self.outputArrays.isEmpty {
try visitor.visitRepeatedStringField(value: self.outputArrays, fieldNumber: 2)
}
if let v = self._variableBatch {
try visitor.visitSingularBoolField(value: v, fieldNumber: 10)
}
if !self.rnnStates.isEmpty {
try visitor.visitRepeatedMessageField(value: self.rnnStates, fieldNumber: 12)
}
if !self.modelChecks.isEmpty {
try visitor.visitRepeatedMessageField(value: self.modelChecks, fieldNumber: 14)
}
if let v = self._allowNonexistentArrays {
try visitor.visitSingularBoolField(value: v, fieldNumber: 16)
}
if let v = self._allowNonasciiArrays {
try visitor.visitSingularBoolField(value: v, fieldNumber: 17)
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _variableBatch: Bool? = nil
fileprivate var _allowNonexistentArrays: Bool? = nil
fileprivate var _allowNonasciiArrays: Bool? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "toco"
extension Toco_InputArrayShape: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2: .same(proto: "dims"),
]
public func _protobuf_generated_isEqualTo(other: Toco_InputArrayShape) -> Bool {
if self.dims != other.dims {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Toco_InputArray: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
6: .same(proto: "shape"),
3: .standard(proto: "mean_value"),
4: .standard(proto: "std_value"),
5: .standard(proto: "data_type"),
]
fileprivate class _StorageClass {
var _name: String? = nil
var _shape: Toco_InputArrayShape? = nil
var _meanValue: Float? = nil
var _stdValue: Float? = nil
var _dataType: Tensorflow_DataType? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_name = source._name
_shape = source._shape
_meanValue = source._meanValue
_stdValue = source._stdValue
_dataType = source._dataType
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public func _protobuf_generated_isEqualTo(other: Toco_InputArray) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let other_storage = _args.1
if _storage._name != other_storage._name {return false}
if _storage._shape != other_storage._shape {return false}
if _storage._meanValue != other_storage._meanValue {return false}
if _storage._stdValue != other_storage._stdValue {return false}
if _storage._dataType != other_storage._dataType {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Toco_RnnState: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "state_array"),
2: .standard(proto: "back_edge_source_array"),
5: .same(proto: "discardable"),
3: .same(proto: "size"),
4: .standard(proto: "manually_create"),
]
public func _protobuf_generated_isEqualTo(other: Toco_RnnState) -> Bool {
if self._stateArray != other._stateArray {return false}
if self._backEdgeSourceArray != other._backEdgeSourceArray {return false}
if self._discardable != other._discardable {return false}
if self._size != other._size {return false}
if self._manuallyCreate != other._manuallyCreate {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Toco_ModelFlags: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "input_arrays"),
2: .standard(proto: "output_arrays"),
10: .standard(proto: "variable_batch"),
12: .standard(proto: "rnn_states"),
14: .standard(proto: "model_checks"),
16: .standard(proto: "allow_nonexistent_arrays"),
17: .standard(proto: "allow_nonascii_arrays"),
]
public func _protobuf_generated_isEqualTo(other: Toco_ModelFlags) -> Bool {
if self.inputArrays != other.inputArrays {return false}
if self.outputArrays != other.outputArrays {return false}
if self._variableBatch != other._variableBatch {return false}
if self.rnnStates != other.rnnStates {return false}
if self.modelChecks != other.modelChecks {return false}
if self._allowNonexistentArrays != other._allowNonexistentArrays {return false}
if self._allowNonasciiArrays != other._allowNonasciiArrays {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Toco_ModelFlags.ModelCheck: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "count_type"),
2: .standard(proto: "count_min"),
3: .standard(proto: "count_max"),
]
public func _protobuf_generated_isEqualTo(other: Toco_ModelFlags.ModelCheck) -> Bool {
if self._countType != other._countType {return false}
if self._countMin != other._countMin {return false}
if self._countMax != other._countMax {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
| apache-2.0 |
superbderrick/SummerSlider | SummerSliderDemo/HorizontalViewController.swift | 1 | 2840 | //
// HorizontalViewController.swift
// SummerSlider
//
// Created by Kang Jinyeoung on 24/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SummerSlider
class HorizontalViewController: UIViewController {
var testSlider1:SummerSlider!
var testSlider2:SummerSlider!
var testSlider3:SummerSlider!
let testRect1 = CGRect(x:30 ,y:70 , width:300 , height:30)
let testRect2 = CGRect(x:30 ,y:120 , width:300 , height:30)
let testRect3 = CGRect(x:30 ,y:170 , width:300 , height:30)
@IBOutlet weak var testSlider4: SummerSlider!
@IBOutlet weak var testSlider5: SummerSlider!
@IBOutlet weak var testSlider6: SummerSlider!
override func viewDidLoad() {
super.viewDidLoad()
var marksArray1 = Array<Float>()
marksArray1 = [0,10,20,30,40,50,60,70,80,90,100]
testSlider1 = SummerSlider(frame: testRect1)
testSlider1.selectedBarColor = UIColor.blue
testSlider1.unselectedBarColor = UIColor.red
testSlider1.markColor = UIColor.yellow
testSlider1.markWidth = 2.0
testSlider1.markPositions = marksArray1
var marksArray2 = Array<Float>()
marksArray2 = [10.0,15.0,23.0,67.0,71.0]
testSlider2 = SummerSlider(frame: testRect2)
testSlider2.selectedBarColor = UIColor(red:138/255.0 ,green:255/255.0 ,blue:0/255 ,alpha:1.0)
testSlider2.unselectedBarColor = UIColor(red:108/255.0 ,green:200/255.0 ,blue:0/255.0 ,alpha:1.0)
testSlider2.markColor = UIColor.red
testSlider2.markWidth = 1.0
testSlider2.markPositions = marksArray2
testSlider3 = SummerSlider(frame: testRect3)
var marksArray3 = Array<Float>()
marksArray3 = [20.0,15.0,23.0,67.0, 90.0]
testSlider3 = SummerSlider(frame: testRect3)
testSlider3.selectedBarColor = UIColor.blue
testSlider3.unselectedBarColor = UIColor(red:20/255.0 ,green:40/255.0 ,blue:0/255.0 ,alpha:1.0)
testSlider3.markColor = UIColor.gray
testSlider3.markWidth = 10.0
testSlider3.markPositions = marksArray3
self.view.addSubview(testSlider1)
self.view.addSubview(testSlider2)
self.view.addSubview(testSlider3)
var marksArray4 = Array<Float>()
marksArray4 = [0.0,25.0,90.0]
testSlider4.markPositions = marksArray4
var marksArray5 = Array<Float>()
marksArray5 = [10.0,20.0,30.0,80,90.0]
testSlider5.markPositions = marksArray5
var marksArray6 = Array<Float>()
marksArray6 = [0,12,23,34,45,56,77,99]
testSlider6.selectedBarColor = UIColor.white
testSlider6.unselectedBarColor = UIColor.black
testSlider6.markColor = UIColor.orange
testSlider6.markWidth = 6.0
testSlider6.markPositions = marksArray6
}
}
| mit |
fishermenlabs/Treasure | Example/Tests/Tests.swift | 1 | 7657 | import UIKit
import XCTest
import Treasure
fileprivate func == <K, V>(left: [K:V], right: [K:V]) -> Bool {
return NSDictionary(dictionary: left).isEqual(to: right)
}
class Tests: XCTestCase {
override func setUp() {
Treasure.strictValidationOnInitialization = true
super.setUp()
}
override func tearDown() {
Treasure.clearChest()
super.tearDown()
}
func testExample() {
let testProject: Project? = Treasure(json: TestJson.projectJson)?.map()
let testUser: User? = User.from(TestJson.userJson)
if let manager = testProject?.manager, let user = testUser {
XCTAssertTrue(manager == user)
} else {
XCTFail()
}
}
func testTopLevelValidation() {
let test = Treasure(json: TestJson.invalidTopLevelJson)
let metaTest = Treasure(json: TestJson.metaJson)
let includedTest = Treasure(json: TestJson.invalidTopLevelIncludedJson)
let validTest = Treasure(json: TestJson.validTopLevelJson)
let validDocumentWithRelationship = Treasure(json: TestJson.validDocumentWithRelationship)
let validDocumentWithManyRelationships = Treasure(json: TestJson.validDocumentWithManyRelationships)
XCTAssertTrue(test == nil)
XCTAssertTrue(metaTest != nil)
XCTAssertTrue(includedTest == nil)
XCTAssertTrue(validTest != nil)
XCTAssertTrue(validDocumentWithRelationship != nil)
XCTAssertTrue(validDocumentWithManyRelationships != nil)
}
func testNoPool() {
let testProjectNotRemoved: Project? = Treasure(json: TestJson.validTopLevelJson)?.map()
let testProject: Project? = Treasure.map(json: TestJson.projectJson)
let testUser: User? = User.from(TestJson.userJson)
if let testNotRemoved = testProjectNotRemoved, let typeChest = Treasure.chest[testNotRemoved.type] as? [JSONObject] {
XCTAssertTrue(typeChest.contains(where: {$0[Key.id] as! String == testNotRemoved.id}))
}
if let test = testProject, let typeChest = Treasure.chest[test.type] as? [JSONObject] {
XCTAssertFalse(typeChest.contains(where: {$0[Key.id] as! String == test.id}))
}
if let manager = testProject?.manager, let user = testUser {
XCTAssertTrue(manager == user)
} else {
XCTFail()
}
}
func testCreateToOne() {
let toOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "4")).jsonWith(key: "users")!
let project = Treasure.jsonForResourceWith(type: "projects", attributes: ["title": "Test Project"], relationship: toOneRelationship)
let testJson = [
"data": [
"type": "projects",
"attributes": [
"title": "Test Project"
],
"relationships": [
"users": [
"data": ["type": "users", "id": "4"]
]
]
]
]
XCTAssertTrue(project as NSDictionary == testJson as NSDictionary)
}
func testCreateToMany() {
let pointsData1 = RelationshipData(type: "points", id: "1")
let pointsData2 = RelationshipData(type: "points", id: "2")
let toManyRelationship = ToManyRelationship.jsonWith(key: "points", data: [pointsData1, pointsData2])
let uuid = UUID()
let project = Treasure.jsonForResourceWith(type: "projects", id: uuid, attributes: ["title": "Test ToMany"], relationship: toManyRelationship)
XCTAssertTrue(project as NSDictionary == TestJson.projectPointsJson(id: uuid) as NSDictionary)
}
func testCreateCombo() {
let usersData = RelationshipData(type: "users", id: "4")
let pointsData1 = RelationshipData(type: "points", id: "1")
let pointsData2 = RelationshipData(type: "points", id: "2")
let toOneRelationship = ToOneRelationship.jsonWith(key: "users", data: usersData)
let toManyRelationship = ToManyRelationship(data: [pointsData1, pointsData2]).jsonWith(key: "points")!
let project = Treasure.jsonForResourceWith(type: "projects", attributes: ["title": "Test ToMany"], relationships: [toOneRelationship, toManyRelationship])
XCTAssertTrue(project as NSDictionary == TestJson.projectJsonManyRelationships as NSDictionary)
}
func testUpdate() {
let _: Project? = Treasure(json: TestJson.projectJson)?.map()
let toOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "10")).jsonWith(key: "users")!
let project = Treasure.jsonForResourceUpdateWith(type: "projects", id: "1", attributes: ["title": "The Best Project"], relationship: toOneRelationship)
XCTAssertTrue(project as NSDictionary == TestJson.projectJsonUpdated as NSDictionary)
}
func testReplace() {
let userJson: JSONObject = [
"id": "4",
"type": "users",
"attributes": [
"name": "New Name"
],
"relationships": [
"projects": [
"data": ["type": "projects", "id": "1"]
]
]
]
let testUserJson: JSONObject = [
"id": "4",
"type": "users",
"attributes": [
"name": "New Name",
"description": "The best test user ever"
],
"relationships": [
"projects": [
"data": ["type": "projects", "id": "1"]
]
]
]
let json: JSONObject = [
"data": [
"id": "1",
"type": "projects",
"attributes": [
"title": "Test Project"
],
"relationships": [
"users": [
"data": ["type": "users", "id": "4"]
]
]
],
"included": [userJson]
]
let _: Project? = Treasure(json: TestJson.projectJson)?.map()
let _: Project? = Treasure(json: json)?.map()
if let user = Treasure.chest["users"] as? [JSONObject] {
XCTAssertTrue(user.first! == testUserJson)
} else {
XCTFail()
}
}
func testStoreData() {
let _: Project? = Treasure(json: TestJson.projectJson)?.map()
let _: User? = Treasure(json: TestJson.userJson)?.map()
let json = Treasure.chest
if let data = Treasure.chestData() {
Treasure.clearChest()
Treasure.store(data)
XCTAssertTrue(json == Treasure.chest)
} else {
XCTFail()
}
}
func testResourceFromRelationship() {
let project: Project? = Treasure(json: TestJson.projectJson)?.map()
let relationship: ToOneRelationship = ToOneRelationship(data: RelationshipData(type: "users", id: "4"))
let user: User? = try? Treasure.resourceFor(relationship: relationship)
if let user = user, let manager = project?.manager {
XCTAssert(manager == user)
} else {
XCTFail()
}
}
}
| mit |
ostatnicky/kancional-ios | Pods/BonMot/Sources/UIKit/Tracking+Adaptive.swift | 2 | 1579 | //
// Tracking+Adaptive.swift
// BonMot
//
// Created by Brian King on 10/2/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension Tracking: AdaptiveStyleTransformation {
func adapt(attributes theAttributes: StyleAttributes, to traitCollection: UITraitCollection) -> StyleAttributes? {
if case .adobe = self {
var attributes = theAttributes
let styledFont = theAttributes[.font] as? UIFont
attributes.update(possibleValue: kerning(for: styledFont), forKey: .kern)
return attributes
}
else {
return nil
}
}
}
extension Tracking: EmbeddedTransformation {
struct Value {
static let adobeTracking = "adobe-tracking"
}
static func from(dictionary dict: StyleAttributes) -> EmbeddedTransformation? {
if case let (Value.adobeTracking?, size?) = (dict[EmbeddedTransformationHelpers.Key.type] as? String, dict[EmbeddedTransformationHelpers.Key.size] as? CGFloat) {
return Tracking.adobe(size)
}
return nil
}
var asDictionary: StyleAttributes {
if case let .adobe(size) = self {
return [
EmbeddedTransformationHelpers.Key.type: Value.adobeTracking,
EmbeddedTransformationHelpers.Key.size: size,
]
}
else {
// We don't need to persist point tracking, as it does not depend on
// the font size.
return [:]
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.