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
|
---|---|---|---|---|---|
ffd518d579964be60c9069be313589d986a1fe0c | 223 | //
// TinkerApp.swift
// Shared
//
// Created by Aleksey Kurepin on 20.10.2021.
//
import SwiftUI
@main
struct TinkerApp: App {
var body: some Scene {
WindowGroup {
MainView()
}
}
}
| 12.388889 | 45 | 0.55157 |
f518c63804dedb78abdf4a5b24bb42945e06f8a4 | 1,183 | //
// KACircleCropScrollView.swift
// Circle Crop View Controller
//
// Created by Keke Arif on 21/02/2016.
// Copyright © 2016 Keke Arif. All rights reserved.
//
import UIKit
class KACircleCropScrollView: UIScrollView {
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = false
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.clipsToBounds = false
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
}
//Allow dragging outside of the scroll view bounds
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let excessWidth = (UIScreen.main.bounds.size.width - self.bounds.size.width)/2
let excessHeight = (UIScreen.main.bounds.size.height - self.bounds.size.height)/2
if self.bounds.insetBy(dx: -excessWidth, dy: -excessHeight).contains(point) {
return self
}
return nil
}
}
| 26.886364 | 89 | 0.639053 |
e0ab136c9ad4dccde9bb60ff222ee256e53b7027 | 750 | import XCTest
import PrahaladSwift
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.862069 | 111 | 0.602667 |
e2147399c21b75b3fd5e4a944d150cc3fde01527 | 2,652 | //#-hidden-code
/*
Copyright (C) 2017 IBM. All Rights Reserved.
See LICENSE.txt for this book's licensing information.
*/
import PlaygroundSupport
import UIKit
PlaygroundPage.current.assessmentStatus = .pass(message: nil)
PlaygroundPage.current.needsIndefiniteExecution = true
//#-end-hidden-code
/*:
* Callout(🤖 TJBot Hardware):
In order to complete this exercise, please ensure your TJBot has a microphone and a speaker.
Did you know you can turn TJBot into a chatbot? TJBot has the ability to engage in a back-and-forth conversation using the [Watson Assistant](https://www.ibm.com/cloud/watson-assistant/) service.
* Callout(⚠️ Prerequisite):
In order to complete this exercise, you will need to define a conversation flow in the [Watson Assistant tool](https://www.ibmwatsonconversation.com/login). Step-by-step instructions for how to do this can be found in this [Instructable](http://www.instructables.com/id/Build-a-Talking-Robot-With-Watson-and-Raspberry-Pi/) (step 6). Log into the [Watson Assistant tool](https://www.ibmwatsonconversation.com/login) tool to create a conversation flow, and take note of the Workspace ID. Note that you need a [Bluemix](http://bluemix.net) account to be able to use the Watson Assistant tool.
**Goal**: Engage in a conversation with TJBot using the `tj.converse(workspaceId:message:)`, `tj.listen(_:)`, and `tj.speak(_:)` methods.
* Callout(💡 Tip):
If you are near your computer, you can import a sample TJBot conversation flow into the Watson Assistant tool. Check out the [Conversation recipe](https://github.com/ibmtjbot/tjbot/tree/master/recipes/conversation) in TJBot's [GitHub repository](https://github.com/ibmtjbot/tjbot). It has a sample conversation file you can use to get started.
The `tj.converse(workspaceId:message:)` method returns a `ConversationResponse` object. This object contains the `text` response that TJBot should speak.
* Callout(⚠️ Caution):
Check the `error` property on the `ConversationResponse` just in case Watson returns an error!
*/
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, hide, page, proxy)
//#-code-completion(identifier, show, tj, ., shine(color:), pulse(color:duration:), raiseArm(), lowerArm(), wave(), sleep(duration:), speak(_:), listen(_:), see(), read(), converse(workspaceId:message:), description, ConversationResponse, error, text)
//#-code-completion(literal, show, color)
let tj = PhysicalTJBot()
let workspaceId = /*#-editable-code*/""/*#-end-editable-code*/
//#-editable-code
//#-end-editable-code
//: [Next page: TJBot's Adventures with You](@next)
| 56.425532 | 590 | 0.749246 |
8a9737511d1375319735a823bcc157b56c83ccef | 6,345 | //
// Bezier.swift
// AnimateUI
//
// Copyright © 2020 E-SOFT. All rights reserved.
//
import UIKit
/**
Animation starts a series of blocks of animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter duration: The duration of the animation block.
- Parameter curve: A curve from the Animation.Curve series, it defaults to .Linear.
- Parameter options: A set of options, for now .Reverse or .Repeat.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func animate(_ view: UIView,
delay: TimeInterval = 0,
duration: TimeInterval = 0.35,
curve: Animation.Curve = .linear,
options: [Animation.Options] = [],
animations: (Ingredient) -> Void) -> Distillery {
let builder = constructor([view], delay, duration, curve, options)
animations(builder.ingredient[0])
validate(builder.distillery)
return builder.distillery
}
/**
Animation starts a series of blocks of animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter duration: The duration of the animation block.
- Parameter curve: A curve from the Animation.Curve series, it defaults to .Linear.
- Parameter options: A set of options, for now .Reverse or .Repeat.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func animate(_ firstView: UIView,
_ secondView: UIView,
delay: TimeInterval = 0,
duration: TimeInterval = 0.35,
curve: Animation.Curve = .linear,
options: [Animation.Options] = [],
animations: (Ingredient, Ingredient) -> Void) -> Distillery {
let builder = constructor([firstView, secondView], delay, duration, curve, options)
animations(builder.ingredient[0], builder.ingredient[1])
validate(builder.distillery)
return builder.distillery
}
/**
Animation starts a series of blocks of animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter duration: The duration of the animation block.
- Parameter curve: A curve from the Animation.Curve series, it defaults to .Linear.
- Parameter options: A set of options, for now .Reverse or .Repeat.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func animate(_ firstView: UIView,
_ secondView: UIView,
_ thirdView: UIView,
delay: TimeInterval = 0,
duration: TimeInterval = 0.35,
curve: Animation.Curve = .linear,
options: [Animation.Options] = [],
animations: (Ingredient, Ingredient, Ingredient) -> Void) -> Distillery {
let builder = constructor([firstView, secondView, thirdView], delay, duration, curve, options)
animations(builder.ingredient[0], builder.ingredient[1], builder.ingredient[2])
validate(builder.distillery)
return builder.distillery
}
/**
Animation starts a series of blocks of animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter duration: The duration of the animation block.
- Parameter curve: A curve from the Animation.Curve series, it defaults to .Linear.
- Parameter options: A set of options, for now .Reverse or .Repeat.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func animate(_ firstView: UIView,
_ secondView: UIView,
_ thirdView: UIView,
_ fourthView: UIView,
duration: TimeInterval = 0.35,
delay: TimeInterval = 0,
curve: Animation.Curve = .linear,
options: [Animation.Options] = [],
animations: (Ingredient, Ingredient, Ingredient, Ingredient) -> Void) -> Distillery {
let builder = constructor([firstView, secondView, thirdView, fourthView], delay, duration, curve, options)
animations(builder.ingredient[0], builder.ingredient[1], builder.ingredient[2], builder.ingredient[3])
validate(builder.distillery)
return builder.distillery
}
// MARK: - Private helpers
private func constructor(_ views: [UIView],
_ delay: TimeInterval,
_ duration: TimeInterval,
_ curve: Animation.Curve,
_ options: [Animation.Options]) -> (ingredient: [Ingredient], distillery: Distillery) {
let distillery = Distillery()
var ingredients: [Ingredient] = []
views.forEach {
ingredients.append(Ingredient(distillery: distillery,
view: $0,
duration: duration,
curve: curve,
options: options))
}
distillery.delays.append(delay)
distillery.ingredients = [ingredients]
return (ingredient: ingredients, distillery: distillery)
}
private func validate(_ distillery: Distillery) {
var shouldProceed = true
distilleries.forEach {
if let ingredients = $0.ingredients.first, let ingredient = ingredients.first, ingredient.finalValues.isEmpty {
shouldProceed = false
return
}
}
distillery.shouldProceed = shouldProceed
if shouldProceed {
distilleries.append(distillery)
distillery.animate()
}
}
| 40.414013 | 124 | 0.595587 |
db3bbb1abd84c04ee5744c8678794258aea683e7 | 1,252 | //
// NSErrorExtension.swift
//
// Created by Pramod Kumar on 04/04/18.
// Copyright © 2018 Pramod Kumar. All rights reserved.
//
import Foundation
extension NSError {
convenience init(localizedDescription : String) {
self.init(domain: "AppNetworkingError", code: 0, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
}
convenience init(code : Int, localizedDescription : String) {
self.init(domain: "AppNetworkingError", code: code, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
}
class func networkConnectionError(urlString: String) -> NSError{
let errorUserInfo =
[ NSLocalizedDescriptionKey : PKNetworkingErrors.noInternet.message,
NSURLErrorFailingURLErrorKey : "\(urlString)"
]
return NSError(domain: NSCocoaErrorDomain, code: 12, userInfo:errorUserInfo)
}
class func jsonParsingError(urlString: String) -> NSError{
let errorUserInfo =
[ NSLocalizedDescriptionKey : "Error In Parsing JSON",
NSURLErrorFailingURLErrorKey : "\(urlString)"
]
return NSError(domain: NSCocoaErrorDomain, code: 32, userInfo:errorUserInfo)
}
}
| 32.947368 | 121 | 0.663738 |
f56d96482039d075b264c5afc8a5c4d7d4fb2200 | 7,767 | import UIKit
import Hero
extension String {
func matches(for regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))
var rs = [String]()
for m in results {
if let range = Range(m.range, in: self) {
rs.append(String(self[range]))
}
}
return rs
} catch let error {
return []
}
}
func removeSymbol() -> String {
let set = CharacterSet(charactersIn: "()[]")
return self.trimmingCharacters(in: set)
}
func isDoujinshi() -> Bool {
return true
//Need more research
//let doujinshiPattern = "^\\(.*\\).*\\[.*\\].*\\(.*\\)"
//return self.matches(for: doujinshiPattern).count != 0
}
var conventionName: String? {
guard isDoujinshi() else { return nil }
let pattern = "^\\([^\\(]*\\)"
return self.matches(for: pattern).first?.removeSymbol() ?? nil
}
var circleName: String? {
guard isDoujinshi() else { return nil }
let pattern = "\\[[^\\]]*\\]"
let matches = self.matches(for: pattern)
if let m = matches.first {
let p = "\\(.*\\)"
if let n = m.matches(for: p).first {
return m.replacingOccurrences(of: n, with: "").removeSymbol()
}
}
return matches.first?.removeSymbol() ?? nil
}
var artist: String? {
guard isDoujinshi() else { return nil }
let pattern = "\\[[^\\]]*\\]"
let matches = self.matches(for: pattern)
if let m = matches.first {
let p = "\\(.*\\)"
if let r = m.matches(for: p).first {
return r.removeSymbol()
}
}
return matches.first?.removeSymbol() ?? nil
}
var language: String? {
let pattern = "\\[[^\\[]+訳\\]"
if let match = self.matches(for: pattern).first?.removeSymbol() {
return match
} else {
let ls = ["albanian", "arabic", "bengali", "catalan", "chinese", "czech", "danish", "dutch", "english", "esperanto",
"estonian", "finnish", "french", "german", "greek", "hebrew", "hindi", "hungarian", "indonesian", "italian",
"japanese", "korean", "latin", "mongolian", "polish", "portuguese", "romanian", "russian", "slovak",
"slovenian", "spanish", "swedish", "tagalog", "thai", "turkish", "ukrainian", "vietnamese"]
for l in ls {
if self.lowercased().contains(l) {
return l
}
}
return nil
}
}
func toIcon(size: CGSize = CGSize(width: 44, height: 44), color: UIColor = UIColor.white, font: UIFont = UIFont.boldSystemFont(ofSize: 40)) -> UIImage {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
label.textAlignment = .center
label.backgroundColor = .clear
label.textColor = color
label.font = font
label.text = self
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
if let currentContext = UIGraphicsGetCurrentContext() {
label.layer.render(in: currentContext)
let nameImage = UIGraphicsGetImageFromCurrentImageContext()
return nameImage ?? UIImage()
}
return UIImage()
}
var htmlAttribute: NSAttributedString {
let font = UIFont.systemFont(ofSize: 14)
let css = "<style>body{font-family: '-apple-system', 'HelveticaNeue'; font-size: \(font.pointSize); color: #222222;}</style>%@"
let modified = String(format: css, self)
if let htmlData = modified.data(using: String.Encoding.unicode), let html = try? NSAttributedString(data: htmlData, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return html
}
return NSAttributedString(string: self)
}
}
protocol PropertyLoopable {
func allProperties() -> [String: Any]
}
extension PropertyLoopable {
func allProperties() -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle, (style == .struct || style == .class) else {
return result
}
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else { continue }
result[label] = valueMaybe
}
return result
}
}
extension UIImage {
var isContentModeFill: Bool {
return (paperRatio * 0.8)...(paperRatio * 1.2) ~= size.height / size.width
}
var preferContentMode: UIView.ContentMode {
return isContentModeFill ? .scaleAspectFill : .scaleAspectFit
}
}
class InteractiveBackGesture: NSObject, UIGestureRecognizerDelegate {
weak var viewController: UIViewController!
weak var view: UIView!
enum Mode {
case push
case modal
}
var mode: Mode
var isSimultaneously = true
init(viewController: UIViewController, toView: UIView, mode: Mode = .push, isSimultaneously: Bool = true ) {
self.viewController = viewController
self.view = toView
self.mode = mode
self.isSimultaneously = isSimultaneously
super.init()
let ges = UIPanGestureRecognizer(target: self, action: #selector(pan(gesture:)))
toView.addGestureRecognizer(ges)
ges.delegate = self
}
@objc func pan(gesture: UIPanGestureRecognizer) {
let v = gesture.velocity(in: nil)
let t = gesture.translation(in: nil)
let progress = mode == .push ? t.x / (viewController.view.bounds.width * 0.8) : t.y / (viewController.view.bounds.height * 0.8)
switch gesture.state {
case .began:
viewController.hero.dismissViewController()
case .changed:
Hero.shared.update(progress)
case .ended:
//Hero Bug fix
DispatchQueue.main.async {
let isFinished = self.mode == .push ? progress + v.x / self.viewController.view.bounds.width > 0.3 : progress + v.y / self.viewController.view.bounds.height > 0.3
if isFinished {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
}
default:
break
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return isSimultaneously
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
switch mode {
case .push:
let p = gestureRecognizer.location(in: nil)
let v = gestureRecognizer.velocity(in: nil)
return p.x < 44 && v.x > 0
case .modal:
let v = gestureRecognizer.velocity(in: nil)
if let scrollView = view as? UIScrollView {
if let vc = viewController as? BaseViewController, vc.isPopover { return false }
return scrollView.contentOffset.y <= -view.safeAreaInsets.top && v.y > 0
} else {
return v.y > abs(v.x) && v.y > 0
}
}
}
return true
}
}
| 37.162679 | 214 | 0.558131 |
f7ec7bf7320d12d467a7fa042e13b886f49d7319 | 144 |
import UIKit
struct SelectedViewModel {
let item: ViewModel
let imageView: UIImageView
let imageViewParentRelativeFrame: CGRect
}
| 16 | 44 | 0.763889 |
ed3b6f0b6fc007f9ff73d1aff4eb49bee15f39c8 | 349 | /// A request which has a strongly-typed response format
public struct HATypedRequest<ResponseType: HADataDecodable> {
/// Create a typed request
/// - Parameter request: The request to be issued
public init(request: HARequest) {
self.request = request
}
/// The request to be issued
public var request: HARequest
}
| 29.083333 | 61 | 0.690544 |
3a8b919400b2863c7de5b42c5ec3f19ace4ac835 | 1,055 | //
// UIViewController+HS.swift
// Rhythm101
//
// Created by Михаил Барашков on 05.06.2018.
// Copyright © 2018 Tinkerswitch. All rights reserved.
//
import Foundation
import UIKit
protocol FromStoryboard: class {
static var storyboardFilename:String {get}
static var storyboardId:String {get}
static func fromStoryboard() -> Self
}
extension FromStoryboard where Self: UIViewController {
/// Load VC from storyboard
/// Storyboard ID is by default assumed to be the class name
/// - Returns: the VC
static func fromStoryboard() -> Self {
let board = UIStoryboard.init(name: self.storyboardFilename, bundle: nil)
guard let vc = board.instantiateViewController(withIdentifier: storyboardId) as? Self else {
fatalError("Unable to instantiate storyboard with identifier: \(storyboardId)")
}
return vc
}
static var storyboardFilename:String {return String(describing: self)}
static var storyboardId:String {return String(describing: self)}
}
| 28.513514 | 100 | 0.690995 |
b90d7e892dc8f323349c857d9c55fbf364f0eb3b | 275 | //
// NetworkId.swift
// AloeStackView
//
// Created by Scott Chou on 2019/2/26.
//
import Foundation
import web3swift
public extension NetworkId {
public static var dexon: NetworkId { return 237 }
public static var dexonTestnet: NetworkId { return 238 }
}
| 17.1875 | 60 | 0.698182 |
7659cc0581b0e49c836a6bfce75dddc80b0cf90e | 3,375 | //
// Copyright (c) 2021 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Adyen
import AdyenActions
import AdyenCard
import AdyenComponents
import AdyenDropIn
import AdyenNetworking
import UIKit
extension IntegrationExample: PartialPaymentDelegate {
internal enum GiftCardError: Error, LocalizedError {
case noBalance
internal var errorDescription: String? {
switch self {
case .noBalance:
return "No Balance"
}
}
}
internal func checkBalance(with data: PaymentComponentData,
completion: @escaping (Result<Balance, Error>) -> Void) {
let request = BalanceCheckRequest(data: data)
apiClient.perform(request) { [weak self] result in
self?.handle(result: result, completion: completion)
}
}
private func handle(result: Result<BalanceCheckResponse, Error>,
completion: @escaping (Result<Balance, Error>) -> Void) {
switch result {
case let .success(response):
handle(response: response, completion: completion)
case let .failure(error):
handle(error: error, completion: completion)
}
}
private func handle(response: BalanceCheckResponse, completion: @escaping (Result<Balance, Error>) -> Void) {
guard let availableAmount = response.balance else {
finish(with: GiftCardError.noBalance)
completion(.failure(GiftCardError.noBalance))
return
}
let balance = Balance(availableAmount: availableAmount, transactionLimit: response.transactionLimit)
completion(.success(balance))
}
private func handle(error: Error, completion: @escaping (Result<Balance, Error>) -> Void) {
finish(with: error)
completion(.failure(error))
}
internal func requestOrder(_ completion: @escaping (Result<PartialPaymentOrder, Error>) -> Void) {
let request = CreateOrderRequest(amount: payment.amount, reference: UUID().uuidString)
apiClient.perform(request) { [weak self] result in
self?.handle(result: result, completion: completion)
}
}
private func handle(result: Result<CreateOrderResponse, Error>,
completion: @escaping (Result<PartialPaymentOrder, Error>) -> Void) {
switch result {
case let .success(response):
completion(.success(response.order))
case let .failure(error):
finish(with: error)
completion(.failure(error))
}
}
internal func cancelOrder(_ order: PartialPaymentOrder) {
let request = CancelOrderRequest(order: order)
apiClient.perform(request) { [weak self] result in
self?.handle(result: result)
}
}
private func handle(result: Result<CancelOrderResponse, Error>) {
switch result {
case let .success(response):
if response.resultCode == .received {
presentAlert(withTitle: "Order Cancelled")
} else {
presentAlert(withTitle: "Something went wrong, order is not canceled but will expire.")
}
case let .failure(error):
finish(with: error)
}
}
}
| 34.090909 | 113 | 0.622815 |
db8722f03f96cd13673b93369e9eee1e22cc6155 | 781 | //
// HomeTracking.swift
// GADemo
//
// Created by John on 13/03/19.
// Copyright © 2019 John Lima. All rights reserved.
//
import BaseTracking
struct HomeTracking: BaseTrackingEvent {
enum ScreenView: String {
case home
}
enum EventCategory: String {
case home = "home_category"
}
enum EventAction: String {
case openMenu = "home_open_menu"
case showDetails = "home_open_details"
}
typealias EventLabel = CustomRawRepresentable
}
extension HomeTracking {
/// Prepare the parameters using dynamic values
/// - Parameter value: Dynamic value
/// - Returns: Event Parameters
static func getSelectButtonParameter(_ value: Any) -> EventLabel? {
let item = "button name - \(value)"
return EventLabel(rawValue: item)
}
}
| 20.552632 | 69 | 0.68758 |
64be8703622a9aad9a1f6372689782ba04438ca4 | 2,925 | //
// MIT License
//
// Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public protocol EncodableKeyValueListConvertible {
associatedtype CodingKeys: CodingKey
func encodableKeyValues() throws -> [EncodableKeyValue<CodingKeys>]
}
// MARK: - Swift.Encodable (JSON)
public extension Encodable where Self: EncodableKeyValueListConvertible {
func encode(to encoder: Encoder) throws {
guard let serializerValueCodingKey = CodingKeys(stringValue: RadixModelType.jsonKey) else {
incorrectImplementation("You MUST declare a CodingKey having the string value `\(RadixModelType.jsonKey)` in your encodable model.")
}
guard let serializerVersionCodingKey = CodingKeys(stringValue: jsonKeyVersion) else {
incorrectImplementation("You MUST declare a CodingKey having the string value `\(jsonKeyVersion)` in your encodable model.")
}
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(serializerVersion, forKey: serializerVersionCodingKey)
if let modelTypeSpecifying = self as? RadixModelTypeStaticSpecifying {
try container.encode(modelTypeSpecifying.serializer, forKey: serializerValueCodingKey)
}
if let destinationsOwner = self as? DestinationsOwner {
guard let destinationsCodingKey = CodingKeys(stringValue: jsonKeyDestinations) else {
incorrectImplementation("You MUST declare a CodingKey having the string value `\(jsonKeyDestinations)` in your encodable model.")
}
try container.encode(destinationsOwner.destinations(), forKey: destinationsCodingKey)
}
try encodableKeyValues().forEach {
try $0.jsonEncoded(by: &container)
}
}
}
| 47.177419 | 145 | 0.722051 |
eda64f78e48f2a218a79870c38a2d7647055a1fa | 238 | //
// TestUIViewController.swift
// Practice_RxFlowTests
//
// Created by 한상진 on 2021/04/14.
//
import UIKit
final class TestUIViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 14.875 | 52 | 0.684874 |
4662ffe29240b2f6c69db1babb923977a4636cd2 | 2,615 | import UIKit
import RxSwift
import RxCocoa
class ViewController : UIViewController {
@IBOutlet private var hexTextField: UITextField!
@IBOutlet private var rgbTextField: UITextField!
@IBOutlet private var colorNameTextField: UITextField!
@IBOutlet private var textFields: [UITextField]!
@IBOutlet private var zeroButton: UIButton!
@IBOutlet private var buttons: [UIButton]!
private let disposeBag = DisposeBag()
private let viewModel = ViewModel()
private let backgroundColor = PublishSubject<UIColor>()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
guard let textField = self.hexTextField else { return }
textField.rx.text.orEmpty
.bind(to: viewModel.hexString)
.disposed(by: disposeBag)
for button in buttons {
button.rx.tap
.bind {
var shouldUpdate = false
switch button.titleLabel!.text! {
case "⊗":
textField.text = "#"
shouldUpdate = true
case "←" where textField.text!.count > 1:
textField.text = String(textField.text!.dropLast())
shouldUpdate = true
case "←":
break
case _ where textField.text!.count < 7:
textField.text!.append(button.titleLabel!.text!)
shouldUpdate = true
default:
break
}
if shouldUpdate {
textField.sendActions(for: .valueChanged)
}
}
.disposed(by: disposeBag)
}
viewModel.color
.drive(onNext: { [unowned self] color in
UIView.animate(withDuration: 0.2) {
self.view.backgroundColor = color
}
})
.disposed(by: disposeBag)
viewModel.rgb
.map { "\($0.0), \($0.1), \($0.2)" }
.drive(rgbTextField.rx.text)
.disposed(by: disposeBag)
viewModel.colorName
.drive(colorNameTextField.rx.text)
.disposed(by: disposeBag)
}
func configureUI() {
textFields.forEach {
$0.layer.shadowOpacity = 1.0
$0.layer.shadowRadius = 0.0
$0.layer.shadowColor = UIColor.lightGray.cgColor
$0.layer.shadowOffset = CGSize(width: -1, height: -1)
}
}
}
| 31.506024 | 75 | 0.512811 |
20473a30e827e82cf08b5d24504d2b2cc5222582 | 4,352 |
#if os(Linux)
#if GLES
import COpenGLES.gles2
#else
import COpenGL
#endif
#else
#if GLES
import OpenGLES
#else
import OpenGL.GL3
#endif
#endif
import Foundation
public let sharedImageProcessingContext = OpenGLContext()
extension OpenGLContext {
public func programForVertexShader(_ vertexShader:String, fragmentShader:String) throws -> ShaderProgram {
let lookupKeyForShaderProgram = "V: \(vertexShader) - F: \(fragmentShader)"
if let shaderFromCache = shaderCache[lookupKeyForShaderProgram] {
return shaderFromCache
} else {
return try sharedImageProcessingContext.runOperationSynchronously{
let program = try ShaderProgram(vertexShader:vertexShader, fragmentShader:fragmentShader)
self.shaderCache[lookupKeyForShaderProgram] = program
return program
}
}
}
public func programForVertexShader(_ vertexShader:String, fragmentShader:URL) throws -> ShaderProgram {
return try programForVertexShader(vertexShader, fragmentShader:try shaderFromFile(fragmentShader))
}
public func programForVertexShader(_ vertexShader:URL, fragmentShader:URL) throws -> ShaderProgram {
return try programForVertexShader(try shaderFromFile(vertexShader), fragmentShader:try shaderFromFile(fragmentShader))
}
public func openGLDeviceSettingForOption(_ option:Int32) -> GLint {
return self.runOperationSynchronously{() -> GLint in
self.makeCurrentContext()
var openGLValue:GLint = 0
glGetIntegerv(GLenum(option), &openGLValue)
return openGLValue
}
}
public func deviceSupportsExtension(_ openGLExtension:String) -> Bool {
#if os(Linux)
return false
#else
return self.extensionString.contains(openGLExtension)
#endif
}
// http://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_rg.txt
public func deviceSupportsRedTextures() -> Bool {
return deviceSupportsExtension("GL_EXT_texture_rg")
}
public func deviceSupportsFramebufferReads() -> Bool {
return deviceSupportsExtension("GL_EXT_shader_framebuffer_fetch")
}
public func sizeThatFitsWithinATextureForSize(_ size:Size) -> Size {
let maxTextureSize = Float(self.maximumTextureSizeForThisDevice)
if ( (size.width < maxTextureSize) && (size.height < maxTextureSize) ) {
return size
}
let adjustedSize:Size
if (size.width > size.height) {
adjustedSize = Size(width:maxTextureSize, height:(maxTextureSize / size.width) * size.height)
} else {
adjustedSize = Size(width:(maxTextureSize / size.height) * size.width, height:maxTextureSize)
}
return adjustedSize
}
func generateTextureVBOs() {
textureVBOs[.noRotation] = generateVBO(for:Rotation.noRotation.textureCoordinates())
textureVBOs[.rotateCounterclockwise] = generateVBO(for:Rotation.rotateCounterclockwise.textureCoordinates())
textureVBOs[.rotateClockwise] = generateVBO(for:Rotation.rotateClockwise.textureCoordinates())
textureVBOs[.rotate180] = generateVBO(for:Rotation.rotate180.textureCoordinates())
textureVBOs[.flipHorizontally] = generateVBO(for:Rotation.flipHorizontally.textureCoordinates())
textureVBOs[.flipVertically] = generateVBO(for:Rotation.flipVertically.textureCoordinates())
textureVBOs[.rotateClockwiseAndFlipVertically] = generateVBO(for:Rotation.rotateClockwiseAndFlipVertically.textureCoordinates())
textureVBOs[.rotateClockwiseAndFlipHorizontally] = generateVBO(for:Rotation.rotateClockwiseAndFlipHorizontally.textureCoordinates())
}
public func textureVBO(for rotation:Rotation) -> GLuint {
guard let textureVBO = textureVBOs[rotation] else {fatalError("GPUImage doesn't have a texture VBO set for the rotation \(rotation)") }
return textureVBO
}
}
@_semantics("sil.optimize.never") public func debugPrint(_ stringToPrint:String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
#if DEBUG
print("\(stringToPrint) --> \((String(describing:file) as NSString).lastPathComponent): \(function): \(line)")
#endif
}
| 40.672897 | 166 | 0.703814 |
18effefe2a149af21f2a3e2f87cddd4e38d1ff5e | 6,303 | //
// LoginViewController.swift
// Instagram
//
// Created by MacBookPro9 on 11/1/18.
// Copyright © 2018 MacBookPro9. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController {
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var usernameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogin(_ sender: Any) {
loginUser()
}
@IBAction func onSignUp(_ sender: Any) {
registerUser()
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
// ------------------------------------------MEHTODs------------------------------------------------
//all the methods related to th login and signin
//-------------------------------------------METHODS -----------------------------------------------
//user registration
func registerUser() {
let newUser = PFUser()
// set user properties
newUser.username = usernameField.text
newUser.password = passwordField.text
// call sign up function on the object
newUser.signUpInBackground { (success: Bool, error: Error?) in
if (newUser.username?.isEmpty)!{
let OKAction = UIAlertAction(title: "OK", style: .default){(action) in}
let alertController = UIAlertController(title: "Username is Required!", message: "Please Choose your Username.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
// add the OK action to the alert controller
alertController.addAction(OKAction)
}
else if (newUser.password?.isEmpty)!{
let OKAction = UIAlertAction(title: "OK", style: .default){(action) in}
let alertController = UIAlertController(title: "Password is Required!", message: "Please Enter a New Password.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
// add the OK action to the alert controller
alertController.addAction(OKAction)
}
if let error = error{
let errorAlertController = UIAlertController(title: "Sign up Failed!!!", message: "Account Already Exist for this username or Check your internet Connection", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Retry", style: .cancel)
errorAlertController.addAction(cancelAction)
self.present(errorAlertController, animated: true)
print(error.localizedDescription)
}else {
let OKAction = UIAlertAction(title: "OK", style: .default){(action) in}
let alertController = UIAlertController(title: "Registered Success!", message: "Now Enter your Username and password to Login.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
// add the OK action to the alert controller
alertController.addAction(OKAction)
// manually segue to logged in view
//self.performSegue(withIdentifier: "loginSegue", sender: nil)
}
}
}
func loginUser() {
let username = usernameField.text ?? ""
let password = passwordField.text ?? ""
PFUser.logInWithUsername(inBackground: username, password: password) { (user: PFUser?, error: Error?) in
if username.isEmpty{
let OKAction = UIAlertAction(title: "OK", style: .default){(action) in}
let alertController = UIAlertController(title: "Username Failed!", message: "Please Enter your Username.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
// add the OK action to the alert controller
alertController.addAction(OKAction)
}
else if password.isEmpty{
let OKAction = UIAlertAction(title: "OK", style: .default){(action) in}
let alertController = UIAlertController(title: "Password Failed!", message: "Please Enter your Password.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
// add the OK action to the alert controller
alertController.addAction(OKAction)
}
else{
if let error = error{
let errorAlertController = UIAlertController(title: "User Log in Failed!", message: "Plese, Verify your username and password or Check your internet Connection", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Retry", style: .cancel)
errorAlertController.addAction(cancelAction)
self.present(errorAlertController, animated: true)
print(error.localizedDescription)
}else {
print("Login Success")
self.performSegue(withIdentifier: "loginSegue", sender: nil)
}
}
}
}
// -----------------------------------------EndMEHTOD-----------------------------------------------
//all the methods related to th login and signin
//-----------------------------------------EndMETHOD------------------------------------------------
/*
// 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.
}
*/
}
| 41.467105 | 205 | 0.56132 |
b95f931fba5b400feb0a69aa3ab0d48de9b909fd | 4,339 | //
// RxRealm extensions
//
// Copyright (c) 2016 RxSwiftCommunity. All rights reserved.
// Check the LICENSE file for details
//
import Foundation
import RealmSwift
import RxCocoa
import RxRealm
import RxSwift
#if os(iOS)
// MARK: - iOS / UIKit
import UIKit
extension Reactive where Base: UITableView {
public func realmChanges<E>(_ dataSource: RxTableViewRealmDataSource<E>)
-> RealmBindObserver<E, AnyRealmCollection<E>, RxTableViewRealmDataSource<E>> {
return RealmBindObserver(dataSource: dataSource) { ds, results, changes in
if ds.tableView == nil {
ds.tableView = self.base
}
ds.tableView?.dataSource = ds
ds.applyChanges(items: AnyRealmCollection<E>(results), changes: changes)
}
}
public func realmModelSelected<E>(_: E.Type) -> ControlEvent<E> where E: RealmSwift.Object {
let source: Observable<E> = itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<E> in
guard let view = view, let ds = view.dataSource as? RxTableViewRealmDataSource<E> else {
return Observable.empty()
}
return Observable.just(ds.model(at: indexPath))
}
return ControlEvent(events: source)
}
}
extension Reactive where Base: UICollectionView {
// public func realmChanges<E>(_ dataSource: RxCollectionViewRealmDataSource)
// -> RealmBindObserver<E, AnyRealmCollection<E>, RxCollectionViewRealmDataSource> {
//
// return RealmBindObserver(dataSource: dataSource) {ds, results, changes in
// if ds.collectionView == nil {
// ds.collectionView = self.base
// }
// ds.collectionView?.dataSource = ds
// cha
// changes.forEach {
//
//// ds.sections?[$0.].applyChanges(items: AnyRealmCollection<E>(results), changes: changes)
// }
// }
// }
//
// @available(*, deprecated, renamed: "modelSelected")
// public func realmModelSelected<E>(_ modelType: E.Type) -> ControlEvent<E> where E: RealmSwift.Object {
// let source: Observable<E> = self.itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<E> in
// guard let view = view, let ds = view.dataSource as? RxCollectionViewRealmDataSource else {
// return Observable.empty()
// }
//
// let section = ds.model(at: indexPath)
// modelSelected(section.E)
// // do {
// return try Observable.just(ds.model(at: indexPath) as! E)
// // } catch {
// // return Observable.empty()
// // }
// }
//
// return ControlEvent(events: source)
// return modelSelected(modelType)
// }
}
#elseif os(OSX)
// MARK: - macOS / Cocoa
import Cocoa
extension Reactive where Base: NSTableView {
public func realmChanges<E>(_ dataSource: RxTableViewRealmDataSource<E>)
-> RealmBindObserver<E, AnyRealmCollection<E>, RxTableViewRealmDataSource<E>> {
base.delegate = dataSource
base.dataSource = dataSource
return RealmBindObserver(dataSource: dataSource) { ds, results, changes in
if dataSource.tableView == nil {
dataSource.tableView = self.base
}
ds.applyChanges(items: AnyRealmCollection<E>(results), changes: changes)
}
}
}
extension Reactive where Base: NSCollectionView {
public func realmChanges<E>(_ dataSource: RxCollectionViewRealmDataSource<E>)
-> RealmBindObserver<E, AnyRealmCollection<E>, RxCollectionViewRealmDataSource<E>> {
return RealmBindObserver(dataSource: dataSource) { ds, results, changes in
if ds.collectionView == nil {
ds.collectionView = self.base
}
ds.collectionView?.dataSource = ds
ds.applyChanges(items: AnyRealmCollection<E>(results), changes: changes)
}
}
}
#endif
| 37.08547 | 139 | 0.581701 |
695427e5120bc291f2215999ca900980c59a3a74 | 1,698 | //
// STPPaymentOption.swift
// Stripe
//
// Created by Ben Guo on 4/19/16.
// Copyright © 2016 Stripe, Inc. All rights reserved.
//
import UIKit
/// This protocol represents a payment method that a user can select and use to
/// pay.
/// The classes that conform to it and are supported by the UI:
/// - `STPApplePay`, which represents that the user wants to pay with
/// Apple Pay
/// - `STPPaymentMethod`. Only `STPPaymentMethod.type == STPPaymentMethodTypeCard` and
/// `STPPaymentMethod.type == STPPaymentMethodTypeFPX` are supported by `STPPaymentContext`
/// and `STPPaymentOptionsViewController`
/// - `STPPaymentMethodParams`. This should be used with non-reusable payment method, such
/// as FPX and iDEAL. Instead of reaching out to Stripe to create a PaymentMethod, you can
/// pass an STPPaymentMethodParams directly to Stripe when confirming a PaymentIntent.
/// @note card-based Sources, Cards, and FPX support this protocol for use
/// in a custom integration.
@objc public protocol STPPaymentOption: NSObjectProtocol {
/// A small (32 x 20 points) logo image representing the payment method. For
/// example, the Visa logo for a Visa card, or the Apple Pay logo.
var image: UIImage { get }
/// A small (32 x 20 points) logo image representing the payment method that can be
/// used as template for tinted icons.
var templateImage: UIImage { get }
/// A string describing the payment method, such as "Apple Pay" or "Visa 4242".
var label: String { get }
/// Describes whether this payment option may be used multiple times. If it is not reusable,
/// the payment method must be discarded after use.
var isReusable: Bool { get }
}
| 45.891892 | 96 | 0.722026 |
fc89a3041fe479f59eecc7c52f198540aae0d925 | 813 | //
// ShopifyPolicyAdapterSpec.swift
// ShopifyTests
//
// Created by Radyslav Krechet on 4/5/18.
// Copyright © 2018 RubyGarage. All rights reserved.
//
import MobileBuySDK
import Nimble
import Quick
import ShopApp_Gateway
@testable import Shopify
class ShopifyPolicyAdapterSpec: QuickSpec {
override func spec() {
describe("when adapter used") {
it("needs to adapt storefront item to model object") {
let item = try! Storefront.ShopPolicy(fields: ShopifyAdapterTestHelper.shopPolicy)
let object = ShopifyPolicyAdapter.adapt(item: item)!
expect(object.title) == item.title
expect(object.body) == item.body
expect(object.url) == item.url.absoluteString
}
}
}
}
| 27.1 | 98 | 0.627306 |
6275d5b1fafc11271bbf98c7c6ab42e7270c9578 | 3,488 | //Find all the leaves
import Swift
class Node: CustomStringConvertible{
var value : Int
var leftChild : Node?
var rightChild : Node?
private let MAX_HEIGHT_DIFF : Int = 1
public var description: String{
return "(Node: \(value)"
}
private var leftHeight: Int{
guard let leftSide = leftChild else{
return 0
}
return leftSide.height
}
private var rightHeight: Int{
guard let rightSide = rightChild else{
return 0
}
return rightSide.height
}
public var height: Int{
if leftHeight > rightHeight{
return leftHeight + 1
}else{
return rightHeight + 1
}
}
private var heightDifference : Int{
return leftHeight - rightHeight
}
public var isLeave : Bool{
return leftHeight == 0 && rightHeight == 0
}
init(value: Int, leftChild: Node, rightChild: Node){
self.value = value
self.leftChild = leftChild
self.rightChild = rightChild
}
init(value: Int, leftChild: Node){
self.value = value
self.leftChild = leftChild
self.rightChild = nil
}
init(value: Int, rightChild: Node){
self.value = value
self.leftChild = nil
self.rightChild = rightChild
}
init(value: Int){
self.value = value
self.leftChild = nil
self.rightChild = nil
}
public func insert(value: Int) -> Node{
//Finding insert point
if self.value > value{
if leftChild == nil{
leftChild = Node(value: value)
}else{
leftChild = leftChild!.insert(value:value)
}
}else if self.value < value{
if rightChild == nil{
rightChild = Node(value: value)
}else{
rightChild = rightChild!.insert(value:value)
}
}else{
//Already in the search tree
return self
}
//Balance tree with height criterium
if heightDifference < -MAX_HEIGHT_DIFF{
guard let rightSide = rightChild else{
return self
}
rightChild = rightSide.leftChild
rightSide.leftChild = self
return rightSide
}else if heightDifference > MAX_HEIGHT_DIFF{
guard let leftSide = leftChild else{
return self
}
leftChild = leftSide.rightChild
leftSide.rightChild = self
return leftSide
}else{
return self
}
}
public func getLeaves() -> [Int]{
if isLeave {
return [value]
}else{
var leaves : [Int] = Array()
if leftChild != nil{
leaves.append(contentsOf: leftChild!.getLeaves())
}
if rightChild != nil{
leaves.append(contentsOf: rightChild!.getLeaves())
}
return leaves
}
}
}
class BinarySearchTree: CustomStringConvertible{
var root : Node?
public var description: String{
guard root != nil else{
return "(Empty binary search tree)"
}
return "(Binary tree: \(root!)"
}
init(root: Node){
self.root = root
}
init(){
self.root = nil
}
public func insert(value: Int){
if root == nil{
root = Node(value: value)
}else{
root = root!.insert(value: value)
}
}
public func getLeaves() -> [Int]{
guard root != nil else{
return []
}
return root!.getLeaves()
}
}
//TEST
var node = Node(value: 4)
var leftNode = Node(value: 3)
var rightNode = Node(value: 6)
node.leftChild = leftNode
node.rightChild = rightNode
var testTree = BinarySearchTree(root: node)
var result = testTree.getLeaves()
var shouldBe = [3,6]
assert(result == shouldBe, "Incorrect leaves \(result), should be \(shouldBe)")
testTree.insert(value: 2)
testTree.insert(value: 1)
testTree.insert(value: 100)
result = testTree.getLeaves()
shouldBe = [1,3,100]
assert(result == shouldBe, "Incorrect leaves \(result), should be \(shouldBe)") | 18.553191 | 79 | 0.669151 |
c14a0f03d09f886ff8d9dcbade76815c64f2121d | 10,908 | //
// GradientActivityIndicatorViewModel.swift
// GradientLoadingBar
//
// Created by Felix Mau on 08/26/19.
// Copyright © 2019 Felix Mau. All rights reserved.
//
import UIKit
import LightweightObservable
// MARK: - Types
/// Array of locations, used to position the gradient colors during the animation.
typealias ColorLocationRow = [NSNumber]
/// Array containing an array of locations, used to position the gradient colors during the animation:
/// - The outer array defines each animation step.
/// - The inner array defines the location of each gradient-color during this animation step.
typealias ColorLocationMatrix = [ColorLocationRow]
/// This view model contains all logic related to the `GradientActivityIndicatorView` and the corresponding animation.
///
/// # How to create the infinite animation
/// Example for `gradientColors = [.red, .yellow, .green, .blue]`
///
/// Given the above `gradientColors` we can define three animation states:
/// - Visible colors at the **start** of the animation: `[.red, .yellow, .green, .blue]`
/// - Visible colors in the **middle** of the animation: `[.blue, .green, .yellow, .red]` (inverted `gradientColors`)
/// - Visible colors at the **end** of the animation: `[.red, .yellow, .green, .blue]` (same as start `gradientColors`)
///
/// So first we have to create a single array of all colors used in the above states:
/// Therefore we'll duplicate the `gradientColors`, reverse them, and remove the first and last item of the reversed array in order to
/// prevent duplicate values at the "inner edges" destroying the infinite look. Afterwards we can append the `gradientColors` again.
///
/// Given the above `gradientColors` our corresponding `gradientLayerColors` will look like this:
/// `gradientLayerColors = [.red, .yellow, .green, .blue, .green, .yellow, .red, .yellow, .green, .blue]`
///
/// Now we can animate through all of the colors, by updating the `locations` property accordingly. Please have a look at the documentation
/// for the method `makeColorLocationMatrix(gradientColorsQuantity:gradientLayerColorsQuantity:)` for further details regarding the `locations`
/// property.
///
/// As the colors at the start are the same as at the end, we can loop the animation without visual artefacts.
final class GradientActivityIndicatorViewModel {
// MARK: - Public properties
/// Observable color array for the gradient layer (of type `CGColor`).
var gradientLayerColors: Observable<[CGColor]> {
gradientLayerColorsSubject
}
/// Observable color locations for the gradient layer.
///
/// - Note: In order to have a working animation we need to provide the initial gradient-locations,
/// which is the first row of our animation matrix.
var colorLocationInitialRow: Observable<ColorLocationRow> {
colorLocationInitialRowSubject
}
/// Observable color location matrix, used to position the gradient colors during the animation.
/// - The outer array defines each animation step.
/// - The inner array defines the location of each gradient-color during this animation step.
var colorLocationMatrix: Observable<ColorLocationMatrix> {
colorLocationMatrixSubject
}
/// Observable duration for the progress animation.
var animationDuration: Observable<TimeInterval> {
animationDurationSubject
}
/// Observable flag, whether we're currently animating the progress.
var isAnimating: Observable<Bool> {
isAnimatingSubject
}
/// Color array used for the gradient (of type `UIColor`).
var gradientColors = UIColor.GradientLoadingBar.gradientColors {
didSet {
gradientLayerColorsSubject.value = makeGradientLayerColors()
let gradientLocationMatrix = makeColorLocationMatrix()
colorLocationInitialRowSubject.value = gradientLocationMatrix[0]
colorLocationMatrixSubject.value = gradientLocationMatrix
}
}
/// The duration for the progress animation.
var progressAnimationDuration: TimeInterval {
get {
animationDurationSubject.value
}
set {
animationDurationSubject.value = newValue
}
}
/// Boolean flag whether the view is currently hidden.
var isHidden = false {
didSet {
isAnimatingSubject.value = !isHidden
}
}
// MARK: - Private properties
private let gradientLayerColorsSubject: Variable<[CGColor]>
private let colorLocationInitialRowSubject: Variable<ColorLocationRow>
private let colorLocationMatrixSubject: Variable<ColorLocationMatrix>
private let animationDurationSubject = Variable(TimeInterval.GradientLoadingBar.progressDuration)
private let isAnimatingSubject = Variable(true)
// MARK: - Initializer
init() {
let gradientLayerColors = Self.makeGradientLayerColors(from: gradientColors)
let gradientLocationMatrix = Self.makeColorLocationMatrix(gradientColorsQuantity: gradientColors.count,
gradientLayerColorsQuantity: gradientLayerColors.count)
gradientLayerColorsSubject = Variable(gradientLayerColors)
colorLocationInitialRowSubject = Variable(gradientLocationMatrix[0])
colorLocationMatrixSubject = Variable(gradientLocationMatrix)
}
// MARK: - Private methods
/// Forward calls to the static factory method `makeGradientLayerColors(from:)` by providing the required parameters.
private func makeGradientLayerColors() -> [CGColor] {
Self.makeGradientLayerColors(from: gradientColors)
}
/// Forward calls to the static factory method `makeColorLocationMatrix(gradientColorsQuantity:gradientLayerColorsQuantity:)`
/// by providing the required parameters.
private func makeColorLocationMatrix() -> ColorLocationMatrix {
Self.makeColorLocationMatrix(gradientColorsQuantity: gradientColors.count,
gradientLayerColorsQuantity: gradientLayerColorsSubject.value.count)
}
/// Generates the colors used on the gradient-layer.
///
/// Example for `gradientColors = [.red, .yellow, .green, .blue]`
/// and therefore `gradientLayerColors = [.red, .yellow, .green, .blue, .green, .yellow, .red, .yellow, .green, .blue]`
///
/// - Note: Declared `static` so we can call this method from the initializer, before `self` is available.
private static func makeGradientLayerColors(from gradientColors: [UIColor]) -> [CGColor] {
// Simulate infinite animation - Therefore we'll reverse the colors and remove the first and last item
// to prevent duplicate values at the "inner edges" destroying the infinite look.
let reversedColors = gradientColors
.reversed()
.dropFirst()
.dropLast()
let infiniteGradientColors = gradientColors + reversedColors + gradientColors
return infiniteGradientColors.map { $0.cgColor }
}
/// Generates a single row for the locations-matrix used for animating the current `gradientColors`.
///
/// Example for `index = 0`
/// `gradientColors = [.red, .yellow, .green, .blue]`
/// and therefore `gradientLayerColors = [.red, .yellow, .green, .blue, .green, .yellow, .red, .yellow, .green, .blue]`
/// ```
/// gradientLayerColors | .red | .yellow | .green | .blue | .green | .yellow | .red | .yellow | .green | .blue
/// gradientLocationRow | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.33 | 0.66 | 1
/// ```
///
/// - Note: Declared `static` so we can call this method from the initializer, before `self` is available.
private static func makeColorLocationRow(index: Int,
gradientColorsQuantity: Int,
gradientLayerColorsQuantity: Int) -> ColorLocationRow {
let startLocationsQuantity = gradientLayerColorsQuantity - gradientColorsQuantity - index
let startLocations = [NSNumber](repeating: 0.0, count: startLocationsQuantity)
// E.g. if we have `gradientColors = [.red, .yellow, .green, .blue]`
// we need to position them as `[ 0.0, 0.33, 0.66, 0.99]`.
let increaseBy = 1.0 / Double(gradientColorsQuantity - 1)
let range = 0 ..< gradientColorsQuantity
let gradientLocations = range.reduce(into: ColorLocationRow(repeating: 0.0, count: gradientColorsQuantity)) { gradientLocations, col in
let value = Double(col) * increaseBy
gradientLocations[col] = value as NSNumber
}
let endLocationsQuantity = index
let endLocations = [NSNumber](repeating: 1.0, count: endLocationsQuantity)
return startLocations + gradientLocations + endLocations
}
/// Generates the locations-matrix used for animating the current `gradientColors`.
///
/// Example for `gradientColors = [.red, .yellow, .green, .blue]`
/// and therefore `gradientLayerColors = [.red, .yellow, .green, .blue, .green, .yellow, .red, .yellow, .green, .blue]`
/// ```
/// i | .red | .yellow | .green | .blue | .green | .yellow | .red | .yellow | .green | .blue
/// 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.33 | 0.66 | 1
/// 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.33 | 0.66 | 1 | 1
/// 2 | 0 | 0 | 0 | 0 | 0 | 0.33 | 0.66 | 1 | 1 | 1
/// 3 | 0 | 0 | 0 | 0 | 0.33 | 0.66 | 1 | 1 | 1 | 1
/// 4 | 0 | 0 | 0 | 0.33 | 0.66 | 1 | 1 | 1 | 1 | 1
/// 5 | 0 | 0 | 0.33 | 0.66 | 1 | 1 | 1 | 1 | 1 | 1
/// 6 | 0 | 0.33 | 0.66 | 1 | 1 | 1 | 1 | 1 | 1 | 1
/// ```
///
/// - Note: Declared `static` so we can call this method from the initializer, before `self` is available.
private static func makeColorLocationMatrix(gradientColorsQuantity: Int,
gradientLayerColorsQuantity: Int) -> ColorLocationMatrix {
let matrixHeight = gradientLayerColorsQuantity - gradientColorsQuantity + 1
let range = 0 ..< matrixHeight
return range.reduce(into: ColorLocationMatrix(repeating: [], count: matrixHeight)) { gradientLocationMatrix, row in
gradientLocationMatrix[row] = Self.makeColorLocationRow(index: row,
gradientColorsQuantity: gradientColorsQuantity,
gradientLayerColorsQuantity: gradientLayerColorsQuantity)
}
}
}
| 50.036697 | 143 | 0.638614 |
e80c85b51cb40086eeee414e4954cc34e3964104 | 1,347 | //
// SPHomeUI_Extension.swift
// SPHomeUIExtension
//
// Created by flowerflower on 2021/12/17.
//
import Foundation
import SPMediator
public extension SPMediator {
@objc func SPHomeUI_homeViewController() -> UIViewController? {
if let controller = self.performTarget_SPHomeUI(action: "homeViewController") {
return controller
}
return nil
}
}
/// Private
extension SPMediator {
/// 通用调用方法
///
/// - Parameters:
/// - action: 方法
/// - param: 参数
/// - shouldCacheTarget: 是否缓存 Target
func performTarget_SPHomeUI(action: String,
param: Dictionary<AnyHashable, Any>? = nil,
shouldCacheTarget: Bool? = false) -> UIViewController? {
let targetName = "SPHomeUI"
var paramDic: Dictionary<AnyHashable, Any> = param ?? [:]
paramDic[kSPMediatorParamsKeySwiftTargetModuleName] = targetName
if let controller = self.performTarget(targetName,
action: action,
params: paramDic,
shouldCacheTarget: false) as? UIViewController {
return controller
}
return nil
}
}
| 24.490909 | 95 | 0.533036 |
87a9e23f71d153aae8d81c31fd16209f744c7cbd | 245 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A {
class b { func g {
let c [ {
for
let d {
case
let {
class
case ,
| 17.5 | 87 | 0.718367 |
5d2d05ed5115f1838a776ad01f5e260be2c81f92 | 1,724 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import UIKit
extension UIApplication: NetworkActivityIndicatorProtocol { }
public extension NetworkActivityController {
/// (iOS-only) A shared NetworkActivityController that uses `UIApplication.shared`
/// to display/hide the network activity indicator in the status bar.
///
/// Since each NetworkActivityController manages its own count of started/stopped
/// procedures with attached NetworkObservers, you are encouraged to use this
/// shared NetworkActivityController to manage the network activity indicator
/// in the status bar (or the convenience initializers that do so).
static let shared = NetworkActivityController()
/// (iOS-only) Initialize a NetworkActivityController that displays/hides the
/// network activity indicator in the status bar. (via UIApplication)
///
/// - Parameter timerInterval: How long to wait after observed network activity stops
/// before the network activity indicator is set to false.
/// (This helps reduce flickering if you rapidly create
/// procedures with attached NetworkObservers.)
public convenience init(timerInterval: TimeInterval = 1.0) {
self.init(timerInterval: timerInterval, indicator: UIApplication.shared)
}
}
public extension NetworkObserver {
/// (iOS-only) Initialize a NetworkObserver that displays/hides
/// the network activity indicator in the status bar. (via UIApplication)
public convenience init() {
self.init(controller: NetworkActivityController.shared)
}
}
| 40.093023 | 89 | 0.704176 |
113797f4f7a05144300470c07c1d1c0d0962568d | 983 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
extension ImageContentMode {
func toUIKit() -> UIImageView.ContentMode {
switch self {
case .fitXY:
return .scaleToFill
case .fitCenter:
return .scaleAspectFit
case .centerCrop:
return .scaleAspectFill
case .center:
return .center
}
}
}
| 29.787879 | 75 | 0.671414 |
280eead6a82b674e03738b186691bd45ca590b5f | 600 | //
// BackgroundItemController.swift
// TabBar
//
// Created by galaxy on 2020/11/3.
//
import UIKit
public class BackgroundItemController: UIViewController {
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(dismissAction))
self.navigationItem.title = "背景item"
}
@objc private func dismissAction() {
self.tabBarController?.dismiss(animated: true, completion: nil)
}
}
| 25 | 144 | 0.686667 |
16a2b005909de8d62ff49978d64f196be9dc52f7 | 1,633 | //
// CollectionCell.swift
// WeatherApp
//
// Created by 박지윤 on 2021/09/18.
//
import Foundation
import UIKit
class CollectionCell: UICollectionViewCell{
var cellTimeLabel = UILabel()
var cellWeatherIcon = UIImageView()
var cellTempLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
cellTimeLabel.textColor = .white
cellWeatherIcon.tintColor = .yellow
cellTempLabel.textColor = .white
self.backgroundColor = UIColor(red: 0.24, green: 0.70, blue: 1.00, alpha: 1.00)
self.cellTempLabel.text = "19"
self.cellWeatherIcon.image = UIImage(systemName: "sun.max.fill")?.withTintColor(.yellow)
addSubview(cellTimeLabel)
addSubview(cellWeatherIcon)
addSubview(cellTempLabel)
cellTimeLabel.snp.makeConstraints { maker in
maker.top.equalTo(contentView.safeAreaLayoutGuide.snp.top).offset(10)
maker.centerX.equalTo(contentView.safeAreaLayoutGuide.snp.centerX)
}
cellWeatherIcon.snp.makeConstraints { maker in
maker.top.equalTo(cellTimeLabel.safeAreaLayoutGuide.snp.bottom).offset(20)
maker.centerX.equalTo(contentView.safeAreaLayoutGuide.snp.centerX)
}
cellTempLabel.snp.makeConstraints { maker in
maker.top.equalTo(cellWeatherIcon.safeAreaLayoutGuide.snp.bottom).offset(20)
maker.centerX.equalTo(contentView.safeAreaLayoutGuide.snp.centerX)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.326531 | 96 | 0.663197 |
f9634f37baee1c588d5ae85fc1c07a8012b78fb2 | 6,073 | //
// Array.swift
// ConvenientSwift
//
// Created by abobrov on 14/09/2018.
// Copyright © 2018 Artem Bobrov. All rights reserved.
//
import Foundation
public extension Array {
/// Insert an element at the beginning of array.
///
/// - Parameter newElement: Element to insert.
public mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// Safely Swap values at index positions.
///
/// - Parameters:
/// - index: Index of first element.
/// - otherIndex: Index of other element.
public mutating func safeSwap(from index: Index, to otherIndex: Index) {
guard index != otherIndex,
startIndex ..< endIndex ~= index,
startIndex ..< endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// Keep elements of Array while condition is true.
///
/// - Parameter condition: Condition to evaluate each element against.
/// - Returns: Self after applying provided condition.
/// - Throws: Provided condition exception.
@discardableResult
public mutating func keep(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy .enumerated() where try !condition(element) {
self = Array(self[startIndex ..< index])
break
}
return self
}
/// Take element of Array while condition is true.
///
/// - Parameter condition: Condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy .enumerated() where try !condition(element) {
return Array(self[startIndex ..< index])
}
return self
}
/// Skip elements of Array while condition is true.
///
/// - Parameter condition: Condition to evaluate each element against.
/// - Returns: All elements after the condition evaluates to false.
public func skip(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy .enumerated() where try !condition(element) {
return Array(self[index ..< endIndex])
}
return [Element]()
}
/// Separates an array into 2 arrays based on a predicate.
///
/// - Parameter predicate: Condition to evaluate each element against.
/// - Returns: Two arrays, the first containing the elements for which the specified condition evaluates to true, the second containing the rest.
public func divided(by predicate: (Element) throws -> Bool) rethrows -> ([Element], [Element]) {
return try reduce(into: ([], []), { result, element in
if try predicate(element) {
result.0.append(element)
} else {
result.1.append(element)
}
})
}
/// Returns a sorted array based on an optional keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
/// - Returns: Sorted array based on keyPath.
public func sorted<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] {
return sorted(by: { (lhs, rhs) -> Bool in
guard let lhsValue = lhs[keyPath: path], let rhsValue = rhs[keyPath: path] else { return false }
return ascending ? lhsValue < rhsValue : lhsValue > rhsValue
})
}
/// Returns a sorted array based on a keypath.
///
/// - Parameter path: Key path to sort. The key path type must be Comparable.
/// - Parameter ascending: If order must be ascending.
/// - Returns: Sorted array based on keyPath.
public func sorted<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) -> [Element] {
return sorted(by: { (lhs, rhs) -> Bool in
ascending ? lhs[keyPath: path] < rhs[keyPath : path]: lhs[keyPath: path] > rhs[keyPath: path]
})
}
/// Sort the array based on an optional keypath.
///
/// - Parameters:
/// - path: Key path to sort, must be Comparable.
/// - ascending: Whether order is ascending or not.
/// - Returns: self after sorting.
public mutating func sort<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) {
self = sorted(by: path, ascending: ascending)
}
/// Sort the array based on a keypath.
///
/// - Parameters:
/// - path: Key path to sort, must be Comparable.
/// - ascending: Whether order is ascending or not.
public mutating func sort<T: Comparable>(by path: KeyPath<Element, T>, ascending: Bool = true) {
self = sorted(by: path, ascending: ascending)
}
}
public extension Array where Element: Equatable {
/// Remove all instances of an item from array.
///
/// - Parameter item: Item to remove.
/// - Returns: Self after removing all instances of item.
@discardableResult
public mutating func removeAll(_ item: Element) -> [Element] {
removeAll(where: { $0 == item })
return self
}
/// Remove all instances contained in items parameter from array.
///
/// - Parameter items: Items to remove.
/// - Returns: Self after removing all instances of all items in given array.
@discardableResult
public mutating func removeAll(_ items: [Element]) -> [Element] {
guard !items.isEmpty else { return self }
removeAll(where: { items.contains($0) })
return self
}
/// Remove all duplicate elements from Array.
public mutating func removeDuplicates() {
self = withoutDuplicates()
}
/// Return array with all duplicate elements removed.
///
/// - Returns: An array of unique elements.
public func withoutDuplicates() -> [Element] {
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
}
| 37.487654 | 149 | 0.618146 |
d74fc3b15d7aceed2ef843c46d70a61b781aaa43 | 4,875 | //
// MTRecommendViewController.swift
// MT_BSBDJ_Swift
//
// Created by Austen on 16/8/3.
// Copyright © 2016年 mlc. All rights reserved.
//
import UIKit
import MJRefresh
import SVProgressHUD
class MTRecommendViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var categoryTableView: UITableView!
@IBOutlet weak var userTableView: UITableView!
let categoryIdentifier = "categoryCell"
let userIdentifier = "userCell"
var categoryArray : [MTCategory] = []
var currentCategory : MTCategory?
override func viewDidLoad() {
super.viewDidLoad()
title = "推荐关注"
setTableView()
setRefresh()
loadCategories()
}
//设置tableView
private func setTableView() {
categoryTableView.registerNib(UINib(nibName: "MTCategoryTableViewCell", bundle: nil), forCellReuseIdentifier: "MTCategoryTableViewCell")
userTableView.registerNib(UINib(nibName:"MTUserTableViewCell", bundle: nil), forCellReuseIdentifier: "MTUserTableViewCell")
automaticallyAdjustsScrollViewInsets = false
categoryTableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
userTableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
userTableView.rowHeight = 70
}
private func setRefresh() {
userTableView.tableFooterView = UIView.init()
weak var weakSelf = self
userTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
weakSelf!.loadNewUsers()
})
}
private func loadNewUsers() {
let refreshCategory = self.currentCategory
weak var weakSelf = self
MTRecommendTool.getUsers(1, categoryId: (self.currentCategory?.id)!) { (obj) -> () in
refreshCategory?.users = obj as! [MTUser]
// 防止因为网速慢 导致 显示内容错位
// 在闭包中,refreshCategory是局部变量,是值引用 不是址引用
if refreshCategory != weakSelf!.currentCategory!{
return
}
SVProgressHUD.dismiss()
weakSelf!.userTableView.reloadData()
// let a = self.userTableView.tableHeaderView as! MJRefreshNormalHeader
// a .endRefreshing()
weakSelf!.userTableView.mj_header.endRefreshing()
}
}
// MARK: - tableView DateSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if tableView == categoryTableView{
return categoryArray.count
}else{
return currentCategory?.users.count ?? 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if tableView == categoryTableView{
let cell = tableView.dequeueReusableCellWithIdentifier("MTCategoryTableViewCell") as! MTCategoryTableViewCell
cell.category = categoryArray[indexPath.row]
return cell
}else{
let cell = tableView.dequeueReusableCellWithIdentifier("MTUserTableViewCell", forIndexPath: indexPath) as! MTUserTableViewCell
cell.user = currentCategory?.users[indexPath.row]
return cell
}
}
// MARK: - tableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == categoryTableView{
// 停止刷新 网络请求并没有停止
// let header = self.userTableView.tableHeaderView as! MJRefreshNormalHeader
// header.endRefreshing()
self.userTableView.mj_header.beginRefreshing()
currentCategory = categoryArray[indexPath.row]
// 刷新tableView 保证 第一次加载时 不会显示刚刚的页面
self.userTableView.reloadData()
// 防止重新加载数据
if (self.currentCategory!.users.isEmpty){
self.userTableView.mj_header.endRefreshing()
}
}
}
// MARK: - private method
// 获得左侧列表
private func loadCategories() {
SVProgressHUD.show()
SVProgressHUD.setDefaultMaskType(.Black)
MTRecommendTool.getCategory { (obj) -> () in
self.categoryArray = obj as! [MTCategory]
self.categoryTableView.reloadData()
self.categoryTableView.selectRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: 0), animated: true, scrollPosition: .Top)
self.tableView(self.categoryTableView, didSelectRowAtIndexPath: NSIndexPath.init(forRow: 0, inSection: 0))
}
}
}
| 31.25 | 144 | 0.609641 |
036198551d9d358f58b6ff8f7dc6d72c95a17f0b | 938 | //
// QueueConversationVideoEventTopicAddress.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class QueueConversationVideoEventTopicAddress: Codable {
public var name: String?
public var nameRaw: String?
public var addressNormalized: String?
public var addressRaw: String?
public var addressDisplayable: String?
public var additionalProperties: JSON?
public init(name: String?, nameRaw: String?, addressNormalized: String?, addressRaw: String?, addressDisplayable: String?, additionalProperties: JSON?) {
self.name = name
self.nameRaw = nameRaw
self.addressNormalized = addressNormalized
self.addressRaw = addressRaw
self.addressDisplayable = addressDisplayable
self.additionalProperties = additionalProperties
}
}
| 23.45 | 157 | 0.682303 |
f83c5017e55efb1831bede8a8c1e684de7b54ad6 | 103 | // RUN: %not %neal %args | %check
import Foundation
print(arc4random()) // CHECK: error: Explanation
| 17.166667 | 48 | 0.68932 |
cca3abc6d51b3d41c7e3a43e811806a798a80a6c | 3,374 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import MaterialMotionRuntime
import MaterialMotionTransitions
import MaterialMotionCoreAnimation
class TransitionTweenPerformer: NSObject, ComposablePerforming {
let target: CALayer
required init(target: Any) {
self.target = target as! CALayer
super.init()
}
func addPlan(_ plan: Plan) {
let transitionTween = plan as! TransitionTween
let from: AnyObject
let to: AnyObject
let segment: TransitionWindowSegment
var timingFunction: CAMediaTimingFunction
switch transitionTween.transition.direction {
case .forward:
from = transitionTween.back
to = transitionTween.fore
timingFunction = transitionTween.timingFunction
segment = transitionTween.segment
case.backward:
from = transitionTween.fore
to = transitionTween.back
if let backwardTimingFunction = transitionTween.backwardTimingFunction {
timingFunction = backwardTimingFunction
} else {
var first: [Float] = [0, 0]
var second: [Float] = [0, 0]
transitionTween.timingFunction.getControlPoint(at: 1, values: &first)
transitionTween.timingFunction.getControlPoint(at: 2, values: &second)
timingFunction = CAMediaTimingFunction(controlPoints: 1 - second[0], 1 - second[1],
1 - first[0], 1 - first[1])
}
if let backwardSegment = transitionTween.backwardSegment {
segment = TransitionWindowSegmentInverted(segment: backwardSegment)
} else {
segment = TransitionWindowSegmentInverted(segment: transitionTween.segment)
}
}
let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
var keyTimes: [Double] = [0]
var values: [Any] = [from]
var timingFunctions: [CAMediaTimingFunction] = []
if segment.position > TransitionWindowSegmentEpsilon {
values.append(from)
timingFunctions.append(linear)
keyTimes.append(Double(segment.position))
}
timingFunctions.append(timingFunction)
if segment.position + segment.length < 1 - TransitionWindowSegmentEpsilon {
values.append(to)
timingFunctions.append(linear)
keyTimes.append(Double(segment.position + segment.length))
}
keyTimes.append(1)
values.append(to)
let tween = Tween(transitionTween.keyPath,
duration: transitionTween.transition.window.duration,
values: values)
tween.keyPositions = keyTimes
tween.timingFunctions = [timingFunction]
tween.timeline = transitionTween.transition.timeline
emitter.emitPlan(tween)
tween.commitLastValue(to: target)
}
var emitter: PlanEmitting!
func setPlanEmitter(_ planEmitter: PlanEmitting) {
emitter = planEmitter
}
}
| 34.783505 | 91 | 0.709247 |
e8bc13c4fad5246fe086810edff4f0337a7ac59d | 1,565 | //
// SwiftLnd
//
// Created by 0 on 08.05.19.
// Copyright © 2019 Zap. All rights reserved.
//
import Foundation
import Logger
import SwiftBTC
enum BackupDisabler {
private static let neutrinoFiles = [
"reg_filter_headers.bin",
"block_headers.bin",
"neutrino.db"
]
static func disableNeutrinoBackup(walletId: WalletId, network: Network) {
var walletDirectory = FileManager.default.walletDirectory(for: walletId)
walletDirectory?.appendPathComponent(dataPath(for: network), isDirectory: true)
for file in neutrinoFiles {
guard let fileURL = walletDirectory?.appendingPathComponent(file, isDirectory: false) else { continue }
addSkipBackupAttributeToItem(at: fileURL)
}
}
private static func dataPath(for network: Network) -> String {
return "data/chain/bitcoin/\(network)"
}
private static func addSkipBackupAttributeToItem(at url: URL) {
if !FileManager.default.fileExists(atPath: url.path) {
Logger.warn("Error excluding \(url.path) from backup. (File not found)")
return
}
do {
var url = url
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try url.setResourceValues(resourceValues)
Logger.info("Did disable backup for \(url.lastPathComponent)")
} catch let error as NSError {
Logger.error("Error excluding \(url.lastPathComponent) from backup \(error)")
}
}
}
| 31.3 | 115 | 0.646006 |
8ad3e0ef01211097a0630317357d57a65abad947 | 1,232 | //
// Endpoint.swift
// NetworkLayer
//
// Created by Genie Sun on 2020/5/6.
// Copyright © 2020 Lookingedu. All rights reserved.
//
import Foundation
import UIKit
public typealias HttpHeaders = [String: String]
public typealias Parameters = [String: Any]
public enum HttpMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
}
public enum HttpTask<T: Encodable> {
case request
// post or get
case requestWithParameters(bodyParameters: T?, queryParameters: Parameters?, pathParameters: [String]?)
// get
case GET(queryParameters: Parameters?)
// post
case POST(bodyParameters: T?)
// get and can set header
case requestWithHeaders(headers: HttpHeaders?, queryParameters: Parameters?)
}
public protocol EndpointType {
associatedtype ParameterType: Encodable
var baseUrl: URL { get }
var path: String { get }
var httpMethod: HttpMethod { get }
var task: HttpTask<ParameterType> { get }
var headers: HttpHeaders? { get }
func loadCookies()
}
public extension EndpointType {
var httpMethod: HttpMethod {
return .post
}
var headers: HttpHeaders? {
return nil
}
func loadCookies(){
}
}
| 22.4 | 107 | 0.665584 |
90cacc304ad8ee1fb25468c6ef14a6d1c9e13e0c | 1,479 | //
// STJSONValue.swift
// STBaseProject
//
// Created by song on 2020/5/26.
// Copyright © 2020 ST. All rights reserved.
//
import Foundation
public enum STJSONValue: Decodable {
case int(Int)
case bool(Bool)
case double(Double)
case string(String)
case array([STJSONValue])
case object([String: STJSONValue])
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = try ((try? container.decode(String.self)).map(STJSONValue.string))
.or((try? container.decode(Int.self)).map(STJSONValue.int))
.or((try? container.decode(Double.self)).map(STJSONValue.double))
.or((try? container.decode(Bool.self)).map(STJSONValue.bool))
.or((try? container.decode([String: STJSONValue].self)).map(STJSONValue.object))
.or((try? container.decode([STJSONValue].self)).map(STJSONValue.array))
.resolve(with: DecodingError.typeMismatch(STJSONValue.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON")))
}
}
extension Optional {
func or(_ other: Optional) -> Optional {
switch self {
case .none: return other
case .some: return self
}
}
func resolve(with error: @autoclosure () -> Error) throws -> Wrapped {
switch self {
case .none: throw error()
case .some(let wrapped): return wrapped
}
}
}
| 31.468085 | 161 | 0.635565 |
670e436331cc87d46c3c721ce6de575651f152ed | 2,256 | //
// JSONResponse.swift
// Ambassador
//
// Created by Fang-Pen Lin on 6/10/16.
// Copyright © 2016 Fang-Pen Lin. All rights reserved.
//
import Foundation
import Embassy
/// A response app for responding JSON data
public struct JSONResponse: WebApp {
/// Underlying data response
let dataResponse: DataResponse
public init(
statusCode: Int = 200,
statusMessage: String = "OK",
contentType: String = "application/json",
jsonWritingOptions: JSONSerialization.WritingOptions = .prettyPrinted,
headers: [(String, String)] = [],
handler: @escaping (_ environ: [String: Any], _ sendJSON: @escaping (Any) -> Void) -> Void
) {
dataResponse = DataResponse(
statusCode: statusCode,
statusMessage: statusMessage,
contentType: contentType,
headers: headers
) { environ, sendData in
handler(environ) { json in
let data = try! JSONSerialization.data(withJSONObject: json, options: jsonWritingOptions)
sendData(data)
}
}
}
public init(
statusCode: Int = 200,
statusMessage: String = "OK",
contentType: String = "application/json",
jsonWritingOptions: JSONSerialization.WritingOptions = .prettyPrinted,
headers: [(String, String)] = [],
handler: ((_ environ: [String: Any]) -> Any)? = nil
) {
dataResponse = DataResponse(
statusCode: statusCode,
statusMessage: statusMessage,
contentType: contentType,
headers: headers
) { environ, sendData in
let data: Data
if let handler = handler {
let json = handler(environ)
data = try! JSONSerialization.data(withJSONObject: json, options: jsonWritingOptions)
} else {
data = Data()
}
sendData(data)
}
}
public func app(
_ environ: [String: Any],
startResponse: @escaping ((String, [(String, String)]) -> Void),
sendBody: @escaping ((Data) -> Void)
) {
return dataResponse.app(environ, startResponse: startResponse, sendBody: sendBody)
}
}
| 31.333333 | 105 | 0.58023 |
ab9230835d2a631760b33f3dd0deb9ea4143b24f | 1,675 | //
// WelcomeViewController.swift
// ApiTapiExample
//
// Created by Appbooster on 03/09/2019.
// Copyright © 2019 Appbooster. All rights reserved.
//
import UIKit
import ApiTapiID
class WelcomeViewController: ShakeToResetDeviceTokenViewController {
@IBOutlet private weak var toPaywallButton: UIButton!
@IBOutlet private weak var infoLabel: UILabel!
private var viewDidAppearOnce: Bool = false
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
infoLabel.text = "This app demonstrates how ApiTapi works.\n\nCurrent device token is\n\(ApiTapi.deviceToken)\n\nDevice token is used for sending the events to analytics system and for A/B testing.\n\nThere is an A/B test running on the paywall (\"old\" / \"new\" text). Please shake the device to reset the device token. It will mean that user will take part in the test as new user.\n\nWhen subscription is confirmed ApiTapi sends event about a trial start and then about premium start to integrated systems."
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Analytics.log(.welcomeScreenHasShown)
if !viewDidAppearOnce {
viewDidAppearOnce = true
ApiTapi.fetchTests { [weak self] error in
guard let self = self else { return }
if let error = error {
log("[ApiTapiExample] Fetching tests error: \(error)")
return
}
log("[ApiTapiExample] User properties: \(ApiTapi.userProperties.debugDescription)")
Analytics.setUserProperties(ApiTapi.userProperties)
Analytics.activate()
self.toPaywallButton.isEnabled = true
}
}
}
}
| 30.454545 | 515 | 0.712836 |
89067408cd48bfb698773cc9cacb613d6177d9b0 | 122 | import XCTest
import LightChartTests
var tests = [XCTestCaseEntry]()
tests += LightChartTests.allTests()
XCTMain(tests)
| 15.25 | 35 | 0.786885 |
61b0e4579297e92bcb1958b02f275ee63ffd97d4 | 1,677 | //
// ProgressView.swift
// DashKitUI
//
// Created by Pete Schwamb on 3/2/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public struct ProgressView: View {
private let progress: CGFloat
private let barHeight: CGFloat = 8
public init(progress: CGFloat) {
self.progress = progress
}
public var body: some View {
return GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle()
.opacity(0.1)
.cornerRadius(self.barHeight/2)
.animation(nil)
Rectangle()
.foregroundColor(Color.accentColor)
.frame(width: geometry.size.width * self.progress)
.cornerRadius(self.barHeight/2)
}
}
.frame(height: barHeight)
}
}
struct ProgressTestView: View {
@State var showDetail: Bool = false
@State var madeProgress: Bool = false
var body: some View {
VStack {
ProgressView(progress: madeProgress ? 0.9 : 0.5)
.animation(.linear(duration: 2))
.padding()
.opacity(showDetail ? 1 : 0)
.animation(.linear(duration: 0.2))
Button("Test") {
self.showDetail.toggle()
self.madeProgress.toggle()
}
}
.animation(.linear(duration: 0.2))
}
}
struct ProgressView_Previews: PreviewProvider {
@State var showDetail: Bool = false
static var previews: some View {
ProgressTestView()
}
}
| 24.304348 | 70 | 0.530113 |
01ba0e8a4c643b771e0ea27366267270f36e560e | 77,208 | //
// CwlSignalTests.swift
// CwlSignal
//
// Created by Matt Gallagher on 2016/06/08.
// Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import CwlPreconditionTesting
import CwlSignal
import CwlUtils
import Foundation
import XCTest
private enum TestError: Error {
case zeroValue
case oneValue
case twoValue
}
extension Exec {
static func syncQueueWithSpecificKey() -> (Exec, DispatchSpecificKey<Void>) {
let q = DispatchQueue(label: "")
let k = DispatchSpecificKey<Void>()
q.setSpecific(key: k, value: ())
return (Exec.queue(q, .mutex), k)
}
}
class SignalTests: XCTestCase {
func testBasics() {
var results = [Result<Int, SignalEnd>]()
let (i1, out) = Signal<Int>.create { $0.subscribe { r in results.append(r) } }
i1.send(result: .success(1))
i1.send(value: 3)
XCTAssert(out.isClosed == false)
out.cancel()
XCTAssert(out.isClosed == true)
i1.send(value: 5)
XCTAssert(results.at(0)?.value == 1)
XCTAssert(results.at(1)?.value == 3)
withExtendedLifetime(out) {}
let (i2, ep2) = Signal<Int>.create { $0.transform { r in .single(r) }.subscribe { r in results.append(r) } }
i2.send(result: .success(5))
i2.send(end: .other(TestError.zeroValue))
XCTAssert(i2.send(result: .success(0)) == SignalSendError.disconnected)
XCTAssert(results.at(2)?.value == 5)
XCTAssert(results.at(3)?.error?.otherError as? TestError == TestError.zeroValue)
ep2.cancel()
_ = Signal<Int>.preclosed().subscribe { r in results.append(r) }
XCTAssert(results.at(4)?.error?.isComplete == true)
}
func testKeepAlive() {
var results = [Result<Int, SignalEnd>]()
let (i, _) = Signal<Int>.create { $0.subscribeWhile { r in
results.append(r)
return r.value != 7
} }
i.send(value: 5)
i.send(value: 7)
i.send(value: 9)
i.complete()
XCTAssert(results.count == 2)
XCTAssert(results.at(0)?.value == 5)
XCTAssert(results.at(1)?.value == 7)
// A lazily generated sequence of strings
let generatedSignal = Signal<String>.generate { input in
if let i = input {
i.send(value: "🤖")
i.send(value: "🎃")
i.send(value: "😡")
i.send(value: "😈")
}
}
// A subscribeAndKeepAlive retains itself (i.e. doesn't return an output that you must hold) until the signal is closed or until you return false
var results2 = Array<String>()
generatedSignal.subscribeValuesWhile {
results2 += $0
return $0 == "😡" ? false : true
}
XCTAssert(results2.count == 3)
}
func testLifetimes() {
weak var weakOutput1: SignalOutput<Int>? = nil
weak var weakToken: NSObject? = nil
weak var weakSignal1: Signal<Int>? = nil
weak var weakSignal2: Signal<Int>? = nil
var results1 = [Result<Int, SignalEnd>]()
var results2 = [Result<Int, SignalEnd>]()
do {
let (input1, signal1) = Signal<Int>.create()
weakSignal1 = signal1
do {
let endPoint = signal1.subscribe { (r: Result<Int, SignalEnd>) in
results1.append(r)
}
weakOutput1 = endPoint
input1.send(result: .success(5))
XCTAssert(weakOutput1 != nil)
XCTAssert(weakSignal1 != nil)
withExtendedLifetime(endPoint) {}
}
XCTAssert(weakOutput1 == nil)
let (input2, signal2) = Signal<Int>.create()
weakSignal2 = signal2
do {
do {
let token = NSObject()
signal2.subscribeUntilEnd { (r: Result<Int, SignalEnd>) in
withExtendedLifetime(token) {}
results2.append(r)
}
weakToken = token
}
input2.send(result: .success(5))
XCTAssert(weakToken != nil)
XCTAssert(weakSignal2 != nil)
}
XCTAssert(weakToken != nil)
input2.complete()
}
XCTAssert(results1.count == 1)
XCTAssert(results1.at(0)?.value == 5)
XCTAssert(weakSignal1 == nil)
XCTAssert(weakToken == nil)
XCTAssert(results2.count == 2)
XCTAssert(results2.at(0)?.value == 5)
XCTAssert(results2.at(1)?.error?.isComplete == true)
XCTAssert(weakSignal2 == nil)
}
func testCreate() {
// Create a signal with default behavior
let (input, signal) = Signal<Int>.create()
// Make sure we get an .Inactive response before anything is connected
XCTAssert(input.send(result: .success(321)) == SignalSendError.inactive)
// Subscribe
var results = [Result<Int, SignalEnd>]()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let ep1 = signal.subscribe(context: context) { r in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
results.append(r)
}
// Ensure we don't immediately receive anything
XCTAssert(results.count == 0)
// Adding a second subscriber results in an assertion failure at DEBUG time or a SignalSendError.duplicate otherwise
let e = catchBadInstruction {
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
#if DEBUG
XCTFail()
#else
XCTAssert(results2.count == 1)
if case .some(.duplicate) = results2.at(0)?.error?.otherError as? SignalBindError<Int> {
} else {
XCTFail()
}
#endif
withExtendedLifetime(ep2) {}
}
#if DEBUG
XCTAssert(e != nil)
#endif
// Send a value and close
XCTAssert(input.send(result: .success(123)) == nil)
XCTAssert(input.send(result: .failure(SignalEnd.complete)) == nil)
// Confirm sending worked
XCTAssert(results.count == 2)
XCTAssert(results.at(0)?.value == 123)
XCTAssert(results.at(1)?.error?.isComplete == true)
// Confirm we can't send to a closed signal
XCTAssert(input.send(result: .success(234)) == .disconnected)
withExtendedLifetime(ep1) {}
}
func testSignalPassthrough() {
// Create a restartable
let (input, s) = Signal<Int>.create()
let signal = s.multicast()
// We should not be active, yet.
XCTAssert(input.send(result: .success(321)) != nil)
// Subscribe send and close
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
// Ensure we don't immediately receive anything
XCTAssert(results1.count == 0)
// Send a value and close
XCTAssert(input.send(result: .success(123)) == nil)
XCTAssert(results1.count == 1)
XCTAssert(results1.at(0)?.value == 123)
// Subscribe and send again, leaving open
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
XCTAssert(input.send(result: .success(345)) == nil)
XCTAssert(results1.count == 2)
XCTAssert(results1.at(1)?.value == 345)
XCTAssert(results2.count == 1)
XCTAssert(results2.at(0)?.value == 345)
// Add a third subscriber
var results3 = [Result<Int, SignalEnd>]()
let ep3 = signal.subscribe { r in results3.append(r) }
XCTAssert(input.send(result: .success(678)) == nil)
XCTAssert(input.send(result: .failure(.complete)) == nil)
XCTAssert(results1.count == 4)
XCTAssert(results1.at(2)?.value == 678)
XCTAssert(results1.at(3)?.error?.isComplete == true)
XCTAssert(results3.count == 2)
XCTAssert(results3.at(0)?.value == 678)
XCTAssert(results3.at(1)?.error?.isComplete == true)
XCTAssert(results2.count == 3)
XCTAssert(results2.at(1)?.value == 678)
XCTAssert(results2.at(2)?.error?.isComplete == true)
XCTAssert(input.send(result: .success(0)) == .disconnected)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
withExtendedLifetime(ep3) {}
}
func testSignalContinuous() {
// Create a signal
let (input, s) = Signal<Int>.create()
let signal = s.continuous()
// Subscribe twice
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
// Ensure we don't immediately receive anything
XCTAssert(results1.count == 0)
XCTAssert(results2.count == 0)
// Send a value and leave open
XCTAssert(input.send(result: .success(123)) == nil)
// Confirm receipt
XCTAssert(results1.count == 1)
XCTAssert(results1.at(0)?.value == 123)
XCTAssert(results2.count == 1)
XCTAssert(results2.at(0)?.value == 123)
// Subscribe again
var results3 = [Result<Int, SignalEnd>]()
let ep3 = signal.subscribe { r in results3.append(r) }
XCTAssert(results3.count == 1)
XCTAssert(results3.at(0)?.value == 123)
// Send another
XCTAssert(input.send(result: .success(234)) == nil)
// Subscribe again, leaving open
var results4 = [Result<Int, SignalEnd>]()
let ep4 = signal.subscribe { r in results4.append(r) }
XCTAssert(results4.count == 1)
XCTAssert(results4.at(0)?.value == 234)
// Confirm receipt
XCTAssert(results1.count == 2)
XCTAssert(results1.at(1)?.value == 234)
XCTAssert(results2.count == 2)
XCTAssert(results2.at(1)?.value == 234)
XCTAssert(results3.count == 2)
XCTAssert(results3.at(1)?.value == 234)
XCTAssert(results4.count == 1)
XCTAssert(results4.at(0)?.value == 234)
// Close
XCTAssert(input.send(result: .failure(SignalEnd.complete)) == nil)
XCTAssert(results1.count == 3)
XCTAssert(results1.at(2)?.error?.isComplete == true)
XCTAssert(results2.count == 3)
XCTAssert(results2.at(2)?.error?.isComplete == true)
XCTAssert(results3.count == 3)
XCTAssert(results3.at(2)?.error?.isComplete == true)
XCTAssert(results4.count == 2)
XCTAssert(results4.at(1)?.error?.isComplete == true)
// Subscribe again, leaving open
var results5 = [Result<Int, SignalEnd>]()
let ep5 = signal.subscribe { r in results5.append(r) }
XCTAssert(results5.count == 1)
XCTAssert(results5.at(0)?.error?.isComplete == true)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
withExtendedLifetime(ep3) {}
withExtendedLifetime(ep4) {}
withExtendedLifetime(ep5) {}
}
func testSignalContinuousWithinitial() {
// Create a signal
let (input, s) = Signal<Int>.create()
let signal = s.continuous(initialValue: 5)
// Subscribe twice
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
// Ensure we immediately receive the initial
XCTAssert(results1.count == 1)
XCTAssert(results1.at(0)?.value == 5)
XCTAssert(results2.count == 1)
XCTAssert(results2.at(0)?.value == 5)
// Send a value and leave open
XCTAssert(input.send(result: .success(123)) == nil)
// Confirm receipt
XCTAssert(results1.count == 2)
XCTAssert(results1.at(1)?.value == 123)
XCTAssert(results2.count == 2)
XCTAssert(results2.at(1)?.value == 123)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
}
func testSignalPlayback() {
// Create a signal
let (input, s) = Signal<Int>.create()
let signal = s.playback()
// Send a value and leave open
XCTAssert(input.send(result: .success(3)) == nil)
XCTAssert(input.send(result: .success(4)) == nil)
XCTAssert(input.send(result: .success(5)) == nil)
// Subscribe twice
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
// Ensure we immediately receive the values
XCTAssert(results1.count == 3)
XCTAssert(results1.at(0)?.value == 3)
XCTAssert(results1.at(1)?.value == 4)
XCTAssert(results1.at(2)?.value == 5)
XCTAssert(results2.count == 3)
XCTAssert(results2.at(0)?.value == 3)
XCTAssert(results2.at(1)?.value == 4)
XCTAssert(results2.at(2)?.value == 5)
// Send a value and leave open
XCTAssert(input.send(result: .success(6)) == nil)
// Confirm receipt
XCTAssert(results1.count == 4)
XCTAssert(results1.at(3)?.value == 6)
XCTAssert(results2.count == 4)
XCTAssert(results2.at(3)?.value == 6)
// Close
XCTAssert(input.send(result: .failure(SignalEnd.complete)) == nil)
// Subscribe again
var results3 = [Result<Int, SignalEnd>]()
let ep3 = signal.subscribe { r in results3.append(r) }
XCTAssert(results1.count == 5)
XCTAssert(results2.count == 5)
XCTAssert(results3.count == 5)
XCTAssert(results1.at(4)?.error?.isComplete == true)
XCTAssert(results2.at(4)?.error?.isComplete == true)
XCTAssert(results3.at(0)?.value == 3)
XCTAssert(results3.at(1)?.value == 4)
XCTAssert(results3.at(2)?.value == 5)
XCTAssert(results3.at(3)?.value == 6)
XCTAssert(results3.at(4)?.error?.isComplete == true)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
withExtendedLifetime(ep3) {}
}
func testSignalCacheUntilActive() {
// Create a signal
let (input, s) = Signal<Int>.create()
let signal = s.cacheUntilActive()
// Send a value and leave open
XCTAssert(input.send(result: .success(5)) == nil)
do {
// Subscribe once
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
// Ensure we immediately receive the values
XCTAssert(results1.count == 1)
XCTAssert(results1.at(0)?.value == 5)
// Subscribe again
let e = catchBadInstruction {
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
#if DEBUG
XCTFail()
#else
// Ensure error received
XCTAssert(results2.count == 1)
if case .some(.duplicate) = results2.at(0)?.error?.otherError as? SignalBindError<Int> {
} else {
XCTFail()
}
#endif
withExtendedLifetime(ep2) {}
}
#if DEBUG
XCTAssert(e != nil)
#endif
withExtendedLifetime(ep1) {}
}
// Send a value again
XCTAssert(input.send(result: .success(7)) == nil)
do {
// Subscribe once
var results3 = [Result<Int, SignalEnd>]()
let ep3 = signal.subscribe { r in results3.append(r) }
// Ensure we get just the value sent after reactivation
XCTAssert(results3.count == 1)
XCTAssert(results3.at(0)?.value == 7)
withExtendedLifetime(ep3) {}
}
}
func testSignalCustomActivation() {
// Create a signal
let (input, s) = Signal<Int>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let signal = s.customActivation(initialValues: [3, 4], context: context) { (activationValues: inout Array<Int>, preclosed: inout SignalEnd?, result: Result<Int, SignalEnd>) -> Void in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
if case .success(6) = result {
activationValues = [7]
}
}
// Send a value and leave open
XCTAssert(input.send(result: .success(5)) == nil)
// Subscribe twice
var results1 = [Result<Int, SignalEnd>]()
let ep1 = signal.subscribe { r in results1.append(r) }
var results2 = [Result<Int, SignalEnd>]()
let ep2 = signal.subscribe { r in results2.append(r) }
// Ensure we immediately receive the values
XCTAssert(results1.count == 2)
XCTAssert(results1.at(0)?.value == 3)
XCTAssert(results1.at(1)?.value == 4)
XCTAssert(results2.count == 2)
XCTAssert(results2.at(0)?.value == 3)
XCTAssert(results2.at(1)?.value == 4)
// Send a value and leave open
XCTAssert(input.send(result: .success(6)) == nil)
// Confirm receipt
XCTAssert(results1.count == 3)
XCTAssert(results1.at(2)?.value == 6)
XCTAssert(results2.count == 3)
XCTAssert(results2.at(2)?.value == 6)
// Subscribe again
var results3 = [Result<Int, SignalEnd>]()
let ep3 = signal.subscribe { r in results3.append(r) }
XCTAssert(results1.count == 3)
XCTAssert(results2.count == 3)
XCTAssert(results3.at(0)?.value == 7)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
withExtendedLifetime(ep3) {}
}
enum State: Equatable {
static func ==(lhs: State, rhs: State) -> Bool {
switch (lhs, rhs) {
case (.inserted(let vl, let il), .inserted(let vr, let ir)): return vl == vr && il == ir
case (.deleted(let vl, let il), .deleted(let vr, let ir)): return vl == vr && il == ir
case (.reset(let al), .reset(let ar)): return al == ar
default: return false
}
}
case inserted(value: Int, index: Int)
case deleted(value: Int, index: Int)
case reset([Int])
var array: [Int] {
switch self {
case .reset(let a): return a
default: return []
}
}
}
func testReduce() {
enum StackOperation {
case push(Int)
case pop
}
let (input, signal) = Signal<StackOperation>.create()
let reduced = signal.reduce(initialState: [0, 1, 2]) { (state: [Int], message: StackOperation) throws -> [Int] in
switch message {
case .push(let value):
if state.count == 5 {
throw TestError.zeroValue
}
return state.appending(value)
case .pop: return Array(state.dropLast())
}
}
var results1 = [Result<[Int], SignalEnd>]()
reduced.subscribeUntilEnd { r in
results1.append(r)
}
input.send(value: .push(3))
input.send(value: .pop)
input.send(value: .pop)
var results2 = [Result<[Int], SignalEnd>]()
reduced.subscribeUntilEnd { r in
results2.append(r)
}
input.send(value: .push(1))
input.send(value: .push(2))
input.send(value: .push(3))
input.send(value: .push(5))
XCTAssert(results1.count == 8)
XCTAssert(results1.at(0)?.value == [0, 1, 2])
XCTAssert(results1.at(1)?.value == [0, 1, 2, 3])
XCTAssert(results1.at(2)?.value == [0, 1, 2])
XCTAssert(results1.at(3)?.value == [0, 1])
XCTAssert(results1.at(4)?.value == [0, 1, 1])
XCTAssert(results1.at(5)?.value == [0, 1, 1, 2])
XCTAssert(results1.at(6)?.value == [0, 1, 1, 2, 3])
XCTAssertEqual(results1.at(7)?.error?.otherError as? TestError, TestError.zeroValue)
XCTAssert(results2.count == 5)
XCTAssert(results2.at(0)?.value == [0, 1])
XCTAssert(results2.at(1)?.value == [0, 1, 1])
XCTAssert(results2.at(2)?.value == [0, 1, 1, 2])
XCTAssert(results2.at(3)?.value == [0, 1, 1, 2, 3])
XCTAssert(results2.at(4)?.error?.otherError as? TestError == TestError.zeroValue)
}
func testReduceWithInitializer() {
enum StackOperation {
case push(Int)
case pop
}
let (input, signal) = Signal<StackOperation>.create()
let initializer = { (message: StackOperation) -> [Int]? in
switch message {
case .push(let p): return Array(repeating: 1, count: p)
case .pop: return nil
}
}
let reduced = signal.reduce(initializer: initializer) { (state: [Int], message: StackOperation) throws -> [Int] in
switch message {
case .push(let value):
if state.count == 5 {
throw TestError.zeroValue
}
return state.appending(value)
case .pop: return Array(state.dropLast())
}
}
var results1 = [Result<[Int], SignalEnd>]()
reduced.subscribeUntilEnd { r in
results1.append(r)
}
input.send(value: .pop)
input.send(value: .pop)
input.send(value: .push(3))
input.send(value: .pop)
input.send(value: .pop)
var results2 = [Result<[Int], SignalEnd>]()
reduced.subscribeUntilEnd { r in
results2.append(r)
}
input.send(value: .push(1))
input.send(value: .push(2))
input.send(value: .push(3))
input.send(value: .push(5))
input.send(value: .push(8))
XCTAssert(results1.count == 8)
XCTAssert(results1.at(0)?.value == [1, 1, 1])
XCTAssert(results1.at(1)?.value == [1, 1])
XCTAssert(results1.at(2)?.value == [1])
XCTAssert(results1.at(3)?.value == [1, 1])
XCTAssert(results1.at(4)?.value == [1, 1, 2])
XCTAssert(results1.at(5)?.value == [1, 1, 2, 3])
XCTAssert(results1.at(6)?.value == [1, 1, 2, 3, 5])
XCTAssertEqual(results1.at(7)?.error?.otherError as? TestError, TestError.zeroValue)
XCTAssert(results2.count == 6)
XCTAssert(results2.at(0)?.value == [1])
XCTAssert(results2.at(1)?.value == [1, 1])
XCTAssert(results2.at(2)?.value == [1, 1, 2])
XCTAssert(results2.at(3)?.value == [1, 1, 2, 3])
XCTAssert(results2.at(4)?.value == [1, 1, 2, 3, 5])
XCTAssert(results2.at(5)?.error?.otherError as? TestError == TestError.zeroValue)
}
func testPreclosed() {
var results1 = [Result<Int, SignalEnd>]()
_ = Signal<Int>.preclosed(1, 3, 5, end: .other(TestError.oneValue)).subscribe { r in
results1.append(r)
}
XCTAssert(results1.count == 4)
XCTAssert(results1.at(0)?.value == 1)
XCTAssert(results1.at(1)?.value == 3)
XCTAssert(results1.at(2)?.value == 5)
XCTAssert(results1.at(3)?.error?.otherError as? TestError == .oneValue)
var results2 = [Result<Int, SignalEnd>]()
_ = Signal<Int>.preclosed().subscribe { r in
results2.append(r)
}
XCTAssert(results2.count == 1)
XCTAssert(results2.at(0)?.error?.isComplete == true)
var results3 = [Result<Int, SignalEnd>]()
_ = Signal<Int>.preclosed(7).subscribe { r in
results3.append(r)
}
XCTAssert(results3.count == 2)
XCTAssert(results3.at(0)?.value == 7)
XCTAssert(results3.at(1)?.error?.isComplete == true)
}
func testCapture() {
let (input, s) = Signal<Int>.create()
let signal = s.continuous()
input.send(value: 1)
let capture = signal.capture()
var results = [Result<Int, SignalEnd>]()
let (subsequentInput, subsequentSignal) = Signal<Int>.create()
let out = subsequentSignal.subscribe { (r: Result<Int, SignalEnd>) in
results.append(r)
}
// Send a value between construction and bind. This must be *blocked* in the capture queue.
XCTAssert(input.send(result: .success(5)) == nil)
let (values, error) = (capture.values, capture.end)
do {
try capture.bind(to: subsequentInput)
} catch {
XCTFail()
}
input.send(value: 3)
input.complete()
XCTAssert(values == [1])
XCTAssert(error == nil)
XCTAssert(results.count == 3)
XCTAssert(results.at(0)?.value == 5)
XCTAssert(results.at(1)?.value == 3)
XCTAssert(results.at(2)?.error?.isComplete == true)
withExtendedLifetime(out) {}
}
func testCaptureAndSubscribe() {
let (input, output) = Signal<Int>.create { signal in signal.continuous() }
input.send(value: 1)
input.send(value: 2)
do {
let capture = output.capture()
let (values, error) = (capture.values, capture.end)
XCTAssert(values == [2])
XCTAssert(error == nil)
input.send(value: 3)
var results = [Result<Int, SignalEnd>]()
_ = capture.resume().subscribe { r in results += r }
XCTAssert(results.count == 1)
XCTAssert(results.at(0)?.value == 3)
}
do {
let capture = output.capture()
let (values, error) = (capture.values, capture.end)
XCTAssert(values == [3])
XCTAssert(error == nil)
input.send(value: 4)
var results = [Result<Int, SignalEnd>]()
let l = capture.resume(onEnd: { (j, e, i) in
i.send(5, 6, 7)
}).subscribe { r in results += r }
input.complete()
XCTAssert(results.count == 5)
XCTAssert(results.at(0)?.value == 4)
XCTAssert(results.at(1)?.value == 5)
XCTAssert(results.at(2)?.value == 6)
XCTAssert(results.at(3)?.value == 7)
XCTAssert(results.at(4)?.error?.isCancelled == true)
withExtendedLifetime(l) {}
}
withExtendedLifetime(input) {}
}
func testCaptureAndSubscribeValues() {
let (input, output) = Signal<Int>.create { signal in signal.continuous() }
input.send(value: 1)
input.send(value: 2)
do {
let capture = output.capture()
let (values, error) = (capture.values, capture.end)
XCTAssert(values == [2])
XCTAssert(error == nil)
input.send(value: 3)
var results = [Int]()
_ = capture.subscribeValues { r in results += r }
XCTAssert(results.count == 1)
XCTAssert(results.at(0) == 3)
}
do {
let capture = output.capture()
let (values, error) = (capture.values, capture.end)
XCTAssert(values == [3])
XCTAssert(error == nil)
input.send(value: 4)
var results = [Int]()
_ = capture.subscribeValues { r in results += r }
XCTAssert(results.count == 1)
XCTAssert(results.at(0) == 4)
}
withExtendedLifetime(input) {}
}
func testCaptureOnError() {
let (input, s) = Signal<Int>.create()
let signal = s.continuous()
input.send(value: 1)
let capture = signal.capture()
var results = [Result<Int, SignalEnd>]()
let (subsequentInput, subsequentSignal) = Signal<Int>.create()
let ep1 = subsequentSignal.subscribe { (r: Result<Int, SignalEnd>) in
results.append(r)
}
let (values, error) = (capture.values, capture.end)
do {
try capture.bind(to: subsequentInput) { (c: SignalCapture<Int>, e: SignalEnd, i: SignalInput<Int>) in
XCTAssert(c === capture)
XCTAssert(e.isComplete)
i.send(error: TestError.twoValue)
}
} catch {
XCTFail()
}
input.send(value: 3)
input.complete()
XCTAssert(values == [1])
XCTAssert(error == nil)
XCTAssert(results.count == 2)
XCTAssert(results.at(0)?.value == 3)
XCTAssert(results.at(1)?.error?.otherError as? TestError == .twoValue)
let (values2, error2) = (capture.values, capture.end)
XCTAssert(values2.count == 0)
XCTAssert(error2?.isComplete == true)
let pc = Signal<Int>.preclosed(end: .other(TestError.oneValue))
let capture2 = pc.capture()
let (values3, error3) = (capture2.values, capture2.end)
var results2 = [Result<Int, SignalEnd>]()
let (subsequentInput2, subsequentSignal2) = Signal<Int>.create()
let ep2 = subsequentSignal2.subscribe { (r: Result<Int, SignalEnd>) in
results2.append(r)
}
do {
try capture2.bind(to: subsequentInput2, resend: .deferred) { (c, e, i) in
XCTAssert(c === capture2)
XCTAssert(e.otherError as? TestError == .oneValue)
i.send(error: TestError.zeroValue)
}
} catch {
XCTFail()
}
XCTAssert(values3 == [])
XCTAssert(error3?.otherError as? TestError == .oneValue)
XCTAssert(results2.count == 1)
XCTAssert(results2.at(0)?.error?.otherError as? TestError == .zeroValue)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
}
func testGenerate() {
var count = 0
var results = [Result<Int, SignalEnd>]()
weak var lifetimeCheck: Box<Void>? = nil
var nilCount = 0
do {
let closureLifetime = Box<Void>(())
lifetimeCheck = closureLifetime
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let s = Signal<Int>.generate(context: context) { input in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
guard let i = input else {
switch (results.count, nilCount) {
case (0, 0), (6, 0), (12, 1): nilCount += 1
default: XCTFail()
}
return
}
if count == 0 {
count += 1
for j in 0..<5 {
i.send(value: j)
}
i.send(error: TestError.zeroValue)
} else {
for j in 10..<15 {
i.send(value: j)
}
i.send(end: SignalEnd.complete)
}
withExtendedLifetime(closureLifetime) {}
}
do {
let ep1 = s.subscribe { (r: Result<Int, SignalEnd>) in
results.append(r)
}
XCTAssert(results.count == 6)
XCTAssert(results.at(0)?.value == 0)
XCTAssert(results.at(1)?.value == 1)
XCTAssert(results.at(2)?.value == 2)
XCTAssert(results.at(3)?.value == 3)
XCTAssert(results.at(4)?.value == 4)
XCTAssert(results.at(5)?.error?.otherError as? TestError == .zeroValue)
withExtendedLifetime(ep1) {}
}
let ep2 = s.subscribe { (r: Result<Int, SignalEnd>) in
results.append(r)
}
XCTAssert(results.count == 12)
XCTAssert(results.at(6)?.value == 10)
XCTAssert(results.at(7)?.value == 11)
XCTAssert(results.at(8)?.value == 12)
XCTAssert(results.at(9)?.value == 13)
XCTAssert(results.at(10)?.value == 14)
XCTAssert(results.at(11)?.error?.isComplete == true)
XCTAssert(lifetimeCheck != nil)
withExtendedLifetime(ep2) {}
}
XCTAssert(nilCount == 2)
XCTAssert(lifetimeCheck == nil)
}
func testJoinDisconnect() {
var firstInput: SignalInput<Int>? = nil
let sequence1 = Signal<Int>.generate { (input) in
if let i = input {
firstInput = i
for x in 0..<3 {
i.send(value: x)
}
}
}
let sequence2 = Signal<Int>.generate { (input) in
if let i = input {
for x in 3..<6 {
i.send(value: x)
}
}
}
let sequence3 = Signal<Int>.generate { (input) in
if let i = input {
i.send(value: 5)
}
}
var results = [Result<Int, SignalEnd>]()
do {
let (i1, s) = Signal<Int>.create()
let out = s.subscribe { results.append($0) }
let d = sequence1.junction()
try d.bind(to: i1)
i1.send(value: 3)
XCTAssert(results.count == 3)
XCTAssert(results.at(0)?.value == 0)
XCTAssert(results.at(1)?.value == 1)
XCTAssert(results.at(2)?.value == 2)
if let i2 = d.disconnect() {
let d2 = sequence2.junction()
try d2.bind(to: i2)
i2.send(value: 6)
XCTAssert(results.count == 7)
XCTAssert(results.at(3)?.value == 3)
XCTAssert(results.at(4)?.value == 4)
XCTAssert(results.at(5)?.value == 5)
XCTAssert(results.at(6)?.error?.isCancelled == true)
if let i3 = d2.disconnect() {
_ = try d.bind(to: i3)
i3.send(value: 3)
XCTAssert(results.count == 7)
} else {
XCTFail()
}
} else {
XCTFail()
}
withExtendedLifetime(out) {}
} catch {
XCTFail()
}
withExtendedLifetime(firstInput) {}
var results2 = [Result<Int, SignalEnd>]()
let (i4, ep2) = Signal<Int>.create { $0.subscribe {
results2.append($0)
} }
do {
try sequence3.junction().bind(to: i4) { d, e, i in
XCTAssert(e.isCancelled == true)
i.send(value: 7)
i.complete()
}
} catch {
XCTFail()
}
XCTAssert(results2.count == 3)
XCTAssert(results2.at(0)?.value == 5)
XCTAssert(results2.at(1)?.value == 7)
XCTAssert(results2.at(2)?.error?.isComplete == true)
withExtendedLifetime(ep2) {}
}
func testJunctionSignal() {
var results = [Result<Int, SignalEnd>]()
var outputs = [Lifetime]()
do {
let signal = Signal<Int>.generate { i in _ = i?.send(value: 5) }
let (junctionInput, output) = Signal<Int>.create()
try! signal.junction().bind(to: junctionInput) { (j, err, input) in
XCTAssert(err.isCancelled)
input.complete()
}
outputs += output.subscribe { r in results += r }
XCTAssert(results.count == 2)
XCTAssert(results.at(1)?.error?.isComplete == true)
}
results.removeAll()
do {
var input: SignalInput<Int>?
var count = 0
let signal = Signal<Int>.generate { inp in
if let i = inp {
input = i
i.send(value: 5)
count += 1
if count == 3 {
i.complete()
}
}
}
let (junctionInput, output) = Signal<Int>.create()
let junction = signal.junction()
try! junction.bind(to: junctionInput)
outputs += output.subscribe { r in results += r }
XCTAssert(results.count == 1)
XCTAssert(results.at(0)?.value == 5)
junction.rebind()
XCTAssert(results.count == 2)
XCTAssert(results.at(1)?.value == 5)
junction.rebind { (j, err, i) in
XCTAssert(err.isComplete == true)
i.send(error: TestError.zeroValue)
}
XCTAssert(results.count == 4)
XCTAssert(results.at(3)?.error?.otherError as? TestError == TestError.zeroValue)
withExtendedLifetime(input) {}
}
}
func testGraphLoop() {
do {
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Int>.create()
let signal3 = signal2.map { $0 }
let combined = signal1.combine(signal3) { (cr: EitherResult2<Int, Int>) -> Signal<Int>.Next in
switch cr {
case .result1(let r): return .single(r)
case .result2(let r): return .single(r)
}
}.transform { r in .single(r) }.continuous()
let ex = catchBadInstruction {
combined.bind(to: input2)
XCTFail()
}
XCTAssert(ex != nil)
withExtendedLifetime(input1) {}
}
}
func testTransform() {
let (input, signal) = Signal<Int>.create()
var results = [Result<String, SignalEnd>]()
// Test using default behavior and context
let ep1 = signal.transform { (r: Result<Int, SignalEnd>) -> Signal<String>.Next in
switch r {
case .success(let v): return .value("\(v)")
case .failure(let e): return .end(e)
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input.send(value: 0)
input.send(value: 1)
input.send(value: 2)
input.complete()
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == "0")
XCTAssert(results.at(1)?.value == "1")
XCTAssert(results.at(2)?.value == "2")
XCTAssert(results.at(3)?.error?.isComplete == true)
results.removeAll()
// Same again but with transform values
let (input3, signal3) = Signal<Int>.create()
let ep3 = signal3.transformValues { v -> Signal<String>.Next in
return .value("\(v)")
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input3.send(value: 0)
input3.send(value: 1)
input3.send(value: 2)
input3.complete()
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == "0")
XCTAssert(results.at(1)?.value == "1")
XCTAssert(results.at(2)?.value == "2")
XCTAssert(results.at(3)?.error?.isComplete == true)
results.removeAll()
// Test using custom behavior and context
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let (input2, signal2) = Signal<Int>.create()
let ep2 = signal2.transform(context: context) { (r: Result<Int, SignalEnd>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
switch r {
case .success(let v): return .value("\(v)")
case .failure(let e): return .end(e)
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input2.send(value: 0)
input2.send(value: 1)
input2.send(value: 2)
input2.cancel()
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == "0")
XCTAssert(results.at(1)?.value == "1")
XCTAssert(results.at(2)?.value == "2")
XCTAssert(results.at(3)?.error?.isCancelled == true)
withExtendedLifetime(ep1) {}
withExtendedLifetime(ep2) {}
withExtendedLifetime(ep3) {}
}
func testTransformWithState() {
let (input, signal) = Signal<Int>.create()
var results = [Result<String, SignalEnd>]()
// Scope the creation of 't' so we can ensure it is removed before we re-add to the signal.
do {
// Test using default behavior and context
let t = signal.transform(initialState: 10) { (state: inout Int, r: Result<Int, SignalEnd>) -> Signal<String>.Next in
switch r {
case .success(let v):
XCTAssert(state == v + 10)
state += 1
return .value("\(v)")
case .failure(let e): return .end(e);
}
}
let ep1 = t.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input.send(value: 0)
input.send(value: 1)
input.send(value: 2)
input.complete()
withExtendedLifetime(ep1) {}
}
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == "0")
XCTAssert(results.at(1)?.value == "1")
XCTAssert(results.at(2)?.value == "2")
XCTAssert(results.at(3)?.error?.isComplete == true)
results.removeAll()
// Test using custom context
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let (input2, signal2) = Signal<Int>.create()
let ep2 = signal2.transform(initialState: 10, context: context) { (state: inout Int, r: Result<Int, SignalEnd>) -> Signal<String>.Next in
switch r {
case .success(let v):
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
XCTAssert(state == v + 10)
state += 1
return .value("\(v)")
case .failure(let e): return .end(e);
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input2.send(value: 0)
input2.send(value: 1)
input2.send(value: 2)
input2.complete()
withExtendedLifetime(ep2) {}
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == "0")
XCTAssert(results.at(1)?.value == "1")
XCTAssert(results.at(2)?.value == "2")
XCTAssert(results.at(3)?.error?.isComplete == true)
}
func testClosedTriangleGraphLeft() {
var results = [Result<Int, SignalEnd>]()
let (input, signal) = Signal<Int>.create { s in s.multicast() }
let left = signal.transform { (r: Result<Int, SignalEnd>) -> Signal<Int>.Next in
switch r {
case .success(let v): return .value(v * 10)
case .failure: return .error(TestError.oneValue)
}
}
let (mergedInput, mergedSignal) = Signal<Int>.createMergedInput()
mergedInput.add(left, closePropagation: .all)
mergedInput.add(signal, closePropagation: .all)
let out = mergedSignal.subscribe { r in results.append(r) }
input.send(value: 3)
input.send(value: 5)
input.complete()
withExtendedLifetime(out) {}
XCTAssert(results.count == 5)
XCTAssert(results.at(0)?.value == 30)
XCTAssert(results.at(1)?.value == 3)
XCTAssert(results.at(2)?.value == 50)
XCTAssert(results.at(3)?.value == 5)
XCTAssert(results.at(4)?.error?.otherError as? TestError == .oneValue)
}
func testClosedTriangleGraphRight() {
var results = [Result<Int, SignalEnd>]()
let (input, signal) = Signal<Int>.create { s in s.multicast() }
let (mergedInput, mergedSignal) = Signal<Int>.createMergedInput()
mergedInput.add(signal, closePropagation: .all)
let out = mergedSignal.subscribe { r in results.append(r) }
let right = signal.transform { (r: Result<Int, SignalEnd>) -> Signal<Int>.Next in
switch r {
case .success(let v): return .value(v * 10)
case .failure: return .error(TestError.oneValue)
}
}
mergedInput.add(right, closePropagation: .all)
input.send(value: 3)
input.send(value: 5)
input.complete()
withExtendedLifetime(out) {}
XCTAssert(results.count == 5)
XCTAssert(results.at(0)?.value == 3)
XCTAssert(results.at(1)?.value == 30)
XCTAssert(results.at(2)?.value == 5)
XCTAssert(results.at(3)?.value == 50)
XCTAssert(results.at(4)?.error?.isComplete == true)
}
func testMergeSet() {
do {
var results = [Result<Int, SignalEnd>]()
let (mergedInput, mergeSignal) = Signal<Int>.createMergedInput()
let (input, out) = Signal<Int>.create { $0.subscribe { r in results.append(r) } }
let disconnector = mergeSignal.junction()
try disconnector.bind(to: input)
let (input1, signal1) = Signal<Int>.create { $0.cacheUntilActive() }
let (input2, signal2) = Signal<Int>.create { $0.cacheUntilActive() }
let (input3, signal3) = Signal<Int>.create { $0.cacheUntilActive() }
let (input4, signal4) = Signal<Int>.create { $0.cacheUntilActive() }
mergedInput.add(signal1, closePropagation: .none, removeOnDeactivate: false)
mergedInput.add(signal2, closePropagation: .all, removeOnDeactivate: false)
mergedInput.add(signal3, closePropagation: .none, removeOnDeactivate: true)
mergedInput.add(signal4, closePropagation: .none, removeOnDeactivate: false)
input1.send(value: 3)
input2.send(value: 4)
input3.send(value: 5)
input4.send(value: 9)
input1.complete()
let reconnectable = disconnector.disconnect()
try reconnectable.map { try disconnector.bind(to: $0) }
mergedInput.remove(signal4)
input1.send(value: 6)
input2.send(value: 7)
input3.send(value: 8)
input4.send(value: 10)
input2.complete()
input3.complete()
XCTAssert(results.count == 7)
XCTAssert(results.at(0)?.value == 3)
XCTAssert(results.at(1)?.value == 4)
XCTAssert(results.at(2)?.value == 5)
XCTAssert(results.at(3)?.value == 9)
XCTAssert(results.at(4)?.value == 7)
XCTAssert(results.at(5)?.value == 8)
XCTAssert(results.at(6)?.error?.isComplete == true)
withExtendedLifetime(out) {}
} catch {
XCTFail()
}
}
func testSingleInput() {
var results = Array<Result<Int, SignalEnd>>()
let mergeSet = Signal<Int>.mergedChannel().subscribe { r in
results.append(r)
}
mergeSet.input.send(value: 5)
XCTAssert(results.count == 1)
XCTAssert(results.at(0)?.value == 5)
}
func testCombine2() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, context: context) { (cr: EitherResult2<Int, Double>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v)")
case .result1(.failure(let e)): return .value("1 e: \(e)")
case .result2(.success(let v)): return .value("2 v: \(v)")
case .result2(.failure(let e)): return .value("2 e: \(e)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input1.send(value: 1)
input1.send(value: 3)
input1.complete()
input2.send(value: 5.0)
input2.send(value: 7.0)
input2.complete()
XCTAssert(results.count == 6)
XCTAssert(results.at(0)?.value == "1 v: 1")
XCTAssert(results.at(1)?.value == "1 v: 3")
XCTAssert(results.at(2)?.value == "1 e: complete")
XCTAssert(results.at(3)?.value == "2 v: 5.0")
XCTAssert(results.at(4)?.value == "2 v: 7.0")
XCTAssert(results.at(5)?.value == "2 e: complete")
withExtendedLifetime(combined) {}
}
func testCombine2WithState() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, initialState: "", context: context) { (state: inout String, cr: EitherResult2<Int, Double>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
state += "\(results.count)"
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v) \(state)")
case .result1(.failure(let e)): return .value("1 e: \(e) \(state)")
case .result2(.success(let v)): return .value("2 v: \(v) \(state)")
case .result2(.failure(let e)): return .value("2 e: \(e) \(state)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input1.send(value: 1)
input1.send(value: 3)
input1.complete()
input2.send(value: 5.0)
input2.send(value: 7.0)
input2.complete()
XCTAssert(results.count == 6)
XCTAssert(results.at(0)?.value == "1 v: 1 0")
XCTAssert(results.at(1)?.value == "1 v: 3 01")
XCTAssert(results.at(2)?.value == "1 e: complete 012")
XCTAssert(results.at(3)?.value == "2 v: 5.0 0123")
XCTAssert(results.at(4)?.value == "2 v: 7.0 01234")
XCTAssert(results.at(5)?.value == "2 e: complete 012345")
withExtendedLifetime(combined) {}
}
func testCombine3() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, context: context) { (cr: EitherResult3<Int, Double, Int8>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v)")
case .result1(.failure(let e)): return .value("1 e: \(e)")
case .result2(.success(let v)): return .value("2 v: \(v)")
case .result2(.failure(let e)): return .value("2 e: \(e)")
case .result3(.success(let v)): return .value("3 v: \(v)")
case .result3(.failure(let e)): return .value("3 e: \(e)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
XCTAssert(results.count == 9)
XCTAssert(results.at(0)?.value == "3 v: 13")
XCTAssert(results.at(1)?.value == "1 v: 1")
XCTAssert(results.at(2)?.value == "2 v: 5.0")
XCTAssert(results.at(3)?.value == "1 v: 3")
XCTAssert(results.at(4)?.value == "1 e: complete")
XCTAssert(results.at(5)?.value == "3 v: 17")
XCTAssert(results.at(6)?.value == "3 e: complete")
XCTAssert(results.at(7)?.value == "2 v: 7.0")
XCTAssert(results.at(8)?.value == "2 e: complete")
withExtendedLifetime(combined) {}
}
func testCombine3WithState() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, initialState: "", context: context) { (state: inout String, cr: EitherResult3<Int, Double, Int8>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
state += "\(results.count)"
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v) \(state)")
case .result1(.failure(let e)): return .value("1 e: \(e) \(state)")
case .result2(.success(let v)): return .value("2 v: \(v) \(state)")
case .result2(.failure(let e)): return .value("2 e: \(e) \(state)")
case .result3(.success(let v)): return .value("3 v: \(v) \(state)")
case .result3(.failure(let e)): return .value("3 e: \(e) \(state)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
XCTAssert(results.count == 9)
XCTAssert(results.at(0)?.value == "3 v: 13 0")
XCTAssert(results.at(1)?.value == "1 v: 1 01")
XCTAssert(results.at(2)?.value == "2 v: 5.0 012")
XCTAssert(results.at(3)?.value == "1 v: 3 0123")
XCTAssert(results.at(4)?.value == "1 e: complete 01234")
XCTAssert(results.at(5)?.value == "3 v: 17 012345")
XCTAssert(results.at(6)?.value == "3 e: complete 0123456")
XCTAssert(results.at(7)?.value == "2 v: 7.0 01234567")
XCTAssert(results.at(8)?.value == "2 e: complete 012345678")
withExtendedLifetime(combined) {}
}
func testCombine4() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (input4, signal4) = Signal<Int16>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, signal4, context: context) { (cr: EitherResult4<Int, Double, Int8, Int16>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v)")
case .result1(.failure(let e)): return .value("1 e: \(e)")
case .result2(.success(let v)): return .value("2 v: \(v)")
case .result2(.failure(let e)): return .value("2 e: \(e)")
case .result3(.success(let v)): return .value("3 v: \(v)")
case .result3(.failure(let e)): return .value("3 e: \(e)")
case .result4(.success(let v)): return .value("4 v: \(v)")
case .result4(.failure(let e)): return .value("4 e: \(e)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input4.send(value: 11)
input4.send(value: 19)
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
input4.complete()
XCTAssert(results.count == 12)
XCTAssert(results.at(0)?.value == "4 v: 11")
XCTAssert(results.at(1)?.value == "4 v: 19")
XCTAssert(results.at(2)?.value == "3 v: 13")
XCTAssert(results.at(3)?.value == "1 v: 1")
XCTAssert(results.at(4)?.value == "2 v: 5.0")
XCTAssert(results.at(5)?.value == "1 v: 3")
XCTAssert(results.at(6)?.value == "1 e: complete")
XCTAssert(results.at(7)?.value == "3 v: 17")
XCTAssert(results.at(8)?.value == "3 e: complete")
XCTAssert(results.at(9)?.value == "2 v: 7.0")
XCTAssert(results.at(10)?.value == "2 e: complete")
XCTAssert(results.at(11)?.value == "4 e: complete")
withExtendedLifetime(combined) {}
}
func testCombine4WithState() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (input4, signal4) = Signal<Int16>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, signal4, initialState: "", context: context) { (state: inout String, cr: EitherResult4<Int, Double, Int8, Int16>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
state += "\(results.count)"
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v) \(state)")
case .result1(.failure(let e)): return .value("1 e: \(e) \(state)")
case .result2(.success(let v)): return .value("2 v: \(v) \(state)")
case .result2(.failure(let e)): return .value("2 e: \(e) \(state)")
case .result3(.success(let v)): return .value("3 v: \(v) \(state)")
case .result3(.failure(let e)): return .value("3 e: \(e) \(state)")
case .result4(.success(let v)): return .value("4 v: \(v) \(state)")
case .result4(.failure(let e)): return .value("4 e: \(e) \(state)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input4.send(value: 11)
input4.send(value: 19)
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
input4.complete()
XCTAssert(results.count == 12)
XCTAssert(results.at(0)?.value == "4 v: 11 0")
XCTAssert(results.at(1)?.value == "4 v: 19 01")
XCTAssert(results.at(2)?.value == "3 v: 13 012")
XCTAssert(results.at(3)?.value == "1 v: 1 0123")
XCTAssert(results.at(4)?.value == "2 v: 5.0 01234")
XCTAssert(results.at(5)?.value == "1 v: 3 012345")
XCTAssert(results.at(6)?.value == "1 e: complete 0123456")
XCTAssert(results.at(7)?.value == "3 v: 17 01234567")
XCTAssert(results.at(8)?.value == "3 e: complete 012345678")
XCTAssert(results.at(9)?.value == "2 v: 7.0 0123456789")
XCTAssert(results.at(10)?.value == "2 e: complete 012345678910")
XCTAssert(results.at(11)?.value == "4 e: complete 01234567891011")
withExtendedLifetime(combined) {}
}
func testCombine5() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (input4, signal4) = Signal<Int16>.create()
let (input5, signal5) = Signal<Int32>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, signal4, signal5, context: context) { (cr: EitherResult5<Int, Double, Int8, Int16, Int32>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v)")
case .result1(.failure(let e)): return .value("1 e: \(e)")
case .result2(.success(let v)): return .value("2 v: \(v)")
case .result2(.failure(let e)): return .value("2 e: \(e)")
case .result3(.success(let v)): return .value("3 v: \(v)")
case .result3(.failure(let e)): return .value("3 e: \(e)")
case .result4(.success(let v)): return .value("4 v: \(v)")
case .result4(.failure(let e)): return .value("4 e: \(e)")
case .result5(.success(let v)): return .value("5 v: \(v)")
case .result5(.failure(let e)): return .value("5 e: \(e)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input4.send(value: 11)
input4.send(value: 19)
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
input4.complete()
input5.send(value: 23)
input5.send(error: TestError.oneValue)
XCTAssert(results.count == 14)
XCTAssert(results.at(0)?.value == "4 v: 11")
XCTAssert(results.at(1)?.value == "4 v: 19")
XCTAssert(results.at(2)?.value == "3 v: 13")
XCTAssert(results.at(3)?.value == "1 v: 1")
XCTAssert(results.at(4)?.value == "2 v: 5.0")
XCTAssert(results.at(5)?.value == "1 v: 3")
XCTAssert(results.at(6)?.value == "1 e: complete")
XCTAssert(results.at(7)?.value == "3 v: 17")
XCTAssert(results.at(8)?.value == "3 e: complete")
XCTAssert(results.at(9)?.value == "2 v: 7.0")
XCTAssert(results.at(10)?.value == "2 e: complete")
XCTAssert(results.at(11)?.value == "4 e: complete")
XCTAssert(results.at(12)?.value == "5 v: 23")
XCTAssertEqual(results.at(13)?.value, "5 e: \(SignalEnd.other(TestError.oneValue))")
withExtendedLifetime(combined) {}
}
func testCombine5WithState() {
var results = [Result<String, SignalEnd>]()
let (input1, signal1) = Signal<Int>.create()
let (input2, signal2) = Signal<Double>.create()
let (input3, signal3) = Signal<Int8>.create()
let (input4, signal4) = Signal<Int16>.create()
let (input5, signal5) = Signal<Int32>.create()
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
let combined = signal1.combine(signal2, signal3, signal4, signal5, initialState: "", context: context) { (state: inout String, cr: EitherResult5<Int, Double, Int8, Int16, Int32>) -> Signal<String>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
state += "\(results.count)"
switch cr {
case .result1(.success(let v)): return .value("1 v: \(v) \(state)")
case .result1(.failure(let e)): return .value("1 e: \(e) \(state)")
case .result2(.success(let v)): return .value("2 v: \(v) \(state)")
case .result2(.failure(let e)): return .value("2 e: \(e) \(state)")
case .result3(.success(let v)): return .value("3 v: \(v) \(state)")
case .result3(.failure(let e)): return .value("3 e: \(e) \(state)")
case .result4(.success(let v)): return .value("4 v: \(v) \(state)")
case .result4(.failure(let e)): return .value("4 e: \(e) \(state)")
case .result5(.success(let v)): return .value("5 v: \(v) \(state)")
case .result5(.failure(let e)): return .value("5 e: \(e) \(state)")
}
}.subscribe { (r: Result<String, SignalEnd>) in
results.append(r)
}
input4.send(value: 11)
input4.send(value: 19)
input3.send(value: 13)
input1.send(value: 1)
input2.send(value: 5.0)
input1.send(value: 3)
input1.complete()
input3.send(value: 17)
input3.complete()
input2.send(value: 7.0)
input2.complete()
input4.complete()
input5.send(value: 23)
input5.send(error: TestError.oneValue)
XCTAssert(results.count == 14)
XCTAssert(results.at(0)?.value == "4 v: 11 0")
XCTAssert(results.at(1)?.value == "4 v: 19 01")
XCTAssert(results.at(2)?.value == "3 v: 13 012")
XCTAssert(results.at(3)?.value == "1 v: 1 0123")
XCTAssert(results.at(4)?.value == "2 v: 5.0 01234")
XCTAssert(results.at(5)?.value == "1 v: 3 012345")
XCTAssert(results.at(6)?.value == "1 e: complete 0123456")
XCTAssert(results.at(7)?.value == "3 v: 17 01234567")
XCTAssert(results.at(8)?.value == "3 e: complete 012345678")
XCTAssert(results.at(9)?.value == "2 v: 7.0 0123456789")
XCTAssert(results.at(10)?.value == "2 e: complete 012345678910")
XCTAssert(results.at(11)?.value == "4 e: complete 01234567891011")
XCTAssert(results.at(12)?.value == "5 v: 23 0123456789101112")
XCTAssert(results.at(13)?.value == "5 e: \(SignalEnd.other(TestError.oneValue)) 012345678910111213")
withExtendedLifetime(combined) {}
}
func testIsSignalClosed() {
let v1 = Result<Int, SignalEnd>.success(5)
let e1 = Result<Int, SignalEnd>.failure(.cancelled)
let e2 = Result<Int, SignalEnd>.failure(SignalEnd.complete)
let e3 = Result<Int, SignalEnd>.failure(.other(SignalReactiveError.timeout))
XCTAssert(v1.isComplete == false)
XCTAssert(e1.error?.isCancelled == true)
XCTAssert(e2.error?.isComplete == true)
XCTAssert(e3.isComplete == false)
}
func testToggle() {
var results = [Result<Bool, SignalEnd>]()
let (i, out) = Signal<Void>.channel().toggle(initialState: true).subscribe {
results.append($0)
}
i.send(value: ())
i.send(value: ())
i.complete()
XCTAssert(results.count == 4)
XCTAssert(results.at(0)?.value == true)
XCTAssert(results.at(1)?.value == false)
XCTAssert(results.at(2)?.value == true)
XCTAssert(results.at(3)?.error?.isComplete == true)
out.cancel()
}
func testOptionalToArray() {
var results = [Result<[Int], SignalEnd>]()
let (i, out) = Signal<Int?>.channel().optionalToArray().subscribe {
results.append($0)
}
i.send(value: 1)
i.send(value: nil)
i.send(value: 2)
i.send(value: nil)
i.complete()
XCTAssert(results.count == 5)
XCTAssert(results.at(0)?.value?.count == 1)
XCTAssert(results.at(0)?.value?.at(0) == 1)
XCTAssert(results.at(1)?.value?.count == 0)
XCTAssert(results.at(2)?.value?.count == 1)
XCTAssert(results.at(2)?.value?.at(0) == 2)
XCTAssert(results.at(3)?.value?.count == 0)
XCTAssert(results.at(4)?.error?.isComplete == true)
out.cancel()
}
func testReactivateDeadlockBugAndStartWithActivationBug() {
// This bug runs `if itemContextNeedsRefresh` in `send(result:predecessor:activationCount:activated:)` multiple times across different activations and deadlocks if the previous handler is released incorrectly.
// It also tests startWith to ensure that it correctly sends *before* activation values, even though it normally sends during normal phase.
var results = [Result<String?, SignalEnd>]()
let sig1 = Signal<String?>.create { s in s.continuous(initialValue: "hello") }
let sig2 = sig1.composed.startWith("boop")
for _ in 1...3 {
let out = sig2.subscribe(context: .main) { r in results.append(r) }
out.cancel()
}
XCTAssert(results.count == 6)
XCTAssert(results.at(0)?.value.flatMap { $0 } == "boop")
XCTAssert(results.at(1)?.value.flatMap { $0 } == "hello")
XCTAssert(results.at(2)?.value.flatMap { $0 } == "boop")
XCTAssert(results.at(3)?.value.flatMap { $0 } == "hello")
XCTAssert(results.at(4)?.value.flatMap { $0 } == "boop")
XCTAssert(results.at(5)?.value.flatMap { $0 } == "hello")
withExtendedLifetime(sig1.input) {}
}
func testDeferActivation() {
var results = [Result<Int, SignalEnd>]()
let coordinator = DebugContextCoordinator()
let (input, signal) = Signal<Int>.create()
let out = signal.continuous(initialValue: 3).deferActivation().map(context: coordinator.mainAsync) {
return $0 * 2
}.subscribe { (r: Signal<Int>.Result) in
results.append(r)
print(results)
}
XCTAssert(results.isEmpty)
coordinator.runScheduledTasks()
XCTAssert(results.count == 1)
XCTAssert(results.at(0)?.value == 6)
XCTAssert(coordinator.currentTime == 1)
withExtendedLifetime(input) { }
withExtendedLifetime(out) { }
}
func testDropActivation() {
var results = [Result<Int, SignalEnd>]()
let (input, signal) = Signal<Int>.create()
let out = signal.continuous(initialValue: 3).dropActivation().subscribe { r in
results.append(r)
}
XCTAssert(results.isEmpty)
input.send(value: 5)
XCTAssert(results.count == 1)
XCTAssert(results.at(0)?.value == 5)
withExtendedLifetime(input) { }
withExtendedLifetime(out) { }
}
func testReconnector() {
var results = [Result<Int, SignalEnd>]()
var input: SignalInput<Int>? = nil
let upstream = Signal<Int>.generate { i in
input = i
}
var (reconnector, downstream) = upstream.reconnector()
let out = downstream.subscribe { r in
results.append(r)
}
input?.send(0, 1, 2)
reconnector.disconnect()
input?.send(3, 4, 5)
reconnector.reconnect()
input?.send(6, 7, 8)
reconnector.disconnect()
reconnector.disconnect()
input?.send(9, 10, 11)
reconnector.reconnect()
reconnector.reconnect()
input?.send(12, 13, 14)
XCTAssert(results.count == 9)
XCTAssert(results.at(0)?.value == 0)
XCTAssert(results.at(1)?.value == 1)
XCTAssert(results.at(2)?.value == 2)
XCTAssert(results.at(3)?.value == 6)
XCTAssert(results.at(4)?.value == 7)
XCTAssert(results.at(5)?.value == 8)
XCTAssert(results.at(6)?.value == 12)
XCTAssert(results.at(7)?.value == 13)
XCTAssert(results.at(8)?.value == 14)
withExtendedLifetime(input) {}
withExtendedLifetime(out) {}
}
func testSignalLatest() {
let (input, signal) = Signal<Int>.create()
let latest = SignalLatest(signal: signal)
XCTAssert(latest.latestValue == nil)
XCTAssert(latest.latestResult == nil)
input.send(3)
XCTAssert(latest.latestValue == 3)
XCTAssert(latest.latestResult?.value == 3)
input.complete()
XCTAssert(latest.latestValue == nil)
XCTAssert(latest.latestResult?.isComplete == true)
}
func testDeadlockBug() {
let context = Exec.asyncQueue()
let signal1 = Signal.just(1)
.continuous()
let signal2 = signal1
.map(context: context) { 2 * $0 }
.continuous()
let ex = expectation(description: "Waiting to ensure deadlock doesn't occur")
var results = [Result<Int, SignalEnd>]()
let ep = signal2.subscribe {
results.append($0)
ex.fulfill()
}
withExtendedLifetime(ep) {
waitForExpectations(timeout: 2) { error in }
}
XCTAssert(results.at(0)?.error?.isComplete == true)
}
func testSyncMutexAssurances() {
let (context, specificKey) = Exec.syncQueueWithSpecificKey()
var result = [Int]()
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1).transform(context: context) { r -> Signal<Int>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
return .single(r)
}.subscribeValuesUntilEnd {
XCTAssert(DispatchQueue.getSpecific(key: specificKey) == nil)
result.append($0)
}
XCTAssert(result.count == 1)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1).transform(initialState: 0, context: context) { s, r -> Signal<Int>.Next in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
return .single(r)
}.subscribeValuesUntilEnd {
XCTAssert(DispatchQueue.getSpecific(key: specificKey) == nil)
result.append($0)
}
XCTAssert(result.count == 2)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1).reduce(initialState: 0, context: context) { s, r -> Int in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
return r
}.subscribeValuesUntilEnd {
XCTAssert(DispatchQueue.getSpecific(key: specificKey) == nil)
result.append($0)
}
XCTAssert(result.count == 3)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1).customActivation(initialValues: [], context: context) { _, _, _ in
XCTAssert(DispatchQueue.getSpecific(key: specificKey) != nil)
}.subscribeValuesUntilEnd {
XCTAssert(DispatchQueue.getSpecific(key: specificKey) == nil)
result.append($0)
}
XCTAssert(result.count == 4)
}
func testAsyncMutexAssurances() {
let coordinator = DebugContextCoordinator()
let context = coordinator.asyncQueue()
let global = context.relativeAsync()
var result = [Int]()
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1, 2, 3).transform(context: context) { r -> Signal<Int>.Next in
XCTAssert(coordinator.currentThread.matches(context))
return .single(r)
}.subscribeValuesUntilEnd {
XCTAssert(coordinator.currentThread.matches(global))
result.append($0)
}
coordinator.runScheduledTasks()
XCTAssert(result.count == 3)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(1, 2, 3).transform(initialState: 0, context: context) { s, r -> Signal<Int>.Next in
XCTAssert(coordinator.currentThread.matches(context))
return .single(r)
}.subscribeValuesUntilEnd {
XCTAssert(coordinator.currentThread.matches(global))
result.append($0)
}
coordinator.runScheduledTasks()
XCTAssert(result.count == 6)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(0, 2, 3).reduce(initialState: 1, context: context) { s, r -> Int in
XCTAssert(coordinator.currentThread.matches(context))
return r
}.subscribeValuesUntilEnd {
XCTAssert(coordinator.currentThread.matches(global))
result.append($0)
}
coordinator.runScheduledTasks()
XCTAssert(result.count == 9)
// The previous stage's context must *not* be active on a subsequent stage
Signal.just(0, 1, 2, 3).customActivation(initialValues: [], context: context) { _, _, _ in
XCTAssert(coordinator.currentThread.matches(context))
return
}.subscribeValuesUntilEnd {
XCTAssert(coordinator.currentThread.matches(global))
result.append($0)
}
coordinator.runScheduledTasks()
XCTAssert(result.count == 12)
// The previous stage's context must *not* be active on a subsequent stage
Signal.preclosed(1, 2, 3).transform(context: context) { r -> Signal<Int>.Next in
XCTAssert(coordinator.currentThread.matches(context))
return .single(r)
}.subscribeValuesUntilEnd {
XCTAssert(coordinator.currentThread.matches(global))
result.append($0)
}
coordinator.runScheduledTasks()
XCTAssert(result.count == 15)
XCTAssert(result == [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
}
}
class SignalTimingTests: XCTestCase {
@inline(never)
private static func noinlineMapFunction(_ value: Int) -> Result<Int, SignalEnd> {
return Result<Int, SignalEnd>.success(value)
}
#if !SWIFT_PACKAGE
func testSinglePerformance() {
var sequenceLength = 10_000_000
var expected = 4.3 // +/- 0.4
var upperThreshold = 5.0
// Override the test parameters when running in Debug.
#if DEBUG
sequenceLength = 10_000
expected = 0.015 // +/- 0.15
upperThreshold = 0.5
#endif
let t = mach_absolute_time()
var count = 0
// A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance.
_ = Signal<Int>.generate(context: .direct) { input in
guard let i = input else { return }
for v in 0..<sequenceLength {
if let _ = i.send(result: .success(v)) { break }
}
i.complete()
}.subscribe { r in
switch r {
case .success: count += 1
case .failure: break
}
}
XCTAssert(count == sequenceLength)
let elapsed = 1e-9 * Double(mach_absolute_time() - t)
XCTAssert(elapsed < upperThreshold)
print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed) per second.")
// Approximate analogue to Signal architecture (sequence -> lazy map to Result -> iterate -> unwrap)
let t2 = mach_absolute_time()
var count2 = 0
(0..<sequenceLength).lazy.map(SignalTimingTests.noinlineMapFunction).forEach { r in
switch r {
case .success: count2 += 1
case .failure: break
}
}
XCTAssert(count2 == sequenceLength)
let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2)
print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).")
}
func testSyncMapPerformance() {
var sequenceLength = 10_000_000
var expected = 10.0 // +/- 0.4
var upperThreshold = 12.0
// Override the test parameters when running in Debug.
#if DEBUG
sequenceLength = 10_000
expected = 0.03
upperThreshold = 0.5
#endif
let t = mach_absolute_time()
var count = 0
// A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance.
_ = Signal<Int>.generate(context: .direct) { input in
guard let i = input else { return }
for v in 0..<sequenceLength {
if let _ = i.send(result: .success(v)) { break }
}
i.complete()
}.map { v in v }.subscribe { r in
switch r {
case .success: count += 1
case .failure: break
}
}
XCTAssert(count == sequenceLength)
let elapsed = 1e-9 * Double(mach_absolute_time() - t)
XCTAssert(elapsed < upperThreshold)
print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed) per second.")
// Approximate analogue to Signal architecture (sequence -> lazy map to Result -> iterate -> unwrap)
let t2 = mach_absolute_time()
var count2 = 0
(0..<sequenceLength).lazy.map(SignalTimingTests.noinlineMapFunction).forEach { r in
switch r {
case .success: count2 += 1
case .failure: break
}
}
XCTAssert(count2 == sequenceLength)
let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2)
print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).")
}
func testAsyncMapPerformance() {
var sequenceLength = 1_000_000
var expected = 9.9 // +/- 0.4
// Override the test parameters when running in Debug.
#if DEBUG
sequenceLength = 10_000
expected = 0.2
#endif
let t1 = mach_absolute_time()
var count1 = 0
let ex = expectation(description: "Waiting for signal")
// A basic test designed to exercise (sequence -> SignalInput -> SignalNode -> SignalQueue) performance.
let out = Signal<Int>.generate { input in
guard let i = input else { return }
for v in 0..<sequenceLength {
_ = i.send(value: v)
}
}.map(context: .global) { v in v }.subscribeValues(context: .main) { v in
count1 += 1
if count1 == sequenceLength {
ex.fulfill()
}
}
waitForExpectations(timeout: 1e2, handler: nil)
withExtendedLifetime(out) {}
precondition(count1 == sequenceLength)
let elapsed1 = 1e-9 * Double(mach_absolute_time() - t1)
print("Performance is \(elapsed1) seconds versus expected \(expected). Rate is \(Double(sequenceLength) / elapsed1) per second.")
}
@inline(never)
private static func noinlineMapToDepthFunction(_ value: Int, _ depth: Int) -> Result<Int, SignalEnd> {
var result = SignalTimingTests.noinlineMapFunction(value)
for _ in 0..<depth {
switch result {
case .success(let v): result = SignalTimingTests.noinlineMapFunction(v)
case .failure(let e): result = .failure(e)
}
}
return result
}
func testDeepSyncPerformance() {
var sequenceLength = 1_000_000
var expected = 3.4 // +/- 0.4
var upperThreshold = 6.5
// Override the test parameters when running with Debug Assertions.
// This is a hack but it avoids the need for conditional compilation options.
#if DEBUG
sequenceLength = 10_000
expected = 0.2 // +/- 0.15
upperThreshold = 3.0
#endif
let depth = 10
let t = mach_absolute_time()
var count = 0
// Similar to the "Single" performance test but further inserts 100 map nodes between the initial node and the output
var signal = Signal<Int>.generate { (input) in
if let i = input {
for x in 0..<sequenceLength {
i.send(value: x)
}
}
}
for _ in 0..<depth {
signal = signal.transform { r in .single(r) }
}
_ = signal.subscribe { r in
switch r {
case .success: count += 1
case .failure: break
}
}
XCTAssert(count == sequenceLength)
let elapsed = 1e-9 * Double(mach_absolute_time() - t)
XCTAssert(elapsed < upperThreshold)
print("Performance is \(elapsed) seconds versus expected \(expected). Rate is \(Double(sequenceLength * depth) / elapsed) per second.")
let t2 = mach_absolute_time()
var count2 = 0
// Again, as close an equivalent as possible
(0..<sequenceLength).lazy.map { SignalTimingTests.noinlineMapToDepthFunction($0, depth) }.forEach { r in
switch r {
case .success: count2 += 1
case .failure: break
}
}
XCTAssert(count2 == sequenceLength)
let elapsed2 = 1e-9 * Double(mach_absolute_time() - t2)
print("Baseline is is \(elapsed2) seconds (\(elapsed / elapsed2) times faster).")
}
#endif
func testAsynchronousJoinAndDetach() {
#if true
let numRuns = 10
#else
// I've occasionally needed a very high number here to fully exercise some obscure threading bugs. It's not exactly time efficient for common usage.
let numRuns = 10000
#endif
for run in 1...numRuns {
asynchronousJoinAndDetachRun(run: run)
}
}
func asynchronousJoinAndDetachRun(run: Int) {
// This is a multi-threaded graph manipulation test.
// Four threads continually try to disconnect the active graph and attach their own subgraph.
// Important expectations:
// 1. some should succeed to completion
// 2. some should be interrupted
// 3. streams of values should never arrive out-of-order
// NOTE: Parameter tweaking may be required here.
// This method tests thread contention over over a SignalJunction. Doing so may require tweaking of the following parameters to ensure the appropriate amount of contention occurs. A good target is an average of 25% completion and a range between 10% and 50% completion – this should ensure the test remains reliable under a wide range of host conditions.
let sequenceLength = 10
let iterations = 50
let threadCount = 4
let depth = 10
var completionCount = 0
var failureCount = 0
var allOutputs = [String: SignalOutput<(thread: Int, iteration: Int, value: Int)>]()
let junction = Signal<Int>.generate { (input) in
if let i = input {
for x in 0..<sequenceLength {
i.send(value: x)
}
i.complete()
}
}.junction()
let triple = { (j: Int, i: Int, v: Int) -> String in
return "Thread \(j), iteration \(i), value \(v)"
}
let double = { (j: Int, i: Int) -> String in
return "Thread \(j), iteration \(i)"
}
let ex = expectation(description: "Waiting for thread completions")
for j in 0..<threadCount {
Exec.global.invoke {
for i in 0..<iterations {
let (input, s) = Signal<Int>.createMergedInput()
var signal = s.transform(initialState: 0) { (count: inout Int, r: Result<Int, SignalEnd>) -> Signal<(thread: Int, iteration: Int, value: Int)>.Next in
switch r {
case .success(let v): return .value((thread: j, iteration: i, value: v))
case .failure(let e): return .end(e)
}
}
for d in 0..<depth {
signal = signal.transform(initialState: 0, context: .global) { (state: inout Int, r: Result<(thread: Int, iteration: Int, value: Int), SignalEnd>) -> Signal<(thread: Int, iteration: Int, value: Int)>.Next in
switch r {
case .success(let v):
if v.value != state {
XCTFail("Failed at depth \(d)")
}
state += 1
return .value(v)
case .failure(let e): return .end(e)
}
}
}
var results = [String]()
let out = signal.subscribe(context: .direct) { r in
switch r {
case .success(let v): results.append(triple(v.thread, v.iteration, v.value))
case .failure(SignalEnd.complete):
XCTAssert(results.count == sequenceLength)
let expected = Array(0..<results.count).map { triple(j, i, $0) }
let match = results == expected
XCTAssert(match)
if !match {
print("Mismatched on completion:\n\(results)")
}
DispatchQueue.main.async {
completionCount += 1
XCTAssert(allOutputs[double(j, i)] != nil)
allOutputs.removeValue(forKey: double(j, i))
if completionCount + failureCount == iterations * threadCount {
ex.fulfill()
}
}
case .failure(let e):
XCTAssert(e.isComplete == false)
let expected = Array(0..<results.count).map { triple(j, i, $0) }
let match = results == expected
XCTAssert(match)
if !match {
print("Mismatched on interruption:\n\(results)")
}
DispatchQueue.main.async {
failureCount += 1
XCTAssert(allOutputs[double(j, i)] != nil)
allOutputs.removeValue(forKey: double(j, i))
if completionCount + failureCount == iterations * threadCount {
ex.fulfill()
}
}
}
}
DispatchQueue.main.async { allOutputs[double(j, i)] = out }
_ = junction.disconnect()
_ = try? junction.bind(to: input, closePropagation: .all)
}
}
}
// This timeout is relatively low. It's helpful to get a failure message within a reasonable time.
waitForExpectations(timeout: 1e1, handler: nil)
XCTAssert(completionCount + failureCount == iterations * threadCount)
XCTAssert(completionCount > threadCount)
XCTAssert(completionCount < (iterations - 1) * threadCount)
print("Finished run \(run) with completion count \(completionCount) of \(iterations * threadCount) (roughly 25% completion desired)")
}
}
| 32.237161 | 356 | 0.653494 |
bb4837decb85ec523fc5636fddcaa43b5cf6c386 | 3,497 | //
// JavaADTRenderer.swift
// Core
//
// Created by Rahul Malik on 1/19/18.
//
import Foundation
extension JavaModelRenderer {
/*
interface FooADTVisitor<R> {
R match(Pin);
R match(Board);
}
public abstract class FooADT<R> {
[properties here]
private FooADT() {}
public abstract R match Foo(FooADTVisitor<R>);
}
*/
func adtRootsForSchema(property: String, schemas: [SchemaObjectProperty]) -> [JavaIR.Root] {
// Open Q: How should AutoValue/GSON work with this?
// Do we need to create a custom runtime type adapter factory?
let adtName = "\(rootSchema.name)_\(property)"
let formattedADTName = adtName.snakeCaseToCamelCase()
let privateInit = JavaIR.method([.private], "\(formattedADTName)()") { [] }
func interfaceMethods() -> [JavaIR.Method] {
return schemas
.map { typeFromSchema("", $0) }
.map { JavaIR.method([], "R match(\($0))") { [] } }
}
let matcherInterface = JavaIR.Interface(modifiers: [],
extends: nil,
name: "\(formattedADTName)Matcher<R>",
methods: interfaceMethods())
let matcherMethod = JavaIR.method([.public], "R match \(formattedADTName)(\(formattedADTName)Matcher<R>)") { [] }
let internalProperties = schemas.enumerated()
.map { (typeFromSchema("", $0.element), $0.offset) }
.map { JavaIR.Property(modifiers: [.private], type: $0.0, name: "value\($0.1)") }
let enumOptions = schemas.enumerated()
.map { (typeFromSchema("", $0.element.schema.unknownNullabilityProperty())
.split(separator: " ")
.filter { !String($0).hasPrefix("@") }
.map { $0.trimmingCharacters(in: .whitespaces) }
.map { $0.replacingOccurrences(of: "<", with: "") }
.map { $0.replacingOccurrences(of: ">", with: "") }
.map { $0.replacingOccurrences(of: ",", with: "") }
.filter { $0 != "" }
.joined(separator: "_"), $0.offset) }
.map { EnumValue<Int>(defaultValue: $0.1, description: $0.0) }
let internalStorageEnum = JavaIR.Enum(name: "InternalStorage", values: .integer(enumOptions))
let internalStorageProp = JavaIR.Property(modifiers: [.private], type: "@InternalStorage int", name: "internalStorage")
let cls = JavaIR.Class(annotations: [],
modifiers: [.public, .final],
extends: nil,
implements: nil,
name: "\(formattedADTName)<R>",
methods: [
privateInit,
matcherMethod,
],
enums: [internalStorageEnum],
innerClasses: [],
properties: internalProperties + [internalStorageProp])
return [
// Interface
JavaIR.Root.interfaceDecl(aInterface: matcherInterface),
// Class
JavaIR.Root.classDecl(aClass: cls),
// - Properties
// - Private Constructor
// - Match method
]
}
}
| 41.141176 | 127 | 0.495282 |
26d19d8c3224bb13d973886aa68f055fef8ce649 | 8,419 | /* file: characterized_product_concept_feature_category.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -ENTITY DEFINITION in EXPRESS
/*
ENTITY characterized_product_concept_feature_category
SUBTYPE OF ( product_concept_feature_category, characterized_object );
END_ENTITY; -- characterized_product_concept_feature_category (line:9281 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
//MARK: - ALL DEFINED ATTRIBUTES
/*
SUPER- ENTITY(1) group
ATTR: name, TYPE: label -- EXPLICIT (AMBIGUOUS/MASKED)
ATTR: description, TYPE: OPTIONAL text -- EXPLICIT (AMBIGUOUS/MASKED)
ATTR: id, TYPE: identifier -- DERIVED
:= get_id_value( SELF )
SUPER- ENTITY(2) product_concept_feature_category
(no local attributes)
SUPER- ENTITY(3) characterized_object
ATTR: name, TYPE: label -- EXPLICIT (DYNAMIC) (AMBIGUOUS/MASKED)
-- possibly overriden by
ENTITY: shape_feature_definition_element_relationship, TYPE: label (as DERIVED)
ENTITY: shape_feature_fit_relationship, TYPE: label (as DERIVED)
ENTITY: characterized_representation, TYPE: label (as DERIVED)
ENTITY: shape_feature_definition_relationship, TYPE: label (as DERIVED)
ATTR: description, TYPE: OPTIONAL text -- EXPLICIT (DYNAMIC) (AMBIGUOUS/MASKED)
-- possibly overriden by
ENTITY: shape_feature_definition_element_relationship, TYPE: text (as DERIVED)
ENTITY: shape_feature_fit_relationship, TYPE: text (as DERIVED)
ENTITY: characterized_representation, TYPE: text (as DERIVED)
ENTITY: shape_feature_definition_relationship, TYPE: text (as DERIVED)
ENTITY(SELF) characterized_product_concept_feature_category
(no local attributes)
*/
//MARK: - Partial Entity
public final class _characterized_product_concept_feature_category : SDAI.PartialEntity {
public override class var entityReferenceType: SDAI.EntityReference.Type {
eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY.self
}
//ATTRIBUTES
// (no local attributes)
public override var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
//SELECT data types (indirectly) referencing the current type as a member of the select list
members.insert(SDAI.STRING(sGENERAL_ORGANIZATIONAL_DATA_SELECT.typeName)) // -> Self
members.insert(SDAI.STRING(sEVENT_OCCURRENCE_ITEM.typeName)) // -> sGENERAL_ORGANIZATIONAL_DATA_SELECT
return members
}
//VALUE COMPARISON SUPPORT
public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) {
super.hashAsValue(into: &hasher, visited: &complexEntities)
}
public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool {
guard let rhs = rhs as? Self else { return false }
if !super.isValueEqual(to: rhs, visited: &comppairs) { return false }
return true
}
public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? {
guard let rhs = rhs as? Self else { return false }
var result: Bool? = true
if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) {
if !comp { return false }
}
else { result = nil }
return result
}
//EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR
public init() {
super.init(asAbstructSuperclass:())
}
//p21 PARTIAL ENTITY CONSTRUCTOR
public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) {
let numParams = 0
guard parameters.count == numParams
else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil }
self.init( )
}
}
//MARK: - Entity Reference
/** ENTITY reference
- EXPRESS:
```express
ENTITY characterized_product_concept_feature_category
SUBTYPE OF ( product_concept_feature_category, characterized_object );
END_ENTITY; -- characterized_product_concept_feature_category (line:9281 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public final class eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY : SDAI.EntityReference {
//MARK: PARTIAL ENTITY
public override class var partialEntityType: SDAI.PartialEntity.Type {
_characterized_product_concept_feature_category.self
}
public let partialEntity: _characterized_product_concept_feature_category
//MARK: SUPERTYPES
public let super_eGROUP: eGROUP // [1]
public let super_ePRODUCT_CONCEPT_FEATURE_CATEGORY: ePRODUCT_CONCEPT_FEATURE_CATEGORY // [2]
public let super_eCHARACTERIZED_OBJECT: eCHARACTERIZED_OBJECT // [3]
public var super_eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY: eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY { return self } // [4]
//MARK: SUBTYPES
//MARK: ATTRIBUTES
// DESCRIPTION: (2 AMBIGUOUS REFs)
// NAME: (2 AMBIGUOUS REFs)
/// __DERIVE__ attribute
/// - origin: SUPER( ``eGROUP`` )
public var ID: tIDENTIFIER? {
get {
if let cached = cachedValue(derivedAttributeName:"ID") {
return cached.value as! tIDENTIFIER?
}
let origin = super_eGROUP
let value = tIDENTIFIER(origin.partialEntity._id__getter(SELF: origin))
updateCache(derivedAttributeName:"ID", value:value)
return value
}
}
//MARK: INITIALIZERS
public convenience init?(_ entityRef: SDAI.EntityReference?) {
let complex = entityRef?.complexEntity
self.init(complex: complex)
}
public required init?(complex complexEntity: SDAI.ComplexEntity?) {
guard let partial = complexEntity?.partialEntityInstance(_characterized_product_concept_feature_category.self) else { return nil }
self.partialEntity = partial
guard let super1 = complexEntity?.entityReference(eGROUP.self) else { return nil }
self.super_eGROUP = super1
guard let super2 = complexEntity?.entityReference(ePRODUCT_CONCEPT_FEATURE_CATEGORY.self) else { return nil }
self.super_ePRODUCT_CONCEPT_FEATURE_CATEGORY = super2
guard let super3 = complexEntity?.entityReference(eCHARACTERIZED_OBJECT.self) else { return nil }
self.super_eCHARACTERIZED_OBJECT = super3
super.init(complex: complexEntity)
}
public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let entityRef = generic?.entityReference else { return nil }
self.init(complex: entityRef.complexEntity)
}
public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) }
public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) }
//MARK: DICTIONARY DEFINITION
public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition }
private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition()
private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition {
let entityDef = SDAIDictionarySchema.EntityDefinition(name: "CHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY", type: self, explicitAttributeCount: 0)
//MARK: SUPERTYPE REGISTRATIONS
entityDef.add(supertype: eGROUP.self)
entityDef.add(supertype: ePRODUCT_CONCEPT_FEATURE_CATEGORY.self)
entityDef.add(supertype: eCHARACTERIZED_OBJECT.self)
entityDef.add(supertype: eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY.self)
//MARK: ATTRIBUTE REGISTRATIONS
entityDef.addAttribute(name: "ID", keyPath: \eCHARACTERIZED_PRODUCT_CONCEPT_FEATURE_CATEGORY.ID,
kind: .derived, source: .superEntity, mayYieldEntityReference: false)
return entityDef
}
}
}
| 38.619266 | 185 | 0.73346 |
e4054cc1f1d880894fb7508a9592d422d028be73 | 809 | //
// PostTableViewCell.swift
// Instagram
//
// Created by Michelle Caplin on 2/20/18.
// Copyright © 2018 Michelle Caplin. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class PostCell: UITableViewCell {
@IBOutlet weak var postImage: PFImageView!
var post = Post()
@IBOutlet weak var captionLabel: UILabel!
/*var instagramPost: PFObject! {
didSet {
self.postImage.file = instagramPost["media"] as? PFFile
self.postImage.loadInBackground()
}
}*/
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.225 | 67 | 0.635352 |
18dec18c5c879e16e431e96d524ab031313efaaa | 2,162 | //
// AppDelegate.swift
// test
//
// Created by maling on 2018/8/11.
// Copyright © 2018年 maling . 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 | 285 | 0.753932 |
876d96a30ede1b1c766f654ddde7609fe5d4bf12 | 1,497 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* specDomain: S10867 (C-0-T10774-A10775-S10801-S10867-cpt)
*/
public enum EPA_FdV_AUTHZ_DataTypeSetOfIntegerNumbers:Int,CustomStringConvertible
{
case SET_x003C_INT_x003E_
case IVL_x003C_INT_x003E_
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_DataTypeSetOfIntegerNumbers?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_DataTypeSetOfIntegerNumbers?
{
var i = 0
while let item = EPA_FdV_AUTHZ_DataTypeSetOfIntegerNumbers(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case .SET_x003C_INT_x003E_: return "SET<INT>"
case .IVL_x003C_INT_x003E_: return "IVL<INT>"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 22.014706 | 93 | 0.53841 |
e5ae788121a6aff1e5de2df4ab675eaf10305be8 | 251 | //
// Importer.swift
// Gordian Seed Tool
//
// Created by Wolf McNally on 12/22/20.
//
import SwiftUI
protocol Importer: View {
associatedtype ModelType: ImportModel
init(model: ModelType, seed: Binding<ModelSeed?>, shouldScan: Bool)
}
| 16.733333 | 71 | 0.697211 |
769723d01c69ef4628572685be6628d25acf2fb8 | 8,374 | //
// MatchView.swift
// Tinder
//
// Created by Yilei Huang on 2019-05-19.
// Copyright © 2019 Joshua Fang. All rights reserved.
//
import UIKit
import Firebase
protocol goMessageDelegate{
func toMessage(cardUid:String,currentUser:User)
}
class MatchView: UIView {
var currentUser: User!{
didSet{
}
}
var delegate:goMessageDelegate!
static var isMessage = false
var cardUID : String!{
didSet{
Firestore.firestore().collection("users").document(cardUID).getDocument { (snapshot, err) in
guard let dictionary = snapshot?.data() else {return}
let user = User(dictionary: dictionary)
guard let url = URL(string: user.imageUrl1 ?? "") else {return}
self.cardUserImageView.sd_setImage(with: url)
self.descirptionLabel.text = "You and \(user.name ?? "") have liked\n each other"
guard let currentUrl = URL(string: self.currentUser.imageUrl1 ?? "") else{return}
self.currentUserImageView.sd_setImage(with: currentUrl, completed: { (_, _, _, _) in
self.setUpAnimation()
})
}
}
}
fileprivate let itsAMacthImageView: UIImageView = {
let iv = UIImageView(image: #imageLiteral(resourceName: "331558320760_.pic_hd"))
iv.contentMode = .scaleAspectFill
return iv
}()
fileprivate let descirptionLabel: UILabel = {
let label = UILabel()
label.text = "You and x have liked\n each other"
label.textAlignment = .center
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 20)
label.numberOfLines = 0
return label
}()
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
fileprivate let currentUserImageView: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "kelly3"))
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.white.cgColor
return imageView
}()
fileprivate let cardUserImageView: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "kelly3"))
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.white.cgColor
imageView.alpha = 0
return imageView
}()
fileprivate let sendButton: UIButton = {
//let button = SendMessageButton(type: .system)
let button = SendMessageButton(type: .system)
button.setTitle("SEND MESSAGE", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
return button
}()
@objc fileprivate func handleSend(){
MatchView.isMessage = true
delegate?.toMessage(cardUid: cardUID,currentUser: currentUser!)
self.removeFromSuperview()
}
fileprivate let keepSwipingBtn: UIButton = {
let button = KeepSwipingBtn(type: .system)
button.setTitle("Keep Swiping", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(handleTap) , for: .touchUpInside)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupBlurView()
setupLayout()
}
fileprivate func setUpAnimation(){
//starting positions
views.forEach({$0.alpha = 1})
let angle = 30 * CGFloat.pi / 180
currentUserImageView.transform = CGAffineTransform(rotationAngle: -angle).concatenating(CGAffineTransform(translationX: 200, y: 0))
cardUserImageView.transform = CGAffineTransform(rotationAngle: angle).concatenating(CGAffineTransform(translationX: -200, y: 0))
sendButton.transform = CGAffineTransform(translationX: -500, y: 0)
keepSwipingBtn.transform = CGAffineTransform(translationX: 500, y: 0)
UIView.animateKeyframes(withDuration: 1.3, delay: 0, options: .calculationModeCubic, animations: {
//animation 1-translation
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.45, animations: {
self.currentUserImageView.transform = CGAffineTransform(rotationAngle: -angle)
self.cardUserImageView.transform = CGAffineTransform(rotationAngle: angle)
})
//animation2 - rotation
UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.4, animations: {
self.currentUserImageView.transform = .identity
self.cardUserImageView.transform = .identity
})
}) { (_) in
}
UIView.animate(withDuration: 0.75, delay: 0.6 * 1.3, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: {
self.sendButton.transform = .identity
self.keepSwipingBtn.transform = .identity
})
}
lazy var views = [
itsAMacthImageView,
descirptionLabel,
currentUserImageView,
cardUserImageView,
sendButton,
keepSwipingBtn
]
fileprivate func setupLayout(){
views.forEach { (v) in
addSubview(v)
v.alpha = 0
}
itsAMacthImageView.anchor(top: nil, leading: nil, bottom: descirptionLabel.topAnchor, trailing: nil,padding: .init(top: 0, left: 0, bottom: 16, right: 0),size: .init(width: 300, height: 80))
itsAMacthImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
descirptionLabel.anchor(top: nil, leading: self.leadingAnchor, bottom: currentUserImageView.topAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 0, bottom: 32, right: 0),size: .init(width: 0, height: 50))
currentUserImageView.anchor(top: nil, leading: nil, bottom: nil, trailing: centerXAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 16), size: .init(width: 140, height: 140))
currentUserImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
currentUserImageView.layer.cornerRadius = 140/2
cardUserImageView.anchor(top: nil, leading: centerXAnchor, bottom: nil, trailing: nil,padding: .init(top: 0, left: 16, bottom: 0, right: 0),size: .init(width: 140, height: 140))
cardUserImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
cardUserImageView.layer.cornerRadius = 140/2
addSubview(sendButton)
sendButton.anchor(top: currentUserImageView.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor,padding: .init(top: 32, left: 48, bottom: 0, right: 48),size: .init(width: 0, height: 60))
addSubview(keepSwipingBtn)
keepSwipingBtn.anchor(top: sendButton.bottomAnchor, leading: leadingAnchor, bottom: nil, trailing: trailingAnchor,padding: .init(top: 32, left: 48, bottom: 0, right: 48),size: .init(width: 0, height: 60))
}
fileprivate func setupBlurView(){
addSubview(visualEffectView)
visualEffectView.fillSuperview()
visualEffectView.alpha = 0
visualEffectView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
self.visualEffectView.alpha = 1
}) { (_) in
}
}
@objc func handleTap(Tap:UITapGestureRecognizer){
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
self.alpha = 0
}) { (_) in
self.removeFromSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 37.891403 | 225 | 0.625149 |
23f6aadbcb92ace3c54fc1bd9c2b7c8446ee7e70 | 1,136 | //
// KeyboardObserver.swift
// NightscoutServiceKitUI
//
// Created by Pete Schwamb on 9/7/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import Foundation
import SwiftUI
class KeyboardObserver: ObservableObject {
@Published var height: CGFloat = 0
var _center: NotificationCenter
init(center: NotificationCenter = .default) {
_center = center
_center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
_center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyBoardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
withAnimation {
height = keyboardSize.height
}
}
}
@objc func keyBoardWillHide(notification: Notification) {
withAnimation {
height = 0
}
}
}
| 22.27451 | 148 | 0.673415 |
5d0f06db5165a7b20e0eae82102003e934aceea5 | 825 | //
// 🦠 Corona-Warn-App
//
import Foundation
import HealthCertificateToolkit
struct ValidationOnboardedCountriesReceiveModel: CBORDecodable {
// MARK: - Protocol CBORDecoding
static func make(with data: Data) -> Result<ValidationOnboardedCountriesReceiveModel, ModelDecodingError> {
switch OnboardedCountriesAccess().extractCountryCodes(from: data) {
case .success(let countryCodes):
let countries = countryCodes.compactMap {
Country(withCountryCodeFallback: $0)
}
return Result.success(ValidationOnboardedCountriesReceiveModel(countries: countries))
case .failure(let error):
return Result.failure(.CBOR_DECODING_ONBOARDED_COUNTRIES(error))
}
}
// MARK: - Internal
let countries: [Country]
// MARK: - Private
private init(countries: [Country] ) {
self.countries = countries
}
}
| 23.571429 | 108 | 0.756364 |
0ec279deffc2ddb43e37788b3f078703cd8a2541 | 1,719 | // Definition for a binary tree node.
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
extension TreeNode {
func traverseInorder(visit:(TreeNode)->Void) {
self.left?.traverseInorder(visit: visit)
visit(self)
self.right?.traverseInorder(visit: visit)
}
}
class Solution {
func isValidBST2(_ root: TreeNode?) -> Bool {
var data = [Int]()
root?.traverseInorder { (node) in
data.append(node.val)
}
print(data)
//check if array is sorted
for i in 1..<data.count {
if data[i-1] > data[i] {
return false
}
}
return true
}
func isValidBST(_ root: TreeNode?) -> Bool {
return isBst(root, min: Int.min, max: Int.max)
}
private func isBst(_ node: TreeNode?, min: Int, max: Int) -> Bool {
if node == nil { return true }
if node!.val <= min || node!.val >= max { return false }
return isBst(node?.left, min: min, max: node!.val) &&
isBst(node?.right, min: node!.val, max: max)
}
}
let left = TreeNode(5)
left.left = nil
left.right = nil
let right = TreeNode(24)
right.left = TreeNode(20)
right.right = TreeNode(30)
let root = TreeNode.init(15, left, right)
let solution = Solution()
print(solution.isValidBST(root))
| 28.65 | 84 | 0.569517 |
8748d4344ce3be1a347545a2baf478abeb8d2cc3 | 5,575 | //
// Helpers.swift
//
// Created by Christopher Helf on 18.07.16.
// Copyright © 2016 Christopher Helf. All rights reserved.
//
import Foundation
import MetalKit
class Helpers {
struct Vertex {
var x : Float
var y : Float
var z : Float
var color : Float
}
struct TexCoord {
var tx : Float
var ty : Float
}
struct Triangle {
var a: UInt32
var b: UInt32
var c: UInt32
}
struct VertexData {
var x: Float
var y: Float
var z: Float
var tx: Float
var ty: Float
}
class func getVertexSize() -> Int {
return MemoryLayout<Vertex>.size
}
class func getTriangleSize() -> Int {
return MemoryLayout<Triangle>.size
}
class func createFloatBuffer(_ size: Int) -> MTLBuffer {
return MetalContext.sharedContext.device.makeBuffer(length: size, options: MTLResourceOptions())
}
class func buildBuffer(_ radius: Float, rows: Int = 20, columns: Int = 20) -> (MTLBuffer, MTLBuffer, MTLBuffer){
var vertices = [Vertex]()
var texCoords = [TexCoord]()
var triangles = [Triangle]()
let deltaAlpha = Float(2.0 * M_PI) / Float(columns)
let deltaBeta = Float(M_PI) / Float(rows)
for row in 0...rows
{
let beta = Float(row) * deltaBeta
let y = radius * cosf(beta)
let tv = Float(row) / Float(rows)
for col in 0...columns
{
let alpha = Float(col) * deltaAlpha
let x = radius * sinf(beta) * cosf(alpha)
let z = radius * sinf(beta) * sinf(alpha)
let tu = Float(col) / Float(columns)
let vertex = Vertex(x: x, y: y, z: z, color: 0.0)
vertices.append(vertex)
texCoords.append(TexCoord(tx: tu, ty: tv))
}
}
var indices = [UInt32]()
for row in 1...rows
{
let topRow = row - 1
let topIndex = (columns + 1) * topRow
let bottomIndex = topIndex + (columns + 1)
for col in 0...columns
{
indices.append(UInt32(topIndex + col))
indices.append(UInt32(bottomIndex + col))
}
indices.append(UInt32(topIndex))
indices.append(UInt32(bottomIndex))
}
for v in 0..<indices.count-2 {
if v & 1 != 0 {
triangles.append(Triangle(a: indices[v], b: indices[v+1], c: indices[v+2]))
} else {
triangles.append(Triangle(a: indices[v], b: indices[v+2], c: indices[v+1]))
}
}
let tBuf = MetalContext.sharedContext.device.makeBuffer(bytes: &triangles, length: triangles.count * MemoryLayout<Triangle>.size, options: MTLResourceOptions())
let texCoordsBuf = MetalContext.sharedContext.device.makeBuffer(bytes: &texCoords, length: texCoords.count * MemoryLayout<TexCoord>.size, options: MTLResourceOptions())
let vBuf = MetalContext.sharedContext.device.makeBuffer(bytes: &vertices, length: vertices.count * MemoryLayout<Vertex>.size, options: MTLResourceOptions())
return (vBuf, tBuf, texCoordsBuf)
}
class func buildVertexBuffer(_ _n : Int) -> MTLBuffer {
var vals = [Vertex]()
for _ in 0..._n {
vals.append(Vertex(x: 0.0, y: 0.0, z: 0.0, color: 0.0))
}
return MetalContext.sharedContext.device.makeBuffer(bytes: &vals, length: vals.count * 4 * MemoryLayout<Float>.size, options: MTLResourceOptions())
}
class func buildSimpleBuffer(_ radius: Float, rows: Int = 20, columns: Int = 20) -> ([VertexData], [UInt32]){
var vertices = [VertexData]()
let deltaAlpha = Float(2.0 * M_PI) / Float(columns)
let deltaBeta = Float(M_PI) / Float(rows)
for row in 0...rows
{
let beta = Float(row) * deltaBeta
let y = radius * cosf(beta)
let tv = Float(row) / Float(rows)
for col in 0...columns
{
let alpha = Float(col) * deltaAlpha
let x = radius * sinf(beta) * cosf(alpha)
let z = radius * sinf(beta) * sinf(alpha)
let tu = Float(col) / Float(columns)
let vertex = VertexData(x: x, y: y, z: z, tx: tu, ty: tv)
vertices.append(vertex)
}
}
var indices = [UInt32]()
for row in 1...rows
{
let topRow = row - 1
let topIndex = (columns + 1) * topRow
let bottomIndex = topIndex + (columns + 1)
for col in 0...columns
{
indices.append(UInt32(topIndex + col))
indices.append(UInt32(bottomIndex + col))
}
indices.append(UInt32(topIndex))
indices.append(UInt32(bottomIndex))
}
return (vertices, indices)
}
class func buildTriangleIdxBuffer(_ n: Int) -> MTLBuffer {
var indices = [UInt32]()
for i in 0..<n {
indices.append(UInt32(i))
}
return MetalContext.sharedContext.device.makeBuffer(bytes: &indices, length: indices.count * MemoryLayout<UInt32>.size, options: MTLResourceOptions())
}
}
| 32.602339 | 176 | 0.523946 |
d71ab4da164cc3c3d6445fd19c13d2eddc6d95fa | 1,266 | //: [Previous](@previous)
import Foundation
//O(1) -> constant -> This is the best-case scenario. The algorithm takes a constant amount of time.
// let value = array[5]
//O(log n) -> logarithmic -> Great performance. Algorithms having O(logn) time complexity halve the amount of data with each iteration.
func logN(of n: Int) {
var j = 1
while j < n {
j *= 2
}
}
//O(n) -> linear -> Good performance. Assuming there is a queue of 10 people waiting at the billing counter, tending to one customer takes 1 second, so completing the task will take 10 seconds.
let array = [10, 20, 30, 40]
let n = 2
for i in 1...n {
print(array[i])
}
//O(n log n) -> “linearithmic” -> Decent performance. This is a combination of O(n) and O(logn).
for i in 1...n {
var j = 1
while j < n {
j *= 2
}
}
//O(n^2) -> quadratic -> Not ideal. Slower than above runtime.
var totalSumOfProductOfPairs = 0
for i in 1...n {
for j in 1...n {
totalSumOfProductOfPairs += i*j
}
}
//O(n^3) -> cubic -> Poor performance.
for i in 1...n {
for j in 1...n {
for k in 1...n {
// some action here
}
}
}
//O(2^n) -> exponential -> Very poor performance.
//O(n!) -> factorial -> Slowest of all
//: [Next](@next)
| 22.210526 | 194 | 0.602686 |
f7659a83b406757dd7c6c1f6b8ccb4d43823952f | 620 | //
// AppDelegate.swift
// AXPhotoViewerExample
//
// Created by Alex Hill on 5/7/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = TableViewController()
self.window?.makeKeyAndVisible()
return true
}
}
| 23.846154 | 152 | 0.703226 |
1d1044ec6be1915ec2d50e20fd726f18f55230f2 | 14,470 | //
// XRC721Functions.swift
// XDC
//
// Created by Developer on 15/06/21.
//
import Foundation
import BigInt
public enum XRC721Functions {
public static var interfaceId: Data {
return "0x80ac58cd".xdc3.hexData!
}
public struct balanceOf: ABIFunction {
public static let name = "balanceOf"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let owner: XDCAddress
public init(contract: XDCAddress,
from: XDCAddress? = nil,
owner: XDCAddress,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.owner = owner
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(owner)
}
}
public struct ownerOf: ABIFunction {
public static let name = "ownerOf"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let tokenId: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
tokenId: BigUInt,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.tokenId = tokenId
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(tokenId)
}
}
public struct getApproved: ABIFunction {
public static let name = "getApproved"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let tokenId: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
tokenId: BigUInt,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.tokenId = tokenId
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(tokenId)
}
}
public struct transferFrom: ABIFunction {
public static let name = "transferFrom"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let sender: XDCAddress
public let to: XDCAddress
public let tokenId: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
sender: XDCAddress,
to: XDCAddress,
tokenId: BigUInt) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.sender = sender
self.to = to
self.tokenId = tokenId
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(sender)
try encoder.encode(to)
try encoder.encode(tokenId)
}
}
public struct isApprovedForAll: ABIFunction {
public static let name = "isApprovedForAll"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let opearator: XDCAddress
public let owner: XDCAddress
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
opearator: XDCAddress,
owner: XDCAddress
) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.owner = owner
self.opearator = opearator
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(owner)
try encoder.encode(opearator)
}
}
public struct safeTransferFrom: ABIFunction {
public static let name = "safeTransferFrom"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let sender: XDCAddress
public let to: XDCAddress
public let tokenId: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
sender: XDCAddress,
to: XDCAddress,
tokenId: BigUInt) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.sender = sender
self.to = to
self.tokenId = tokenId
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(sender)
try encoder.encode(to)
try encoder.encode(tokenId)
}
}
public struct safeTransferFromAndData: ABIFunction {
public static let name = "safeTransferFrom"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let sender: XDCAddress
public let to: XDCAddress
public let tokenId: BigUInt
public let data: Data
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
sender: XDCAddress,
to: XDCAddress,
tokenId: BigUInt,
data: Data) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.sender = sender
self.to = to
self.tokenId = tokenId
self.data = data
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(sender)
try encoder.encode(to)
try encoder.encode(tokenId)
try encoder.encode(data)
}
}
public struct setApprovalForAll: ABIFunction {
public static let name = "setApprovalForAll"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let to: XDCAddress
public let approved: Bool
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
to: XDCAddress,
approved: Bool) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.to = to
self.approved = approved
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(to)
try encoder.encode(approved)
}
}
public struct approve: ABIFunction {
public static let name = "approve"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let to: XDCAddress
public let tokenId: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil,
to: XDCAddress,
tokenId: BigUInt) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.to = to
self.tokenId = tokenId
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(to)
try encoder.encode(tokenId)
}
}
}
public enum XRC721MetadataFunctions {
public static var interfaceId: Data {
return "name()".xdc3.keccak256.xdc3.bytes4 ^
"symbol()".xdc3.keccak256.xdc3.bytes4 ^
"tokenURI(uint256)".xdc3.keccak256.xdc3.bytes4
}
public struct name: ABIFunction {
public static let name = "name"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws { }
}
public struct symbol: ABIFunction {
public static let name = "symbol"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws { }
}
public struct tokenURI: ABIFunction {
public static let name = "tokenURI"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let tokenID: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
tokenID: BigUInt,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.tokenID = tokenID
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(tokenID)
}
}
}
public enum XRC721EnumerableFunctions {
public static var interfaceId: Data {
return "totalSupply()".xdc3.keccak256.xdc3.bytes4 ^
"tokenByIndex(uint256)".xdc3.keccak256.xdc3.bytes4 ^
"tokenOfOwnerByIndex(address,uint256)".xdc3.keccak256.xdc3.bytes4
}
public struct totalSupply: ABIFunction {
public static let name = "totalSupply"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public init(contract: XDCAddress,
from: XDCAddress? = nil,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws { }
}
public struct tokenByIndex: ABIFunction {
public static let name = "tokenByIndex"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let index: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
index: BigUInt,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.index = index
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(index)
}
}
public struct tokenOfOwnerByIndex: ABIFunction {
public static let name = "tokenOfOwnerByIndex"
public let gasPrice: BigUInt?
public let gasLimit: BigUInt?
public var contract: XDCAddress
public let from: XDCAddress?
public let address: XDCAddress
public let index: BigUInt
public init(contract: XDCAddress,
from: XDCAddress? = nil,
address: XDCAddress,
index: BigUInt,
gasPrice: BigUInt? = nil,
gasLimit: BigUInt? = nil) {
self.contract = contract
self.from = from
self.address = address
self.index = index
self.gasPrice = gasPrice
self.gasLimit = gasLimit
}
public func encode(to encoder: ABIFunctionEncoder) throws {
try encoder.encode(address)
try encoder.encode(index)
}
}
}
| 32.084257 | 77 | 0.530615 |
6149c6c60e6809c733b88958b5924df1d048b14c | 10,702 | //
// NetworkService.swift
// lior-sdk
//
// Created by romaAdmin on 13.11.2019.
// Copyright © 2019 ItWorksinUA. All rights reserved.
//
import Alamofire
import UIKit
// import SwifterSwift
internal extension Dictionary {
func jsonString(prettify: Bool = false) -> String? {
guard JSONSerialization.isValidJSONObject(self) else { return nil }
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) else { return nil }
return String(data: jsonData, encoding: .utf8)
}
}
open class NetworkService {
public typealias EmptyClosure = () -> Void
public typealias ErrorClosure = (Error?) -> Void
public typealias GenericCallback<T> = (T?, Error?) -> Void
public typealias ResponseCallback = GenericCallback<Any>
public static let shared = NetworkService()
var deviceToken: String = UIDevice.current.identifierForVendor?.uuidString ?? ""
private(set) var sessionToken: String?
public var securityCode = "12345"
public func getSessionToken(_ completion: ErrorClosure?) {
request(query: .sessionToken(firebaseID: deviceToken, securityCode: securityCode)) { (sessionToken: SessionToken?, error: Error?) in
if let token = sessionToken?.token {
self.sessionToken = token
completion?(nil)
} else {
completion?(error)
}
}
}
public func registerClientDevice(phoneNumber: String, name: String = UIDevice.current.name, completion: GenericCallback<ClientDevice>?) {
let deviceGuid = UIDevice.current.identifierForVendor!.uuidString
request(query: .registerClient(registrationID: deviceToken, phoneNumber: phoneNumber, deviceName: name, deviceGuid: deviceGuid), completion)
}
public func pullMessageData(status: String, completion: GenericCallback<MessageData>?) {
request(query: .pullMessage(registrationID: deviceToken, status: status), completion)
}
public func sendCallbackData(messageFrom: String, fromDevice: String, toDevice: String, mode: String, status: String, completion: GenericCallback<GenericStatus>?) {
request(query: .callbackData(registrationID: deviceToken, messageFrom: messageFrom, fromDevice: fromDevice, toDevice: toDevice, mode: mode, status: status), completion)
}
public func getCampaignByPhoneNumber(outgoingPhoneNumber: String, completion: GenericCallback<GenericStatus>?) {
request(query: .campaignByPhoneNumber(registrationID: deviceToken, outgoingPhoneNumber: outgoingPhoneNumber), completion)
}
public func respondTopic(fromDevice: String, status: String, completion: GenericCallback<GenericStatus>?) {
request(query: .respondTopic(registrationID: deviceToken, fromDevice: fromDevice, status: status), completion)
}
private func request<T>(query: Query, _ completion: GenericCallback<T>?) where T: Codable, T: BaseResponse {
Alamofire.upload(multipartFormData: { formData in
query.params.forEach { arg0 in
let (key, value) = arg0
guard let valueStr = value as? String, let data = valueStr.data(using: .utf8, allowLossyConversion: false) else { return }
formData.append(data, withName: key)
}
}, to: query.endpoint, method: query.method, headers: query.headers(sessionToken: sessionToken)) { result in
switch result {
case let .success(request, _, _):
request.responseDecodable(completionHandler: { (response: DataResponse<T>) in
switch response.result {
case let .success(value):
if let status = value.status, let code = status.code.flatMap({ Int($0) }) {
if code == 0 {
completion?(value, nil)
return
} else {
completion?(nil, self.error(code: code, message: status.msg ?? ""))
return
}
} else {
completion?(nil, self.error(code: 404, message: "unknown status"))
return
}
case let .failure(error):
completion?(nil, error)
}
})
case let .failure(error):
completion?(nil, error)
}
}
#if DEBUG
let jsonString = query.params.jsonString() ?? ""
print("-------------------------")
print("\(query.method.rawValue.uppercased()) \(query.endpoint)")
let headers = query.headers(sessionToken: sessionToken)
if !headers.isEmpty {
print("HEADERS \(headers.jsonString() ?? "")")
}
print("PARAMS \(jsonString)")
print("-------------------------")
#endif
}
private init() {}
fileprivate enum Query {
case sessionToken(firebaseID: String, securityCode: String)
case registerClient(registrationID: String, phoneNumber: String, deviceName: String, deviceGuid: String)
case pullMessage(registrationID: String, status: String)
case callbackData(registrationID: String, messageFrom: String, fromDevice: String, toDevice: String, mode: String, status: String)
case campaignByPhoneNumber(registrationID: String, outgoingPhoneNumber: String)
case respondTopic(registrationID: String, fromDevice: String, status: String)
fileprivate var endpoint: String {
var path: String
switch self {
case .sessionToken:
path = "/getSessionToken"
case .registerClient:
path = "/registerClientDevice"
case .pullMessage:
path = "/pullMessageData"
case .callbackData:
path = "/sendCallbackData"
case .campaignByPhoneNumber:
path = "/getCampaignByPhoneNumber"
case .respondTopic:
path = "/respondTopic"
}
return "https://picup-server-sdk-v2.appspot.com\(path)"
}
fileprivate var method: HTTPMethod {
return .post
}
fileprivate func headers(sessionToken: String?) -> HTTPHeaders {
var headers: HTTPHeaders = [:]
switch self {
case .sessionToken:
break
default:
guard let sessionToken = sessionToken else { return headers }
headers["Authorization"] = "Bearer \(sessionToken)"
switch self {
case .callbackData, .respondTopic:
headers["User-Agent"] = "PicupSdkMobile"
default:
break
}
}
return headers
}
fileprivate var params: Parameters {
var params: Parameters = [:]
switch self {
case let .sessionToken(firebaseID, securityCode):
params = [
"id": firebaseID,
"code": securityCode,
]
case let .registerClient(registrationID, _, _, _),
let .pullMessage(registrationID, _),
let .callbackData(registrationID, _, _, _, _, _),
let .campaignByPhoneNumber(registrationID, _),
let .respondTopic(registrationID, _, _):
params["registrationID"] = registrationID
switch self {
case let .pullMessage(_, status),
let .callbackData(_, _, _, _, _, status),
let .respondTopic(_, _, status):
params["status"] = status
default: break
}
switch self {
case let .registerClient(_, phoneNumber, deviceName, deviceGuid):
params["phoneNumber"] = phoneNumber
params["deviceName"] = deviceName
params["deviceGuid"] = deviceGuid
case let .callbackData(_, messageFrom, fromDevice, toDevice, mode, _):
params["messageFrom"] = messageFrom
params["fromDevice"] = fromDevice
params["toDevice"] = toDevice
params["mode"] = mode
case let .campaignByPhoneNumber(_, outgoingPhoneNumber):
params["outgoingPhoneNumber"] = outgoingPhoneNumber
case let .respondTopic(_, fromDevice, _):
params["fromDevice"] = fromDevice
default: break
}
}
params["organizationCode"] = "\(555)"
params["sdkVersion"] = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
return params
}
}
fileprivate func error(code: Int, message: String) -> Error {
return NSError(domain: Bundle.main.bundleIdentifier ?? "lior-sdk-internal", code: code, userInfo: [NSLocalizedDescriptionKey: message])
}
}
// MARK: - Alamofire response handlers
private extension DataRequest {
private var decoder: JSONDecoder {
let decoder = JSONDecoder()
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
decoder.dateDecodingStrategy = .iso8601
}
return decoder
}
private var encoder: JSONEncoder {
let encoder = JSONEncoder()
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
encoder.dateEncodingStrategy = .iso8601
}
return encoder
}
func decodableResponseSerializer<T: Decodable>() -> DataResponseSerializer<T> {
return DataResponseSerializer { _, response, data, error in
guard error == nil else { return .failure(error!) }
guard let data = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
return Result { try self.decoder.decode(T.self, from: data) }
}
}
@discardableResult
func responseDecodable<T: Decodable>(queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler)
}
}
| 42.133858 | 176 | 0.580639 |
6170c0e06a3a1f76f24a8d28458dd7648858a869 | 1,986 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MuJoCo",
platforms: [.macOS(.v10_14), .iOS(.v11), .watchOS(.v3), .tvOS(.v10)],
products: [
.library(name: "MuJoCo", type: .static, targets: ["MuJoCo"]),
.executable(name: "simulate", targets: ["simulate"]),
.executable(name: "codegen", targets: ["codegen"]),
],
dependencies: [
.package(
name: "C_mujoco", url: "https://github.com/liuliu/mujoco.git",
.revision("5e2af0b65785d742b9de05c48c75d71354a3d23d")),
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
],
targets: [
.target(
name: "CShim_mujoco",
dependencies: ["C_mujoco"],
path: "Sources/CShim",
sources: [
"CShim.c"
],
publicHeadersPath: "."),
.target(
name: "C_glfw",
path: "Sources/glfw",
sources: ["glfw.c"],
publicHeadersPath: ".",
linkerSettings: [.linkedLibrary("glfw")]),
.target(
name: "MuJoCo",
dependencies: ["CShim_mujoco", "C_glfw", "C_mujoco"],
path: "Sources",
exclude: ["CShim", "glfw", "codegen"]),
.target(
name: "simulate",
dependencies: ["MuJoCo", .product(name: "Numerics", package: "swift-numerics")],
path: "Examples/simulate",
sources: [
"main.swift"
]),
.target(
name: "ChangeCases",
path: "Sources/codegen",
sources: [
"changeCases.swift"
]),
.target(
name: "MuJoCoCSyntax",
dependencies: ["ChangeCases"],
path: "Sources/codegen",
sources: [
"enumDecl.swift",
"functionExtension.swift",
"parseHeaders.swift",
"structExtension.swift",
]),
.target(
name: "codegen",
dependencies: ["MuJoCoCSyntax"],
path: "Sources/codegen",
sources: [
"main.swift"
]),
]
)
| 27.583333 | 96 | 0.572004 |
9b564a1f358be01ef453aa5c09a975415fcd7a01 | 499 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let:{class B{struct a{let:Boolean,A{struct A{struct Q<T where B:o{struct S{enum b{struct B{let:T.E={
| 49.9 | 100 | 0.749499 |
1cfe9a38b0220f92273131c4f2c57c9f9dcd5a2e | 1,684 | //
// ForecastViewModel.swift
// OpenWeatherChallenge
//
// Created by Leonardo Soares on 17/02/22.
//
import Foundation
import RxSwift
typealias GroupedDate = (key: String, value: [Array<Current>.Element])?
class ForecastViewModel: BaseViewModel {
let disposeBag = DisposeBag()
let service: ServiceProtocol
var groupedDates: [GroupedDate]? {
didSet {
self.onLoaded?()
}
}
var numberOfSections: Int {
return self.groupedDates?.count ?? 0
}
init(service: ServiceProtocol) {
self.service = service
}
func loadForecast() {
service.fetch(type: .forecast).subscribe { [weak self] forecast in
let dictionary = Dictionary(grouping: forecast, by: { $0.day })
let sortedDictionary = dictionary.sorted { $0.0 < $1.0 }
self?.groupedDates = sortedDictionary
} onError: { [weak self] error in
guard let self = self else { return }
self.onError?(self.display(error: error as! APIError))
}.disposed(by: disposeBag)
}
func loadImage(icon: String) -> Observable<UIImage?> {
service.loadImage(icon: icon).map { UIImage(data: $0) }
}
func getGroupedDate(for indexPath: IndexPath) -> Current? {
return self.groupedDates?[indexPath.section]?.value[indexPath.item]
}
func getNumberOfItensForSection(for section: Int) -> Int {
return self.groupedDates?[section]?.value.count ?? 0
}
func getTitleForSetion(at indexPath: IndexPath) -> String {
return self.groupedDates?[indexPath.section]?.value[indexPath.item].fullDate ?? ""
}
}
| 29.034483 | 90 | 0.621734 |
1d21f40e942e83c87a8796d55f999a38e67cce2a | 2,562 | // NavigationViewExtensions.swift
// Created by beequri on 02 Apr 2021
/*
MIT License
Copyright (c) 2021 NavigationExplorer (https://github.com/beequri/NavigationExplorer)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
extension NavigationView {
public func showCategoriesForPortraitWithAnimation(completion: (()->())? = nil) {
showCategoriesForPortrait(animation: true)
}
public func showCategoriesForPortraitWithoutAnimation() {
showCategoriesForPortrait(animation: false)
}
public func hideCategoriesForPortraitWithAnimation(completion: (()->())? = nil) {
hideCategoriesForPortrait(animation: true)
}
public func hideCategoriesForPortraitWithoutAnimation() {
hideCategoriesForPortrait(animation: false)
}
public func showCategoriesForLandscapeWithAnimation(completion: (()->())? = nil) {
showCategoriesForLandscape(animation: true)
}
public func showCategoriesForLandscapeWithoutAnimation() {
showCategoriesForLandscape(animation: false)
}
public func hideCategoriesForLandscapeWithAnimation(completion: (()->())? = nil) {
hideCategoriesForLandscape(animation: true)
}
public func hideCategoriesForLandscapeWithoutAnimation() {
hideCategoriesForLandscape(animation: false)
}
}
extension NavigationView {
var isLandscape: Bool {
UIViewController.isLandscape
}
var loginShadowHeight: CGFloat {
return isLandscape == true ? 120.0 : 20.0
}
}
| 34.621622 | 86 | 0.735363 |
6123da7b6781afe1678a818b2573294edca05d22 | 1,203 | //
// The MIT License (MIT)
//
// Copyright (c) 2021 David Costa Gonçalves
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
public struct ZomatoUIKit {
}
| 40.1 | 80 | 0.755611 |
7515ea8023ab9fa9526993913454ac78b296f0e6 | 2,879 | //
// Copyright © 2015 Apple Inc. All Rights Reserved.
// See LICENSE.txt for this sample’s licensing information
//
// Modified by Andrew Podkovyrin, 2019
//
import Foundation
import SystemConfiguration
/**
This is a condition that performs a very high-level reachability check.
It does *not* perform a long-running reachability check, nor does it respond to changes in reachability.
Reachability is evaluated once when the operation to which this is attached is asked about its readiness.
*/
struct ReachabilityCondition: OperationCondition {
static let name = "Reachability"
static let isMutuallyExclusive = false
let host: URL
init(host: URL) {
self.host = host
}
func dependency(for operation: ANOperation) -> Operation? {
return nil
}
func evaluate(for operation: ANOperation, completion: @escaping (OperationConditionResult) -> Void) {
ReachabilityController.requestReachability(host) { reachable in
if reachable {
completion(.success)
}
else {
let error = OperationError.reachabilityConditionFailed(host: self.host)
completion(.failure(error))
}
}
}
}
/// A private singleton that maintains a basic cache of `SCNetworkReachability` objects.
private class ReachabilityController {
static var reachabilityRefs = [String: SCNetworkReachability]()
static let reachabilityQueue = DispatchQueue(label: "Operations.Reachability", qos: .default, attributes: [])
static func requestReachability(_ url: URL, completionHandler: @escaping (Bool) -> Void) {
guard let host = url.host else {
completionHandler(false)
return
}
reachabilityQueue.async {
var ref = self.reachabilityRefs[host]
if ref == nil {
let hostString = host as NSString
if let nodename = hostString.utf8String {
ref = SCNetworkReachabilityCreateWithName(nil, nodename)
}
}
if let ref = ref {
self.reachabilityRefs[host] = ref
var reachable = false
var flags: SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(ref, &flags) {
/*
Note that this is a very basic "is reachable" check.
Your app may choose to allow for other considerations,
such as whether or not the connection would require
VPN, a cellular connection, etc.
*/
reachable = flags.contains(.reachable)
}
completionHandler(reachable)
}
else {
completionHandler(false)
}
}
}
}
| 33.091954 | 113 | 0.599514 |
e41250444ecce4a1dcb3790e7f42ba7d394cca62 | 492 | //
// UINavigationController+Extension.swift
// EverydayExtensions
//
// Created by Nick Sorge on 11.09.19.
// Copyright © 2019 Nick Sorge. All rights reserved.
//
import UIKit
public extension UINavigationController {
// MARK: - Public Properties
var rootViewController: UIViewController? {
return viewControllers.first
}
override var preferredStatusBarStyle: UIStatusBarStyle {
visibleViewController?.preferredStatusBarStyle ?? .lightContent
}
}
| 22.363636 | 71 | 0.723577 |
1126670e13d20394fed5b0175bb58d04a91e0fde | 2,910 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import SotoCore
/// Error enum for RUM
public struct RUMErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case conflictException = "ConflictException"
case internalServerException = "InternalServerException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceQuotaExceededException = "ServiceQuotaExceededException"
case throttlingException = "ThrottlingException"
case validationException = "ValidationException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize RUM
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// You don't have sufficient permissions to perform this action.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// This operation attempted to create a resource that already exists.
public static var conflictException: Self { .init(.conflictException) }
/// Internal service exception.
public static var internalServerException: Self { .init(.internalServerException) }
/// Resource not found.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// This request exceeds a service quota.
public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) }
/// The request was throttled because of quota limits.
public static var throttlingException: Self { .init(.throttlingException) }
/// One of the arguments for the request is not valid.
public static var validationException: Self { .init(.validationException) }
}
extension RUMErrorType: Equatable {
public static func == (lhs: RUMErrorType, rhs: RUMErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension RUMErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 37.792208 | 99 | 0.672509 |
efbb314377931bff7965292a6edaf7ba55ebbf97 | 1,634 | //
// TouchViewController.swift
// iOSDemo
//
// Created by Stan Hu on 17/11/2017.
// Copyright © 2017 Stan Hu. All rights reserved.
//
import UIKit
import SnapKit
class TouchViewController: UIViewController {
var arrData = ["Touch Test"]
var tbMenu = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
tbMenu.dataSource = self
tbMenu.delegate = self
tbMenu.tableFooterView = UIView()
view.addSubview(tbMenu)
tbMenu.snp.makeConstraints { (m) in
m.edges.equalTo(0)
}
}
}
extension TouchViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = arrData[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
navigationController?.pushViewController(TouchTestViewController(), animated: true)
case 1:
break
case 2:
break
case 3:
break
default:
break
}
}
}
| 27.233333 | 100 | 0.629743 |
09bbf1509eddc8a2f1b9f163488de413683fc9ee | 185 | import Combine
var subscription = Set<AnyCancellable>()
["a", "1", "3.1"].publisher
.compactMap({ Float($0) })
.sink(receiveValue: { print($0)})
.store(in: &subscription)
| 20.555556 | 40 | 0.621622 |
f9e03fdd14251caf48720b2f4856aa3ae390a146 | 2,610 | //
// Copyright (c) 2018 Muukii <[email protected]>
//
// 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 PixelEngine
open class ShadowsControlBase : FilterControlBase {
public required init(context: PixelEditContext) {
super.init(context: context)
}
}
open class ShadowsControl : ShadowsControlBase {
open override var title: String {
return L10n.editShadows
}
private let navigationView = NavigationView()
public let slider = StepSlider(frame: .zero)
open override func setup() {
super.setup()
backgroundColor = Style.default.control.backgroundColor
TempCode.layout(navigationView: navigationView, slider: slider, in: self)
slider.addTarget(self, action: #selector(valueChanged), for: .valueChanged)
navigationView.didTapCancelButton = { [weak self] in
self?.context.action(.revert)
self?.pop(animated: true)
}
navigationView.didTapDoneButton = { [weak self] in
self?.context.action(.commit)
self?.pop(animated: true)
}
}
open override func didReceiveCurrentEdit(_ edit: EditingStack.Edit) {
slider.set(value: edit.filters.shadows?.value ?? 0, in: FilterShadows.range)
}
@objc
private func valueChanged() {
let value = slider.transition(in: FilterShadows.range)
guard value != 0 else {
context.action(.setFilter({ $0.shadows = nil }))
return
}
var f = FilterShadows()
f.value = value
context.action(.setFilter({ $0.shadows = f }))
}
}
| 30 | 80 | 0.701149 |
ab2afa320e0512637acabdb1e29f2171cc516d16 | 1,409 | //
// WTestUITests.swift
// WTestUITests
//
// Created by Carlos Correa on 06/03/2021.
//
import XCTest
class WTestUITests: 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, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.767442 | 182 | 0.654365 |
bf29d98e2b156f89872af2038aa67eca1a06596f | 1,106 | //
// MenuHeaderView.swift
// WeatherApp
//
// Created by Alexander Rojas Benavides on 3/19/21.
//
import Foundation
import SwiftUI
struct MenuHeaderView: View {
@ObservedObject var cityVM: CityViewModel
@State private var searchTerm = "Ciudad Quesada"
var body: some View {
HStack {
TextField("", text: $searchTerm)
.padding(.leading, 20)
Button {
cityVM.city = searchTerm
} label: {
ZStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue)
Image(systemName: "location.fill")
}
}
.frame(width: 50, height: 50)
}
.foregroundColor(.white)
.padding()
.background(ZStack(alignment: .leading) {
Image(systemName: "magnifyingglass")
.foregroundColor(.white)
.padding(.leading, 10)
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue.opacity(0.5))
})
}
}
| 25.72093 | 54 | 0.505425 |
f490d02944ed87d9bd866e4584fb434d90fb8ba4 | 2,068 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// A disposable container that will dispose a collection of disposables upon deinit.
public final class DisposeBag: DisposableType {
private var disposables: [DisposableType] = []
/// This will return true whenever the bag is empty.
public var isDisposed: Bool {
return disposables.count == 0
}
public init() {
}
/// Adds the given disposable to the bag.
/// DisposableType will be disposed when the bag is deinitialized.
public func addDisposable(disposable: DisposableType) {
disposables.append(disposable)
}
/// Disposes all disposables that are currenty in the bag.
public func dispose() {
for disposable in disposables {
disposable.dispose()
}
disposables = []
}
deinit {
dispose()
}
}
public extension DisposableType {
public func disposeIn(disposeBag: DisposeBag) {
disposeBag.addDisposable(self)
}
}
| 33.901639 | 85 | 0.723404 |
fb4212c4716a280e3615ab5d5ad4ba0378f8bdc4 | 445 | //
// HomePresenter.swift
// AndesUI_Example
//
// Created by Santiago Lazzari on 19/12/2019.
// Copyright © 2019 MercadoLibre. All rights reserved.
//
import UIKit
class HomePresenter {
private let router = HomeAppRouter()
unowned var viewController: UIViewController?
func present(view: TestappViews) {
if let vc = self.viewController {
self.router.doRoute(fromVC: vc, newRouter: view)
}
}
}
| 21.190476 | 60 | 0.667416 |
1e9e5a0f3dd9c659bfd03cd32ea9fa3806a8d3f5 | 8,486 | //
// PeiqiView.swift
// FaceIt
//
// Created by PengZK on 2018/5/21.
// Copyright © 2018年 KUN. All rights reserved.
//
import UIKit
@IBDesignable
class PeiqiView: UIView {
var scale : CGFloat = 0.5
var lineWidth : CGFloat = 4.0
var bgColor : UIColor = UIColor(red: 255 / 255.0, green: 179 / 255.0, blue: 218 / 255.0, alpha: 1.0)
var borderColor : UIColor = UIColor(red: 239 / 255.0, green: 150 / 255.0, blue: 194 / 255.0, alpha: 1.0)
private var skullRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
private var skullCenter: CGPoint {
return CGPoint(x: bounds.midX, y: bounds.midY)
}
private enum Eye {
case left
case right
}
private enum Ear {
case left
case right
}
private func drawPathForEye(_ eye: Eye)
{
func centerOfEye(_ eye: Eye) -> CGPoint {
let eyeOffset = skullRadius / Ratios.skullRadiusToEyeOffset
var eyeCenter = skullCenter
eyeCenter.y -= eyeOffset
eyeCenter.x += ((eye == .left) ? 0 : 2) * eyeOffset
return eyeCenter
}
let eyeRadius = skullRadius / Ratios.skullRadiusToEyeRadius
let eyeCenter = centerOfEye(eye)
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
path.lineWidth = lineWidth
UIColor.white.setFill()
path.fill()
let eyeballRadius = eyeRadius * 0.4
let eyeballPath = UIBezierPath(arcCenter: CGPoint(x: eyeCenter.x - eyeballRadius - 1, y: eyeCenter.y - 1), radius: eyeballRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
UIColor.black.setFill()
eyeballPath.fill()
path.stroke()
}
private func drawPathForMouth()
{
let mouthWidth = skullRadius / Ratios.skullRadiusToMouthWidth
let mouthHeight = skullRadius / Ratios.skullRadiusToMouthHeight
let mouthOffset = skullRadius / Ratios.skullRadiusToMouthOffset
let mouthRect = CGRect(
x: skullCenter.x - mouthWidth * 0,
y: skullCenter.y + mouthOffset,
width: mouthWidth,
height: mouthHeight
)
let smileOffset_down = 1.0 * mouthRect.height
let smileOffset_up = 0.5 * mouthRect.height
let start = CGPoint(x: mouthRect.minX, y: mouthRect.midY)
let end = CGPoint(x: mouthRect.maxX, y: mouthRect.midY)
let path = UIBezierPath()
path.move(to: start)
// let cp1 = CGPoint(x: start.x + mouthRect.width / 3, y: start.y + smileOffset_down)
// let cp2 = CGPoint(x: end.x - mouthRect.width / 3, y: start.y + smileOffset_down)
// path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2)
path.addQuadCurve(to: end, controlPoint: CGPoint(x: start.x + mouthRect.width / 2, y: start.y + smileOffset_down))
path.move(to: end)
path.addQuadCurve(to: start, controlPoint: CGPoint(x: start.x + mouthRect.width / 2, y: start.y + smileOffset_up))
path.lineWidth = lineWidth
UIColor.black.setFill()
path.fill()
UIColor(red: 206 / 255.0, green: 66 / 255.0, blue: 118 / 255.0, alpha: 1).setStroke()
path.stroke()
}
private func drawPathForSkull()
{
let path = UIBezierPath(ovalIn: CGRect(x: skullCenter.x - skullRadius * 0.7, y: skullCenter.y - skullRadius * 0.4, width: skullRadius * 2.0, height: skullRadius * 1.5))
path.lineWidth = lineWidth
bgColor.setFill()
path.fill()
path.stroke()
let blankPath = UIBezierPath(rect: CGRect(x: skullCenter.x - skullRadius * 0.8, y: skullCenter.y + skullRadius * 0.2, width: skullRadius, height: skullRadius))
UIColor.white.setFill()
blankPath.fill()
let linePath1 = UIBezierPath()
linePath1.lineWidth = lineWidth
let start = CGPoint(x: skullCenter.x - skullRadius * 0.7, y: skullCenter.y + skullRadius * 0.2)
let end1 = CGPoint(x: skullCenter.x - skullRadius * 0.1, y: skullCenter.y + skullRadius * 0.4)
let end2 = CGPoint(x: skullCenter.x + skullRadius * 0.2 + 1, y: skullCenter.y + skullRadius + 9)
linePath1.move(to: start)
linePath1.addQuadCurve(to: end1, controlPoint: CGPoint(x: skullCenter.x - skullRadius * 0.6, y: skullCenter.y + skullRadius * 0.5))
linePath1.move(to: CGPoint(x: skullCenter.x - skullRadius * 0.15, y: skullCenter.y + skullRadius * 0.4))
linePath1.addQuadCurve(to: end2, controlPoint: CGPoint(x: skullCenter.x - skullRadius * 0.2, y: skullCenter.y + skullRadius * 0.9))
bgColor.setFill()
linePath1.fill()
linePath1.stroke()
let linePath2 = UIBezierPath()
linePath2.lineWidth = 0
linePath2.move(to: CGPoint(x: skullCenter.x + skullRadius * 0.2, y: skullCenter.y + skullRadius + 7))
linePath2.addLine(to: CGPoint(x: skullCenter.x + skullRadius * 0.2 + 1, y: skullCenter.y + skullRadius * 0.2))
linePath2.addLine(to: CGPoint(x: skullCenter.x - skullRadius * 0.7, y: skullCenter.y + skullRadius * 0.2 - 2))
linePath2.addLine(to: CGPoint(x: skullCenter.x - skullRadius * 0.15 - 1, y: skullCenter.y + skullRadius * 0.4))
// linePath2.close()
bgColor.setFill()
linePath2.fill()
}
private func drawPathForEar(_ ear: Ear)
{
func centerOfEar(_ ear: Ear) -> CGPoint {
let earOffset = skullRadius / Ratios.skullRadiusToEarOffset
var earCenter = CGPoint(x: skullCenter.x, y: skullCenter.y - skullRadius * 0.4)
earCenter.y -= 0.5 * earOffset
earCenter.x += ((ear == .left) ? 1 : 3) * earOffset
return earCenter
}
let earRadius = skullRadius / Ratios.skullRadiusToEarRadius
let earCenter = centerOfEar(ear)
let path = UIBezierPath(ovalIn: CGRect(x: earCenter.x - earRadius, y: earCenter.y - earRadius, width: earRadius, height: earRadius * 2.0))
path.lineWidth = lineWidth
bgColor.setFill()
path.fill()
path.stroke()
}
private func drawPathForNose()
{
let path = UIBezierPath(ovalIn: CGRect(x: skullCenter.x - 66, y: skullCenter.y - 4, width: 30, height: 40))
path.lineWidth = lineWidth
//旋转
// path.apply(CGAffineTransform(rotationAngle: -0.6 / 180.0 * CGFloat.pi))
bgColor.setFill()
path.fill()
let nostrilPath = UIBezierPath(ovalIn: CGRect(x: skullCenter.x - 62, y: skullCenter.y + 13, width: 8, height: 8))
UIColor(red: 213 / 255.0, green: 97 / 255.0, blue: 144 / 255.0, alpha: 1).setFill()
nostrilPath.fill()
let nostrilPath_right = UIBezierPath(ovalIn: CGRect(x: skullCenter.x - 51, y: skullCenter.y + 10, width: 8, height: 8))
UIColor(red: 213 / 255.0, green: 97 / 255.0, blue: 144 / 255.0, alpha: 1).setFill()
nostrilPath_right.fill()
path.stroke()
}
private func drawPathForBlusher()
{
let path = UIBezierPath(ovalIn: CGRect(x: skullCenter.x + 68, y: skullCenter.y - 10, width: 33, height: 40))
UIColor(red: 255 / 255.0, green: 139 / 255.0, blue: 199 / 255.0, alpha: 0.6).setFill()
path.fill()
}
override func draw(_ rect: CGRect) {
// Drawing code
borderColor.setStroke()
// 耳朵
drawPathForEar(.left)
drawPathForEar(.right)
// 脑壳
drawPathForSkull()
// 眼睛👀
drawPathForEye(.left)
drawPathForEye(.right)
// 鼻子
drawPathForNose()
// 腮红
drawPathForBlusher()
// 嘴巴
drawPathForMouth()
self.layer.transform = CATransform3DRotate(CATransform3DIdentity, CGFloat.pi * 30 / 180.0, 0, 0, 1)
}
private struct Ratios {
static let skullRadiusToEyeOffset: CGFloat = 6
static let skullRadiusToEyeRadius: CGFloat = 9
static let skullRadiusToEarOffset: CGFloat = 5
static let skullRadiusToEarRadius: CGFloat = 4
static let skullRadiusToMouthWidth: CGFloat = 1.4
static let skullRadiusToMouthHeight: CGFloat = 1.7
static let skullRadiusToMouthOffset: CGFloat = 4.8
}
}
| 39.105991 | 195 | 0.603111 |
2f8756e57234f4bd8c2806a78e25dfc02fa7fe4d | 3,236 | //
// ListOfPlaces.swift
// firstDemo
//
// Created by Никита Дубовик on 09.05.2021.
//
import SwiftUI
import MapKit
struct PlacesList: View {
@ObservedObject var viewmodel: MainViewModel
@Binding var userLocation: CLLocationCoordinate2D?
@State var isFounded = true
@State var showAboutUs = false
var body: some View {
NavigationView {
VStack {
ScrollView {
VStack(spacing: 7) {
Text(isFounded ? "Looking for owner" : "Looking for pet").font(.headline)
.foregroundColor(.black).frame(width: UIScreen.main.bounds.width - 10, alignment: .center)
ForEach(viewmodel.places.sorted{ $0.publishTime! > $1.publishTime!}.filter{ $0.isFounded == self.isFounded } ) { place in
NavigationLink(destination: ListItemView(item: place, userLocation: $userLocation)) {
ListItem(item: place)
}
}
}
}
}.sheet(isPresented: $showAboutUs, content: {
AboutView(showAboutUs: $showAboutUs)
}).offset(x: 0, y: -20).toolbar {
ToolbarItem(placement: .navigation) {
Text("Recent").font(.largeTitle).fontWeight(.bold).padding(.leading).padding(.top, 10)
}
}.navigationBarItems(trailing:
HStack {
Button(action: {
isFounded.toggle()
}) {
Image(systemName: isFounded ? "person.fill.checkmark" : "person.fill.questionmark").resizable().frame(width: 30, height: 20)
}
Button("About us") {
showAboutUs = true
}
})
}.edgesIgnoringSafeArea(.all)
}
}
struct ListItem: View {
@State var item: Place
var body: some View {
HStack {
Text(item.animalType!).frame(width: 60, height: 60).font(.system(size: 49, weight: .bold)).padding(.leading, 15)
Divider()
VStack {
HStack {
Text(item.title).font(.custom("san francisco", size: 20, relativeTo: .title))
.foregroundColor(Color("listCl"))
Image(systemName: item.isFounded ? "person.fill.checkmark" : "person.fill.questionmark").resizable().frame(width: 20, height: 15).foregroundColor(.gray)
}.frame(width: 250, height: 10, alignment: .leading)
Text("\(item.formattingDate(date: item.publishTime, withoutTime: false)!)").font(.custom("san francisco", size: 18, relativeTo: .title)).frame(width: 250, height: 10, alignment: .leading).foregroundColor(Color.gray).padding(.top, 15)
}
Spacer()
Image(systemName: "chevron.right")
.resizable().frame(width: 10, height: 20)
.padding(.trailing, 20)
.foregroundColor(.gray)
}.frame(width: UIScreen.main.bounds.width - 20, height: 80, alignment: .leading).background(Color.gray.opacity(0.2)).cornerRadius(15)
}
}
//AppleSDGothicNeo-SemiBold
//AppleSDGothicNeo-thin
| 39.463415 | 249 | 0.549135 |
1ebe3c72ebb56c708988ccf657cff58aac6c6f5d | 2,684 | //
// modal.swift
// Inkolors
//
// Created by Gui Reis on 02/06/21.
//
import UIKit
class PrizeViewController: UIViewController {
let myView = PrizeView()
let defaults = UserDefaults.standard
var currentLevel:Int = 0
var completedLevels:Int = 0
let medals:[UIImage] = [#imageLiteral(resourceName: "medalha-grande-bronze"), #imageLiteral(resourceName: "medalha-grande-prata"), #imageLiteral(resourceName: "medalha-grande-ouro")]
let phrases:[String] = ["Good Job!", "Nice Going!", "Perfect!"]
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.view = self.myView
}
override func viewDidLoad() {
super.viewDidLoad()
self.currentLevel = self.defaults.integer(forKey: "level")
self.completedLevels = self.defaults.integer(forKey: "completedLevels")
self.myView.setCurrentLevel(level: self.currentLevel)
let buttonHome = self.myView.getButtonHome()
buttonHome.addTarget(self, action: #selector(actHome), for: .touchDown)
let buttonRestart = self.myView.getButtonRestart()
buttonRestart.addTarget(self, action: #selector(actRestart), for: .touchDown)
let buttonNext = self.myView.getButtonNext()
buttonNext.addTarget(self, action: #selector(actNext), for: .touchDown)
let titleLabel = self.myView.getTitleLabel()
titleLabel.text = self.phrases[self.currentLevel]
let medalImage = self.myView.getMedalImage()
medalImage.image = self.medals[self.currentLevel]
}
@IBAction func actHome() -> Void{
guard let vc = storyboard?.instantiateViewController(identifier: "idMenu") as? MenuViewController else {return}
vc.modalPresentationStyle = .fullScreen
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true)
}
@IBAction func actRestart() -> Void{
guard let vc = storyboard?.instantiateViewController(identifier: "idAction") as? ActionViewController else {return}
vc.modalPresentationStyle = .fullScreen
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true)
}
@IBAction func actNext() -> Void{
self.currentLevel += 1
self.defaults.set(self.currentLevel, forKey: "level")
guard let vc = storyboard?.instantiateViewController(identifier: "idIntro") as? IntroViewController else {return}
vc.modalPresentationStyle = .fullScreen
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true)
}
}
| 33.974684 | 186 | 0.65313 |
560d5db890a66767fc61168650af0481cc06d0e4 | 2,638 | //
// SignInViewController.swift
// Uber
//
// Created by Anil Allewar on 12/17/15.
// Copyright © 2015 Parse. All rights reserved.
//
import Parse
class SignInViewController: UIViewController {
@IBOutlet var userPictureView: UIImageView!
@IBOutlet var isDriver: UISwitch!
@IBAction func signUpClicked(sender: AnyObject) {
do {
PFUser.currentUser()?["isDriver"] = self.isDriver.on
try PFUser.currentUser()?.save()
print("Signed up current user with isDriver: \(self.isDriver.on)")
if self.isDriver.on == true {
self.performSegueWithIdentifier("showDriverView", sender: self)
} else {
self.performSegueWithIdentifier("showRiderView", sender: self)
}
} catch {
print("Error while signing up the user: \(error)")
}
}
override func viewDidLoad() {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, name, gender, email"])
graphRequest.startWithCompletionHandler { (connection, object, error) -> Void in
if error != nil {
print("Error while making Graph request to Facebook")
} else {
if let result = object {
PFUser.currentUser()?["name"] = result["name"]
PFUser.currentUser()?["email"] = result["email"]
PFUser.currentUser()?["gender"] = result["gender"]
PFUser.currentUser()?.saveInBackground()
let userId = result["id"] as! String
self.saveUserImageInBackground(userId)
}
}
}
}
private func saveUserImageInBackground(userId:String) -> Void {
let facebookProfileUrlString = "https://graph.facebook.com/" + userId + "/picture?type=large"
if let facebookProfileUrl = NSURL(string: facebookProfileUrlString){
if let data = NSData(contentsOfURL: facebookProfileUrl){
self.userPictureView.image = UIImage(data: data)
let imageFile:PFFile = PFFile(data: data)!
PFUser.currentUser()?["picture"] = imageFile
PFUser.currentUser()?.saveInBackground()
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "logOut"{
PFUser.logOut()
}
}
}
| 34.25974 | 131 | 0.547384 |
758b004b09390bfbc8065c13ef84d1987f4c96d0 | 161 | //
// ScrollInsetsTests.swift
// Listable-Unit-Tests
//
// Created by Kyle Van Essen on 11/27/19.
//
import XCTest
class ScrollInsetsTests: XCTestCase
{
}
| 11.5 | 42 | 0.695652 |
895a8313dedd543c3f56dfbec9beeb4a00fe558c | 4,747 | //
// UICollectionViewCell+ATKit.swift
// ATKit_Swift
//
// Created by wangws1990 on 2020/12/3.
// Copyright © 2020 wangws1990. All rights reserved.
//
import UIKit
public extension UICollectionViewCell{
static var confiTag : Int = 32241981
class func cellForCollectionView(collectionView:UICollectionView,indexPath : IndexPath) -> Self{
return self.cellForCollectionView(collectionView: collectionView, indexPath: indexPath, identifier:nil, config: nil)
}
class func cellForCollectionView(collectionView:UICollectionView,indexPath: IndexPath,identifier:String? = nil,config:((_ cell :UICollectionViewCell) ->Void)? = nil) ->Self{
let identy : String = cellRegister(collectionView: collectionView, identifier: identifier)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:identy, for: indexPath)
if cell.tag != confiTag {
cell.tag = confiTag
if (config != nil) {
config!(cell)
}
}
return cell as! Self
}
class func cellRegister(collectionView:UICollectionView,identifier :String? = nil) ->String{
let identy : String = identifier != nil ? identifier! : NSStringFromClass(self.classForCoder())
var res1 : Bool = false
var res2 : Bool = false
let dic1 = collectionView.value(forKeyPath: "cellNibDict")
if dic1 != nil {
let dic1 : NSDictionary = (dic1 as? NSDictionary)!
res1 = (dic1.value(forKeyPath:identy) != nil) ? true : false
}
let dic2 = collectionView.value(forKeyPath: "cellClassDict")
if dic2 != nil {
let dic2 : NSDictionary = (dic2 as? NSDictionary)!
res2 = (dic2.value(forKeyPath: identy) != nil) ? true : false
}
let hasRegister : Bool = res1 || res2
if hasRegister == false {
let nib = Bundle.main.url(forResource:self.xibName(), withExtension:"nib")
if (nib != nil) {
collectionView.register(UINib(nibName: self.xibName(), bundle: nil), forCellWithReuseIdentifier: identy)
}else{
collectionView.register(self.classForCoder(), forCellWithReuseIdentifier: identy)
}
}
return identy
}
}
public extension UICollectionReusableView{
static var configTag : Int = 32241982;
class func viewForCollectionView(collectionView:UICollectionView,elementKind:String,indexPath:IndexPath) ->Self{
return self.viewForCollectionView(collectionView: collectionView, elementKind: elementKind, indexPath: indexPath, identifier: nil, config: nil)
}
class func viewForCollectionView(collectionView:UICollectionView,elementKind:String,indexPath:IndexPath,identifier:String? = nil,config:((_ cell :UICollectionReusableView) ->Void)? = nil) ->Self {
assert(elementKind.count > 0)
let identy = viewRegister(collectionView: collectionView, elementKind: elementKind, indexPath: indexPath, identifier: identifier)
let cell : UICollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: identy, for: indexPath)
if cell.tag != configTag{
cell.tag = configTag
if config != nil {
config!(cell)
}
}
return cell as! Self
}
class func viewRegister(collectionView:UICollectionView,elementKind:String,indexPath:IndexPath,identifier:String? = nil) ->String{
let identy : String = identifier != nil ? identifier! : NSStringFromClass(self.classForCoder())
let keyPath = elementKind.appendingFormat("/" + identy)
var res1 : Bool = false
var res2 : Bool = false
let dic1 = collectionView.value(forKeyPath:"supplementaryViewNibDict")
if dic1 != nil {
let dic = dic1 as! NSDictionary
res1 = dic.value(forKeyPath:keyPath) != nil ? true : false
}
let dic2 = collectionView.value(forKeyPath:"supplementaryViewClassDict")
if dic2 != nil {
let dic = dic2 as! NSDictionary
res2 = dic.value(forKeyPath:keyPath) != nil ? true : false
}
let hasRegister = res1 || res2
if hasRegister == false {
let nib = Bundle.main.url(forResource:self.xibName(), withExtension:"nib")
if (nib != nil) {
collectionView.register(UINib(nibName: self.xibName(), bundle:nil), forSupplementaryViewOfKind: elementKind, withReuseIdentifier:identy)
}else{
collectionView.register(self.classForCoder(), forSupplementaryViewOfKind: elementKind, withReuseIdentifier:identy)
}
}
return identy
}
}
| 48.438776 | 200 | 0.653676 |
6944228b48a691e69204cbfad157644e2137e6e2 | 1,367 | //
// AppDelegate.swift
// Nursery Rhymes
//
// Created by Maciej Gad on 06/12/2020.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.945946 | 179 | 0.748354 |
f44a7593221c008b27176d5d3e8a78812e6f06f7 | 1,083 | // Copyright 2021-present Xsolla (USA), Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at q
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing and permissions and
import Foundation
import XsollaSDKUtilities
extension LogDomain
{
// This is how you add the custom domains to suit your needs
public static let loginDemoApp = Self(title: "Xsolla Login Demo App")
public static let all: [LogDomain] =
[
.common,
.loginDemoApp
]
public static func all(excluding: [LogDomain]) -> [LogDomain]
{
all.filter { domain in (excluding.filter { $0.description == domain.description }).isEmpty }
}
}
| 31.852941 | 100 | 0.701754 |
28c57e93ac1f999a69aeaa439eaeae41601e5e2c | 31,303 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// =============================================================================
// MARK: - KeyedSubscriptFunction
/**
`KeyedSubscriptFunction` is used by the Mustache rendering engine whenever it
has to resolve identifiers in expressions such as `{{ name }}` or
`{{ user.name }}`. Subscript functions turn those identifiers into
`MustacheBox`, the type that wraps rendered values.
All types that expose keys to Mustache templates provide such a subscript
function by conforming to the `MustacheBoxable` protocol. This is the case of
built-in types such as NSObject, that uses `valueForKey:` in order to expose
its properties; String, which exposes its "length"; collections, which expose
keys like "count", "first", etc. etc.
var box = Box("string")
box = box["length"] // Evaluates the KeyedSubscriptFunction
box.value // 6
box = Box(["a", "b", "c"])
box = box["first"] // Evaluates the KeyedSubscriptFunction
box.value // "a"
Your can build boxes that hold a custom subscript function. This is a rather
advanced usage, only supported with the low-level function
`func Box(boolValue:value:keyedSubscript:filter:render:willRender:didRender:) -> MustacheBox`.
// A KeyedSubscriptFunction that turns "key" into "KEY":
let keyedSubscript: KeyedSubscriptFunction = { (key: String) -> MustacheBox in
return Box(key.uppercaseString)
}
// Render "FOO & BAR"
let template = try! Template(string: "{{foo}} & {{bar}}")
let box = Box(keyedSubscript: keyedSubscript)
try! template.render(box)
### Missing keys vs. missing values.
`KeyedSubscriptFunction` returns a non-optional `MustacheBox`.
In order to express "missing key", and have Mustache rendering engine dig deeper
in the context stack in order to resolve a key, return the empty box `Box()`.
In order to express "missing value", and prevent the rendering engine from
digging deeper, return `Box(NSNull())`.
*/
public typealias KeyedSubscriptFunction = (key: String) -> MustacheBox
// =============================================================================
// MARK: - FilterFunction
/**
`FilterFunction` is the core type that lets GRMustache evaluate filtered
expressions such as `{{ uppercase(string) }}`.
To build a filter, you use the `Filter()` function. It takes a function as an
argument. For example:
let increment = Filter { (x: Int?) in
return Box(x! + 1)
}
To let a template use a filter, register it:
let template = try! Template(string: "{{increment(x)}}")
template.registerInBaseContext("increment", Box(increment))
// "2"
try! template.render(Box(["x": 1]))
`Filter()` can take several types of functions, depending on the type of filter
you want to build. The example above processes `Int` values. There are three
types of filters:
- Values filters:
- `(MustacheBox) throws -> MustacheBox`
- `(T?) throws -> MustacheBox` (Generic)
- `([MustacheBox]) throws -> MustacheBox` (Multiple arguments)
- Pre-rendering filters:
- `(Rendering) throws -> Rendering`
- Custom rendering filters:
- `(MustacheBox, RenderingInfo) throws -> Rendering`
- `(T?, RenderingInfo) throws -> Rendering` (Generic)
See the documentation of the `Filter()` functions.
*/
public typealias FilterFunction = (box: MustacheBox, partialApplication: Bool) throws -> MustacheBox
// -----------------------------------------------------------------------------
// MARK: - Values Filters
/**
Builds a filter that takes a single argument.
For example, here is the trivial `identity` filter:
let identity = Filter { (box: MustacheBox) in
return box
}
let template = try! Template(string: "{{identity(a)}}, {{identity(b)}}")
template.registerInBaseContext("identity", Box(identity))
// "foo, 1"
try! template.render(Box(["a": "foo", "b": 1]))
If the template provides more than one argument, the filter returns a
MustacheError of type RenderError.
- parameter filter: A function `(MustacheBox) throws -> MustacheBox`.
- returns: A FilterFunction.
*/
public func Filter(filter: (MustacheBox) throws -> MustacheBox) -> FilterFunction {
return { (box: MustacheBox, partialApplication: Bool) in
guard !partialApplication else {
// This is a single-argument filter: we do not wait for another one.
throw MustacheError(kind: .RenderError, message: "Too many arguments")
}
return try filter(box)
}
}
/**
Builds a filter that takes a single argument of type `T?`.
For example:
let increment = Filter { (x: Int?) in
return Box(x! + 1)
}
let template = try! Template(string: "{{increment(x)}}")
template.registerInBaseContext("increment", Box(increment))
// "2"
try! template.render(Box(["x": 1]))
The argument is converted to `T` using the built-in `as?` operator before being
given to the filter.
If the template provides more than one argument, the filter returns a
MustacheError of type RenderError.
- parameter filter: A function `(T?) throws -> MustacheBox`.
- returns: A FilterFunction.
*/
public func Filter<T>(filter: (T?) throws -> MustacheBox) -> FilterFunction {
return { (box: MustacheBox, partialApplication: Bool) in
guard !partialApplication else {
// This is a single-argument filter: we do not wait for another one.
throw MustacheError(kind: .RenderError, message: "Too many arguments")
}
return try filter(box.value as? T)
}
}
/**
Returns a filter than accepts any number of arguments.
For example:
// `sum(x, ...)` evaluates to the sum of provided integers
let sum = VariadicFilter { (boxes: [MustacheBox]) in
// Extract integers out of input boxes, assuming zero for non numeric values
let integers = boxes.map { (box) in (box.value as? Int) ?? 0 }
let sum = integers.reduce(0, combine: +)
return Box(sum)
}
let template = try! Template(string: "{{ sum(a,b,c) }}")
template.registerInBaseContext("sum", Box(sum))
// Renders "6"
try! template.render(Box(["a": 1, "b": 2, "c": 3]))
- parameter filter: A function `([MustacheBox]) throws -> MustacheBox`.
- returns: A FilterFunction.
*/
public func VariadicFilter(filter: ([MustacheBox]) throws -> MustacheBox) -> FilterFunction {
// f(a,b,c) is implemented as f(a)(b)(c).
//
// f(a) returns another filter, which returns another filter, which
// eventually computes the final result.
//
// It is the partialApplication flag the tells when it's time to return the
// final result.
func partialFilter(filter: ([MustacheBox]) throws -> MustacheBox, arguments: [MustacheBox]) -> FilterFunction {
return { (nextArgument: MustacheBox, partialApplication: Bool) in
let arguments = arguments + [nextArgument]
if partialApplication {
// Wait for another argument
return Box(partialFilter(filter, arguments: arguments))
} else {
// No more argument: compute final value
return try filter(arguments)
}
}
}
return partialFilter(filter, arguments: [])
}
// -----------------------------------------------------------------------------
// MARK: - Pre-Rendering Filters
/**
Builds a filter that performs post rendering.
`Rendering` is a type that wraps a rendered String, and its content type (HTML
or Text). This filter turns a rendering in another one:
// twice filter renders its argument twice:
let twice = Filter { (rendering: Rendering) in
return Rendering(rendering.string + rendering.string, rendering.contentType)
}
let template = try! Template(string: "{{ twice(x) }}")
template.registerInBaseContext("twice", Box(twice))
// Renders "foofoo", "123123"
try! template.render(Box(["x": "foo"]))
try! template.render(Box(["x": 123]))
When this filter is executed, eventual HTML-escaping performed by the rendering
engine has not happened yet: the rendering argument may contain raw text. This
allows you to chain pre-rendering filters without mangling HTML entities.
- parameter filter: A function `(Rendering) throws -> Rendering`.
- returns: A FilterFunction.
*/
public func Filter(filter: (Rendering) throws -> Rendering) -> FilterFunction {
return { (box: MustacheBox, partialApplication: Bool) in
guard !partialApplication else {
// This is a single-argument filter: we do not wait for another one.
throw MustacheError(kind: .RenderError, message: "Too many arguments")
}
// Box a RenderFunction
return Box { (info: RenderingInfo) in
let rendering = try box.render(info: info)
return try filter(rendering)
}
}
}
// -----------------------------------------------------------------------------
// MARK: - Custom Rendering Filters
/**
Builds a filter that takes a single argument and performs custom rendering.
See the documentation of the `RenderFunction` type for a detailed discussion of
the `RenderingInfo` and `Rendering` types.
For an example of such a filter, see the documentation of
`func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction`.
This example processes `T?` instead of `MustacheBox`, but the idea is the same.
- parameter filter: A function `(MustacheBox, RenderingInfo) throws -> Rendering`.
- returns: A FilterFunction.
*/
public func Filter(filter: (MustacheBox, RenderingInfo) throws -> Rendering) -> FilterFunction {
return Filter { (box: MustacheBox) in
// Box a RenderFunction
return Box { (info: RenderingInfo) in
return try filter(box, info)
}
}
}
/**
Builds a filter that takes a single argument of type `T?` and performs custom
rendering.
For example:
// {{# pluralize(count) }}...{{/ }} renders the plural form of the section
// content if the `count` argument is greater than 1.
let pluralize = Filter { (count: Int?, info: RenderingInfo) in
// Pluralize the inner content of the section tag:
var string = info.tag.innerTemplateString
if count > 1 {
string += "s" // naive pluralization
}
return Rendering(string)
}
let template = try! Template(string: "I have {{ cats.count }} {{# pluralize(cats.count) }}cat{{/ }}.")
template.registerInBaseContext("pluralize", Box(pluralize))
// Renders "I have 3 cats."
let data = ["cats": ["Kitty", "Pussy", "Melba"]]
try! template.render(Box(data))
The argument is converted to `T` using the built-in `as?` operator before being
given to the filter.
If the template provides more than one argument, the filter returns a
MustacheError of type RenderError.
See the documentation of the `RenderFunction` type for a detailed discussion of
the `RenderingInfo` and `Rendering` types.
- parameter filter: A function `(T?, RenderingInfo) throws -> Rendering`.
- returns: A FilterFunction.
*/
public func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction {
return Filter { (t: T?) in
// Box a RenderFunction
return Box { (info: RenderingInfo) in
return try filter(t, info)
}
}
}
// =============================================================================
// MARK: - RenderFunction
/**
`RenderFunction` is used by the Mustache rendering engine when it renders a
variable tag (`{{name}}` or `{{{body}}}`) or a section tag
(`{{#name}}...{{/name}}`).
### Output: `Rendering`
The return type of `RenderFunction` is `Rendering`, a type that wraps a rendered
String, and its ContentType (HTML or Text).
Text renderings are HTML-escaped, except for `{{{triple}}}` mustache tags, and
Text templates (see `Configuration.contentType` for a full discussion of the
content type of templates).
For example:
let HTML: RenderFunction = { (_) in
return Rendering("<HTML>", .HTML)
}
let text: RenderFunction = { (_) in
return Rendering("<text>") // default content type is text
}
// Renders "<HTML>, <text>"
let template = try! Template(string: "{{HTML}}, {{text}}")
let data = ["HTML": Box(HTML), "text": Box(text)]
let rendering = try! template.render(Box(data))
### Input: `RenderingInfo`
The `info` argument contains a `RenderingInfo` which provides information
about the requested rendering:
- `info.context: Context` is the context stack which contains the rendered data.
- `info.tag: Tag` is the tag to render.
- `info.tag.type: TagType` is the type of the tag (variable or section). You can
use this type to have a different rendering for variable and section tags.
- `info.tag.innerTemplateString: String` is the inner content of the tag,
unrendered. For the section tag `{{# person }}Hello {{ name }}!{{/ person }}`,
it is `Hello {{ name }}!`.
- `info.tag.render: (Context) throws -> Rendering` is a
function that renders the inner content of the tag, given a context stack.
For example, the section tag `{{# person }}Hello {{ name }}!{{/ person }}`
would render `Hello Arthur!`, assuming the provided context stack provides
"Arthur" for the key "name".
### Example
As an example, let's write a `RenderFunction` which performs the default
rendering of a value:
- `{{ value }}` and `{{{ value }}}` renders the built-in Swift String
Interpolation of the value: our render function will return a `Rendering` with
content type Text when the rendered tag is a variable tag. The Text content
type makes sure that the returned string will be HTML-escaped if needed.
- `{{# value }}...{{/ value }}` pushes the value on the top of the context
stack, and renders the inner content of section tags.
The default rendering thus reads:
let value = ... // Some value
let renderValue: RenderFunction = { (info: RenderingInfo) throws in
// Default rendering depends on the tag type:
switch info.tag.type {
case .Variable:
// {{ value }} and {{{ value }}}
// Return the built-in Swift String Interpolation of the value:
return Rendering("\(value)", .Text)
case .Section:
// {{# value }}...{{/ value }}
// Push the value on the top of the context stack:
let context = info.context.extendedContext(Box(value))
// Renders the inner content of the section tag:
return try info.tag.render(context)
}
}
let template = try! Template(string: "{{value}}")
let rendering = try! template.render(Box(["value": Box(renderValue)]))
- parameter info: A RenderingInfo.
- parameter error: If there is a problem in the rendering, throws an error
that describes the problem.
- returns: A Rendering.
*/
public typealias RenderFunction = (info: RenderingInfo) throws -> Rendering
// -----------------------------------------------------------------------------
// MARK: - Mustache lambdas
/**
Builds a `RenderFunction` which conforms to the "lambda" defined by the
Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml).
The `lambda` parameter is a function which takes the unrendered context of a
section, and returns a String. The returned `RenderFunction` renders this string
against the current delimiters.
For example:
let template = try! Template(string: "{{#bold}}{{name}} has a Mustache!{{/bold}}")
let bold = Lambda { (string) in "<b>\(string)</b>" }
let data = [
"name": Box("Clark Gable"),
"bold": Box(bold)]
// Renders "<b>Clark Gable has a Mustache.</b>"
let rendering = try! template.render(Box(data))
**Warning**: the returned String is *parsed* each time the lambda is executed.
In the example above, this is inefficient because the inner content of the
bolded section has already been parsed with its template. You may prefer the raw
`RenderFunction` type, capable of an equivalent and faster implementation:
let bold: RenderFunction = { (info: RenderingInfo) in
let rendering = try info.tag.render(info.context)
return Rendering("<b>\(rendering.string)</b>", rendering.contentType)
}
let data = [
"name": Box("Clark Gable"),
"bold": Box(bold)]
// Renders "<b>Lionel Richie has a Mustache.</b>"
let rendering = try! template.render(Box(data))
- parameter lambda: A `String -> String` function.
- returns: A RenderFunction.
*/
public func Lambda(lambda: String -> String) -> RenderFunction {
return { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ lambda }}
return Rendering("(Lambda)")
case .Section:
// {{# lambda }}...{{/ lambda }}
//
// https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L117
// > Lambdas used for sections should parse with the current delimiters
let templateRepository = TemplateRepository()
templateRepository.configuration.tagDelimiterPair = info.tag.tagDelimiterPair
let templateString = lambda(info.tag.innerTemplateString)
let template = try templateRepository.template(string: templateString)
return try template.render(info.context)
// IMPLEMENTATION NOTE
//
// This lambda implementation is unable of two things:
//
// - process partial tags correctly, because it uses a
// TemplateRepository that does not know how to load partials.
// - honor the current content type.
//
// This partial problem is a tricky one to solve. A `{{>partial}}`
// tag loads the "partial" template which is sibling of the
// currently rendered template.
//
// Imagine the following template hierarchy:
//
// - /a.mustache: {{#lambda}}...{{/lambda}}...{{>dir/b}}
// - /x.mustache: ...
// - /dir/b.mustache: {{#lambda}}...{{/lambda}}
// - /dir/x.mustache: ...
//
// If the lambda returns `{{>x}}` then rendering the `a.mustache`
// template should trigger the inclusion of both `/x.mustache` and
// `/dir/x.mustache`.
//
// Given the current state of GRMustache types, achieving proper
// lambda would require:
//
// - a template repository
// - a TemplateID
// - a property `Tag.contentType`
// - a method `TemplateRepository.template(string:contentType:tagDelimiterPair:baseTemplateID:)`
//
// Code would read something like:
//
// let templateString = lambda(info.tag.innerTemplateString)
// let templateRepository = info.tag.templateRepository
// let templateID = info.tag.templateID
// let contentType = info.tag.contentType
// let template = try templateRepository.template(
// string: templateString,
// contentType: contentType
// tagDelimiterPair: info.tag.tagDelimiterPair,
// baseTemplateID: templateID)
// return try template.render(info.context)
//
// Should we ever implement this, beware the retain cycle between
// tags and template repositories (which own tags through their
// cached templateASTs).
}
}
}
/**
Builds a `RenderFunction` which conforms to the "lambda" defined by the
Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml).
The `lambda` parameter is a function without any argument that returns a String.
The returned `RenderFunction` renders this string against the default `{{` and
`}}` delimiters.
For example:
let template = try! Template(string: "{{fullName}} has a Mustache.")
let fullName = Lambda { "{{firstName}} {{lastName}}" }
let data = [
"firstName": Box("Lionel"),
"lastName": Box("Richie"),
"fullName": Box(fullName)]
// Renders "Lionel Richie has a Mustache."
let rendering = try! template.render(Box(data))
**Warning**: the returned String is *parsed* each time the lambda is executed.
In the example above, this is inefficient because the same
`"{{firstName}} {{lastName}}"` would be parsed several times. You may prefer
using a Template instead of a lambda (see the documentation of
`Template.mustacheBox` for more information):
let fullName = try! Template(string:"{{firstName}} {{lastName}}")
let data = [
"firstName": Box("Lionel"),
"lastName": Box("Richie"),
"fullName": Box(fullName)]
// Renders "Lionel Richie has a Mustache."
let rendering = try! template.render(Box(data))
- parameter lambda: A `() -> String` function.
- returns: A RenderFunction.
*/
public func Lambda(lambda: () -> String) -> RenderFunction {
return { (info: RenderingInfo) in
switch info.tag.type {
case .Variable:
// {{ lambda }}
//
// https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L73
// > Lambda results should be appropriately escaped
//
// Let's render a text template:
let templateRepository = TemplateRepository()
templateRepository.configuration.contentType = .Text
let templateString = lambda()
let template = try templateRepository.template(string: templateString)
return try template.render(info.context)
// IMPLEMENTATION NOTE
//
// This lambda implementation is unable to process partial tags
// correctly: it uses a TemplateRepository that does not know how
// to load partials.
//
// This problem is a tricky one to solve. The `{{>partial}}` tag
// loads the "partial" template which is sibling of the currently
// rendered template.
//
// Imagine the following template hierarchy:
//
// - /a.mustache: {{lambda}}...{{>dir/b}}
// - /x.mustache: ...
// - /dir/b.mustache: {{lambda}}
// - /dir/x.mustache: ...
//
// If the lambda returns `{{>x}}` then rendering the `a.mustache`
// template should trigger the inclusion of both `/x.mustache` and
// `/dir/x.mustache`.
//
// Given the current state of GRMustache types, achieving this
// feature would require:
//
// - a template repository
// - a TemplateID
// - a method `TemplateRepository.template(string:contentType:tagDelimiterPair:baseTemplateID:)`
//
// Code would read something like:
//
// let templateString = lambda(info.tag.innerTemplateString)
// let templateRepository = info.tag.templateRepository
// let templateID = info.tag.templateID
// let template = try templateRepository.template(
// string: templateString,
// contentType: .Text,
// tagDelimiterPair: ("{{", "}}),
// baseTemplateID: templateID)
// return try template.render(info.context)
//
// Should we ever implement this, beware the retain cycle between
// tags and template repositories (which own tags through their
// cached templateASTs).
case .Section:
// {{# lambda }}...{{/ lambda }}
//
// Behave as a true object, and render the section.
let context = info.context.extendedContext(Box(Lambda(lambda)))
return try info.tag.render(context)
}
}
}
/**
`Rendering` is a type that wraps a rendered String, and its content type (HTML
or Text).
See `RenderFunction` and `FilterFunction` for more information.
*/
public struct Rendering {
/// The rendered string
public let string: String
/// The content type of the rendering
public let contentType: ContentType
/**
Builds a Rendering with a String and a ContentType.
Rendering("foo") // Defaults to Text
Rendering("foo", .Text)
Rendering("foo", .HTML)
- parameter string: A string.
- parameter contentType: A content type.
- returns: A Rendering.
*/
public init(_ string: String, _ contentType: ContentType = .Text) {
self.string = string
self.contentType = contentType
}
}
extension Rendering : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
var contentTypeString: String
switch contentType {
case .HTML:
contentTypeString = "HTML"
case .Text:
contentTypeString = "Text"
}
return "Rendering(\(contentTypeString):\(string.debugDescription))"
}
}
/**
`RenderingInfo` provides information about a rendering.
See `RenderFunction` for more information.
*/
public struct RenderingInfo {
/// The currently rendered tag.
public let tag: Tag
/// The current context stack.
public var context: Context
// If true, the rendering is part of an enumeration. Some values don't
// render the same whenever they render as an enumeration item, or alone:
// {{# values }}...{{/ values }} vs. {{# value }}...{{/ value }}.
//
// This is the case of Int, UInt, Double, Bool: they enter the context
// stack when used in an iteration, and do not enter the context stack when
// used as a boolean (see https://github.com/groue/GRMustache/issues/83).
//
// This is also the case of collections: they enter the context stack when
// used as an item of a collection, and enumerate their items when used as
// a collection.
var enumerationItem: Bool
}
// =============================================================================
// MARK: - WillRenderFunction
/**
Once a `WillRenderFunction` has entered the context stack, it is called just
before tags are about to render, and has the opportunity to replace the value
they are about to render.
let logTags: WillRenderFunction = { (tag: Tag, box: MustacheBox) in
print("\(tag) will render \(box.value!)")
return box
}
// By entering the base context of the template, the logTags function
// will be notified of all tags.
let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}")
template.extendBaseContext(Box(logTags))
// Prints:
// {{# user }} at line 1 will render { firstName = Errol; lastName = Flynn; }
// {{ firstName }} at line 1 will render Errol
// {{ lastName }} at line 1 will render Flynn
let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]]
try! template.render(Box(data))
`WillRenderFunction` don't have to enter the base context of a template to
perform: they can enter the context stack just like any other value, by being
attached to a section. In this case, they are only notified of tags inside that
section.
let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}")
// Prints:
// {{ lastName }} at line 1 will render Flynn
let data = [
"user": Box(["firstName": "Errol", "lastName": "Flynn"]),
"spy": Box(logTags)
]
try! template.render(Box(data))
*/
public typealias WillRenderFunction = (tag: Tag, box: MustacheBox) -> MustacheBox
// =============================================================================
// MARK: - DidRenderFunction
/**
Once a DidRenderFunction has entered the context stack, it is called just
after tags have been rendered.
let logRenderings: DidRenderFunction = { (tag: Tag, box: MustacheBox, string: String?) in
println("\(tag) did render \(box.value!) as `\(string!)`")
}
// By entering the base context of the template, the logRenderings function
// will be notified of all tags.
let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}")
template.extendBaseContext(Box(logRenderings))
// Renders "Errol Flynn"
//
// Prints:
// {{ firstName }} at line 1 did render Errol as `Errol`
// {{ lastName }} at line 1 did render Flynn as `Flynn`
// {{# user }} at line 1 did render { firstName = Errol; lastName = Flynn; } as `Errol Flynn`
let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]]
try! template.render(Box(data))
DidRender functions don't have to enter the base context of a template to
perform: they can enter the context stack just like any other value, by being
attached to a section. In this case, they are only notified of tags inside that
section.
let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}")
// Renders "Errol Flynn"
//
// Prints:
// {{ lastName }} at line 1 did render Flynn as `Flynn`
let data = [
"user": Box(["firstName": "Errol", "lastName": "Flynn"]),
"spy": Box(logRenderings)
]
try! template.render(Box(data))
The string argument of DidRenderFunction is optional: it is nil if and only if
the tag could not render because of a rendering error.
See also:
- WillRenderFunction
*/
public typealias DidRenderFunction = (tag: Tag, box: MustacheBox, string: String?) -> Void
| 36.611696 | 119 | 0.626681 |
03b185c39bdb4f9f4ca25838fefbd57273837f74 | 8,237 | //
// UREffectCloudNode.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 5. 31..
// Copyright © 2017년 zigbang. All rights reserved.
//
import SpriteKit
enum UREffectCloudType: Int {
case type01 = 1
case type02 = 2
case type03 = 3
case type04 = 4
var texture: SKTexture {
let bundle = Bundle(for: UREffectCloudNode.self)
switch self {
case .type01:
return SKTexture(image: UIImage(named: "cloud_01", in: bundle, compatibleWith: nil)!)
case .type02:
return SKTexture(image: UIImage(named: "cloud_02", in: bundle, compatibleWith: nil)!)
case .type03:
return SKTexture(image: UIImage(named: "cloud_03", in: bundle, compatibleWith: nil)!)
case .type04:
return SKTexture(image: UIImage(named: "cloud_04", in: bundle, compatibleWith: nil)!)
}
}
}
public struct UREffectCloudOption: UREffectOption {
/// emittable AreaRatio
var emittableArea: CGRect
var movingAngle: CGFloat
var textureScaleRatio: CGFloat = 0.3
var movingDuration: TimeInterval = 5.0
static let DefaultSpeedCoefficient: CGFloat = 0.01
// var makingCount: UInt32 = 10
// var isRandomCountInMax: Bool = true
public init(_ emittableArea: CGRect, angleInDegree: CGFloat, scaleRatio: CGFloat = 0.3, movingDuration: TimeInterval = 5.0) {
self.init(emittableArea, angleInRadian: angleInDegree.degreesToRadians, scaleRatio: scaleRatio, movingDuration: movingDuration)
}
public init(_ emittableArea: CGRect, angleInRadian: CGFloat, scaleRatio: CGFloat = 0.3, movingDuration: TimeInterval = 5.0) {
self.emittableArea = emittableArea
self.movingAngle = angleInRadian
self.textureScaleRatio = scaleRatio
self.movingDuration = movingDuration
// self.maxCount = maxCount
// self.isRandomCountInMax = isRandomCountInMax
}
}
/// create a sprite node of cloud which texture is random
class UREffectCloudNode: SKSpriteNode {
class func makeClouds(maxCount: UInt32, isRandomCountInMax: Bool, cloudOption option: UREffectCloudOption, on scene: SKView) -> [UREffectCloudNode] {
return UREffectCloudNode.makeClouds(maxCount: maxCount, isRandomCountInMax: isRandomCountInMax, emittableAreaRatio: option.emittableArea, on: scene, movingAngleInRadian: option.movingAngle, movingDuration: option.movingDuration)
}
class func makeClouds(maxCount: UInt32, isRandomCountInMax: Bool, emittableAreaRatio area: CGRect, on scene: SKView, movingAngleInDegree: CGFloat, movingDuration: TimeInterval = 5.0) -> [UREffectCloudNode] {
return UREffectCloudNode.makeClouds(maxCount: maxCount, isRandomCountInMax: isRandomCountInMax, emittableAreaRatio: area, on: scene, movingAngleInRadian: movingAngleInDegree.degreesToRadians)
}
class func makeClouds(maxCount: UInt32, isRandomCountInMax: Bool, emittableAreaRatio area: CGRect, on scene: SKView, movingAngleInRadian: CGFloat, movingDuration: TimeInterval = 5.0) -> [UREffectCloudNode] {
var clouds: [UREffectCloudNode] = [UREffectCloudNode]()
var realMakingCount: UInt32 = maxCount
if isRandomCountInMax {
let minMakingCount: UInt32 = UInt32(floor(Double(maxCount) * 0.6))
realMakingCount = arc4random_uniform(maxCount)
if realMakingCount < minMakingCount {
realMakingCount = minMakingCount
}
}
for i in 0 ..< realMakingCount {
let rect: CGRect = CGRect(x: area.origin.x * scene.bounds.size.width, y: area.origin.y * scene.bounds.size.height, width: area.size.width * scene.bounds.size.width, height: area.size.height * scene.bounds.size.height)
let cloud: UREffectCloudNode = UREffectCloudNode(rect, angleInRadian: movingAngleInRadian)
cloud.name = "cloud\(i)"
clouds.append(cloud)
}
return clouds
}
var cloudType: UREffectCloudType
var option: UREffectCloudOption!
var emittingPosition: CGPoint = .zero
private override init(texture: SKTexture?, color: UIColor, size: CGSize) {
self.cloudType = UREffectCloudType(rawValue: Int(arc4random_uniform(3) + 1))!
super.init(texture: self.cloudType.texture, color: .clear, size: self.cloudType.texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(_ emittableArea: CGRect, angleInDegree: CGFloat, textureScaleRatio: CGFloat = 0.3, movingDuration: TimeInterval = 5.0) {
self.init(texture: nil, color: .clear, size: .zero)
self.option = UREffectCloudOption(emittableArea, angleInDegree: angleInDegree, scaleRatio: textureScaleRatio, movingDuration: movingDuration)
self.initNode()
}
convenience init(_ emittableArea: CGRect, angleInRadian: CGFloat, textureScaleRatio: CGFloat = 0.3, movingDuration: TimeInterval = 5.0) {
self.init(texture: nil, color: .clear, size: .zero)
self.option = UREffectCloudOption(emittableArea, angleInRadian: angleInRadian, scaleRatio: textureScaleRatio, movingDuration: movingDuration)
self.initNode()
}
func initNode() {
let rawSize: CGSize = self.cloudType.texture.size()
let ratioAppliedSize: CGSize = CGSize(width: rawSize.width * self.option.textureScaleRatio, height: rawSize.height * self.option.textureScaleRatio)
self.size = ratioAppliedSize
let rangeX: CGFloat = self.option.emittableArea.origin.x + (CGFloat(arc4random_uniform(UInt32(self.option.emittableArea.width * 100.0))) / 100.0)
let rangeY: CGFloat = self.option.emittableArea.origin.y + (CGFloat(arc4random_uniform(UInt32(self.option.emittableArea.height * 100.0))) / 100.0)
self.emittingPosition = CGPoint(x: rangeX, y: rangeY)
self.position = self.emittingPosition
}
func makeStreamingAction(isRepeat: Bool = false) {
let actionFadeOut: SKAction = SKAction.fadeOut(withDuration: 0.0)
let actionFadeIn: SKAction = SKAction.fadeIn(withDuration: 0.5)
let speedCoefficient: CGFloat = CGFloat(arc4random_uniform(5) + 5) * UREffectCloudOption.DefaultSpeedCoefficient
let actionMoveToDestination: SKAction = SKAction.move(to: self.destinationPoint, duration: self.option.movingDuration / Double(speedCoefficient * 10.0))
actionMoveToDestination.speed = speedCoefficient
let actionFadeOut2: SKAction = SKAction.fadeOut(withDuration: 0.5)
if isRepeat {
let startPoint: CGPoint = self.emittingPosition
let actionMoveToStarting: SKAction = SKAction.move(to: startPoint, duration: 0.0)
self.run(SKAction.repeatForever(SKAction.sequence([actionFadeOut, actionFadeIn, actionMoveToDestination, actionFadeOut2, actionMoveToStarting])))
} else {
let actionDestroy: SKAction = SKAction.run {
self.removeFromParent()
}
self.run(SKAction.sequence([actionFadeOut, actionFadeIn, actionMoveToDestination, actionFadeOut2, actionDestroy]))
}
}
var destinationPoint: CGPoint {
let pointZeroAngleOnAxisY: CGPoint = CGPoint(x: self.emittingPosition.x + self.option.emittableArea.width, y: self.emittingPosition.y)
let rotatedPoint: CGPoint = pointZeroAngleOnAxisY.rotateAround(point: self.emittingPosition, angle: self.option.movingAngle)
return CGPoint(x: rotatedPoint.x + self.size.width * 0.2, y: rotatedPoint.y + self.size.height * 0.2)
}
}
extension UREffectCloudNode: Comparable {
public static func <(lhs: UREffectCloudNode, rhs: UREffectCloudNode) -> Bool {
return lhs.emittingPosition.y < rhs.emittingPosition.y
}
public static func <=(lhs: UREffectCloudNode, rhs: UREffectCloudNode) -> Bool {
return lhs.emittingPosition.y <= rhs.emittingPosition.y
}
public static func >=(lhs: UREffectCloudNode, rhs: UREffectCloudNode) -> Bool {
return lhs.emittingPosition.y >= rhs.emittingPosition.y
}
public static func >(lhs: UREffectCloudNode, rhs: UREffectCloudNode) -> Bool {
return lhs.emittingPosition.y > rhs.emittingPosition.y
}
}
| 45.508287 | 236 | 0.703169 |
bf6f4888d6c0fb96753480fa1b4f5c3edcb17887 | 848 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct RoomAvatarViewData: AvatarViewDataProtocol {
let roomId: String
let displayName: String?
let avatarUrl: String?
let mediaManager: MXMediaManager
var matrixItemId: String {
return roomId
}
}
| 29.241379 | 75 | 0.728774 |
f8cae21d13fcd2a5d8237e4e682aaa2440dbe6fb | 1,413 | //
// tipperUITests.swift
// tipperUITests
//
// Created by Matheus G Santos on 12/24/20.
//
import XCTest
class tipperUITests: 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, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.860465 | 182 | 0.654636 |
7267ce3d1e09e9083da105cc75ad386dc84e3e47 | 4,487 | import AppKit
//import HoleFillingLib
//import InputValidator
struct App {
private let holeFiller: HoleFillerType
private let validator: InputValidatorType
init(holeFiller: HoleFillerType, validator: InputValidatorType) {
self.holeFiller = holeFiller
self.validator = validator
}
}
extension App: AppType {
func main(arguments commandLineArguments: [String]) {
let arguments = commandLineArguments.dropFirst().asArray()
switch validator.validate(arguments: arguments) {
case .valid(let input):
loadImagesAndSaveHoleFilledOne(with: input)
case .invalid(let errorMessage):
print("🛑 " + errorMessage)
}
}
private func loadImagesAndSaveHoleFilledOne(with input: ValidInput) {
guard let rgbBaseImage
= rgbBaseImage(from: input.rgbBaseImageAbsolutePath) else { return }
guard let rgbHoleMaskImage
= rgbHoleMaskImage(from: input.rgbHoleMaskImageAbsolutePath) else { return }
print("⏳ Base image grayscale conversion...")
let baseGrayPixelMatrix = rgbBaseImage.asGrayPixelMatrix()
print("✅ Base image converted to grayscale")
print("⏳ Hole mask image grayscale conversion...")
let holeMaskGrayPixelMatrix = rgbHoleMaskImage.asGrayPixelMatrix()
print("✅ Hole mask image converted to grayscale")
guard let holeFilledGrayMatrix = holeFilledGrayMatrix(
baseGrayPixelMatrix: baseGrayPixelMatrix,
holeMaskGrayPixelMatrix: holeMaskGrayPixelMatrix,
z: input.z,
epsilon: input.epsilon,
pixelConnectivity: input.pixelConnectivity
) else { return }
guard let holeFilledGrayImage
= holeFilledGrayImage(from: holeFilledGrayMatrix) else { return }
save(
holeFilledGrayImage: holeFilledGrayImage,
at: input.outputImageAbsolutePath
)
}
private func rgbBaseImage(from rgbBaseImageAbsolutePath: String) -> NSImage? {
print("⏳ Base image loading...")
guard let rgbBaseImage = NSImage(contentsOfFile: rgbBaseImageAbsolutePath) else {
print("🛑 Couldn't load \(rgbBaseImageAbsolutePath)")
return nil
}
print("✅ Base image loaded")
return rgbBaseImage
}
private func rgbHoleMaskImage(from rgbHoleMaskImageAbsolutePath: String) -> NSImage? {
print("⏳ Hole mask image loading...")
guard let rgbHoleMaskImage
= NSImage(contentsOfFile: rgbHoleMaskImageAbsolutePath) else {
print("🛑 Couldn't load \(rgbHoleMaskImageAbsolutePath)")
return nil
}
print("✅ Hole mask image loaded")
return rgbHoleMaskImage
}
private func holeFilledGrayMatrix(
baseGrayPixelMatrix: Matrix<GrayPixel>,
holeMaskGrayPixelMatrix: Matrix<GrayPixel>,
z: Float,
epsilon: PositiveNonZeroFloat,
pixelConnectivity: PixelConnectivity) -> Matrix<GrayPixel>? {
print("⏳ Hole filling...")
guard let holeFilledGrayMatrix = holeFiller.grayPixelMatrixWithFilledHole(
baseGrayPixelMatrix: baseGrayPixelMatrix,
holeMaskGrayPixelMatrix: holeMaskGrayPixelMatrix,
isHolePixel: { $0.isBlack },
weightingFunction: defaultWeightingFunction(z: z, epsilon: epsilon),
pixelConnectivity: pixelConnectivity
) else {
print("🛑 Error while processing")
return nil
}
print("✅ Hole filling completed")
return holeFilledGrayMatrix
}
private func holeFilledGrayImage(
from holeFilledGrayMatrix: Matrix<GrayPixel>) -> NSImage? {
print("⏳ Hole filled gray image creation...")
guard let holeFilledGrayImage = holeFilledGrayMatrix.asImage() else {
print("🛑 Error converting processed data to image")
return nil
}
print("✅ Hole filled gray image created")
return holeFilledGrayImage
}
private func save(
holeFilledGrayImage: NSImage,
at outputImageAbsolutePath: String) {
print("⏳ Hole filled gray image saving...")
do {
try holeFilledGrayImage.saveAs(fileAbsolutePath: outputImageAbsolutePath)
} catch {
print("🛑 Error saving image to disk")
}
print("✅ Hole filled gray image saved at: " + outputImageAbsolutePath)
}
}
| 34.251908 | 90 | 0.648317 |
5b4f7be1c6971a7ddf14ea89c70bcb0649c86c9c | 6,727 | //
// AppFlowController.swift
// LobstersReader
//
// Created by Colin Drake on 5/27/17.
// Copyright © 2017 Colin Drake. All rights reserved.
//
import UIKit
import SafariServices
/// Main app flow controller responsible for application navigation and view controller management.
final class AppFlowController: NSObject, StoriesViewControllerDelegate, InfoViewControllerDelegate, TagsViewControllerDelegate, UITabBarControllerDelegate {
fileprivate let rootViewController: UITabBarController
fileprivate let client = APIClient()
fileprivate let readTracker: PersistentStoryReadTracker
init(withWindow window: UIWindow) {
// Apply theme.
AppTheme.apply()
// Set up cache.
guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
fatalError("Could not find cache directory")
}
let readTrackerCacheFileName = cachePath.appending("/readTrackingCache")
readTracker = PersistentStoryReadTracker(cacheFilePath: readTrackerCacheFileName)
// Setup view controller hierarchy.
rootViewController = UITabBarController()
let newestStoriesViewController = StoriesViewController(type: .hottest, fetcher: client, readTracker: readTracker)
let hottestStoriesViewController = StoriesViewController(type: .newest, fetcher: client, readTracker: readTracker)
let infoViewController = InfoViewController(info: defaultAppInfo)
let tagsViewController = TagsViewController()
super.init()
infoViewController.delegate = self
newestStoriesViewController.delegate = self
hottestStoriesViewController.delegate = self
tagsViewController.delegate = self
rootViewController.delegate = self
rootViewController.viewControllers = [
UINavigationController(rootViewController: newestStoriesViewController),
UINavigationController(rootViewController: hottestStoriesViewController),
UINavigationController(rootViewController: tagsViewController),
UINavigationController(rootViewController: infoViewController)
]
// Install into window.
Logger.shared.log("Installing app flow controller...")
window.rootViewController = rootViewController
// Subscribe to notifications.
NotificationCenter.default.addObserver(self, selector: #selector(AppFlowController.appBackgrounded), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
}
func appBackgrounded() {
readTracker.save()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: 3D Touch Shortcuts
fileprivate enum Shortcut: String {
case hottest, newest, tags
static let all: [Shortcut] = [.hottest, .newest, .tags]
var tabIndex: Int {
return Shortcut.all.index(of: self)!
}
}
var shortcutItems: [UIApplicationShortcutItem] {
return Shortcut.all.map { shortcut in
let identifier = shortcut.rawValue
let name = identifier.localizedCapitalized
let icon = UIApplicationShortcutIcon(templateImageName: "\(name)Icon")
return UIApplicationShortcutItem(type: identifier, localizedTitle: name, localizedSubtitle: nil, icon: icon, userInfo: nil)
}
}
func attemptToHandle(shortcut: UIApplicationShortcutItem) -> Bool {
guard let shortcut = Shortcut(rawValue: shortcut.type) else {
return false
}
rootViewController.selectedIndex = shortcut.tabIndex
return true
}
// MARK: Helpers
fileprivate func controllerToShow(url: URL) -> SFSafariViewController {
let viewController = SFSafariViewController(url: url)
viewController.preferredControlTintColor = .lobstersRed
return viewController
}
// MARK: UITabBarDelegate
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let selectedController = tabBarController.selectedViewController else { return true }
guard let viewController = viewController as? UINavigationController else { return true }
// Check if we're selecting an already selected view controller.
// If so, allow power users to use this bounce to top of stories controller, or back to tags listing.
if selectedController == viewController {
if let viewController = viewController.viewControllers.first as? StoriesViewController {
viewController.scrollToTop()
} else if let viewController = viewController.viewControllers.first as? TagsViewController {
viewController.navigationController?.popViewController(animated: true)
}
}
return true
}
// MARK: StoriesViewControllerDelegate
func showStory(_ story: StoryViewModel, storiesViewController: StoriesViewController) {
let viewController = controllerToShow(url: story.viewableUrl)
rootViewController.present(viewController, animated: true, completion: nil)
}
func showCommentsForStory(_ story: StoryViewModel, storiesViewController: StoriesViewController) {
let viewController = controllerToShow(url: story.commentsUrl)
rootViewController.present(viewController, animated: true, completion: nil)
}
func previewingViewControllerForStory(_ story: StoryViewModel, storiesViewController: StoriesViewController) -> UIViewController {
let viewController = controllerToShow(url: story.viewableUrl)
return viewController
}
func commitPreviewingViewControllerForStory(_ viewController: UIViewController, storiesViewController: StoriesViewController) {
rootViewController.present(viewController, animated: true, completion: nil)
}
// MARK: InfoViewControllerDelegate
func infoViewController(infoViewController: InfoViewController, selectedUrl url: URL) {
let viewController = controllerToShow(url: url)
rootViewController.present(viewController, animated: true, completion: nil)
}
// MARK: TagsViewControllerDelegate
func tagsViewController(tagsViewController: TagsViewController, selectedTag tag: String) {
guard let navigationController = tagsViewController.navigationController else {
return
}
let tagViewController = StoriesViewController(type: FeedType.tagged(tag), fetcher: client, readTracker: readTracker)
tagViewController.delegate = self
navigationController.pushViewController(tagViewController, animated: true)
}
}
| 40.769697 | 178 | 0.721124 |
9177a89223d44e70a46de978875b325477bfb06c | 1,174 | //
// TTModeMusicPlayPauseOptions.swift
// Turn Touch iOS
//
// Created by Samuel Clay on 7/30/18.
// Copyright © 2018 Turn Touch. All rights reserved.
//
import UIKit
class TTModeMusicPlayPauseOptions: TTOptionsDetailViewController {
required init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "TTModeMusicPlayPauseOptions", bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| 26.088889 | 106 | 0.674617 |
89922a9bbdec326b2ba2c65982dd164944d1b9cd | 606 | //
// VolumeDescription.swift
// ComicList
//
// Created by Francisco Solano Gómez Pino on 09/10/2016.
// Copyright © 2016 Guillermo Gonzalez. All rights reserved.
//
import Foundation
public struct VolumeDescription {
public let description: String?
}
extension VolumeDescription: JSONDecodable {
public init?(dictionary: JSONDictionary) {
guard let description:String = dictionary["description"] as? String else {
self.description = nil
return
}
self.description = description.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
| 20.2 | 119 | 0.711221 |
89270d32824f9ed3312437114d17383fc693bfe2 | 6,628 | //
// Store.swift
// ReCombine
//
// Created by Crowson, John on 12/10/19.
// Copyright © 2019 Crowson, John.
// Licensed under Apache License 2.0
//
import Combine
/// Protocol that all action's must implement.
///
/// Example implementation:
/// ```
/// struct GetPostSuccess: Action {
/// let post: Post
/// }
/// ```
public protocol Action : CustomEquatable {}
public protocol CustomEquatable {
func isEqualTo(_ other: CustomEquatable) -> Bool
}
extension CustomEquatable {
public func isEqualTo(_ other: CustomEquatable) -> Bool {
false
}
}
extension CustomEquatable where Self: Equatable {
public func isEqualTo(_ other: CustomEquatable) -> Bool {
(other as? Self) == self
}
}
/// A generic representation of a reducer function.
///
/// Reducer functions are pure functions which take a State and Action and return a State.
/// ```
/// let reducer: ReducerFn = { (state: State, action: Action) in
/// var state = state
/// switch action {
/// case let action as SetScores:
/// state.home = action.game.home
/// state.away = action.game.away
/// return state
/// default:
/// return state
/// }
/// }
/// ```
public typealias ReducerFn<S> = (inout S, Action) -> Void
/// A generic representation of a selector function.
///
/// Selector functions are pure functions which take a State and return data derived from that State.
/// ```
/// let selectPost = { (state: AppState) in
/// return state.singlePost.post
/// }
/// ```
public typealias SelectorFn<S, V> = (S) -> V
/// Combine-based state management. Enables dispatching of actions, executing reducers, performing side-effects, and listening for the latest state.
///
/// Implements the `Publisher` protocol, allowing direct subscription for the latest state.
/// ```
/// import ReCombine
/// import Combine
///
/// struct CounterView {
/// struct Increment: Action {}
/// struct Decrement: Action {}
///
/// struct State {
/// var count = 0
/// }
///
/// static func reducer(state: State, action: Action) -> State {
/// var state = state
/// switch action {
/// case _ as Increment:
/// state.count += 1
/// return state
/// case _ as Decrement:
/// state.count -= 1
/// return state
/// default:
/// return state
/// }
/// }
///
/// static let effect = Effect(dispatch: false) { (actions: AnyPublisher<Action, Never>) in
/// actions.ofTypes(Increment.self, Decrement.self).print("Action Dispatched").eraseToAnyPublisher()
/// }
/// }
///
/// let store = Store(reducer: CounterView.reducer, initialState: CounterView.State(), effects: [CounterView.effect])
/// ```
open class Store<S>: Publisher {
/// Publisher protocol - emits the state :nodoc:
public typealias Output = S
/// Publisher protocol :nodoc:
public typealias Failure = Never
private var state: S
private var stateSubject: CurrentValueSubject<S, Never>
private var actionSubject: PassthroughSubject<Action, Never>
private var cancellableSet: Set<AnyCancellable> = []
private let reducer: ReducerFn<S>
/// Creates a new Store.
/// - Parameter reducer: a single reducer function which will handle reducing state for all actions dispatched to the store.
/// - Parameter initialState: the initial state. This state will be used by consumers before the first action is dispatched.
/// - Parameter epics: action based side-effects. Each `Epic` element is processed for the lifetime of the `Store` instance.
public init(reducer: @escaping ReducerFn<S>, initialState: S, epics: [Epic<S>] = []) {
self.reducer = reducer
state = initialState
stateSubject = CurrentValueSubject(initialState)
actionSubject = PassthroughSubject()
for epic in epics {
// Effects registered through init are maintained for the lifecycle of the Store.
register(epic).store(in: &cancellableSet)
}
}
/// Dispatch `Action` to the Store. Calls reducer function with the passed `action` and previous state to generate a new state.
/// - Parameter action: action to call the reducer with.
///
/// Dispatching an action to the Store:
/// ```
/// struct Increment: Action {}
///
/// store.dispatch(action: Increment())
/// ```
open func dispatch(action: Action) {
reducer(&state, action)
stateSubject.send(state)
actionSubject.send(action)
}
/// Returns derived data from the application state based on a given selector function.
///
/// Selector functions help return view-specific data from a minimum application state.
///
/// **Example:** If a view needs the count of characters in a username, instead of storing both the username and the character count in state, store only the username, and use a selector to retrieve the count.
/// ```
/// store.select({ (state: AppState) in state.username.count })
/// ```
/// To enable reuse, abstract the closure into a separate property.
/// ```
/// let selectUsernameCount = { (state: AppState) in state.username.count }
/// // ...
/// store.select(selectUsernameCount)
/// ```
public func select<V: Equatable>(_ selector: @escaping (S) -> V) -> AnyPublisher<V, Never> {
return map(selector).removeDuplicates().eraseToAnyPublisher()
}
/// Publisher protocol - use the internal stateSubject under the hood :nodoc:
open func receive<T>(subscriber: T) where T: Subscriber, Failure == T.Failure, Output == T.Input {
stateSubject.receive(subscriber: subscriber)
}
/// Registers an epic that processes from when this function is called until the returned `AnyCancellable` instance in cancelled.
///
/// This can be useful for:
/// 1. Epics that should not process for the entire lifetime of the `Store` instance.
/// 2. Epics that need to capture a particular scope in it's `source` closure.
///
/// ```
/// - Parameter effect: action based side-effect. It is processed until the returned `AnyCancellable` instance is cancelled.
open func register(_ epic: Epic<S>) -> AnyCancellable {
return epic.source(StatePublisher(storeSubject: stateSubject), actionSubject.eraseToAnyPublisher())
.filter { _ in return epic.dispatch }
.sink(receiveValue: { [weak self] action in self?.dispatch(action: action) })
}
}
| 36.417582 | 213 | 0.638051 |
792264a5a965140bf7ba1fe59fa4cd8cb37ab2e5 | 509 | //
// ViewController.swift
// TouchTracker
//
// Created by Charles Kang on 7/5/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.576923 | 80 | 0.669941 |
753795d79446635b3d31bf0b8982948a894a4905 | 3,415 | import BuildArtifacts
import DeveloperDirModels
import Foundation
import MetricsExtensions
import PluginSupport
import QueueModels
import SimulatorPoolModels
import RunnerModels
public struct SchedulerBucket: CustomStringConvertible, Equatable {
public let bucketId: BucketId
public let analyticsConfiguration: AnalyticsConfiguration
public let pluginLocations: Set<PluginLocation>
public let runTestsBucketPayload: RunTestsBucketPayload
public var description: String {
var result = [String]()
result.append("\(bucketId)")
result.append("buildArtifacts: \(runTestsBucketPayload.buildArtifacts)")
result.append("developerDir: \(runTestsBucketPayload.developerDir)")
result.append("pluginLocations: \(pluginLocations)")
result.append("simulatorControlTool: \(runTestsBucketPayload.simulatorControlTool)")
result.append("simulatorOperationTimeouts: \(runTestsBucketPayload.simulatorOperationTimeouts)")
result.append("simulatorSettings: \(runTestsBucketPayload.simulatorSettings)")
result.append("testDestination: \(runTestsBucketPayload.testDestination)")
result.append("testEntries: " + runTestsBucketPayload.testEntries.map { $0.testName.stringValue }.joined(separator: ","))
result.append("testExecutionBehavior: \(runTestsBucketPayload.testExecutionBehavior)")
result.append("testRunnerTool: \(runTestsBucketPayload.testRunnerTool)")
result.append("testTimeoutConfiguration: \(runTestsBucketPayload.testTimeoutConfiguration)")
result.append("testType: \(runTestsBucketPayload.testType)")
return "<\((type(of: self))) " + result.joined(separator: " ") + ">"
}
public init(
bucketId: BucketId,
analyticsConfiguration: AnalyticsConfiguration,
pluginLocations: Set<PluginLocation>,
runTestsBucketPayload: RunTestsBucketPayload
) {
self.bucketId = bucketId
self.analyticsConfiguration = analyticsConfiguration
self.pluginLocations = pluginLocations
self.runTestsBucketPayload = runTestsBucketPayload
}
public static func from(bucket: Bucket, testExecutionBehavior: TestExecutionBehavior) -> SchedulerBucket {
return SchedulerBucket(
bucketId: bucket.bucketId,
analyticsConfiguration: bucket.analyticsConfiguration,
pluginLocations: bucket.pluginLocations,
runTestsBucketPayload: RunTestsBucketPayload(
buildArtifacts: bucket.runTestsBucketPayload.buildArtifacts,
developerDir: bucket.runTestsBucketPayload.developerDir,
simulatorControlTool: bucket.runTestsBucketPayload.simulatorControlTool,
simulatorOperationTimeouts: bucket.runTestsBucketPayload.simulatorOperationTimeouts,
simulatorSettings: bucket.runTestsBucketPayload.simulatorSettings,
testDestination: bucket.runTestsBucketPayload.testDestination,
testEntries: bucket.runTestsBucketPayload.testEntries,
testExecutionBehavior: testExecutionBehavior,
testRunnerTool: bucket.runTestsBucketPayload.testRunnerTool,
testTimeoutConfiguration: bucket.runTestsBucketPayload.testTimeoutConfiguration,
testType: bucket.runTestsBucketPayload.testType
)
)
}
}
| 49.492754 | 129 | 0.726794 |
8a37f56ad50ae65a40250eb8ff44121b6eff789d | 5,915 | //
// ToolTipView.swift
// EasyTipView-Example
//
// Created by MANISH PATHAK on 7/3/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class TooltipView: UIView {
//MARK: - IBInspectable
@IBInspectable var arrowTopLeft: Bool = false
@IBInspectable var arrowTopCenter: Bool = true
@IBInspectable var arrowTopRight: Bool = false
@IBInspectable var arrowBottomLeft: Bool = false
@IBInspectable var arrowBottomCenter: Bool = false
@IBInspectable var arrowBottomRight: Bool = false
@IBInspectable var fillColor: UIColor = UIColor.white
@IBInspectable var borderColor: UIColor = UIColor(red:0, green:0, blue:0, alpha:0.05)
@IBInspectable var borderRadius: CGFloat = 18
@IBInspectable var borderWidth: CGFloat = 1
@IBInspectable var shadowColor: UIColor = UIColor(red:0, green:0, blue:0, alpha:0.14)
@IBInspectable var shadowOffsetX: CGFloat = 0
@IBInspectable var shadowOffsetY: CGFloat = 2
@IBInspectable var shadowBlur: CGFloat = 10
//MARK: - Global Variables
var tooltipWidth = 0
var tooltipHeight = 0
//MARK: - Initialization
override func draw(_ rect: CGRect) {
drawTooltip()
}
//MARK: - Private Methods
// Orientation methods
private func topLeft(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
private func topRight(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: CGFloat(tooltipWidth) - x, y: y)
}
private func bottomLeft(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: CGFloat(tooltipHeight) - y)
}
private func bottomRight(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: CGFloat(tooltipWidth) - x, y: CGFloat(tooltipHeight) - y)
}
// Draw methods
private func drawTooltip() {
tooltipWidth = Int(bounds.width)
tooltipHeight = Int(bounds.height)
// Define Bubble Shape
let bubblePath = UIBezierPath()
// Top left corner
bubblePath.move(to: topLeft(0, borderRadius))
bubblePath.addCurve(to: topLeft(borderRadius, 0), controlPoint1: topLeft(0, borderRadius / 2), controlPoint2: topLeft(borderRadius / 2, 0))
// Top right corner
bubblePath.addLine(to: topRight(borderRadius, 0))
bubblePath.addCurve(to: topRight(0, borderRadius), controlPoint1: topRight(borderRadius / 2, 0), controlPoint2: topRight(0, borderRadius / 2))
// Bottom right corner
bubblePath.addLine(to: bottomRight(0, borderRadius))
bubblePath.addCurve(to: bottomRight(borderRadius, 0), controlPoint1: bottomRight(0, borderRadius / 2), controlPoint2: bottomRight(borderRadius / 2, 0))
// Bottom left corner
bubblePath.addLine(to: bottomLeft(borderRadius, 0))
bubblePath.addCurve(to: bottomLeft(0, borderRadius), controlPoint1: bottomLeft(borderRadius / 2, 0), controlPoint2: bottomLeft(0, borderRadius / 2))
bubblePath.close()
// Arrow
if(arrowTopLeft) {
bubblePath.move(to: topLeft(3, 10))
bubblePath.addLine(to: topLeft(3, -4))
bubblePath.addLine(to: topLeft(16, 2))
bubblePath.close()
}
if(arrowTopCenter) {
bubblePath.move(to: topLeft(CGFloat((tooltipWidth / 2) - 5), 0))
bubblePath.addLine(to: topLeft(CGFloat(tooltipWidth / 2), -8))
bubblePath.addLine(to: topLeft(CGFloat(tooltipWidth / 2 + 5), 0))
bubblePath.close()
}
if(arrowTopRight) {
bubblePath.move(to: topRight(16, 2))
bubblePath.addLine(to: topRight(3, -4))
bubblePath.addLine(to: topRight(3, 10))
bubblePath.close()
}
if(arrowBottomLeft) {
bubblePath.move(to: bottomLeft(16, 2))
bubblePath.addLine(to: bottomLeft(3, -4))
bubblePath.addLine(to: bottomLeft(3, 10))
bubblePath.close()
}
if(arrowBottomCenter) {
bubblePath.move(to: bottomLeft(CGFloat((tooltipWidth / 2) - 5), 0))
bubblePath.addLine(to: bottomLeft(CGFloat(tooltipWidth / 2), -8))
bubblePath.addLine(to: bottomLeft(CGFloat(tooltipWidth / 2 + 5), 0))
bubblePath.close()
}
if(arrowBottomRight) {
bubblePath.move(to: bottomRight(3, 10))
bubblePath.addLine(to: bottomRight(3, -4))
bubblePath.addLine(to: bottomRight(16, 2))
bubblePath.close()
}
// Shadow Layer
let shadowShape = CAShapeLayer()
shadowShape.path = bubblePath.cgPath
shadowShape.fillColor = fillColor.cgColor
shadowShape.shadowColor = shadowColor.cgColor
shadowShape.shadowOffset = CGSize(width: CGFloat(shadowOffsetX), height: CGFloat(shadowOffsetY))
shadowShape.shadowRadius = CGFloat(shadowBlur)
shadowShape.shadowOpacity = 0.8
// Border Layer
let borderShape = CAShapeLayer()
borderShape.path = bubblePath.cgPath
borderShape.fillColor = fillColor.cgColor
borderShape.strokeColor = borderColor.cgColor
borderShape.lineWidth = CGFloat(borderWidth*2)
// Fill Layer
let fillShape = CAShapeLayer()
fillShape.path = bubblePath.cgPath
fillShape.fillColor = fillColor.cgColor
// Add Sublayers
self.layer.insertSublayer(shadowShape, at: 0)
self.layer.insertSublayer(borderShape, at: 0)
self.layer.insertSublayer(fillShape, at: 0)
}
}
| 33.607955 | 159 | 0.606424 |
e9f3cd90ad210bdd0632f172ff6428f3ba1a638a | 5,171 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@testable import CareKit
import CareKitUI
import Foundation
import XCTest
class TestGridTaskViewSynchronizer: XCTestCase {
var viewSynchronizer: OCKGridTaskViewSynchronizer!
var view: OCKGridTaskView!
var taskEvents: OCKTaskEvents!
override func setUp() {
super.setUp()
viewSynchronizer = .init()
view = viewSynchronizer.makeView()
}
func testViewIsClearedInInitialState() {
XCTAssertNil(view.instructionsLabel.text)
XCTAssertNil(view.headerView.titleLabel.text)
XCTAssertNil(view.headerView.detailLabel.text)
}
func testCellIsClearedInInitialState() {
let cell = OCKGridTaskView.DefaultCellType()
XCTAssertFalse(cell.completionButton.isSelected)
XCTAssertNil(cell.completionButton.label.text)
}
func testViewDoesUpdate() {
taskEvents = OCKTaskEvents.mock(eventsHaveOutcomes: false)
viewSynchronizer.updateView(view, context: .init(viewModel: taskEvents, oldViewModel: .init(), animated: false))
XCTAssertEqual(view.instructionsLabel.text, taskEvents.first?.first?.task.instructions)
XCTAssertEqual(view.headerView.titleLabel.text, taskEvents.first?.first?.task.title)
XCTAssertEqual(view.headerView.detailLabel.text, OCKScheduleUtility.scheduleLabel(for: taskEvents.first!))
}
func testCellDoesUpdateWithNoOutcomes() {
taskEvents = OCKTaskEvents.mock(eventsHaveOutcomes: false)
let itemCount = taskEvents.first?.count
for index in 0..<(itemCount ?? 0) {
let cell = OCKGridTaskView.DefaultCellType()
cell.updateWith(event: taskEvents[0][index], animated: false)
XCTAssertFalse(cell.completionButton.isSelected)
XCTAssertEqual(cell.completionButton.label.text,
OCKScheduleUtility.timeLabel(for: taskEvents[0][index], includesEnd: false))
// Accessibility
XCTAssertEqual(cell.accessibilityLabel, cell.completionButton.label.text)
XCTAssertEqual(cell.accessibilityValue, loc("INCOMPLETE"))
}
}
func testCellDoesUpdateWithOutcomes() {
taskEvents = OCKTaskEvents.mock(eventsHaveOutcomes: true)
let itemCount = taskEvents.first?.count
for index in 0..<(itemCount ?? 0) {
let cell = OCKGridTaskView.DefaultCellType()
cell.updateWith(event: taskEvents[0][index], animated: false)
XCTAssertTrue(cell.completionButton.isSelected)
XCTAssertEqual(cell.completionButton.label.text,
OCKScheduleUtility.completedTimeLabel(for: taskEvents[0][index]))
// Accessibility
XCTAssertEqual(cell.accessibilityLabel, cell.completionButton.label.text)
XCTAssertEqual(cell.accessibilityValue, loc("COMPLETED"))
}
}
func testViewDoesClearAfterUpdate() {
taskEvents = OCKTaskEvents.mock(eventsHaveOutcomes: false)
viewSynchronizer.updateView(view, context: .init(viewModel: taskEvents, oldViewModel: .init(), animated: false))
XCTAssertNotNil(view.instructionsLabel.text)
XCTAssertNotNil(view.headerView.titleLabel.text)
XCTAssertNotNil(view.headerView.detailLabel.text)
viewSynchronizer.updateView(view, context: .init(viewModel: .init(), oldViewModel: .init(), animated: false))
XCTAssertNil(view.instructionsLabel.text)
XCTAssertNil(view.headerView.titleLabel.text)
XCTAssertNil(view.headerView.detailLabel.text)
}
}
| 45.761062 | 120 | 0.730033 |
ff86633fdc3f6e45c5d4021152f2161a7572e939 | 1,049 | //
// ModelAwareViewController.swift
// SobrKit-Example
//
// Created by Silas Knobel on 26/04/15.
// Copyright (c) 2015 Software Brauerei AG. All rights reserved.
//
import UIKit
import SobrKit
class MyModel: NSObject {
dynamic var text: String?
}
class ModelAwareViewController: UIViewController {
var data = MyModel()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func loadJoke(sender: AnyObject) {
API.fetchJokes({ (jokes) -> Void in
let randomIndex = self.randomIndexInRange(0..<jokes.count)
let randomJoke = jokes[randomIndex]
self.data.text = randomJoke.text
}, failure: { (error) -> Void in
self.data.text = error.localizedDescription
})
}
func randomIndexInRange(range: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
}
}
| 24.97619 | 100 | 0.64347 |
d9fab916193028968a6e3ebdb8b6696b1f5bc68f | 519 | //
// 🦠 Corona-Warn-App
//
import Foundation
struct AerosoleDecayFunctionLinear: Codable {
// MARK: - Init
init(from aerosoleDecayFunctionLinear: SAP_Internal_V2_PresenceTracingSubmissionParameters.AerosoleDecayFunctionLinear) {
self.minutesRange = ENARange(from: aerosoleDecayFunctionLinear.minutesRange)
self.slope = aerosoleDecayFunctionLinear.slope
self.intercept = aerosoleDecayFunctionLinear.intercept
}
// MARK: - Internal
let minutesRange: ENARange
let slope: Double
let intercept: Double
}
| 21.625 | 122 | 0.797688 |
d9bf4afaf351d35374504ccb9c8b0d101729c5ab | 2,665 | //
// PhotosController.swift
// doko
//
// Created by Emily on 9/8/18.
// Copyright © 2018 Emily. All rights reserved.
//
import Foundation
import UIKit
class PhotosController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var data: [Spot] = []
//??
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getPostsByLocation(lat: -75.19211, lon: 39.953321) { posts in
self.data = []
print(posts)
print(posts[0].spotId)
posts.forEach({ post in
getSpotById(id: post.spotId) { spot in
self.data.append(spot)
self.tableView.reloadData()
}
})
}
let cellReuseIdentifier = "cell";
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier);
tableView.delegate = self;
tableView.dataSource = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count;
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: PhotoCell = self.tableView.dequeueReusableCell(withIdentifier: "PhotoCell") as! PhotoCell
cell.username.text = self.data[indexPath.row].name;
cell.profile_img.image = #imageLiteral(resourceName: "temp")
cell.geolocation.text = self.data[indexPath.row].id
cell.liked_img.image = #imageLiteral(resourceName: "temp")
cell.likes.text = "Yunno"
cell.time_liked.text = "Liked two days ago"
return cell;
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
performSegue(withIdentifier: "photo_store", sender: cell)
}
}
class PhotoCell: UITableViewCell {
@IBOutlet var profile_img: UIImageView!
@IBOutlet var username: UILabel!
@IBOutlet var geolocation: UILabel!
@IBOutlet var liked_img: UIImageView!
@IBOutlet var likes: UILabel!
@IBOutlet var time_liked: UILabel!
}
| 29.94382 | 107 | 0.624765 |
874b4bcd805d231e690804f4760719d01e41ad9f | 1,311 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Defines tests to ensure that some of our layouts are working as expected.
*/
import XCTest
/**
A simple layout type to use for testing. We can check the frame after laying
out the rect to see the effect of composing other layouts. Note that this layout's
`Content` is also a `TestLayout`, so these layouts will be at the leaves.
*/
struct TestLayout: Layout {
typealias Content = TestLayout
var frame: CGRect
init(frame: CGRect = .zero) {
self.frame = frame
}
mutating func layout(in rect: CGRect) {
self.frame = rect
}
var contents: [Content] {
return [self]
}
}
class LayoutTests: XCTestCase {
func testLayout() {
let child1 = TestLayout()
let child2 = TestLayout()
var layout = DecoratingLayout(content: child1, decoration: child2)
layout.layout(in: CGRect(x: 0, y: 0, width: 90, height: 40))
// Check to see that the frames are at the expected values.
XCTAssertEqual(layout.contents[0].frame, CGRect(x: 0, y: 5, width: 25, height: 30))
XCTAssertEqual(layout.contents[1].frame, CGRect(x: 35, y: 5, width: 50, height: 30))
}
}
| 27.893617 | 92 | 0.647597 |
8a59c37a9fe4b34cf2f061739bd601074fb7757a | 380 | //
// User.swift
// Followers
//
// Created by Stefano Bertagno on 10/03/2020.
// Copyright © 2020 Stefano Bertagno. All rights reserved.
//
import Foundation
/// A `struct` holding reference to a user's basic info.
struct User: Codable {
/// The username.
var username: String
/// The full name.
var name: String?
/// The avatar.
var avatar: URL?
}
| 19 | 59 | 0.639474 |
22ca811340be922af5505b8c0347de600a85d216 | 3,344 | //
// WCSession.swift
// CellSignal
//
// Created by Royce Albert Dy on 15/11/2015.
// Copyright © 2015 rad182. All rights reserved.
//
import Foundation
import WatchConnectivity
import ClockKit
let SessionUtility = CSSessionUtility()
class CSSessionUtility: NSObject {
var currentSession: WCSession?
var currentRadioAccessTechnology: String?
var currentSignalStrengthPercentage = 0
override init () {
super.init()
self.currentSession = WCSession.defaultSession()
self.currentSession!.delegate = self
self.currentSession!.activateSession()
}
// MARK: - Public Methods
func refreshComplications() {
let server = CLKComplicationServer.sharedInstance()
for complication in server.activeComplications {
server.reloadTimelineForComplication(complication)
}
}
func updateCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentage(completion: ((currentRadioAccessTechnology: String?, currentSignalStrengthPercentage: Int) -> Void)?) {
if let currentSession = self.currentSession where currentSession.reachable {
currentSession.sendMessage(["request": CSCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentageRequestKey],
replyHandler: { (response) -> Void in
print(response)
let currentRadioAccessTechnology = response[CSCurrentRadioAccessTechnologyKey] as? String
let currentSignalStrengthPercentage = response[CSCurrentSignalStrengthPercentageKey] as! Int
completion?(currentRadioAccessTechnology: currentRadioAccessTechnology, currentSignalStrengthPercentage: currentSignalStrengthPercentage)
}, errorHandler: { (error) -> Void in
print(error)
})
} else {
completion?(currentRadioAccessTechnology: nil, currentSignalStrengthPercentage: 0)
}
}
func reloadComplicationData() {
if let currentSession = self.currentSession where currentSession.reachable {
currentSession.sendMessage(["request": CSCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentageRequestKey],
replyHandler: { (response) -> Void in
print(response)
self.currentRadioAccessTechnology = response[CSCurrentRadioAccessTechnologyKey] as? String
self.currentSignalStrengthPercentage = response[CSCurrentSignalStrengthPercentageKey] as! Int
self.refreshComplications()
}, errorHandler: { (error) -> Void in
print(error)
self.refreshComplications()
}
)
} else {
self.currentRadioAccessTechnology = nil
self.currentSignalStrengthPercentage = 0
self.refreshComplications()
}
}
}
extension CSSessionUtility: WCSessionDelegate {
func sessionReachabilityDidChange(session: WCSession) {
print("sessionReachabilityDidChange \(session.reachable)")
if session.reachable {
self.reloadComplicationData()
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
self.reloadComplicationData()
}
} | 39.809524 | 181 | 0.665371 |
71a650a22c932263647cf01fed7f251d7083ad1d | 1,338 | //
// ViewController.swift
// ZXLockView
//
// Created by admin on 28/02/2017.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func setPassword(_ sender: UIButton) {
let passwordVC = PasswordViewController(nibName: nil, bundle: nil)
passwordVC.lockViewType = ZXLockView.LockViewType.set
passwordVC.labelTT = "请绘制手势密码"
self.present(passwordVC, animated: true, completion: nil)
}
@IBAction func changePassword(_ sender: UIButton) {
let passwordVC = PasswordViewController(nibName: nil, bundle: nil)
passwordVC.lockViewType = ZXLockView.LockViewType.change
passwordVC.labelTT = "请绘制原手势密码"
self.present(passwordVC, animated: true, completion: nil)
}
@IBAction func testPassword(_ sender: UIButton) {
let passwordVC = PasswordViewController(nibName: nil, bundle: nil)
passwordVC.lockViewType = ZXLockView.LockViewType.test
passwordVC.labelTT = "请绘制原手势密码"
self.present(passwordVC, animated: true, completion: nil)
}
}
| 30.409091 | 74 | 0.681614 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.