hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
7a3f84aa033ad07008189774863f967654efacf6 | 1,002 | import XCTest
import UIKit
import Stash
final class StashImageTests: StashImageBase {
func testResourceFetchExisting() {
// given
let identifier = UUID()
// when
Cache.stash(catImage, with: identifier, duration: .short)
// then
let image = Cache.resource(for: identifier)
XCTAssertEqual(image, catImage)
}
func testResourceFetchNonExisting() {
// given
let identifier = UUID()
// then
let resource = Cache.resource(for: identifier)
XCTAssertNil(resource)
}
func testExpiry() {
// given
let identifier = UUID()
// when
let date = Date().addingTimeInterval(1)
Cache.stash(catImage, with: identifier, duration: .custom(date))
sleep(2)
// then
let resource = Cache.resource(for: identifier)
XCTAssertNil(resource)
}
}
| 22.266667 | 72 | 0.538922 |
39df2a40f93cc57b54d3401ef040f5a0e918b79e | 2,613 | //
// SwiftUI Router
// Created by Freek Zijlmans on 13/01/2021.
//
import SwiftUI
/// Convenience wrapper around a `Button` with the ability to navigate to a new path.
///
/// A button that will navigate to the given path when pressed. Additionally it can provide information
/// whether the current path matches the `NavLink` path. This allows the developer to apply specific styling
/// when the `NavLink` is 'active'. E.g. highlighting or disabling the contents.
///
/// ```swift
/// NavLink(to: "/news/latest") { active in
/// Text("Latest news")
/// .color(active ? Color.primary : Color.secondary)
/// }
/// ```
///
/// - Note: The given path is always relative to the current route environment. See the documentation for `Route` about
/// the specifics of path relativity.
public struct NavLink<Content: View>: View {
@EnvironmentObject private var navigator: Navigator
@Environment(\.relativePath) private var relativePath
private let content: (Bool) -> Content
private let exact: Bool
private let path: String
private let replace: Bool
// MARK: - Initializers.
/// Button to navigate to a new path.
///
/// - Parameter to: New path to navigate to when pressed.
/// - Parameter replace: Replace the current entry in the history stack.
/// - Parameter exact: The `Bool` in the `content` parameter will only be `true` if the current path and the
/// `to` path are an *exact* match.
/// - Parameter content: Content views. The passed `Bool` indicates whether the current path matches `to` path.
public init(
to path: String,
replace: Bool = false,
exact: Bool = false,
@ViewBuilder content: @escaping (Bool) -> Content
) {
self.path = path
self.replace = replace
self.exact = exact
self.content = content
}
/// Button to navigate to a new path.
///
/// - Parameter to: New path to navigate to when pressed.
/// - Parameter replace: Replace the current entry in the history stack.
/// - Parameter content: Content views.
public init(to path: String, replace: Bool = false, @ViewBuilder content: @escaping () -> Content) {
self.init(to: path, replace: replace, exact: false, content: { _ in content() })
}
// MARK: -
private func onPressed() {
let resolvedPath = resolvePaths(relativePath, path)
if navigator.path != resolvedPath {
navigator.navigate(resolvedPath, replace: replace)
}
}
public var body: some View {
let absolutePath = resolvePaths(relativePath, path)
let active = exact ? navigator.path == absolutePath : navigator.path.starts(with: absolutePath)
return Button(action: onPressed) {
content(active)
}
}
}
| 33.075949 | 119 | 0.699579 |
e8f77e83e39ccebba9d81e62dea58cfe08f5fbb5 | 2,836 | //
// RiderListOffer+Additions.swift
// CD
//
// Created by Vladislav Simovic on 12/3/16.
// Copyright © 2016 CustomDeal. All rights reserved.
//
import Foundation
import CoreData
extension RiderListOffer {
// MARK: - RiderListOffer CRUD
static func createOrUpdateRiderListOfferWith(JSON:[String : Any], context:NSManagedObjectContext) -> RiderListOffer {
// fetch Language or create new one
var riderListOffer = RiderListOffer.findRiderListOfferWith(id: JSON["uid"] as! String, context: context)
riderListOffer = riderListOffer ?? RiderListOffer(context: context)
riderListOffer!.initWith(JSON: JSON)
return riderListOffer!
}
static func findRiderListOfferWith(id: String, context:NSManagedObjectContext) -> RiderListOffer? {
let fetchRequest: NSFetchRequest<RiderListOffer> = RiderListOffer.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uid == %@", id)
return try! context.fetch(fetchRequest).first
}
// MARK: - JSON serialization
func initWith(JSON:[String : Any]) {
self.uid = JSON["uid"] as? String ?? self.uid
self.offerorUid = JSON["offerorUid"] as? String ?? self.offerorUid
self.price = JSON["price"] as? NSNumber ?? self.price
self.riderListId = JSON["riderListId"] as? String ?? self.riderListId
self.message = JSON["message"] as? String ?? self.message
// get offeror info
if let offerorInfoDictionary = JSON["offerorInfo"] as? [String : String] {
self.offerorFirstName = offerorInfoDictionary["firstName"] ?? self.offerorFirstName
self.offerorLastName = offerorInfoDictionary["lastName"] ?? self.offerorLastName
self.offerorCity = offerorInfoDictionary["city"] ?? self.offerorCity
self.offerorCountry = offerorInfoDictionary["country"] ?? self.offerorCountry
self.offerorPhotoURL = offerorInfoDictionary["photoURL"] ?? self.offerorPhotoURL
}
}
func asJSON() -> [String : Any] {
var JSON = [String : Any]()
JSON["uid"] = self.uid
JSON["offerorUid"] = self.offerorUid
JSON["price"] = self.price
JSON["riderListId"] = self.riderListId
JSON["message"] = self.message
// set offeror info
var offerorInfoDictionary = [String : String]()
offerorInfoDictionary["firstName"] = self.offerorFirstName
offerorInfoDictionary["lastName"] = self.offerorLastName
offerorInfoDictionary["city"] = self.offerorCity
offerorInfoDictionary["country"] = self.offerorCountry
offerorInfoDictionary["photoURL"] = self.offerorPhotoURL
JSON["offerorInfo"] = offerorInfoDictionary
return JSON;
}
}
| 38.849315 | 121 | 0.651622 |
33fc5509bec741683e3a88343ed033905ede1e18 | 678 | import Foundation
private var configurations: [UUID: TinkCore.Configuration] = [:]
extension Tink {
static func registerConfiguration(_ configuration: TinkCore.Configuration) -> UUID {
let uuid = UUID()
configurations[uuid] = configuration
return uuid
}
static func deregisterConfiguration(for uuid: UUID) {
configurations[uuid] = nil
}
static func registeredConfigurations(for url: URL) -> [TinkCore.Configuration] {
configurations.values.filter { tink in
guard let appURI = tink.appURI else { return false }
return url.absoluteString.starts(with: appURI.absoluteString)
}
}
}
| 29.478261 | 88 | 0.668142 |
e48d3640dec751997a2591ee0e02d01a624b1b4c | 1,427 | //
// PreworkUITests.swift
// PreworkUITests
//
// Created by Adonis Deonarine on 7/1/21.
//
import XCTest
class PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.186047 | 182 | 0.655922 |
2f97b4ddbd62b421482810b926d302749315436d | 1,216 | import XCTest
@testable import RnaTranscription
class RnaTranscriptionTests: XCTestCase {
func testRnaComplementOfCytosineIsGuanine() {
XCTAssertEqual("G", Nucleotide("C").complementOfDNA)
}
func testRnaComplementOfGuanineIsCytosine() {
XCTAssertEqual("C", Nucleotide("G").complementOfDNA)
}
func testRnaComplementOfThymineIsAdenine() {
XCTAssertEqual("A", Nucleotide("T").complementOfDNA)
}
func testRnaComplementOfAdenineIsUracil() {
XCTAssertEqual("U", Nucleotide("A").complementOfDNA)
}
func testRnaComplement() {
XCTAssertEqual("UGCACCAGAAUU", Nucleotide("ACGTGGTCTTAA").complementOfDNA)
}
static var allTests: [(String, (RnaTranscriptionTests) -> () throws -> Void)] {
return [
("testRnaComplementOfCytosineIsGuanine", testRnaComplementOfCytosineIsGuanine),
("testRnaComplementOfGuanineIsCytosine", testRnaComplementOfGuanineIsCytosine),
("testRnaComplementOfThymineIsAdenine", testRnaComplementOfThymineIsAdenine),
("testRnaComplementOfAdenineIsUracil", testRnaComplementOfAdenineIsUracil),
("testRnaComplement", testRnaComplement),
]
}
}
| 34.742857 | 91 | 0.706414 |
ff369da19c4288e61bc17fbc51e01409c49ddbce | 412 | import PackageDescription
let package = Package(
name: "Skelton",
targets: [
Target(name: "SkeltonPerformance", dependencies: ["Skelton"]),
Target(name: "Skelton")
],
dependencies: [
.Package(url: "https://github.com/noppoMan/Suv.git", majorVersion: 0, minor: 13),
.Package(url: "https://github.com/slimane-swift/HTTPCore.git", majorVersion: 0, minor: 1)
]
)
| 29.428571 | 97 | 0.628641 |
db5c239fad3e55ad0e7d6eaf4adb000184b5c002 | 913 | //
// Weibo.swift
// WeiBo_Swift3.0
//
// Created by 李明禄 on 2016/11/26.
// Copyright © 2016年 SocererGroup. All rights reserved.
//
import UIKit
class Weibo: NSObject {
var text: String?
var name: String?
var icon: String?
var vip: Bool = true
var picture: String?
let properties = ["text", "name", "icon", "vip", "picture"]
override var description: String {
let dict = dictionaryWithValues(forKeys: properties)
return ("\(dict)")
}
// MARK: - 构造函数
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) { }
class func dictModel(list: [[String: AnyObject]]) -> [Weibo] {
var models = [Weibo]()
for dict in list {
models.append(Weibo(dict: dict))
}
return models
}
}
| 22.825 | 75 | 0.571742 |
87e9b16815a002786a94e4295e81635d4ea1d85e | 1,812 | import Dispatch
import Foundation
extension Array where Element: NSTextCheckingResult {
func ranges() -> [NSRange] {
return map { $0.range }
}
}
extension Array where Element: Equatable {
var unique: [Element] {
var uniqueValues = [Element]()
for item in self where !uniqueValues.contains(item) {
uniqueValues.append(item)
}
return uniqueValues
}
}
extension Array {
static func array(of obj: Any?) -> [Element]? {
if let array = obj as? [Element] {
return array
} else if let obj = obj as? Element {
return [obj]
}
return nil
}
func group<U: Hashable>(by transform: (Element) -> U) -> [U: [Element]] {
return Dictionary(grouping: self, by: { transform($0) })
}
func partitioned(by belongsInSecondPartition: (Element) throws -> Bool) rethrows ->
(first: ArraySlice<Element>, second: ArraySlice<Element>) {
var copy = self
let pivot = try copy.partition(by: belongsInSecondPartition)
return (copy[0..<pivot], copy[pivot..<count])
}
func parallelFlatMap<T>(transform: (Element) -> [T]) -> [T] {
return parallelMap(transform: transform).flatMap { $0 }
}
func parallelCompactMap<T>(transform: (Element) -> T?) -> [T] {
return parallelMap(transform: transform).compactMap { $0 }
}
func parallelMap<T>(transform: (Element) -> T) -> [T] {
var result = ContiguousArray<T?>(repeating: nil, count: count)
return result.withUnsafeMutableBufferPointer { buffer in
DispatchQueue.concurrentPerform(iterations: buffer.count) { idx in
buffer[idx] = transform(self[idx])
}
return buffer.map { $0! }
}
}
}
| 30.711864 | 87 | 0.587748 |
8a795c42fbe7c656823de463bcfe6cc5dc58a88b | 746 | //
// Calendar+Extension.swift
// AndroTrack (iOS)
//
// Created by Benoit Sida on 2021-11-15.
//
import Foundation
extension Calendar {
func generateDates(
inside interval: DateInterval,
matching components: DateComponents
) -> [Date] {
var dates: [Date] = []
dates.append(interval.start)
enumerateDates(
startingAfter: interval.start,
matching: components,
matchingPolicy: .nextTime
) { date, _, stop in
if let date = date {
if date < interval.end {
dates.append(date)
} else {
stop = true
}
}
}
return dates
}
}
| 21.314286 | 43 | 0.497319 |
fefbb1850f5298781c0e112aadbc6f0fcba384c2 | 533 | //
// PlatterButton.swift
// AutoLayoutConvenienceDemo
//
// Created by Andreas Verhoeven on 28/04/2021.
//
import UIKit
// Helper method for buttons
extension UIButton {
static func platter(title: String?, backgroundColor: UIColor? = nil, titleColor: UIColor? = nil) -> UIButton {
let button = UIButton(title: title, type: .system)
titleColor.map {button.setTitleColor($0, for: .normal) }
button.backgroundColor = backgroundColor ?? .systemBlue
button.layer.cornerRadius = 8
return button.constrain(height: 50)
}
}
| 26.65 | 111 | 0.726079 |
89ade3743a449d121f3b596822cfe3328d33aa6a | 915 | //
// ShadowProvider.swift
// SwiftStylish
//
import UIKit
/**
Provides **shadow** value to subclasses of:
- UIView
*/
class ShadowProvider: BaseProvider {}
extension ShadowProvider: ViewProviderProtocol
{
/**
Applies shadow values to UIView:
- shadowOffset
- shadowColor
- shadowRadius
- shadowOpacity
*/
func applyItem(forView view: UIView, item: StyleItem, variables: StyleVariables?) throws
{
let value = StyleValue(value: item.value, bundle: self.bundle, variables: variables)
let (shadow, opacity) = try value.toShadowValues()
let color = shadow.shadowColor as? UIColor
view.layer.shadowOffset = shadow.shadowOffset
view.layer.shadowColor = color?.withAlphaComponent(1.0).cgColor
view.layer.shadowRadius = shadow.shadowBlurRadius
view.layer.shadowOpacity = opacity
}
}
| 25.416667 | 92 | 0.659016 |
fb719b409f1e194217581ad6cbccbe40617d60d6 | 5,681 | import UIKit
import Foundation
import SwiftyUserDefaults
struct Helper {
// 最前面のViewControllerを取得する
static func frontViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return frontViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return frontViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return frontViewController(controller: presented)
}
return controller
}
static func getUpCommand1() -> String {
guard let string = Defaults[.upCommand1] else {
return ""
}
return string
}
static func getUpCommand2() -> String {
guard let string = Defaults[.upCommand2] else {
return ""
}
return string
}
static func getLeftCommand1() -> String {
guard let string = Defaults[.leftCommand1] else {
return ""
}
return string
}
static func getLeftCommand2() -> String {
guard let string = Defaults[.leftCommand2] else {
return ""
}
return string
}
static func getRightCommand1() -> String {
guard let string = Defaults[.rightCommand1] else {
return ""
}
return string
}
static func getRightCommand2() -> String {
guard let string = Defaults[.rightCommand2] else {
return ""
}
return string
}
static func getDownCommand1() -> String {
guard let string = Defaults[.downCommand1] else {
return ""
}
return string
}
static func getDownCommand2() -> String {
guard let string = Defaults[.downCommand2] else {
return ""
}
return string
}
static func getACommand1() -> String {
guard let string = Defaults[.ACommand1] else {
return ""
}
return string
}
static func getACommand2() -> String {
guard let string = Defaults[.ACommand2] else {
return ""
}
return string
}
static func getBCommand1() -> String {
guard let string = Defaults[.BCommand1] else {
return ""
}
return string
}
static func getBCommand2() -> String {
guard let string = Defaults[.BCommand2] else {
return ""
}
return string
}
static func getYCommand1() -> String {
guard let string = Defaults[.YCommand1] else {
return ""
}
return string
}
static func getYCommand2() -> String {
guard let string = Defaults[.YCommand2] else {
return ""
}
return string
}
static func getXCommand1() -> String {
guard let string = Defaults[.XCommand1] else {
return ""
}
return string
}
static func getXCommand2() -> String {
guard let string = Defaults[.XCommand2] else {
return ""
}
return string
}
static func getStartCommand1() -> String {
guard let string = Defaults[.startCommand1] else {
return ""
}
return string
}
static func getStartCommand2() -> String {
guard let string = Defaults[.startCommand2] else {
return ""
}
return string
}
static func getSelectCommand1() -> String {
guard let string = Defaults[.selectCommand1] else {
return ""
}
return string
}
static func getSelectCommand2() -> String {
guard let string = Defaults[.selectCommand2] else {
return ""
}
return string
}
static func setUpCommand(command1: String, command2: String){
Defaults[.upCommand1] = command1
Defaults[.upCommand2] = command2
}
static func setLeftCommand(command1: String, command2: String) {
Defaults[.leftCommand1] = command1
Defaults[.leftCommand2] = command2
}
static func setRightCommand(command1: String, command2: String) {
Defaults[.rightCommand1] = command1
Defaults[.rightCommand2] = command2
}
static func setDownCommand(command1: String, command2: String) {
Defaults[.downCommand1] = command1
Defaults[.downCommand2] = command2
}
static func setACommand(command1: String, command2: String) {
Defaults[.ACommand1] = command1
Defaults[.ACommand2] = command2
}
static func setBCommand(command1: String, command2: String) {
Defaults[.BCommand1] = command1
Defaults[.BCommand2] = command2
}
static func setYCommand(command1: String, command2: String) {
Defaults[.YCommand1] = command1
Defaults[.YCommand2] = command2
}
static func setXCommand(command1: String, command2: String) {
Defaults[.XCommand1] = command1
Defaults[.XCommand2] = command2
}
static func setStartCommand(command1: String, command2: String) {
Defaults[.startCommand1] = command1
Defaults[.startCommand2] = command2
}
static func setSelectCommand(command1: String, command2: String) {
Defaults[.selectCommand1] = command1
Defaults[.selectCommand2] = command2
}
}
| 26.671362 | 142 | 0.586869 |
fb9f08bccadde5f1ba0bbdc4c52d2261d95c0a43 | 2,176 | //
// AppDelegate.swift
// MainTabView
//
// Created by mozead1996 on 03/19/2022.
// Copyright (c) 2022 mozead1996. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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 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:.
}
}
| 46.297872 | 285 | 0.754596 |
c16d6be8e9e995259919df467c73d599ed06bba9 | 328 | //
// Publisher.swift
// Main
//
// Created by iq3AddLi on 2019/09/26.
//
import Foundation
public final class Publisher{
var identifier: Int?
var name: String
init(name: String, identifier: Int? = nil){
self.name = name
self.identifier = identifier
}
}
extension Publisher: Codable{}
| 15.619048 | 47 | 0.628049 |
e0520d5a78a6025d0762290baecb16a1abee9580 | 510 | //
// CollectionViewable.swift
// Cellorama
//
// Created by Sahel Jalal on 2/17/22.
//
import Foundation
import UIKit
typealias CollectionView = CollectionViewable & UICollectionView
protocol CollectionViewable {
var source: CollectionSourceable { get set }
var container: Container { get }
func applyLayout()
func applySnapshot()
func optionUpdated(_ kind: Options.Kind)
}
extension CollectionViewable {
var container: Container { source.container }
}
| 17.586207 | 64 | 0.696078 |
1a06fc91d526c103f1bf190f021f0175250e2133 | 15,459 | //
// AlamofireObjectMapperTests.swift
// AlamofireObjectMapperTests
//
// Created by Tristan Himmelman on 2015-04-30.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Tristan Himmelman
//
// 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 XCTest
import ObjectMapper
import Alamofire
import AlamofireObjectMapper
class AlamofireObjectMapperTests: 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 testResponseObject() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseObject { (response: DataResponse<WeatherResponse>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testResponseObjectMapToObject() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = self.expectation(description: "\(URL)")
let weatherResponse = WeatherResponse()
weatherResponse.date = Date()
_ = Alamofire.request(URL, method: .get).responseObject(mapToObject: weatherResponse) { (response: DataResponse<WeatherResponse>) in
expectation.fulfill()
let mappedObject = response.result.value
print(weatherResponse)
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.date, "Date should not be nil") // Date is not in JSON but should not be nil because we mapped onto an existing object with a date set
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testResponseObjectWithKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseObject(keyPath: "data") { (response: DataResponse<WeatherResponse>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testResponseObjectWithNestedKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/97231a04e6e4970612efcc0b7e0c125a83e3de6e/sample_keypath_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseObject(keyPath: "response.data") { (response: DataResponse<WeatherResponse>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testResponseArray() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseArray { (response: DataResponse<[Forecast]>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
XCTAssertTrue(mappedArray?.count == 3, "Didn't parse correct amount of objects")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testArrayResponseArrayWithKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseArray(keyPath: "three_day_forecast") { (response: DataResponse<[Forecast]>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testArrayResponseArrayWithNestedKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/97231a04e6e4970612efcc0b7e0c125a83e3de6e/sample_keypath_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseArray(keyPath: "response.data.three_day_forecast") { (response: DataResponse<[Forecast]>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
// MARK: - Immutable Tests
func testResponseImmutableObject() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseObject { (response: DataResponse<WeatherResponseImmutable>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
func testResponseImmutableArray() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
let expectation = self.expectation(description: "\(URL)")
_ = Alamofire.request(URL, method: .get).responseArray { (response: DataResponse<[ImmutableForecast]>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
XCTAssertTrue(mappedArray?.count == 3, "Didn't parse correct amount of objects")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error, "\(String(describing: error))")
}
}
}
// MARK: - Response classes
// MARK: - ImmutableMappable
class ImmutableWeatherResponse: ImmutableMappable {
let location: String
let threeDayForecast: [ImmutableForecast]
required init(map: Map) throws {
location = try map.value("location")
threeDayForecast = try map.value("three_day_forecast")
}
func mapping(map: Map) {
location >>> map["location"]
threeDayForecast >>> map["three_day_forecast"]
}
}
class ImmutableForecast: ImmutableMappable {
let day: String
let temperature: Int
let conditions: String
required init(map: Map) throws {
day = try map.value("day")
temperature = try map.value("temperature")
conditions = try map.value("conditions")
}
func mapping(map: Map) {
day >>> map["day"]
temperature >>> map["temperature"]
conditions >>> map["conditions"]
}
}
// MARK: - Mappable
class WeatherResponse: Mappable {
var location: String?
var threeDayForecast: [Forecast]?
var date: Date?
init(){}
required init?(map: Map){
}
func mapping(map: Map) {
location <- map["location"]
threeDayForecast <- map["three_day_forecast"]
}
}
class Forecast: Mappable {
var day: String?
var temperature: Int?
var conditions: String?
required init?(map: Map){
}
func mapping(map: Map) {
day <- map["day"]
temperature <- map["temperature"]
conditions <- map["conditions"]
}
}
struct WeatherResponseImmutable: ImmutableMappable {
let location: String
var threeDayForecast: [Forecast]
var date: Date?
init(map: Map) throws {
location = try map.value("location")
threeDayForecast = try map.value("three_day_forecast")
}
func mapping(map: Map) {
location >>> map["location"]
threeDayForecast >>> map["three_day_forecast"]
}
}
struct ForecastImmutable: ImmutableMappable {
let day: String
var temperature: Int
var conditions: String?
init(map: Map) throws {
day = try map.value("day")
temperature = try map.value("temperature")
conditions = try? map.value("conditions")
}
func mapping(map: Map) {
day >>> map["day"]
temperature >>> map["temperature"]
conditions >>> map["conditions"]
}
}
| 39.335878 | 176 | 0.647066 |
1428b76b64e28a645b719a3841c3bd9ca8fd61d7 | 681 | //
// AppDelegate.swift
// scantest
//
// Created by Brandon Stakenborg on 6/11/19.
// Copyright © 2019 Brandon Stakenborg. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
}
| 26.192308 | 145 | 0.696035 |
093f4787e7c3126c592f4b8818e1ba9bfba0b255 | 4,812 | //
// IOTCardView.swift
// IOTPay-iOS nonFramework
//
// Created by macbook on 2021-04-14.
//
import UIKit
class IOTCardView: UIView {
//init
let layout: IOTCardInfoViewLayout
private let cardWidthHeightRatio: CGFloat = 1.586
// var current = UIView()
// var nextOne = UIView()
var facade: IOTCardInfoComponentsFacade!
var side: CardFlipCycle = .front
var brand: CardCulingCycle = .unrecognized
var tillBrand: CardCulingCycle = .unrecognized
var isInvalid: Bool = false
var timer: Timer?
var current: IOTCardImageView!
override var frame: CGRect {
didSet {
layoutSub()
}
}
//var markView = CardMarkView(frame: CGRect.zero)
init(layout: IOTCardInfoViewLayout) {
self.layout = layout
super.init(frame: CGRect.zero)
IOTCardImageView.logoRect = nil
// current = makeCard(brand: .unrecognized, side: .front)
// addSubview(current)
}
init(frame: CGRect, layout: IOTCardInfoViewLayout) {
self.layout = layout
super.init(frame: frame)
IOTCardImageView.logoRect = nil
// current = makeCard(brand: .unrecognized, side: .front)
// addSubview(current)
//backgroundColor = .red
// markView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
// markView.layoutRect()
// addSubview(markView)
//
// markView.play(color: .red)
}
func setView(width: CGFloat) {
let height = width / cardWidthHeightRatio
frame.size = CGSize(width: width, height: height)
}
func layoutSub() {
subviews.forEach { $0.removeFromSuperview() }
current = makeCard(brand: .unrecognized, side: .front)
addSubview(current)
}
func playFlipAnimation() {
let card = makeCard(brand: brand, side: side.nextSide)
addSubview(card)
flip(fromView: current, toView: card)
side = side.nextSide
}
func playCycleAnimation(till: CardCulingCycle) {
tillBrand = till
startCycleTimer()
}
func playInvalidAnimation() {
}
func checkStopTimer() {
if tillBrand == brand {
stopTimer()
}
}
func startCycleTimer() {
stopTimer()
timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: { [weak self] (t) in
if let self = self, t.isValid {
let card = self.makeCard(brand: self.brand.nextCard, side: .front)
self.addSubview(card)
self.cycle(fromView: self.current, toView: card)
self.brand = self.brand.nextCard
self.checkStopTimer()
}
})
}
func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
deinit {
stopTimer()
}
private func flip(fromView: IOTCardImageView, toView: IOTCardImageView) {
let option: AnimationOptions
switch layout {
case .tripleLineWithLargeCardIconOnLeft,
.tripleLineWithLargeCardViewOnTop,
.singleLineWithSmallCardIcon:
option = .transitionFlipFromLeft
case .tripleLineOnLargeCardView:
option = .transitionCrossDissolve
}
UIView.transition(from: fromView, to: toView, duration: 0.4, options: [ option
//.transitionCrossDissolve,
//.transitionFlipFromLeft
//.transitionCurlDown
//.transitionCurlUp, //.showHideTransitionViews
])
current = toView
}
func cycle(fromView: IOTCardImageView, toView: IOTCardImageView) {
let option: AnimationOptions
switch layout {
case .tripleLineWithLargeCardIconOnLeft,
.tripleLineWithLargeCardViewOnTop,
.singleLineWithSmallCardIcon:
option = .transitionCurlUp
case .tripleLineOnLargeCardView:
option = .transitionCrossDissolve
}
UIView.transition(from: fromView, to: toView, duration: 0.2, options: [ option
//.transitionCrossDissolve,
//.transitionFlipFromLeft
//.transitionFlipFromTop
//.transitionCurlDown
//.transitionCurlUp, //.showHideTransitionViews
])
current = toView
}
private func makeCard(brand: CardCulingCycle?, side: CardFlipCycle) -> IOTCardImageView {
let card = IOTCardImageView(frame: CGRect(origin: CGPoint.zero, size: frame.size), layout: layout)
card.setCard(brand: brand, side: side)
return card
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func centering() {
let origin = CGPoint(x: (frame.width - frame.size.width) * 0.5,
y: (frame.height - frame.size.height) * 0.5)
frame.origin = origin
}
private func aspectRatioFit(rect: CGSize, image: UIImage?) -> CGSize {
guard let image = image else { return CGSize.zero }
let imageRatio = image.size.width / image.size.height
return aspectRatioFit(rect: rect, imageRatio: imageRatio)
}
private func aspectRatioFit(rect: CGSize, imageRatio: CGFloat) -> CGSize {
let width: CGFloat
let height: CGFloat
let rectRatio = rect.width / rect.height
if rectRatio <= imageRatio {
width = rect.width
height = width / imageRatio
} else {
height = rect.height
width = height * imageRatio
}
return CGSize(width: width, height: height)
}
}
| 23.704433 | 100 | 0.706983 |
e25ebc87feafe4942dfd91bdf9bbaf9def03bf05 | 6,426 | import UIKit
public class PageDotsView: UIView {
let currentDot: Int
private var dots: [UIView] = []
private var dotCount: Int
private let dotSize: CGFloat
private let dotColor: UIColor
private let currentDotColor: UIColor
private let imageIndices: [Int: UIImage]
private let dotContainer: UIView = {
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
view.accessibilityIdentifier = "DotContainer"
return view
}()
public init(
count: Int,
dotColor: UIColor = .gray,
currentDotColor: UIColor = .red,
dotSize: CGFloat = 7,
currentDot: Int = 0,
imageIndices: [Int: UIImage]=[:],
frame: CGRect
) {
self.dotCount = count
self.dotSize = dotSize
self.currentDot = currentDot
self.dotColor = dotColor
self.currentDotColor = currentDotColor
self.imageIndices = imageIndices
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.accessibilityIdentifier = "PageDotsView"
self.dots = setupViews(
count: count,
dotColor: dotColor,
currentDotColor: currentDotColor,
dotSize: dotSize,
imageIndices: imageIndices
)
setupConstraints(dotSize: dotSize)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func shiftRight() throws -> PageDotsView {
guard currentDot < dots.count - 1 else { throw DotsError.outOfBounds }
return PageDotsView(
count: self.dotCount,
dotColor: self.dotColor,
currentDotColor: self.currentDotColor,
dotSize: self.dotSize,
currentDot: self.currentDot + 1,
imageIndices: self.imageIndices,
frame: self.frame
)
}
public func shiftLeft() throws -> PageDotsView {
guard currentDot > 0 else { throw DotsError.outOfBounds }
return PageDotsView(
count: self.dotCount,
dotColor: self.dotColor,
currentDotColor: self.currentDotColor,
dotSize: self.dotSize,
currentDot: self.currentDot - 1,
imageIndices: self.imageIndices,
frame: self.frame
)
}
public func moveTo(index: Int) throws -> PageDotsView {
guard index < self.dotCount, index >= 0 else { throw DotsError.outOfBounds }
return PageDotsView(
count: self.dotCount,
dotColor: self.dotColor,
currentDotColor: self.currentDotColor,
dotSize: self.dotSize,
currentDot: index,
imageIndices: self.imageIndices,
frame: self.frame
)
}
override public var intrinsicContentSize: CGSize {
let width = Double(dots.count * (Int(dotSize) * 2) - Int(dotSize)) + 4
let height = Double(dotSize) * 1.50
return CGSize(width: width, height: height)
}
}
private extension PageDotsView {
func setupViews(
count: Int,
dotColor: UIColor,
currentDotColor: UIColor,
dotSize: CGFloat,
imageIndices: [Int: UIImage]
) -> [UIView] {
self.addSubview(dotContainer)
let adjustedImageIndices = imageIndices.reduce(into: [Int: UIImage]()) { (result, keyValue) in
result[keyValue.key < 0 ? count + keyValue.key : keyValue.key] = keyValue.value
}
return (0..<count).map { index in
if let image = adjustedImageIndices[index] {
let imageView = prepareImageDot(
image: image,
index: index,
color: dotColor,
currentColor: currentDotColor
)
self.dotContainer.addSubview(imageView)
return imageView
} else {
let dot = generateDot(
index: index,
dotColor: dotColor,
currentDotColor: currentDotColor,
dotSize: dotSize
)
self.dotContainer.addSubview(dot)
return dot
}
}
}
func setupConstraints(dotSize: CGFloat) {
var previousDot: UIView?
let dotConstraints = dots.flatMap { (dot) -> [NSLayoutConstraint] in
var constraints = [
dot.heightAnchor.constraint(equalToConstant: dotSize),
dot.widthAnchor.constraint(equalToConstant: dotSize),
dot.centerYAnchor.constraint(equalTo: self.dotContainer.centerYAnchor)
]
if let previousDot = previousDot {
constraints.append(dot.leadingAnchor.constraint(equalTo: previousDot.trailingAnchor, constant: dotSize))
}
previousDot = dot
return constraints
}
NSLayoutConstraint.activate(dotConstraints)
NSLayoutConstraint.activate([
dotContainer.widthAnchor.constraint(equalToConstant: self.intrinsicContentSize.width),
dotContainer.heightAnchor.constraint(equalToConstant: self.intrinsicContentSize.height),
dotContainer.centerXAnchor.constraint(equalTo: self.centerXAnchor),
dotContainer.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])
}
func generateDot(
index: Int,
dotColor: UIColor,
currentDotColor: UIColor,
dotSize: CGFloat
) -> DotView {
let frame = CGRect(x: 0, y: 0, width: dotSize, height: dotSize)
let color = index == self.currentDot ? currentDotColor : dotColor
let dot: DotView = DotView(frame: frame, mainColor: color)
dot.accessibilityIdentifier = "DotAt\(index)"
return dot
}
func prepareImageDot(
image: UIImage,
index: Int,
color: UIColor,
currentColor: UIColor
) -> UIImageView {
let imageColor = index == self.currentDot ? currentColor : color
let tintedImage = image.tint(with: imageColor)
let imageView = UIImageView(image: tintedImage)
imageView.accessibilityIdentifier = "ImageAt\(index)"
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}
}
| 32.291457 | 120 | 0.596016 |
e6e9303ac30c7c8fd52ae1cd58c199e1cefe227c | 3,852 | // Tests/SwiftProtobufTests/Test_Enum_Proto2.swift - Exercise generated enums
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Check that proto enums are properly translated into Swift enums. Among
/// other things, enums can have duplicate tags, the names should be correctly
/// translated into Swift lowerCamelCase conventions, etc.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
class Test_Enum_Proto2: XCTestCase, PBTestHelpers {
typealias MessageTestType = ProtobufUnittest_TestAllTypes
func testEqual() {
XCTAssertEqual(ProtobufUnittest_TestEnumWithDupValue.foo1, ProtobufUnittest_TestEnumWithDupValue.foo2)
XCTAssertNotEqual(ProtobufUnittest_TestEnumWithDupValue.foo1, ProtobufUnittest_TestEnumWithDupValue.bar1)
}
func testUnknownIgnored() {
// Proto2 requires that unknown enum values be dropped or ignored.
assertJSONDecodeSucceeds("{\"optionalNestedEnum\":\"FOO\"}") { (m: MessageTestType) -> Bool in
// If this compiles, then it includes all cases.
// If it fails to compile because it's missing an "UNRECOGNIZED" case,
// the code generator has created an UNRECOGNIZED case that should not be there.
switch m.optionalNestedEnum {
case .foo: return true
case .bar: return false
case .baz: return false
case .neg: return false
// DO NOT ADD A DEFAULT CASE TO THIS SWITCH!!!
}
}
}
func testJSONsingular() {
assertJSONEncode("{\"optionalNestedEnum\":\"FOO\"}") { (m: inout MessageTestType) in
m.optionalNestedEnum = ProtobufUnittest_TestAllTypes.NestedEnum.foo
}
}
func testJSONrepeated() {
assertJSONEncode("{\"repeatedNestedEnum\":[\"FOO\",\"BAR\"]}") { (m: inout MessageTestType) in
m.repeatedNestedEnum = [.foo, .bar]
}
}
func testEnumPrefix() {
XCTAssertEqual(ProtobufUnittest_SwiftEnumTest.EnumTest1.firstValue.rawValue, 1)
XCTAssertEqual(ProtobufUnittest_SwiftEnumTest.EnumTest1.secondValue.rawValue, 2)
XCTAssertEqual(ProtobufUnittest_SwiftEnumTest.EnumTest2.firstValue.rawValue, 1)
XCTAssertEqual(ProtobufUnittest_SwiftEnumTest.EnumTest2.secondValue.rawValue, 2)
}
func testUnknownValues() throws {
let orig = Proto3PreserveUnknownEnumUnittest_MyMessagePlusExtra.with {
$0.e = .eExtra
$0.repeatedE.append(.eExtra)
$0.repeatedPackedE.append(.eExtra)
$0.oneofE1 = .eExtra
}
let origSerialized = try orig.serializedData()
let msg = try Proto2PreserveUnknownEnumUnittest_MyMessage(serializedData: origSerialized)
// Nothing should be set, should all be in unknowns.
XCTAssertFalse(msg.hasE)
XCTAssertEqual(msg.repeatedE.count, 0)
XCTAssertEqual(msg.repeatedPackedE.count, 0)
XCTAssertNil(msg.o)
XCTAssertFalse(msg.unknownFields.data.isEmpty)
let msgSerialized = try msg.serializedData()
let msgPrime = try Proto3PreserveUnknownEnumUnittest_MyMessagePlusExtra(serializedData: msgSerialized)
// They should be back in the right fields.
XCTAssertEqual(msgPrime.e, .eExtra)
XCTAssertEqual(msgPrime.repeatedE, [.eExtra])
XCTAssertEqual(msgPrime.repeatedPackedE, [.eExtra])
XCTAssertEqual(msgPrime.o, .oneofE1(.eExtra))
XCTAssertTrue(msgPrime.unknownFields.data.isEmpty)
}
}
| 41.869565 | 113 | 0.662513 |
ac9872e5bf440990c736a3e8a3166b8a91640881 | 2,356 | //
// ShotFixture.swift
// Drrrible
//
// Created by Suyeol Jeon on 22/03/2017.
// Copyright © 2017 Suyeol Jeon. All rights reserved.
//
import Foundation
@testable import Drrrible
struct ShotFixture {
static let shot1: Shot = fixture([
"id": 1,
"title": "title1",
"description": "description1",
"width": 400,
"height": 300,
"images": [
"hidpi": NSNull(),
"normal": "https://example.com/shot1.png",
"teaser": "https://example.com/shot1_teaser.png"
],
"views_count": 4372,
"likes_count": 149,
"comments_count": 27,
"attachments_count": 0,
"rebounds_count": 2,
"buckets_count": 8,
"created_at": "2012-03-15T01:52:33Z",
"updated_at": "2012-03-15T02:12:57Z",
"animated": false,
"tags": [
"tag1",
"tag2",
],
"user": [
"id": 123,
"name": "Suyeol Jeon",
"username": "devxoul",
"avatar_url": "https://example.com/devxoul.png",
"bio": "https://xoul.kr",
"followers_count": 29262,
"followings_count": 1728,
"likes_count": 34954,
"shots_count": 214,
"can_upload_shot": true,
"type": "Player",
"pro": false,
"created_at": "2009-07-08T02:51:22Z",
"updated_at": "2014-02-22T17:10:33Z"
],
])
static let shot2: Shot = fixture([
"id": 2,
"title": "title2",
"description": "description2",
"width": 400,
"height": 300,
"images": [
"hidpi": NSNull(),
"normal": "https://example.com/shot2.png",
"teaser": "https://example.com/shot2_teaser.png"
],
"views_count": 4372,
"likes_count": 149,
"comments_count": 27,
"attachments_count": 0,
"rebounds_count": 2,
"buckets_count": 8,
"created_at": "2012-03-15T01:52:33Z",
"updated_at": "2012-03-15T02:12:57Z",
"animated": false,
"tags": [
"tag1",
"tag2",
],
"user": [
"id": 123,
"name": "Suyeol Jeon",
"username": "devxoul",
"avatar_url": "https://example.com/devxoul.png",
"bio": "https://xoul.kr",
"followers_count": 29262,
"followings_count": 1728,
"likes_count": 34954,
"shots_count": 214,
"can_upload_shot": true,
"type": "Player",
"pro": false,
"created_at": "2009-07-08T02:51:22Z",
"updated_at": "2014-02-22T17:10:33Z"
],
])
}
| 24.541667 | 54 | 0.551783 |
fcfb9b280f654f60e2a6424e52f7cc5ee447f515 | 1,031 | //
// ContentView.swift
// Game Catalogue
//
// Created by Laminal Falah on 12/08/21.
//
import SwiftUI
enum Tab {
case games
case developer
case creator
}
struct ContentView: View {
@State private var selection: Tab = .games
var body: some View {
TabView(selection: $selection) {
GameListView()
.tabItem {
Label("Games", systemImage: "gamecontroller")
}
.tag(Tab.games)
DeveloperListView()
.tabItem {
Label("Developer", systemImage: "star")
}
.tag(Tab.developer)
CreatorListView()
.tabItem {
Label("Creator", systemImage: "person.3")
}
.tag(Tab.creator)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(ServiceMock())
}
}
| 21.479167 | 65 | 0.491756 |
ab49ab5704cbda636ff3934beab98f4b684ec4dd | 1,326 | //
// ViewController.swift
// ZdataBinding
//
// Created by ABBAS TORABI on 12/4/1397 AP.
// Copyright © 1397 ABBAS TORABI. All rights reserved.
//
import UIKit
import Pods_ZdataBinding_Example
class ViewController: UIViewController {
var viewModel : ViewControllerViewModel! {
didSet {
// you can use this code for bind value from viewModel to textfiled or label or etc...
viewModel.my_variable.bind = { [unowned self] in self.myTextField.text = $0 }
viewModel.my_variable.bind = { [unowned self] in self.MyLabel.text = $0 }
}
}
@IBOutlet weak var MyLabel: UILabel!
@IBOutlet weak var myTextField: BindingTextField! {
didSet {
self.myTextField.bind { self.viewModel.my_variable.value = $0 }
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel = ViewControllerViewModel()
// you can add listener for hear value when changing
viewModel.my_variable.bind = { [unowned self] in self.MyVariableOnChange(value: $0) }
}
// create listener function
func MyVariableOnChange(value: String) {
MyLabel.text = value
myTextField.text = value
}
@IBAction func ResultBtn(_ sender: Any) {
viewModel.dataBindingValidate()
}
}
| 29.466667 | 98 | 0.640271 |
5066ea5906e30f48a6936ff15e08036e8918ba80 | 2,965 | //
// CardDetailTableViewController.swift
// Flashcards
//
// Created by Morgan Davison on 10/28/15.
// Copyright © 2015 Morgan Davison. All rights reserved.
//
import UIKit
protocol CardDetailTableViewControllerDelegate: class {
func cardDetailTableViewControllerDidCancel(controller: CardDetailTableViewController)
func cardDetailTableViewController(controller: CardDetailTableViewController, didFinishAddingCard card: Card)
func cardDetailTableViewController(controller: CardDetailTableViewController, didFinishEditingCard card: Card)
}
class CardDetailTableViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var frontTextField: UITextField!
@IBOutlet weak var backTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
weak var delegate: CardDetailTableViewControllerDelegate?
var cardToEdit: Card?
override func viewDidLoad() {
super.viewDidLoad()
if let card = cardToEdit {
title = "Edit Card"
frontTextField.text = card.frontText
backTextField.text = card.backText
saveButton.enabled = true
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
frontTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
// MARK: - UITextFieldDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText: NSString = textField.text!
let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
saveButton.enabled = (newText.length > 0)
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Actions
@IBAction func cancel() {
delegate?.cardDetailTableViewControllerDidCancel(self)
}
@IBAction func save() {
if let card = cardToEdit {
card.frontText = frontTextField.text!
card.backText = backTextField.text!
delegate?.cardDetailTableViewController(self, didFinishEditingCard: card)
} else {
let card = Card()
card.frontText = frontTextField.text!
card.backText = backTextField.text!
delegate?.cardDetailTableViewController(self, didFinishAddingCard: card)
}
}
}
| 32.582418 | 132 | 0.680607 |
232f67786ded22bcb5f939844a753140af9c0284 | 644 | import UIKit
struct UITextFieldBuilder {
private var textField: UITextField
init() {
textField = UITextField()
}
func withPlaceholderText(_ placeholderText: String) -> UITextFieldBuilder {
textField.placeholder = placeholderText
return self
}
func withText(_ text: String) -> UITextFieldBuilder {
textField.text = text
return self
}
func withInputAccessoryView(_ inputAccessoryView: UIView) -> UITextFieldBuilder {
textField.inputAccessoryView = inputAccessoryView
return self
}
func build() -> UITextField {
return textField
}
}
| 22.206897 | 85 | 0.658385 |
bf7e5be2148010fd64a1c96b3524ef2a85f7db32 | 11,446 | //
// ParameterEncoding.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/**
HTTP method definitions.
See https://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
// MARK: ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
for how to encode collection types, the convention of appending `[]` to the key for array
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
dictionary values (`foo[bar]=baz`).
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
implementation as the `.URL` case, but always applies the encoded result to the URL.
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
set to `application/json`.
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
according to the associated format and write options values, which is set as the body of the
request. The `Content-Type` HTTP header field of an encoded request is set to
`application/x-plist`.
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
parameters.
*/
public enum ParameterEncoding {
case url
case urlEncodedInURL
case json
case propertyList(PropertyListSerialization.PropertyListFormat, PropertyListSerialization.WriteOptions)
case custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply.
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
public func encode(
_ URLRequest: URLRequestConvertible,
parameters: [String: AnyObject]?)
-> (NSMutableURLRequest, NSError?)
{
var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters else { return (mutableURLRequest, nil) }
var encodingError: NSError? = nil
switch self {
case .url, .urlEncodedInURL:
func query(_ parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&")
}
func encodesParametersInURL(_ method: Method) -> Bool {
switch self {
case .urlEncodedInURL:
return true
default:
break
}
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if let method = Method(rawValue: mutableURLRequest.httpMethod) , encodesParametersInURL(method) {
if let
URLComponents = URLComponents(url: mutableURLRequest.url!, resolvingAgainstBaseURL: false)
, !parameters.isEmpty
{
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.url = URLComponents.url
}
} else {
if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil {
mutableURLRequest.setValue(
"application/x-www-form-urlencoded; charset=utf-8",
forHTTPHeaderField: "Content-Type"
)
}
mutableURLRequest.httpBody = query(parameters).data(
using: String.Encoding.utf8,
allowLossyConversion: false
)
}
case .json:
do {
let options = JSONSerialization.WritingOptions()
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.httpBody = data
} catch {
encodingError = error as NSError
}
case .propertyList(let format, let options):
do {
let data = try PropertyListSerialization.data(
fromPropertyList: parameters,
format: format,
options: options
)
if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.httpBody = data
} catch {
encodingError = error as NSError
}
case .custom(let closure):
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, encodingError)
}
/**
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
- parameter key: The key of the query component.
- parameter value: The value of the query component.
- returns: The percent-escaped, URL encoded query string components.
*/
public func queryComponents(_ key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = (CharacterSet.urlQueryAllowed as NSCharacterSet).mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharacters(in: generalDelimitersToEncode + subDelimitersToEncode)
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, OSX 10.10, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = <#T##Collection corresponding to `index`##Collection#>.index(index, offsetBy: batchSize, limitedBy: string.endIndex)
let range = startIndex..<endIndex
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
}
| 43.687023 | 147 | 0.587454 |
29076e9b0ff91b25b54dcf64705eb18af1a8ce16 | 1,826 | //
// APIListViewController.swift
// Dribbbler
//
// Created by 林 達也 on 2017/05/09.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import UIKit
import Dribbbler
private enum Row: String {
case userShots, shots
var title: String { return rawValue }
}
final class APIListViewController: UITableViewController {
fileprivate let rows: [Row] = [
.userShots,
.shots
]
@IBAction
private func authorizeAction() {
do {
try UIApplication.shared.open(
OAuth().authorizeURL(with: [.public, .write]), options: [:], completionHandler: nil)
} catch _ as OAuth.Error {
} catch {
}
}
}
extension APIListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = rows[indexPath.row].title
return cell
}
}
extension APIListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch rows[indexPath.row] {
case .userShots:
let userShots = Model.UserShots(userId: 1)
let vc = ShotsViewController(timeline: userShots)
navigationController?.pushViewController(vc, animated: true)
case .shots:
let shots = Model.Shots(list: .animated, sort: .recent)
let vc = ShotsViewController(timeline: shots)
navigationController?.pushViewController(vc, animated: true)
}
}
}
| 28.092308 | 109 | 0.650602 |
ccec4368cd9739b1f97d3105bec1f61f4c79b627 | 1,434 | import SwiftUI
struct FlowLayoutDemo: View {
@ObservedObject var model = FlowLayoutModel(string: .gettysburgShort)
@State private var inset: CGFloat = 0
private var padding: CGFloat = 10
var body: some View {
VStack {
// Textfield to test dynamically entering text
TextField("Enter some text", text: $model.string)
.textFieldStyle(RoundedBorderTextFieldStyle())
// Buttons to load empty, short, and long texts into model
HStack(spacing: 25) {
Button("Clear") { self.model.string = ""}
.padding(5).overlay(Capsule().stroke(Color.blue))
Button("Short text") { self.model.string = .gettysburgShort}
.padding(5).overlay(Capsule().stroke(Color.blue))
Button("Long text") { self.model.string = .gettysburg}
.padding(5).overlay(Capsule().stroke(Color.blue))
}
// Slider changes width of FlowLayout view
Slider(value: $inset, in: 0...100, step: 1)
HStack(spacing: 0) {
Rectangle().fill(Color.blue.opacity(0.3)).frame(width: inset)
FlowLayout(model: model)
Rectangle().fill(Color.blue.opacity(0.3)).frame(width: inset)
}
.frame(minWidth: 0, maxWidth: UIScreen.main.bounds.width - 2 * padding)
}
.padding(padding)
}
}
| 42.176471 | 83 | 0.571827 |
22e0ba502ef93bb0d12eee72707d191f343a1d89 | 204 | public struct Size: Hashable {
public var width: Double
public var height: Double
public init(width: Double, height: Double) {
self.width = width
self.height = height
}
}
| 20.4 | 48 | 0.627451 |
4b2cc48d9587d9064e4653d7932b8208b2d1ed14 | 2,125 | //
// ContentView.swift
// watchos WatchKit Extension
//
// Created by Moi Gutierrez on 2/19/21.
//
import SwiftUI
import SwiftUIComponents
struct ContentView: View {
let howTos = [
HowTo(isResolved: true, "use button", AnyView(UseButton())),
HowTo(isResolved: true, "change background", AnyView(ChangeBackground())),
]
var body: some View {
NavigationView {
List {
Section(footer:
VStack {
Divider()
VStack {
Text("✅ resolved")
Divider()
Text("❌ unresolved")
}
.fixedSize()
Divider()
VStack {
Text("by ") +
Text("Moi Gutiérrez")
.font(.system(size: 10, weight: .bold, design: .default)) +
Text(" with ❤️")
Link("@moyoteg",
destination: URL(string: "https://www.twitter.com/moyoteg")!)
}
}
, content: {
ForEach(howTos) { (howTo) in
NavigationLink(howTo.description,
destination:
howTo.view
.navigationBarTitle("\(howTo.name)")
)
}
})
}
.navigationBarTitle("How To")
}
.shadow(radius: 10)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 33.203125 | 102 | 0.328941 |
ffd7a0bafff4f3759f8e39a972d748900dba9e7a | 24,243 | //
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate, ColorPickerTextFieldDelegate {
let sectionTitles = ["UIKeyboard handling",
"IQToolbar handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"IQKeyboardManager Debug"]
let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font","Toolbar Tint Color","Toolbar Done BarButtonItem Image","Toolbar Done Button Text"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Debugging logs in Console"]]
let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager","Set keyboard distance from textField"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text","Override toolbar tintColor property","Replace toolbar done button text with provided image","Override toolbar done button text"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Setting enableDebugging to YES/No to turn on/off debugging mode"]]
var selectedIndexPathForOptions : IndexPath?
@IBAction func doneAction (_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
/** UIKeyboard Handling */
@objc func enableAction (_ sender: UISwitch) {
IQKeyboardManager.shared.enable = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
@objc func keyboardDistanceFromTextFieldAction (_ sender: UIStepper) {
IQKeyboardManager.shared.keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none)
}
/** IQToolbar handling */
@objc func enableAutoToolbarAction (_ sender: UISwitch) {
IQKeyboardManager.shared.enableAutoToolbar = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: .fade)
}
@objc func shouldToolbarUsesTextFieldTintColorAction (_ sender: UISwitch) {
IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = sender.isOn
}
@objc func shouldShowToolbarPlaceholder (_ sender: UISwitch) {
IQKeyboardManager.shared.shouldShowToolbarPlaceholder = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: .fade)
}
@objc func toolbarDoneBarButtonItemImage (_ sender: UISwitch) {
if sender.isOn {
IQKeyboardManager.shared.toolbarDoneBarButtonItemImage = UIImage(named:"IQButtonBarArrowDown")
} else {
IQKeyboardManager.shared.toolbarDoneBarButtonItemImage = nil
}
self.tableView.reloadSections(IndexSet(integer: 1), with: .fade)
}
/** "Keyboard appearance overriding */
@objc func overrideKeyboardAppearanceAction (_ sender: UISwitch) {
IQKeyboardManager.shared.overrideKeyboardAppearance = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 2), with: .fade)
}
/** Resign first responder handling */
@objc func shouldResignOnTouchOutsideAction (_ sender: UISwitch) {
IQKeyboardManager.shared.shouldResignOnTouchOutside = sender.isOn
}
/** Sound handling */
@objc func shouldPlayInputClicksAction (_ sender: UISwitch) {
IQKeyboardManager.shared.shouldPlayInputClicks = sender.isOn
}
/** Debugging */
@objc func enableDebugging (_ sender: UISwitch) {
IQKeyboardManager.shared.enableDebugging = sender.isOn
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
#if swift(>=4.2)
return UITableView.automaticDimension
#else
return UITableViewAutomaticDimension
#endif
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.shared.enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.shared.enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.shared.shouldShowToolbarPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 2:
if IQKeyboardManager.shared.overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 3,4,5:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch ((indexPath as NSIndexPath).section) {
case 0:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.enable
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), for: .valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.stepper.value = Double(IQKeyboardManager.shared.keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.shared.keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, for: .allEvents)
cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), for: .valueChanged)
return cell
default:
break
}
case 1:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), for: .valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), for: .valueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.shouldShowToolbarPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldShowToolbarPlaceholder(_:)), for: .valueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 5:
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorTableViewCell") as! ColorTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.colorPickerTextField.selectedColor = IQKeyboardManager.shared.toolbarTintColor
cell.colorPickerTextField.tag = 15
cell.colorPickerTextField.delegate = self
return cell
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageSwitchTableViewCell") as! ImageSwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.arrowImageView.image = IQKeyboardManager.shared.toolbarDoneBarButtonItemImage
cell.switchEnable.isOn = IQKeyboardManager.shared.toolbarDoneBarButtonItemImage != nil
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), for: .valueChanged)
return cell
case 7:
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell") as! TextFieldTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.textField.text = IQKeyboardManager.shared.toolbarDoneBarButtonItemText
cell.textField.tag = 17
cell.textField.delegate = self
return cell
default:
break
}
case 2:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), for: .valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
default:
break
}
case 3:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), for: .valueChanged)
return cell
default:
break
}
case 4:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), for: .valueChanged)
return cell
default:
break
}
case 5:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.shared.enableDebugging
cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), for: .valueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func colorPickerTextField(_ textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String : Any] = [:]) {
if textField.tag == 15 {
let color = colorAttributes["color"] as! UIColor
if color.isEqual(UIColor.clear) {
IQKeyboardManager.shared.toolbarTintColor = nil
} else {
IQKeyboardManager.shared.toolbarTintColor = color
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 17 {
IQKeyboardManager.shared.toolbarDoneBarButtonItemText = textField.text?.isEmpty == false ? textField.text : nil
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destination as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPath(for: cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.shared.toolbarManageBehaviour.hashValue
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.shared.toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
if let placeholderFont = IQKeyboardManager.shared.placeholderFont {
if let index = fonts.firstIndex(of: placeholderFont) {
controller.selectedIndex = index
}
}
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.shared.keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(_ controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.shared.toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
IQKeyboardManager.shared.placeholderFont = fonts[index]
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.shared.keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
| 45.569549 | 377 | 0.600008 |
64f7cad02d78547331ea58784d259c202cc73443 | 1,227 | // This file is auto-generated, don't edit it. Thanks.
import Foundation
import Tea.Swift
open class UpdateAppRequest : TeaModel {
@objc public var appId:String = "";
@objc public var appName:String = "";
@objc public var description_:String = "";
@objc public var isThirdParty:Bool = true;
@objc public var logo:String = "";
@objc public var redirectUri:String = "";
@objc public var scope:[String:Any] = [String:NSObject]();
@objc public var type:String = "";
public override init() {
super.init();
self.__name["appId"] = "app_id";
self.__name["appName"] = "app_name";
self.__name["description_"] = "description";
self.__name["isThirdParty"] = "is_third_party";
self.__name["logo"] = "logo";
self.__name["redirectUri"] = "redirect_uri";
self.__name["scope"] = "scope";
self.__name["type"] = "type";
self.__required["appId"] = true;
self.__required["appName"] = true;
self.__required["isThirdParty"] = true;
self.__required["logo"] = true;
self.__required["redirectUri"] = true;
self.__required["scope"] = true;
self.__required["type"] = true;
}
}
| 29.214286 | 62 | 0.601467 |
0a9825d9381bc00fa99857c1d86e895ded7942f9 | 2,630 | //
// NewsYellowViewController.swift
// BaseSwift
//
// Created by Gary on 2016/12/28.
// Copyright © 2016年 shadowR. All rights reserved.
//
import SRKit
class NewsYellowViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var dataArray: [AnyDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.contentInset = UIEdgeInsets(0, 0, C.tabBarHeight(), 0)
dataArray = NonNull.array(C.resourceDirectory.appending(pathComponent: "json/debug/title_party.json").fileJsonObject) as! [AnyDictionary]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
LogDebug("\(NSStringFromClass(type(of: self))).\(#function)")
NotifyDefault.remove(self)
}
//MARK: - UITableViewDelegate, UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataArray[section]["category"] as! String?
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NonNull.array(dataArray[section]["titles"]).count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: C.reuseIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: C.reuseIdentifier)
cell?.selectionStyle = .default
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.textColor = UIColor.darkGray
}
cell?.textLabel?.font = UIFont.preferred.body
cell?.textLabel?.text =
((NonNull.array(dataArray[indexPath.section]["titles"]))[indexPath.row] as! String)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
| 35.066667 | 145 | 0.681749 |
87cb7e3479bbbcffe7cb8c9942fbdf9de4233456 | 7,332 | //
// DocumentTableViewCell.swift
// zScanner
//
// Created by Jakub Skořepa on 21/07/2019.
// Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved.
//
import UIKit
import RxSwift
protocol DocumentViewDelegate: class {
func handleError(_ error: RequestError)
}
class DocumentTableViewCell: UITableViewCell {
//MARK: Instance part
private var viewModel: DocumentViewModel?
private weak var delegate: DocumentViewDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Lifecycle
override func prepareForReuse() {
super.prepareForReuse()
viewModel = nil
delegate = nil
titleLabel.text = nil
detailLabel.text = nil
loadingCircle.isHidden = true
loadingCircle.progressValue(is: 0, animated: false)
successImageView.isHidden = true
retryButton.isHidden = true
disposeBag = DisposeBag()
}
//MARK: Interface
func setup(with model: DocumentViewModel, delegate: DocumentViewDelegate) {
self.viewModel = model
self.delegate = delegate
// Make sure the label will keep the space even when empty while respecting the dynamic font size
titleLabel.text = String(format: "%@ %@", model.document.folder.externalId, model.document.folder.name)
detailLabel.text = [
model.document.type.name,
String(format: "document.documentCell.numberOfPagesFormat".localized, model.document.pages.count),
]
.filter({ !$0.isEmpty })
.joined(separator: " - ")
let onCompleted: () -> Void = { [weak self] in
self?.retryButton.isHidden = true
// If not animating, skip trnasition animation
if self?.loadingCircle.isHidden == true {
self?.loadingCircle.isHidden = true
self?.successImageView.isHidden = false
return
}
self?.successImageView.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
self?.successImageView.isHidden = false
self?.successImageView.alpha = 0
UIView.animate(withDuration: 0.5, animations: {
self?.successImageView.alpha = 1
self?.successImageView.transform = CGAffineTransform(scaleX: 1, y: 1)
self?.loadingCircle.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
self?.loadingCircle.alpha = 0
}, completion: { _ in
self?.loadingCircle.isHidden = true
self?.loadingCircle.alpha = 1
self?.loadingCircle.transform = CGAffineTransform(scaleX: 1, y: 1)
})
}
let onError: (Error?) -> Void = { [weak self] error in
self?.loadingCircle.isHidden = true
self?.successImageView.isHidden = true
self?.retryButton.isHidden = false
if let error = error as? RequestError {
self?.delegate?.handleError(error)
}
}
model.documentUploadStatus
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] status in
switch status {
case .awaitingInteraction:
self?.loadingCircle.isHidden = true
self?.successImageView.isHidden = true
self?.retryButton.isHidden = true
case .progress(let percentage):
self?.loadingCircle.progressValue(is: percentage)
self?.loadingCircle.isHidden = false
self?.successImageView.isHidden = true
self?.retryButton.isHidden = true
case .success:
onCompleted()
case .failed(let error):
onError(error)
}
})
.disposed(by: disposeBag)
retryButton.rx.tap.subscribe(onNext: { [weak self] in
self?.viewModel?.reupload()
})
.disposed(by: disposeBag)
}
//MARK: Helpers
private var disposeBag = DisposeBag()
private func setupView() {
selectionStyle = .none
preservesSuperviewLayoutMargins = true
contentView.preservesSuperviewLayoutMargins = true
contentView.addSubview(textContainer)
textContainer.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.topMargin)
make.bottom.equalTo(contentView.snp.bottomMargin)
make.left.equalTo(contentView.snp.leftMargin)
}
textContainer.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.top.right.left.equalToSuperview()
}
titleLabel.setContentHuggingPriority(.init(rawValue: 251), for: .vertical)
titleLabel.setContentCompressionResistancePriority(.init(rawValue: 751), for: .vertical)
textContainer.addSubview(detailLabel)
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(4)
make.right.left.bottom.equalToSuperview()
}
contentView.addSubview(statusContainer)
statusContainer.snp.makeConstraints { make in
make.right.equalTo(contentView.snp.rightMargin)
make.left.equalTo(textContainer.snp.right).offset(8)
make.width.height.equalTo(30)
make.centerY.equalToSuperview()
}
statusContainer.addSubview(loadingCircle)
loadingCircle.snp.makeConstraints { make in
make.center.equalToSuperview()
}
statusContainer.addSubview(successImageView)
successImageView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
statusContainer.addSubview(retryButton)
retryButton.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
private var titleLabel: UILabel = {
let label = UILabel()
label.font = .body
label.textColor = .black
return label
}()
private var detailLabel: UILabel = {
let label = UILabel()
label.font = .footnote
label.textColor = UIColor.black.withAlphaComponent(0.7)
label.numberOfLines = 0
return label
}()
private var loadingCircle = LoadingCircle()
private var successImageView: UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFit
image.image = #imageLiteral(resourceName: "checkmark")
return image
}()
private var retryButton: UIButton = {
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "refresh"), for: .normal)
return button
}()
private var textContainer = UIView()
private var statusContainer = UIView()
}
| 34.584906 | 111 | 0.592744 |
281a695525096614bc0840d9943b644e2189ea1c | 7,704 | //
// AppButtons.swift
// Stopwatch
//
// Created by Chris Mendez on 9/27/15.
// Copyright (c) 2015 Skyground Media. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class AppButtons : NSObject {
//// Cache
private struct Cache {
static let green: UIColor = UIColor(red: 0.259, green: 0.804, blue: 0.000, alpha: 1.000)
static let blue: UIColor = UIColor(red: 0.337, green: 0.718, blue: 0.945, alpha: 1.000)
static let red: UIColor = UIColor(red: 1.000, green: 0.000, blue: 0.000, alpha: 1.000)
static let orange: UIColor = UIColor(red: 1.000, green: 0.631, blue: 0.004, alpha: 1.000)
static var image: UIImage?
}
//// Colors
public class var green: UIColor { return Cache.green }
public class var blue: UIColor { return Cache.blue }
public class var red: UIColor { return Cache.red }
public class var orange: UIColor { return Cache.orange }
//// Images
public class var image: UIImage {
if Cache.image == nil {
Cache.image = UIImage(named: "image.png")!
}
return Cache.image!
}
//// Drawing Methods
public class func drawStart() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Drawing
let symbolRect = CGRectMake(0, 0, 100, 100)
CGContextSaveGState(context)
UIRectClip(symbolRect)
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y)
AppButtons.drawGUIButton(fuchsia: AppButtons.green)
CGContextRestoreGState(context)
//// Text Drawing
let textRect = CGRectMake(0, 24, 100, 51)
let textTextContent = NSString(string: "Start")
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 32)!, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
public class func drawLap() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Drawing
let symbolRect = CGRectMake(0, 0, 100, 100)
CGContextSaveGState(context)
UIRectClip(symbolRect)
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y)
AppButtons.drawGUIButton(fuchsia: AppButtons.blue)
CGContextRestoreGState(context)
//// Text Drawing
let textRect = CGRectMake(0, 24, 100, 51)
let textTextContent = NSString(string: "Lap")
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 32)!, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
public class func drawGUIButton(fuchsia fuchsia: UIColor = UIColor(red: 1.000, green: 0.000, blue: 0.921, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRectMake(2, 2, 96, 96))
fuchsia.setFill()
ovalPath.fill()
UIColor.darkGrayColor().setStroke()
ovalPath.lineWidth = 1
CGContextSaveGState(context)
CGContextSetLineDash(context, 0, [1, 2], 2)
ovalPath.stroke()
CGContextRestoreGState(context)
}
public class func drawStop() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Drawing
let symbolRect = CGRectMake(0, 0, 100, 100)
CGContextSaveGState(context)
UIRectClip(symbolRect)
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y)
AppButtons.drawGUIButton(fuchsia: AppButtons.red)
CGContextRestoreGState(context)
//// Text Drawing
let textRect = CGRectMake(0, 24, 100, 51)
let textTextContent = NSString(string: "Start")
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 32)!, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
public class func drawReset() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Symbol Drawing
let symbolRect = CGRectMake(0, 0, 100, 100)
CGContextSaveGState(context)
UIRectClip(symbolRect)
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y)
AppButtons.drawGUIButton(fuchsia: AppButtons.orange)
CGContextRestoreGState(context)
//// Text Drawing
let textRect = CGRectMake(0, 24, 100, 51)
let textTextContent = NSString(string: "Reset")
let textStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .Center
let textFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 32)!, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
}
| 43.039106 | 234 | 0.703531 |
14fb126a74fdf1d9e6cf6b410191d73d48424207 | 4,145 | //
// Saturn.swift
// SwiftAA
//
// Created by Cédric Foellmi on 19/06/16.
// MIT Licence. See LICENCE file.
//
import Foundation
/// The Saturn planet.
public class Saturn: Planet {
/// The average color of the planet.
public class override var averageColor: Color {
get { return Color(red: 0.941, green:0.827, blue:0.616, alpha: 1.0) }
}
public fileprivate(set) var Mimas: SaturnianMoon
public fileprivate(set) var Enceladus: SaturnianMoon
public fileprivate(set) var Tethys: SaturnianMoon
public fileprivate(set) var Dione: SaturnianMoon
public fileprivate(set) var Rhea: SaturnianMoon
public fileprivate(set) var Titan: SaturnianMoon
public fileprivate(set) var Hyperion: SaturnianMoon
public fileprivate(set) var Iapetus: SaturnianMoon
public fileprivate(set) var ringSystem: SaturnRingSystem
/// The list of saturnian moons, in increasing order of distance from the planet.
public var moons: [SaturnianMoon] {
get { return [self.Mimas, self.Enceladus, self.Tethys, self.Dione, self.Rhea, self.Titan, self.Hyperion, self.Iapetus] }
}
/// Returns a Saturn object.
///
/// - Parameters:
/// - julianDay: The julian day at which the planet is considered.
/// - highPrecision: A boolean indicating whether high precision (VSOP87 theory) must be used. Default is true.
public required init(julianDay: JulianDay, highPrecision: Bool = true) {
let details = KPCAASaturnMoonsDetails_Calculate(julianDay.value, highPrecision)
self.Mimas = SaturnianMoon(name: "Mimas", details: details.Satellite1, synodicPeriod: 0.9425, visualMagnitude: 12.9, diameter: 400.0)
self.Enceladus = SaturnianMoon(name: "Enceladus", details: details.Satellite2, synodicPeriod: 1.3704, visualMagnitude: 11.7, diameter: 498)
self.Tethys = SaturnianMoon(name: "Tethys", details: details.Satellite3, synodicPeriod: 1.8881, visualMagnitude: 10.2, diameter: 1046.0)
self.Dione = SaturnianMoon(name: "Dione", details: details.Satellite4, synodicPeriod: 2.7376, visualMagnitude: 10.4, diameter: 1120.0)
self.Rhea = SaturnianMoon(name: "Rhea", details: details.Satellite5, synodicPeriod: 4.5194, visualMagnitude: 9.7, diameter: 1528.0)
self.Titan = SaturnianMoon(name: "Titan", details: details.Satellite6, synodicPeriod: 15.9691, visualMagnitude: 8.3, diameter: 5150.0)
self.Hyperion = SaturnianMoon(name: "Hyperion", details: details.Satellite7, synodicPeriod: 21.3188, visualMagnitude: 14.2, diameter: 286.0)
self.Iapetus = SaturnianMoon(name: "Iapetus", details: details.Satellite8, synodicPeriod: 79.9202, visualMagnitude: 10.2, diameter: 1460.0)
let ringDetails = KPCAASaturnRings_Calculate(julianDay.value, highPrecision)
self.ringSystem = SaturnRingSystem(ringDetails, julianDay: julianDay)
super.init(julianDay: julianDay, highPrecision: highPrecision)
}
/// The magnitude of the planet. Includes the contribution from the ring.
public var magnitude: Magnitude {
get { return Magnitude(KPCAAIlluminatedFraction_SaturnMagnitudeAA(self.radiusVector.value,
self.apparentGeocentricDistance.value,
self.ringSystem.saturnicentricSunEarthLongitudesDifference.value,
self.ringSystem.earthCoordinates.latitude.value)) } }
/// The magnitude 'Muller' of the planet. Includes the contribution from the ring.
public var magnitudeMuller: Magnitude {
get { return Magnitude(KPCAAIlluminatedFraction_SaturnMagnitudeMuller(self.radiusVector.value,
self.apparentGeocentricDistance.value,
self.ringSystem.saturnicentricSunEarthLongitudesDifference.value,
self.ringSystem.earthCoordinates.latitude.value)) } }
}
| 57.569444 | 148 | 0.662002 |
5d2058e7122f6e0443d63ff694b713ff248fe198 | 68,720 | /**
* Copyright IBM Corporation 2016, 2017
*
* 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.
**/
// swiftlint:disable function_body_length force_try force_unwrapping superfluous_disable_command
import XCTest
import Foundation
import ConversationV1
class ConversationTests: XCTestCase {
private var conversation: Conversation!
private let workspaceID = Credentials.ConversationWorkspace
// MARK: - Test Configuration
/** Set up for each test by instantiating the service. */
override func setUp() {
super.setUp()
continueAfterFailure = false
instantiateConversation()
}
static var allTests: [(String, (ConversationTests) -> () throws -> Void)] {
return [
("testMessage", testMessage),
("testMessageAllFields1", testMessageAllFields1),
("testMessageAllFields2", testMessageAllFields2),
("testMessageContextVariable", testMessageContextVariable),
("testListAllWorkspaces", testListAllWorkspaces),
("testListAllWorkspacesWithPageLimit1", testListAllWorkspacesWithPageLimit1),
("testListAllWorkspacesWithIncludeCount", testListAllWorkspacesWithIncludeCount),
("testCreateAndDeleteWorkspace", testCreateAndDeleteWorkspace),
("testListSingleWorkspace", testListSingleWorkspace),
("testCreateUpdateAndDeleteWorkspace", testCreateUpdateAndDeleteWorkspace),
("testListAllIntents", testListAllIntents),
("testListAllIntentsWithIncludeCount", testListAllIntentsWithIncludeCount),
("testListAllIntentsWithPageLimit1", testListAllIntentsWithPageLimit1),
("testListAllIntentsWithExport", testListAllIntentsWithExport),
("testCreateAndDeleteIntent", testCreateAndDeleteIntent),
("testGetIntentWithExport", testGetIntentWithExport),
("testCreateUpdateAndDeleteIntent", testCreateUpdateAndDeleteIntent),
("testListAllExamples", testListAllExamples),
("testListAllExamplesWithIncludeCount", testListAllExamplesWithIncludeCount),
("testListAllExamplesWithPageLimit1", testListAllExamplesWithPageLimit1),
("testCreateAndDeleteExample", testCreateAndDeleteExample),
("testGetExample", testGetExample),
("testCreateUpdateAndDeleteExample", testCreateUpdateAndDeleteExample),
("testListAllCounterexamples", testListAllCounterexamples),
("testListAllCounterexamplesWithIncludeCount", testListAllCounterexamplesWithIncludeCount),
("testListAllCounterexamplesWithPageLimit1", testListAllCounterexamplesWithPageLimit1),
("testCreateAndDeleteCounterexample", testCreateAndDeleteCounterexample),
("testGetCounterexample", testGetCounterexample),
("testCreateUpdateAndDeleteCounterexample", testCreateUpdateAndDeleteCounterexample),
("testListAllEntities", testListAllEntities),
("testListAllEntitiesWithIncludeCount", testListAllEntitiesWithIncludeCount),
("testListAllEntitiesWithPageLimit1", testListAllEntitiesWithPageLimit1),
("testListAllEntitiesWithExport", testListAllEntitiesWithExport),
("testCreateAndDeleteEntity", testCreateAndDeleteEntity),
("testCreateUpdateAndDeleteEntity", testCreateUpdateAndDeleteEntity),
("testGetEntity", testGetEntity),
("testListAllValues", testListAllValues),
("testCreateUpdateAndDeleteValue", testCreateUpdateAndDeleteValue),
("testGetValue", testGetValue),
("testListAllSynonym", testListAllSynonym),
("testListAllSynonymWithIncludeCount", testListAllSynonymWithIncludeCount),
("testListAllSynonymWithPageLimit1", testListAllSynonymWithPageLimit1),
("testCreateAndDeleteSynonym", testCreateAndDeleteSynonym),
("testGetSynonym", testGetSynonym),
("testCreateUpdateAndDeleteSynonym", testCreateUpdateAndDeleteSynonym),
// Test temporarily disabled pending resolution of server-side issue
// ("testListLogs", testListLogs),
("testMessageUnknownWorkspace", testMessageUnknownWorkspace),
("testMessageInvalidWorkspaceID", testMessageInvalidWorkspaceID),
]
}
/** Instantiate Conversation. */
func instantiateConversation() {
let username = Credentials.ConversationUsername
let password = Credentials.ConversationPassword
let version = "2017-05-26"
conversation = Conversation(username: username, password: password, version: version)
conversation.defaultHeaders["X-Watson-Learning-Opt-Out"] = "true"
conversation.defaultHeaders["X-Watson-Test"] = "true"
}
/** Fail false negatives. */
func failWithError(error: Error) {
XCTFail("Positive test failed with error: \(error)")
}
/** Fail false positives. */
func failWithResult<T>(result: T) {
XCTFail("Negative test returned a result.")
}
/** Fail false positives. */
func failWithResult() {
XCTFail("Negative test returned a result.")
}
/** Wait for expectations. */
func waitForExpectations(timeout: TimeInterval = 5.0) {
waitForExpectations(timeout: timeout) { error in
XCTAssertNil(error, "Timeout")
}
}
// MARK: - Positive Tests
func testMessage() {
let description1 = "Start a conversation."
let expectation1 = self.expectation(description: description1)
let response1 = ["Hi. It looks like a nice drive today. What would you like me to do?"]
let nodes1 = ["node_1_1467221909631"]
var context: Context?
conversation.message(workspaceID: workspaceID, failure: failWithError) {
response in
// verify input
XCTAssertNil(response.input?.text)
// verify context
XCTAssertNotNil(response.context.conversationID)
XCTAssertNotEqual(response.context.conversationID, "")
XCTAssertNotNil(response.context.system)
XCTAssertNotNil(response.context.system.additionalProperties)
XCTAssertFalse(response.context.system.additionalProperties.isEmpty)
// verify entities
XCTAssertTrue(response.entities.isEmpty)
// verify intents
XCTAssertTrue(response.intents.isEmpty)
// verify output
XCTAssertTrue(response.output.logMessages.isEmpty)
XCTAssertEqual(response.output.text, response1)
XCTAssertEqual(response.output.nodesVisited!, nodes1)
context = response.context
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Continue a conversation."
let expectation2 = self.expectation(description: description2)
let input = InputData(text: "Turn on the radio.")
let request = MessageRequest(input: input, context: context!)
let response2 = ["", "Sure thing! Which genre would you prefer? Jazz is my personal favorite.."]
let nodes2 = ["node_1_1467232431348", "node_2_1467232480480", "node_1_1467994455318"]
conversation.message(workspaceID: workspaceID, request: request, failure: failWithError) {
response in
// verify input
XCTAssertEqual(response.input?.text, input.text)
// verify context
XCTAssertEqual(response.context.conversationID, context!.conversationID)
XCTAssertNotNil(response.context.system)
XCTAssertNotNil(response.context.system.additionalProperties)
XCTAssertFalse(response.context.system.additionalProperties.isEmpty)
// verify entities
XCTAssertEqual(response.entities.count, 1)
XCTAssertEqual(response.entities[0].entity, "appliance")
XCTAssertEqual(response.entities[0].location[0], 12)
XCTAssertEqual(response.entities[0].location[1], 17)
XCTAssertEqual(response.entities[0].value, "music")
// verify intents
XCTAssertEqual(response.intents.count, 1)
XCTAssertEqual(response.intents[0].intent, "turn_on")
XCTAssert(response.intents[0].confidence >= 0.80)
XCTAssert(response.intents[0].confidence <= 1.00)
// verify output
XCTAssertTrue(response.output.logMessages.isEmpty)
XCTAssertEqual(response.output.text, response2)
XCTAssertEqual(response.output.nodesVisited!, nodes2)
expectation2.fulfill()
}
waitForExpectations()
}
func testMessageAllFields1() {
let description1 = "Start a conversation."
let expectation1 = expectation(description: description1)
var context: Context?
var entities: [RuntimeEntity]?
var intents: [RuntimeIntent]?
var output: OutputData?
conversation.message(workspaceID: workspaceID, failure: failWithError) {
response in
context = response.context
entities = response.entities
intents = response.intents
output = response.output
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Continue a conversation."
let expectation2 = expectation(description: description2)
let input2 = InputData(text: "Turn on the radio.")
let request2 = MessageRequest(input: input2, context: context, entities: entities, intents: intents, output: output)
conversation.message(workspaceID: workspaceID, request: request2, failure: failWithError) {
response in
// verify objects are non-nil
XCTAssertNotNil(entities)
XCTAssertNotNil(intents)
XCTAssertNotNil(output)
// verify intents are equal
for i in 0..<response.intents.count {
let intent1 = intents![i]
let intent2 = response.intents[i]
XCTAssertEqual(intent1.intent, intent2.intent)
XCTAssertEqual(intent1.confidence, intent2.confidence, accuracy: 10E-5)
}
// verify entities are equal
for i in 0..<response.entities.count {
let entity1 = entities![i]
let entity2 = response.entities[i]
XCTAssertEqual(entity1.entity, entity2.entity)
XCTAssertEqual(entity1.location[0], entity2.location[0])
XCTAssertEqual(entity1.location[1], entity2.location[1])
XCTAssertEqual(entity1.value, entity2.value)
}
expectation2.fulfill()
}
waitForExpectations()
}
func testMessageAllFields2() {
let description1 = "Start a conversation."
let expectation1 = expectation(description: description1)
var context: Context?
var entities: [RuntimeEntity]?
var intents: [RuntimeIntent]?
var output: OutputData?
conversation.message(workspaceID: workspaceID, failure: failWithError) {
response in
context = response.context
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Continue a conversation."
let expectation2 = expectation(description: description2)
let input2 = InputData(text: "Turn on the radio.")
let request2 = MessageRequest(input: input2, context: context, entities: entities, intents: intents, output: output)
conversation.message(workspaceID: workspaceID, request: request2, failure: failWithError) {
response in
context = response.context
entities = response.entities
intents = response.intents
output = response.output
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Continue a conversation with non-empty intents and entities."
let expectation3 = expectation(description: description3)
let input3 = InputData(text: "Rock music.")
let request3 = MessageRequest(input: input3, context: context, entities: entities, intents: intents, output: output)
conversation.message(workspaceID: workspaceID, request: request3, failure: failWithError) {
response in
// verify objects are non-nil
XCTAssertNotNil(entities)
XCTAssertNotNil(intents)
XCTAssertNotNil(output)
// verify intents are equal
for i in 0..<response.intents.count {
let intent1 = intents![i]
let intent2 = response.intents[i]
XCTAssertEqual(intent1.intent, intent2.intent)
XCTAssertEqual(intent1.confidence, intent2.confidence, accuracy: 10E-5)
}
// verify entities are equal
for i in 0..<response.entities.count {
let entity1 = entities![i]
let entity2 = response.entities[i]
XCTAssertEqual(entity1.entity, entity2.entity)
XCTAssertEqual(entity1.location[0], entity2.location[0])
XCTAssertEqual(entity1.location[1], entity2.location[1])
XCTAssertEqual(entity1.value, entity2.value)
}
expectation3.fulfill()
}
waitForExpectations()
}
func testMessageContextVariable() {
let description1 = "Start a conversation."
let expectation1 = expectation(description: description1)
var context: Context?
conversation.message(workspaceID: workspaceID, failure: failWithError) {
response in
context = response.context
context?.additionalProperties["foo"] = .string("bar")
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Continue a conversation."
let expectation2 = expectation(description: description2)
let input2 = InputData(text: "Turn on the radio.")
let request2 = MessageRequest(input: input2, context: context)
conversation.message(workspaceID: workspaceID, request: request2, failure: failWithError) {
response in
let additionalProperties = response.context.additionalProperties
guard case let .string(bar) = additionalProperties["foo"]! else {
XCTFail("Additional property \"foo\" expected but not present.")
return
}
guard case let .boolean(reprompt) = additionalProperties["reprompt"]! else {
XCTFail("Additional property \"reprompt\" expected but not present.")
return
}
XCTAssertEqual(bar, "bar")
XCTAssertTrue(reprompt)
expectation2.fulfill()
}
waitForExpectations()
}
// MARK: - Workspaces
func testListAllWorkspaces() {
let description = "List all workspaces."
let expectation = self.expectation(description: description)
conversation.listWorkspaces(failure: failWithError) { workspaceResponse in
for workspace in workspaceResponse.workspaces {
XCTAssertNotNil(workspace.name)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.language)
XCTAssertNotNil(workspace.workspaceID)
}
XCTAssertNotNil(workspaceResponse.pagination.refreshUrl)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllWorkspacesWithPageLimit1() {
let description = "List all workspaces with page limit specified as 1."
let expectation = self.expectation(description: description)
conversation.listWorkspaces(pageLimit: 1, failure: failWithError) { workspaceResponse in
XCTAssertEqual(workspaceResponse.workspaces.count, 1)
for workspace in workspaceResponse.workspaces {
XCTAssertNotNil(workspace.name)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.language)
XCTAssertNotNil(workspace.workspaceID)
}
XCTAssertNotNil(workspaceResponse.pagination.refreshUrl)
XCTAssertNotNil(workspaceResponse.pagination.nextUrl)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllWorkspacesWithIncludeCount() {
let description = "List all workspaces with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listWorkspaces(includeCount: true, failure: failWithError) { workspaceResponse in
for workspace in workspaceResponse.workspaces {
XCTAssertNotNil(workspace.name)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.language)
XCTAssertNotNil(workspace.workspaceID)
}
XCTAssertNotNil(workspaceResponse.pagination.refreshUrl)
XCTAssertNotNil(workspaceResponse.pagination.total)
XCTAssertNotNil(workspaceResponse.pagination.matched)
XCTAssertEqual(workspaceResponse.pagination.total, workspaceResponse.workspaces.count)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteWorkspace() {
var newWorkspace: String?
let description1 = "Create a workspace."
let expectation1 = expectation(description: description1)
let workspaceName = "swift-sdk-test-workspace"
let workspaceDescription = "temporary workspace for the swift sdk unit tests"
let workspaceLanguage = "en"
let workspaceMetadata: [String: JSON] = ["testKey": .string("testValue")]
let intentExample = CreateExample(text: "This is an example of Intent1")
let workspaceIntent = CreateIntent(intent: "Intent1", description: "description of Intent1", examples: [intentExample])
let entityValue = CreateValue(value: "Entity1Value", metadata: workspaceMetadata, synonyms: ["Synonym1", "Synonym2"])
let workspaceEntity = CreateEntity(entity: "Entity1", description: "description of Entity1", values: [entityValue])
let workspaceDialogNode = CreateDialogNode(dialogNode: "DialogNode1", description: "description of DialogNode1")
let workspaceCounterexample = CreateCounterexample(text: "This is a counterexample")
let createWorkspaceBody = CreateWorkspace(name: workspaceName, description: workspaceDescription, language: workspaceLanguage, intents: [workspaceIntent], entities: [workspaceEntity], dialogNodes: [workspaceDialogNode], counterexamples: [workspaceCounterexample], metadata: workspaceMetadata)
conversation.createWorkspace(properties: createWorkspaceBody, failure: failWithError) { workspace in
XCTAssertEqual(workspace.name, workspaceName)
XCTAssertEqual(workspace.description, workspaceDescription)
XCTAssertEqual(workspace.language, workspaceLanguage)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.workspaceID)
newWorkspace = workspace.workspaceID
expectation1.fulfill()
}
waitForExpectations(timeout: 10.0)
guard let newWorkspaceID = newWorkspace else {
XCTFail("Failed to get the ID of the newly created workspace.")
return
}
let description2 = "Get the newly created workspace."
let expectation2 = expectation(description: description2)
conversation.getWorkspace(workspaceID: newWorkspaceID, export: true, failure: failWithError) { workspace in
XCTAssertEqual(workspace.name, workspaceName)
XCTAssertEqual(workspace.description, workspaceDescription)
XCTAssertEqual(workspace.language, workspaceLanguage)
XCTAssertNotNil(workspace.metadata)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertEqual(workspace.workspaceID, newWorkspaceID)
XCTAssertNotNil(workspace.status)
XCTAssertNotNil(workspace.intents)
for intent in workspace.intents! {
XCTAssertEqual(intent.intentName, workspaceIntent.intent)
XCTAssertEqual(intent.description, workspaceIntent.description)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNotNil(intent.examples)
for example in intent.examples! {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertEqual(example.exampleText, intentExample.text)
}
}
XCTAssertNotNil(workspace.counterexamples)
for counterexample in workspace.counterexamples! {
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertEqual(counterexample.text, workspaceCounterexample.text)
}
expectation2.fulfill()
}
waitForExpectations(timeout: 10.0)
let description3 = "Delete the newly created workspace."
let expectation3 = expectation(description: description3)
conversation.deleteWorkspace(workspaceID: newWorkspaceID, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
func testListSingleWorkspace() {
let description = "List details of a single workspace."
let expectation = self.expectation(description: description)
conversation.getWorkspace(workspaceID: workspaceID, export: false, failure: failWithError) { workspace in
XCTAssertNotNil(workspace.name)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.language)
XCTAssertNotNil(workspace.metadata)
XCTAssertNotNil(workspace.workspaceID)
XCTAssertNotNil(workspace.status)
XCTAssertNil(workspace.intents)
XCTAssertNil(workspace.entities)
XCTAssertNil(workspace.counterexamples)
XCTAssertNil(workspace.dialogNodes)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteWorkspace() {
var newWorkspace: String?
let description1 = "Create a workspace."
let expectation1 = expectation(description: description1)
let workspaceName = "swift-sdk-test-workspace"
let workspaceDescription = "temporary workspace for the swift sdk unit tests"
let workspaceLanguage = "en"
let createWorkspaceBody = CreateWorkspace(name: workspaceName, description: workspaceDescription, language: workspaceLanguage)
conversation.createWorkspace(properties: createWorkspaceBody, failure: failWithError) { workspace in
XCTAssertEqual(workspace.name, workspaceName)
XCTAssertEqual(workspace.description, workspaceDescription)
XCTAssertEqual(workspace.language, workspaceLanguage)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.workspaceID)
newWorkspace = workspace.workspaceID
expectation1.fulfill()
}
waitForExpectations()
guard let newWorkspaceID = newWorkspace else {
XCTFail("Failed to get the ID of the newly created workspace.")
return
}
let description2 = "Update the newly created workspace."
let expectation2 = expectation(description: description2)
let newWorkspaceName = "swift-sdk-test-workspace-2"
let newWorkspaceDescription = "new description for the temporary workspace"
let updateWorkspaceBody = UpdateWorkspace(name: newWorkspaceName, description: newWorkspaceDescription)
conversation.updateWorkspace(workspaceID: newWorkspaceID, properties: updateWorkspaceBody, failure: failWithError) { workspace in
XCTAssertEqual(workspace.name, newWorkspaceName)
XCTAssertEqual(workspace.description, newWorkspaceDescription)
XCTAssertEqual(workspace.language, workspaceLanguage)
XCTAssertNotNil(workspace.created)
XCTAssertNotNil(workspace.updated)
XCTAssertNotNil(workspace.workspaceID)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete the newly created workspace."
let expectation3 = expectation(description: description3)
conversation.deleteWorkspace(workspaceID: newWorkspaceID, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Intents
func testListAllIntents() {
let description = "List all the intents in a workspace."
let expectation = self.expectation(description: description)
conversation.listIntents(workspaceID: workspaceID, failure: failWithError) { intents in
for intent in intents.intents {
XCTAssertNotNil(intent.intentName)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNil(intent.examples)
}
XCTAssertNotNil(intents.pagination.refreshUrl)
XCTAssertNil(intents.pagination.nextUrl)
XCTAssertNil(intents.pagination.total)
XCTAssertNil(intents.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllIntentsWithIncludeCount() {
let description = "List all the intents in a workspace with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listIntents(workspaceID: workspaceID, includeCount: true, failure: failWithError) { intents in
for intent in intents.intents {
XCTAssertNotNil(intent.intentName)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNil(intent.examples)
}
XCTAssertNotNil(intents.pagination.refreshUrl)
XCTAssertNil(intents.pagination.nextUrl)
XCTAssertNotNil(intents.pagination.total)
XCTAssertNotNil(intents.pagination.matched)
XCTAssertEqual(intents.pagination.total, intents.intents.count)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllIntentsWithPageLimit1() {
let description = "List all the intents in a workspace with pageLimit specified as 1."
let expectation = self.expectation(description: description)
conversation.listIntents(workspaceID: workspaceID, pageLimit: 1, failure: failWithError) { intents in
XCTAssertEqual(intents.intents.count, 1)
for intent in intents.intents {
XCTAssertNotNil(intent.intentName)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNil(intent.examples)
}
XCTAssertNotNil(intents.pagination.refreshUrl)
XCTAssertNotNil(intents.pagination.nextUrl)
XCTAssertNil(intents.pagination.total)
XCTAssertNil(intents.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllIntentsWithExport() {
let description = "List all the intents in a workspace with export as true."
let expectation = self.expectation(description: description)
conversation.listIntents(workspaceID: workspaceID, export: true, failure: failWithError) { intents in
for intent in intents.intents {
XCTAssertNotNil(intent.intentName)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNotNil(intent.examples)
for example in intent.examples! {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertNotNil(example.exampleText)
}
}
XCTAssertNotNil(intents.pagination.refreshUrl)
XCTAssertNil(intents.pagination.nextUrl)
XCTAssertNil(intents.pagination.total)
XCTAssertNil(intents.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteIntent() {
let description = "Create a new intent."
let expectation = self.expectation(description: description)
let newIntentName = "swift-sdk-test-intent" + UUID().uuidString
let newIntentDescription = "description for \(newIntentName)"
let example1 = CreateExample(text: "example 1 for \(newIntentName)")
let example2 = CreateExample(text: "example 2 for \(newIntentName)")
conversation.createIntent(workspaceID: workspaceID, intent: newIntentName, description: newIntentDescription, examples: [example1, example2], failure: failWithError) { intent in
XCTAssertEqual(intent.intentName, newIntentName)
XCTAssertEqual(intent.description, newIntentDescription)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Delete the new intent."
let expectation2 = self.expectation(description: description2)
conversation.deleteIntent(workspaceID: workspaceID, intent: newIntentName, failure: failWithError) {
expectation2.fulfill()
}
waitForExpectations()
}
func testGetIntentWithExport() {
let description = "Get details of a specific intent."
let expectation = self.expectation(description: description)
conversation.getIntent(workspaceID: workspaceID, intent: "weather", export: true, failure: failWithError) { intent in
XCTAssertNotNil(intent.intentName)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
XCTAssertNotNil(intent.examples)
for example in intent.examples! {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertNotNil(example.exampleText)
}
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteIntent() {
let description = "Create a new intent."
let expectation = self.expectation(description: description)
let newIntentName = "swift-sdk-test-intent" + UUID().uuidString
let newIntentDescription = "description for \(newIntentName)"
let example1 = CreateExample(text: "example 1 for \(newIntentName)")
let example2 = CreateExample(text: "example 2 for \(newIntentName)")
conversation.createIntent(workspaceID: workspaceID, intent: newIntentName, description: newIntentDescription, examples: [example1, example2], failure: failWithError) { intent in
XCTAssertEqual(intent.intentName, newIntentName)
XCTAssertEqual(intent.description, newIntentDescription)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Update the new intent."
let expectation2 = self.expectation(description: description2)
let updatedIntentName = "updated-name-for-\(newIntentName)"
let updatedIntentDescription = "updated-description-for-\(newIntentName)"
let updatedExample1 = CreateExample(text: "updated example for \(newIntentName)")
conversation.updateIntent(workspaceID: workspaceID, intent: newIntentName, newIntent: updatedIntentName, newDescription: updatedIntentDescription, newExamples: [updatedExample1], failure: failWithError) { intent in
XCTAssertEqual(intent.intentName, updatedIntentName)
XCTAssertEqual(intent.description, updatedIntentDescription)
XCTAssertNotNil(intent.created)
XCTAssertNotNil(intent.updated)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete the new intent."
let expectation3 = self.expectation(description: description3)
conversation.deleteIntent(workspaceID: workspaceID, intent: updatedIntentName, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Examples
func testListAllExamples() {
let description = "List all the examples of an intent."
let expectation = self.expectation(description: description)
conversation.listExamples(workspaceID: workspaceID, intent: "weather", failure: failWithError) { examples in
for example in examples.examples {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertNotNil(example.exampleText)
}
XCTAssertNotNil(examples.pagination.refreshUrl)
XCTAssertNil(examples.pagination.total)
XCTAssertNil(examples.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllExamplesWithIncludeCount() {
let description = "List all the examples for an intent with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listExamples(workspaceID: workspaceID, intent: "weather", includeCount: true, failure: failWithError) { examples in
for example in examples.examples {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertNotNil(example.exampleText)
}
XCTAssertNotNil(examples.pagination.refreshUrl)
XCTAssertNotNil(examples.pagination.total)
XCTAssertNotNil(examples.pagination.matched)
XCTAssertEqual(examples.pagination.total, examples.examples.count)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllExamplesWithPageLimit1() {
let description = "List all the examples for an intent with pageLimit specified as 1."
let expectation = self.expectation(description: description)
conversation.listExamples(workspaceID: workspaceID, intent: "weather", pageLimit: 1, failure: failWithError) { examples in
XCTAssertEqual(examples.examples.count, 1)
for example in examples.examples {
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertNotNil(example.exampleText)
}
XCTAssertNotNil(examples.pagination.refreshUrl)
XCTAssertNotNil(examples.pagination.nextUrl)
XCTAssertNil(examples.pagination.total)
XCTAssertNil(examples.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteExample() {
let description = "Create a new example."
let expectation = self.expectation(description: description)
let newExample = "swift-sdk-test-example" + UUID().uuidString
conversation.createExample(workspaceID: workspaceID, intent: "weather", text: newExample, failure: failWithError) { example in
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertEqual(example.exampleText, newExample)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Delete the new example."
let expectation2 = self.expectation(description: description2)
conversation.deleteExample(workspaceID: workspaceID, intent: "weather", text: newExample, failure: failWithError) {
expectation2.fulfill()
}
waitForExpectations()
}
func testGetExample() {
let description = "Get details of a specific example."
let expectation = self.expectation(description: description)
let exampleText = "tell me the weather"
conversation.getExample(workspaceID: workspaceID, intent: "weather", text: exampleText, failure: failWithError) { example in
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertEqual(example.exampleText, exampleText)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteExample() {
let description = "Create a new example."
let expectation = self.expectation(description: description)
let newExample = "swift-sdk-test-example" + UUID().uuidString
conversation.createExample(workspaceID: workspaceID, intent: "weather", text: newExample, failure: failWithError) { example in
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertEqual(example.exampleText, newExample)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Update the new example."
let expectation2 = self.expectation(description: description2)
let updatedText = "updated-" + newExample
conversation.updateExample(workspaceID: workspaceID, intent: "weather", text: newExample, newText: updatedText, failure: failWithError) { example in
XCTAssertNotNil(example.created)
XCTAssertNotNil(example.updated)
XCTAssertEqual(example.exampleText, updatedText)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete the new example."
let expectation3 = self.expectation(description: description3)
conversation.deleteExample(workspaceID: workspaceID, intent: "weather", text: updatedText, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Counterexamples
func testListAllCounterexamples() {
let description = "List all the counterexamples of a workspace."
let expectation = self.expectation(description: description)
conversation.listCounterexamples(workspaceID: workspaceID, failure: failWithError) { counterexamples in
for counterexample in counterexamples.counterexamples {
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertNotNil(counterexample.text)
}
XCTAssertNotNil(counterexamples.pagination.refreshUrl)
XCTAssertNil(counterexamples.pagination.nextUrl)
XCTAssertNil(counterexamples.pagination.total)
XCTAssertNil(counterexamples.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllCounterexamplesWithIncludeCount() {
let description = "List all the counterexamples of a workspace with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listCounterexamples(workspaceID: workspaceID, includeCount: true, failure: failWithError) { counterexamples in
for counterexample in counterexamples.counterexamples {
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertNotNil(counterexample.text)
}
XCTAssertNotNil(counterexamples.pagination.refreshUrl)
XCTAssertNil(counterexamples.pagination.nextUrl)
XCTAssertNotNil(counterexamples.pagination.total)
XCTAssertNotNil(counterexamples.pagination.matched)
XCTAssertEqual(counterexamples.pagination.total, counterexamples.counterexamples.count)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllCounterexamplesWithPageLimit1() {
let description = "List all the counterexamples of a workspace with pageLimit specified as 1."
let expectation = self.expectation(description: description)
conversation.listCounterexamples(workspaceID: workspaceID, pageLimit: 1, failure: failWithError) { counterexamples in
for counterexample in counterexamples.counterexamples {
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertNotNil(counterexample.text)
}
XCTAssertNotNil(counterexamples.pagination.refreshUrl)
XCTAssertNil(counterexamples.pagination.total)
XCTAssertNil(counterexamples.pagination.matched)
XCTAssertEqual(counterexamples.counterexamples.count, 1)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteCounterexample() {
let description = "Create a new counterexample."
let expectation = self.expectation(description: description)
let newExample = "swift-sdk-test-counterexample" + UUID().uuidString
conversation.createCounterexample(workspaceID: workspaceID, text: newExample, failure: failWithError) { counterexample in
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertNotNil(counterexample.text)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Delete the new counterexample."
let expectation2 = self.expectation(description: description2)
conversation.deleteCounterexample(workspaceID: workspaceID, text: newExample, failure: failWithError) {
expectation2.fulfill()
}
waitForExpectations()
}
func testGetCounterexample() {
let description = "Get details of a specific counterexample."
let expectation = self.expectation(description: description)
let exampleText = "I want financial advice today."
conversation.getCounterexample(workspaceID: workspaceID, text: exampleText, failure: failWithError) { counterexample in
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertEqual(counterexample.text, exampleText)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteCounterexample() {
let description = "Create a new counterexample."
let expectation = self.expectation(description: description)
let newExample = "swift-sdk-test-counterexample" + UUID().uuidString
conversation.createCounterexample(workspaceID: workspaceID, text: newExample, failure: failWithError) { counterexample in
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertEqual(counterexample.text, newExample)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Update the new example."
let expectation2 = self.expectation(description: description2)
let updatedText = "updated-"+newExample
conversation.updateCounterexample(workspaceID: workspaceID, text: newExample, newText: updatedText, failure: failWithError) { counterexample in
XCTAssertNotNil(counterexample.created)
XCTAssertNotNil(counterexample.updated)
XCTAssertEqual(counterexample.text, updatedText)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete the new counterexample."
let expectation3 = self.expectation(description: description3)
conversation.deleteCounterexample(workspaceID: workspaceID, text: updatedText, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Entities
func testListAllEntities() {
let description = "List all entities"
let expectation = self.expectation(description: description)
conversation.listEntities(workspaceID: workspaceID, failure: failWithError){entities in
for entity in entities.entities {
XCTAssertNotNil(entity.entityName)
XCTAssertNotNil(entity.created)
XCTAssertNotNil(entity.updated)
}
XCTAssert(entities.entities.count > 0)
XCTAssertNotNil(entities.pagination.refreshUrl)
XCTAssertNil(entities.pagination.nextUrl)
XCTAssertNil(entities.pagination.total)
XCTAssertNil(entities.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllEntitiesWithIncludeCount() {
let description = "List all the entities in a workspace with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listEntities(workspaceID: workspaceID, includeCount: true, failure: failWithError) { entities in
for entity in entities.entities {
XCTAssertNotNil(entity.entityName)
XCTAssertNotNil(entity.created)
XCTAssertNotNil(entity.updated)
}
XCTAssertNotNil(entities.pagination.refreshUrl)
XCTAssertNil(entities.pagination.nextUrl)
XCTAssertNotNil(entities.pagination.total)
XCTAssertNotNil(entities.pagination.matched)
XCTAssertEqual(entities.pagination.total, entities.entities.count)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllEntitiesWithPageLimit1() {
let description = "List all entities with page limit 1"
let expectation = self.expectation(description: description)
conversation.listEntities(workspaceID: workspaceID, pageLimit: 1, failure: failWithError){entities in
for entity in entities.entities {
XCTAssertNotNil(entity.entityName)
XCTAssertNotNil(entity.created)
XCTAssertNotNil(entity.updated)
}
XCTAssertNotNil(entities.pagination.refreshUrl)
XCTAssertNotNil(entities.pagination.nextUrl)
XCTAssertNil(entities.pagination.total)
XCTAssertNil(entities.pagination.matched)
XCTAssert(entities.entities.count > 0)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllEntitiesWithExport() {
let description = "List all the entities in a workspace with export as true."
let expectation = self.expectation(description: description)
conversation.listEntities(workspaceID: workspaceID, export: true, failure: failWithError) { entities in
for entity in entities.entities {
XCTAssertNotNil(entity.entityName)
XCTAssertNotNil(entity.created)
XCTAssertNotNil(entity.updated)
}
XCTAssertNotNil(entities.entities)
XCTAssertNil(entities.pagination.total)
XCTAssertNil(entities.pagination.matched)
XCTAssertNil(entities.pagination.nextUrl)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteEntity(){
let description = "Create an Entity"
let expectation = self.expectation(description: description)
let entityName = "swift-sdk-test-entity" + UUID().uuidString
let entityDescription = "This is a test entity"
let entity = CreateEntity.init(entity: entityName, description: entityDescription)
conversation.createEntity(workspaceID: workspaceID, properties: entity, failure: failWithError){ entityResponse in
XCTAssertEqual(entityResponse.entityName, entityName)
XCTAssertEqual(entityResponse.description, entityDescription)
XCTAssertNotNil(entityResponse.created)
XCTAssertNotNil(entityResponse.updated)
expectation.fulfill()
}
waitForExpectations()
let descriptionTwo = "Delete the entity"
let expectationTwo = self.expectation(description: descriptionTwo)
conversation.deleteEntity(workspaceID: workspaceID, entity: entity.entity) {
expectationTwo.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteEntity(){
let description = "Create an Entity"
let expectation = self.expectation(description: description)
let entityName = "swift-sdk-test-entity" + UUID().uuidString
let entityDescription = "This is a test entity"
let entity = CreateEntity.init(entity: entityName, description: entityDescription)
conversation.createEntity(workspaceID: workspaceID, properties: entity, failure: failWithError){ entityResponse in
XCTAssertEqual(entityResponse.entityName, entityName)
XCTAssertEqual(entityResponse.description, entityDescription)
XCTAssertNotNil(entityResponse.created)
XCTAssertNotNil(entityResponse.updated)
expectation.fulfill()
}
waitForExpectations()
let descriptionTwo = "Update the entity"
let expectationTwo = self.expectation(description: descriptionTwo)
let updatedEntityName = "up-" + entityName
let updatedEntityDescription = "This is a new description for a test entity"
let updatedEntity = UpdateEntity.init(entity: updatedEntityName, description: updatedEntityDescription)
conversation.updateEntity(workspaceID: workspaceID, entity: entityName, properties: updatedEntity, failure: failWithError){ entityResponse in
XCTAssertEqual(entityResponse.entityName, updatedEntityName)
XCTAssertEqual(entityResponse.description, updatedEntityDescription)
XCTAssertNotNil(entityResponse.created)
XCTAssertNotNil(entityResponse.updated)
expectationTwo.fulfill()
}
waitForExpectations()
let descriptionFour = "Delete the entity"
let expectationFour = self.expectation(description: descriptionFour)
conversation.deleteEntity(workspaceID: workspaceID, entity: updatedEntityName, failure: failWithError) {
expectationFour.fulfill()
}
waitForExpectations()
}
func testGetEntity() {
let description = "Get details of a specific entity."
let expectation = self.expectation(description: description)
conversation.listEntities(workspaceID: workspaceID, failure: failWithError) {entityCollection in
XCTAssert(entityCollection.entities.count > 0)
let entity = entityCollection.entities[0]
self.conversation.getEntity(workspaceID: self.workspaceID, entity: entity.entityName, export: true, failure: self.failWithError) { entityExport in
XCTAssertEqual(entityExport.entityName, entity.entityName)
XCTAssertEqual(entityExport.description, entity.description)
XCTAssertNotNil(entityExport.created)
XCTAssertNotNil(entityExport.updated)
expectation.fulfill()
}
}
waitForExpectations()
}
// MARK: - Values
func testListAllValues() {
let description = "List all the values for an entity."
let expectation = self.expectation(description: description)
let entityName = "appliance"
conversation.listValues(workspaceID: workspaceID, entity: entityName, failure: failWithError) { valueCollection in
for value in valueCollection.values {
XCTAssertNotNil(value.valueText)
XCTAssertNotNil(value.created)
XCTAssertNotNil(value.updated)
}
XCTAssertNotNil(valueCollection.pagination.refreshUrl)
XCTAssertNil(valueCollection.pagination.total)
XCTAssertNil(valueCollection.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteValue(){
let description = "Create a value for an entity"
let expectation = self.expectation(description: description)
let entityName = "appliance"
let valueName = "swift-sdk-test-value" + UUID().uuidString
let value = CreateValue(value: valueName)
conversation.createValue(workspaceID: workspaceID, entity: entityName, properties: value, failure: failWithError) { value in
XCTAssertEqual(value.valueText, valueName)
XCTAssertNotNil(value.created)
XCTAssertNotNil(value.updated)
expectation.fulfill()
}
waitForExpectations()
let descriptionTwo = "Update the value"
let expectationTwo = self.expectation(description: descriptionTwo)
let updatedValueName = "up-" + valueName
let updatedValue = UpdateValue(value: updatedValueName, metadata: ["oldname": .string(valueName)])
conversation.updateValue(workspaceID: workspaceID, entity: entityName, value: valueName, properties: updatedValue, failure: failWithError) { value in
XCTAssertEqual(value.valueText, updatedValueName)
XCTAssertNotNil(value.created)
XCTAssertNotNil(value.updated)
XCTAssertNotNil(value.metadata)
expectationTwo.fulfill()
}
waitForExpectations()
let descriptionThree = "Delete the updated value"
let expectationThree = self.expectation(description: descriptionThree)
conversation.deleteValue(workspaceID: workspaceID, entity: entityName, value: updatedValueName, failure: failWithError) {
expectationThree.fulfill()
}
waitForExpectations()
}
func testGetValue() {
let description = "Get a value for an entity."
let expectation = self.expectation(description: description)
let entityName = "appliance"
conversation.listValues(workspaceID: workspaceID, entity: entityName, failure: failWithError) { valueCollection in
XCTAssert(valueCollection.values.count > 0)
let value = valueCollection.values[0]
self.conversation.getValue(workspaceID: self.workspaceID, entity: entityName, value: value.valueText, export: true, failure: self.failWithError) { valueExport in
XCTAssertEqual(valueExport.valueText, value.valueText)
XCTAssertNotNil(valueExport.created)
XCTAssertNotNil(valueExport.updated)
expectation.fulfill()
}
}
waitForExpectations()
}
// MARK: - Synonyms
func testListAllSynonym() {
let description = "List all the synonyms for an entity and value."
let expectation = self.expectation(description: description)
conversation.listSynonyms(workspaceID: workspaceID, entity: "appliance", value: "lights", failure: failWithError) { synonyms in
for synonym in synonyms.synonyms {
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertNotNil(synonym.synonymText)
}
XCTAssertNotNil(synonyms.pagination.refreshUrl)
XCTAssertNil(synonyms.pagination.total)
XCTAssertNil(synonyms.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllSynonymWithIncludeCount() {
let description = "List all the synonyms for an entity and value with includeCount as true."
let expectation = self.expectation(description: description)
conversation.listSynonyms(workspaceID: workspaceID, entity: "appliance", value: "lights", includeCount: true, failure: failWithError) { synonyms in
for synonym in synonyms.synonyms {
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertNotNil(synonym.synonymText)
}
XCTAssertNotNil(synonyms.pagination.refreshUrl)
XCTAssertNotNil(synonyms.pagination.total)
XCTAssertNotNil(synonyms.pagination.matched)
XCTAssertEqual(synonyms.pagination.total, synonyms.synonyms.count)
expectation.fulfill()
}
waitForExpectations()
}
func testListAllSynonymWithPageLimit1() {
let description = "List all the synonyms for an entity and value with pageLimit specified as 1."
let expectation = self.expectation(description: description)
conversation.listSynonyms(workspaceID: workspaceID, entity: "appliance", value: "lights", pageLimit: 1, failure: failWithError) { synonyms in
XCTAssertEqual(synonyms.synonyms.count, 1)
for synonym in synonyms.synonyms {
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertNotNil(synonym.synonymText)
}
XCTAssertNotNil(synonyms.pagination.refreshUrl)
XCTAssertNotNil(synonyms.pagination.nextUrl)
XCTAssertNil(synonyms.pagination.total)
XCTAssertNil(synonyms.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteSynonym() {
let description = "Create a new synonym."
let expectation = self.expectation(description: description)
let newSynonym = "swift-sdk-test-synonym" + UUID().uuidString
conversation.createSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: newSynonym, failure: failWithError) { synonym in
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertEqual(synonym.synonymText, newSynonym)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Delete the new synonym."
let expectation2 = self.expectation(description: description2)
conversation.deleteSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: newSynonym, failure: failWithError) {
expectation2.fulfill()
}
waitForExpectations()
}
func testGetSynonym() {
let description = "Get details of a specific synonym."
let expectation = self.expectation(description: description)
let synonymName = "headlight"
conversation.getSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: synonymName, failure: failWithError) { synonym in
XCTAssertEqual(synonym.synonymText, synonymName)
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteSynonym() {
let description = "Create a new synonym."
let expectation = self.expectation(description: description)
let newSynonym = "swift-sdk-test-synonym" + UUID().uuidString
conversation.createSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: newSynonym, failure: failWithError) { synonym in
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertEqual(synonym.synonymText, newSynonym)
expectation.fulfill()
}
waitForExpectations()
let description2 = "Update the new synonym."
let expectation2 = self.expectation(description: description2)
let updatedSynonym = "new-" + newSynonym
conversation.updateSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: newSynonym, newSynonym: updatedSynonym, failure: failWithError){ synonym in
XCTAssertNotNil(synonym.created)
XCTAssertNotNil(synonym.updated)
XCTAssertEqual(synonym.synonymText, updatedSynonym)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete the new synonym."
let expectation3 = self.expectation(description: description3)
conversation.deleteSynonym(workspaceID: workspaceID, entity: "appliance", value: "lights", synonym: updatedSynonym, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Dialog Nodes
func testListAllDialogNodes() {
let description = "List all dialog nodes"
let expectation = self.expectation(description: description)
conversation.listDialogNodes(workspaceID: workspaceID, failure: failWithError) { nodes in
for node in nodes.dialogNodes {
XCTAssertNotNil(node.dialogNodeID)
}
XCTAssertGreaterThan(nodes.dialogNodes.count, 0)
XCTAssertNotNil(nodes.pagination.refreshUrl)
XCTAssertNil(nodes.pagination.nextUrl)
XCTAssertNil(nodes.pagination.total)
XCTAssertNil(nodes.pagination.matched)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateAndDeleteDialogNode() {
let description1 = "Create a dialog node."
let expectation1 = self.expectation(description: description1)
let dialogNode = CreateDialogNode(
dialogNode: "YesYouCan",
description: "Reply affirmatively",
conditions: "#order_pizza",
parent: nil,
previousSibling: nil,
output: [
"text": .object([
"selection_policy": .string("random"),
"values": .array([.string("Yes you can!"), .string("Of course!")]),
]),
],
context: nil,
metadata: ["swift-sdk-test": .boolean(true)],
nextStep: nil,
actions: nil,
title: "YesYouCan",
nodeType: nil,
eventName: nil,
variable: nil)
conversation.createDialogNode(workspaceID: workspaceID, properties: dialogNode, failure: failWithError) {
node in
XCTAssertEqual(dialogNode.dialogNode, node.dialogNodeID)
XCTAssertEqual(dialogNode.description, node.description)
XCTAssertEqual(dialogNode.conditions, node.conditions)
XCTAssertNil(node.parent)
XCTAssertNil(node.previousSibling)
XCTAssertEqual(dialogNode.output!, node.output!)
XCTAssertNil(node.context)
XCTAssertEqual(dialogNode.metadata!, node.metadata!)
XCTAssertNil(node.nextStep)
XCTAssertNil(node.actions)
XCTAssertEqual(dialogNode.title!, node.title!)
//XCTAssertNil(node.nodeType)
XCTAssertNil(node.eventName)
XCTAssertNil(node.variable)
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Delete a dialog node"
let expectation2 = self.expectation(description: description2)
conversation.deleteDialogNode(workspaceID: workspaceID, dialogNode: dialogNode.dialogNode, failure: failWithError) {
expectation2.fulfill()
}
waitForExpectations()
}
func testCreateUpdateAndDeleteDialogNode() {
let description1 = "Create a dialog node."
let expectation1 = self.expectation(description: description1)
let dialogNode = CreateDialogNode(dialogNode: "test-node")
conversation.createDialogNode(workspaceID: workspaceID, properties: dialogNode, failure: failWithError) {
node in
XCTAssertEqual(dialogNode.dialogNode, node.dialogNodeID)
expectation1.fulfill()
}
waitForExpectations()
let description2 = "Update a dialog node."
let expectation2 = self.expectation(description: description2)
let updatedNode = UpdateDialogNode(dialogNode: "test-node-updated")
conversation.updateDialogNode(workspaceID: workspaceID, dialogNode: "test-node", properties: updatedNode, failure: failWithError) {
node in
XCTAssertEqual(updatedNode.dialogNode, node.dialogNodeID)
expectation2.fulfill()
}
waitForExpectations()
let description3 = "Delete a dialog node."
let expectation3 = self.expectation(description: description3)
conversation.deleteDialogNode(workspaceID: workspaceID, dialogNode: updatedNode.dialogNode, failure: failWithError) {
expectation3.fulfill()
}
waitForExpectations()
}
func testGetDialogNode() {
let description = "Get details of a specific dialog node."
let expectation = self.expectation(description: description)
conversation.listDialogNodes(workspaceID: workspaceID, failure: failWithError) { nodes in
XCTAssertGreaterThan(nodes.dialogNodes.count, 0)
let dialogNode = nodes.dialogNodes.first!
self.conversation.getDialogNode(
workspaceID: self.workspaceID,
dialogNode: dialogNode.dialogNodeID,
failure: self.failWithError) {
node in
XCTAssertEqual(dialogNode.dialogNodeID, node.dialogNodeID)
expectation.fulfill()
}
}
waitForExpectations()
}
// MARK: - Logs
func testListLogs() {
let description = "List the logs from the sdk"
let expectation = self.expectation(description: description)
conversation.listLogs(workspaceID: workspaceID, failure: failWithError) { logCollection in
XCTAssert(logCollection.logs.count > 0)
expectation.fulfill()
}
waitForExpectations()
}
// MARK: - Negative Tests
func testMessageUnknownWorkspace() {
let description = "Start a conversation with an invalid workspace."
let expectation = self.expectation(description: description)
let workspaceID = "this-id-is-unknown"
let failure = { (error: Error) in
// The following check fails on Linux with Swift 3.1.1 and earlier, but has been fixed in later releases.
XCTAssert(error.localizedDescription.contains("not a valid GUID"))
expectation.fulfill()
}
conversation.message(workspaceID: workspaceID, failure: failure, success: failWithResult)
waitForExpectations()
}
func testMessageInvalidWorkspaceID() {
let description = "Start a conversation with an invalid workspace."
let expectation = self.expectation(description: description)
let workspaceID = "this id is invalid" // workspace id with spaces should gracefully return error
let failure = { (error: Error) in
// The following check fails on Linux with Swift 3.1.1 and earlier, but has been fixed in later releases.
XCTAssert(error.localizedDescription.contains("not a valid GUID"))
expectation.fulfill()
}
conversation.message(workspaceID: workspaceID, failure: failure, success: failWithResult)
waitForExpectations()
}
}
| 44.136159 | 300 | 0.664537 |
91a97dca7bc10bbb14f458c4a3c4530b682e42ed | 988 | //
// AppDelegate.swift
// MyWayPizza
//
// Created by Egzon Pllana on 18.10.21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Initialization of Dependency Injection
configure(dependency: AppDependency())
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
| 31.870968 | 179 | 0.736842 |
5dc32136bcf829a0a045234ad6b4add3447dca41 | 1,747 |
import UIKit
public extension PlayerVC {
//MARK: current track + Plist
var currentTrackName: String {
return PlistManager.trackName(currentTrackIndex)
}
var currentArtistName: String {
return PlistManager.artist(currentTrackIndex)
}
var currentAlbum: String {
return PlistManager.album(currentTrackIndex)
}
var currentArtworkName: String {
return PlistManager.artworkName(currentTrackIndex)
}
var currentArtworkImage: UIImage {
return UIImage(named: currentArtworkName)!
}
var currentTrackURL: URL {
return getTrackURL(named:currentTrackName)
}
var currentTrackLength: Double {
return getTrackDuration(audioFileURL: currentTrackURL)
}
//MARK: displayed track + Plist
var displayedTrackName: String {
return PlistManager.trackName(displayedTrackIndex)
}
var displayedArtistName: String {
return PlistManager.artist(displayedTrackIndex)
}
var displayedAlbum: String {
return PlistManager.album(displayedTrackIndex)
}
var displayedArtworkName: String {
return PlistManager.artworkName(displayedTrackIndex)
}
var displayedArtworkImage: UIImage {
return UIImage(named: displayedArtworkName)!
}
var displayedTrackURL: URL {
return getTrackURL(named: displayedTrackName)
}
var displayedTrackLength: Double {
return getTrackDuration(audioFileURL: displayedTrackURL)
}
private func getTrackURL(named trackName: String,
filetype: String = "mp3") -> URL {
return URL(fileURLWithPath: Bundle.main.path(forResource: trackName, ofType: filetype)!)
}
}
| 28.177419 | 96 | 0.675444 |
8981e517b45eb750463033b78e0632d85eef5415 | 3,063 | //
// MIT License
//
// AsynchronousOperation.swift
//
// Copyright (c) 2016 Devin McKaskle
//
// 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
open class AsynchronousOperation: Operation {
// MARK: - Enum
fileprivate enum State {
case initial, executing, finished
var key: String {
switch self {
case .initial: return ""
case .executing: return "isExecuting"
case .finished: return "isFinished"
}
}
var executing: Bool {
switch self {
case .executing: return true
case .initial, .finished: return false
}
}
var finished: Bool {
switch self {
case .finished: return true
case .initial, .executing: return false
}
}
}
// MARK: - Public Methods
/// Call this function to signal to the system that execution of the operation
/// has completed.
open func completeOperation() {
state = .finished
}
// MARK: - Private Properties
fileprivate var state = State.initial {
willSet {
assert(newValue != .initial, "Should never move back to the Initial State.")
willChangeValue(forKey: state.key)
willChangeValue(forKey: newValue.key)
}
didSet {
didChangeValue(forKey: oldValue.key)
didChangeValue(forKey: state.key)
}
}
// MARK: - Operation
open override var isAsynchronous: Bool { return true }
open override var isExecuting: Bool { return state.executing }
open override var isFinished: Bool { return state.finished }
open override func cancel() {
super.cancel()
state = .finished
}
open override func start() {
guard !isCancelled else {
state = .finished
return
}
state = .executing
main()
}
/// Override this method with work to do. It will be called automatically
/// if it's appropriate, based on state (e.g. cancelled operations will not
/// have main() called.
open override func main() { }
}
| 27.106195 | 82 | 0.669278 |
4a866308e1e80d832dc4288aa40efb8d371ecd4d | 927 | //
// Int+RomanNumeral.swift
// TPPDF
//
// Created by Philip Niedertscheider on 04/11/2017.
//
/**
Extends an integer with conversion to Roman Numerals
*/
extension Int {
/**
Converts `self` into a string of roman numerals.
*/
internal var romanNumerals: String {
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = self
for (index, romanChar) in romanValues.enumerated() {
let arabicValue = arabicValues[index]
let div = startingValue / arabicValue
if div > 0 {
for _ in 0..<div {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
return romanValue
}
}
| 24.394737 | 97 | 0.515642 |
89a854e41fc5893a568aeba00d9006592920bf69 | 1,515 | //
// SizeAdaptor.swift
// AppAdapter
//
// Created by Simon on 2021/5/14.
//
import Foundation
import UIKit
/// 屏幕宽度
public let kScreenWidth: CGFloat = UIScreen.main.bounds.width
/// 屏幕高度
public let kScreenHeight: CGFloat = UIScreen.main.bounds.height
/// 屏幕宽高最大值
public let kScreenMax: CGFloat = max(kScreenWidth, kScreenHeight)
/// 状态栏高度
public let kStatusBarHeight: CGFloat = kStatusBarSize().height
/// 导航栏高度
public let kNavBarHeight: CGFloat = 44.0
/// 顶部高度
public let kTopHeight: CGFloat = kStatusBarHeight + kNavBarHeight
/// 底部安全高度
public let kSafeHeight: CGFloat = kBottomSafeHeight()
/// Tabbar 高度
public let kTabBarHeight: CGFloat = kSafeHeight + 49.0
/// 以宽度为基准, 适配比例, 以iPhone6为比例
public let kScale: CGFloat = kScreenWidth / 375.0
// MARK: 函数
/// 动态获取状态栏size
public func kStatusBarSize() -> CGSize {
if #available(iOS 13, *) {
let window = UIApplication.shared.windows.first
return window?.windowScene?.statusBarManager?.statusBarFrame.size ?? CGSize(width: 0.0, height: 0.0)
} else {
return UIApplication.shared.statusBarFrame.size
}
}
public func kBottomSafeHeight() -> CGFloat {
if #available(iOS 11, *) {
return UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0.0
}
return 0.0
}
/// UI 宽高适配,
/// - Parameters:
/// - size: 设计稿尺寸大小
/// - scale: 是否缩放
/// - Returns: 适配后的大小
public func kAdaptor(_ size: CGFloat, scale: Bool = true) -> CGFloat {
if scale {
return ceil(size * kScale)
}
return size
}
| 24.836066 | 108 | 0.688449 |
46b4e17c8c4e895932202e792e2e6090fcf5d0d9 | 9,661 | //
// CustomTabViewController.swift
// SEDaily-IOS
//
// Created by Craig Holliday on 6/26/17.
// Copyright © 2017 Koala Tea. All rights reserved.
//
enum CollectionConfig {
case latest
case bookmarks
case downloaded
case search
}
import UIKit
import MessageUI
import PopupDialog
import SnapKit
import StoreKit
import SwifterSwift
import SwiftIcons
import Firebase
class CustomTabViewController: UITabBarController, UITabBarControllerDelegate {
var ifset = false
var actionSheet = UIAlertController()
weak var audioOverlayDelegate: AudioOverlayDelegate?
init(audioOverlayDelegate: AudioOverlayDelegate?) {
self.audioOverlayDelegate = audioOverlayDelegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
self.view.backgroundColor = .white
setupTabs()
setupTitleView()
self.tabBar.tintColor = Stylesheet.Colors.base
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupNavBar()
AskForReview.tryToExecute { didExecute in
if didExecute {
self.askForReview()
}
}
}
func setupNavBar() {
let rightBarButton = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(self.rightBarButtonPressed))
self.navigationItem.rightBarButtonItem = rightBarButton
switch UserManager.sharedInstance.getActiveUser().isLoggedIn() {
case false:
let leftBarButton = UIBarButtonItem(title: L10n.loginTitle, style: .done, target: self, action: #selector(self.loginButtonPressed))
self.navigationItem.leftBarButtonItem = leftBarButton
case true:
let leftBarButton = UIBarButtonItem(title: L10n.logoutTitle, style: .plain, target: self, action: #selector(self.leftBarButtonPressed))
// Hacky way to show bars icon
let iconSize: CGFloat = 16.0
let image = UIImage(bgIcon: .fontAwesome(.bars), bgTextColor: .clear, bgBackgroundColor: .clear, topIcon: .fontAwesome(.bars), topTextColor: .white, bgLarge: false, size: CGSize(width: iconSize, height: iconSize))
leftBarButton.image = image
leftBarButton.imageInsets = UIEdgeInsets(top: 0, left: -(iconSize / 2), bottom: 0, right: 0)
self.navigationItem.leftBarButtonItem = leftBarButton
}
}
@objc func rightBarButtonPressed() {
let layout = UICollectionViewLayout()
var searchCollectionViewController = SearchCollectionViewController(collectionViewLayout: layout, audioOverlayDelegate: self.audioOverlayDelegate)
self.navigationController?.pushViewController(searchCollectionViewController)
Analytics2.searchNavButtonPressed()
}
@objc func leftBarButtonPressed() {
self.setupLogoutSubscriptionActionSheet()
self.actionSheet.show()
}
@objc func loginButtonPressed() {
Analytics2.loginNavButtonPressed()
let vc = LoginViewController()
self.navigationController?.pushViewController(vc)
}
@objc func logoutButtonPressed() {
Analytics2.logoutNavButtonPressed()
UserManager.sharedInstance.logoutUser()
self.setupNavBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupTabs() {
let layout = UICollectionViewLayout()
let feedListStoryboard = UIStoryboard.init(name: "FeedList", bundle: nil)
guard let FeedViewController = feedListStoryboard.instantiateViewController(
withIdentifier: "FeedListViewController") as? FeedListViewController else {
return
}
FeedViewController.audioOverlayDelegate = self.audioOverlayDelegate
let forumStoryboard = UIStoryboard.init(name: "ForumList", bundle: nil)
guard let ForumViewController = forumStoryboard.instantiateViewController(
withIdentifier: "ForumListViewController") as? ForumListViewController else {
return
}
let latestVC = PodcastPageViewController(audioOverlayDelegate: self.audioOverlayDelegate)
let bookmarksVC = BookmarkCollectionViewController(collectionViewLayout: layout, audioOverlayDelegate: self.audioOverlayDelegate)
let downloadsVC = DownloadsCollectionViewController(collectionViewLayout: layout, audioOverlayDelegate: self.audioOverlayDelegate)
let profileVC = ProfileViewController()
self.viewControllers = [
latestVC,
bookmarksVC,
downloadsVC,
profileVC
]
#if DEBUG
// This will cause the tab bar to overflow so it will be auto turned into "More ..."
let debugStoryboard = UIStoryboard.init(name: "Debug", bundle: nil)
let debugViewController = debugStoryboard.instantiateViewController(
withIdentifier: "DebugTabViewController")
if let viewControllers = self.viewControllers {
self.viewControllers = viewControllers + [debugViewController]
}
#endif
self.tabBar.backgroundColor = .white
self.tabBar.isTranslucent = false
}
func setupTitleView() {
let height = UIView.getValueScaledByScreenHeightFor(baseValue: 40)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: height, height: height))
imageView.contentMode = .scaleAspectFit
imageView.image = #imageLiteral(resourceName: "Logo_BarButton")
self.navigationItem.titleView = imageView
}
private func askForReview() {
let popup = PopupDialog(title: L10n.enthusiasticHello,
message: L10n.appReviewPromptQuestion,
gestureDismissal: false)
let feedbackPopup = PopupDialog(title: L10n.appReviewApology,
message: L10n.appReviewGiveFeedbackQuestion)
let feedbackYesButton = DefaultButton(title: L10n.enthusiasticSureSendEmail) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject(L10n.appReviewEmailSubject)
self.present(mail, animated: true, completion: nil)
} else {
let emailUnsupportedPopup = PopupDialog(title: L10n.emailUnsupportedOnDevice, message: L10n.emailUnsupportedMessage)
let okayButton = DefaultButton(title: L10n.genericOkay) {
emailUnsupportedPopup.dismiss()
}
emailUnsupportedPopup.addButton(okayButton)
self.present(emailUnsupportedPopup, animated: true, completion: nil)
}
}
let feedbackNoButton = DefaultButton(title: L10n.noWithGratitude) {
popup.dismiss()
}
let yesButton = DefaultButton(title: L10n.enthusiasticYes) {
SKStoreReviewController.requestReview()
AskForReview.setReviewed()
}
let noButton = DefaultButton(title: L10n.genericNo) {
popup.dismiss()
self.present(feedbackPopup, animated: true, completion: nil)
}
popup.addButtons([yesButton, noButton])
feedbackPopup.addButtons([feedbackYesButton, feedbackNoButton])
self.present(popup, animated: true, completion: nil)
}
func setupLogoutSubscriptionActionSheet() {
self.actionSheet = UIAlertController(title: "", message: "Whatcha wanna do?", preferredStyle: .actionSheet)
self.actionSheet.popoverPresentationController?.barButtonItem = self.navigationItem.leftBarButtonItem
switch UserManager.sharedInstance.getActiveUser().hasPremium {
case true:
self.actionSheet.addAction(title: "View Subscription", style: .default, isEnabled: true) { _ in
// Show view subscription status view
let rootVC = SubscriptionStatusViewController()
let navVC = UINavigationController(rootViewController: rootVC)
self.present(navVC, animated: true, completion: nil)
}
case false:
// self.actionSheet.addAction(title: "Purchase Subscription", style: .default, isEnabled: true) { _ in
// // Show purchase subscription view
// let rootVC = PurchaseSubscriptionViewController()
// let navVC = UINavigationController(rootViewController: rootVC)
// self.present(navVC, animated: true, completion: nil)
// }
break
}
self.actionSheet.addAction(title: "Logout", style: .destructive, isEnabled: true) { _ in
self.logoutButtonPressed()
}
self.actionSheet.addAction(title: "Cancel", style: .cancel, isEnabled: true) { _ in
self.actionSheet.dismiss(animated: true, completion: nil)
}
}
}
extension CustomTabViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .sent:
AskForReview.setReviewed()
default: break
}
}
}
| 38.035433 | 225 | 0.664217 |
62889aee8a1bed9604834b1ca5f76380b3e638bd | 5,154 | //
// RSBorderedButton.swift
// Pods
//
// Created by James Kizer on 7/11/17.
//
//
import UIKit
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
public extension UIButton {
func setBackgroundColor(backgroundColor: UIColor?, for state: UIControl.State) {
if let color = backgroundColor {
self.setBackgroundImage(UIImage.from(color: color), for: state)
}
else {
self.setBackgroundImage(nil, for: state)
}
}
}
open class RSBorderedButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
self.initButton()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initButton()
}
private func initButton() {
self.titleLabel?.font = self.defaultFont
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 5.0
self.clipsToBounds = true
self.internalSetColors(primaryColor: self.tintColor)
}
//what we would like is that normally, a bordered button is text and border set to primary color, and background is clear
//When highlighted or selected, the text is set to secondary color (defaults to white), border and background set to primary color
//when disabled, text and border is set to grey (black w/ alpha)
// private func setTitleColor(_ color: UIColor?) {
// self.setTitleColor(color, for: UIControlState.normal)
// self.setTitleColor(UIColor.white, for: UIControlState.highlighted)
// self.setTitleColor(UIColor.white, for: UIControlState.selected)
// self.setTitleColor(UIColor.black.withAlphaComponent(0.3), for: UIControlState.disabled)
// }
//
public var userInfo: [String: Any]?
var primaryColor: UIColor?
var secondaryColor: UIColor?
public func setColors(primaryColor: UIColor, secondaryColor: UIColor? = nil) {
self.primaryColor = primaryColor
self.secondaryColor = secondaryColor
self.internalSetColors(primaryColor: primaryColor, secondaryColor: secondaryColor)
}
private func internalSetColors(primaryColor: UIColor, secondaryColor: UIColor? = nil) {
let secondaryColor = secondaryColor ?? UIColor.white
//normal, text and border set to primary color, and background is clear
self.setTitleColor(primaryColor, for: UIControl.State.normal)
self.setBackgroundColor(backgroundColor: nil, for: UIControl.State.normal)
//disabled, text and border is set to grey (black w/ alpha)
self.setTitleColor(UIColor.black.withAlphaComponent(0.3), for: UIControl.State.disabled)
self.setBackgroundColor(backgroundColor: nil, for: UIControl.State.disabled)
//highlighted
self.setTitleColor(secondaryColor, for: UIControl.State.highlighted)
self.setBackgroundColor(backgroundColor: primaryColor, for: UIControl.State.highlighted)
//selected
self.setTitleColor(secondaryColor, for: UIControl.State.highlighted)
self.setBackgroundColor(backgroundColor: primaryColor, for: UIControl.State.highlighted)
}
override open func layoutSubviews() {
super.layoutSubviews()
//normal, highlighted, selected: primary color
//disabled: grey
if self.state == .disabled {
self.layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor
}
else {
self.layer.borderColor = (self.primaryColor ?? self.tintColor).cgColor
}
}
//by default, the tint color should be the primary color and secondary color is white
//first, check to see if color has been configured
override open func tintColorDidChange() {
//if we have not configured the color, set
super.tintColorDidChange()
if let _ = self.primaryColor {
return
}
else {
self.internalSetColors(primaryColor: self.tintColor, secondaryColor: nil)
}
}
override open var intrinsicContentSize : CGSize {
let superSize = super.intrinsicContentSize
return CGSize(width: superSize.width + 20.0, height: superSize.height)
}
open var defaultFont: UIFont {
// regular, 14
return RSBorderedButton.defaultFont
}
open class var defaultFont: UIFont {
// regular, 14
let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFont.TextStyle.headline)
let fontSize: Double = (descriptor.object(forKey: UIFontDescriptor.AttributeName.size) as! NSNumber).doubleValue
return UIFont.systemFont(ofSize: CGFloat(fontSize))
}
}
| 35.30137 | 134 | 0.659294 |
bff418b25d5cef3f2222945f8f817d941eec8d9a | 308 | //
// ViewController.swift
// MvcIos
//
// Created by Tim on 12.08.19.
// Copyright © 2019 Tim. All rights reserved.
//
import UIKit
class NotesView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 14.666667 | 58 | 0.63961 |
e472aa76df0eb8ce9a666500e57aa00a8d119263 | 1,155 | //
// ViewController.swift
// Passworder
//
// Created by nastia on 21.12.16.
// Copyright © 2016 Anastasiia Soboleva. All rights reserved.
//
import UIKit
class ViewController: UIViewController, PasswordGeneratorProtocol {
let passwordGenerator = PasswordGenerator()
@IBOutlet weak var passwordLabel: UILabel!
@IBAction func generateButtonPressed(_ sender: UIButton) {
updatePassword()
}
@IBAction func settingsPressed(_ sender: UIButton) {
performSegue(withIdentifier: "toSettingsVCSID", sender: sender)
}
override func viewDidLoad() {
super.viewDidLoad()
passwordGenerator.passwordDelegate = self
updatePassword()
}
func updatePassword() {
let password = passwordGenerator.generate()
passwordLabel.text = password
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "toSettingsVCSID", let dvc = segue.destination as? SettingsVC else {
return
}
dvc.passwordGenerator = passwordGenerator
}
//MARK: - PasswordGeneratorProtocol methods
func passwordGeneratorDidUpdateSettings(passwordGenerator: PasswordGenerator) {
updatePassword()
}
}
| 21.792453 | 96 | 0.744589 |
efb37f3e34371d49b805737f255b38e8fc03c11a | 21,014 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_2 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_3 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_4 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_5 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_6 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_KW_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_KW_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_1 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1 < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1_NEGATIVE < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_2 | %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_1 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL_NO_DUPLICATES < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=NEGATIVE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CLOSURE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_CLOSURE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_1 > %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.1.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_2 > %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_3 > %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.3.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_4 > %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.4.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_6 > %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.6.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_1 > %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.1.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_3 > %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.3.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_4 > %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.4.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_1 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_3 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_4 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_5 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_5 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_6 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_6 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_7 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_7 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_8 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_8 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_9 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_10 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_AUTOCLOSURE_1 | %FileCheck %s -check-prefix=AUTOCLOSURE_STRING
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_SWITCH_CASE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_SWITCH_CASE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_1 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_2 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_1 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_2 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_1 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_2 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_3 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_4 | %FileCheck %s -check-prefix=STRING_INTERP
// Test code completion in top-level code.
//
// This test is not meant to test that we can correctly form all kinds of
// completion results in general; that should be tested elsewhere.
struct FooStruct {
var instanceVar = 0
func instanceFunc(_ a: Int) {}
// Add more stuff as needed.
}
var fooObject : FooStruct
func fooFunc1() {}
func fooFunc2(_ a: Int, _ b: Double) {}
func erroneous1(_ x: Undeclared) {}
//===--- Test code completions of expressions that can be typechecked.
// Although the parser can recover in most of these test cases, we resync it
// anyway to ensure that there parser recovery does not interfere with code
// completion.
func resyncParser1() {}
fooObject#^TYPE_CHECKED_EXPR_1^#
// TYPE_CHECKED_EXPR_1: Begin completions
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_1-NEXT: End completions
func resyncParser2() {}
// Test that we can code complete after a top-level var decl.
var _tmpVar1 : FooStruct
fooObject#^TYPE_CHECKED_EXPR_2^#
// TYPE_CHECKED_EXPR_2: Begin completions
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_2-NEXT: End completions
func resyncParser3() {}
fooObject#^TYPE_CHECKED_EXPR_3^#.bar
// TYPE_CHECKED_EXPR_3: Begin completions
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_3-NEXT: End completions
func resyncParser4() {}
fooObject.#^TYPE_CHECKED_EXPR_4^#
// TYPE_CHECKED_EXPR_4: Begin completions
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: End completions
func resyncParser5() {}
fooObject.#^TYPE_CHECKED_EXPR_5^#.bar
// TYPE_CHECKED_EXPR_5: Begin completions
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: End completions
func resyncParser6() {}
fooObject.instanceFunc(#^TYPE_CHECKED_EXPR_6^#
func resyncParser6() {}
fooObject.is#^TYPE_CHECKED_EXPR_KW_1^#
// TYPE_CHECKED_EXPR_KW_1: found code completion token
// TYPE_CHECKED_EXPR_KW_1-NOT: Begin completions
func resyncParser7() {}
// We have an error in the initializer here, but the type is explicitly written
// in the source.
var fooObjectWithErrorInInit : FooStruct = unknown_var
fooObjectWithErrorInInit.#^TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1^#
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1: Begin completions
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: End completions
func resyncParser6a() {}
var topLevelVar1 = #^TOP_LEVEL_VAR_INIT_1^#
// TOP_LEVEL_VAR_INIT_1: Begin completions
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1: End completions
// Check that the variable itself does not show up.
// TOP_LEVEL_VAR_INIT_1_NEGATIVE-NOT: topLevelVar1
func resyncParser7() {}
var topLevelVar2 = FooStruct#^TOP_LEVEL_VAR_INIT_2^#
// TOP_LEVEL_VAR_INIT_2: Begin completions
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ({#instanceVar: Int#})[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: End completions
func resyncParser8() {}
#^PLAIN_TOP_LEVEL_1^#
// PLAIN_TOP_LEVEL: Begin completions
// PLAIN_TOP_LEVEL-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL: End completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES: Begin completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc2({#(a): Int#}, {#(b): Double#})[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc1
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc2
// PLAIN_TOP_LEVEL_NO_DUPLICATES: End completions
func resyncParser9() {}
// Test that we can code complete immediately after a decl with a syntax error.
func _tmpFuncWithSyntaxError() { if return }
#^PLAIN_TOP_LEVEL_2^#
func resyncParser10() {}
_ = {
#^TOP_LEVEL_CLOSURE_1^#
}()
// TOP_LEVEL_CLOSURE_1: Begin completions
// TOP_LEVEL_CLOSURE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1: End completions
func resyncParser11() {}
//===--- Test code completions of types.
func resyncParserA1() {}
var topLevelVarType1 : #^TOP_LEVEL_VAR_TYPE_1^#
// TOP_LEVEL_VAR_TYPE_1: Begin completions
// TOP_LEVEL_VAR_TYPE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_TYPE_1: End completions
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[GlobalVar
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[FreeFunc
func resyncParserA1_1() {}
var topLevelVarType2 : [#^TOP_LEVEL_VAR_TYPE_2^#]
func resyncParserA1_2() {}
var topLevelVarType3 : [#^TOP_LEVEL_VAR_TYPE_3^#: Int]
func resyncParserA1_3() {}
var topLevelVarType4 : [Int: #^TOP_LEVEL_VAR_TYPE_4^#]
func resyncParserA1_4() {}
if let topLevelVarType5 : [#^TOP_LEVEL_VAR_TYPE_5^#] {}
func resyncParserA1_5() {}
guard let topLevelVarType6 : [#^TOP_LEVEL_VAR_TYPE_6^#] else {}
func resyncParserA1_6() {}
_ = ("a" as #^TOP_LEVEL_EXPR_TYPE_1^#)
func resyncParserA1_7() {}
_ = ("a" as! #^TOP_LEVEL_EXPR_TYPE_2^#)
func resyncParserA1_8() {}
_ = ("a" as? #^TOP_LEVEL_EXPR_TYPE_3^#)
func resyncParserA1_9() {}
_ = ("a" is #^TOP_LEVEL_EXPR_TYPE_4^#)
func resyncParserA2() {}
//===--- Test code completion in statements.
func resyncParserB1() {}
if (true) {
#^TOP_LEVEL_STMT_1^#
}
func resyncParserB2() {}
while (true) {
#^TOP_LEVEL_STMT_2^#
}
func resyncParserB3() {}
repeat {
#^TOP_LEVEL_STMT_3^#
} while true
func resyncParserB4() {}
for ; ; {
#^TOP_LEVEL_STMT_4^#
}
func resyncParserB5() {}
for var i = 0; ; {
#^TOP_LEVEL_STMT_5^#
// TOP_LEVEL_STMT_5: Begin completions
// TOP_LEVEL_STMT_5: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// TOP_LEVEL_STMT_5: End completions
}
func resyncParserB6() {}
for i in [] {
#^TOP_LEVEL_STMT_6^#
// TOP_LEVEL_STMT_6: Begin completions
// TOP_LEVEL_STMT_6: Decl[LocalVar]/Local: i[#Any#]{{; name=.+$}}
// TOP_LEVEL_STMT_6: End completions
}
func resyncParserB7() {}
for i in [1, 2, 3] {
#^TOP_LEVEL_STMT_7^#
// TOP_LEVEL_STMT_7: Begin completions
// TOP_LEVEL_STMT_7: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// TOP_LEVEL_STMT_7: End completions
}
func resyncParserB8() {}
for i in unknown_var {
#^TOP_LEVEL_STMT_8^#
// TOP_LEVEL_STMT_8: Begin completions
// TOP_LEVEL_STMT_8: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// TOP_LEVEL_STMT_8: End completions
}
func resyncParserB9() {}
switch (0, 42) {
case (0, 0):
#^TOP_LEVEL_STMT_9^#
}
func resyncParserB10() {}
// rdar://20738314
if true {
var z = #^TOP_LEVEL_STMT_10^#
} else {
assertionFailure("Shouldn't be here")
}
func resyncParserB11() {}
// rdar://21346928
func optStr() -> String? { return nil }
let x = (optStr() ?? "autoclosure").#^TOP_LEVEL_AUTOCLOSURE_1^#
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#]
func resyncParserB12() {}
// rdar://21661308
switch 1 {
case #^TOP_LEVEL_SWITCH_CASE_1^#
}
// TOP_LEVEL_SWITCH_CASE_1: Begin completions
func resyncParserB13() {}
#^TOP_LEVEL_BEFORE_GUARD_NAME_1^#
// TOP_LEVEL_BEFORE_GUARD_NAME-NOT: name=guardedName
guard let guardedName = 1 as Int? {
#^TOP_LEVEL_BEFORE_GUARD_NAME_2^#
}
#^TOP_LEVEL_GUARD_1^#
func interstitial() {}
#^TOP_LEVEL_GUARD_2^#
// TOP_LEVEL_GUARD: Decl[LocalVar]/Local: guardedName[#Int#]; name=guardedName
func resyncParserB14() {}
"\(#^STRING_INTERP_1^#)"
"\(1) \(#^STRING_INTERP_2^#) \(2)"
var stringInterp = "\(#^STRING_INTERP_3^#)"
_ = "" + "\(#^STRING_INTERP_4^#)" + ""
// STRING_INTERP: Begin completions
// STRING_INTERP-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#];
// STRING_INTERP-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#];
// STRING_INTERP-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#];
// STRING_INTERP: End completions
func resyncParserC1() {}
//
//===--- DON'T ADD ANY TESTS AFTER THIS LINE.
//
// These declarations should not show up in top-level code completion results
// because forward references are not allowed at the top level.
struct StructAtEOF {}
// NEGATIVE-NOT: StructAtEOF
extension FooStruct {
func instanceFuncAtEOF() {}
// NEGATIVE-NOT: instanceFuncAtEOF
}
var varAtEOF : Int
// NEGATIVE-NOT: varAtEOF
| 45.882096 | 198 | 0.746122 |
184e57141b247791d3c41055893a016635cc91a8 | 749 | import XCTest
import akulaiev2019
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.827586 | 111 | 0.602136 |
f8c8dbf4717003d4be1a01efc5df973c726ec221 | 12,098 | //
// NYC2016Sponsors.swift
// TrySwiftData
//
// Created by Tim Oliver on 1/29/17.
// Copyright © 2017 NatashaTheRobot. All rights reserved.
//
import Foundation
import RealmSwift
import TrySwiftData
public let tko2017Sponsors: [String : Sponsor] = [
//Platinum
"ibm" : {
let sponsor = Sponsor()
sponsor.name = "IBM"
sponsor.url = "http://www.ibm.com/"
sponsor.displayURL = "ibm.com"
sponsor.twitter = "IBM"
sponsor.logoAssetName = "ibm.png"
sponsor.level = .platinum
return sponsor
}(),
"cyberagent" : {
let sponsor = Sponsor()
sponsor.name = "CyberAgent"
sponsor.url = "http://www.cyberagent.co.jp/"
sponsor.displayURL = "cyberagent.co.jp"
sponsor.twitter = "CyberAgentInc"
sponsor.logoAssetName = "cyberagent.png"
sponsor.level = .platinum
return sponsor
}(),
"realm" : {
let sponsor = Sponsor()
sponsor.name = "Realm"
sponsor.url = "http://www.realm.io/"
sponsor.displayURL = "realm.io"
sponsor.twitter = "Realm"
sponsor.logoAssetName = "realm.png"
sponsor.level = .platinum
return sponsor
}(),
"recruit" : {
let sponsor = Sponsor()
sponsor.name = "Recruit Marketing Partners"
sponsor.url = "http://www.recruit-mp.co.jp/career_engineer/"
sponsor.displayURL = "recruit-mp.co.jp"
sponsor.logoAssetName = "recruit_marketing_partners.png"
sponsor.level = .platinum
return sponsor
}(),
"yahoo" : {
let sponsor = Sponsor()
sponsor.name = "Yahoo! JAPAN"
sponsor.url = "http://www.yahoo.co.jp"
sponsor.displayURL = "yahoo.co.jp"
sponsor.logoAssetName = "yahoo.png"
sponsor.level = .platinum
return sponsor
}(),
"line" : {
let sponsor = Sponsor()
sponsor.name = "LINE"
sponsor.url = "https://linecorp.com/ja/"
sponsor.displayURL = "linecorp.com"
sponsor.logoAssetName = "line.png"
sponsor.level = .platinum
return sponsor
}(),
//Gold
"speee" : {
let sponsor = Sponsor()
sponsor.name = "Speee"
sponsor.url = "http://www.speee.jp"
sponsor.displayURL = "speee.jp"
sponsor.twitter = "speee_pr"
sponsor.logoAssetName = "speee.png"
sponsor.level = .gold
return sponsor
}(),
"casareal" : {
let sponsor = Sponsor()
sponsor.name = "casareal"
sponsor.url = "https://www.casareal.co.jp"
sponsor.displayURL = "casareal.co.jp"
sponsor.logoAssetName = "casareal.png"
sponsor.level = .gold
return sponsor
}(),
"cookpad" : {
let sponsor = Sponsor()
sponsor.name = "Cookpad"
sponsor.url = "https://info.cookpad.com"
sponsor.displayURL = "cookpad.com"
sponsor.twitter = "cookpad_pr"
sponsor.logoAssetName = "cookpad.png"
sponsor.level = .gold
return sponsor
}(),
"firebase" : {
let sponsor = Sponsor()
sponsor.name = "Firebase"
sponsor.url = "http://www.firebase.com/"
sponsor.displayURL = "firebase.com"
sponsor.twitter = "Firebase"
sponsor.logoAssetName = "firebase.png"
sponsor.level = .gold
return sponsor
}(),
"laiso" : {
let sponsor = Sponsor()
sponsor.name = "laiso"
sponsor.url = "http://www.github.com/laiso"
sponsor.displayURL = "github.com/laiso"
sponsor.twitter = "laiso"
sponsor.logoAssetName = "laiso.png"
sponsor.level = .gold
return sponsor
}(),
"moneyforward" : {
let sponsor = Sponsor()
sponsor.name = "Money Forward"
sponsor.url = "https://moneyforward.com"
sponsor.displayURL = "moneyforward.com"
sponsor.twitter = "moneyforward"
sponsor.logoAssetName = "moneyforward.png"
sponsor.level = .gold
return sponsor
}(),
"sansan" : {
let sponsor = Sponsor()
sponsor.name = "Sansan"
sponsor.url = "https://jp.corp-sansan.com"
sponsor.displayURL = "corp-sansan.com"
sponsor.twitter = "sansan_pr"
sponsor.logoAssetName = "sansan.png"
sponsor.level = .gold
return sponsor
}(),
"mercari" : {
let sponsor = Sponsor()
sponsor.name = "Mercari"
sponsor.url = "https://www.mercari.com"
sponsor.displayURL = "mercari.com"
sponsor.twitter = "mercari_app"
sponsor.logoAssetName = "mercari.png"
sponsor.level = .gold
return sponsor
}(),
"balto" : {
let sponsor = Sponsor()
sponsor.name = "Balto (Goodpatch Inc.)"
sponsor.url = "http://www.balto.io/"
sponsor.displayURL = "balto.io"
sponsor.twitter = "balto_appjp"
sponsor.logoAssetName = "balto.png"
sponsor.level = .gold
return sponsor
}(),
//Silver
"furyu" : {
let sponsor = Sponsor()
sponsor.name = "FuRyu"
sponsor.url = "http://www.saiyo.furyu.jp"
sponsor.displayURL = "saiyo.furyu.jp"
sponsor.logoAssetName = "furyu.png"
sponsor.level = .silver
return sponsor
}(),
"player" : {
let sponsor = Sponsor()
sponsor.name = "Player! (ookami Inc.)"
sponsor.url = "http://www.playerapp.tokyo"
sponsor.displayURL = "playerapp.tokyo"
sponsor.logoAssetName = "player.png"
sponsor.level = .silver
return sponsor
}(),
"ubiregi" : {
let sponsor = Sponsor()
sponsor.name = "Ubiregi"
sponsor.url = "https://ubiregi.com"
sponsor.displayURL = "ubiregi.com"
sponsor.twitter = "ubiregi"
sponsor.logoAssetName = "ubiregi.png"
sponsor.level = .silver
return sponsor
}(),
"freee" : {
let sponsor = Sponsor()
sponsor.name = "freee"
sponsor.url = "https://corp.freee.co.jp"
sponsor.displayURL = "corp.freee.co.jp"
sponsor.twitter = "freee_jp"
sponsor.logoAssetName = "freee.png"
sponsor.level = .silver
return sponsor
}(),
"ohako" : {
let sponsor = Sponsor()
sponsor.name = "OHAKO"
sponsor.url = "http://ohako-inc.jp"
sponsor.displayURL = "ohako-inc.jp"
sponsor.logoAssetName = "ohako.png"
sponsor.level = .silver
return sponsor
}(),
"hatena" : {
let sponsor = Sponsor()
sponsor.name = "Hatena"
sponsor.url = "http://hatenacorp.jp"
sponsor.displayURL = "hatenacorp.jp"
sponsor.logoAssetName = "hatena.png"
sponsor.level = .silver
return sponsor
}(),
"prtimes" : {
let sponsor = Sponsor()
sponsor.name = "PR TIMES"
sponsor.url = "http://prtimes.co.jp"
sponsor.displayURL = "prtimes.co.jp"
sponsor.logoAssetName = "prtimes.png"
sponsor.level = .silver
return sponsor
}(),
"kytrade" : {
let sponsor = Sponsor()
sponsor.name = "KY TRADE"
sponsor.url = "http://www.kytrade.co.jp"
sponsor.displayURL = "kytrade.co.jp"
sponsor.logoAssetName = "kytrade.png"
sponsor.level = .silver
return sponsor
}(),
"gmo" : {
let sponsor = Sponsor()
sponsor.name = "GMO Pepabo"
sponsor.url = "https://pepabo.com"
sponsor.displayURL = "pepabo.com"
sponsor.logoAssetName = "gmopepabo.png"
sponsor.level = .silver
return sponsor
}(),
"fyusion" : {
let sponsor = Sponsor()
sponsor.name = "Fyusion"
sponsor.url = "http://www.fyusion.com"
sponsor.displayURL = "fyusion.com"
sponsor.logoAssetName = "fyusion.png"
sponsor.level = .silver
return sponsor
}(),
"caraquri" : {
let sponsor = Sponsor()
sponsor.name = "Caraquri"
sponsor.url = "http://caraquri.com/"
sponsor.displayURL = "caraquri.com"
sponsor.logoAssetName = "caraquri.png"
sponsor.level = .silver
return sponsor
}(),
"payjp" : {
let sponsor = Sponsor()
sponsor.name = "PAY.JP (BASE,Inc.)"
sponsor.url = "https://pay.jp/"
sponsor.displayURL = "pay.jp/"
sponsor.logoAssetName = "payjp.png"
sponsor.level = .silver
return sponsor
}(),
// Student
"cyberagent-student" : {
let sponsor = Sponsor()
sponsor.name = "CyberAgent"
sponsor.url = "http://www.cyberagent.co.jp/"
sponsor.displayURL = "cyberagent.co.jp"
sponsor.twitter = "CyberAgentInc"
sponsor.logoAssetName = "cyberagent.png"
sponsor.level = .student
return sponsor
}(),
"prtimes-student" : {
let sponsor = Sponsor()
sponsor.name = "PR TIMES"
sponsor.url = "http://prtimes.co.jp"
sponsor.displayURL = "prtimes.co.jp"
sponsor.logoAssetName = "prtimes.png"
sponsor.level = .student
return sponsor
}(),
"sansan-student" : {
let sponsor = Sponsor()
sponsor.name = "Sansan"
sponsor.url = "https://jp.corp-sansan.com"
sponsor.displayURL = "corp-sansan.com"
sponsor.twitter = "sansan_pr"
sponsor.logoAssetName = "sansan.png"
sponsor.level = .student
return sponsor
}(),
"mercari-student" : {
let sponsor = Sponsor()
sponsor.name = "Mercari"
sponsor.url = "https://www.mercari.com"
sponsor.displayURL = "mercari.com"
sponsor.twitter = "mercari_app"
sponsor.logoAssetName = "mercari.png"
sponsor.level = .student
return sponsor
}(),
// Event
"meetup" : {
let sponsor = Sponsor()
sponsor.name = "Meetup"
sponsor.url = "https://www.meetup.com"
sponsor.displayURL = "meetup.com"
sponsor.twitter = "meetup"
sponsor.logoAssetName = "meetup.png"
sponsor.level = .event
return sponsor
}(),
"oisix" : {
let sponsor = Sponsor()
sponsor.name = "Oisix"
sponsor.url = "http://www.oisix.co.jp"
sponsor.displayURL = "oisix.co.jp"
sponsor.twitter = "oisix_com"
sponsor.logoAssetName = "oisix.png"
sponsor.level = .event
return sponsor
}(),
"polidea" : {
let sponsor = Sponsor()
sponsor.name = "Polidea"
sponsor.url = "https://www.polidea.com"
sponsor.displayURL = "polidea.com"
sponsor.twitter = "polidea"
sponsor.logoAssetName = "polidea.png"
sponsor.level = .event
return sponsor
}(),
"2-3works" : {
let sponsor = Sponsor()
sponsor.name = "2-3 Works"
sponsor.url = "http://2-3works.tokyo"
sponsor.displayURL = "2-3works.tokyo"
sponsor.twitter = "yucovin"
sponsor.logoAssetName = "2-3works.png"
sponsor.level = .event
return sponsor
}(),
"pivotal" : {
let sponsor = Sponsor()
sponsor.name = "Pivotal"
sponsor.url = "https://pivotal.io"
sponsor.displayURL = "pivotal.io"
sponsor.twitter = "pivotal"
sponsor.logoAssetName = "pivotal.png"
sponsor.level = .event
return sponsor
}(),
"ninedrafts" : {
let sponsor = Sponsor()
sponsor.name = "Nine Drafts"
sponsor.url = "https://www.facebook.com/9drafts/"
sponsor.displayURL = "facebook.com/9drafts/"
sponsor.logoAssetName = "ninedrafts.png"
sponsor.level = .event
return sponsor
}(),
"appdojo" : {
let sponsor = Sponsor()
sponsor.name = "アプリクリエイター道場"
sponsor.url = "http://app-dojo.jp"
sponsor.displayURL = "app-dojo.jp"
sponsor.twitter = "appcreatordojo"
sponsor.logoAssetName = "appcreatordojo.png"
sponsor.level = .event
return sponsor
}()
]
| 31.100257 | 68 | 0.561415 |
16bafb452c2183821355b9a25433d6180cad11f3 | 2,177 | //
// ActivityIndicator.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> ()) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator : SharedSequenceConvertibleType {
public typealias E = Bool
public typealias SharingStrategy = DriverSharingStrategy
private let _lock = NSRecursiveLock()
private let _variable = Variable(0)
private let _loading: SharedSequence<SharingStrategy, Bool>
public init() {
_loading = _variable.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> {
return Observable.using({ () -> ActivityToken<O.E> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
private func increment() {
_lock.lock()
_variable.value = _variable.value + 1
_lock.unlock()
}
private func decrement() {
_lock.lock()
_variable.value = _variable.value - 1
_lock.unlock()
}
public func asSharedSequence() -> SharedSequence<SharingStrategy, E> {
return _loading
}
}
extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> {
return activityIndicator.trackActivityOfObservable(self)
}
}
| 26.876543 | 110 | 0.66192 |
2f22bec54f671b819122720ea91c4303a0befa3c | 937 | // Copyright © 2019 hipolabs. All rights reserved.
import Foundation
import UIKit
extension NSAttributedString {
public func boundingSize(multiline: Bool = true, fittingSize: CGSize = .greatestFiniteMagnitude) -> CGSize {
let options: NSStringDrawingOptions
if multiline {
options = [.usesFontLeading, .usesLineFragmentOrigin, .truncatesLastVisibleLine]
} else {
options = [.usesFontLeading]
}
let fittingBoundingRect = boundingRect(with: fittingSize, options: options, context: nil)
return CGSize(width: min(fittingBoundingRect.width.ceil(), fittingSize.width), height: min(fittingBoundingRect.height.ceil(), fittingSize.height))
}
}
extension Optional where Wrapped == NSAttributedString {
public var isNilOrEmpty: Bool {
return unwrap(
{
$0.string.isEmpty
},
or: true
)
}
}
| 31.233333 | 154 | 0.651014 |
09621775773edb23222398a583751cca272e7fc3 | 145 | //
// Copyright © 2020 Microsoft. All rights reserved.
//
import Foundation
struct Prediction {
var label: String
var confidence: Float
}
| 13.181818 | 52 | 0.710345 |
f832090e36e90e5dadb4636ae70e6025dc6c545d | 371 | //
// task_tracker_swiftuiApp.swift
// task-tracker-swiftui
//
//
import SwiftUI
import RealmSwift
let app = App(id: "tasktracker-svrtk")
@main
struct task_tracker_swiftuiApp: SwiftUI.App {
@StateObject var state = AppState()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(state)
}
}
}
| 16.130435 | 45 | 0.625337 |
e0f9e6cd8ba38abee699a9b2492547f422fc1e7e | 1,558 | //
// CurrencyTableView.swift
// CurrencyApp
//
// Created by Дмитрий on 07.01.2022.
//
import UIKit
final class CurrencyTableView: UIView {
override init(frame: CGRect) {
super.init(frame: .zero)
addSubviews()
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public lazy var currencyTableView: UITableView = {
var view = UITableView()
view.register(cell: CurrencyViewCell.self)
view.isScrollEnabled = true
view.contentInsetAdjustmentBehavior = .automatic
view.separatorStyle = .none
view.rowHeight = 100
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.backgroundColor = UIColor(red: 37 / 255, green: 40 / 255, blue: 47 / 255, alpha: 1)
view.alpha = 0.0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private func addSubviews() {
addSubview(currencyTableView)
}
private func setupLayout() {
NSLayoutConstraint.activate([
currencyTableView.topAnchor.constraint(equalTo: topAnchor),
currencyTableView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
currencyTableView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
currencyTableView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
| 28.851852 | 101 | 0.643132 |
9cd681f3ba3404c504debe9a94e6e75300f97c64 | 12,459 | //
// Colors.swift
// SwiftTerm
//
// Created by Miguel de Icaza on 3/1/20.
// Copyright © 2020 Miguel de Icaza. All rights reserved.
//
import Foundation
/**
* This represents the colors used in SwiftTerm, in particular for cells and backgrounds
* in 16-bit RGB mode
*/
public class Color: Hashable {
/// Red component 0..65535
public var red: UInt16
/// Green component 0..65535
public var green: UInt16
/// Blue component 0..65535
public var blue: UInt16
// This can be altered at runtime by remote applications
static var ansiColors: [Color] = setupDefaultAnsiColors (initialColors: installedColors)
// This is our blueprint to reset
static var defaultAnsiColors: [Color] = setupDefaultAnsiColors (initialColors: installedColors)
static var defaultForeground = Color (red: 35389, green: 35389, blue: 35389)
static var defaultBackground = Color (red: 0, green: 0, blue: 0)
public static func == (lhs: Color, rhs: Color) -> Bool {
lhs.red == rhs.red && lhs.blue == rhs.blue && lhs.green == rhs.green
}
public func hash(into hasher: inout Hasher) {
hasher.combine(red)
hasher.combine(green)
hasher.combine(blue)
}
static let paleColors: [Color] = [
// dark colors
Color (red8: 0x2e, green8: 0x34, blue8: 0x36),
Color (red8: 0xcc, green8: 0x00, blue8: 0x00),
Color (red8: 0x4e, green8: 0x9a, blue8: 0x06),
Color (red8: 0xc4, green8: 0xa0, blue8: 0x00),
Color (red8: 0x34, green8: 0x65, blue8: 0xa4),
Color (red8: 0x75, green8: 0x50, blue8: 0x7b),
Color (red8: 0x06, green8: 0x98, blue8: 0x9a),
Color (red8: 0xd3, green8: 0xd7, blue8: 0xcf),
// bright colors
Color (red8: 0x55, green8: 0x57, blue8: 0x53),
Color (red8: 0xef, green8: 0x29, blue8: 0x29),
Color (red8: 0x8a, green8: 0xe2, blue8: 0x34),
Color (red8: 0xfc, green8: 0xe9, blue8: 0x4f),
Color (red8: 0x72, green8: 0x9f, blue8: 0xcf),
Color (red8: 0xad, green8: 0x7f, blue8: 0xa8),
Color (red8: 0x34, green8: 0xe2, blue8: 0xe2),
Color (red8: 0xee, green8: 0xee, blue8: 0xec)
]
static let vgaColors: [Color] = [
// dark colors
Color (red8: 0, green8: 0, blue8: 0),
Color (red8: 170, green8: 0, blue8: 0),
Color (red8: 0, green8: 170, blue8: 0),
Color (red8: 170, green8: 85, blue8: 0),
Color (red8: 0, green8: 0, blue8: 170),
Color (red8: 170, green8: 0, blue8: 170),
Color (red8: 0, green8: 170, blue8: 170),
Color (red8: 170, green8: 170, blue8: 170),
Color (red8: 85, green8: 85, blue8: 85),
Color (red8: 255, green8: 85, blue8: 85),
Color (red8: 85, green8: 255, blue8: 85),
Color (red8: 255, green8: 255, blue8: 85),
Color (red8: 85, green8: 85, blue8: 255),
Color (red8: 255, green8: 85, blue8: 255),
Color (red8: 85, green8: 255, blue8: 255),
Color (red8: 255, green8: 255, blue8: 255),
]
static let terminalAppColors: [Color] = [
Color (red8: 0, green8: 0, blue8: 0),
Color (red8: 194, green8: 54, blue8: 33),
Color (red8: 37, green8: 188, blue8: 36),
Color (red8: 173, green8: 173, blue8: 39),
Color (red8: 73, green8: 46, blue8: 225),
Color (red8: 211, green8: 56, blue8: 211),
Color (red8: 51, green8: 187, blue8: 200),
Color (red8: 203, green8: 204, blue8: 205),
Color (red8: 129, green8: 131, blue8: 131),
Color (red8: 252, green8: 57, blue8: 31),
Color (red8: 49, green8: 231, blue8: 34),
Color (red8: 234, green8: 236, blue8: 35),
Color (red8: 88, green8: 51, blue8: 255),
Color (red8: 249, green8: 53, blue8: 248),
Color (red8: 20, green8: 240, blue8: 240),
Color (red8: 233, green8: 235, blue8: 235),
]
static let xtermColors: [Color] = [
Color (red8: 0, green8: 0, blue8: 0),
Color (red8: 205, green8: 0, blue8: 0),
Color (red8: 0, green8: 205, blue8: 0),
Color (red8: 205, green8: 205, blue8: 0),
Color (red8: 0, green8: 0, blue8: 238),
Color (red8: 205, green8: 0, blue8: 205),
Color (red8: 0, green8: 205, blue8: 205),
Color (red8: 229, green8: 229, blue8: 229),
Color (red8: 127, green8: 127, blue8: 127),
Color (red8: 255, green8: 0, blue8: 0),
Color (red8: 0, green8: 255, blue8: 0),
Color (red8: 255, green8: 255, blue8: 0),
Color (red8: 92, green8: 92, blue8: 255),
Color (red8: 255, green8: 0, blue8: 255),
Color (red8: 0, green8: 255, blue8: 255),
Color (red8: 255, green8: 255, blue8: 255),
]
// These colors can be changed via the hosting application
static var installedColors: [Color] = [
Color (red8: 0, green8: 0, blue8: 0),
Color (red8: 153, green8: 0, blue8: 1),
Color (red8: 0, green8: 166, blue8: 3),
Color (red8: 153, green8: 153, blue8: 0),
Color (red8: 3, green8: 0, blue8: 178),
Color (red8: 178, green8: 0, blue8: 178),
Color (red8: 0, green8: 165, blue8: 178),
Color (red8: 191, green8: 191, blue8: 191),
Color (red8: 138, green8: 137, blue8: 138),
Color (red8: 229, green8: 0, blue8: 1),
Color (red8: 0, green8: 216, blue8: 0),
Color (red8: 229, green8: 229, blue8: 0),
Color (red8: 7, green8: 0, blue8: 254),
Color (red8: 229, green8: 0, blue8: 229),
Color (red8: 0, green8: 229, blue8: 229),
Color (red8: 229, green8: 229, blue8: 229),
]
/// Installs the new colors as the default colors and recomputes the
/// current and ansi palette. This will not change the UI layer, for that it is better
/// to call the `installColors` method on `TerminalView`, which will
/// both call this method, and update the display appropriately.
///
/// - Parameter colors: this should be an array of 16 values that correspond to the 16 ANSI colors,
/// if the array does not contain 16 elements, it will not do anything
public static func installPalette (colors: [Color])
{
if colors.count != 16 {
return
}
installedColors = colors
}
static func setupDefaultAnsiColors (initialColors: [Color]) -> [Color]
{
var colors = initialColors
// Fill in the remaining 240 ANSI colors.
let v = [ 0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff ];
// Generate colors (16-231)
for i in 0..<216 {
let r = UInt16 (v [(i / 36) % 6])
let g = UInt16 (v [(i / 6) % 6])
let b = UInt16 (v [i % 6])
colors.append(Color (red8: r, green8: g, blue8: b))
}
// Generate greys (232-255)
for i in 0..<24 {
let c = UInt16 (8 + i * 10)
colors.append (Color (red8: c, green8: c, blue8: c))
}
return colors
}
// Contructs a color from 8 bit values, this can be made public,
// but then we probably should enforce the values to not go
// beyond 8 bits. Otherwise, this can throw at runtime due to overflow.
init(red8: UInt16, green8: UInt16, blue8: UInt16)
{
self.red = red8 * 257
self.green = green8 * 257
self.blue = blue8 * 257
}
// Contructs a color from 4 bit values, this can be made public,
// but then we probably should enforce the values to not go
// beyond 4 bits. Otherwise, this can throw at runtime due to overflow.
init(red4: UInt16, green4: UInt16, blue4: UInt16)
{
// The other one is 4369
self.red = red4 * 0x1010
self.green = green4 * 0x1010
self.blue = blue4 * 0x1010
}
/// Initializes a color with the red, green and blue components in the 0...65535 range
public init(red: UInt16, green: UInt16, blue: UInt16)
{
self.red = red
self.green = green
self.blue = blue
}
func formatAsXcolor () -> String
{
let rs = String(format:"%04x", red)
let gs = String(format:"%04x", green)
let bs = String(format:"%04x", blue)
return "rgb:\(rs)/\(gs)/\(bs)"
}
static func parseColor (_ data: ArraySlice<UInt8>) -> Color?
{
// parses the hex value until the first "/" and returns both the value, and the number of bytes used
func parseHex (_ data: ArraySlice<UInt8>, _ idx: inout Int) -> (UInt16, Int)
{
var ret: UInt16 = 0
let limit = data.endIndex
var count = 0
idx = max (data.startIndex, idx)
while count < 4 && idx < limit {
let c = data [idx]
idx += 1
var n: UInt16 = 0
if c >= UInt8(ascii: "0") && c <= UInt8 (ascii: "9"){
n = UInt16 (c - UInt8(ascii: "0"))
} else if c >= UInt8(ascii: "a") && c <= UInt8 (ascii: "f") {
n = UInt16 ((c - UInt8(ascii:"a") + 10))
} else if c >= UInt8(ascii: "A") && c <= UInt8 (ascii: "F") {
n = UInt16 ((c - UInt8(ascii:"A") + 10))
} else if c == UInt8 (ascii: "/") {
break
} else {
break
}
count += 1
ret = ret * 16 + n
}
if idx < limit && data [idx] == UInt8(ascii: "/") {
idx += 1
}
return (ret, count)
}
func makeColor (_ r: UInt16, _ g: UInt16, _ b: UInt16, scale: Int) -> Color?
{
switch scale {
case 1:
// 4 bit scaled
return Color(red4: r, green4: g, blue4: b)
case 2:
// 8 bit scaled
return Color(red8: r, green8: g, blue8: b)
case 3:
// 12 bit scaled
return Color(red: (r << 4) | (r >> 4), green: (g << 4) | (g >> 4), blue: (b << 4) | (b >> 4))
case 4:
// 16 bits
return Color(red: r, green: g, blue: b)
default:
return nil
}
}
// Parse #XXX, #XXXXXX, #XXXXXXXXX color
if data.first == UInt8 (ascii: "#") {
let count = data.endIndex-(data.startIndex+1)
let rest = data [(data.startIndex+1)...]
let p = data.startIndex+1
var idx = p
switch count {
case 3:
let (r, _) = parseHex (rest [(p+0)..<(p+1)], &idx)
let (g, _) = parseHex (rest [(p+1)..<(p+2)], &idx)
let (b, _) = parseHex (rest [(p+1)..<(p+3)], &idx)
return makeColor (r, g, b, scale: 1)
case 6:
let (r, _) = parseHex (rest [(p+0)..<(p+2)], &idx)
let (g, _) = parseHex (rest [(p+2)..<(p+4)], &idx)
let (b, _) = parseHex (rest [(p+4)..<(p+6)], &idx)
return makeColor (r, g, b, scale: 2)
case 9:
let (r, _) = parseHex (rest[(p+0)..<(p+3)], &idx)
let (g, _) = parseHex (rest[(p+3)..<(p+6)], &idx)
let (b, _) = parseHex (rest[(p+6)..<(p+9)], &idx)
return makeColor (r, g, b, scale: 3)
case 12:
let (r, _) = parseHex (rest [(p+0)..<(p+4)], &idx)
let (g, _) = parseHex (rest [(p+4)..<(p+8)], &idx)
let (b, _) = parseHex (rest [(p+8)..<(p+12)], &idx)
return makeColor (r, g, b, scale: 4)
default:
break
}
} else if data.starts(with: [UInt8(ascii:"r"), UInt8(ascii:"g"), UInt8(ascii:"b"), UInt8(ascii:":")]) {
// Parses rgb:X/X/X rgb:XX/XX/XX/XX, rgb:XXX/XXX/XXX, rgb:XXXX/XXXX/XXXX
var nidx = data.startIndex + 4
let (r, rlen) = parseHex (data, &nidx)
let (g, glen) = parseHex (data, &nidx)
let (b, blen) = parseHex (data, &nidx)
return makeColor (r, g, b, scale: max (rlen, max (glen, blen)))
}
return nil
}
static func resetAllColors ()
{
ansiColors = defaultAnsiColors
}
}
| 38.813084 | 111 | 0.514728 |
6afb3c4046bc03aebd46ccd471822c994df9b11b | 24,822 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIO
import NIOWebSocket
private class CloseSwallower: ChannelOutboundHandler {
typealias OutboundIn = Any
typealias OutboundOut = Any
private var closePromise: EventLoopPromise<Void>? = nil
private var ctx: ChannelHandlerContext? = nil
public func allowClose() {
self.ctx!.close(promise: self.closePromise)
}
func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
self.closePromise = promise
self.ctx = ctx
}
}
/// A class that calls ctx.close() when it receives a decoded websocket frame, and validates that it does
/// not receive two.
private final class SynchronousCloser: ChannelInboundHandler {
typealias InboundIn = WebSocketFrame
private var closeFrame: WebSocketFrame?
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
guard case .connectionClose = frame.opcode else {
ctx.fireChannelRead(data)
return
}
// Ok, connection close. Confirm we haven't seen one before.
XCTAssertNil(self.closeFrame)
self.closeFrame = frame
// Now we're going to call close.
ctx.close(promise: nil)
}
}
public class WebSocketFrameDecoderTest: XCTestCase {
public var decoderChannel: EmbeddedChannel!
public var encoderChannel: EmbeddedChannel!
public var buffer: ByteBuffer!
public override func setUp() {
self.decoderChannel = EmbeddedChannel()
self.encoderChannel = EmbeddedChannel()
self.buffer = decoderChannel.allocator.buffer(capacity: 128)
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameDecoder()).wait())
XCTAssertNoThrow(try self.encoderChannel.pipeline.add(handler: WebSocketFrameEncoder()).wait())
}
public override func tearDown() {
XCTAssertNoThrow(try self.encoderChannel.finish())
_ = try? self.decoderChannel.finish()
self.encoderChannel = nil
self.buffer = nil
}
private func frameForFrame(_ frame: WebSocketFrame) -> WebSocketFrame? {
self.encoderChannel.writeAndFlush(frame, promise: nil)
while case .some(.byteBuffer(let d)) = self.encoderChannel.readOutbound() {
XCTAssertNoThrow(try self.decoderChannel.writeInbound(d))
}
guard let producedFrame: WebSocketFrame = self.decoderChannel.readInbound() else {
XCTFail("Did not produce a frame")
return nil
}
// Should only have gotten one frame!
XCTAssertNil(self.decoderChannel.readInbound() as WebSocketFrame?)
return producedFrame
}
private func assertFrameRoundTrips(frame: WebSocketFrame) {
XCTAssertEqual(frameForFrame(frame), frame)
}
private func assertFrameDoesNotRoundTrip(frame: WebSocketFrame) {
XCTAssertNotEqual(frameForFrame(frame), frame)
}
private func swapDecoder(for handler: ChannelHandler) {
// We need to insert a decoder that doesn't do error handling. We still insert
// an encoder because we want to fail gracefully if a frame is written.
XCTAssertNoThrow(try self.decoderChannel.pipeline.context(handlerType: WebSocketFrameDecoder.self).then {
self.decoderChannel.pipeline.remove(handler: $0.handler)
}.then { (_: Bool) in
self.decoderChannel.pipeline.add(handler: handler)
}.wait())
}
public func testFramesWithoutBodies() throws {
let frame = WebSocketFrame(fin: true, opcode: .ping, data: self.buffer)
assertFrameRoundTrips(frame: frame)
}
public func testFramesWithExtensionDataDontRoundTrip() throws {
// We don't know what the extensions are, so all data goes in...well...data.
self.buffer.write(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let frame = WebSocketFrame(fin: false,
opcode: .binary,
data: self.buffer.getSlice(at: self.buffer.readerIndex, length: 5)!,
extensionData: self.buffer.getSlice(at: self.buffer.readerIndex + 5, length: 5)!)
assertFrameDoesNotRoundTrip(frame: frame)
}
public func testFramesWithExtensionDataCanBeRecovered() throws {
self.buffer.write(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let frame = WebSocketFrame(fin: false,
opcode: .binary,
data: self.buffer.getSlice(at: self.buffer.readerIndex, length: 5)!,
extensionData: self.buffer.getSlice(at: self.buffer.readerIndex + 5, length: 5)!)
var newFrame = frameForFrame(frame)!
// Copy some data out into the extension on the frame. The first 5 bytes are extension.
newFrame.extensionData = newFrame.data.readSlice(length: 5)
XCTAssertEqual(newFrame, frame)
}
public func testFramesWithReservedBitsSetRoundTrip() throws {
self.buffer.write(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let frame = WebSocketFrame(fin: false,
rsv1: true,
rsv2: true,
rsv3: true,
opcode: .binary,
data: self.buffer)
assertFrameRoundTrips(frame: frame)
}
public func testFramesWith16BitLengthsRoundTrip() throws {
self.buffer.write(bytes: Array(repeating: UInt8(4), count: 300))
let frame = WebSocketFrame(fin: true,
opcode: .binary,
data: self.buffer)
assertFrameRoundTrips(frame: frame)
}
public func testFramesWith64BitLengthsRoundTrip() throws {
// We need a new decoder channel here, because the max length would otherwise trigger an error.
_ = try! self.decoderChannel.finish()
self.decoderChannel = EmbeddedChannel()
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameDecoder(maxFrameSize: 80000)).wait())
self.buffer.write(bytes: Array(repeating: UInt8(4), count: 66000))
let frame = WebSocketFrame(fin: true,
opcode: .binary,
data: self.buffer)
assertFrameRoundTrips(frame: frame)
}
public func testMaskedFramesRoundTripWithMaskingIntact() throws {
self.buffer.write(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let frame = WebSocketFrame(fin: false,
opcode: .binary,
maskKey: [0x80, 0x77, 0x11, 0x33],
data: self.buffer)
let producedFrame = frameForFrame(frame)!
XCTAssertEqual(producedFrame.fin, frame.fin)
XCTAssertEqual(producedFrame.rsv1, frame.rsv1)
XCTAssertEqual(producedFrame.rsv2, frame.rsv2)
XCTAssertEqual(producedFrame.rsv3, frame.rsv3)
XCTAssertEqual(producedFrame.maskKey, frame.maskKey)
XCTAssertEqual(producedFrame.length, frame.length)
// The produced frame contains the masked data in its data field.
var maskedBuffer = self.buffer!
maskedBuffer.webSocketMask([0x80, 0x77, 0x11, 0x33])
XCTAssertEqual(maskedBuffer, producedFrame.data)
// But we can get the unmasked data back.
XCTAssertEqual(producedFrame.unmaskedData, self.buffer)
}
public func testMaskedFramesRoundTripWithMaskingIntactEvenWithExtensions() throws {
self.buffer.write(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let frame = WebSocketFrame(fin: false,
opcode: .binary,
maskKey: [0x80, 0x77, 0x11, 0x33],
data: self.buffer.getSlice(at: self.buffer.readerIndex + 5, length: 5)!,
extensionData: self.buffer.getSlice(at: self.buffer.readerIndex, length: 5)!)
var producedFrame = frameForFrame(frame)!
XCTAssertEqual(producedFrame.fin, frame.fin)
XCTAssertEqual(producedFrame.rsv1, frame.rsv1)
XCTAssertEqual(producedFrame.rsv2, frame.rsv2)
XCTAssertEqual(producedFrame.rsv3, frame.rsv3)
XCTAssertEqual(producedFrame.maskKey, frame.maskKey)
XCTAssertEqual(producedFrame.length, frame.length)
// The produced frame contains the masked data in its data field, but doesn't know which is extension and which
// is not. Let's fix that up first.
producedFrame.extensionData = producedFrame.data.readSlice(length: 5)
var maskedBuffer = self.buffer!
maskedBuffer.webSocketMask([0x80, 0x77, 0x11, 0x33])
XCTAssertEqual(maskedBuffer.getSlice(at: maskedBuffer.readerIndex + 5, length: 5)!, producedFrame.data)
XCTAssertEqual(maskedBuffer.getSlice(at: maskedBuffer.readerIndex, length: 5)!, producedFrame.extensionData)
// But we can get the unmasked data back.
XCTAssertEqual(producedFrame.unmaskedData, self.buffer.getSlice(at: self.buffer.readerIndex + 5, length: 5)!)
XCTAssertEqual(producedFrame.unmaskedExtensionData, self.buffer.getSlice(at: self.buffer.readerIndex, length: 5)!)
}
public func testDecoderRejectsOverlongFrames() throws {
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims that the length of the frame is 16385 bytes,
// larger than the frame max.
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xF1])
}
public func testDecoderRejectsFragmentedControlFrames() throws {
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
}
public func testDecoderRejectsMultibyteControlFrameLengths() throws {
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.write(bytes: [0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
}
func testIgnoresFurtherDataAfterRejectedFrame() throws {
let swallower = CloseSwallower()
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: swallower, first: true).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
// Now write another broken frame, this time an overlong frame.
// No error should occur here.
self.buffer.clear()
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
XCTAssertNoThrow(try self.decoderChannel.writeInbound(self.buffer))
// No extra data should have been sent.
XCTAssertNil(self.decoderChannel.readOutbound())
// Allow the channel to close.
swallower.allowClose()
// Take the handler out for cleanliness.
XCTAssertNoThrow(try self.decoderChannel.pipeline.remove(handler: swallower).wait())
}
public func testClosingSynchronouslyOnChannelRead() throws {
// We're going to send a connectionClose frame and confirm we only see it once.
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: SynchronousCloser()).wait())
var errorCodeBuffer = self.encoderChannel.allocator.buffer(capacity: 4)
errorCodeBuffer.write(webSocketErrorCode: .normalClosure)
let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: errorCodeBuffer)
// Write the frame, send it through the decoder channel. We need to do this in one go to trigger
// a double-parse edge case.
self.encoderChannel.write(frame, promise: nil)
var frameBuffer = self.decoderChannel.allocator.buffer(capacity: 10)
while case .some(.byteBuffer(var d)) = self.encoderChannel.readOutbound() {
frameBuffer.write(buffer: &d)
}
XCTAssertNoThrow(try self.decoderChannel.writeInbound(frameBuffer))
// No data should have been sent or received.
XCTAssertNil(self.decoderChannel.readOutbound())
XCTAssertNil(self.decoderChannel.readInbound() as WebSocketFrame?)
}
public func testDecoderRejectsOverlongFramesWithNoAutomaticErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling. We still insert
// an encoder because we want to fail gracefully if a frame is written.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims that the length of the frame is 16385 bytes,
// larger than the frame max.
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// No error frame should be written.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [])
}
public func testDecoderRejectsFragmentedControlFramesWithNoAutomaticErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling. We still insert
// an encoder because we want to fail gracefully if a frame is written.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// No error frame should be written.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [])
}
public func testDecoderRejectsMultibyteControlFrameLengthsWithNoAutomaticErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling. We still insert
// an encoder because we want to fail gracefully if a frame is written.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.write(bytes: [0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// No error frame should be written.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [])
}
func testIgnoresFurtherDataAfterRejectedFrameWithNoAutomaticErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling. We still insert
// an encoder because we want to fail gracefully if a frame is written.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// No error frame should be written.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [])
// Now write another broken frame, this time an overlong frame.
// No error should occur here.
self.buffer.clear()
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
XCTAssertNoThrow(try self.decoderChannel.writeInbound(self.buffer))
// No extra data should have been sent.
XCTAssertNil(self.decoderChannel.readOutbound())
}
public func testDecoderRejectsOverlongFramesWithSeparateErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling, and then a separate error
// handler.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait())
// A fake frame header that claims that the length of the frame is 16385 bytes,
// larger than the frame max.
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xF1])
}
public func testDecoderRejectsFragmentedControlFramesWithSeparateErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling, and then a separate error
// handler.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
}
public func testDecoderRejectsMultibyteControlFrameLengthsWithSeparateErrorHandling() throws {
// We need to insert a decoder that doesn't do error handling, and then a separate error
// handler.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait())
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.write(bytes: [0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
}
func testIgnoresFurtherDataAfterRejectedFrameWithSeparateErrorHandling() throws {
let swallower = CloseSwallower()
// We need to insert a decoder that doesn't do error handling, and then a separate error
// handler.
self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false))
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait())
XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: swallower, first: true).wait())
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.write(bytes: [0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
}
// We expect that an error frame will have been written out.
let errorFrame = self.decoderChannel.readAllOutboundBytes()
XCTAssertEqual(errorFrame, [0x88, 0x02, 0x03, 0xEA])
// Now write another broken frame, this time an overlong frame.
// No error should occur here.
self.buffer.clear()
self.buffer.write(bytes: [0x81, 0xFE, 0x40, 0x01])
XCTAssertNoThrow(try self.decoderChannel.writeInbound(self.buffer))
// No extra data should have been sent.
XCTAssertNil(self.decoderChannel.readOutbound())
// Allow the channel to close.
swallower.allowClose()
// Take the handler out for cleanliness.
XCTAssertNoThrow(try self.decoderChannel.pipeline.remove(handler: swallower).wait())
}
}
| 44.325 | 122 | 0.651881 |
eb2ec985ff59966d256b56f2e4dbe2a92bace8f0 | 1,462 | //
// CardView.swift
// FundTransferApp
//
// Created by Anik on 24/9/20.
//
import SwiftUI
struct CardView: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25.0)
.fill(Color.cardLinear)
.frame(height: 220)
VStack(alignment: .leading, spacing: 15) {
HStack(alignment: .top) {
Text("Hello, Dimest \nBalance")
.font(.system(size: 20, weight: .bold))
Spacer()
Text("P")
.font(.system(size: 30, weight: .heavy))
.italic()
}
Text("$9844.00")
.font(.system(size: 30, weight: .heavy))
ZStack {
RoundedRectangle(cornerRadius: 15)
.frame(height: 50)
HStack {
Text("Your Transaction")
Spacer()
Image(systemName: "chevron.down")
}
.foregroundColor(.black)
.padding(.horizontal)
}
}
.padding(.horizontal)
.foregroundColor(.white)
}
}
}
| 28.115385 | 64 | 0.357729 |
67572168dc204138455d1953f6b46d68e69d89ee | 278 | // 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
{
extension NSData {
struct B<T where g: a {
let start = [Void{
if true {
enum B : a {
class
case c,
| 19.857143 | 87 | 0.723022 |
fb6d8fa5c4c5906769e0a4b4245eb6673681ddcb | 450 | //
// Parser.swift
// MaskIsseoyo
//
// Created by Seungyeon Lee on 2020/03/13.
// Copyright © 2020 Seungyeon Lee. All rights reserved.
//
import Foundation
class Parser {
static let jsonDecoder: JSONDecoder = {
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
jsonDecoder.dateDecodingStrategy = .formatted(DateFormatter.yyyyMMdd)
return jsonDecoder
}()
}
| 22.5 | 77 | 0.68 |
debe9b316e0a66fca3a4f217a6e329022d77d56a | 1,739 | //
// RowingStrokeData.swift
//
//
// Created by Chris Hinkle on 10/3/20.
//
import Foundation
import CBGATT
public struct RowingStrokeData:CharacteristicModel
{
public static let dataLength:Int = 20
public let elapsedTime:C2TimeInterval
public let distance:C2Distance
public let driveLength:C2DriveLength
public let driveTime:C2DriveTime
public let strokeRecoveryTime:C2TimeInterval
public let strokeDistance:C2Distance
public let peakDriveForce:C2DriveForce
public let averageDriveForce:C2DriveForce
public let workPerStroke:C2Work
public let strokeCount:C2StrokeCount
public init( bytes:[UInt8] )
{
elapsedTime = C2TimeInterval( timeWithLow:UInt32( bytes[ 0 ] ), mid:UInt32( bytes[ 1 ] ), high:UInt32( bytes[ 2 ] ) )
distance = C2Distance( distanceWithLow:UInt32( bytes[ 3 ] ), mid:UInt32( bytes[ 4 ] ), high:UInt32( bytes[ 5 ] ) )
driveLength = C2DriveLength( driveLengthWithLow:bytes[6 ] )
driveTime = C2DriveTime( timeWithLow:UInt32( bytes[ 7 ] ), mid:0, high:0 )
strokeRecoveryTime = C2TimeInterval( timeWithLow:UInt32( bytes[ 8 ] ), mid:UInt32( bytes[ 9 ] ), high:0 )
strokeDistance = C2Distance( distanceWithLow:UInt32( bytes[ 10 ] ), mid:UInt32( bytes[ 11 ] ), high:0 )
peakDriveForce = C2DriveForce( driveForceWithLow:UInt16( bytes[ 12 ] ), high:UInt16( bytes[ 13 ] ) )
averageDriveForce = C2DriveForce( driveForceWithLow:UInt16( bytes[ 14 ] ), high:UInt16( bytes[ 15 ] ) )
workPerStroke = C2Work( workWithLow:UInt16( bytes[ 16 ] ), high:UInt16( bytes[ 17 ] ) )
strokeCount = C2StrokeCount( strokeCountWithLow:UInt16( bytes[ 18 ] ), high:UInt16( bytes[ 19 ] ) )
}
}
| 41.404762 | 125 | 0.683151 |
768a7cead2f3e1517d400fb42fcdba424d7d4987 | 745 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of HDF5Kit. The full HDF5Kit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
import HDF5Kit
func tempFilePath() -> String {
return "/tmp/\(UUID()).hdf"
}
func createFile(_ filePath: String) -> File {
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
return file
}
func openFile(_ filePath: String) -> File {
guard let file = File.open(filePath, mode: .readOnly) else {
fatalError("Failed to open file")
}
return file
}
| 27.592593 | 77 | 0.691275 |
64faecc6eb8f3875cd897dd9287ab71db6eeafe1 | 2,032 | //
// Automat
//
// Copyright (c) 2019 Automat Berlin GmbH - https://automat.berlin/
//
// 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 Intents
extension NSUserActivity {
var startCallHandle: String? {
if let interaction = interaction,
let startCallIntent = interaction.intent as? INStartAudioCallIntent,
let contact = startCallIntent.contacts?.first {
return contact.personHandle?.value
}
if let interaction = interaction,
let startCallIntent = interaction.intent as? INStartVideoCallIntent,
let contact = startCallIntent.contacts?.first {
return contact.personHandle?.value
}
return nil
}
var isVideoIntent: Bool {
if let interaction = interaction,
// swiftlint:disable:next unused_optional_binding
let _ = interaction.intent as? INStartVideoCallIntent {
return true
}
return false
}
}
| 36.945455 | 81 | 0.704232 |
3989c782fc59704ca61c5e58af0e7102c092f065 | 1,045 | //
// YKTabBarVC.swift
// dy
//
// Created by Eric.Wu on 17/1/10.
// Copyright © 2017年 eric. All rights reserved.
//
import UIKit
class YKTabBarVC: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVCs(vc: YKHomeViewController(), title:"首页", imageName: "btn_home_")
addChildVCs(vc: YKLiveViewController(), title:"直播", imageName: "btn_column_")
addChildVCs(vc: YKFollowViewController(), title:"关注", imageName: "btn_live_")
addChildVCs(vc: YKProfileViewController(), title:"我的", imageName: "btn_user_")
}
}
extension YKTabBarVC{
fileprivate func addChildVCs(vc:UIViewController,title:String,imageName:String){
vc.title = title
vc.tabBarItem.image = UIImage(named: imageName + "normal")
vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")
// vc.tabBarItem.title = "skdsk"
let nav = UINavigationController(rootViewController:vc)
addChildViewController(nav)
}
}
| 27.5 | 86 | 0.661244 |
1c43b9b45eefe5ffda77518b7d703f91c650032c | 7,214 | //******************************************************************************
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//==============================================================================
/// SyncStorage
/// A synchronous host memory element storage buffer
public final class CpuStorage: StorageBuffer {
// StorageBuffer protocol properties
public let alignment: Int
public let byteCount: Int
public let id: Int
public let isReadOnly: Bool
public let isReference: Bool
public var name: String
//--------------------------------------------------------------------------
// implementation properties
// host storage buffer
public let hostBuffer: UnsafeMutableRawBufferPointer
//--------------------------------------------------------------------------
// init(type:count:name:
@inlinable public init<Element>(
storedType: Element.Type,
count: Int,
name: String
) {
assert(MemoryLayout<Element>.size != 0,
"type: \(Element.self) is size 0")
self.name = name
alignment = MemoryLayout<Element>.alignment
byteCount = MemoryLayout<Element>.size * count
id = Context.nextBufferId
isReadOnly = false
isReference = false
hostBuffer = UnsafeMutableRawBufferPointer.allocate(
byteCount: byteCount,
alignment: alignment)
#if DEBUG
diagnostic("\(allocString) \(diagnosticName) " +
"\(Element.self)[\(count)]", categories: .dataAlloc)
#endif
}
//--------------------------------------------------------------------------
/// `init(storedElement:name:
public convenience init<Element>(storedElement: Element, name: String) {
// TODO: change to data member to avoid heap alloc
self.init(storedType: Element.self, count: 1, name: name)
hostBuffer.bindMemory(to: Element.self)[0] = storedElement
}
//--------------------------------------------------------------------------
// init(other:queue:
@inlinable public init(copying other: CpuStorage, using queue: DeviceQueue){
alignment = other.alignment
byteCount = other.byteCount
id = Context.nextBufferId
isReadOnly = other.isReadOnly
isReference = other.isReference
name = other.name
if isReference {
hostBuffer = other.hostBuffer
} else {
hostBuffer = UnsafeMutableRawBufferPointer.allocate(
byteCount: other.byteCount,
alignment: other.alignment)
hostBuffer.copyMemory(from: UnsafeRawBufferPointer(other.hostBuffer))
}
}
//--------------------------------------------------------------------------
// init(buffer:name:
@inlinable public init<Element>(
referenceTo buffer: UnsafeBufferPointer<Element>,
name: String
) {
alignment = MemoryLayout<Element>.alignment
byteCount = MemoryLayout<Element>.size * buffer.count
let buff = UnsafeMutableBufferPointer(mutating: buffer)
self.hostBuffer = UnsafeMutableRawBufferPointer(buff)
self.id = Context.nextBufferId
self.isReadOnly = true
self.isReference = true
self.name = name
#if DEBUG
diagnostic("\(referenceString) \(diagnosticName) " +
"\(Element.self)[\(buffer.count)]", categories: .dataAlloc)
#endif
}
//--------------------------------------------------------------------------
// init(type:buffer:name:
@inlinable public init<Element>(
referenceTo buffer: UnsafeMutableBufferPointer<Element>,
name: String
) {
alignment = MemoryLayout<Element>.alignment
byteCount = MemoryLayout<Element>.size * buffer.count
self.hostBuffer = UnsafeMutableRawBufferPointer(buffer)
self.id = Context.nextBufferId
self.isReadOnly = false
self.isReference = true
self.name = name
#if DEBUG
diagnostic("\(referenceString) \(diagnosticName) " +
"\(Element.self)[\(buffer.count)]", categories: .dataAlloc)
#endif
}
//--------------------------------------------------------------------------
// streaming
@inlinable
public init<S, Stream>(block shape: S, bufferedBlocks: Int, stream: Stream)
where S: TensorShape, Stream: BufferStream
{
fatalError()
}
//--------------------------------------------------------------------------
// deinit
@inlinable deinit {
if !isReference {
hostBuffer.deallocate()
#if DEBUG
diagnostic("\(releaseString) \(diagnosticName) ",
categories: .dataAlloc)
#endif
}
}
//--------------------------------------------------------------------------
// read
@inlinable public func read<Element>(
type: Element.Type,
at index: Int,
count: Int
) -> UnsafeBufferPointer<Element> {
// advance to typed starting position
let start = hostBuffer.baseAddress!
.bindMemory(to: Element.self, capacity: count)
.advanced(by: index)
// return read only buffer pointer
return UnsafeBufferPointer(start: start, count: count)
}
//--------------------------------------------------------------------------
// read
@inlinable public func read<Element>(
type: Element.Type,
at index: Int,
count: Int,
using queue: DeviceQueue
) -> UnsafeBufferPointer<Element> {
read(type: type, at: index, count: count)
}
//--------------------------------------------------------------------------
// readWrite
@inlinable public func readWrite<Element>(
type: Element.Type,
at index: Int,
count: Int
) -> UnsafeMutableBufferPointer<Element> {
// advance to typed starting position
let start = hostBuffer.baseAddress!
.bindMemory(to: Element.self, capacity: count)
.advanced(by: index)
// return read/write buffer pointer
return UnsafeMutableBufferPointer(start: start, count: count)
}
//--------------------------------------------------------------------------
// readWrite
@inlinable public func readWrite<Element>(
type: Element.Type,
at index: Int,
count: Int,
using queue: DeviceQueue
) -> UnsafeMutableBufferPointer<Element> {
readWrite(type: type, at: index, count: count)
}
}
| 35.536946 | 81 | 0.523843 |
09132943a8328b1084e3a986febff47c3bce2be9 | 744 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "PayseraBlacklistSDK",
platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)],
products: [
.library(name: "PayseraBlacklistSDK", targets: ["PayseraBlacklistSDK"]),
],
dependencies: [
.package(
name: "PayseraCommonSDK",
url: "https://github.com/paysera/swift-lib-common-sdk",
.exact("4.2.0")
)
],
targets: [
.target(
name: "PayseraBlacklistSDK",
dependencies: ["PayseraCommonSDK"]
),
.testTarget(
name: "PayseraBlacklistSDKTests",
dependencies: ["PayseraBlacklistSDK"]
),
]
)
| 26.571429 | 80 | 0.551075 |
9cc9b8473b1abae25ec932b99d410ae1b3c8ed89 | 12,739 | //
// RecordFilterViewController.swift
// Bank
//
// Created by Koh Ryu on 16/1/20.
// Copyright © 2016年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
import SwiftDate
import Alamofire
import PromiseKit
import URLNavigator
import MBProgressHUD
import PullToRefresh
public enum DataType: Int {
/// 积分明细
case point
/// 银行卡明细
case bank
/// 还款明细
case debt
}
class RecordFilterViewController: BaseViewController {
@IBOutlet weak var calendar2ImageView: UIImageView!
@IBOutlet weak var calendar1ImageView: UIImageView!
@IBOutlet fileprivate weak var startTextField: UITextField!
@IBOutlet fileprivate weak var endTextField: UITextField!
@IBOutlet fileprivate weak var tableView: UITableView!
@IBOutlet fileprivate weak var pickerView: UIDatePicker!
fileprivate lazy var noneView: NoneView = { return NoneView(frame: self.tableView.bounds, type: .other)}()
fileprivate var toolBar: InputAccessoryToolbar!
var filterType: DetailActionType?
var type: BalanceStatementType = .cardBill
var cardID: String?
var dataType: DataType = .bank
fileprivate var datas: [TransactionDetail] = []
fileprivate var startTime: Date?
fileprivate var endTime: Date?
fileprivate var pointArray: [PointObject] = []
fileprivate var repayments: [Repayment] = []
fileprivate var currentPage: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
startTextField.delegate = self
endTextField.delegate = self
pickerView.maximumDate = Date()
startTextField.setValue(UIColor.white.withAlphaComponent(0.5), forKeyPath: "_placeholderLabel.textColor")
endTextField.setValue(UIColor.white.withAlphaComponent(0.5), forKeyPath: "_placeholderLabel.textColor")
setupTableView()
setupCondition()
addPullToRefresh()
}
deinit {
if let tableView = tableView {
if let bottomRefresh = tableView.bottomPullToRefresh {
tableView.removePullToRefresh(bottomRefresh)
}
}
}
fileprivate func addPullToRefresh() {
let bottomRefresh = PullToRefresh(position: .bottom)
tableView.addPullToRefresh(bottomRefresh) { [weak self] in
if self?.dataType == .bank {
self?.requestRecordData((self?.currentPage ?? 1) + 1)
} else if self?.dataType == .point {
self?.requestPointData((self?.currentPage ?? 1) + 1)
} else {
self?.requesDebtData((self?.currentPage ?? 1) + 1)
}
self?.tableView.endRefreshing(at: .bottom)
}
}
func setupTableView() {
if dataType == .bank {
tableView.register(R.nib.accountTableViewCell)
} else if dataType == .point {
tableView.register(R.nib.integralDetailMenuTableViewCell)
} else {
tableView.register(R.nib.detailTableViewCell)
}
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView()
tableView.configBackgroundView()
}
func setupCondition() {
toolBar = R.nib.inputAccessoryToolbar.firstView(owner: self, options: nil)
toolBar.doneHandleBlock = {
if self.startTextField.isFirstResponder {
self.startTextField.text = self.pickerView.date.toString("yyyy-MM-dd")
self.startTime = self.pickerView.date
} else if self.endTextField.isFirstResponder {
self.endTextField.text = self.pickerView.date.toString("yyyy-MM-dd")
self.endTime = self.pickerView.date
}
self.view.endEditing(true)
}
toolBar.cancelHandleBlock = {
self.view.endEditing(true)
}
startTextField.inputView = pickerView
startTextField.inputAccessoryView = toolBar
endTextField.inputView = pickerView
endTextField.inputAccessoryView = toolBar
guard let type = filterType else {
return
}
switch type {
case .filter3Month:
endTextField.text = Date().toString("yyyy-MM-dd")
startTextField.text = 3.months.ago()?.toString("yyyy-MM-dd")
endTime = Date()
startTime = 3.months.ago()
case .filterMonth:
endTextField.text = Date().toString("yyyy-MM-dd")
startTextField.text = 1.months.ago()?.toString("yyyy-MM-dd")
endTime = Date()
startTime = 1.months.ago()
case .filterWeek:
endTextField.text = Date().toString("yyyy-MM-dd")
startTextField.text = 7.days.ago()?.toString("yyyy-MM-dd")
endTime = Date()
startTime = 7.days.ago()
default:
break
}
}
@IBAction func doneHandle() {
// TODO: record filter
if dataType == .bank {
requestRecordData()
} else if dataType == .point {
requestPointData()
} else {
requesDebtData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
calendar1ImageView.image = UIImage(named: startTextField.text == "" ? "btn_calendar1" : "btn_calendar2")
calendar2ImageView.image = UIImage(named: endTextField.text == "" ? "btn_calendar1" : "btn_calendar2")
}
}
// MARK: - Request
extension RecordFilterViewController {
/// 请求银行卡明细
func requestRecordData(_ page: Int = 1) {
let parameter = BankCardParameter()
parameter.cardID = cardID
parameter.startTime = startTime
parameter.endTime = endTime
parameter.page = page
parameter.perPage = 20
let req: Promise<BankCardTransformDetailListData> = handleRequest(Router.endpoint( BankCardPath.bill, param: parameter))
req.then { (value) -> Void in
if let items = value.data?.items {
self.currentPage = page
if self.currentPage == 1 {
self.datas = items
} else {
self.datas.append(contentsOf: items)
}
self.tableView.reloadData()
}
if self.datas.isEmpty {
self.tableView.tableFooterView = self.noneView
} else {
self.tableView.tableFooterView = UIView()
}
}.catch { error in
guard let err = error as? AppError else {
return
}
MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription)
}
}
/// 请求积分明细
func requestPointData(_ page: Int = 1) {
MBProgressHUD.loading(view: view)
validDate(page).then { (param) -> Promise<PointObjectListData> in
let req: Promise<PointObjectListData> = handleRequest(Router.endpoint( MallPath.pointEarnList, param: param))
return req
}.then { value -> Void in
if value.isValid {
if let items = value.data?.items {
self.currentPage = page
if self.currentPage == 1 {
self.pointArray = items
} else {
self.pointArray.append(contentsOf: items)
}
self.tableView.reloadData()
}
}
if self.pointArray.isEmpty {
self.tableView.tableFooterView = self.noneView
} else {
self.tableView.tableFooterView = UIView()
}
}.always {
MBProgressHUD.hide(for: self.view, animated: true)
}.catch { (error) in
if let err = error as? AppError {
MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription)
}
}
}
fileprivate func validDate(_ page: Int) -> Promise<MallParameter> {
return Promise { fulfill, reject in
let count = startTime != nil && endTime != nil
switch count {
case true:
let param = MallParameter()
param.page = page
param.startTime = startTime
param.endTime = endTime
fulfill(param)
case false:
let error = AppError(code: ValidInputsErrorCode.empty, msg: nil)
reject(error)
}
}
}
/**
请求还款明细数据
*/
func requesDebtData(_ page: Int = 1) {
MBProgressHUD.loading(view: view)
let param = MallParameter()
param.page = page
param.startTime = startTime
param.endTime = endTime
let req: Promise<RepaymentListData> = handleRequest(Router.endpoint( EAccountPath.creditBillHistory, param: param))
req.then { (value) -> Void in
if value.isValid {
if let repayment = value.data?.items {
self.currentPage = page
if self.currentPage == 1 {
self.repayments = repayment
} else {
self.repayments.append(contentsOf: repayment)
}
}
self.tableView.reloadData()
}
if self.repayments.isEmpty {
self.tableView.tableFooterView = self.noneView
} else {
self.tableView.tableFooterView = UIView()
}
}.always {
MBProgressHUD.hide(for: self.view, animated: true)
}.catch { (error) in
if let err = error as? AppError {
MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription)
}
}
}
}
// MARK: - UITextFieldDelegate
extension RecordFilterViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == startTextField {
calendar1ImageView.image = UIImage(named: startTextField.text == "" ? "btn_calendar1" : "btn_calendar2")
} else {
calendar2ImageView.image = UIImage(named: endTextField.text == "" ? "btn_calendar1" : "btn_calendar2")
}
}
}
// MARK: Table View Data Source
extension RecordFilterViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if dataType == .bank {
return datas.count
} else if dataType == .point {
return pointArray.count
} else {
return repayments.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if dataType == .bank {
guard let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.accountTableViewCell, for: indexPath) else {
return UITableViewCell()
}
cell.configBalanceStatement(datas[indexPath.row])
return cell
} else if dataType == .point {
guard let cell: IntegralDetailMenuTableViewCell = tableView.dequeueReusableCell(withIdentifier: R.nib.integralDetailMenuTableViewCell, for: indexPath) else {
return UITableViewCell()
}
cell.conforInfo(pointArray[indexPath.row])
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.detailTableViewCell, for: indexPath) else {
return UITableViewCell()
}
cell.configInfo(self.repayments[indexPath.row])
return cell
}
}
}
// MARK: - UITableViewDelegate
extension RecordFilterViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 13.0
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
}
| 36.293447 | 169 | 0.584583 |
c11e731e6d9bd369956148dc51f54cd88db51707 | 719 | //
// MainTabBarController.swift
// NYCWifi
//
// Created by Pritesh Nadiadhara on 3/1/21.
//
import UIKit
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let mapVC = MapViewController()
//TODO: - UIImage named wifi update
mapVC.tabBarItem = UITabBarItem(title: "Map", image: UIImage(named: "Wifi"), tag: 0)
let savedVC = SavedViewController()
//TODO: - UIImage named wifi update
savedVC.tabBarItem = UITabBarItem(title: "Saved", image: UIImage(named: "Saved"), tag: 1)
let tabBarLists = [mapVC, savedVC]
viewControllers = tabBarLists.map(UINavigationController.init)
}
}
| 23.966667 | 97 | 0.652295 |
168e5d51f425ce3e8e3ad9b907550e992f828a0b | 541 | //
// MainCell.swift
// PDStrategy
//
// Created by Pavel Deminov on 04/11/2017.
// Copyright © 2017 Pavel Deminov. All rights reserved.
//
import UIKit
class MainCell: PDTableViewCell {
var titleLabel: PDTitleLabel!
override func setup() {
selectionStyle = .none
weak var wSelf = self
TitleBuilder.addTitle(to: contentView, with: { (titleLabel) in
wSelf?.titleLabel = titleLabel;
})
}
override func updateUI() {
titleLabel.text = itemInfo?.pdTitle
}
}
| 20.807692 | 70 | 0.617375 |
dd141cacbe6c43e8f85eca3144acdfd53794f7f3 | 560 | //
// Log.swift
// DLogger
//
// Created by Administrator on 13/02/18.
// Copyright © 2018 Order of the Light. All rights reserved.
//
import Foundation
import MBProgressHUD
public class Log{
public func dLog(_ str : String){
let topView = UIApplication.shared.keyWindow?.rootViewController?.view
print("Cocoapod --- >>\(str)")
MBProgressHUD.showAdded(to: topView!, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
MBProgressHUD.hide(for: topView!, animated: true)
}
}
}
| 25.454545 | 78 | 0.644643 |
0816caccce37e9a21516d289930376a9394ef1c1 | 946 | //
// ProtobufSampleTests.swift
// ProtobufSampleTests
//
// Created by Kenta Kudo on 2016/11/30.
//
//
import XCTest
@testable import ProtobufSample
class ProtobufSampleTests: 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.
}
}
}
| 25.567568 | 111 | 0.635307 |
eda71507814c3c88019626898d6580b8cc314ff8 | 2,897 | //
// SARequestBuilder.swift
// SampleApp
//
// Created by Kunal Kumar on 2020-10-07.
//
import Foundation
/// Protocol to design a new URL Request.
public protocol RequestBuilder {
/// Building a request with a URL
func buildURLRequest(withURL url: URL) -> URLRequest
/// Building a request with a SAURLBuilder and parameters.
func buildURLRequest<T: SAURLBuilder>(withURLBuilder urlBuilder: T, andParameters parameters: [String: String]) throws -> URLRequest
}
/// Error thrown during request building.
public enum BuilderError: Error {
case unableToResolveURL(URL)
case unableBuildURL(message: String)
}
public class NetworkRequestBuilder: RequestBuilder {
/**
Building a request with a URL
- Parameters:
- url: The URL for the request.
- Returns: URLRequest.
*/
public func buildURLRequest(withURL url: URL) -> URLRequest {
return URLRequest(url: url,
cachePolicy: URLRequest.CachePolicy.reloadRevalidatingCacheData,
timeoutInterval: 30)
}
/**
Building a request with a LDURLBuilder and parameters.
- Parameters:
- withURLBuilder: The type conforming to SAURLBuilder.
- andParameters: The parameters for request.
- Returns: URLRequest.
*/
public func buildURLRequest<T: SAURLBuilder>(withURLBuilder urlBuilder: T, andParameters parameters: [String: String]) throws -> URLRequest {
var components = URLComponents()
if let httpMethod = urlBuilder.httpMethod {
components.scheme = httpMethod.rawValue
}
components.host = SANetworkConstant.baseURL
components.path = urlBuilder.endPoint
var queryParams: [String: String] = parameters
queryParams[SANetworkConstant.apiParameterKey] = SANetworkConstant.apiKey
var queryItems = [URLQueryItem]()
for key in queryParams.keys.sorted() {
guard let param = queryParams[key] else { continue }
queryItems.append(URLQueryItem(name: key, value: param))
}
components.queryItems = queryItems
guard let localUrl = components.url else {
let errorMessage = components.queryItems?.map { String(describing: $0) }.joined(separator: ", ") ?? ""
throw BuilderError.unableBuildURL(message: "query item \(errorMessage)")
}
var urlrequest = URLRequest(url: localUrl,
cachePolicy: URLRequest.CachePolicy.reloadRevalidatingCacheData,
timeoutInterval: TimeInterval(SANetworkConstant.timeout))
if let requestType = urlBuilder.requestType {
urlrequest.httpMethod = requestType.rawValue
}
return urlrequest
}
}
| 33.686047 | 145 | 0.633069 |
1cdfff5742410d5cfba29ba0ad09dfc58d32d255 | 121 | import XCTest
import WebBrowserTests
var tests = [XCTestCaseEntry]()
tests += WebBrowserTests.allTests()
XCTMain(tests) | 17.285714 | 35 | 0.793388 |
757b061a17ccd9c7ba4f9c403ebd764c0ca289a3 | 6,654 | import XCTest
@testable import DJiRData
class _JSONGenericUnkeyedDecodingContainerTests: XCTestCase {
enum TwoKeys: String, CodingKey {
case aKey = "1"
case notherKey = "2"
}
var emptyModel: JSONGenericModel {
.init(m: [:], d: [])
}
var notSupportedContainer: _JSONGenericUnkeyedDecodingContainer = {
.init(data: .init(m: [:], d: []), codingPath: [])
}()
// MARK: - Init
func testInit_CodingPath_IsSet() {
let codingPath: [CodingKey] = [TwoKeys.aKey, TwoKeys.notherKey]
let container = _JSONGenericUnkeyedDecodingContainer(data: emptyModel, codingPath: codingPath)
let comparableCodingPath = codingPath.map { $0.stringValue }
let comparableContainerCodingPath = container.codingPath.map { $0.stringValue }
XCTAssertEqual(comparableContainerCodingPath, comparableCodingPath)
}
func testInit_Count_IsSet() {
let data = JSONGenericModel(
m: [TwoKeys.aKey.stringValue : "Irrelevant name of field"],
d: [[TwoKeys.aKey.stringValue : JSONGenericModel.Value(stringValue: "A Value")]]
)
let container = _JSONGenericUnkeyedDecodingContainer(data: data, codingPath: [])
XCTAssertEqual(container.count, 1)
}
func testInit_IsAtEnd_IsFalse() {
let data = JSONGenericModel(
m: [TwoKeys.aKey.stringValue : "Irrelevant name of field"],
d: [[TwoKeys.aKey.stringValue : JSONGenericModel.Value(stringValue: "A Value")]]
)
let container = _JSONGenericUnkeyedDecodingContainer(data: data, codingPath: [])
XCTAssertFalse(container.isAtEnd)
}
func testInit_IsAtEnd_IsTrueWithEmptyModel() {
let container = _JSONGenericUnkeyedDecodingContainer(data: emptyModel, codingPath: [])
XCTAssertTrue(container.isAtEnd)
}
func testInit_CurrentIndex_IsZero() {
let container = _JSONGenericUnkeyedDecodingContainer(data: emptyModel, codingPath: [])
XCTAssertEqual(container.currentIndex, 0)
}
// MARK: - Decode
func testDecode_ArrayOfKeyed() throws {
struct Keyed: Decodable {
let aValue: String
let notherValue: String
enum CodingKeys: String, CodingKey {
case aValue = "1"
case notherValue = "2"
}
}
let data = JSONGenericModel(
m: [
TwoKeys.aKey.stringValue: "Irrelevant name of field",
TwoKeys.notherKey.stringValue: "Irrelevant name of field"
],
d: [
[
TwoKeys.aKey.stringValue: JSONGenericModel.Value(stringValue: "Hello"),
TwoKeys.notherKey.stringValue: JSONGenericModel.Value(stringValue: "World!")
]
]
)
var container = _JSONGenericUnkeyedDecodingContainer(data: data, codingPath: [])
let result = try container.decode([Keyed].self)
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result[0].aValue, "Hello")
XCTAssertEqual(result[0].notherValue, "World!")
}
// MARK: - Not Suported
func testNotSupported_DecodeNil() {
XCTAssertThrowsError(try notSupportedContainer.decodeNil())
}
func testNotSupported_DecodeBool() {
XCTAssertThrowsError(try notSupportedContainer.decode(Bool.self))
}
func testNotSupported_DecodeFloat() {
XCTAssertThrowsError(try notSupportedContainer.decode(Float.self))
}
func testNotSupported_DecodeInt8() {
XCTAssertThrowsError(try notSupportedContainer.decode(Int8.self))
}
func testNotSupported_DecodeInt16() {
XCTAssertThrowsError(try notSupportedContainer.decode(Int16.self))
}
func testNotSupported_DecodeInt32() {
XCTAssertThrowsError(try notSupportedContainer.decode(Int32.self))
}
func testNotSupported_DecodeInt64() {
XCTAssertThrowsError(try notSupportedContainer.decode(Int64.self))
}
func testNotSupported_DecodeUInt() {
XCTAssertThrowsError(try notSupportedContainer.decode(UInt.self))
}
func testNotSupported_DecodeUInt8() {
XCTAssertThrowsError(try notSupportedContainer.decode(UInt8.self))
}
func testNotSupported_DecodeUInt16() {
XCTAssertThrowsError(try notSupportedContainer.decode(UInt16.self))
}
func testNotSupported_DecodeUInt32() {
XCTAssertThrowsError(try notSupportedContainer.decode(UInt32.self))
}
func testNotSupported_DecodeUInt64() {
XCTAssertThrowsError(try notSupportedContainer.decode(UInt64.self))
}
func testNotSupported_DecodeIfPresentBool() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Bool.self))
}
func testNotSupported_DecodeIfPresentFloat() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Float.self))
}
func testNotSupported_DecodeIfPresentInt8() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Int8.self))
}
func testNotSupported_DecodeIfPresentInt16() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Int16.self))
}
func testNotSupported_DecodeIfPresentInt32() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Int32.self))
}
func testNotSupported_DecodeIfPresentInt64() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(Int64.self))
}
func testNotSupported_DecodeIfPresentUInt() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(UInt.self))
}
func testNotSupported_DecodeIfPresentUInt8() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(UInt8.self))
}
func testNotSupported_DecodeIfPresentUInt16() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(UInt16.self))
}
func testNotSupported_DecodeIfPresentUInt32() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(UInt32.self))
}
func testNotSupported_DecodeIfPresentUInt64() {
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(UInt64.self))
}
func testNotSupported_DecodeIfPresentT() {
struct ADecodable: Decodable {
let aValue: Int
}
XCTAssertThrowsError(try notSupportedContainer.decodeIfPresent(ADecodable.self))
}
}
| 31.386792 | 102 | 0.664112 |
28ad02fb2ea8eeebc3f92802c8bdb3407e9758ff | 563 | //
// CWTextMessageObject.swift
// CWWeChat
//
// Created by chenwei on 2017/3/26.
// Copyright © 2017年 chenwei. All rights reserved.
//
import UIKit
class CWTextMessageBody: NSObject, CWMessageBody {
weak var message: CWMessage?
/// 消息体类型
var type: CWMessageType = .text
/// 文本内容
var text: String
init(text: String) {
self.text = text
}
}
extension CWTextMessageBody {
var messageEncode: String {
return text
}
func messageDecode(string: String) {
self.text = string
}
}
| 16.558824 | 51 | 0.612789 |
624c3f988a335eced383cd0031759ea28a504987 | 674 | //
// Visibility.swift
// Puyopuyo
//
// Created by Jrwong on 2019/6/27.
//
import Foundation
public enum Visibility: CaseIterable, Outputing, CustomStringConvertible {
public typealias OutputType = Visibility
case visible // calculate and visible
case invisible // calculate and invisible
case free // non calculate and visible
case gone // non calculate and invisible
public var description: String {
switch self {
case .visible:
return "visible"
case .invisible:
return "invisible"
case .free:
return "free"
case .gone:
return "gone"
}
}
}
| 21.741935 | 74 | 0.611276 |
21186cd4acfb4c3aa149fde2534ce1ed60ea16bd | 1,060 | import blend2d
/// Creates a pointer reference to a given value and invokes a given closure
/// with, passing a nil pointer, in case 'value' itself is nil.
///
/// Used to provide nullable pointers to C functions that use them as 'nullable
/// struct references'.
@inlinable
func withUnsafeNullablePointer<T, Result>(to value: T?, _ closure: (UnsafePointer<T>?) -> Result) -> Result {
return _withUnsafeNullablePointer(to: value, closure)
}
@inlinable
@discardableResult
func withUnsafeNullablePointer<T>(to value: T?, _ closure: (UnsafePointer<T>?) -> BLResult) -> BLResult {
return _withUnsafeNullablePointer(to: value, closure)
}
// Used to allow defining two signatures for withUnsafeNullablePointer, one with
// `BLResult` being a discardable result
@inlinable
func _withUnsafeNullablePointer<T, Result>(to value: T?, _ closure: (UnsafePointer<T>?) -> Result) -> Result {
if let value = value {
return withUnsafePointer(to: value) { pointer in
closure(pointer)
}
} else {
return closure(nil)
}
}
| 34.193548 | 110 | 0.707547 |
e2a6bed8d0b6cdac9036761588ab597e1c84dba1 | 1,669 | //
// UIImageView+Extension.swift
// NAExtensions
//
// Created by Nitin A on 22/01/20.
// Copyright © 2020 Nitin A. All rights reserved.
//
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
public extension UIImageView {
// download the image from image url string.
func downloadImage(urlString: String) -> Void {
if urlString.isEmpty { return }
self.image = nil
// if image is cached of this url string, fetch the cached image.
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
guard let url = URL(string: urlString) else { return }
// send request to download the image from url.
let request = URLRequest(url: url)
let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in
if error != nil { return }
DispatchQueue.main.async {
let downloadedImage = UIImage(data: data!)
if let image = downloadedImage {
imageCache.setObject(image, forKey: urlString as AnyObject)
self.image = UIImage(data: data!)
}
}
}
dataTask.resume()
}
// to add the black gradient from bottom to top.
func addBlackGradient(frame: CGRect, colors: [UIColor]) {
let gradient = CAGradientLayer()
gradient.frame = frame
gradient.locations = [0.5, 1.0]
gradient.colors = colors.map({$0.cgColor})
self.layer.addSublayer(gradient)
}
}
| 30.907407 | 92 | 0.582984 |
1ccfa5b4dda9a8be207bb5a45ba20c0e4740c9fa | 645 | extension ConnectionPool: Database where Source.Connection: Database {
public func execute(_ query: DatabaseQuery, _ onOutput: @escaping (DatabaseOutput) throws -> ()) -> EventLoopFuture<Void> {
return self.withConnection { $0.execute(query, onOutput) }
}
public func execute(_ schema: DatabaseSchema) -> EventLoopFuture<Void> {
return self.withConnection { $0.execute(schema) }
}
public func withConnection<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> {
return self.withConnection { (conn: Source.Connection) in
return closure(conn)
}
}
}
| 40.3125 | 127 | 0.675969 |
b93881ae1ef63f4ff15033f3fa35f823cc23b2ee | 2,175 | //
// AppDelegate.swift
// Project20
//
// Created by Wbert Castro on 29/07/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.276596 | 285 | 0.755402 |
4bd918682ba628bf1a3da438fa492124556e090b | 1,397 | //
// SubredditPostThubnailView.swift
// RedditOs
//
// Created by Thomas Ricouard on 21/07/2020.
//
import SwiftUI
import Backend
import SDWebImageSwiftUI
struct SubredditPostThumbnailView: View {
let post: SubredditPost
@ViewBuilder
var body: some View {
if let url = post.thumbnailURL {
WebImage(url: url)
.frame(width: 80, height: 60)
.aspectRatio(contentMode: .fit)
.cornerRadius(8)
} else {
ZStack(alignment: .center) {
RoundedRectangle(cornerRadius: 8)
.frame(width: 80, height: 60)
.foregroundColor(Color.gray)
if post.url != nil {
if post.selftext == nil || post.selftext?.isEmpty == true {
Image(systemName: "link")
.imageScale(.large)
.foregroundColor(.blue)
} else {
Image(systemName: "bubble.left.and.bubble.right.fill")
.imageScale(.large)
.foregroundColor(.white)
}
}
}
}
}
}
struct SubredditPostThubnailView_Previews: PreviewProvider {
static var previews: some View {
SubredditPostThumbnailView(post: static_listing)
}
}
| 29.104167 | 79 | 0.506084 |
1d62ae156e2e51a1db6b3660c4637be057c4fb91 | 1,204 | //
// AppDelegate.swift
// XNTodayNews
//
// Created by Dandre on 2018/6/6.
// Copyright © 2018年 Dandre. All rights reserved.
//
import UIKit
import SwiftTheme
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 设置主题颜色
ThemeManager.setTheme(plistName: UserDefaults.standard.bool(forKey: isNight) ? "night_theme" : "default_theme" , path: .mainBundle)
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = XNTabBarController()
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| 23.153846 | 144 | 0.70598 |
e8b803a7ce00c5cb9338c150be46ed67b6c3b1d2 | 1,167 | //
// ConsoleViewController.swift
// MMAutoPost
//
// Created by JC Nolan on 9/22/20.
// Copyright © 2020 JC Nolan. All rights reserved.
//
import Cocoa
class ConsoleViewController: NSViewController, ConsoleManagerViewController {
@IBOutlet weak var consoleScrollView: NSScrollView!
@IBOutlet weak var consoleTextView: NSTextView!
override func viewDidLoad() {
// Set font programatically because an editable text view does not seem to let you set the font :(
if let font = NSFont(name: "Courier", size: 14) {
let attributes = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)
consoleTextView.typingAttributes = attributes as! [NSAttributedString.Key : Any]
consoleTextView.textColor = .white
}
}
public func writeToDebugConsole( _ destinationText:String) { consoleScrollView.documentView!.insertText(destinationText) }
@IBAction func clear(_ sender: Any) { consoleTextView.string = "" }
@IBAction func cancel(_ sender: Any) { ConsoleViewManager.hideConsole() }
}
| 36.46875 | 127 | 0.664096 |
381a2e7559d38e37849d909430882d4c42dd15a5 | 2,081 | import Foundation
import UIKit
import AVFoundation
public class CollectionViewCameraCell: CollectionViewCustomContentCell<CameraView> {
override public func setup() {
super.setup()
selectionElement.isHidden = true
}
}
public final class CameraView: UIView {
public var representedStream: Camera.PreviewStream? = nil {
didSet {
guard representedStream != oldValue else {
return
}
self.setup()
}
}
private var videoLayer: AVCaptureVideoPreviewLayer? {
didSet {
guard oldValue !== videoLayer else {
return
}
oldValue?.removeFromSuperlayer()
if let newLayer = videoLayer {
self.layer.insertSublayer(newLayer, below: cameraIconImageView.layer)
}
}
}
private lazy var cameraIconImageView: UIImageView = {
let bundle = Bundle(for: CollectionViewCameraCell.self)
let cameraIcon = UIImage(named: "camera_icon", in: bundle, compatibleWith: nil)
return UIImageView(image: cameraIcon)
}()
private func setup() {
self.videoLayer = nil
self.layer.backgroundColor = UIColor.black.cgColor
if let stream = self.representedStream {
stream.queue.async {
let videoLayer = AVCaptureVideoPreviewLayer(session: stream.session)
videoLayer.videoGravity = .resizeAspectFill
DispatchQueue.main.async {
self.videoLayer = videoLayer
}
}
}
if subviews.contains(cameraIconImageView) == false {
addSubview(cameraIconImageView)
}
}
override public func layoutSubviews() {
super.layoutSubviews()
if videoLayer?.frame != self.bounds {
videoLayer?.frame = self.bounds
}
cameraIconImageView.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
public func reset() {
self.representedStream = nil
}
}
| 26.0125 | 87 | 0.593465 |
14ef13f5a9fcd3c480d632fb2567eaa1f36930e4 | 1,181 | //
// ViewController.swift
// AvoidKeyboard
//
// Created by Cesar Bess on 23/02/19.
// Copyright © 2019 Cesar Bess. All rights reserved.
//
import UIKit
import KeyboardAdjustable
class SingleConstraintViewController: UIViewController, KeyboardAdjustable {
var keyboardAdjustingStrategy: KeyboardAdjustingStrategy?
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Register for keyboard notifications
registerForKeyboardNotifications()
// Set your desired strategy to adjust the view when the keyboard appears
self.keyboardAdjustingStrategy = .singleConstraint(constraint: bottomConstraint, originalConstant: bottomConstraint.constant, spaceAboveKeyboard: 20)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Unregister for keyboard notifications
unregisterForKeyboardNotification()
}
}
extension SingleConstraintViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
}
| 28.804878 | 157 | 0.735817 |
d61502fd2c8066b83257a37f7c94dbb429f41658 | 356 | //
// BaseConfig.swift
// Pods
//
// Created by ZhouMin on 2019/8/17.
//
import Foundation
public struct BaseConfig {
/// 请求基本链接
public static var baseAppServiceUrl = ""
/// 请求公共参数
public static var commonParams = Dictionary<String, Any>()
//APP默认分割线颜色
public static var defaultLineColor = "#dae0e5"
}
| 15.478261 | 62 | 0.615169 |
87d45cedb5f9f386ff931367976c45aef6e206d9 | 2,188 | //
// CoinStaticCollectionViewCell.swift
// RomanWalk
//
// Created by Somogyi Balázs on 2020. 04. 15..
// Copyright © 2020. Somogyi Balázs. All rights reserved.
//
import UIKit
class CoinStaticCollectionViewCell: UICollectionViewCell {
static let reuseIdentifier = String(describing: CoinStaticCollectionViewCell.self)
let descriptionLabel = UILabel()
let percentageLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
fatalError()
}
}
extension CoinStaticCollectionViewCell {
func configure() {
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
percentageLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(descriptionLabel)
contentView.addSubview(percentageLabel)
descriptionLabel.font = UIFont.preferredFont(forTextStyle: .body)
descriptionLabel.adjustsFontForContentSizeCategory = true
descriptionLabel.textColor = .black
descriptionLabel.numberOfLines = 0
percentageLabel.font = UIFont.preferredFont(forTextStyle: .title1)
percentageLabel.adjustsFontForContentSizeCategory = true
percentageLabel.textColor = .red
percentageLabel.textAlignment = .center
NSLayoutConstraint.activate([
descriptionLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
descriptionLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 20),
descriptionLabel.topAnchor.constraint(equalTo: contentView.topAnchor),
percentageLabel.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 10),
percentageLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
percentageLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
percentageLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
}
| 37.724138 | 106 | 0.689214 |
7a120175604dd6f00e3200c0eb92cbd1744f9134 | 1,073 | //
// StateBindingExerciseView.swift
// SwiftUITutorial
//
// Created by 1900822 on 2021/6/12.
//
import SwiftUI
struct StateBindingExerciseView: View {
@State private var firstCounter = 1
@State private var secondCounter = 1
@State private var thirdCounter = 1
var body: some View {
VStack(alignment: .center, spacing: 50) {
Text("\(firstCounter + secondCounter + thirdCounter)")
.font(.system(size: 200, weight: .bold, design: .rounded))
.minimumScaleFactor(0.5)
HStack {
CounterButton(counter: $firstCounter, color: .blue, circleSize: 100, fontSize: 60)
CounterButton(counter: $secondCounter, color: .green, circleSize: 100, fontSize: 60)
CounterButton(counter: $thirdCounter, color: .red, circleSize: 100, fontSize: 60)
}
.padding()
}
}
}
struct StateBindingExerciseView_Previews: PreviewProvider {
static var previews: some View {
StateBindingExerciseView()
}
}
| 28.236842 | 100 | 0.61137 |
0e883a362fdf779e4a1e4d8fa70fc779a124956c | 6,266 | //
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(key: DisposeKey) {
abstractMethod()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<E>) {
abstractMethod()
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> SubjectObserverType {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
}
/**
Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
- parameter bufferSize: Maximal number of elements to replay to observer after subscription.
- returns: New instance of replay subject.
*/
public static func create(bufferSize bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/**
Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
number of elements.
*/
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
}
class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
private var _lock = NSRecursiveLock()
// state
private var _disposed = false
private var _stoppedEvent = nil as Event<Element>?
private var _observers = Bag<AnyObserver<Element>>()
func trim() {
abstractMethod()
}
func addValueToBuffer(value: Element) {
abstractMethod()
}
func replayBuffer(observer: AnyObserver<Element>) {
abstractMethod()
}
override func on(event: Event<Element>) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_on(event)
}
func _synchronized_on(event: Event<E>) {
if _disposed {
return
}
if _stoppedEvent != nil {
return
}
switch event {
case .Next(let value):
addValueToBuffer(value)
trim()
_observers.on(event)
case .Error, .Completed:
_stoppedEvent = event
trim()
_observers.on(event)
_observers.removeAll()
}
}
override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
if _disposed {
observer.on(.Error(RxError.Disposed(object: self)))
return NopDisposable.instance
}
let AnyObserver = observer.asObserver()
replayBuffer(AnyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
else {
let key = _observers.insert(AnyObserver)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(disposeKey: DisposeKey) {
if _disposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock(); defer { _lock.unlock() }
_synchronized_dispose()
}
func _synchronized_dispose() {
_disposed = true
_stoppedEvent = nil
_observers.removeAll()
}
}
final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(value: Element) {
_value = value
}
override func replayBuffer(observer: AnyObserver<Element>) {
if let value = _value {
observer.on(.Next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
private var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(value: Element) {
_queue.enqueue(value)
}
override func replayBuffer(observer: AnyObserver<E>) {
for item in _queue {
observer.on(.Next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_queue.dequeue()
}
}
}
final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
} | 24.572549 | 114 | 0.60166 |
eff1e3f9755474c7cd3adce44fea0e10ca81b5f1 | 3,574 | import UIKit
import XCPlayground
import KeychainAccess
var keychain: Keychain
/***************
* Instantiation
***************/
/* for Application Password */
keychain = Keychain(service: "com.example.github-token")
/* for Internet Password */
let URL = NSURL(string: "https://github.com")!
keychain = Keychain(server: URL, protocolType: .HTTPS)
/**************
* Adding items
**************/
/* subscripting */
keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef"
/* set method */
keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
/*****************
* Obtaining items
*****************/
var token: String?
/* subscripting (automatically convert to String) */
token = keychain["kishikawakatsumi"]
/* get method */
// as String
token = keychain.get("kishikawakatsumi")
token = keychain.getString("kishikawakatsumi")
// as Data
let data = keychain.getData("kishikawakatsumi")
/****************
* Removing items
****************/
/* subscripting */
keychain["kishikawakatsumi"] = nil
/* remove method */
keychain.remove("kishikawakatsumi")
/****************
* Error handling
*****************/
/* set */
if let error = keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") {
println("error: \(error.localizedDescription)")
}
/* get */
// First, get the failable (value or error) object
let failable = keychain.getStringOrError("kishikawakatsumi")
// 1. check the enum state
switch failable {
case .Success:
println("token: \(failable.value)")
case .Failure:
println("error: \(failable.error)")
}
// 2. check the error object
if let error = failable.error {
println("error: \(failable.error)")
} else {
println("token: \(failable.value)")
}
// 3. check the failed property
if failable.failed {
println("error: \(failable.error)")
} else {
println("token: \(failable.value)")
}
/* remove */
if let error = keychain.remove("kishikawakatsumi") {
println("error: \(error.localizedDescription)")
}
/*******************
* Label and Comment
*******************/
keychain = Keychain(server: NSURL(string: "https://github.com")!, protocolType: .HTTPS)
.label("github.com (kishikawakatsumi)")
.comment("github access token")
/***************
* Configuration
***************/
/* for background application */
let background = Keychain(service: "com.example.github-token")
.accessibility(.AfterFirstUnlock)
/* for forground application */
let forground = Keychain(service: "com.example.github-token")
.accessibility(.WhenUnlocked)
/* Sharing Keychain Items */
let shared = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared")
/* Synchronizing Keychain items with iCloud */
let iCloud = Keychain(service: "com.example.github-token")
.synchronizable(true)
/* One-Shot configuration change */
keychain
.accessibility(.AfterFirstUnlock)
.synchronizable(true)
.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
keychain
.accessibility(.WhenUnlocked)
.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
/***********
* Debugging
***********/
/* Display all stored items if print keychain object */
keychain = Keychain(server: NSURL(string: "https://github.com")!, protocolType: .HTTPS)
println("\(keychain)")
/* Obtaining all stored keys */
let keys = keychain.allKeys()
for key in keys {
println("key: \(key)")
}
/* Obtaining all stored items */
let items = keychain.allItems()
for item in items {
println("item: \(item)")
}
| 22.477987 | 94 | 0.653609 |
de4775b5872d1a15d61656a464afa61fdb16d36e | 265 | //
// ColorModel.swift
// SwiftUIWatchTour WatchKit Extension
//
// Created by Craig Clayton on 12/7/19.
// Copyright © 2019 Cocoa Academy. All rights reserved.
//
import Foundation
struct ColorModel: Identifiable {
var id = UUID()
var name: String
}
| 17.666667 | 56 | 0.69434 |
fc0a24e325d0df334af3f87e5a9fb6f75a029103 | 14,680 | //
// DownView.swift
// Down
//
// Created by Rob Phillips on 6/1/16.
// Copyright © 2016 Glazed Donut, LLC. All rights reserved.
//
import WebKit
import Highlightr
#if os(iOS)
import NightNight
#endif
// MARK: - Public API
public typealias DownViewClosure = () -> ()
open class MarkdownView: WKWebView {
/**
Initializes a web view with the results of rendering a CommonMark Markdown string
- parameter frame: The frame size of the web view
- parameter markdownString: A string containing CommonMark Markdown
- parameter openLinksInBrowser: Whether or not to open links using an external browser
- parameter templateBundle: Optional custom template bundle. Leaving this as `nil` will use the bundle included with Down.
- parameter didLoadSuccessfully: Optional callback for when the web content has loaded successfully
- returns: An instance of Self
*/
public init(imagesStorage: URL? = nil, frame: CGRect, markdownString: String, openLinksInBrowser: Bool = true, css: String, templateBundle: Bundle? = nil, didLoadSuccessfully: DownViewClosure? = nil) throws {
self.didLoadSuccessfully = didLoadSuccessfully
if let templateBundle = templateBundle {
self.bundle = templateBundle
} else {
let classBundle = Bundle(for: MarkdownView.self)
let url = classBundle.url(forResource: "DownView", withExtension: "bundle")!
self.bundle = Bundle(url: url)!
}
let userContentController = WKUserContentController()
userContentController.add(HandlerCopyCode(), name: "notification")
#if os(OSX)
userContentController.add(HandlerMouseOver(), name: "mouseover")
userContentController.add(HandlerMouseOut(), name: "mouseout")
#endif
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
super.init(frame: frame, configuration: configuration)
#if os(OSX)
setValue(false, forKey: "drawsBackground")
#else
isOpaque = false
backgroundColor = UIColor.clear
scrollView.backgroundColor = UIColor.clear
#endif
if openLinksInBrowser || didLoadSuccessfully != nil { navigationDelegate = self }
try loadHTMLView(markdownString, css: MarkdownView.getPreviewStyle(), imagesStorage: imagesStorage)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#if os(OSX)
open override func mouseDown(with event: NSEvent) {
guard let vc = ViewController.shared(),
let note = EditTextView.note,
note.container == .encryptedTextPack,
!note.isUnlocked()
else { return }
vc.unLock(notes: [note])
}
#endif
// MARK: - API
/**
Renders the given CommonMark Markdown string into HTML and updates the DownView while keeping the style intact
- parameter markdownString: A string containing CommonMark Markdown
- parameter didLoadSuccessfully: Optional callback for when the web content has loaded successfully
- throws: `DownErrors` depending on the scenario
*/
public func update(markdownString: String, didLoadSuccessfully: DownViewClosure? = nil) throws {
// Note: As the init method takes this callback already, we only overwrite it here if
// a non-nil value is passed in
if let didLoadSuccessfully = didLoadSuccessfully {
self.didLoadSuccessfully = didLoadSuccessfully
}
try loadHTMLView(markdownString, css: "")
}
private func getMathJaxJS() -> String {
if !UserDefaultsManagement.mathJaxPreview {
return String()
}
return """
<script src="js/MathJax-2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ showMathMenu: false, tex2jax: { inlineMath: [ ['$', '$'], ['\\(', '\\)'] ], }, messageStyle: "none", showProcessingMessages: true });
</script>
"""
}
public static func getPreviewStyle(theme: String? = nil) -> String {
var css = String()
if let cssURL = UserDefaultsManagement.markdownPreviewCSS {
if FileManager.default.fileExists(atPath: cssURL.path), let content = try? String(contentsOf: cssURL) {
css = content
}
}
let theme = theme ?? UserDefaultsManagement.codeTheme
var codeStyle = ""
if let hgPath = Bundle(for: Highlightr.self).path(forResource: theme + ".min", ofType: "css") {
codeStyle = try! String.init(contentsOfFile: hgPath)
}
let familyName = UserDefaultsManagement.noteFont.familyName
#if os(iOS)
if #available(iOS 11.0, *) {
if let font = UserDefaultsManagement.noteFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
let fontSize = fontMetrics.scaledFont(for: font).pointSize
let fs = Int(fontSize) - 2
return "body {font: \(fs)px '\(familyName)'; } code, pre {font: \(fs)px Courier New; font-weight: bold; } img {display: block; margin: 0 auto;} \(codeStyle)"
}
}
#endif
let family = familyName ?? "-apple-system"
let margin = Int(UserDefaultsManagement.marginSize)
return "body {font: \(UserDefaultsManagement.fontSize)px '\(family)', '-apple-system'; margin: 0 \(margin)px; } code, pre {font: \(UserDefaultsManagement.codeFontSize)px '\(UserDefaultsManagement.codeFontName)', Courier, monospace, 'Liberation Mono', Menlo;} img {display: block; margin: 0 auto;} \(codeStyle) \(css)"
}
// MARK: - Private Properties
let bundle: Bundle
fileprivate lazy var baseURL: URL = {
return self.bundle.url(forResource: "index", withExtension: "html")!
}()
fileprivate var didLoadSuccessfully: DownViewClosure?
func createTemporaryBundle(pageHTMLString: String) -> URL? {
guard let bundleResourceURL = bundle.resourceURL
else { return nil }
let customCSS = UserDefaultsManagement.markdownPreviewCSS
let webkitPreview = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("wkPreview")
try? FileManager.default.createDirectory(at: webkitPreview, withIntermediateDirectories: true, attributes: nil)
let indexURL = webkitPreview.appendingPathComponent("index.html")
// If updating markdown contents, no need to re-copy bundle.
if !FileManager.default.fileExists(atPath: indexURL.path) {
// Copy bundle resources to temporary location.
do {
let fileList = try FileManager.default.contentsOfDirectory(atPath: bundleResourceURL.path)
for file in fileList {
if customCSS != nil && file == "css" {
continue
}
let tmpURL = webkitPreview.appendingPathComponent(file)
try FileManager.default.copyItem(atPath: bundleResourceURL.appendingPathComponent(file).path, toPath: tmpURL.path)
}
} catch {
print(error)
}
}
if let customCSS = customCSS {
let cssDst = webkitPreview.appendingPathComponent("css")
let styleDst = cssDst.appendingPathComponent("markdown-preview.css", isDirectory: false)
do {
try FileManager.default.createDirectory(at: cssDst, withIntermediateDirectories: false, attributes: nil)
_ = try FileManager.default.copyItem(at: customCSS, to: styleDst)
} catch {
print(error)
}
}
// Write generated index.html to temporary location.
try? pageHTMLString.write(to: indexURL, atomically: true, encoding: .utf8)
return indexURL
}
}
// MARK: - Private API
private extension MarkdownView {
func loadHTMLView(_ markdownString: String, css: String, imagesStorage: URL? = nil) throws {
var htmlString = renderMarkdownHTML(markdown: markdownString)!
if let imagesStorage = imagesStorage {
htmlString = loadImages(imagesStorage: imagesStorage, html: htmlString)
}
var pageHTMLString = try htmlFromTemplate(htmlString, css: css)
pageHTMLString = pageHTMLString.replacingOccurrences(of: "MATH_JAX_JS", with: getMathJaxJS())
let indexURL = createTemporaryBundle(pageHTMLString: pageHTMLString)
if let i = indexURL {
let accessURL = i.deletingLastPathComponent()
loadFileURL(i, allowingReadAccessTo: accessURL)
}
}
private func loadImages(imagesStorage: URL, html: String) -> String {
var htmlString = html
do {
let regex = try NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"")
let results = regex.matches(in: html, range: NSRange(html.startIndex..., in: html))
let images = results.map {
String(html[Range($0.range, in: html)!])
}
for image in images {
var localPath = image.replacingOccurrences(of: "<img src=\"", with: "").dropLast()
guard !localPath.starts(with: "http://") && !localPath.starts(with: "https://") else {
continue
}
let localPathClean = localPath.removingPercentEncoding ?? String(localPath)
let fullImageURL = imagesStorage
let imageURL = fullImageURL.appendingPathComponent(localPathClean)
let webkitPreview = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("wkPreview")
let create = webkitPreview
.appendingPathComponent(localPathClean)
.deletingLastPathComponent()
let destination = webkitPreview.appendingPathComponent(localPathClean)
try? FileManager.default.createDirectory(atPath: create.path, withIntermediateDirectories: true, attributes: nil)
try? FileManager.default.removeItem(at: destination)
try? FileManager.default.copyItem(at: imageURL, to: destination)
var orientation = 0
let url = NSURL(fileURLWithPath: imageURL.path)
if let imageSource = CGImageSourceCreateWithURL(url, nil) {
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
if let orientationProp = imageProperties?[kCGImagePropertyOrientation] as? Int {
orientation = orientationProp
}
}
if localPath.first == "/" {
localPath.remove(at: localPath.startIndex)
}
let imPath = "<img data-orientation=\"\(orientation)\" class=\"fsnotes-preview\" src=\"" + localPath + "\""
htmlString = htmlString.replacingOccurrences(of: image, with: imPath)
}
} catch let error {
print("Images regex: \(error.localizedDescription)")
}
return htmlString
}
func htmlFromTemplate(_ htmlString: String, css: String) throws -> String {
var template = try NSString(contentsOf: baseURL, encoding: String.Encoding.utf8.rawValue)
template = template.replacingOccurrences(of: "DOWN_CSS", with: css) as NSString
#if os(iOS)
if NightNight.theme == .night {
template = template.replacingOccurrences(of: "CUSTOM_CSS", with: "darkmode") as NSString
}
#else
if UserDataService.instance.isDark {
template = template.replacingOccurrences(of: "CUSTOM_CSS", with: "darkmode") as NSString
}
#endif
return template.replacingOccurrences(of: "DOWN_HTML", with: htmlString)
}
}
// MARK: - WKNavigationDelegate
extension MarkdownView: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else { return }
switch navigationAction.navigationType {
case .linkActivated:
decisionHandler(.cancel)
#if os(iOS)
UIApplication.shared.openURL(url)
#elseif os(OSX)
NSWorkspace.shared.open(url)
#endif
default:
decisionHandler(.allow)
}
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
didLoadSuccessfully?()
}
}
#if os(OSX)
class HandlerCopyCode: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
let message = (message.body as! String).trimmingCharacters(in: .whitespacesAndNewlines)
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(message, forType: NSPasteboard.PasteboardType.string)
}
}
class HandlerMouseOver: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
NSCursor.pointingHand.set()
}
}
class HandlerMouseOut: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
NSCursor.arrow.set()
}
}
#endif
#if os(iOS)
import MobileCoreServices
class HandlerCopyCode: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
let message = (message.body as! String).trimmingCharacters(in: .whitespacesAndNewlines)
let pasteboard = UIPasteboard.general
let item = [kUTTypeUTF8PlainText as String : message as Any]
pasteboard.items = [item]
}
}
#endif
| 38.429319 | 325 | 0.627316 |
8f7757a531e95ec3d8bf9c4e33e1d0413318d4d3 | 385 | // RUN: %target-swift-frontend %s -module-name Test -sil-serialize-all -emit-module -emit-module-path - -o /dev/null | %target-sil-opt -enable-sil-verify-all -disable-sil-linking -module-name="Test" | %FileCheck %s
// Check that default witness tables are properly deserialized.
// rdar://problem/29173229
// CHECK: import Swift
public class MyType {
}
public protocol MyProto {
}
| 29.615385 | 214 | 0.727273 |
1a0158b298f47c1ee260a020ae9a995a2c1ceec0 | 1,189 | //
// TodayViewController.swift
// QuizTodayExtension
//
// Created by Tomosuke Okada on 2020/05/22.
//
import Domain
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet private weak var shadowImageView: UIImageView!
private var number = 0
override func viewDidLoad() {
super.viewDidLoad()
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
self.number = RandomPokemonNumberGenrator.generate()
let url = PokemonImageURLGenerator.generateThumbnailURL(from: self.number)
self.shadowImageView.loadShadowImage(with: url, shadowColor: .black) { result in
switch result {
case .success:
completionHandler(NCUpdateResult.newData)
case .failure:
completionHandler(NCUpdateResult.failed)
}
}
}
}
// MARK: - IBAction
extension TodayViewController {
@IBAction private func didTapWidget() {
let url = URL(string: "pokedex://open/pokemon_detail?number=\(self.number)")
extensionContext?.open(url!, completionHandler: nil)
}
}
| 27.022727 | 88 | 0.673675 |
9cc3e5b96cbaaa3aed5d84b957099c5c74d6ba82 | 423 | //
// VehicleStatii+Cmds.swift
// Car
//
// Created by Mikk Rätsep on 08/07/2017.
// Copyright © 2017 High-Mobility GmbH. All rights reserved.
//
import AutoAPI
import Foundation
public extension Car {
func getVehicleStatii(failed: @escaping CommandFailed) {
let bytes = AAVehicleStatus.getVehicleStatus()
print("- Car - get vehicle statii")
sendCommand(bytes, failed: failed)
}
}
| 18.391304 | 61 | 0.673759 |
e488e69f68f1b95d345fd335a75b93ced57ec62b | 319 | //
// UIScreenExt.swift
// Pods
//
// Created by 杨建祥 on 2020/2/1.
//
import UIKit
import QMUIKit
public extension UIScreen {
static var width: CGFloat {
return UIScreen.main.bounds.size.width
}
static var height: CGFloat {
return UIScreen.main.bounds.size.height
}
}
| 14.5 | 47 | 0.617555 |
ab58a704612920e4cea09037524ba57a8e0ffbd1 | 1,356 | //
// AppDelegate.swift
// LandMarkBook
//
// Created by Adem Deliaslan on 10.02.2022.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.648649 | 179 | 0.74705 |
e4b019774f98ca52ea59fdf8df89068eda141d0f | 6,681 | // Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import UIKit
public func text<Object: UITextField>() -> Lens<Object, String?> {
return Lens(
get: { $0.text },
setter: { $0.text = $1 }
)
}
public func attributedText<Object: UITextField>() -> Lens<Object, NSAttributedString?> {
return Lens(
get: { $0.attributedText },
setter: { $0.attributedText = $1 }
)
}
public func textColor<Object: UITextField>() -> Lens<Object, UIColor?> {
return Lens(
get: { $0.textColor },
setter: { $0.textColor = $1 }
)
}
public func font<Object: UITextField>() -> Lens<Object, UIFont?> {
return Lens(
get: { $0.font },
setter: { $0.font = $1 }
)
}
public func textAlignment<Object: UITextField>() -> Lens<Object, NSTextAlignment> {
return Lens(
get: { $0.textAlignment },
setter: { $0.textAlignment = $1 }
)
}
public func borderStyle<Object: UITextField>() -> Lens<Object, UITextField.BorderStyle> {
return Lens(
get: { $0.borderStyle },
setter: { $0.borderStyle = $1 }
)
}
public func defaultTextAttributes<Object: UITextField>() -> Lens<Object, [NSAttributedString.Key : Any]> {
return Lens(
get: { $0.defaultTextAttributes },
setter: { $0.defaultTextAttributes = $1 }
)
}
public func placeholder<Object: UITextField>() -> Lens<Object, String?> {
return Lens(
get: { $0.placeholder },
setter: { $0.placeholder = $1 }
)
}
public func attributedPlaceholder<Object: UITextField>() -> Lens<Object, NSAttributedString?> {
return Lens(
get: { $0.attributedPlaceholder },
setter: { $0.attributedPlaceholder = $1 }
)
}
public func clearsOnBeginEditing<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.clearsOnBeginEditing },
setter: { $0.clearsOnBeginEditing = $1 }
)
}
public func adjustsFontSizeToFitWidth<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.adjustsFontSizeToFitWidth },
setter: { $0.adjustsFontSizeToFitWidth = $1 }
)
}
public func minimumFontSize<Object: UITextField>() -> Lens<Object, CGFloat> {
return Lens(
get: { $0.minimumFontSize },
setter: { $0.minimumFontSize = $1 }
)
}
public func delegate<Object: UITextField>() -> Lens<Object, UITextFieldDelegate?> {
return Lens(
get: { $0.delegate },
setter: { $0.delegate = $1 }
)
}
public func background<Object: UITextField>() -> Lens<Object, UIImage?> {
return Lens(
get: { $0.background },
setter: { $0.background = $1 }
)
}
public func disabledBackground<Object: UITextField>() -> Lens<Object, UIImage?> {
return Lens(
get: { $0.disabledBackground },
setter: { $0.disabledBackground = $1 }
)
}
public func allowsEditingTextAttributes<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.allowsEditingTextAttributes },
setter: { $0.allowsEditingTextAttributes = $1 }
)
}
public func clearButtonMode<Object: UITextField>() -> Lens<Object, UITextField.ViewMode> {
return Lens(
get: { $0.clearButtonMode },
setter: { $0.clearButtonMode = $1 }
)
}
public func leftView<Object: UITextField>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.leftView },
setter: { $0.leftView = $1 }
)
}
public func leftViewMode<Object: UITextField>() -> Lens<Object, UITextField.ViewMode> {
return Lens(
get: { $0.leftViewMode },
setter: { $0.leftViewMode = $1 }
)
}
public func rightView<Object: UITextField>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.rightView },
setter: { $0.rightView = $1 }
)
}
public func rightViewMode<Object: UITextField>() -> Lens<Object, UITextField.ViewMode> {
return Lens(
get: { $0.rightViewMode },
setter: { $0.rightViewMode = $1 }
)
}
public func inputView<Object: UITextField>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.inputView },
setter: { $0.inputView = $1 }
)
}
public func inputAccessoryView<Object: UITextField>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.inputAccessoryView },
setter: { $0.inputAccessoryView = $1 }
)
}
public func clearsOnInsertion<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.clearsOnInsertion },
setter: { $0.clearsOnInsertion = $1 }
)
}
public func autocorrectionType<Object: UITextField>() -> Lens<Object, UITextAutocorrectionType> {
return Lens(
get: { $0.autocorrectionType },
setter: { $0.autocorrectionType = $1 }
)
}
public func spellCheckingType<Object: UITextField>() -> Lens<Object, UITextSpellCheckingType> {
return Lens(
get: { $0.spellCheckingType },
setter: { $0.spellCheckingType = $1 }
)
}
@available(iOS 11.0, *)
public func smartQuotesType<Object: UITextField>() -> Lens<Object, UITextSmartQuotesType> {
return Lens(
get: { $0.smartQuotesType },
setter: { $0.smartQuotesType = $1 }
)
}
@available(iOS 11.0, *)
public func smartDashesType<Object: UITextField>() -> Lens<Object, UITextSmartDashesType> {
return Lens(
get: { $0.smartDashesType },
setter: { $0.smartDashesType = $1 }
)
}
@available(iOS 11.0, *)
public func smartInsertDeleteType<Object: UITextField>() -> Lens<Object, UITextSmartInsertDeleteType> {
return Lens(
get: { $0.smartInsertDeleteType },
setter: { $0.smartInsertDeleteType = $1 }
)
}
public func keyboardType<Object: UITextField>() -> Lens<Object, UIKeyboardType> {
return Lens(
get: { $0.keyboardType },
setter: { $0.keyboardType = $1 }
)
}
public func keyboardAppearance<Object: UITextField>() -> Lens<Object, UIKeyboardAppearance> {
return Lens(
get: { $0.keyboardAppearance },
setter: { $0.keyboardAppearance = $1 }
)
}
public func returnKeyType<Object: UITextField>() -> Lens<Object, UIReturnKeyType> {
return Lens(
get: { $0.returnKeyType },
setter: { $0.returnKeyType = $1 }
)
}
public func enablesReturnKeyAutomatically<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.enablesReturnKeyAutomatically },
setter: { $0.enablesReturnKeyAutomatically = $1 }
)
}
public func isSecureTextEntry<Object: UITextField>() -> Lens<Object, Bool> {
return Lens(
get: { $0.isSecureTextEntry },
setter: { $0.isSecureTextEntry = $1 }
)
}
| 27.158537 | 106 | 0.611884 |
d5ab3e011548c9fc0a457b4159bff6d307cefb5f | 437 | import SwiftUI
import Combine
import JavaScriptCore
final class RnViewModel: ObservableObject, HxContainer {
@Published var children: [HxAnyModel] = []
func update(_ jsValue: JSValue) -> () { }
var view: AnyView { AnyView(RnViewView(model: self)) }
}
struct RnViewView: View {
@ObservedObject var model: RnViewModel
var body: some View {
VStack {
ForEach(model.children) {
$0.view
}
}
}
}
| 17.48 | 56 | 0.659039 |
d743f80fbc80dc39cfcdb7b2a7272dce7bcdbad0 | 362 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "JJFloatingActionButton",
products: [
.library(
name: "JJFloatingActionButton",
targets: ["JJFloatingActionButton"]),
],
targets: [
.target(
name: "JJFloatingActionButton",
path: "Sources")
]
)
| 20.111111 | 49 | 0.569061 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.