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
|
---|---|---|---|---|---|
ebd1026032783026884ae33e909318deb72529fb | 205 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C<T where I.h:y{func c()->Self | 41 | 87 | 0.756098 |
8f431e2d9b257e18e951c703f62899cb1fa0fa70 | 1,656 | //
// AutoCompleteGoal.swift
// MeFocus
//
// Created by Hao on 11/20/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
import AutoCompleteTextField
protocol AutoCompleteGoalDelegate {
func onResignFirstResponder(suggestion:Suggestion)
func onResignFirstResponder(goal:String)
}
class AutoCompleteGoal: AutoCompleteTextField {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var autoCompleteGoalDelegate:AutoCompleteGoalDelegate?
override open func resignFirstResponder() -> Bool {
let responder = super.resignFirstResponder()
if let delegate = autoCompleteGoalDelegate {
let goal:String = text ?? ""
if let suggestion = SuggestionsManager.findByGoal(goal: goal){
delegate.onResignFirstResponder(suggestion: suggestion)
return responder
}
delegate.onResignFirstResponder(goal: goal)
}
return responder
}
}
extension AutoCompleteGoal:AutoCompleteTextFieldDataSource {
func autoCompleteTextFieldDataSource(_ autoCompleteTextField: AutoCompleteTextField) -> [String] {
let suggestions = SuggestionsManager.all
return suggestions.map({
(suggestion:Suggestion) in
if let name = suggestion.goal {
return name
}
return ""
})
}
}
| 24.716418 | 102 | 0.620169 |
5d8770e150f439ced691ddabaf4c64e2114b75c3 | 852 | //
// StructPrototypeNode.swift
// Cub
//
// Created by Louis D'hauwe on 10/01/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
public struct StructPrototypeNode: ASTNode {
public let name: String
public let members: [String]
public init(name: String, members: [String]) throws {
guard members.count > 0 else {
throw CompileError.emptyStruct
}
self.name = name
self.members = members
}
public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody {
return []
}
public var childNodes: [ASTNode] {
return []
}
public var description: String {
return "StructPrototypeNode(name: \(name), members: \(members))"
}
public var nodeDescription: String? {
return "Struct Prototype"
}
public var descriptionChildNodes: [ASTChildNode] {
return []
}
}
| 18.12766 | 94 | 0.696009 |
b996521b6f3f407ffc61ef6f8e20630227e76bac | 219 | //
// KulaApp.swift
// Kula
//
// Created by Cédric Bahirwe on 26/07/2021.
//
import SwiftUI
@main
struct KulaApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.166667 | 44 | 0.543379 |
e821ee94193b2e940bbe83aaf8d56174c10649ff | 1,095 | //
// MZFatherController.swift
// diary
//
// Created by 曾龙 on 2018/6/20.
// Copyright © 2018年 mz. All rights reserved.
//
import UIKit
class MZFatherController: UIViewController {
var bgImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.bgImageView = UIImageView.init(frame: self.view.bounds);
self.view.addSubview(self.bgImageView);
self.view.backgroundColor = UIColor.white;
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
//3.重写无参数初始化方法,自动调用xib文件
convenience init() {
let nibNameOrNil = String(describing: type(of: self))
//考虑到xib文件可能不存在或被删,故加入判断
if Bundle.main.path(forResource: nibNameOrNil, ofType: "nib") != nil {
self.init(nibName: nibNameOrNil, bundle: nil)
}else{
self.init(nibName: nil, bundle: nil)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 26.071429 | 82 | 0.631963 |
cc99c1414009b09115425d9812a709466dd399b7 | 2,573 | //
// AppDelegate.swift
// htchhkr-development
//
// Created by Mustafa GUNES on 24.02.2018.
// Copyright © 2018 Mustafa GUNES. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
fileprivate var containerVC = ContainerVC()
var MenuContainerVC : ContainerVC
{
return containerVC
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
containerVC = ContainerVC()
window?.rootViewController = containerVC
window?.makeKeyAndVisible()
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:.
}
class func getAppDelegate() -> AppDelegate
{
return UIApplication.shared.delegate as! AppDelegate
}
}
| 40.203125 | 285 | 0.731053 |
fcde34ce3344e50c611c0bd7c07069c63e404712 | 7,922 | //
// EntryViewController.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/19/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
protocol EntryPresenterDelegate: class {
var isResponsiveToTouches: Bool { set get }
func displayPendingEntryIfNeeded()
}
class EKRootViewController: UIViewController {
// MARK: - Props
private unowned let delegate: EntryPresenterDelegate
private var lastAttributes: EKAttributes!
private let backgroundView = EKBackgroundView()
private lazy var wrapperView: EKWrapperView = {
return EKWrapperView()
}()
/*
Count the total amount of currently displaying entries,
meaning, total subviews less one - the backgorund of the entry
*/
fileprivate var displayingEntryCount: Int {
return view.subviews.count - 1
}
fileprivate var isDisplaying: Bool {
return lastEntry != nil
}
private var lastEntry: EKContentView? {
return view.subviews.last as? EKContentView
}
private var isResponsive = false {
didSet {
wrapperView.isAbleToReceiveTouches = isResponsive
delegate.isResponsiveToTouches = isResponsive
}
}
override var shouldAutorotate: Bool {
if lastAttributes == nil {
return true
}
return lastAttributes.positionConstraints.rotation.isEnabled
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
guard let lastAttributes = lastAttributes else {
return super.supportedInterfaceOrientations
}
switch lastAttributes.positionConstraints.rotation.supportedInterfaceOrientations {
case .standard:
return super.supportedInterfaceOrientations
case .all:
return .all
}
}
// Previous status bar style
private let previousStatusBar: EKAttributes.StatusBar
private var statusBar: EKAttributes.StatusBar? = nil {
didSet {
if let statusBar = statusBar, ![statusBar, oldValue].contains(.ignored) {
UIApplication.shared.set(statusBarStyle: statusBar)
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if [previousStatusBar, statusBar].contains(.ignored) {
return super.preferredStatusBarStyle
}
return statusBar?.appearance.style ?? previousStatusBar.appearance.style
}
override var prefersStatusBarHidden: Bool {
if [previousStatusBar, statusBar].contains(.ignored) {
return super.prefersStatusBarHidden
}
return !(statusBar?.appearance.visible ?? previousStatusBar.appearance.visible)
}
// MARK: - Lifecycle
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(with delegate: EntryPresenterDelegate) {
self.delegate = delegate
previousStatusBar = .currentStatusBar
super.init(nibName: nil, bundle: nil)
}
override public func loadView() {
view = wrapperView
view.insertSubview(backgroundView, at: 0)
backgroundView.isUserInteractionEnabled = false
backgroundView.fillSuperview()
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
statusBar = previousStatusBar
}
// Set status bar
func setStatusBarStyle(for attributes: EKAttributes) {
statusBar = attributes.statusBar
}
// MARK: - Setup
func configure(entryView: EKEntryView) {
// In case the entry is a view controller, add the entry as child of root
if let viewController = entryView.content.viewController {
addChild(viewController)
}
// Extract the attributes struct
let attributes = entryView.attributes
// Assign attributes
let previousAttributes = lastAttributes
// Remove the last entry
removeLastEntry(lastAttributes: previousAttributes, keepWindow: true)
lastAttributes = attributes
let entryContentView = EKContentView(withEntryDelegate: self)
view.addSubview(entryContentView)
entryContentView.setup(with: entryView)
switch attributes.screenInteraction.defaultAction {
case .forward:
isResponsive = false
default:
isResponsive = true
}
if previousAttributes?.statusBar != attributes.statusBar {
setNeedsStatusBarAppearanceUpdate()
}
if shouldAutorotate {
UIViewController.attemptRotationToDeviceOrientation()
}
}
// Check priority precedence for a given entry
func canDisplay(attributes: EKAttributes) -> Bool {
guard let lastAttributes = lastAttributes else {
return true
}
return attributes.precedence.priority >= lastAttributes.precedence.priority
}
// Removes last entry - can keep the window 'ON' if necessary
private func removeLastEntry(lastAttributes: EKAttributes?, keepWindow: Bool) {
guard let attributes = lastAttributes else {
return
}
if attributes.popBehavior.isOverriden {
lastEntry?.removePromptly()
} else {
popLastEntry()
}
}
// Make last entry exit using exitAnimation - animatedly
func animateOutLastEntry(completionHandler: SwiftEntryKit.DismissCompletionHandler? = nil) {
lastEntry?.dismissHandler = completionHandler
lastEntry?.animateOut(pushOut: false)
}
// Pops last entry (using pop animation) - animatedly
func popLastEntry() {
lastEntry?.animateOut(pushOut: true)
}
}
// MARK: - UIResponder
extension EKRootViewController {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
switch lastAttributes.screenInteraction.defaultAction {
case .dismissEntry:
lastEntry?.animateOut(pushOut: false)
fallthrough
default:
lastAttributes.screenInteraction.customTapActions.forEach { $0() }
}
}
}
// MARK: - EntryScrollViewDelegate
extension EKRootViewController: EntryContentViewDelegate {
func didFinishDisplaying(entry: EKEntryView, keepWindowActive: Bool) {
guard !isDisplaying else {
return
}
guard !keepWindowActive else {
return
}
delegate.displayPendingEntryIfNeeded()
}
func changeToInactive(withAttributes attributes: EKAttributes, pushOut: Bool) {
guard displayingEntryCount <= 1 else {
return
}
let clear = {
self.changeBackground(to: .clear, duration: attributes.exitAnimation.totalDuration)
}
guard pushOut else {
clear()
return
}
guard let lastBackroundStyle = lastAttributes?.screenBackground else {
clear()
return
}
if lastBackroundStyle != attributes.screenBackground {
clear()
}
}
func changeToActive(withAttributes attributes: EKAttributes) {
changeBackground(to: attributes.screenBackground, duration: attributes.entranceAnimation.totalDuration)
}
private func changeBackground(to style: EKAttributes.BackgroundStyle, duration: TimeInterval) {
DispatchQueue.main.async {
UIView.animate(withDuration: duration, delay: 0, options: [], animations: {
self.backgroundView.background = style
}, completion: nil)
}
}
}
| 29.781955 | 111 | 0.633931 |
7241d59a29e8b4716dca5950f85e43277e59ac64 | 6,993 | // The MIT License (MIT)
//
// Copyright (c) 2020–2021 Alexander Grebenyuk (github.com/kean).
import SwiftUI
@available(iOS 13.0, tvOS 14.0, watchOS 6, *)
struct KeyValueSectionView: View {
let model: KeyValueSectionViewModel
var limit: Int = Int.max
private var actualTintColor: Color {
model.items.isEmpty ? .gray : model.color
}
var body: some View {
VStack(alignment: .leading) {
HStack {
Text(model.title)
.font(.headline)
Spacer()
#if os(iOS)
if let action = model.action {
Button(action: action.action, label: {
Text(action.title)
Image(systemName: "chevron.right")
.foregroundColor(Color.gray)
.font(.caption)
.padding(.top, 2)
})
.padding(EdgeInsets(top: 7, leading: 11, bottom: 7, trailing: 11))
.background(Color.secondaryFill)
.cornerRadius(20)
}
#endif
}
#if os(watchOS)
KeyValueListView(model: model, limit: limit)
.padding(.top, 6)
.border(width: 2, edges: [.top], color: actualTintColor)
.padding(.top, 2)
if let action = model.action {
Spacer().frame(height: 10)
Button(action: action.action, label: {
Text(action.title)
Image(systemName: "chevron.right")
.foregroundColor(.separator)
.font(.caption)
})
}
#else
KeyValueListView(model: model, limit: limit)
.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
.border(width: 2, edges: [.leading], color: actualTintColor)
.padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 0))
#endif
}
}
}
@available(iOS 13.0, tvOS 14.0, watchOS 6, *)
private struct KeyValueListView: View {
let model: KeyValueSectionViewModel
var limit: Int = Int.max
private var actualTintColor: Color {
model.items.isEmpty ? .gray : model.color
}
var items: [(String, String?)] {
var items = Array(model.items.prefix(limit))
if model.items.count > limit {
items.append(("And \(model.items.count - limit) more", "..."))
}
return items
}
#if os(macOS)
var body: some View {
if model.items.isEmpty {
HStack {
Text("Empty")
.foregroundColor(actualTintColor)
.font(.system(size: fontSize, weight: .medium))
}
} else {
Label(text: text)
.padding(.bottom, 5)
}
}
private var text: NSAttributedString {
let text = NSMutableAttributedString()
for (index, row) in items.enumerated() {
text.append(makeRow(row))
if index != items.indices.last {
text.append("\n")
}
}
return text
}
private func makeRow(_ row: (String, String?)) -> NSAttributedString {
let text = NSMutableAttributedString()
text.append(row.0 + ": ", [
.font: NSFont.systemFont(ofSize: fontSize, weight: .medium),
.foregroundColor: NSColor(actualTintColor),
.paragraphStyle: ps
])
text.append(row.1 ?? "–", [
.font: NSFont.systemFont(ofSize: fontSize),
.foregroundColor: NSColor(Color.primary),
.paragraphStyle: ps
])
return text
}
#else
var body: some View {
if model.items.isEmpty {
HStack {
Text("Empty")
.foregroundColor(actualTintColor)
.font(.system(size: fontSize, weight: .medium))
}
} else {
VStack(spacing: 2) {
let rows = items.enumerated().map(Row.init)
ForEach(rows, id: \.index, content: makeRow)
}
}
}
private func makeRow(_ row: Row) -> some View {
HStack {
let title = Text(row.item.0 + ": ")
.foregroundColor(actualTintColor)
.font(.system(size: fontSize, weight: .medium))
let value = Text(row.item.1 ?? "–")
.foregroundColor(.primary)
.font(.system(size: fontSize, weight: .regular))
#if os(watchOS)
VStack(alignment: .leading) {
title
value
.lineLimit(2)
}
#elseif os(tvOS)
(title + value)
.lineLimit(nil)
#else
(title + value)
.lineLimit(4)
.contextMenu(ContextMenu(menuItems: {
Button(action: {
UXPasteboard.general.string = "\(row.item.0): \(row.item.1 ?? "–")"
runHapticFeedback()
}) {
Text("Copy")
Image(systemName: "doc.on.doc")
}
Button(action: {
UXPasteboard.general.string = row.item.1
runHapticFeedback()
}) {
Text("Copy Value")
Image(systemName: "doc.on.doc")
}
}))
#endif
Spacer()
}
}
#endif
}
#if os(macOS)
private struct Label: NSViewRepresentable {
let text: NSAttributedString
func makeNSView(context: Context) -> NSTextField {
let label = NSTextField.label()
label.isSelectable = true
label.attributedStringValue = text
label.allowsEditingTextAttributes = true
label.lineBreakMode = .byCharWrapping
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}
func updateNSView(_ nsView: NSTextField, context: Context) {
}
}
private let ps: NSParagraphStyle = {
let ps = NSMutableParagraphStyle()
ps.minimumLineHeight = 20
ps.maximumLineHeight = 20
return ps
}()
#endif
private var fontSize: CGFloat {
#if os(iOS)
return 15
#elseif os(watchOS)
return 14
#elseif os(tvOS)
return 28
#else
return 12
#endif
}
@available(iOS 13.0, tvOS 14.0, watchOS 6, *)
struct KeyValueSectionViewModel {
let title: String
let color: Color
var action: ActionViewModel?
let items: [(String, String?)]
}
private struct Row {
let index: Int
let item: (String, String?)
}
struct ActionViewModel {
let action: () -> Void
let title: String
}
| 29.757447 | 91 | 0.497783 |
90cde41574d44da1bfb1d98564324f41d01b9ce8 | 565 | import Cocoa
import SampleMacAppViewModel
class ViewController: NSViewController {
let viewModel = ViewModel()
@IBOutlet var counterLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
counterLabel.stringValue = viewModel.counterText
viewModel.delegate = self
}
@IBAction func didTapIncrement(_: NSButton) {
viewModel.increment()
}
}
extension ViewController: ViewModelDelegate {
func viewModelDidChange(counterText: String) {
counterLabel.stringValue = counterText
}
}
| 21.730769 | 56 | 0.704425 |
50e8b17544884c7de1dff0209db6ec979491798c | 3,733 | //
// Source.swift
// Kingfisher
//
// Created by onevcat on 2018/11/17.
//
// Copyright (c) 2019 Wei Wang <[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
/// Represents an image setting source for Kingfisher methods.
///
/// A `Source` value indicates the way how the target image can be retrieved and cached.
///
/// - network: The target image should be got from network remotely. The associated `Resource`
/// value defines detail information like image URL and cache key.
/// - provider: The target image should be provided in a data format. Normally, it can be an image
/// from local storage or in any other encoding format (like Base64).
public enum Source {
/// Represents the source task identifier when setting an image to a view with extension methods.
/// 数据源的任务标识
public enum Identifier {
/// The underlying value type of source identifier.
/// 源标识符的基础值类型。
public typealias Value = UInt
static var current: Value = 0
static func next() -> Value {
current += 1
return current
}
}
// MARK: Member Cases
/// The target image should be got from network remotely. The associated `Resource`
/// value defines detail information like image URL and cache key.
/// 从网络远程获取目标图像。相关的“资源”值定义了详细信息,如图像URL和缓存键。
case network(Resource)
/// The target image should be provided in a data format. Normally, it can be an image
/// from local storage or in any other encoding format (like Base64).
/// 目标图像应以数据格式提供。通常,它可以是本地存储或任何其他编码格式(如Base64)的图像。
case provider(ImageDataProvider)
// MARK: Getting Properties
/// The cache key defined for this source value.
public var cacheKey: String {
switch self {
case .network(let resource): return resource.cacheKey
case .provider(let provider): return provider.cacheKey
}
}
/// The URL defined for this source value.
///
/// For a `.network` source, it is the `downloadURL` of associated `Resource` instance.
/// For a `.provider` value, it is always `nil`.
public var url: URL? {
switch self {
case .network(let resource): return resource.downloadURL
case .provider(let provider): return provider.contentURL
}
}
}
extension Source {
var asResource: Resource? {
guard case .network(let resource) = self else {
return nil
}
return resource
}
var asProvider: ImageDataProvider? {
guard case .provider(let provider) = self else {
return nil
}
return provider
}
}
| 36.598039 | 101 | 0.676668 |
e6cf98b879aa78e2fce845188517e60dde12e71c | 12,419 | //
// AccountSelectViewController.swift
// Cosmostation
//
// Created by yongjoo on 21/10/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
class AccountSelectViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
var resultDelegate: AccountSelectDelegate?
@IBOutlet weak var chainTableView: UITableView!
@IBOutlet weak var accountTableView: UITableView!
var mAccounts = Array<Account>()
var mSelectedChain = 0;
override func viewDidLoad() {
super.viewDidLoad()
account = BaseData.instance.selectAccountById(id: BaseData.instance.getRecentAccountId())
mSelectedChain = BaseData.instance.getRecentChain()
self.accountTableView.delegate = self
self.accountTableView.dataSource = self
self.accountTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
self.accountTableView.register(UINib(nibName: "AccountPopupCell", bundle: nil), forCellReuseIdentifier: "AccountPopupCell")
self.accountTableView.register(UINib(nibName: "ManageAccountAddCell", bundle: nil), forCellReuseIdentifier: "ManageAccountAddCell")
self.chainTableView.delegate = self
self.chainTableView.dataSource = self
self.chainTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
self.chainTableView.register(UINib(nibName: "ManageChainCell", bundle: nil), forCellReuseIdentifier: "ManageChainCell")
self.chainTableView.selectRow(at: IndexPath.init(item: mSelectedChain, section: 0), animated: false, scrollPosition: .top)
onRefechUserInfo()
let dismissTap1 = UITapGestureRecognizer(target: self, action: #selector(tableTapped))
let dismissTap2 = UITapGestureRecognizer(target: self, action: #selector(tableTapped))
self.accountTableView.backgroundView = UIView()
self.chainTableView.backgroundView = UIView()
self.accountTableView.backgroundView?.addGestureRecognizer(dismissTap1)
self.chainTableView.backgroundView?.addGestureRecognizer(dismissTap2)
}
@objc public func tableTapped() {
// self.dismiss(animated: false, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func OnClose(_ sender: UIButton) {
self.dismiss(animated: false, completion: nil)
}
func onRefechUserInfo() {
if (mSelectedChain == 0) {
self.mAccounts = BaseData.instance.selectAllAccounts()
} else {
let selectedChain = ChainType.SUPPRT_CHAIN()[mSelectedChain - 1]
self.mAccounts = BaseData.instance.selectAllAccountsByChain(selectedChain)
}
self.mAccounts.sort{
return $0.account_sort_order < $1.account_sort_order
}
self.accountTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView == chainTableView) {
return ChainType.SUPPRT_CHAIN().count + 1
} else {
if (mSelectedChain == 0) {
return mAccounts.count
} else {
if (mAccounts.count < 5) {
return mAccounts.count + 1
} else {
return mAccounts.count
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == chainTableView) {
let cell:ManageChainCell? = tableView.dequeueReusableCell(withIdentifier:"ManageChainCell") as? ManageChainCell
if (indexPath.row == 0) {
cell?.chainImg.isHidden = true
cell?.chainName.isHidden = true
cell?.chainAll.isHidden = false
} else {
let selectedChain = ChainType.SUPPRT_CHAIN()[indexPath.row - 1]
if (selectedChain == ChainType.COSMOS_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "cosmosWhMain")
cell?.chainName.text = "COSMOS"
} else if (selectedChain == ChainType.IRIS_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "irisWh")
cell?.chainName.text = "IRIS"
} else if (selectedChain == ChainType.BINANCE_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "binanceChImg")
cell?.chainName.text = "BINANCE"
} else if (selectedChain == ChainType.KAVA_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "kavaImg")
cell?.chainName.text = "KAVA"
} else if (selectedChain == ChainType.IOV_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "iovChainImg")
cell?.chainName.text = "STARNAME"
} else if (selectedChain == ChainType.BAND_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "bandChainImg")
cell?.chainName.text = "BAND"
} else if (selectedChain == ChainType.SECRET_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "secretChainImg")
cell?.chainName.text = "SECRET"
} else if (selectedChain == ChainType.CERTIK_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "certikChainImg")
cell?.chainName.text = "CERTIK"
} else if (selectedChain == ChainType.AKASH_MAIN) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "akashChainImg")
cell?.chainName.text = "AKASH"
}
else if (selectedChain == ChainType.COSMOS_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "cosmosTestChainImg")
cell?.chainName.text = "STARGATE"
} else if (selectedChain == ChainType.BINANCE_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "binancetestnet")
cell?.chainName.text = "BINANCE TEST"
} else if (selectedChain == ChainType.KAVA_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "kavaTestImg")
cell?.chainName.text = "KAVA TEST"
} else if (selectedChain == ChainType.IOV_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "iovTestnetImg")
cell?.chainName.text = "STARNAME TEST"
} else if (selectedChain == ChainType.OKEX_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "okexTestnetImg")
cell?.chainName.text = "OKEX TEST"
} else if (selectedChain == ChainType.CERTIK_TEST) {
cell?.chainImg.isHidden = false
cell?.chainName.isHidden = false
cell?.chainAll.isHidden = true
cell?.chainImg.image = UIImage(named: "certikTestnetImg")
cell?.chainName.text = "CERTIK TEST"
}
}
return cell!
} else {
if (mAccounts.count <= indexPath.row) {
let cell:ManageAccountAddCell? = tableView.dequeueReusableCell(withIdentifier:"ManageAccountAddCell") as? ManageAccountAddCell
return cell!
}
let account = mAccounts[indexPath.row]
let cell:AccountPopupCell? = tableView.dequeueReusableCell(withIdentifier:"AccountPopupCell") as? AccountPopupCell
let userChain = WUtils.getChainType(account.account_base_chain)
if (account.account_has_private) {
cell?.keyImg.image = cell?.keyImg.image!.withRenderingMode(.alwaysTemplate)
cell?.keyImg.tintColor = WUtils.getChainColor(userChain)
} else {
cell?.keyImg.tintColor = COLOR_DARK_GRAY
}
if (account.account_nick_name == "") {
cell?.nameLabel.text = NSLocalizedString("wallet_dash", comment: "") + String(account.account_id)
} else {
cell?.nameLabel.text = account.account_nick_name
}
cell?.address.text = account.account_address
cell?.amount.attributedText = WUtils.displayAmount2(account.account_last_total, cell!.amount.font, 0, 6)
WUtils.setDenomTitle(userChain, cell!.amountDenom)
cell?.cardView.borderColor = UIColor.init(hexString: "#9ca2ac")
if (self.account?.account_id == account.account_id) {
cell?.cardView.borderWidth = 1.0
} else {
cell?.cardView.borderWidth = 0.0
}
return cell!
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (tableView == chainTableView) {
if (mSelectedChain != indexPath.row) {
mSelectedChain = indexPath.row
BaseData.instance.setRecentChain(mSelectedChain)
self.onRefechUserInfo()
}
} else if (mAccounts.count <= indexPath.row) {
let toAddChain:ChainType = ChainType.SUPPRT_CHAIN()[mSelectedChain - 1]
self.resultDelegate?.addAccount(toAddChain)
self.dismiss(animated: false, completion: nil)
} else {
self.resultDelegate?.accountSelected(Int(mAccounts[indexPath.row].account_id))
self.dismiss(animated: false, completion: nil)
}
}
}
protocol AccountSelectDelegate{
func accountSelected (_ id:Int)
func addAccount(_ chain:ChainType)
}
| 44.512545 | 142 | 0.559063 |
3aec34dab266f6d42b345caf00218508e3620668 | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class S<T{func a<h{func b<T where h.g=a{a{let f{{{{{a{{{{{b{}{{{let a
| 46.2 | 78 | 0.720779 |
2ff2448df566cc5aff0362c5bf88260136626f06 | 14,332 | //
// WebServiceGroupProvider.swift
// WebServiceSwift 3.0.0
//
// Created by Короткий Виталий (ViR) on 22.06.2018.
// Copyright © 2018 ProVir. All rights reserved.
//
import Foundation
/// Provider for group requests
@available(*, deprecated, message: "Can be removed in next versions")
public class WebServiceGroupProvider<GroupType: WebServiceGroupRequests>: WebServiceRestrictedProvider, WebServiceProvider {
public required init(webService: WebService) {
super.init(webService: webService, requestTypes: GroupType.requestTypes)
}
}
/// Equal WebService functional, but support only concrete request types (assert if don't support)
@available(*, deprecated, message: "Can be removed in next versions")
public class WebServiceRestrictedProvider {
private let service: WebService
private let requestTypes: [WebServiceBaseRequesting.Type]
private let requestTypesAsKeys: Set<String>
/// Constructor with filter request types.
public init(webService: WebService, requestTypes: [WebServiceBaseRequesting.Type]) {
self.service = webService
self.requestTypes = requestTypes
self.requestTypesAsKeys = Set(requestTypes.map { "\($0)" })
}
/// Response delegate for responses. Apply before call new request.
public weak var delegate: WebServiceDelegate?
/// When `true` - response result from storage send to delegate only if have data.
public var responseStorageOnlyDataForDelegate: Bool = false
/// MARK: Test request for support
public func canUseRequest(type requestType: WebServiceBaseRequesting.Type) -> Bool {
return requestTypesAsKeys.contains("\(requestType)")
}
func testRequest(type requestType: WebServiceBaseRequesting.Type, file: StaticString = #file, line: UInt = #line) -> Bool {
if canUseRequest(type: requestType) { return true }
assertionFailure("Request type don't support in this provider", file: file, line: line)
return false
}
// MARK: Perform requests
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The request with data and result type.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting>(_ request: RequestType, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
guard testRequest(type: RequestType.self) else {
completionHandler(.canceledRequest(duplicate: false))
return
}
service.performRequest(request, completionHandler: completionHandler)
}
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The request with data and result type.
- key: unique key for controling requests - contains and canceled. Also use for excludeDuplicate.
- excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting>(_ request: RequestType, key: AnyHashable, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
guard testRequest(type: RequestType.self) else {
completionHandler(.canceledRequest(duplicate: false))
return
}
service.performRequest(request, key: key, excludeDuplicate: excludeDuplicate, completionHandler: completionHandler)
}
/**
Request to server (endpoint). Response result in closure.
- Parameters:
- request: The hashable (also equatable) request with data and result type.
- excludeDuplicate: Exclude duplicate equatable requests.
- completionHandler: Closure for response result from server.
*/
public func performRequest<RequestType: WebServiceRequesting & Hashable>(_ request: RequestType, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
guard testRequest(type: RequestType.self) else {
completionHandler(.canceledRequest(duplicate: false))
return
}
service.performRequest(request, excludeDuplicate: excludeDuplicate, completionHandler: completionHandler)
}
/**
Read last success data from storage. Response result in closure.
- Parameters:
- request: The request with data.
- dependencyNextRequest: Type dependency from next performRequest.
- completionHandler: Closure for read data from storage.
- timeStamp: TimeStamp when saved from server (endpoint).
- response: Result read from storage.
*/
public func readStorage<RequestType: WebServiceRequesting>(_ request: RequestType, dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceResponse<RequestType.ResultType>) -> Void) {
guard testRequest(type: RequestType.self) else {
completionHandler(nil, .canceledRequest(duplicate: false))
return
}
service.readStorage(request, dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandler)
}
/**
Read last success data from storage without information result type data. Response result in closure.
- Parameters:
- request: The request with data.
- dependencyNextRequest: Type dependency from next performRequest.
- completionHandler: Closure for read data from storage.
- timeStamp: TimeStamp when saved from server (endpoint).
- response: Result read from storage.
*/
public func readStorageAnyData(_ request: WebServiceBaseRequesting,
dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend,
completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceAnyResponse) -> Void) {
guard testRequest(type: type(of: request)) else {
completionHandler(nil, .canceledRequest(duplicate: false))
return
}
service.readStorageAnyData(request, dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandler)
}
// MARK: Perform requests use delegate for response
/**
Request to server (endpoint). Response result send to delegate.
- Parameter request: The request with data.
*/
public func performRequest(_ request: WebServiceBaseRequesting) {
guard testRequest(type: type(of: request)) else {
delegate?.webServiceResponse(request: request, key: nil, isStorageRequest: false, response: .canceledRequest(duplicate: false))
return
}
service.performRequest(request, responseDelegate: delegate)
}
/**
Request to server (endpoint). Response result send to delegate.
- Parameters:
- request: The request with data.
- key: unique key for controling requests - contains and canceled. Also use for excludeDuplicate.
- excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match.
*/
public func performRequest(_ request: WebServiceBaseRequesting, key: AnyHashable, excludeDuplicate: Bool) {
guard testRequest(type: type(of: request)) else {
delegate?.webServiceResponse(request: request, key: key, isStorageRequest: false, response: .canceledRequest(duplicate: false))
return
}
service.performRequest(request, key: key, excludeDuplicate: excludeDuplicate, responseDelegate: delegate)
}
/**
Request to server (endpoint). Response result send to delegate.
- Parameters:
- request: The hashable (also equatable) request with data.
- excludeDuplicate: Exclude duplicate equatable requests.
*/
public func performRequest<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType, excludeDuplicate: Bool) {
guard testRequest(type: RequestType.self) else {
delegate?.webServiceResponse(request: request, key: nil, isStorageRequest: false, response: .canceledRequest(duplicate: false))
return
}
service.performRequest(request, excludeDuplicate: excludeDuplicate, responseDelegate: delegate)
}
/**
Read last success data from storage. Response result send to delegate.
- Parameters:
- request: The request with data.
- key: unique key for controling requests, use only for response delegate.
- dependencyNextRequest: Type dependency from next performRequest.
- responseOnlyData: When `true` - response result send to delegate only if have data. Default use `responseStorageOnlyDataForDelegate`.
*/
public func readStorage(_ request: WebServiceBaseRequesting, key: AnyHashable? = nil, dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, responseOnlyData: Bool? = nil) {
guard testRequest(type: type(of: request)) else {
if !(responseOnlyData ?? responseStorageOnlyDataForDelegate) {
delegate?.webServiceResponse(request: request, key: key, isStorageRequest: true, response: .canceledRequest(duplicate: false))
}
return
}
if let delegate = delegate {
service.readStorage(request, key: key,
dependencyNextRequest: dependencyNextRequest,
responseOnlyData: responseOnlyData ?? responseStorageOnlyDataForDelegate,
responseDelegate: delegate)
}
}
// MARK: Contains requests
/**
Returns a Boolean value indicating whether the current queue contains support requests.
- Returns: `true` if one request from requestTypes was found in the current queue; otherwise, `false`.
*/
public func containsSupportRequests() -> Bool {
for requestType in requestTypes {
if service.containsRequest(type: requestType) { return true }
}
return false
}
/**
Returns a Boolean value indicating whether the current queue contains the given request.
- Parameter request: The request to find in the current queue.
- Returns: `true` if the request was found in the current queue; otherwise, `false`.
*/
public func containsRequest<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType) -> Bool {
guard testRequest(type: RequestType.self) else { return false }
return service.containsRequest(request)
}
/**
Returns a Boolean value indicating whether the current queue contains requests the given type.
- Parameter requestType: The type request to find in the all current queue.
- Returns: `true` if one request with WebServiceBaseRequesting.Type was found in the current queue; otherwise, `false`.
*/
public func containsRequest(type requestType: WebServiceBaseRequesting.Type) -> Bool {
guard testRequest(type: requestType) else { return false }
return service.containsRequest(type: requestType)
}
/**
Returns a Boolean value indicating whether the current queue contains the given request with key.
- Parameter key: The key to find requests in the current queue.
- Returns: `true` if the request with key was found in the current queue; otherwise, `false`.
*/
public func containsRequest(key: AnyHashable) -> Bool {
return service.containsRequest(key: key)
}
/**
Returns a Boolean value indicating whether the current queue contains requests the given type key.
- Parameter keyType: The type requestKey to find in the all current queue.
- Returns: `true` if one request with key.Type was found in the current queue; otherwise, `false`.
*/
public func containsRequest<T: Hashable>(keyType: T.Type) -> Bool {
return service.containsRequest(keyType: keyType)
}
//MARK: Cancel requests
/// Cancel all support requests from requestTypes.
public func cancelAllSupportRequests() {
for requestType in requestTypes {
service.cancelRequests(type: requestType)
}
}
/**
Cancel all requests with equal this request.
- Parameter request: The request to find in the current queue.
*/
public func cancelRequests<RequestType: WebServiceBaseRequesting & Hashable>(_ request: RequestType) {
guard testRequest(type: RequestType.self) else { return }
service.cancelRequests(request)
}
/**
Cancel all requests for request type.
- Parameter requestType: The WebServiceBaseRequesting.Type to find in the current queue.
*/
public func cancelRequests(type requestType: WebServiceBaseRequesting.Type) {
guard testRequest(type: requestType) else { return }
service.cancelRequests(type: requestType)
}
/**
Cancel all requests with key.
- Parameter key: The key to find in the current queue.
*/
public func cancelRequests(key: AnyHashable) {
service.cancelRequests(key: key)
}
/**
Cancel all requests with key.Type.
- Parameter keyType: The key.Type to find in the current queue.
*/
public func cancelRequests<K: Hashable>(keyType: K.Type) {
service.cancelRequests(keyType: keyType)
}
//MARK: Delete data in Storages
/**
Delete data in storage for concrete request.
- Parameter request: Original request.
*/
public func deleteInStorage<RequestType: WebServiceBaseRequesting>(request: RequestType) {
guard testRequest(type: RequestType.self) else { return }
service.deleteInStorage(request: request)
}
}
| 42.277286 | 277 | 0.675412 |
bfd5208c172b7cc480cb57d73aebfc996f146e84 | 1,079 | import Vapor
/*
This is Vapor's HTTP routing.
We use it for WebSockets, and the local HTTP interface.
*/
extension Droplet {
func setupRoutes() throws {
//Set up routes
get("peers") { req in
return "\(state.blockChain.depth)"
}
post("addPeer") { req in
return "Send a new peer here so I can add it!"
}
//Set up webSockets
//Special WebSocket for a miner connection
socket("miner") { message, webSocket in
webSocket.onText = { ws, text in
print("Miner msg: " + text)
let json = try JSON(bytes: Array(text.utf8))
state.minerProtocol.received(json: json)
}
}
//Socket for light clients
socket("light") { message, webSocket in
webSocket.onText = { ws, text in
}
}
socket("p2p") { message, webSocket in
webSocket.onText = { ws, text in
print("Received message: " + text)
let json = try JSON(bytes: Array(text.utf8))
let response = state.p2pProtocol.received(json: json)
do {
try ws.send(response.makeBytes())
} catch {
print("Failed to send reply")
}
}
}
}
}
| 21.58 | 57 | 0.626506 |
ef136a74f714d523d4639e88b6db27ad319bb870 | 379 | //
// GetPersonsUseCase.swift
// PersonsFeature
//
// Created by Joachim Kret on 04/07/2019.
// Copyright © 2019 Joachim Kret. All rights reserved.
//
import Foundation
import Shared
import AppCore
struct GetPersonsUseCase {
let gateway: GetPersonsGateway
func prepare() -> Future<[Person], ApplicationError> {
return gateway.getPersons()
}
}
| 18.047619 | 58 | 0.686016 |
5d9f21b2e9a4a4422bb455e1389e7de0e29d9b9d | 553 | //
// NetworkRequestUtilsMock.swift
// Choco-ExampleTests
//
// Created by Roxana Bucura on 25.02.20.
// Copyright © 2020 RB. All rights reserved.
//
import Foundation
@testable import Pocket_Explorer
class NetworkRequestUtilsMock: NetworkRequestUtils {
override func makeRequestObjectFor(url: URL, httpMethod: HTTPMethod) -> URLRequest? {
return nil
}
override func makeRequestObjectWithRequestBodyFor<T>(url: URL, httpMethod: HTTPMethod, requestObject: T) -> URLRequest? where T : Encodable {
return nil
}
}
| 26.333333 | 145 | 0.717902 |
bfc6814291314c2de5aaf5e9d57250ef5bac282e | 690 |
//
// StartTestPage.swift
// reiner_ccid_via_dk_sample
//
// Created by Prakti_E on 02.06.15.
// Copyright (c) 2015 Reiner SCT. All rights reserved.
//
import Foundation
import UIKit
class StartTestPage: UIViewController, BluetoothTestProtocol {
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.
}
func openDeviceSelection(){}
func startWithSelectedReader(){}
func startWithClosestReader(){}
} | 22.258065 | 80 | 0.671014 |
ac2712f645672ccb5092d94d4567f1ec3dbc6454 | 7,060 | import ArgumentParser
import BeeDataset
import BeeTracking
import PenguinParallelWithFoundation
import PenguinStructures
import PythonKit
import SwiftFusion
import TensorFlow
struct BeeTrackingTool: ParsableCommand {
static var configuration = CommandConfiguration(
subcommands: [TrainRAE.self, InferTrackRAE.self, InferTrackRawPixels.self])
}
/// The dimension of the hidden layer in the appearance model.
let kHiddenDimension = 500
/// The dimension of the latent code in the appearance model.
let kLatentDimension = 10
/// Returns a `[N, h, w, c]` batch of normalized patches from a VOT video, and returns the
/// statistics used to normalize them.
func makeVOTBatch(votBaseDirectory: String, videoName: String, appearanceModelSize: (Int, Int))
-> (normalized: Tensor<Double>, statistics: FrameStatistics)
{
let data = VOTVideo(votBaseDirectory: votBaseDirectory, videoName: videoName)!
let images = (0..<data.frames.count).map { (i: Int) -> Tensor<Double> in
return Tensor<Double>(data.frames[i].patch(at: data.track[i], outputSize: appearanceModelSize))
}
let stacked = Tensor(stacking: images)
let statistics = FrameStatistics(stacked)
return (statistics.normalized(stacked), statistics)
}
/// Trains a RAE on the VOT dataset.
struct TrainRAE: ParsableCommand {
@Option(help: "Load weights from this file before training")
var loadWeights: String?
@Option(help: "Save weights to this file after training")
var saveWeights: String
@Option(help: "Number of epochs to train")
var epochCount: Int = 20
@Option(help: "Base directory of the VOT dataset")
var votBaseDirectory: String
@Option(help: "Name of the VOT video to use")
var videoName: String
@Option(help: "Number of rows in the appearance model output")
var appearanceModelRows: Int = 100
@Option(help: "Number of columns in the appearance model output")
var appearanceModelCols: Int = 100
func run() {
let np = Python.import("numpy")
let (batch, _) = makeVOTBatch(
votBaseDirectory: votBaseDirectory, videoName: videoName, appearanceModelSize: (appearanceModelRows, appearanceModelCols))
print("Batch shape: \(batch.shape)")
let (imageHeight, imageWidth, imageChannels) =
(batch.shape[1], batch.shape[2], batch.shape[3])
var model = DenseRAE(
imageHeight: imageHeight, imageWidth: imageWidth, imageChannels: imageChannels,
hiddenDimension: kHiddenDimension, latentDimension: kLatentDimension)
if let loadWeights = loadWeights {
let weights = np.load(loadWeights, allow_pickle: true)
model.load(weights: weights)
}
let loss = DenseRAELoss()
_ = loss(model, batch, printLoss: true)
// Use ADAM as optimizer
let optimizer = Adam(for: model)
optimizer.learningRate = 1e-3
// Thread-local variable that model layers read to know their mode
Context.local.learningPhase = .training
for i in 0..<epochCount {
print("Step \(i), loss: \(loss(model, batch))")
let grad = gradient(at: model) { loss($0, batch) }
optimizer.update(&model, along: grad)
}
_ = loss(model, batch, printLoss: true)
np.save(saveWeights, np.array(model.numpyWeights, dtype: Python.object))
}
}
/// Infers a track on a VOT video, using the RAE tracker.
struct InferTrackRAE: ParsableCommand {
@Option(help: "Load weights from this file")
var loadWeights: String
@Option(help: "Base directory of the VOT dataset")
var votBaseDirectory: String
@Option(help: "Name of the VOT video to use")
var videoName: String
@Option(help: "Number of rows in the appearance model output")
var appearanceModelRows: Int = 100
@Option(help: "Number of columns in the appearance model output")
var appearanceModelCols: Int = 100
@Option(help: "How many frames to track")
var frameCount: Int = 50
@Flag(help: "Print progress information")
var verbose: Bool = false
func run() {
let np = Python.import("numpy")
let appearanceModelSize = (appearanceModelRows, appearanceModelCols)
let video = VOTVideo(votBaseDirectory: votBaseDirectory, videoName: videoName)!
let (_, frameStatistics) = makeVOTBatch(
votBaseDirectory: votBaseDirectory, videoName: videoName,
appearanceModelSize: appearanceModelSize)
var model = DenseRAE(
imageHeight: appearanceModelRows, imageWidth: appearanceModelCols,
imageChannels: video.frames[0].shape[2],
hiddenDimension: kHiddenDimension, latentDimension: kLatentDimension)
model.load(weights: np.load(loadWeights, allow_pickle: true))
let videoSlice = video[0..<min(video.frames.count, frameCount)]
var tracker = makeRAETracker(
model: model,
statistics: frameStatistics,
frames: videoSlice.frames,
targetSize: (video.track[0].rows, video.track[0].cols))
if verbose { tracker.optimizer.verbosity = .SUMMARY }
let startPose = videoSlice.track[0].center
let startPatch = Tensor<Double>(videoSlice.frames[0].patch(
at: videoSlice.track[0], outputSize: appearanceModelSize))
let startLatent = Vector10(
flatTensor: model.encode(
frameStatistics.normalized(startPatch).expandingShape(at: 0)).squeezingShape(at: 0))
let prediction = tracker.infer(knownStart: Tuple2(startPose, startLatent))
let boxes = tracker.frameVariableIDs.map { frameVariableIDs -> OrientedBoundingBox in
let poseID = frameVariableIDs.head
return OrientedBoundingBox(
center: prediction[poseID], rows: video.track[0].rows, cols: video.track[0].cols)
}
print(boxes.count)
}
}
/// Infers a track on a VOT video, using the raw pixel tracker.
struct InferTrackRawPixels: ParsableCommand {
@Option(help: "Base directory of the VOT dataset")
var votBaseDirectory: String
@Option(help: "Name of the VOT video to use")
var videoName: String
@Option(help: "How many frames to track")
var frameCount: Int = 50
@Flag(help: "Print progress information")
var verbose: Bool = false
func run() {
let video = VOTVideo(votBaseDirectory: votBaseDirectory, videoName: videoName)!
let videoSlice = video[0..<min(video.frames.count, frameCount)]
let startPose = videoSlice.track[0].center
let startPatch = videoSlice.frames[0].patch(at: videoSlice.track[0])
var tracker = makeRawPixelTracker(frames: videoSlice.frames, target: startPatch)
if verbose { tracker.optimizer.verbosity = .SUMMARY }
let prediction = tracker.infer(knownStart: Tuple1(startPose))
let boxes = tracker.frameVariableIDs.map { frameVariableIDs -> OrientedBoundingBox in
let poseID = frameVariableIDs.head
return OrientedBoundingBox(
center: prediction[poseID], rows: video.track[0].rows, cols: video.track[0].cols)
}
print(boxes.count)
}
}
// It is important to set the global threadpool before doing anything else, so that nothing
// accidentally uses the default threadpool.
ComputeThreadPools.global =
NonBlockingThreadPool<PosixConcurrencyPlatform>(name: "mypool", threadCount: 12)
BeeTrackingTool.main()
| 33.942308 | 128 | 0.724221 |
21961beaf7d5048b1522f73aa2070bab433b9137 | 844 | import FluentPostgreSQL
struct CreateSelectedUnitPsychicPower: PostgreSQLMigration {
static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
return PostgreSQLDatabase.create(SelectedUnitPsychicPower.self, on: conn) { (builder) in
builder.field(for: \.id, isIdentifier: true)
builder.field(for: \.unitId)
builder.field(for: \.psychicPowerId)
builder.reference(from: \.unitId, to: \SelectedUnit.id, onDelete: .cascade)
builder.reference(from: \.psychicPowerId, to: \PsychicPower.id, onDelete: .cascade)
builder.unique(on: \.unitId, \.psychicPowerId)
}
}
static func revert(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
return PostgreSQLDatabase.delete(SelectedUnitPsychicPower.self, on: conn)
}
}
| 42.2 | 96 | 0.683649 |
3a08ff159baf5052464438188ffedbfd03244aac | 753 | import XCTest
import FUSegmentControl
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.965517 | 111 | 0.60425 |
edf04d698dc39502a9c779a2d78b300c0023cc4c | 9,356 | //
// QXSetting.swift
// Project
//
// Created by labi3285 on 2019/12/16.
// Copyright © 2019 labi3285_lab. All rights reserved.
//
import QXUIKitExtension
/**
* 样例
*
let gobal_key_test1 = QXDebugSwitch.Key("调试开关1", "test1")
let gobal_key_test2 = QXDebugSwitch.Key("调试开关2", "test2")
let key_api1 = QXDebugSetting.Key("api地址1", "api1")
let key_api2 = QXDebugSetting.Key("api地址2", "api2")
let key_api3 = QXDebugSetting.Key("api地址3", "api3")
/// 在所有方法之前配置
func SetupApis() {
QXDebugTodo.todos.append(QXDebugTodo("测试", {
// todo
}))
QXDebugSwitch.switches = [
QXDebugSwitch(gobal_key_test1, true),
QXDebugSwitch(gobal_key_test2, true),
]
QXDebugSetting.settings = [
QXDebugSetting(.release, key_api1, "release_url1"),
QXDebugSetting(.release, key_api2, "release_url2"),
QXDebugSetting(.release, key_api3, "release_url3"),
QXDebugSetting(.test, key_api1, "test_url1"),
QXDebugSetting(.test, key_api2, "test_url2"),
QXDebugSetting(.test, key_api3, "test_url3"),
QXDebugSetting(.uat, key_api1, "uat_url1"),
QXDebugSetting(.uat, key_api2, "uat_url2"),
QXDebugSetting(.uat, key_api3, "uat_url3"),
QXDebugSetting(.other1(name: "自定义环境1"), key_api1, "other1_url1"),
QXDebugSetting(.other1(name: "自定义环境1"), key_api2, "other1_url2"),
QXDebugSetting(.other1(name: "自定义环境1"), key_api3, "other1_url3"),
QXDebugSetting(.custom, key_api1, "custom_url1"),
QXDebugSetting(.custom, key_api2, "custom_url2"),
QXDebugSetting(.custom, key_api3, "custom_url3"),
]
}
var baseApi1: String {
return QXDebugSetting.value(key_api1) as? String ?? ""
}
var baseApi2: String {
return QXDebugSetting.value(key_api2) as? String ?? ""
}
var baseApi3: String {
return QXDebugSetting.value(key_api3) as? String ?? ""
}
*/
public struct QXDebugSetting {
public static var isForceDebugMode: Bool = false
public static var envirment: QXDebugSetting.Environment {
func debugEnvirment() -> QXDebugSetting.Environment {
if let code = UserDefaults.standard.value(forKey: "kQXDebugEnvironmentCode") as? String {
switch code {
case "release":
return .release
case "custom":
return .custom
case "test":
return .test
case "uat":
return .uat
case "ut":
return .ut
case "it":
return .it
case "st":
return .st
default:
if code.hasPrefix("other1_") {
let name = code.replacingOccurrences(of: "other1_", with: "")
return .other1(name: name)
} else if code.hasPrefix("other2_") {
let name = code.replacingOccurrences(of: "other2_", with: "")
return .other2(name: name)
} else if code.hasPrefix("other3_") {
let name = code.replacingOccurrences(of: "other3_", with: "")
return .other3(name: name)
} else if code.hasPrefix("other4_") {
let name = code.replacingOccurrences(of: "other4_", with: "")
return .other4(name: name)
} else if code.hasPrefix("other5_") {
let name = code.replacingOccurrences(of: "other5_", with: "")
return .other5(name: name)
}
}
}
return QXDebugSetting.settings.first?.environment ?? QXDebugSetting.Environment.test
}
#if DEBUG
return debugEnvirment()
#else
if isForceDebugMode {
return debugEnvirment()
} else {
return QXDebugSetting.Environment.release
}
#endif
}
public static func value(_ key: QXDebugSetting.Key) -> Any? {
var envCode = QXDebugSetting.Environment.release.code
#if DEBUG
envCode = UserDefaults.standard.value(forKey: "kQXDebugEnvironmentCode") as? String ?? QXDebugSetting.settings.first?.environment.code ?? QXDebugSetting.Environment.test.code
#endif
if envCode == QXDebugSetting.Environment.custom.code {
if let data = UserDefaults.standard.value(forKey: "kQXDebugEnvironmentCustomData") as? Data {
if let dic = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if let e = dic[key.key] {
return e
}
}
}
}
for e in settings {
if e.environment.code == envCode {
if e.key.key == key.key {
return e.value
}
}
}
return nil
}
public static var settings: [QXDebugSetting] = []
public enum Environment {
/// 发布
case release
/// 自定义
case custom
/// 测试
case test
/// 验收
case uat
/// 单元测试
case ut
/// 集成测试
case it
/// 系统测试
case st
/// 其他1
case other1(name: String)
/// 其他2
case other2(name: String)
/// 其他3
case other3(name: String)
/// 其他4
case other4(name: String)
/// 其他5
case other5(name: String)
public static var settings: [QXDebugSetting] = []
public var name: String {
switch self {
case .release:
return "生产"
case .custom:
return "自定义"
case .test:
return "测试"
case .uat:
return "验收(UAT)"
case .ut:
return "单元测试(UT)"
case .it:
return "集成测试(IT)"
case .st:
return "系统测试(ST)"
case .other1(name: let n):
return n
case .other2(name: let n):
return n
case .other3(name: let n):
return n
case .other4(name: let n):
return n
case .other5(name: let n):
return n
}
}
public var code: String {
switch self {
case .release:
return "release"
case .custom:
return "custom"
case .test:
return "test"
case .uat:
return "uat"
case .ut:
return "ut"
case .it:
return "it"
case .st:
return "st"
case .other1(name: let name):
return "other1_" + name
case .other2(name: let name):
return "other2_" + name
case .other3(name: let name):
return "other3_" + name
case .other4(name: let name):
return "other4_" + name
case .other5(name: let name):
return "other5_" + name
}
}
}
public struct Key {
public let name: String
public let key: String
public init(_ name: String, _ key: String) {
self.name = name
self.key = key
}
}
public let environment: Environment
public let key: Key
public let value: Any
public init(_ environment: Environment, _ key: Key, _ value: Any) {
self.environment = environment
self.key = key
self.value = value
}
}
public class QXDebugSwitch {
public static var switches: [QXDebugSwitch] = []
public static func value(_ key: QXDebugSwitch.Key) -> Bool {
for e in switches {
if e.key.key == key.key {
return e.currentValue
}
}
return QXDebugFatalError("invalid key", false)
}
public struct Key {
public let name: String
public let key: String
public init(_ name: String, _ key: String) {
self.name = name
self.key = key
}
}
public let key: Key
public let value: Bool
public var currentValue: Bool {
#if DEBUG
if let e = _cache_value {
return e
}
let b = UserDefaults.standard.value(forKey: key.key) as? String ?? "NO" == "YES"
_cache_value = b
return b
#else
return value
#endif
}
private var _cache_value: Bool?
public func reset() {
_cache_value = nil
}
public init(_ key: Key, _ value: Bool) {
self.key = key
self.value = value
}
}
public struct QXDebugTodo {
public let name: String
public let todo: () -> Void
public init(_ name: String, _ todo: @escaping () -> Void) {
self.name = name
self.todo = todo
}
public static var todos: [QXDebugTodo] = []
}
| 29.055901 | 182 | 0.503206 |
206279e9a65860a54ce8dea7d84f5957210aa0cb | 2,666 | /*:
> # IMPORTANT: To use `Rx.playground`, please:
1. Open `Rx.xcworkspace`
2. Build `RxSwift-OSX` scheme
3. And then open `Rx` playground in `Rx.xcworkspace` tree view.
4. Choose `View > Show Debug Area`
*/
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
import Foundation
/*:
## Error Handling Operators
Operators that help to recover from error notifications from an Observable.
*/
/*:
### `catchError`
Recover from an `Error` notification by continuing the sequence without error
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/catch.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/catch.html )
*/
example("catchError 1") {
let sequenceThatFails = PublishSubject<Int>()
let recoverySequence = Observable.of(100, 200, 300, 400)
_ = sequenceThatFails
.catchError { error in
return recoverySequence
}
.subscribe {
print($0)
}
sequenceThatFails.on(.Next(1))
sequenceThatFails.on(.Next(2))
sequenceThatFails.on(.Next(3))
sequenceThatFails.on(.Next(4))
sequenceThatFails.on(.Error(NSError(domain: "Test", code: 0, userInfo: nil)))
}
example("catchError 2") {
let sequenceThatFails = PublishSubject<Int>()
_ = sequenceThatFails
.catchErrorJustReturn(100)
.subscribe {
print($0)
}
sequenceThatFails.on(.Next(1))
sequenceThatFails.on(.Next(2))
sequenceThatFails.on(.Next(3))
sequenceThatFails.on(.Next(4))
sequenceThatFails.on(.Error(NSError(domain: "Test", code: 0, userInfo: nil)))
}
/*:
### `retry`
If a source Observable emits an error, resubscribe to it in the hopes that it will complete without error
![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png)
[More info in reactive.io website]( http://reactivex.io/documentation/operators/retry.html )
*/
example("retry") {
var count = 1 // bad practice, only for example purposes
let funnyLookingSequence = Observable<Int>.create { observer in
let error = NSError(domain: "Test", code: 0, userInfo: nil)
observer.on(.Next(0))
observer.on(.Next(1))
observer.on(.Next(2))
if count < 2 {
observer.on(.Error(error))
count += 1
}
observer.on(.Next(3))
observer.on(.Next(4))
observer.on(.Next(5))
observer.on(.Completed)
return NopDisposable.instance
}
_ = funnyLookingSequence
.retry()
.subscribe {
print($0)
}
}
//: [Index](Index) - [Next >>](@next)
| 25.634615 | 105 | 0.644036 |
ffbf9a0f137064502f2320e538f41c6050f16f6e | 1,223 | //
// CheckboxPaths.swift
// bitlish
//
// Created by Margarita Shishkina on 29/05/2018.
// Copyright © 2018 Margarita Sergeevna. All rights reserved.
//
import UIKit
class PathsManager {
var size: CGSize
var lineWidth: CGFloat
var cornerRadius: CGFloat
init(size: CGSize, lineWidth: CGFloat, cornerRadius: CGFloat) {
self.size = size
self.lineWidth = lineWidth
self.cornerRadius = cornerRadius
}
func pathForRect() -> UIBezierPath {
let w = size.width
let h = size.height
let rect = CGRect(x: lineWidth/2, y: lineWidth/2, width: w - lineWidth, height: h - lineWidth)
let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
path.lineWidth = lineWidth
return path
}
func pathForCheck() -> UIBezierPath {
let w = size.width
let h = size.height
let point1 = CGPoint(x: w/4, y: h/2)
let point2 = CGPoint(x: w/2, y: (h/3)*2)
let point3 = CGPoint(x: (w/4)*3, y: h/3)
let path = UIBezierPath()
path.move(to: point1)
path.addLine(to: point2)
path.addLine(to: point3)
path.lineWidth = lineWidth
return path
}
}
| 26.586957 | 102 | 0.605887 |
56407516f3e3c38869a54f582f8c7256bba82c5d | 8,328 | import Foundation
public struct AccessChallengeAttempts: Equatable {
public let count: Int32
public var bootTimestamp: Int32
public var uptime: Int32
public init(count: Int32, bootTimestamp: Int32, uptime: Int32) {
self.count = count
self.bootTimestamp = bootTimestamp
self.uptime = uptime
}
}
public enum PostboxAccessChallengeData: PostboxCoding, Equatable, Codable {
enum CodingKeys: String, CodingKey {
case numericalPassword
case plaintextPassword
}
case none
case numericalPassword(value: String)
case plaintextPassword(value: String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("r", orElse: 0) {
case 0:
self = .none
case 1:
self = .numericalPassword(value: decoder.decodeStringForKey("t", orElse: ""))
case 2:
self = .plaintextPassword(value: decoder.decodeStringForKey("t", orElse: ""))
default:
assertionFailure()
self = .none
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .none:
encoder.encodeInt32(0, forKey: "r")
case let .numericalPassword(text):
encoder.encodeInt32(1, forKey: "r")
encoder.encodeString(text, forKey: "t")
case let .plaintextPassword(text):
encoder.encodeInt32(2, forKey: "r")
encoder.encodeString(text, forKey: "t")
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(String.self, forKey: .numericalPassword) {
self = .numericalPassword(value: value)
} else if let value = try? container.decode(String.self, forKey: .plaintextPassword) {
self = .plaintextPassword(value: value)
} else {
self = .none
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .none:
break
case let .numericalPassword(value):
try container.encode(value, forKey: .numericalPassword)
case let .plaintextPassword(value):
try container.encode(value, forKey: .plaintextPassword)
}
}
public var isLockable: Bool {
if case .none = self {
return false
} else {
return true
}
}
public var lockId: String? {
switch self {
case .none:
return nil
case let .numericalPassword(value):
return "numericalPassword:\(value)"
case let .plaintextPassword(value):
return "plaintextPassword:\(value)"
}
}
}
public struct AuthAccountRecord: PostboxCoding, Codable {
enum CodingKeys: String, CodingKey {
case id
case attributes
}
public let id: AccountRecordId
public let attributes: [AccountRecordAttribute]
init(id: AccountRecordId, attributes: [AccountRecordAttribute]) {
self.id = id
self.attributes = attributes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(AccountRecordId.self, forKey: .id)
let attributesData = try container.decode(Array<Data>.self, forKey: .attributes)
var attributes: [AccountRecordAttribute] = []
for data in attributesData {
if let object = PostboxDecoder(buffer: MemoryBuffer(data: data)).decodeRootObject() as? AccountRecordAttribute {
attributes.append(object)
}
}
self.attributes = attributes
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.id, forKey: .id)
let attributesData: [Data] = self.attributes.map { attribute in
let encoder = PostboxEncoder()
encoder.encodeRootObject(attribute)
return encoder.makeData()
}
try container.encode(attributesData, forKey: .attributes)
}
public init(decoder: PostboxDecoder) {
self.id = AccountRecordId(rawValue: decoder.decodeOptionalInt64ForKey("id")!)
self.attributes = decoder.decodeObjectArrayForKey("attributes").compactMap({ $0 as? AccountRecordAttribute })
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.id.rawValue, forKey: "id")
encoder.encodeGenericObjectArray(self.attributes.map { $0 as PostboxCoding }, forKey: "attributes")
}
}
enum AccountManagerMetadataOperation {
case updateCurrentAccountId(AccountRecordId)
case updateCurrentAuthAccountRecord(AuthAccountRecord?)
}
private enum MetadataKey: Int64 {
case currentAccountId = 0
case currentAuthAccount = 1
case accessChallenge = 2
case version = 3
}
final class AccountManagerMetadataTable: Table {
static func tableSpec(_ id: Int32) -> ValueBoxTable {
return ValueBoxTable(id: id, keyType: .int64, compactValuesOnCreation: false)
}
private func key(_ key: MetadataKey) -> ValueBoxKey {
let result = ValueBoxKey(length: 8)
result.setInt64(0, value: key.rawValue)
return result
}
func getVersion() -> Int32? {
if let value = self.valueBox.get(self.table, key: self.key(.version)) {
var id: Int32 = 0
value.read(&id, offset: 0, length: 4)
return id
} else {
return 0
}
}
func setVersion(_ version: Int32) {
var value: Int32 = version
self.valueBox.set(self.table, key: self.key(.version), value: MemoryBuffer(memory: &value, capacity: 4, length: 4, freeWhenDone: false))
}
func getCurrentAccountId() -> AccountRecordId? {
if let value = self.valueBox.get(self.table, key: self.key(.currentAccountId)) {
var id: Int64 = 0
value.read(&id, offset: 0, length: 8)
return AccountRecordId(rawValue: id)
} else {
return nil
}
}
func setCurrentAccountId(_ id: AccountRecordId, operations: inout [AccountManagerMetadataOperation]) {
var rawValue = id.rawValue
self.valueBox.set(self.table, key: self.key(.currentAccountId), value: MemoryBuffer(memory: &rawValue, capacity: 8, length: 8, freeWhenDone: false))
operations.append(.updateCurrentAccountId(id))
}
func getCurrentAuthAccount() -> AuthAccountRecord? {
if let value = self.valueBox.get(self.table, key: self.key(.currentAuthAccount)), let object = PostboxDecoder(buffer: value).decodeRootObject() as? AuthAccountRecord {
return object
} else {
return nil
}
}
func setCurrentAuthAccount(_ record: AuthAccountRecord?, operations: inout [AccountManagerMetadataOperation]) {
if let record = record {
let encoder = PostboxEncoder()
encoder.encodeRootObject(record)
withExtendedLifetime(encoder, {
self.valueBox.set(self.table, key: self.key(.currentAuthAccount), value: encoder.readBufferNoCopy())
})
} else {
self.valueBox.remove(self.table, key: self.key(.currentAuthAccount), secure: false)
}
operations.append(.updateCurrentAuthAccountRecord(record))
}
func getAccessChallengeData() -> PostboxAccessChallengeData {
if let value = self.valueBox.get(self.table, key: self.key(.accessChallenge)) {
return PostboxAccessChallengeData(decoder: PostboxDecoder(buffer: value))
} else {
return .none
}
}
func setAccessChallengeData(_ data: PostboxAccessChallengeData) {
let encoder = PostboxEncoder()
data.encode(encoder)
withExtendedLifetime(encoder, {
self.valueBox.set(self.table, key: self.key(.accessChallenge), value: encoder.readBufferNoCopy())
})
}
}
| 35.438298 | 175 | 0.620077 |
1eb9859aeed3a2c33db1e689426be0ef77e670ef | 8,495 | //
// SettingsViewController.swift
// ClockClock
//
// Created by Korel Hayrullah on 14.09.2021.
//
import UIKit
class SettingsViewController: UITableViewController {
// MARK: - Properties
@IBOutlet
private weak var animationDurationLabel: UILabel!
@IBOutlet
private weak var lineWidthLabel: UILabel!
@IBOutlet
private weak var outlineWidthLabel: UILabel!
@IBOutlet
private weak var darkModeLineColorView: UIView!
@IBOutlet
private weak var darkModeOutlineColorView: UIView!
@IBOutlet
private weak var lightModeLineColorView: UIView!
@IBOutlet
private weak var lightModeOutlineColorView: UIView!
@IBOutlet
private var saveBarButtonItem: UIBarButtonItem!
private var mutableSettings: SettingsModelMutable = SettingsModelMutable(model: Settings.current)
var dismissed: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
update()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let views: [UIView] = [
darkModeLineColorView,
darkModeOutlineColorView,
lightModeLineColorView,
lightModeOutlineColorView
]
views.forEach { view in
view.layer.cornerRadius = view.frame.height / 2
}
}
private func configureUI() {
let views: [UIView] = [
darkModeLineColorView,
darkModeOutlineColorView,
lightModeLineColorView,
lightModeOutlineColorView
]
views.forEach { view in
view.layer.borderWidth = 0.5
view.layer.borderColor = UIColor.black.cgColor
}
}
private func update() {
animationDurationLabel.text = "\(mutableSettings.animationDuration)s"
lineWidthLabel.text = "\(Int(mutableSettings.lineWidth))"
outlineWidthLabel.text = "\(Int(mutableSettings.outlineWidth))"
darkModeLineColorView.backgroundColor = mutableSettings.darkModeLineColor
darkModeOutlineColorView.backgroundColor = mutableSettings.darkModeOutlineColor
lightModeLineColorView.backgroundColor = mutableSettings.lightModeLineColor
lightModeOutlineColorView.backgroundColor = mutableSettings.lightModeOutlineColor
let hasChanges = Settings.current != SettingsModel(model: mutableSettings)
navigationItem.rightBarButtonItems = hasChanges ? [saveBarButtonItem] : []
}
// MARK: - Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch (indexPath.section, indexPath.row) {
case (0, 0):
presentAnimationDurationAlert { [weak self] duration in
self?.mutableSettings.animationDuration = duration
self?.update()
}
case (0, 1):
let completion: (CGFloat) -> Void = { [weak self] lineWidth in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.lineWidth != lineWidth
self.mutableSettings.lineWidth = lineWidth
self.update()
}
presentNumberSelectionPickerAlert(
title: "Select Line Width",
selected: Int(mutableSettings.lineWidth),
numbers: [1, 2, 3, 4, 5, 6],
completion: completion
)
case (0, 2):
let completion: (CGFloat) -> Void = { [weak self] lineWidth in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.outlineWidth != lineWidth
self.mutableSettings.outlineWidth = lineWidth
self.update()
}
presentNumberSelectionPickerAlert(
title: "Select Outline Width",
selected: Int(mutableSettings.outlineWidth),
numbers: [1, 2, 3],
completion: completion
)
case (1, 0):
presentColorSelectionController(selected: mutableSettings.darkModeLineColor, completion: { [weak self] color in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.darkModeLineColor != color
self.mutableSettings.darkModeLineColor = color
self.update()
})
case (1, 1):
presentColorSelectionController(selected: mutableSettings.darkModeOutlineColor, completion: { [weak self] color in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.darkModeOutlineColor != color
self.mutableSettings.darkModeOutlineColor = color
self.update()
})
case (2, 0):
presentColorSelectionController(selected: mutableSettings.lightModeLineColor, completion: { [weak self] color in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.lightModeLineColor != color
self.mutableSettings.lightModeLineColor = color
self.update()
})
case (2, 1):
presentColorSelectionController(selected: mutableSettings.lightModeOutlineColor, completion: { [weak self] color in
guard let self = self else { return }
Settings.needsRedraw = self.mutableSettings.lightModeOutlineColor != color
self.mutableSettings.lightModeOutlineColor = color
self.update()
})
default:
break
}
}
// MARK: - Actions
@IBAction
private func resetButtonPressed(_ sender: UIButton) {
let alert = UIAlertController(
title: "Reset",
message: "Are you sure you want to reset your settings?",
preferredStyle: .actionSheet
)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let reset = UIAlertAction(title: "Reset", style: .destructive) { [weak self] _ in
self?.mutableSettings = SettingsModelMutable(model: .preset)
self?.update()
}
alert.addAction(reset)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
@IBAction
private func closeBarButtonItemPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: { [weak self] in
self?.dismissed?()
})
}
@IBAction
private func saveBarButtonItemPressed(_ sender: UIBarButtonItem) {
Settings.current = SettingsModel(model: mutableSettings)
dismiss(animated: true, completion: { [weak self] in
self?.dismissed?()
})
}
}
// MARK: - Alerts and Presentations
extension SettingsViewController {
private func presentNumberSelectionPickerAlert(title: String?, selected: Int? = nil, numbers: [Int], completion: @escaping (CGFloat) -> Void) {
let alert = UIAlertController(
title: title,
message: "\n\n\n\n\n\n",
preferredStyle: .alert
)
alert.isModalInPresentation = true
let picker = NumberPickerView(frame: CGRect(x: 5, y: 20, width: 250, height: 140))
picker.set(numbers)
if let selected = selected {
picker.select(selected)
}
alert.view.addSubview(picker)
let select = UIAlertAction(title: "Select", style: .default, handler: { _ in
guard let lineWidth = picker.selected else { return }
completion(CGFloat(lineWidth))
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(select)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
private func presentColorSelectionController(selected: UIColor, completion: @escaping (UIColor) -> Void) {
let identifier = "ColorSelectionViewControllerNavigationController"
guard let nav = UIStoryboard.instantiateViewController(identifier: identifier) as? UINavigationController else { return }
guard let controller = nav.rootViewController as? ColorSelectionViewController else { return }
controller.selectedColor = selected
controller.completion = completion
present(nav, animated: true, completion: nil)
}
private func presentAnimationDurationAlert(completion: @escaping (Double) -> Void) {
let alert = UIAlertController(
title: "Animation Duration",
message: nil,
preferredStyle: .alert
)
alert.addTextField { tf in
tf.textAlignment = .center
tf.keyboardType = .numberPad
}
let apply = UIAlertAction(title: "Set", style: .default, handler: { [weak self] _ in
guard let text = alert.textFields?.first?.text else { return }
guard let number = Double(text) else {
self?.presentErrorAlert(message: "Entered text is not a number!")
return
}
guard number > 0 else {
self?.presentErrorAlert(message: "Entered number must be greater than 0 and a non-negative number!")
return
}
completion(number)
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(apply)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
private func presentErrorAlert(message: String) {
let alert = UIAlertController(
title: "Error",
message: message,
preferredStyle: .alert
)
let confirm = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(confirm)
present(alert, animated: true, completion: nil)
}
}
| 30.017668 | 144 | 0.726192 |
eb215195ab6e5132eb09a46459388af4ab709fd8 | 54,418 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '((Int, Double)) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{'myMap' is unavailable: call the 'map()' method on the sequence}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot invoke 'count' with no arguments}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{type of expression is ambiguous without more context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
// FIXME: rdar://41416346
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{'map' produces '[T]', not the expected contextual result type '[(Int, Color)]'}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{unavailable}}
a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() } // expected-note {{in call to operator '+++'}}
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42
// FIXME: rdar://41416382
_ = bytes[i+++] // expected-error {{generic parameter 'T' could not be inferred}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{11-11=x: 5, }} {{15-21=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{17-17=x: 5, }} {{21-27=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{35-35=Int(}} {{42-42=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{18-18=Float(}} {{34-34=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{24-24=Float(}} {{27-27=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{16-16=Int(}} {{19-19=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'String'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(3) * "0"
struct S {}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'S'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note {{found this candidate}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Double'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Double, Double)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{argument 'foo' must precede argument 'b'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{argument 'a' must precede argument 'c'}} {{14-14=a: { !$0 }, }} {{26-38=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{argument 'x' must precede unnamed argument #1}} {{12-12=x: 20, }} {{21-28=}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 {{ambiguous use of operator '+'}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {}
// expected-note@-1 {{in call to function 'elephant'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{generic parameter 'U' could not be inferred}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{type of expression is ambiguous without more context}}
// FIXME: terrible diagnostic
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{ambiguous reference to member '=='}}
}
| 44.973554 | 210 | 0.669925 |
46d074238fa440e564a8fcdfde35c7ed2d8a4d3c | 9,314 | //
// EnterChatNameVC.swift
// sample-chat-swift
//
// Created by Injoit on 10/9/19.
// Copyright © 2019 Quickblox. All rights reserved.
//
import UIKit
struct EnterChatNameConstant {
static let nameHint = NSLocalizedString("Must be in a range from 3 to 20 characters.", comment: "")
static let chatname = "^[^_][\\w\\u00C0-\\u1FFF\\u2C00-\\uD7FF\\s]{2,19}$"
}
class EnterChatNameVC: UITableViewController {
@IBOutlet weak var chatNameTextField: UITextField!
@IBOutlet weak var chatNameLabel: UILabel!
@IBOutlet weak var hintLabel: UILabel!
private var titleView = TitleView()
var selectedUsers: [QBUUser] = []
private let chatManager = ChatManager.instance
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 102.0
tableView.rowHeight = UITableView.automaticDimension
tableView.keyboardDismissMode = .onDrag
tableView.delaysContentTouches = false
let backButtonItem = UIBarButtonItem(image: UIImage(named: "chevron"),
style: .plain,
target: self,
action: #selector(didTapBack(_:)))
navigationItem.leftBarButtonItem = backButtonItem
backButtonItem.tintColor = .white
let createButtonItem = UIBarButtonItem(title: "Finish",
style: .plain,
target: self,
action: #selector(createChatButtonPressed(_:)))
navigationItem.rightBarButtonItem = createButtonItem
createButtonItem.tintColor = .white
navigationItem.titleView = titleView
setupNavigationTitle()
setupViews()
//MARK: - Reachability
let updateConnectionStatus: ((_ status: NetworkConnectionStatus) -> Void)? = { [weak self] status in
let notConnection = status == .notConnection
if notConnection == true {
self?.showAlertView(LoginConstant.checkInternet, message: LoginConstant.checkInternetMessage)
}
}
Reachability.instance.networkStatusBlock = { status in
updateConnectionStatus?(status)
}
updateConnectionStatus?(Reachability.instance.networkConnectionStatus())
}
//MARK - Setup
private func setupNavigationTitle() {
let title = CreateNewDialogConstant.newChat
let numberUsers = "\(selectedUsers.count) users selected"
titleView.setupTitleView(title: title, subTitle: numberUsers)
}
private func setupViews() {
chatNameTextField.becomeFirstResponder()
hintLabel.text = ""
chatNameTextField.setPadding(left: 12.0)
chatNameTextField.addShadowToTextField(color: #colorLiteral(red: 0.8755381703, green: 0.9203008413, blue: 1, alpha: 1), cornerRadius: 4.0)
chatNameTextField.text = ""
validate(chatNameTextField)
}
//MARK - Setup keyboardWillHideNotification
@objc func keyboardWillHide(notification: Notification) {
if hintLabel.text?.isEmpty == true {
hintLabel.text = ""
}
tableView.reloadData()
}
// MARK: - UITextField Helpers
private func isValid(chatName: String?) -> Bool {
let characterSet = CharacterSet.whitespaces
let trimmedText = chatName?.trimmingCharacters(in: characterSet)
let regularExtension = EnterChatNameConstant.chatname
let predicate = NSPredicate(format: "SELF MATCHES %@", regularExtension)
let isValid = predicate.evaluate(with: trimmedText)
return isValid
}
private func validate(_ textField: UITextField?) {
if textField == chatNameTextField, isValid(chatName: chatNameTextField.text) == false {
navigationItem.rightBarButtonItem?.isEnabled = false
hintLabel.text = EnterChatNameConstant.nameHint
} else {
navigationItem.rightBarButtonItem?.isEnabled = true
hintLabel.text = ""
}
tableView.beginUpdates()
tableView.endUpdates()
}
@IBAction func chatNameDidChanged(_ sender: UITextField) {
validate(sender)
}
//MARK: - Actions
@objc func didTapBack(_ sender: UIBarButtonItem) {
navigationController?.popViewController(animated: true)
}
@objc func createChatButtonPressed(_ sender: UIBarButtonItem) {
if Reachability.instance.networkConnectionStatus() == .notConnection {
showAlertView(LoginConstant.checkInternet, message: LoginConstant.checkInternetMessage)
SVProgressHUD.dismiss()
return
}
if selectedUsers.count > 1 {
let chatName = chatNameTextField.text ?? "New Group Chat"
SVProgressHUD.show()
chatManager.storage.update(users: selectedUsers)
chatManager.createGroupDialog(withName: chatName,
photo: nil,
occupants: selectedUsers) { [weak self] (response, dialog) -> Void in
guard response?.error == nil,
let dialog = dialog,
let dialogOccupants = dialog.occupantIDs else {
SVProgressHUD.showError(withStatus: response?.error?.error?.localizedDescription)
return
}
if let message = self?.messageText(withChatName: chatName) {
self?.chatManager.sendAddingMessage(message, action: .create, withUsers: dialogOccupants, to: dialog, completion: { (error) in
SVProgressHUD.showSuccess(withStatus: "STR_DIALOG_CREATED".localized)
self?.openNewDialog(dialog)
})
}
}
}
}
private func messageText(withChatName chatName: String) -> String {
let actionMessage = "SA_STR_CREATE_NEW".localized
guard let current = QBSession.current.currentUser,
let fullName = current.fullName else {
return ""
}
return "\(fullName) \(actionMessage) \"\(chatName)\""
}
private func openNewDialog(_ newDialog: QBChatDialog) {
guard let navigationController = navigationController else {
return
}
let controllers = navigationController.viewControllers
var newStack = [UIViewController]()
//change stack by replacing view controllers after ChatVC with ChatVC
controllers.forEach{
newStack.append($0)
if $0 is DialogsViewController {
let storyboard = UIStoryboard(name: "Chat", bundle: nil)
guard let chatController = storyboard.instantiateViewController(withIdentifier: "ChatViewController")
as? ChatViewController else {
return
}
chatController.dialogID = newDialog.id
newStack.append(chatController)
navigationController.setViewControllers(newStack, animated: true)
return
}
}
//else perform segue
self.performSegue(withIdentifier: "SA_STR_SEGUE_GO_TO_CHAT".localized, sender: newDialog.id)
}
//MARK: - Overrides
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SA_STR_SEGUE_GO_TO_CHAT".localized {
if let chatVC = segue.destination as? ChatViewController {
chatVC.dialogID = sender as? String
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if hintLabel.text?.isEmpty == true, indexPath.row == 1 {
return 6
}
return UITableView.automaticDimension
}
}
//MARK: - UITextFieldDelegate
extension EnterChatNameVC: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
validate(textField)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
return true
}
}
| 39.634043 | 174 | 0.567533 |
1dca38c9ea34a4b040cef71418b942c73924a6ba | 2,372 | //
// StrartupLaunch.swift
// eye
//
// Created by Alimjan on 2021/3/18.
//
import Foundation
final class StartupLaunch: NSObject {
class var isAppLoginItem: Bool {
return itemReferencesInLoginItems.existingReference != nil
}
private class var itemReferencesInLoginItems: (existingReference: LSSharedFileListItem?, lastReference: LSSharedFileListItem?) {
if let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileList? {
let loginItems = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray as! [LSSharedFileListItem]
if loginItems.count > 0 {
let appUrl = URL(fileURLWithPath: Bundle.main.bundlePath)
let itemUrl = UnsafeMutablePointer<Unmanaged<CFURL>?>.allocate(capacity: 1)
defer { itemUrl.deallocate(capacity: 1) }
for i in loginItems {
if let itemUrl = LSSharedFileListItemCopyResolvedURL(i, 0, nil), itemUrl.takeRetainedValue() as URL == appUrl {
return (i, loginItems.last)
}
}
return (nil, loginItems.last)
} else {
return(nil, kLSSharedFileListItemBeforeFirst.takeRetainedValue())
}
}
return (nil, nil)
}
class func setLaunchOnLogin(_ launch: Bool) {
let itemReferences = itemReferencesInLoginItems
let isSet = itemReferences.existingReference != nil
let type = kLSSharedFileListSessionLoginItems.takeUnretainedValue()
if let loginItemsRef = LSSharedFileListCreate(nil, type, nil).takeRetainedValue() as LSSharedFileList? {
if launch && !isSet {
let appUrl = URL(fileURLWithPath: Bundle.main.bundlePath) as CFURL
LSSharedFileListInsertItemURL(loginItemsRef, itemReferences.lastReference, nil, nil, appUrl, nil, nil)
} else if !launch && isSet, let itemRef = itemReferences.existingReference {
LSSharedFileListItemRemove(loginItemsRef, itemRef)
}
}
}
}
| 42.357143 | 166 | 0.599494 |
18e566d73967d5b6feccb02e17bfddef1bf80587 | 6,367 | //
// UserServices.swift
// Linner
//
// Created by Yves Songolo on 8/21/18.
// Copyright © 2018 Yves Songolo. All rights reserved.
//
import UIKit
import Foundation
import Firebase
import GoogleSignIn
import FBSDKCoreKit
import FBSDKLoginKit
struct UserServices{
/* Implements The CRUD Services of a User model
Methods :
- show : shows a single user
- create : creates a single user
- signUp: registers a single user
- signIn: logs in a single user
- update : updates a single user
*/
/* THIS METHOD CREATES A SINGLE USER OBJECT AND STORES IT IN THE DATABASE
@param user : The user object to be created
@param completion -> Any: The single user obejct to be returned after the method call
*/
private static func create(user: User, completion: @escaping(Any)->()){
let authUser = Auth.auth().currentUser
let ref = Constant.user((authUser?.uid)!)
ref.setValue(user.toDictionary()) { (error, _) in
if error != nil{
return completion(error!)
}
return completion(user)
}
}
/* THIS METHOD RETRIEVE USER FROM THE DATABASE
@param completion -> User: The single user obejct to be returned after the method call
*/
static func show(completion: @escaping(User?)-> ()){
let uid = Auth.auth().currentUser?.uid
let ref = Constant.user(uid!)
ref.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists(){
let user = try! JSONDecoder().decode(User.self, withJSONObject: snapshot.value!)
return completion(user)
}
else{
return completion(nil)
}
}
}
/* THIS METHOD SIGNS UP A NEW USER
@param email : The user's email address
@param password: The user's password
@param completion -> Any: The single user obejct to be returned after the method call
*/
static func signUp(_ email: String, _ password: String, completion: @escaping (Any)->()){
Auth.auth().createUser(withEmail: email, password: password) { (authUser, error) in
guard authUser != nil else {return completion(error!)}
let user = User.init("", (authUser?.user.uid)!, (authUser?.user.email!)!)
create(user: user, completion: { (newUser) in
if (newUser as? User) != nil{
show(completion: { (user) in
print("User succesfully signed up")
return completion(user!)
})
}
})
}
}
/* THIS METHOD LOGS IN A USER INTO THEIR ACCOUT
@param email : The user's email address
@param password: The user's password
@param completion -> Any: The single user obejct to be returned after the method call
*/
static func signIn(_ email: String, _ password: String, completion: @escaping (Any) ->()){
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if error != nil {return completion(error.debugDescription)}
show(completion: { (user) in
return completion(user!)
})
}
}
/* THIS METHOD UPDATES A USER ACCOUNT
@param newUser: The user object to be updated
@param completion -> Any: The single user obejct to be returned after the method call
*/
static func update(_ newUser: User,completion: @escaping (User)->()){
let ref = Constant.user((Auth.auth().currentUser?.uid)!)
ref.updateChildValues(newUser.toDictionary()) { (error, ref) in
show { (user) in
return completion(user!)
}
}
}
/// method to add google user to firrebase
static func loginWithGoogle(googleUser: GIDGoogleUser, completion: @escaping(User?) -> ()){
let profile = googleUser.profile
var user = User.init((Auth.auth().currentUser?.displayName)!, "", (profile?.email)!)
//let user = User(fn: (profile?.givenName)!, ln: (profile?.familyName)!, un: (profile?.name)!, deviceToken: "", accountType: "client", email: (profile?.email)!)
if (profile?.hasImage)!{
user.profileUrl = profile?.imageURL(withDimension: 300).absoluteString
}
show { (existingUser) in
if existingUser == nil{
create( user: user) { (created) in
if (created as? User != nil){
return completion(created as? User)
}
else{
print("couldn't create user")
completion(nil)
}
}
}
else{
return completion(existingUser)
}
}
}
static func loginWithFacebook(sender: UIViewController,completion: @escaping(User?)->()){
FBSDKProfile.loadCurrentProfile(completion: { profile, error in
if let profile = profile {
guard let authUser = Auth.auth().currentUser else {
return completion(nil)
}
var user = User.init(profile.name, "", Auth.auth().currentUser?.email ?? "")
user.profileUrl = profile.imageURL(for: .square, size: CGSize(width: 100, height: 100)).absoluteString
/// fetch user from database
show(completion: { (databaseUser) in
if let databaseUser = databaseUser{
completion(databaseUser)
}
else{
/// create user if first time login
create(user: user, completion: { (createdUser) in
if let user = createdUser as? User{
completion(user)
}
else{
print("user wasn't create in the database")
completion(nil)
}
})
}
})
}
})
}
}
| 34.983516 | 168 | 0.527407 |
ab78536e260c6b2e2c5a9fc8ea2940404750b121 | 4,940 | // This file defines all utility functions used in this project.
import Foundation
import SwiftUI
/// Decodes a `Data` object to a generic type `T` where
/// `T` is a `Decodable`.
/// - Parameter data: The data that has to be decoded.
func decodeJSON<T: Decodable>(data: Data) -> T {
do {
return try JSONDecoder().decode(T.self, from: data)
}
catch {
fatalError("Could not decode data as \(T.self).")
}
}
/// Decodes a `Data` object to a generic type `T` when `T` is a `Decodable`.
/// - Parameters:
/// - type: Type to be decoded to.
/// - data: The data that has to be decoded.
func decodeJSON<T: Decodable>(_ type: T.Type, data: Data) -> T {
do {
return try JSONDecoder().decode(type.self, from: data)
}
catch {
fatalError("Could not decode data as \(T.self).")
}
}
/// A utility function that performs an asynchronous data task using `URLSession.shared`.
/// - Parameters:
/// - _: A `URLRequest` object that has the required configuration.
/// - completionHandler: The task to perform after the data task is completed.
func dataTaskWithURLRequest(_ urlRequest: URLRequest,
completionHandler: @escaping (Data, HTTPURLResponse, Error?) -> Void) {
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil,
let data = data,
let response = response as? HTTPURLResponse
else {
return
}
completionHandler(data, response, error)
}.resume()
}
/// A utility function to perform a synchronous request.
/// - Parameter _: A fully configured `URLRequest` object
func syncDataTaskWithURLRequest(_ urlRequest: URLRequest) -> (Data, HTTPURLResponse, Error?) {
var returnData: Data = Data()
var returnResponse: HTTPURLResponse = HTTPURLResponse()
var returnError: Error?
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil,
let data = data,
let response = response as? HTTPURLResponse
else {
return
}
returnData = data
returnResponse = response
returnError = error
semaphore.signal()
}
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (returnData, returnResponse, returnError)
}
/// A utility function that returns a serialisable representation of a `Date` object.
/// - Parameter _: The date object that has to be serialisable.
/// - Returns: An RFC3339 representation of the date.
func stringFromDate(_ date: Date) -> String {
let iso8601Formatter = ISO8601DateFormatter()
iso8601Formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
iso8601Formatter.timeZone = TimeZone(secondsFromGMT: 0)!
return iso8601Formatter.string(from: date)
}
/// A utility function that converts an RFC3339 date string to a `Date` object.
/// - Parameter _: An RFC3339 representation of date.
func dateFromString(_ string: String) -> Date {
let iso8601Formatter = ISO8601DateFormatter()
iso8601Formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
iso8601Formatter.timeZone = TimeZone(secondsFromGMT: 0)!
guard let date = iso8601Formatter.date(from: string) else {
fatalError("[DateToStringConverter] - Could not obtain a date for the string: '\(string)'.")
}
return date
}
func decodeFromFile<T: Decodable>(_ filename: String) -> T {
guard let fileURL = Bundle.main.url(forResource: filename, withExtension: nil) else {
fatalError("[Utils/DecodeFromFile] - Couldn't find file \(filename).")
}
let data: Data
do {
data = try Data(contentsOf: fileURL)
}
catch {
fatalError("[Utils/DecodeFromFile] - Couldn't load data from file \(filename).\n\(error)")
}
let returnVal: T = decodeJSON(data: data)
return returnVal
}
/// A utility function to load an image from a URL.
/// - Parameter fromURL: The URL of the image as a `String`
/// - Returns: An `Image` object of the image as received from the server.
func loadImage(fromURL urlString: String) -> Image {
guard let url = URL(string: urlString) else {
fatalError("[Utils/LoadImage] - Could not construct URL.")
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
let (data, response, _) = syncDataTaskWithURLRequest(request)
switch response.statusCode {
case 200:
guard let uiImage = UIImage(data: data) else {
fatalError("[Utils/LoadImage] - Could not create `UIImage` object from `Data`.")
}
return Image(uiImage: uiImage)
default:
fatalError("[Utils/LoadImage] - Image could not be found.")
}
}
| 34.068966 | 100 | 0.647976 |
eb7f3bb0dfb3df51f3f2292cc5e7fe3b945115d5 | 1,042 | //
// WidthModulation.swift
// Doodling
//
// Created by wow250250 on 2017/8/2.
// Copyright © 2017年 ZZH. All rights reserved.
//
import UIKit
class Modulation {
public class func modulationWidth(width: CGFloat, velocity: CGPoint, previousVelocity: CGPoint, previousWidth: CGFloat) -> CGFloat {
let velocityAdjustement: CGFloat = 600.0
let speed = velocity.length / velocityAdjustement
let previousSpeed = previousVelocity.length / velocityAdjustement
let modulated = width / (0.6 * speed + 0.4 * previousSpeed)
let limited = clamp(value: modulated, min: 0.90 * previousWidth, max: 1.10 * previousWidth)
let final = clamp(value: limited, min: 0.2*width, max: width)
return final
}
private class func clamp<T: Comparable>(value: T, min: T, max: T) -> T {
if (value < min) { return min }
if (value > max) { return max }
return value
}
}
extension CGPoint {
var length: CGFloat {
return sqrt((x*x) + (y*y))
}
}
| 28.944444 | 136 | 0.627639 |
dee1cb1020796706c9306400f16ca852e100d574 | 1,507 | //
// ImageHelper.swift
// Marvel Challenge
//
// Created by Guilherme Assis on 11/03/16.
// Copyright © 2016 Guilherme Assis. All rights reserved.
//
import UIKit
import Kingfisher
public typealias ImageLoadCompletionBlock = (image: UIImage?) -> Void
class ImageHelper: NSObject {
class func loadImageWithUrl(url: NSURL, completion: ImageLoadCompletionBlock) {
let downloader = KingfisherManager.sharedManager.downloader
let myCache = ImageCache(name: url.absoluteString)
let optionInfo: KingfisherOptionsInfo = [
.ForceRefresh,
.TargetCache(myCache)
]
downloader.downloadImageWithURL(url, options: optionInfo, progressBlock: nil) { (image, error, imageURL, originalData) -> () in
completion(image: image)
}
}
}
extension UIImageView {
func loadImageWithUrl(url: String, placeholder: UIImage?) {
if let _placeholder = placeholder {
self.image = _placeholder
}
ImageHelper.loadImageWithUrl(NSURL(string: url)!) { (image) -> Void in
self.image = image
}
}
func loadResourceImageWithUrl(url: String, placeholder: UIImage?) {
if let _placeholder = placeholder {
self.image = _placeholder
}
let _url = NSURL(string: url)
let resource = Resource(downloadURL: _url!, cacheKey: url)
self.kf_setImageWithResource(resource)
}
}
| 27.907407 | 135 | 0.625083 |
1a2a057ee81e7eb3fdcb7de6edb7a38569b31ae0 | 268 | import Vapor
extension GoogleDirectionResponse {
public struct Coordinate: Content {
public var latitude: Double
public var longitude: Double
enum CodingKeys: String, CodingKey {
case latitude = "lat"
case longitude = "lng"
}
}
}
| 19.142857 | 40 | 0.66791 |
bfdf46e658a0daaf4a402ed2a980d3376446bc95 | 1,668 | //
// SPPageView.swift
// SPPageView
//
// Created by simple on 2017/5/18.
// Copyright © 2017年 simple. All rights reserved.
//
import UIKit
class SPPageView: UIView {
var titles : [String]
var style : SPPageStyle
var childVCArray : [UIViewController]
var parentVC : UIViewController
// MARK: 初始化
init(frame: CGRect, titles: [String], style: SPPageStyle, childVCArray:[UIViewController],parentVC: UIViewController) {
self.titles = titles
self.style = style
self.childVCArray = childVCArray
self.parentVC = parentVC
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: 初始化UI
extension SPPageView {
fileprivate func setupUI () {
// 1.初始化titleView
let titleFrame = CGRect(x: 0, y: 0, width: bounds.width, height: style.titleHeight)
let titleView = SPTitleView(frame: titleFrame, titles: self.titles, style: style)
titleView.backgroundColor = UIColor.blue
addSubview(titleView)
// 2.初始化contentView
let contentFrame = CGRect(x: 0, y: titleFrame.maxY, width: bounds.width, height: bounds.height - style.titleHeight)
let contentView = SPContentView(frame: contentFrame, childVCArray: childVCArray, parentVC: parentVC)
contentView.backgroundColor = UIColor.white
addSubview(contentView)
// 3.设置代理
titleView.delegate = contentView
contentView.delegate = titleView
}
}
| 26.0625 | 123 | 0.621703 |
bf9652fa821c96409d7de7adc1d9ccfba12a85e5 | 7,698 | //
// rSRecordViewController.swift
// suracare
//
// Created by hoi on 8/16/16.
// Copyright © 2016 Sugar Rain. All rights reserved.
//
import UIKit
import AVFoundation
class rSRecordViewController: rSBaseViewController {
var audioRecorder: AVAudioRecorder?
var meterTimer: NSTimer?
let recordDuration = 10.0
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var voiceRecordHUD: KMVoiceRecordHUD!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
voiceRecordHUD.update(0.0)
voiceRecordHUD.fillColor = UIColor.greenColor()
durationLabel.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func finishRecord(sender: AnyObject) {
meterTimer?.invalidate()
meterTimer = nil
voiceRecordHUD.update(0.0)
if audioRecorder?.currentTime > 0 {
audioRecorder?.stop()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
audioRecorder = nil
self.dismissViewControllerAnimated(true, completion: nil)
}
AudioSessionHelper.setupSessionActive(false)
}
// MARK: Notification
func handleInterruption(notification: NSNotification) {
if let userInfo = notification.userInfo {
let interruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as! UInt
if interruptionType == AVAudioSessionInterruptionType.Began.rawValue {
if audioRecorder?.recording == true {
audioRecorder?.pause()
}
meterTimer?.invalidate()
meterTimer = nil
voiceRecordHUD.update(0.0)
} else if interruptionType == AVAudioSessionInterruptionType.Ended.rawValue {
let alertController = UIAlertController(title: nil, message: "Do you want to continue the recording?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { _ in
self.finishRecord(self)
}
alertController.addAction(cancelAction)
let resumeAction = UIAlertAction(title: "Resume", style: .Default) { _ in
self.delay(0.8) {
if let recorder = self.audioRecorder {
recorder.record()
self.updateRecorderCurrentTimeAndMeters()
self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
target: self,
selector: "updateRecorderCurrentTimeAndMeters",
userInfo: nil,
repeats: true)
}
}
}
alertController.addAction(resumeAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
}
// MARK: Other
func delay(time: NSTimeInterval, block: () -> Void) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
func updateRecorderCurrentTimeAndMeters() {
if let recorder = audioRecorder {
let currentTime = Int(recorder.currentTime)
let timeLeft = Int(recordDuration) - currentTime
if timeLeft > 10 {
durationLabel.text = "\(currentTime)″"
} else {
voiceRecordHUD.fillColor = UIColor.redColor()
durationLabel.text = "\(timeLeft) seconds left"
if timeLeft == 0 {
durationLabel.text = "Time is up"
finishRecord(self)
}
}
if recorder.recording {
recorder.updateMeters()
let ALPHA = 0.05
let peakPower = pow(10, (ALPHA * Double(recorder.peakPowerForChannel(0))))
var rate: Double = 0.0
if (peakPower <= 0.2) {
rate = 0.2
} else if (peakPower > 0.9) {
rate = 1.0
} else {
rate = peakPower
}
voiceRecordHUD.update(CGFloat(rate))
}
}
}
func configRecorderWithURL(url: NSURL, delegate: AVAudioRecorderDelegate) {
let session:AVAudioSession = AVAudioSession.sharedInstance()
session.requestRecordPermission {granted in
if granted {
debugPrint("Recording permission has been granted")
let recordSettings: [String : AnyObject] = [
AVFormatIDKey : NSNumber(unsignedInt: kAudioFormatLinearPCM),
AVSampleRateKey : 44100.0,
AVNumberOfChannelsKey : 2,
AVLinearPCMBitDepthKey : 16,
AVLinearPCMIsBigEndianKey : false,
AVLinearPCMIsFloatKey : false,
]
self.audioRecorder = try? AVAudioRecorder(URL: url, settings: recordSettings)
guard let recorder = self.audioRecorder else {
return
}
recorder.delegate = delegate
recorder.meteringEnabled = true
AudioSessionHelper.postStartAudioNotificaion(recorder)
self.delay(0.8) {
AudioSessionHelper.setupSessionActive(true, catagory: AVAudioSessionCategoryRecord)
if recorder.prepareToRecord() {
recorder.recordForDuration(self.recordDuration)
debugPrint("Start recording")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: AVAudioSession.sharedInstance())
self.updateRecorderCurrentTimeAndMeters()
self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
target: self,
selector: "updateRecorderCurrentTimeAndMeters",
userInfo: nil,
repeats: true)
}
}
} else {
debugPrint("Recording permission has been denied")
}
}
}
}
| 40.730159 | 198 | 0.538581 |
fe43f449d9a48f4319b9f4324c3b66a2167af248 | 131 | import UIKit
@objc(TestingAppDelegate)
class TestingAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 18.714286 | 62 | 0.801527 |
508a153d73dfb05c12cb984229039f0a8c3cd8a0 | 2,529 | public extension HAR {
/// List of posted parameters, if any (embedded in `PostData` object).
struct Param: Equatable, Hashable, Codable, CustomStringConvertible,
CustomDebugStringConvertible
{
// MARK: Properties
/// Name of a posted parameter.
public var name: String
/// Value of a posted parameter or content of a posted file.
public var value: String?
/// Name of a posted file.
public var fileName: String?
/// Content type of a posted file.
public var contentType: String?
/// A comment provided by the user or the application.
///
/// - Version: 1.2
public var comment: String?
// MARK: Initializers
/// Create param.
public init(
name: String,
value: String? = nil,
fileName: String? = nil,
contentType: String? = nil,
comment: String? = nil
) {
self.name = name
self.value = value
self.fileName = fileName
self.contentType = contentType
self.comment = comment
}
// MARK: Encoding and Decoding
/// Create Param from Decoder.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
/// Override synthesised decoder to handle empty `name`.
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
self.value = try container.decodeIfPresent(String.self, forKey: .value)
self.fileName = try container.decodeIfPresent(String.self, forKey: .fileName)
self.contentType = try container.decodeIfPresent(String.self, forKey: .contentType)
}
// MARK: Describing Params
/// A human-readable description for the data.
public var description: String {
var str = "\(name)"
if let fileName = fileName {
str += "=@\(fileName)"
if let contentType = contentType {
str += ";type=\(contentType)"
}
} else if let value = value {
str += "=\(value)"
}
return str
}
/// A human-readable debug description for the data.
public var debugDescription: String {
"HAR.Param { \(description) }"
}
}
/// Array of Param objects.
typealias Params = [Param]
}
| 30.107143 | 95 | 0.548834 |
e27d9262de65652be3e4c17264b4170bf297e7af | 8,945 | //
// SecretCodesView.swift
// ClubhouseAvatarMaker
//
// Created by Антон Текутов on 08.03.2021.
//
import UIKit
final class SecretCodesView: UIView {
let padding: CGFloat = 24
let closeButton = ButtonWithTouchSize()
let scroll = UIScrollView()
let titleLabel = UILabel()
let codeTextField = UITextField()
let useCodeButton = ButtonWithTouchSize()
let tableTitleLabel = UILabel()
let usedCodesTableView = ContentFittingTableView()
let promotionTitleLabel = UILabel()
let promotionTextLabel = UILabel()
let emailLabel = CopyLabelView()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK: - Private methods
private func setupView() {
backgroundColor = R.color.main()
addSubview(closeButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.setImage(R.image.cross(), for: .normal)
closeButton.setImage(R.image.cross(), for: .highlighted)
addSubview(scroll)
scroll.translatesAutoresizingMaskIntoConstraints = false
setupCodesMenu()
setupPromotionInfo()
makeConstraints()
}
private func setupCodesMenu() {
scroll.addSubview(titleLabel)
UIStyleManager.lableTitle(titleLabel)
titleLabel.numberOfLines = 0
titleLabel.text = NSLocalizedString("Use secret code", comment: "")
scroll.addSubview(codeTextField)
codeTextField.autocapitalizationType = .allCharacters
UIStyleManager.textFieldDefault(textField: codeTextField,
placeholderText: NSLocalizedString("Enter code here", comment: ""))
scroll.addSubview(useCodeButton)
UIStyleManager.buttonDark(useCodeButton)
useCodeButton.setTitle(NSLocalizedString("Apply", comment: ""), for: .normal)
scroll.addSubview(tableTitleLabel)
tableTitleLabel.translatesAutoresizingMaskIntoConstraints = false
tableTitleLabel.font = R.font.sfuiTextBold(size: 18)
tableTitleLabel.textColor = R.color.tintColorDark()
tableTitleLabel.numberOfLines = 0
tableTitleLabel.text = NSLocalizedString("Used codes", comment: "")
scroll.addSubview(usedCodesTableView)
usedCodesTableView.translatesAutoresizingMaskIntoConstraints = false
usedCodesTableView.estimatedRowHeight = CodeTableViewCell.cellHeight
usedCodesTableView.rowHeight = UITableView.automaticDimension
usedCodesTableView.separatorStyle = .none
usedCodesTableView.allowsSelection = false
usedCodesTableView.register(CodeTableViewCell.self, forCellReuseIdentifier: CodeTableViewCell.identifier)
}
private func setupPromotionInfo() {
let titleText = R.string.localizable.thisIsServiceFor()
let text = R.string.localizable.codesInscruction()
scroll.addSubview(promotionTitleLabel)
promotionTitleLabel.translatesAutoresizingMaskIntoConstraints = false
promotionTitleLabel.textColor = R.color.tintColorDark()
promotionTitleLabel.numberOfLines = 0
promotionTitleLabel.font = R.font.sfuiTextBold(size: 18)
var attributedString = NSMutableAttributedString(string: titleText)
var range: NSRange = attributedString.mutableString.range(of: NSLocalizedString("branded", comment: ""),
options: .caseInsensitive)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.thick.rawValue, range: range)
range = attributedString.mutableString.range(of: NSLocalizedString("corporate", comment: ""),
options: .caseInsensitive)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.thick.rawValue, range: range)
promotionTitleLabel.attributedText = attributedString
scroll.addSubview(promotionTextLabel)
promotionTextLabel.translatesAutoresizingMaskIntoConstraints = false
promotionTextLabel.textColor = R.color.tintColorDark()
promotionTextLabel.numberOfLines = 0
promotionTextLabel.font = R.font.sfuiTextLight(size: 16)
attributedString = NSMutableAttributedString(string: text)
range = attributedString.mutableString.range(of: NSLocalizedString("How does it works?", comment: ""),
options: .caseInsensitive)
attributedString.addAttribute(NSAttributedString.Key.font, value: R.font.sfuiTextBold(size: 16)!, range: range)
range = attributedString.mutableString.range(of: NSLocalizedString("Note:", comment: ""),
options: .caseInsensitive)
attributedString.addAttribute(NSAttributedString.Key.font, value: R.font.sfuiTextBold(size: 16)!, range: range)
promotionTextLabel.attributedText = attributedString
scroll.addSubview(emailLabel)
emailLabel.translatesAutoresizingMaskIntoConstraints = false
emailLabel.setText(labelText: Contacts.mainContactEmail, copyText: Contacts.mainContactEmail)
}
private func makeConstraints() {
NSLayoutConstraint.activate([
closeButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 25),
closeButton.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 25),
closeButton.widthAnchor.constraint(equalToConstant: 20),
closeButton.heightAnchor.constraint(equalToConstant: 20),
scroll.topAnchor.constraint(equalTo: closeButton.bottomAnchor, constant: padding),
scroll.leftAnchor.constraint(equalTo: leftAnchor),
scroll.rightAnchor.constraint(equalTo: rightAnchor),
scroll.bottomAnchor.constraint(equalTo: bottomAnchor),
titleLabel.topAnchor.constraint(equalTo: scroll.topAnchor, constant: padding),
titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
titleLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -padding * 2),
codeTextField.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: padding),
codeTextField.leftAnchor.constraint(equalTo: scroll.leftAnchor, constant: padding),
useCodeButton.topAnchor.constraint(equalTo: codeTextField.topAnchor),
useCodeButton.leftAnchor.constraint(equalTo: codeTextField.rightAnchor, constant: 8),
useCodeButton.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding),
useCodeButton.widthAnchor.constraint(equalTo: useCodeButton.titleLabel!.widthAnchor, constant: padding * 2),
useCodeButton.titleLabel!.widthAnchor.constraint(equalToConstant: useCodeButton.titleLabel!.text!.width(with: useCodeButton.titleLabel!.font)),
tableTitleLabel.topAnchor.constraint(equalTo: codeTextField.bottomAnchor, constant: padding),
tableTitleLabel.leftAnchor.constraint(equalTo: scroll.leftAnchor, constant: padding),
tableTitleLabel.rightAnchor.constraint(equalTo: scroll.rightAnchor, constant: -padding),
usedCodesTableView.topAnchor.constraint(equalTo: tableTitleLabel.bottomAnchor, constant: padding / 2),
usedCodesTableView.leftAnchor.constraint(equalTo: leftAnchor),
usedCodesTableView.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding),
promotionTitleLabel.topAnchor.constraint(equalTo: usedCodesTableView.bottomAnchor, constant: padding * 2),
promotionTitleLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: padding),
promotionTitleLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding),
promotionTextLabel.topAnchor.constraint(equalTo: promotionTitleLabel.bottomAnchor, constant: padding),
promotionTextLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: padding),
promotionTextLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding),
emailLabel.topAnchor.constraint(equalTo: promotionTextLabel.bottomAnchor),
emailLabel.bottomAnchor.constraint(equalTo: scroll.bottomAnchor, constant: -100),
emailLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: padding),
emailLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -padding)
])
}
}
| 50.252809 | 155 | 0.685299 |
b91cd3963be624569274f0741a0e6a190fe46ee9 | 15,522 | import Quick
import Nimble
import Stencil
@testable import Sourcery
class GeneratorSpec: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
describe("Generator") {
let fooType = Class(name: "Foo", variables: [Variable(name: "intValue", typeName: TypeName("Int"))], inheritedTypes: ["NSObject", "Decodable", "AlternativeProtocol"])
let fooSubclassType = Class(name: "FooSubclass", inheritedTypes: ["Foo", "ProtocolBasedOnKnownProtocol"], annotations: ["foo": NSNumber(value: 2)])
let barType = Struct(name: "Bar", inheritedTypes: ["KnownProtocol", "Decodable"], annotations: ["bar": NSNumber(value: true)])
let complexType = Struct(name: "Complex", accessLevel: .public, isExtension: false, variables: [])
let fooVar = Variable(name: "foo", typeName: TypeName("Foo"), accessLevel: (read: .public, write: .private), isComputed: false)
fooVar.type = fooType
let barVar = Variable(name: "bar", typeName: TypeName("Bar"), accessLevel: (read: .public, write: .public), isComputed: false)
barVar.type = barType
complexType.variables = [
fooVar,
barVar,
Variable(name: "fooBar", typeName: TypeName("Int"), isComputed: true),
Variable(name: "tuple", typeName: TypeName("(Int, Bar)"))
]
complexType.methods = [
Method(name: "foo(some: Int)", selectorName: "foo(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName("Int"))], accessLevel: .public),
Method(name: "foo2(some: Int)", selectorName: "foo2(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName("Float"))], isStatic: true),
Method(name: "foo3(some: Int)", selectorName: "foo3(some:)", parameters: [MethodParameter(name: "some", typeName: TypeName("Int"))], isClass: true)
]
let types = [
fooType,
fooSubclassType,
complexType,
barType,
Enum(name: "Options", accessLevel: .public, inheritedTypes: ["KnownProtocol"], cases: [EnumCase(name: "optionA"), EnumCase(name: "optionB")], containedTypes: [
Type(name: "InnerOptions", accessLevel: .public, variables: [
Variable(name: "foo", typeName: TypeName("Int"), accessLevel: (read: .public, write: .public), isComputed: false)
])
]),
Enum(name: "FooOptions", accessLevel: .public, inheritedTypes: ["Foo", "KnownProtocol"], rawTypeName: TypeName("Foo"), cases: [EnumCase(name: "fooA"), EnumCase(name: "fooB")]),
Type(name: "NSObject", accessLevel: .none, isExtension: true, inheritedTypes: ["KnownProtocol"]),
Class(name: "ProjectClass", accessLevel: .open),
Class(name: "ProjectFooSubclass", inheritedTypes: ["FooSubclass"]),
Protocol(name: "KnownProtocol", variables: [Variable(name: "protocolVariable", typeName: TypeName("Int"), isComputed: true)]),
Protocol(name: "AlternativeProtocol"),
Protocol(name: "ProtocolBasedOnKnownProtocol", inheritedTypes: ["KnownProtocol"])
]
let arguments: [String: NSObject] = ["some": "value" as NSString, "number": NSNumber(value: Float(4))]
func generate(_ template: String) -> String {
let types = Composer().uniqueTypes(FileParserResult(path: nil, module: nil, types: types, typealiases: []))
return (try? Generator.generate(Types(types: types),
template: StencilTemplate(templateString: template),
arguments: arguments)) ?? ""
}
it("generates types.all by skipping protocols") {
expect(generate("Found {{ types.all.count }} types")).to(equal("Found 9 types"))
}
it("generates types.protocols") {
expect(generate("Found {{ types.protocols.count }} protocols")).to(equal("Found 3 protocols"))
}
it("generates types.classes") {
expect(generate("Found {{ types.classes.count }} classes, first: {{ types.classes.first.name }}, second: {{ types.classes.last.name }}")).to(equal("Found 4 classes, first: Foo, second: ProjectFooSubclass"))
}
it("generates types.structs") {
expect(generate("Found {{ types.structs.count }} structs, first: {{ types.structs.first.name }}")).to(equal("Found 2 structs, first: Bar"))
}
it("generates types.enums") {
expect(generate("Found {{ types.enums.count }} enums, first: {{ types.enums.first.name }}")).to(equal("Found 2 enums, first: FooOptions"))
}
it("feeds types.implementing specific protocol") {
expect(generate("Found {{ types.implementing.KnownProtocol.count }} types")).to(equal("Found 8 types"))
expect(generate("Found {{ types.implementing.Decodable.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.implementing.Foo.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.implementing.NSObject.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.implementing.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types"))
}
it("feeds types.inheriting specific class") {
expect(generate("Found {{ types.inheriting.KnownProtocol.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.inheriting.Decodable.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.inheriting.Foo.count }} types")).to(equal("Found 2 types"))
expect(generate("Found {{ types.inheriting.NSObject.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("Found {{ types.inheriting.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types"))
}
it("feeds types.based specific type or protocol") {
expect(generate("Found {{ types.based.KnownProtocol.count }} types")).to(equal("Found 8 types"))
expect(generate("Found {{ types.based.Decodable.count }} types")).to(equal("Found 4 types"))
expect(generate("Found {{ types.based.Foo.count }} types")).to(equal("Found 2 types"))
expect(generate("Found {{ types.based.NSObject.count }} types")).to(equal("Found 3 types"))
expect(generate("Found {{ types.based.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types"))
expect(generate("{{ types.all|implements:\"KnownProtocol\"|count }}")).to(equal("7"))
expect(generate("{{ types.all|inherits:\"Foo\"|count }}")).to(equal("2"))
expect(generate("{{ types.all|based:\"Decodable\"|count }}")).to(equal("4"))
}
describe("accessing specific type via type.Typename") {
it("can render accessLevel") {
expect(generate("{{ type.Complex.accessLevel }}")).to(equal("public"))
}
it("can access supertype") {
expect(generate("{{ type.FooSubclass.supertype.name }}")).to(equal("Foo"))
}
it("counts all variables including implements, inherits") {
expect(generate("{{ type.ProjectFooSubclass.allVariables.count }}")).to(equal("2"))
}
it("can use annotations filter") {
expect(generate("{% for type in types.all|annotated:\"bar\" %}{{ type.name }}{% endfor %}")).to(equal("Bar"))
expect(generate("{% for type in types.all|annotated:\"foo = 2\" %}{{ type.name }}{% endfor %}")).to(equal("FooSubclass"))
}
it("can use filter on variables") {
expect(generate("{{ type.Complex.allVariables|computed|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.allVariables|stored|count }}")).to(equal("3"))
expect(generate("{{ type.Complex.allVariables|instance|count }}")).to(equal("4"))
expect(generate("{{ type.Complex.allVariables|static|count }}")).to(equal("0"))
expect(generate("{{ type.Complex.allVariables|tuple|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.allVariables|implements:\"KnownProtocol\"|count }}")).to(equal("2"))
expect(generate("{{ type.Complex.allVariables|based:\"Decodable\"|count }}")).to(equal("2"))
expect(generate("{{ type.Complex.allVariables|inherits:\"NSObject\"|count }}")).to(equal("0"))
}
it("can use filter on methods") {
expect(generate("{{ type.Complex.allMethods|instance|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.allMethods|class|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.allMethods|static|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.allMethods|initializer|count }}")).to(equal("0"))
expect(generate("{{ type.Complex.allMethods|count }}")).to(equal("3"))
}
it("can use access level filter on type") {
expect(generate("{{ types.all|public|count }}")).to(equal("3"))
expect(generate("{{ types.all|open|count }}")).to(equal("1"))
expect(generate("{{ types.all|!private|!fileprivate|!internal|count }}")).to(equal("4"))
}
it("can use access level filter on method") {
expect(generate("{{ type.Complex.methods|public|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.methods|private|count }}")).to(equal("0"))
expect(generate("{{ type.Complex.methods|internal|count }}")).to(equal("2"))
}
it("can use access level filter on variable") {
expect(generate("{{ type.Complex.variables|publicGet|count }}")).to(equal("2"))
expect(generate("{{ type.Complex.variables|publicSet|count }}")).to(equal("1"))
expect(generate("{{ type.Complex.variables|privateSet|count }}")).to(equal("1"))
}
context("given tuple variable") {
it("can access tuple elements") {
expect(generate("{% for var in type.Complex.allVariables|tuple %}{% for e in var.typeName.tuple.elements %}{{ e.typeName.name }},{% endfor %}{% endfor %}")).to(equal("Int,Bar,"))
}
it("can access tuple element type metadata") {
expect(generate("{% for var in type.Complex.allVariables|tuple %}{% for e in var.typeName.tuple.elements|implements:\"KnownProtocol\" %}{{ e.type.name }},{% endfor %}{% endfor %}")).to(equal("Bar,"))
}
}
it("generates type.TypeName") {
expect(generate("{{ type.Foo.name }} has {{ type.Foo.variables.first.name }} variable")).to(equal("Foo has intValue variable"))
}
it("generates contained types properly, type.ParentType.ContainedType properly") {
expect(generate("{{ type.Options.InnerOptions.variables.count }} variable")).to(equal("1 variable"))
}
it("generates enum properly") {
expect(generate("{% for case in type.Options.cases %} {{ case.name }} {% endfor %}")).to(equal(" optionA optionB "))
}
it("classifies computed properties properly") {
expect(generate("{{ type.Complex.variables.count }}, {{ type.Complex.computedVariables.count }}, {{ type.Complex.storedVariables.count }}")).to(equal("4, 1, 3"))
}
it("can access variable type information") {
expect(generate("{% for variable in type.Complex.variables %}{{ variable.type.name }}{% endfor %}")).to(equal("FooBar"))
}
it("can render variable isOptional") {
expect(generate("{{ type.Complex.variables.first.isOptional }}")).to(equal("0"))
}
it("generates proper response for type.inherits") {
expect(generate("{% if type.Foo.inherits.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Foo.inherits.Decodable %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Foo.inherits.KnownProtocol %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Foo.inherits.AlternativeProtocol %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.inherits.Foo %} TRUE {% endif %}")).to(equal(" TRUE "))
}
it("generates proper response for type.implements") {
expect(generate("{% if type.Bar.implements.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Bar.implements.Decodable %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Bar.implements.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.implements.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.implements.AlternativeProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
}
it("generates proper response for type.based") {
expect(generate("{% if type.Bar.based.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE "))
expect(generate("{% if type.Bar.based.Decodable %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.Bar.based.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.based.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.based.Foo %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.based.Decodable %} TRUE {% endif %}")).to(equal(" TRUE "))
expect(generate("{% if type.ProjectFooSubclass.based.AlternativeProtocol %} TRUE {% endif %}")).to(equal(" TRUE "))
}
}
context("given additional arguments") {
it("can reflect them") {
expect(generate("{{ argument.some }}")).to(equal("value"))
}
it("parses numbers correctly") {
expect(generate("{% if argument.number > 2 %}TRUE{% endif %}")).to(equal("TRUE"))
}
}
}
}
}
| 63.355102 | 223 | 0.552055 |
f4961f327ba862230a3f12d1e62cf9e264c86f36 | 3,406 | //
// HTTPService.swift
// Morty
//
// Created by George Kye on 2019-07-03.
// Copyright © 2019 georgekye. All rights reserved.
//
import Foundation
public struct HTTPService: HTTPServiceType {
enum HTTPMethod: String {
case GET
case POST
}
public init() {}
}
private extension HTTPService {
func request(_ method: HTTPMethod, url: String, parameters: [String : Any], headers: [String : String]?, completion: @escaping (Result<NetworkModels.DataResponse, NetworkError>) -> Void) {
guard let requestURL = URL(string: url) else {
return DispatchQueue.main.async {
print("Error: Invalid URL = \(url))")
completion(.failure(NetworkError(statusCode: 0)))
}
}
var request = URLRequest(url: requestURL)
switch method {
case .GET:
request = URLRequest(
url: requestURL.appendingQueryItems(parameters)
)
case .POST:
request = URLRequest(url: requestURL)
do {
let body = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
request.httpBody = body
} catch {
DispatchQueue.main.async {
completion(.failure(
NetworkError(
urlRequest: request,
statusCode: 0,
internalError: error
))
)
}
}
}
request.httpMethod = method.rawValue
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let data_ = data,
let response_ = response as? HTTPURLResponse else {
return DispatchQueue.main.async {
let err = NetworkError(
urlRequest: request,
statusCode: (response as? HTTPURLResponse)?.statusCode ?? 0,
headerValues: [:],
serverData: data,
internalError: error
)
completion(.failure(err))
}
}
completion(.success(
NetworkModels.DataResponse(
data: data_,
headers: [:], //TODO:
statusCode: response_.statusCode))
)
}
}
task.resume()
}
}
public extension HTTPService {
func get(url: String, parameters: [String : Any], headers: [String : String]?, completion: @escaping (Result<NetworkModels.DataResponse, NetworkError>) -> Void) {
request(.GET, url: url, parameters: parameters, headers: headers) {
completion($0)
}
}
func post(url: String, parameters: [String : Any], headers: [String : String]?, completion: @escaping (Result<NetworkModels.DataResponse, NetworkError>) -> Void) {
request(.POST, url: url, parameters: parameters, headers: headers) {
completion($0)
}
}
}
| 33.392157 | 192 | 0.487375 |
4bb3dc8c532c538d1c0fddd8ededaee09ced9a0b | 11,675 | //
// SumChain3CollectionIndex.swift
//
import Foundation
import HDXLCommonUtilities
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Definition
// -------------------------------------------------------------------------- //
@frozen
public struct SumChain3CollectionIndex<
A:Collection,
B:Collection,
C:Collection> {
@usableFromInline
internal typealias Storage = SumChain3CollectionIndexStorage<A,B,C>
@usableFromInline
internal typealias Position = Storage.Position
@usableFromInline
internal var storage: Storage
@inlinable
internal init(storage: Storage) {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(storage.isValid)
defer { pedantic_assert(storage.isValid) }
// /////////////////////////////////////////////////////////////////////////
self.storage = storage
}
@inlinable
internal init(position: Position) {
self.init(
storage: .position(position)
)
}
@inlinable
internal static var endIndex: SumChain3CollectionIndex<A,B,C> {
get {
return SumChain3CollectionIndex<A,B,C>(
storage: .end
)
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Componentwise Constructors
// -------------------------------------------------------------------------- //
internal extension SumChain3CollectionIndex {
@inlinable
init(a: A.Index) {
self.init(position: .a(a))
}
@inlinable
init(b: B.Index) {
self.init(position: .b(b))
}
@inlinable
init(c: C.Index) {
self.init(position: .c(c))
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Reflection Support
// -------------------------------------------------------------------------- //
internal extension SumChain3CollectionIndex {
@inlinable
static var shortTypeName: String {
get {
return "SumChain3CollectionIndex"
}
}
@inlinable
static var completeTypeName: String {
get {
return "\(self.shortTypeName)<\(self.typeParameterNames)>"
}
}
@inlinable
static var typeParameterNames: String {
get {
return [
String(reflecting: A.self),
String(reflecting: B.self),
String(reflecting: C.self)
].joined(separator: ", ")
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Validatable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndex : Validatable {
@inlinable
public var isValid: Bool {
get {
return self.storage.isValid
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Equatable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndex : Equatable {
@inlinable
public static func ==(
lhs: SumChain3CollectionIndex<A,B,C>,
rhs: SumChain3CollectionIndex<A,B,C>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage == rhs.storage
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - Comparable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndex : Comparable {
@inlinable
public static func <(
lhs: SumChain3CollectionIndex<A,B,C>,
rhs: SumChain3CollectionIndex<A,B,C>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage < rhs.storage
}
@inlinable
public static func >(
lhs: SumChain3CollectionIndex<A,B,C>,
rhs: SumChain3CollectionIndex<A,B,C>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage > rhs.storage
}
@inlinable
public static func <=(
lhs: SumChain3CollectionIndex<A,B,C>,
rhs: SumChain3CollectionIndex<A,B,C>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage <= rhs.storage
}
@inlinable
public static func >=(
lhs: SumChain3CollectionIndex<A,B,C>,
rhs: SumChain3CollectionIndex<A,B,C>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage >= rhs.storage
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - CustomStringConvertible
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndex : CustomStringConvertible {
@inlinable
public var description: String {
get {
return self.storage.description
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndex - CustomStringConvertible
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndex : CustomDebugStringConvertible {
@inlinable
public var debugDescription: String {
get {
return "\(type(of: self).completeTypeName)(storage: \(String(reflecting: self.storage)))"
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - Definition
// -------------------------------------------------------------------------- //
@usableFromInline
internal enum SumChain3CollectionIndexStorage<
A:Collection,
B:Collection,
C:Collection> {
@usableFromInline
internal typealias Position = Sum3<A.Index,B.Index,C.Index>
case position(Position)
case end
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - Reflection Support
// -------------------------------------------------------------------------- //
internal extension SumChain3CollectionIndexStorage {
@inlinable
static var shortTypeName: String {
get {
return "SumChain3CollectionIndexStorage"
}
}
@inlinable
static var completeTypeName: String {
get {
return "\(self.shortTypeName)<\(self.typeParameterNames)>"
}
}
@inlinable
static var typeParameterNames: String {
get {
return [
String(reflecting: A.self),
String(reflecting: B.self),
String(reflecting: C.self)
].joined(separator: ", ")
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - Validatable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndexStorage : Validatable {
@inlinable
internal var isValid: Bool {
get {
switch self {
case .position(let position):
return position.isValid
case .end:
return true
}
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - Equatable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndexStorage : Equatable {
@inlinable
internal static func ==(
lhs: SumChain3CollectionIndexStorage<A,B,C>,
rhs: SumChain3CollectionIndexStorage<A,B,C>) -> Bool {
switch (lhs, rhs) {
case (.position(let l), .position(let r)):
return l == r
case (.end, .end):
return true
default:
return false
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - Comparable
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndexStorage : Comparable {
@inlinable
internal static func <(
lhs: SumChain3CollectionIndexStorage<A,B,C>,
rhs: SumChain3CollectionIndexStorage<A,B,C>) -> Bool {
switch (lhs, rhs) {
case (.position(let l), .position(let r)):
return l.isPseudoLessThan(r)
case (.position(_), .end):
return true
case (.end, .position(_)):
return false
case (.end, .end):
return false
}
}
@inlinable
internal static func >(
lhs: SumChain3CollectionIndexStorage<A,B,C>,
rhs: SumChain3CollectionIndexStorage<A,B,C>) -> Bool {
switch (lhs, rhs) {
case (.position(let l), .position(let r)):
return l.isPseudoGreaterThan(r)
case (.position(_), .end):
return false
case (.end, .position(_)):
return true
case (.end, .end):
return false
}
}
@inlinable
internal static func <=(
lhs: SumChain3CollectionIndexStorage<A,B,C>,
rhs: SumChain3CollectionIndexStorage<A,B,C>) -> Bool {
switch (lhs, rhs) {
case (.position(let l), .position(let r)):
return l.isPseudoLessThanOrEqual(r)
case (.position(_), .end):
return true
case (.end, .position(_)):
return false
case (.end, .end):
return true
}
}
@inlinable
internal static func >=(
lhs: SumChain3CollectionIndexStorage<A,B,C>,
rhs: SumChain3CollectionIndexStorage<A,B,C>) -> Bool {
switch (lhs, rhs) {
case (.position(let l), .position(let r)):
return l.isPseudoGreaterThanOrEqual(r)
case (.position(_), .end):
return false
case (.end, .position(_)):
return true
case (.end, .end):
return true
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - CustomStringConvertible
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndexStorage : CustomStringConvertible {
@inlinable
internal var description: String {
get {
switch self {
case .position(let position):
return ".position(\(String(describing: position)))"
case .end:
return ".end"
}
}
}
}
// -------------------------------------------------------------------------- //
// MARK: SumChain3CollectionIndexStorage - CustomDebugStringConvertible
// -------------------------------------------------------------------------- //
extension SumChain3CollectionIndexStorage : CustomDebugStringConvertible {
@inlinable
internal var debugDescription: String {
get {
switch self {
case .position(let position):
return "\(type(of: self).completeTypeName).position(\(String(reflecting: position)))"
case .end:
return "\(type(of: self).completeTypeName).end"
}
}
}
}
| 27.214452 | 95 | 0.471006 |
f792608ca2b42e82c0d7f977beef837523ced5b2 | 582 | //
// ViewController.swift
// weatherLUtility
//
// Created by amanK1n on 02/18/2022.
// Copyright (c) 2022 amanK1n. All rights reserved.
//
import UIKit
import weatherLUtility
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let location = LocationViewModel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.068966 | 80 | 0.670103 |
bb4db8089d05f8bf0e89c3c0786cb1f6eadcc186 | 1,293 | //
// AndesTagLeftContentIconView.swift
// AndesUI
//
// Created by Samuel Sainz on 6/4/20.
//
import Foundation
class AndesTagLeftContentIconView: UIView {
private var icon: UIImage?
private var iconColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
convenience init(backgroundColor: UIColor, icon: UIImage, iconColor: UIColor) {
self.init()
self.backgroundColor = backgroundColor
self.icon = icon
self.iconColor = iconColor
setupView()
}
func setupView() {
guard let icon = self.icon, let iconColor = self.iconColor else {
return
}
let imageView = UIImageView(image: icon)
imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = iconColor
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 24).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 24).isActive = true
imageView.contentMode = .center
self.addSubview(imageView)
imageView.pinToSuperview(top: 0, left: 0, bottom: 0, right: 0)
}
}
| 28.108696 | 83 | 0.66048 |
014bfad7a866416b4aad2135752b295150ac8bbe | 2,433 | import Foundation
class SynchronizedDictionary<KeyType: Hashable, ValueType> {
private var dictionary: [KeyType: ValueType] = [:]
private let queue = DispatchQueue(label: "SynchronizedDictionaryAccess", attributes: .concurrent)
subscript(key: KeyType) -> ValueType? {
set {
queue.async(flags: .barrier) {
self.dictionary[key] = newValue
}
}
get {
queue.sync {
dictionary[key]
}
}
}
var rawDictionary: [KeyType: ValueType] {
set {
queue.async(flags: .barrier) {
self.dictionary = newValue
}
}
get {
queue.sync {
dictionary
}
}
}
func removeValue(forKey key: KeyType) {
queue.async(flags: .barrier) {
self.dictionary.removeValue(forKey: key)
}
}
}
public class SynchronizedArray<T> {
private var array: [T] = []
private let accessQueue = DispatchQueue(label: "SynchronizedArrayAccess", attributes: .concurrent)
public func append(_ newElement: T) {
self.accessQueue.async(flags:.barrier) {
self.array.append(newElement)
}
}
public func removeAtIndex(index: Int) {
self.accessQueue.async(flags:.barrier) {
self.array.remove(at: index)
}
}
public var count: Int {
var count = 0
self.accessQueue.sync {
count = self.array.count
}
return count
}
public func first() -> T? {
var element: T?
self.accessQueue.sync {
if !self.array.isEmpty {
element = self.array[0]
}
}
return element
}
public subscript(index: Int) -> T {
set {
self.accessQueue.async(flags:.barrier) {
self.array[index] = newValue
}
}
get {
var element: T!
self.accessQueue.sync {
element = self.array[index]
}
return element
}
}
func forEach(_ body: (T) -> ()) {
self.accessQueue.sync {
array.forEach { value in
body(value)
}
}
}
func filter(_ isIncluded: (T) -> Bool) -> [T] {
return array.filter { value in isIncluded(value) }
}
} | 22.321101 | 102 | 0.501028 |
46e79d31f031b5d3076cf60733872e064ba7bb90 | 2,973 | //
// UBHistorySettings.swift
// UBHistory
//
// Created by Usemobile on 08/03/19.
//
import Foundation
public enum HistoryLanguage: String {
case en = "en-US"
case pt = "pt-BR"
case es = "es-BO"
}
var currentLanguage: HistoryLanguage = .pt
public class UBHistorySettings {
public var language: HistoryLanguage = .pt {
didSet {
currentLanguage = language
}
}
public var mainColor: UIColor
public var lottieName: String
public var hasRefresh: Bool
public var hasInfiniteScroll: Bool
public var isUserApp: Bool
public var leftViewSettings: LeftViewSettings
public var rightViewSettings: RightViewSettings
public var historyDetailsSettings: HistoryDetailsSettings
public var segmentedSettings: SegmentedSettings
public var scheduleLeftViewSettings: ScheduleLeftViewSettings
public var emptyImage: UIImage?
public var emptyFont: UIFont
public var closeImage: UIImage?
public var closeColor: UIColor
public var retryTitleColor: UIColor = .white
public var retryFont: UIFont = .systemFont(ofSize: 18, weight: .medium)
public var forceTouchEnabled = false
public var hasPaymentInfos = true {
didSet {
self.historyDetailsSettings.hasPaymentInfos = self.hasPaymentInfos
}
}
public var hasSchedules: Bool = false
public static var `default`: UBHistorySettings {
return UBHistorySettings(mainColor: .mainColor, lottieName: "loading")
}
public init(mainColor: UIColor, lottieName: String, hasRefresh: Bool = true, hasInfiniteScroll: Bool = true, isUserApp: Bool = true, emptyImage: UIImage? = nil, emptyFont: UIFont = .systemFont(ofSize: 20), closeImage: UIImage? = nil, closeColor: UIColor = .white, retryTitleColor: UIColor = .white, leftViewSettings: LeftViewSettings = .default, rightViewSettings: RightViewSettings = .default, historyDetailsSettings: HistoryDetailsSettings = .default, segmentedSettings: SegmentedSettings = .default, scheduleLeftViewSettings: ScheduleLeftViewSettings = .default) {
self.mainColor = mainColor
self.lottieName = lottieName
self.hasRefresh = hasRefresh
self.hasInfiniteScroll = hasInfiniteScroll
self.isUserApp = isUserApp
self.emptyImage = emptyImage
self.emptyFont = emptyFont
self.closeImage = closeImage
self.closeColor = closeColor
// self.retryTitleColor = retryTitleColor
// self.retryFont = retryFont
self.leftViewSettings = leftViewSettings
self.rightViewSettings = rightViewSettings
self.historyDetailsSettings = historyDetailsSettings
self.historyDetailsSettings.hasPaymentInfos = self.hasPaymentInfos
self.segmentedSettings = segmentedSettings
self.segmentedSettings.backgroundColor = mainColor
self.scheduleLeftViewSettings = scheduleLeftViewSettings
}
}
| 38.115385 | 571 | 0.711066 |
46210eee2163dc1e046eb33c154e176a012c398f | 2,605 | //
// HTMLRender.swift
// TestSummaries
//
// Created by Kazuya Ueoka on 2018/04/24.
//
import Foundation
struct HTMLRender: TestSummariesRenderable {
var testSummaries: [TestSummaries]
var paths: [String]
var backgroundColor: String
var textColor: String
private func convertColor(with text: String) -> String {
if text.hasPrefix("#") {
return text
} else {
return "#" + text
}
}
/// convert testSummaries to HTML
///
/// - Returns: String
func toHTML() -> String {
var result: String = HTMLTemplates.html
result = result.replacingOccurrences(of: "${backgroundColor}", with: convertColor(with: backgroundColor))
result = result.replacingOccurrences(of: "${textColor}", with: convertColor(with: textColor))
let attachments: [String] = zip(testSummaries, paths).map({ item -> String in
let testSummary = item.0
let path = item.1
let fileName = path.components(separatedBy: "/").last ?? ""
var template = HTMLTemplates.attachments
template = template.replacingOccurrences(of: "${filename}", with: fileName)
let attachments: [AttachmentWithParent] = testSummary.attachments
let attachmentItems: [String] = attachments.map({ (attachment) -> String in
var item = HTMLTemplates.attachmentItem
item = item.replacingOccurrences(of: "${path}", with: path)
item = item.replacingOccurrences(of: "${fileName}", with: attachment.attachment.fileName)
item = item.replacingOccurrences(of: "${title}", with: attachment.parent.testIdentifier)
return item
})
template = template.replacingOccurrences(of: "${attachmentItem}", with: attachmentItems.joined())
return template
})
result = result.replacingOccurrences(of: "${attachments}", with: attachments.joined())
return result
}
/// write HTML to path
///
/// - Parameter path: String
/// - Throws: Error
func writeTo(path: String) throws {
var html = toHTML()
let directoryPath = path.components(separatedBy: "/").dropLast().joined(separator: "/")
html = html.replacingOccurrences(of: directoryPath, with: ".")
let data = html.data(using: .utf8)!
try data.write(to: URL(fileURLWithPath: path))
}
}
| 33.397436 | 113 | 0.577735 |
5b082dc2c2e0dd871c7ae16ba90c13df90b84cc0 | 2,182 | //
// PreferencesStorage.swift
// Go Cycling
//
// Created by Anthony Hopkins on 2021-04-18.
//
import Foundation
import CoreData
class PreferencesStorage: NSObject, ObservableObject {
@Published var storedPreferences: [UserPreferences] = []
private let preferencesController: NSFetchedResultsController<UserPreferences>
init(managedObjectContext: NSManagedObjectContext) {
preferencesController = NSFetchedResultsController(fetchRequest: UserPreferences.savedPreferencesFetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: nil, cacheName: nil)
super.init()
preferencesController.delegate = self
do {
try preferencesController.performFetch()
if (preferencesController.fetchedObjects?.count ?? 0 < 1) {
// Default values for the user preferences
let defaultPreferences = UserPreferences(context: managedObjectContext)
defaultPreferences.usingMetric = true
defaultPreferences.displayingMetrics = true
defaultPreferences.largeMetrics = false
defaultPreferences.colourChoice = ColourChoice.blue.rawValue
defaultPreferences.sortingChoice = SortChoice.dateDescending.rawValue
defaultPreferences.deletionConfirmation = true
defaultPreferences.deletionEnabled = true
defaultPreferences.iconIndex = 0
defaultPreferences.namedRoutes = true
defaultPreferences.selectedRoute = ""
storedPreferences = [defaultPreferences]
}
else {
storedPreferences = preferencesController.fetchedObjects!
}
} catch {
print("Failed to fetch items!")
}
}
}
extension PreferencesStorage: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard let savedPreferences = controller.fetchedObjects as? [UserPreferences]
else { return }
storedPreferences = savedPreferences
}
}
| 36.983051 | 118 | 0.673694 |
5006cd912801808b6ccc3f72d78e7f174beaade5 | 2,763 | //
// SceneDelegate.swift
// I Am Rich
//
// Created by Rafael Plinio on 29/10/19.
// Copyright © 2019 Rafael Plinio. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.507692 | 147 | 0.705393 |
e540ed823a555ad5aa90c9dcdc066d100472dedb | 12,411 | //
// Copyright © 2019 Swinject Contributors. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable import Swinject
class AssemblerSpec: QuickSpec {
override func spec() {
describe("Assembler basic init") {
it("can assembly a single container") {
let assembler = Assembler([
AnimalAssembly(),
])
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
}
it("can assembly a container with nil parent") {
let assembler = Assembler(parentAssembler: nil)
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
}
it("can assembly a container with nil parent and assemblies") {
let assembler = Assembler([
AnimalAssembly(),
], parent: nil)
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
}
it("uses injected default object scope") {
let assembler = Assembler([], parent: nil, defaultObjectScope: ObjectScope.container)
assembler.apply(assembly: ContainerSpyAssembly())
let container = assembler.resolver.resolve(Container.self)
let serviceEntry = container?.register(Animal.self) { _ in Siamese(name: "Siam") }
expect(serviceEntry?.objectScope) === ObjectScope.container
}
it("uses graph scope if no default object scope is injected") {
let assembler = Assembler([], parent: nil)
assembler.apply(assembly: ContainerSpyAssembly())
let container = assembler.resolver.resolve(Container.self)
let serviceEntry = container?.register(Animal.self) { _ in Siamese(name: "Siam") }
expect(serviceEntry?.objectScope) === ObjectScope.graph
}
it("can assembly a multiple container") {
let assembler = Assembler([
AnimalAssembly(),
FoodAssembly(),
])
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
it("can assembly a multiple container with inter dependencies") {
let assembler = Assembler([
AnimalAssembly(),
FoodAssembly(),
PersonAssembly(),
])
let petOwner = assembler.resolver.resolve(PetOwner.self)
expect(petOwner).toNot(beNil())
let cat = petOwner!.pet
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = petOwner!.favoriteFood
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
it("can assembly a multiple container with inter dependencies in any order") {
let assembler = Assembler([
PersonAssembly(),
AnimalAssembly(),
FoodAssembly(),
])
let petOwner = assembler.resolver.resolve(PetOwner.self)
expect(petOwner).toNot(beNil())
let cat = petOwner!.pet
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = petOwner!.favoriteFood
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
}
describe("Assembler lazy build") {
it("can assembly a single container") {
let assembler = Assembler([])
var cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
assembler.apply(assembly: AnimalAssembly())
cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
}
it("can assembly a single load aware container") {
let assembler = Assembler([])
var cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
let loadAwareAssembly = LoadAwareAssembly { resolver in
let cat = resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
expect(loadAwareAssembly.loaded) == false
assembler.apply(assembly: loadAwareAssembly)
expect(loadAwareAssembly.loaded) == true
cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
it("can assembly a multiple containers 1 by 1") {
let assembler = Assembler([])
var cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
var sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
assembler.apply(assembly: AnimalAssembly())
cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
assembler.apply(assembly: FoodAssembly())
sushi = assembler.resolver.resolve(Food.self)
expect(sushi).toNot(beNil())
}
it("can assembly a multiple containers at once") {
let assembler = Assembler([])
var cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
var sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
assembler.apply(assemblies: [
AnimalAssembly(),
FoodAssembly(),
])
cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
sushi = assembler.resolver.resolve(Food.self)
expect(sushi).toNot(beNil())
}
}
describe("Assembler load aware") {
it("can assembly a single container") {
let loadAwareAssembly = LoadAwareAssembly { resolver in
let cat = resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
expect(loadAwareAssembly.loaded) == false
let assembler = Assembler([
loadAwareAssembly,
])
expect(loadAwareAssembly.loaded) == true
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
it("can assembly a multiple container") {
let loadAwareAssembly = LoadAwareAssembly { resolver in
let cat = resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
let sushi = resolver.resolve(Food.self)
expect(sushi).toNot(beNil())
}
expect(loadAwareAssembly.loaded) == false
let assembler = Assembler([
loadAwareAssembly,
FoodAssembly(),
])
expect(loadAwareAssembly.loaded) == true
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).toNot(beNil())
}
}
describe("Empty Assembler") {
it("can create an empty assembler and build it") {
let assembler = Assembler()
var cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
assembler.apply(assembly: AnimalAssembly())
cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
}
}
describe("Child Assembler") {
it("can be empty") {
let assembler = Assembler([
AnimalAssembly(),
])
let childAssembler = Assembler(parentAssembler: assembler)
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).toNot(beNil())
let sushi = assembler.resolver.resolve(Food.self)
expect(sushi).to(beNil())
let childCat = childAssembler.resolver.resolve(Animal.self)
expect(childCat).toNot(beNil())
let childSushi = childAssembler.resolver.resolve(Food.self)
expect(childSushi).to(beNil())
}
it("can't give entities to parent") {
let assembler = Assembler()
let childAssembler = Assembler([
AnimalAssembly(),
], parent: assembler)
let cat = assembler.resolver.resolve(Animal.self)
expect(cat).to(beNil())
let childCat = childAssembler.resolver.resolve(Animal.self)
expect(childCat).toNot(beNil())
}
it("uses injected default object scope") {
let parentContainer = Container()
let parentAssembler = Assembler(container: parentContainer)
let childAssembler = Assembler(parentAssembler: parentAssembler,
defaultObjectScope: ObjectScope.container)
childAssembler.apply(assembly: ContainerSpyAssembly())
let container = childAssembler.resolver.resolve(Container.self)
let serviceEntry = container?.register(Animal.self) { _ in Siamese(name: "Siam") }
expect(serviceEntry?.objectScope) === ObjectScope.container
}
it("has default object scope of graph type") {
let parentContainer = Container()
let parentAssembler = Assembler(container: parentContainer)
let childAssembler = Assembler(parentAssembler: parentAssembler)
childAssembler.apply(assembly: ContainerSpyAssembly())
let container = childAssembler.resolver.resolve(Container.self)
let serviceEntry = container?.register(Animal.self) { _ in Siamese(name: "Siam") }
expect(serviceEntry?.objectScope) === ObjectScope.graph
}
it("uses given list of behaviors to container") {
let spy = BehaviorSpy()
let assembler = Assembler(parentAssembler: Assembler(), behaviors: [spy])
assembler.apply(assembly: ContainerSpyAssembly())
expect(spy.entries).to(haveCount(1))
}
it("uses given list of behaviors before applying assemblies") {
let spy = BehaviorSpy()
_ = Assembler([ContainerSpyAssembly()], parent: Assembler(), behaviors: [spy])
expect(spy.entries).to(haveCount(1))
}
}
}
}
| 37.609091 | 101 | 0.519942 |
5bb0e2e92a1a1e0aad2db8c3179d372facff0bf8 | 9,481 | //
// Tokenizer.swift
// Tokenizer
//
// Created by Ulf Akerstedt-Inoue on 2019/01/08.
//
import Foundation
public class Tokenizer: Sequence, IteratorProtocol {
public enum ContextDependent {
case none
case binary
case decimal
case octal
case hexadecimal
}
public enum IdentifierKind {
case char
case string
}
struct TokenBuffer {
var tokens: [Token?] = []
var index = 0
}
private var buffer: TokenBuffer = TokenBuffer()
public var contextDependent: ContextDependent = .none
fileprivate var characters: UnicodeScalarView
fileprivate var trie: Trie = Trie()
private(set) var filterComments: Bool = false
private(set) var symbols = Set<String>(arrayLiteral: "'", "\"", "//", "/*", "*/")
private(set) var keywords = Set<String>()
private(set) var identifierKind: IdentifierKind = .string
public init(source: String,
buffer size: Int = 5,
filterComments filter: Bool = false,
symbols: Set<String>,
keywords: Set<String>,
identifier: IdentifierKind = .string)
{
buffer = TokenBuffer(tokens: Array(repeating: .none, count: size))
characters = UnicodeScalarView(source.unicodeScalars)
self.filterComments = filter
self.symbols.formUnion(Set(symbols))
self.keywords = Set(keywords)
self.identifierKind = identifier
// Insert all character-based symbols into the Trie.
self.symbols.forEach { trie.insert(word: $0) }
// prefill buffer
for _ in 1...buffer.tokens.count { updateBuffer() }
// start condition
assert(buffer.index == 0)
}
// Generates an array of tokens from a source string.
public func tokenize() -> [Token] {
var tokens: [Token] = []
while let token = next() {
if case .comment(_) = token { if filterComments { continue } }
tokens.append(token)
}
if !self.characters.isEmpty {
tokens.append(.invalid(.unrecognizedInput(String(characters))))
}
return tokens
}
/// Create an iterator.
public func makeIterator() -> Tokenizer {
return self
}
/// Return a single token, or nil.
public func next() -> Token? {
let token = buffer.tokens[buffer.index]
updateBuffer()
return token
}
private func nextToken() -> Token? {
// Skip all irrelevant characters until we find something.
characters.skipWhitespace()
// Match any symbol as long as possible (munch principle).
guard let char = characters.first else { return nil }
let munchNode = trie.walkSequence(for: Character(char)) { (node) in
if self.characters.isEmpty == false {
self.characters.removeFirst()
return self.characters.first != nil ? Character(self.characters.first!) : nil
} else {
return nil
}
}
// Remaining character(s) may contain literals, keywords or comments.
if let symbol = munchNode.word {
switch symbol {
case "'": return characters.parseLiteral(until: "'")
case "\"": return characters.parseLiteral(until: "\"")
case "//": return characters.parseLineComment()
case "/*": return characters.parseBlockComment(match: "*/")
case "*/": fatalError("multiline comment illformed")
default:
return .symbol(symbol)
}
} else { // From here on we parse identifiers or numbers.
if let scalar = characters.first, CharacterSet.alphanumerics.contains(scalar) {
switch contextDependent {
case .none:
switch identifierKind {
case .char:
if let ch = self.characters.readCharacter(where: { CharacterSet.letters.contains($0) } ) {
return .char(Character(ch))
} else {
if let number = self.characters.readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9")
}) {
return .number(.decimal(number.integerValue ?? 0))
}
}
case .string:
if CharacterSet.letters.contains(scalar) {
return characters.parseIdentifier(keywords: self.keywords)
} else {
if let number = self.characters.readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9")
}) {
return .number(.decimal(number.integerValue ?? 0))
}
}
}
case .binary:
if let number = self.characters.readCharacters(where: {
$0 == UnicodeScalar("0") || $0 == UnicodeScalar("1")
}) {
return .number(.binary(Int(number.binaryValue ?? 0)))
}
case .decimal:
if let number = self.characters.readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9")
}) {
return .number(.decimal(number.integerValue ?? 0))
}
case .octal:
if let number = self.characters.readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9")
}) {
return .number(.octal(number.octalValue ?? 0))
}
case .hexadecimal:
if let number = self.characters.readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9") ||
$0 >= UnicodeScalar("A") && $0 <= UnicodeScalar("F") ||
$0 >= UnicodeScalar("a") && $0 <= UnicodeScalar("f")
}) {
return .number(.octal(number.octalValue ?? 0))
}
}
}
}
return nil
}
/// Returns true if input string has been processed.
public var isEmpty: Bool {
return characters.isEmpty
}
/// Consumes one token from the buffer of tokens.
public func consume() {
updateBuffer()
}
/// Peek at current character for a symbol match.
public func peek(ahead n: Int) -> Token? {
assert((n>0) && n < buffer.tokens.count)
return buffer.tokens[(buffer.index+n-1) % buffer.tokens.count]
}
// Fills current slot with next token and increments current index.
private func updateBuffer() {
buffer.tokens[buffer.index] = nextToken()
buffer.index = (buffer.index+1) % buffer.tokens.count
}
}
extension UnicodeScalarView {
/// Read characters until any newline character is matched.
mutating func parseLineComment() -> Token? {
return readCharacters(where: {
!CharacterSet.newlines.contains($0)
})
.map { .comment($0) }
}
/// Read characters until closing comment marker '*/' character is matched.
/// Small bug: Character following a `*` is never copied when the comment match
/// fails.
mutating func parseBlockComment(match symbol: String) -> Token? {
let start = self
var string = ""
while let scalar = self.popFirst() {
if scalar == "*" {
if let next = self.popFirst(), next == "/" {
return .comment(string)
}
}
string.append(Character(scalar))
}
self = start
return nil
}
mutating func parseLiteral(until terminator: Unicode.Scalar) -> Token? {
var string = ""
while let scalar = self.popFirst() {
switch scalar {
case terminator:
return .literal(string)
default:
string.append(Character(scalar))
}
}
return .invalid(.unterminatedString)
}
// Parses a token containing any consecutive digit (0-9) characters, or nil
mutating func parseDigit() -> Token? {
return readCharacters(where: {
$0 >= UnicodeScalar("0") && $0 <= UnicodeScalar("9")
})
.map { .number(.decimal($0.integerValue ?? 0)) }
}
// Parses identifier lexically conforming to [A-Za-z] ( [A-Za-z_] | [0-9] )*
mutating func parseIdentifier(keywords: Set<String>) -> Token? {
guard let head = self.first, CharacterSet.letters.contains(head) else { return nil }
var name = String(self.removeFirst())
while let c = self.first, CharacterSet.alphanumerics.contains(c) || c == "_" {
name.append(Character(self.removeFirst()))
}
if keywords.contains(name) {
return .keyword(name)
} else {
return .identifier(name)
}
}
}
| 35.376866 | 114 | 0.516612 |
e8032692aeef5240c6742eef9c4d176529f4c896 | 6,162 | /* Copyright 2018 JDCLOUD.COM
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.
画像单标签输出接口
画像单标签输出接口
OpenAPI spec version: v1
Contact:
NOTE: This class is auto generated by the jdcloud code generator program.
*/
import Foundation
/// regionIndustryDataList
public class RegionIndustryDataList:NSObject,Codable{
/// 查询结果的数组类型
var dataList:[RegionIndustryData?]?
public override init(){
super.init()
}
enum RegionIndustryDataListCodingKeys: String, CodingKey {
case dataList
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: RegionIndustryDataListCodingKeys.self)
if decoderContainer.contains(.dataList)
{
self.dataList = try decoderContainer.decode([RegionIndustryData?]?.self, forKey: .dataList)
}
}
}
public extension RegionIndustryDataList{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: RegionIndustryDataListCodingKeys.self)
try encoderContainer.encode(dataList, forKey: .dataList)
}
}
/// regionIndustryData
public class RegionIndustryData:NSObject,Codable{
/// 区域
var region:String?
/// 行业
var industry:String?
/// 一级指标
var firstIndex:String?
/// 二级指标
var secondIndex:String?
/// 日期
var dateTime:String?
/// 日期类型(月、天)
var dateType:String?
/// 指标数值
var indexValue:String?
/// 数值单位
var valueUnit:String?
/// 属性类别
var attrType:String?
/// 属性值
var attrValue:String?
/// 属性值扩展内容
var attrValueExt:String?
public override init(){
super.init()
}
enum RegionIndustryDataCodingKeys: String, CodingKey {
case region
case industry
case firstIndex
case secondIndex
case dateTime
case dateType
case indexValue
case valueUnit
case attrType
case attrValue
case attrValueExt
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: RegionIndustryDataCodingKeys.self)
if decoderContainer.contains(.region)
{
self.region = try decoderContainer.decode(String?.self, forKey: .region)
}
if decoderContainer.contains(.industry)
{
self.industry = try decoderContainer.decode(String?.self, forKey: .industry)
}
if decoderContainer.contains(.firstIndex)
{
self.firstIndex = try decoderContainer.decode(String?.self, forKey: .firstIndex)
}
if decoderContainer.contains(.secondIndex)
{
self.secondIndex = try decoderContainer.decode(String?.self, forKey: .secondIndex)
}
if decoderContainer.contains(.dateTime)
{
self.dateTime = try decoderContainer.decode(String?.self, forKey: .dateTime)
}
if decoderContainer.contains(.dateType)
{
self.dateType = try decoderContainer.decode(String?.self, forKey: .dateType)
}
if decoderContainer.contains(.indexValue)
{
self.indexValue = try decoderContainer.decode(String?.self, forKey: .indexValue)
}
if decoderContainer.contains(.valueUnit)
{
self.valueUnit = try decoderContainer.decode(String?.self, forKey: .valueUnit)
}
if decoderContainer.contains(.attrType)
{
self.attrType = try decoderContainer.decode(String?.self, forKey: .attrType)
}
if decoderContainer.contains(.attrValue)
{
self.attrValue = try decoderContainer.decode(String?.self, forKey: .attrValue)
}
if decoderContainer.contains(.attrValueExt)
{
self.attrValueExt = try decoderContainer.decode(String?.self, forKey: .attrValueExt)
}
}
}
public extension RegionIndustryData{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: RegionIndustryDataCodingKeys.self)
try encoderContainer.encode(region, forKey: .region)
try encoderContainer.encode(industry, forKey: .industry)
try encoderContainer.encode(firstIndex, forKey: .firstIndex)
try encoderContainer.encode(secondIndex, forKey: .secondIndex)
try encoderContainer.encode(dateTime, forKey: .dateTime)
try encoderContainer.encode(dateType, forKey: .dateType)
try encoderContainer.encode(indexValue, forKey: .indexValue)
try encoderContainer.encode(valueUnit, forKey: .valueUnit)
try encoderContainer.encode(attrType, forKey: .attrType)
try encoderContainer.encode(attrValue, forKey: .attrValue)
try encoderContainer.encode(attrValueExt, forKey: .attrValueExt)
}
}
/// testOpenApiReq
public class TestOpenApiReq:NSObject,Codable{
/// 名字
var name:String?
public override init(){
super.init()
}
enum TestOpenApiReqCodingKeys: String, CodingKey {
case name
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: TestOpenApiReqCodingKeys.self)
if decoderContainer.contains(.name)
{
self.name = try decoderContainer.decode(String?.self, forKey: .name)
}
}
}
public extension TestOpenApiReq{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: TestOpenApiReqCodingKeys.self)
try encoderContainer.encode(name, forKey: .name)
}
}
| 31.438776 | 103 | 0.663908 |
de8e97385c399b95c8277760c4d6e02078b69458 | 1,210 | //
// PersistenceManager.swift
// PodcastApp
//
// Created by Ben Scheirman on 10/18/19.
// Copyright © 2019 NSScreencast. All rights reserved.
//
import Foundation
import CoreData
class PersistenceManager {
static var shared = PersistenceManager()
private let persistentContainer: NSPersistentContainer
private var isLoaded = false
var mainContext: NSManagedObjectContext {
precondition(isLoaded)
return persistentContainer.viewContext
}
func newBackgroundContext() -> NSManagedObjectContext {
precondition(isLoaded)
return persistentContainer.newBackgroundContext()
}
private init() {
persistentContainer = NSPersistentContainer(name: "Subscriptions")
}
func initializeModel(then completion: @escaping () -> Void) {
persistentContainer.loadPersistentStores { (storeDescription, error) in
if let error = error {
fatalError("Core Data error: \(error.localizedDescription)")
} else {
self.isLoaded = true
print("Loaded Store: \(storeDescription.url?.absoluteString ?? "nil")")
completion()
}
}
}
}
| 26.304348 | 87 | 0.649587 |
f917f124ea10017e0892119b0afc3c75dd7218b0 | 5,083 | //
// UIView+ReturnAnchors.swift
// SBPWidget
//
// Created by Mykola Hordynchuk on 6/9/19.
// Copyright © 2019 Mykola Hordynchuk. All rights reserved.
//
import UIKit
extension UIView {
func _anchorTop(_ top: NSLayoutYAxisAnchor, _ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = topAnchor.constraint(greaterThanOrEqualTo: top, constant: constant)
case .lessThanOrEqual:
anchor = topAnchor.constraint(lessThanOrEqualTo: top, constant: constant)
default:
anchor = topAnchor.constraint(equalTo: top, constant: constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorBottom(_ bottom: NSLayoutYAxisAnchor, _ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = bottomAnchor.constraint(greaterThanOrEqualTo: bottom, constant: -constant)
case .lessThanOrEqual:
anchor = bottomAnchor.constraint(lessThanOrEqualTo: bottom, constant: -constant)
default:
anchor = bottomAnchor.constraint(equalTo: bottom, constant: -constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorLeft(_ left: NSLayoutXAxisAnchor, _ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = leftAnchor.constraint(greaterThanOrEqualTo: left, constant: constant)
case .lessThanOrEqual:
anchor = leftAnchor.constraint(lessThanOrEqualTo: left, constant: constant)
default:
anchor = leftAnchor.constraint(equalTo: left, constant: constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorRight(_ right: NSLayoutXAxisAnchor, _ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = rightAnchor.constraint(greaterThanOrEqualTo: right, constant: -constant)
case .lessThanOrEqual:
anchor = rightAnchor.constraint(lessThanOrEqualTo: right, constant: -constant)
default:
anchor = rightAnchor.constraint(equalTo: right, constant: -constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorWidth(_ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = widthAnchor.constraint(greaterThanOrEqualToConstant: constant)
case .lessThanOrEqual:
anchor = widthAnchor.constraint(lessThanOrEqualToConstant: constant)
default:
anchor = widthAnchor.constraint(equalToConstant: constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorHeight(_ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = heightAnchor.constraint(greaterThanOrEqualToConstant: constant)
case .lessThanOrEqual:
anchor = heightAnchor.constraint(lessThanOrEqualToConstant: constant)
default:
anchor = heightAnchor.constraint(equalToConstant: constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
func _anchorCenterY(_ centerYAnchor: NSLayoutYAxisAnchor, _ constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
var anchor: NSLayoutConstraint
switch relation {
case .greaterThanOrEqual:
anchor = self.centerYAnchor.constraint(greaterThanOrEqualTo: centerYAnchor, constant: constant)
case .lessThanOrEqual:
anchor = self.centerYAnchor.constraint(lessThanOrEqualTo: centerYAnchor, constant: constant)
default:
anchor = self.centerYAnchor.constraint(equalTo: centerYAnchor, constant: constant)
}
anchor.priority = priority
anchor.isActive = true
return anchor
}
}
| 36.833333 | 192 | 0.736376 |
21fde8f598dfa8d5f0e0c21a7e62ee5a5518bdaa | 2,771 | //
// WindowController.swift
// FloatCoin
//
// Created by Kaunteya Suryawanshi on 01/01/18.
// Copyright © 2018 Kaunteya Suryawanshi. All rights reserved.
//
import AppKit
class WindowController: NSWindowController {
override func awakeFromNib() {
Log.info("awakeFromNib")
initialiseWindow()
}
func initialiseWindow() {
window!.isMovableByWindowBackground = true
window!.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(CGWindowLevelKey.popUpMenuWindow)))
window!.makeMain()
window!.hidesOnDeactivate = !UserDefaults.floatOnTop
window!.delegate = self
window?.backgroundColor = .clear
}
func toggleAppWindow() {
(window!.isVisible ? hide : show)()
}
func show() {
Log.info("Show")
window!.makeKeyAndOrderFront(self)
window!.makeMain()
NSApp.activate(ignoringOtherApps: true)
(window!.contentViewController as! MainViewController).ratesController.startTimer()
}
private func hide() {
Log.info("Hide")
window!.orderOut(self)
(window!.contentViewController as! MainViewController).ratesController.stopTimer()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == UserDefaults.keyFloatOnTop {
Log.info("\(keyPath!) CHANGED \(UserDefaults.floatOnTop)")
self.window!.hidesOnDeactivate = !UserDefaults.floatOnTop
}
}
}
extension WindowController: NSWindowDelegate {
func windowDidBecomeKey(_ notification: Notification) {
// Log.info("windowDidBecomeKey")
}
func windowDidResignKey(_ notification: Notification) {
// Log.info("windowDidResignKey")
}
func windowDidBecomeMain(_ notification: Notification) {
// Log.info("windowDidBecomeMain")
UserDefaults.standard.addObserver(self, forKeyPath: UserDefaults.keyFloatOnTop, options: .new, context: nil)
}
func windowDidResignMain(_ notification: Notification) {
// Log.info("windowDidResignMain")
UserDefaults.standard.removeObserver(self, forKeyPath: UserDefaults.keyFloatOnTop)
/// If window is not pinned(hides on deactivate) it does not close(just hides)
/// Hence close is expicitly called
if UserDefaults.floatOnTop == false {
(window?.contentViewController as! MainViewController).ratesController.stopTimer()
window?.close()
}
}
func windowWillClose(_ notification: Notification) {
// Log.info("windowDidResignMain")
}
}
class Window: NSWindow {
override var canBecomeMain: Bool {
return true
}
}
| 30.788889 | 151 | 0.670516 |
eb065d1b57b3e783be70272b1cab148e84d5779a | 777 | //
// MapWithTouchEvents.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 20/11/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
class MapWithTouchEvents: NTMapView {
var isTouchInProgress = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouchInProgress = true
super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouchInProgress = false
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouchInProgress = false
super.touchesCancelled(touches, with: event)
}
}
| 25.9 | 83 | 0.669241 |
ed214692528d61a78307d73a0668835caadecd75 | 672 | // AutomationAccountState enumerates the values for automation account state.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
public enum AutomationAccountStateEnum: String, Codable
{
// Ok specifies the ok state for automation account state.
case Ok = "Ok"
// Suspended specifies the suspended state for automation account state.
case Suspended = "Suspended"
// Unavailable specifies the unavailable state for automation account state.
case Unavailable = "Unavailable"
}
| 42 | 96 | 0.758929 |
6ab04048410b8558366b438772bae61740eec258 | 507 | //
// AnyPublisher+Init.swift
// XUI
//
// Created by Paul Kraft on 01.03.21.
// Copyright © 2021 QuickBird Studios. All rights reserved.
//
extension AnyPublisher {
// MARK: Factory Methods
public static func just(_ value: Output) -> AnyPublisher {
Just(value)
.mapError { _ -> Failure in }
.eraseToAnyPublisher()
}
public static func failure(_ error: Failure) -> AnyPublisher {
Fail(error: error)
.eraseToAnyPublisher()
}
}
| 20.28 | 66 | 0.60355 |
3a386f938a9a8e28c940cc31e6f0ea2c55fa538f | 2,289 | //
// GridLayout.swift
// Memorize
//
import SwiftUI
struct GridLayout {
private(set) var size: CGSize
private(set) var rowCount: Int = 0
private(set) var columnCount: Int = 0
init(itemCount: Int, nearAspectRatio desiredAspectRatio: Double = 1, in size: CGSize) {
self.size = size
// if our size is zero width or height or the itemCount is not > 0
// then we have no work to do (because our rowCount & columnCount will be zero)
guard size.width != 0, size.height != 0, itemCount > 0 else { return }
// find the bestLayout
// i.e., one which results in cells whose aspectRatio
// has the smallestVariance from desiredAspectRatio
// not necessarily most optimal code to do this, but easy to follow (hopefully)
var bestLayout: (rowCount: Int, columnCount: Int) = (1, itemCount)
var smallestVariance: Double?
let sizeAspectRatio = abs(Double(size.width/size.height))
for rows in 1...itemCount {
let columns = (itemCount / rows) + (itemCount % rows > 0 ? 1 : 0)
if (rows - 1) * columns < itemCount {
let itemAspectRatio = sizeAspectRatio * (Double(rows)/Double(columns))
let variance = abs(itemAspectRatio - desiredAspectRatio)
if smallestVariance == nil || variance < smallestVariance! {
smallestVariance = variance
bestLayout = (rowCount: rows, columnCount: columns)
}
}
}
rowCount = bestLayout.rowCount
columnCount = bestLayout.columnCount
}
var itemSize: CGSize {
if rowCount == 0 || columnCount == 0 {
return CGSize.zero
} else {
return CGSize(
width: size.width / CGFloat(columnCount),
height: size.height / CGFloat(rowCount)
)
}
}
func location(ofItemAt index: Int) -> CGPoint {
if rowCount == 0 || columnCount == 0 {
return CGPoint.zero
} else {
return CGPoint(
x: (CGFloat(index % columnCount) + 0.5) * itemSize.width,
y: (CGFloat(index / columnCount) + 0.5) * itemSize.height
)
}
}
}
| 36.333333 | 91 | 0.567497 |
d91f82056b909ab4d2c00bc4a0d8d8497b60c035 | 13,686 | // Copyright © 2018 Brad Howes. All rights reserved.
import UIKit
import os
/// Manager of the strip informational strip between the keyboard and the SoundFont presets / favorites screens. Supports
/// left/right swipes to switch the upper view, and two-finger left/right pan to adjust the keyboard range.
public final class InfoBarController: UIViewController {
private lazy var log = Logging.logger("InfoBarController")
@IBOutlet private weak var status: UILabel!
@IBOutlet private weak var patchInfo: UILabel!
@IBOutlet private weak var lowestKey: UIButton!
@IBOutlet private weak var addSoundFont: UIButton!
@IBOutlet private weak var highestKey: UIButton!
@IBOutlet private weak var touchView: UIView!
@IBOutlet private weak var showGuide: UIButton!
@IBOutlet private weak var showSettings: UIButton!
@IBOutlet private weak var editVisibility: UIButton!
@IBOutlet private weak var slidingKeyboardToggle: UIButton!
@IBOutlet private weak var showTags: UIButton!
@IBOutlet private weak var showEffects: UIButton!
@IBOutlet private weak var showMoreButtonsButton: UIButton!
@IBOutlet private weak var moreButtons: UIView!
@IBOutlet private weak var moreButtonsXConstraint: NSLayoutConstraint!
private let doubleTap = UITapGestureRecognizer()
private var panOrigin: CGPoint = CGPoint.zero
private var fader: UIViewPropertyAnimator?
private var activePresetManager: ActivePresetManager!
private var soundFonts: SoundFonts!
private var isMainApp: Bool!
private var observers = [NSKeyValueObservation]()
private var lowestKeyValue = ""
private var highestKeyValue = ""
private var showingMoreButtons = false
public override func viewDidLoad() {
// Hide until we know for sure that they should be visible
highestKey.isHidden = true
lowestKey.isHidden = true
slidingKeyboardToggle.isHidden = true
doubleTap.numberOfTouchesRequired = 1
doubleTap.numberOfTapsRequired = 2
touchView.addGestureRecognizer(doubleTap)
let panner = UIPanGestureRecognizer(target: self, action: #selector(panKeyboard))
panner.minimumNumberOfTouches = 1
panner.maximumNumberOfTouches = 1
touchView.addGestureRecognizer(panner)
observers.append(
Settings.shared.observe(\.slideKeyboard, options: [.new]) { [weak self] _, _ in
self?.updateSlidingKeyboardState()
}
)
updateSlidingKeyboardState()
showEffects.tintColor = Settings.instance.showEffects ? .systemOrange : .systemTeal
}
/**
Detect changes in orientation and adjust button layouts
- parameter newCollection: the new size traits
- parameter coordinator: the animation coordinator
*/
public override func willTransition(to newCollection: UITraitCollection,
with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(
alongsideTransition: { _ in
self.hideMoreButtons()
},
completion: { _ in
self.hideMoreButtons()
})
}
}
extension InfoBarController {
@IBAction
func toggleMoreButtons(_ sender: UIButton) {
setMoreButtonsVisible(state: !showingMoreButtons)
}
@IBAction private func showSettings(_ sender: UIButton) {
setMoreButtonsVisible(state: false)
}
@IBAction private func showGuide(_ sender: UIButton) {
guard traitCollection.horizontalSizeClass == .compact else { return }
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 0.4,
delay: 0.0,
options: [.curveEaseOut],
animations: {
self.moreButtonsXConstraint.constant = -40
},
completion: { _ in
self.moreButtonsXConstraint.constant = -40
}
)
}
@IBAction private func toggleSlideKeyboard(_ sender: UIButton) {
Settings.shared.slideKeyboard = !Settings.shared.slideKeyboard
}
}
extension InfoBarController: ControllerConfiguration {
public func establishConnections(_ router: ComponentContainer) {
activePresetManager = router.activePresetManager
activePresetManager.subscribe(self, notifier: activePresetChange)
soundFonts = router.soundFonts
isMainApp = router.isMainApp
router.favorites.subscribe(self, notifier: favoritesChange)
useActivePresetKind(activePresetManager.active)
showEffects.isEnabled = router.isMainApp
showEffects.isHidden = !router.isMainApp
}
}
extension InfoBarController: InfoBar {
public func updateButtonsForPresetsViewState(visible: Bool) {
editVisibility.isEnabled = visible
showTags.isEnabled = visible
}
public var moreButtonsVisible: Bool { showingMoreButtons }
/**
Add an event target to one of the internal UIControl entities.
- parameter event: the event to target
- parameter target: the instance to notify when the event fires
- parameter action: the method to call when the event fires
*/
public func addEventClosure(_ event: InfoBarEvent, _ closure: @escaping UIControl.Closure) {
switch event {
case .shiftKeyboardUp: addShiftKeyboardUpClosure(closure)
case .shiftKeyboardDown: addShiftKeyboardDownClosure(closure)
case .doubleTap: doubleTap.addClosure(closure)
case .addSoundFont: addSoundFont.addClosure(closure)
case .showGuide: showGuide.addClosure(closure)
case .showSettings: showSettings.addClosure(closure)
case .editVisibility: editVisibility.addClosure(closure)
case .showEffects: showEffects.addClosure(closure)
case .showTags: showTags.addClosure(closure)
case .showMoreButtons: addShowMoreButtonsClosure(closure)
case .hideMoreButtons: addHideMoreButtonsClosure(closure)
}
}
private func addShiftKeyboardUpClosure(_ closure: @escaping UIControl.Closure) {
highestKey.addClosure(closure)
highestKey.isHidden = false
slidingKeyboardToggle.isHidden = false
}
private func addShiftKeyboardDownClosure(_ closure: @escaping UIControl.Closure) {
lowestKey.addClosure(closure)
lowestKey.isHidden = false
slidingKeyboardToggle.isHidden = false
}
private func addShowMoreButtonsClosure(_ closure: @escaping UIControl.Closure) {
showMoreButtonsButton.addClosure { [weak self] button in
guard let self = self, self.showingMoreButtons else { return }
closure(button)
}
}
private func addHideMoreButtonsClosure(_ closure: @escaping UIControl.Closure) {
showMoreButtonsButton.addClosure { [weak self] button in
guard let self = self, !self.showingMoreButtons else { return }
closure(button)
}
}
public func resetButtonState(_ event: InfoBarEvent) {
let button: UIButton? = {
switch event {
case .addSoundFont: return addSoundFont
case .showGuide: return showGuide
case .showSettings: return showSettings
case .editVisibility: return editVisibility
case .showEffects: return showEffects
case .showTags: return showTags
default: return nil
}
}()
button?.tintColor = .systemTeal
}
/**
Set the text to temporarily show in the center of the info bar.
- parameter value: the text to display
*/
public func setStatusText(_ value: String) {
status.text = value
startStatusAnimation()
}
/**
Set the range of keys to show in the bar
- parameter from: the first key label
- parameter to: the last key label
*/
public func setVisibleKeyLabels(from: String, to: String) {
lowestKeyValue = from
highestKeyValue = to
updateKeyLabels()
}
public func showMoreButtons() {
setMoreButtonsVisible(state: true)
}
public func hideMoreButtons() {
setMoreButtonsVisible(state: false)
}
}
// MARK: - Private
extension InfoBarController: SegueHandler {
public enum SegueIdentifier: String {
case settings
}
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if case .settings = segueIdentifier(for: segue) {
beginSettingsView(segue, sender: sender)
}
}
private func beginSettingsView(_ segue: UIStoryboardSegue, sender: Any?) {
guard let navController = segue.destination as? UINavigationController,
let viewController = navController.topViewController as? SettingsViewController
else { return }
viewController.soundFonts = soundFonts
viewController.isMainApp = isMainApp
if !isMainApp {
viewController.modalPresentationStyle = .fullScreen
navController.modalPresentationStyle = .fullScreen
}
if let ppc = navController.popoverPresentationController {
ppc.sourceView = showSettings
ppc.sourceRect = showSettings.bounds
ppc.permittedArrowDirections = .any
}
}
}
extension InfoBarController {
private func setMoreButtonsVisible(state: Bool) {
guard state != showingMoreButtons else { return }
guard traitCollection.horizontalSizeClass == .compact else { return }
let willBeHidden = !state
showingMoreButtons = state
moreButtonsXConstraint.constant = willBeHidden ? 0 : -moreButtons.frame.width
view.layoutIfNeeded()
let newImage = UIImage(
named: willBeHidden ? "More Right" : "More Right Filled", in: Bundle(for: Self.self),
compatibleWith: .none)
let newConstraint = willBeHidden ? -moreButtons.frame.width : 0
let newAlpha: CGFloat = willBeHidden ? 1.0 : 0.5
moreButtons.isHidden = false
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 0.4,
delay: 0.0,
options: [willBeHidden ? .curveEaseOut : .curveEaseIn],
animations: {
self.moreButtonsXConstraint.constant = newConstraint
self.touchView.alpha = newAlpha
self.view.layoutIfNeeded()
},
completion: { _ in
self.moreButtons.isHidden = willBeHidden
self.touchView.alpha = newAlpha
}
)
UIView.transition(with: showMoreButtonsButton, duration: 0.4, options: .transitionCrossDissolve)
{
self.showMoreButtonsButton.setImage(newImage, for: .normal)
}
}
private func activePresetChange(_ event: ActivePresetEvent) {
if case let .active(old: _, new: new, playSample: _) = event {
useActivePresetKind(new)
}
}
private func favoritesChange(_ event: FavoritesEvent) {
switch event {
case let .added(index: _, favorite: favorite): updateInfoBar(with: favorite)
case let .changed(index: _, favorite: favorite): updateInfoBar(with: favorite)
case let .removed(index: _, favorite: favorite): updateInfoBar(with: favorite.soundFontAndPreset)
case .selected: break
case .beginEdit: break
case .removedAll: break
case .restored: break
}
}
private func updateInfoBar(with favorite: Favorite) {
if favorite.soundFontAndPreset == activePresetManager.active.soundFontAndPreset {
setPresetInfo(name: favorite.presetConfig.name, isFavored: true)
}
}
private func updateInfoBar(with soundFontAndPreset: SoundFontAndPreset) {
if soundFontAndPreset == activePresetManager.active.soundFontAndPreset {
if let patch = activePresetManager.resolveToPreset(soundFontAndPreset) {
setPresetInfo(name: patch.presetConfig.name, isFavored: false)
}
}
}
private func useActivePresetKind(_ activePresetKind: ActivePresetKind) {
if let favorite = activePresetKind.favorite {
setPresetInfo(name: favorite.presetConfig.name, isFavored: true)
} else if let soundFontAndPreset = activePresetKind.soundFontAndPreset {
if let preset = activePresetManager.resolveToPreset(soundFontAndPreset) {
setPresetInfo(name: preset.presetConfig.name, isFavored: false)
}
} else {
setPresetInfo(name: "-", isFavored: false)
}
}
private func setPresetInfo(name: String, isFavored: Bool) {
os_log(.info, log: log, "setPresetInfo: %{public}s %d", name, isFavored)
patchInfo.text = TableCell.favoriteTag(isFavored) + name
cancelStatusAnimation()
}
private func startStatusAnimation() {
cancelStatusAnimation()
status.isHidden = false
status.alpha = 1.0
patchInfo.alpha = 0.0
self.fader = UIViewPropertyAnimator(duration: 0.25, curve: .linear) {
self.status.alpha = 0.0
self.patchInfo.alpha = 1.0
}
self.fader?.addCompletion { _ in
self.status.isHidden = true
self.fader = nil
}
self.fader?.startAnimation(afterDelay: 1.0)
}
private func cancelStatusAnimation() {
if let fader = self.fader {
fader.stopAnimation(true)
self.fader = nil
}
}
@objc private func panKeyboard(_ panner: UIPanGestureRecognizer) {
if panner.state == .began {
panOrigin = panner.translation(in: view)
} else {
let point = panner.translation(in: view)
let change = Int((point.x - panOrigin.x) / 40.0)
if change < 0 {
for _ in change..<0 {
highestKey.sendActions(for: .touchUpInside)
}
panOrigin = point
} else if change > 0 {
for _ in 0..<change {
lowestKey.sendActions(for: .touchUpInside)
}
panOrigin = point
}
}
}
private func updateKeyLabels() {
UIView.performWithoutAnimation {
lowestKey.setTitle("❰" + lowestKeyValue, for: .normal)
lowestKey.accessibilityLabel = "Keyboard down before " + lowestKeyValue
lowestKey.layoutIfNeeded()
highestKey.setTitle(highestKeyValue + "❱", for: .normal)
highestKey.accessibilityLabel = "Keyboard up after " + highestKeyValue
highestKey.layoutIfNeeded()
}
}
private func updateSlidingKeyboardState() {
slidingKeyboardToggle.setTitleColor(Settings.shared.slideKeyboard ? .systemTeal : .darkGray, for: .normal)
}
}
| 32.35461 | 121 | 0.715841 |
1a75addcc7a23405d701b351550c824856230cca | 2,163 | import XCTest
@testable import EasyDocument
#if !os(macOS)
final class EasyDocumentTests: XCTestCase {
override func setUpWithError() throws {
CoreDataManager(.swiftPackage)
ColorValueTransformer.register()
}
override func tearDownWithError() throws {
// No need to clear out CoreData objects because nothing is persisted.
}
func setupEvent() -> Event {
let context = (CoreDataManager.shared?.viewContext)!
let newEvent = Event(context: context)
let red = CGFloat.random(in: 200...255)/255.0
let green = CGFloat.random(in: 200...255)/255.0
let blue = CGFloat.random(in: 200...255)/255.0
let color = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
newEvent.timestamp = Date()
newEvent.anyColor = color
let detail = Detail(context: context)
detail.event = newEvent
detail.title = "Test Event"
CoreDataManager.shared?.saveViewContext()
return newEvent
}
func testDeepCopy() {
let originalEvent = setupEvent()
// There should no inserted objects to start with
XCTAssertEqual(CoreDataManager.shared!.viewContext.insertedObjects.count, 0)
let _ = originalEvent.duplicate()
// There should now be two new insertedObjects (Event and Detail)
XCTAssertEqual(CoreDataManager.shared!.viewContext.insertedObjects.count, 2)
}
func testUniquenessAndValidity() {
let originalEvent = setupEvent()
let duplicateEvent: Event? = originalEvent.duplicate()
// The managed objects are distinct, even if they are duplicates
XCTAssertEqual(originalEvent == duplicateEvent, false)
// The related managed objects are distinct, even if they are duplicates
XCTAssertEqual(originalEvent.detail == duplicateEvent?.detail, false)
// Test duplication of color property
XCTAssertEqual(originalEvent.anyColor.hashValue == duplicateEvent?.anyColor.hashValue, true)
// Test duplication of related property
XCTAssertEqual(duplicateEvent?.detail?.title == "Test Event", true)
}
func testDocument() {
}
static var allTests = [
("testDeepCopy", testDeepCopy),
("testUniquenessAndValidity", testUniquenessAndValidity),
("testDocument", testDocument),
]
}
#endif
| 27.730769 | 94 | 0.734628 |
cc4a37642a3a2ac6c91e4d000b0cc23da7fe69ca | 21,879 | import Foundation
enum EventLoggingError {
case generic
}
@objc(WMFEventLoggingService)
public class EventLoggingService : NSObject, URLSessionDelegate {
private struct Key {
static let isEnabled = "SendUsageReports"
static let appInstallID = "WMFAppInstallID"
static let lastLoggedSnapshot = "WMFLastLoggedSnapshot"
static let appInstallDate = "AppInstallDate"
static let loggedDaysInstalled = "DailyLoggingStatsDaysInstalled"
}
private var pruningAge: TimeInterval = 60*60*24*30 // 30 days
private var sendImmediatelyOnWWANThreshhold: TimeInterval = 30
private var postBatchSize = 10
private var postTimeout: TimeInterval = 60*2 // 2 minutes
private var postInterval: TimeInterval = 60*10 // 10 minutes
private var debugDisableImmediateSend = false
#if WMF_EVENT_LOGGING_DEV_DEBUG
private static let scheme = "http"
private static let host = "deployment.wikimedia.beta.wmflabs.org"
#else
private static let scheme = "https"
private static let host = "meta.wikimedia.org"
#endif
private static let path = "/beacon/event"
private let reachabilityManager: AFNetworkReachabilityManager
private let urlSessionConfiguration: URLSessionConfiguration
private var urlSession: URLSession?
private var timer: Timer?
private var lastNetworkRequestTimestamp: TimeInterval?
private let persistentStoreCoordinator: NSPersistentStoreCoordinator
private let managedObjectContext: NSManagedObjectContext
private let operationQueue: OperationQueue
@objc(sharedInstance) public static let shared: EventLoggingService = {
let fileManager = FileManager.default
var permanentStorageDirectory = fileManager.wmf_containerURL().appendingPathComponent("Event Logging", isDirectory: true)
var didGetDirectoryExistsError = false
do {
try fileManager.createDirectory(at: permanentStorageDirectory, withIntermediateDirectories: true, attributes: nil)
} catch let error {
DDLogError("EventLoggingService: Error creating permanent cache: \(error)")
}
do {
var values = URLResourceValues()
values.isExcludedFromBackup = true
try permanentStorageDirectory.setResourceValues(values)
} catch let error {
DDLogError("EventLoggingService: Error excluding from backup: \(error)")
}
let permanentStorageURL = permanentStorageDirectory.appendingPathComponent("Events.sqlite")
DDLogDebug("EventLoggingService: Events persistent store: \(permanentStorageURL)")
return EventLoggingService(permanentStorageURL: permanentStorageURL)
}()
@objc
public func log(event: Dictionary<String, Any>, schema: String, revision: Int, wiki: String) {
let event: NSDictionary = ["event": event, "schema": schema, "revision": revision, "wiki": wiki]
logEvent(event)
}
private var shouldSendImmediately: Bool {
if (debugDisableImmediateSend) {
return false
}
if self.reachabilityManager.isReachableViaWiFi {
return true
}
if self.reachabilityManager.isReachableViaWWAN,
let lastNetworkRequestTimestamp = self.lastNetworkRequestTimestamp,
Date.timeIntervalSinceReferenceDate < (lastNetworkRequestTimestamp + sendImmediatelyOnWWANThreshhold) {
return true
}
return false
}
public init(urlSesssionConfiguration: URLSessionConfiguration, reachabilityManager: AFNetworkReachabilityManager, permanentStorageURL: URL? = nil) {
self.reachabilityManager = reachabilityManager
self.urlSessionConfiguration = urlSesssionConfiguration
operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
let bundle = Bundle.wmf
let modelURL = bundle.url(forResource: "EventLogging", withExtension: "momd")!
let model = NSManagedObjectModel(contentsOf: modelURL)!
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true), NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true)]
if let storeURL = permanentStorageURL {
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch {
do {
try FileManager.default.removeItem(at: storeURL)
} catch {
}
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch {
abort()
}
}
} else {
do {
try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: options)
} catch {
abort()
}
}
self.persistentStoreCoordinator = psc
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
}
private convenience init(permanentStorageURL: URL) {
let reachabilityManager = AFNetworkReachabilityManager.init(forDomain: EventLoggingService.host)
let urlSessionConfig = URLSessionConfiguration.default
urlSessionConfig.httpShouldUsePipelining = true
urlSessionConfig.allowsCellularAccess = true
urlSessionConfig.httpMaximumConnectionsPerHost = 2
urlSessionConfig.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
self.init(urlSesssionConfiguration: urlSessionConfig, reachabilityManager: reachabilityManager, permanentStorageURL: permanentStorageURL)
}
deinit {
stop()
}
@objc
public func start() {
assert(Thread.isMainThread, "must be started on main thread")
let backgroundTaskIdentifier = Background.manager.beginTask()
let operation = AsyncBlockOperation { (operation) in
DispatchQueue.main.async {
self.urlSession = URLSession(configuration: self.urlSessionConfiguration, delegate: self, delegateQueue: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name.WMFNetworkRequestBegan, object: nil, queue: .main) { (note) in
self.lastNetworkRequestTimestamp = Date.timeIntervalSinceReferenceDate
//DDLogDebug("last network request: \(String(describing: self.lastNetworkRequestTimestamp))")
}
self.reachabilityManager.setReachabilityStatusChange { (status) in
switch status {
case .reachableViaWiFi:
self.tryPostEvents()
default:
break
}
}
self.reachabilityManager.startMonitoring()
self.timer = Timer.scheduledTimer(timeInterval: self.postInterval, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats: true)
self.prune()
#if DEBUG
self.managedObjectContext.perform {
do {
let countFetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest()
countFetch.includesSubentities = false
let count = try self.managedObjectContext.count(for: countFetch)
DDLogInfo("EventLoggingService: There are \(count) queued events")
} catch let error {
DDLogError(error.localizedDescription)
}
operation.finish()
}
#else
operation.finish()
#endif
}
}
operationQueue.addOperation(operation)
operationQueue.addOperation {
Background.manager.endTask(withIdentifier: backgroundTaskIdentifier)
}
}
@objc
private func timerFired() {
tryPostEvents()
asyncSave()
}
@objc
public func stop() {
let backgroundTaskIdentifier = Background.manager.beginTask()
assert(Thread.isMainThread, "must be stopped on main thread")
let operation = AsyncBlockOperation { (operation) in
DispatchQueue.main.async {
self.reachabilityManager.stopMonitoring()
self.urlSession?.finishTasksAndInvalidate()
self.urlSession = nil
NotificationCenter.default.removeObserver(self)
self.timer?.invalidate()
self.timer = nil
self.managedObjectContext.perform {
self.save()
operation.finish()
}
}
}
operationQueue.addOperation(operation)
operationQueue.addOperation {
Background.manager.endTask(withIdentifier: backgroundTaskIdentifier)
}
}
@objc
public func reset() {
self.resetSession()
self.resetInstall()
}
// Called inside AsyncBlockOperation.
private func prune() {
self.managedObjectContext.perform {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "WMFEventRecord")
fetch.returnsObjectsAsFaults = false
let pruneDate = Date().addingTimeInterval(-(self.pruningAge)) as NSDate
fetch.predicate = NSPredicate(format: "(recorded < %@) OR (posted != nil) OR (failed == TRUE)", pruneDate)
let delete = NSBatchDeleteRequest(fetchRequest: fetch)
delete.resultType = .resultTypeCount
do {
let result = try self.managedObjectContext.execute(delete)
guard let deleteResult = result as? NSBatchDeleteResult else {
DDLogError("EventLoggingService: Could not read NSBatchDeleteResult")
return
}
guard let count = deleteResult.result as? Int else {
DDLogError("EventLoggingService: Could not read NSBatchDeleteResult count")
return
}
DDLogInfo("EventLoggingService: Pruned \(count) events")
} catch let error {
DDLogError("EventLoggingService: Error pruning events: \(error.localizedDescription)")
}
}
}
@objc
private func logEvent(_ event: NSDictionary) {
let now = NSDate()
let moc = self.managedObjectContext
moc.perform {
let record = NSEntityDescription.insertNewObject(forEntityName: "WMFEventRecord", into: self.managedObjectContext) as! EventRecord
record.event = event
record.recorded = now
record.userAgent = WikipediaAppUtils.versionedUserAgent()
DDLogDebug("EventLoggingService: \(record.objectID) recorded!")
self.save()
if self.shouldSendImmediately {
self.tryPostEvents()
}
}
}
@objc
private func tryPostEvents() {
let operation = AsyncBlockOperation { (operation) in
let moc = self.managedObjectContext
moc.perform {
let fetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest()
fetch.sortDescriptors = [NSSortDescriptor(keyPath: \EventRecord.recorded, ascending: true)]
fetch.predicate = NSPredicate(format: "(posted == nil) AND (failed != TRUE)")
fetch.fetchLimit = self.postBatchSize
var eventRecords: [EventRecord] = []
do {
eventRecords = try moc.fetch(fetch)
} catch let error {
DDLogError(error.localizedDescription)
}
defer {
if eventRecords.count > 0 {
self.postEvents(eventRecords, completion: {
operation.finish()
})
} else {
operation.finish()
}
}
}
}
operationQueue.addOperation(operation)
}
private func asyncSave() {
self.managedObjectContext.perform {
self.save()
}
}
private func postEvents(_ eventRecords: [EventRecord], completion: () -> Void) {
DDLogDebug("EventLoggingService: Posting \(eventRecords.count) events!")
let taskGroup = WMFTaskGroup()
var completedRecordIDs = Set<NSManagedObjectID>()
var failedRecordIDs = Set<NSManagedObjectID>()
for record in eventRecords {
let moid = record.objectID
guard let payload = record.event else {
failedRecordIDs.insert(moid)
continue
}
taskGroup.enter()
let userAgent = record.userAgent ?? WikipediaAppUtils.versionedUserAgent()
submit(payload: payload, userAgent: userAgent) { (error) in
if error != nil {
failedRecordIDs.insert(moid)
} else {
completedRecordIDs.insert(moid)
}
taskGroup.leave()
}
}
taskGroup.waitInBackground {
self.managedObjectContext.perform {
let postDate = NSDate()
for moid in completedRecordIDs {
let mo = try? self.managedObjectContext.existingObject(with: moid)
guard let record = mo as? EventRecord else {
continue
}
record.posted = postDate
}
for moid in failedRecordIDs {
let mo = try? self.managedObjectContext.existingObject(with: moid)
guard let record = mo as? EventRecord else {
continue
}
record.failed = true
}
self.save()
if (completedRecordIDs.count == eventRecords.count) {
DDLogDebug("EventLoggingService: All records succeeded, attempting to post more")
self.tryPostEvents()
} else {
DDLogDebug("EventLoggingService: Some records failed, waiting to post more")
}
}
}
}
private func submit(payload: NSObject, userAgent: String, completion: @escaping (EventLoggingError?) -> Void) {
guard let urlSession = self.urlSession else {
assertionFailure("urlSession was nil")
completion(EventLoggingError.generic)
return
}
do {
let payloadJsonData = try JSONSerialization.data(withJSONObject:payload, options: [])
guard let payloadString = String(data: payloadJsonData, encoding: .utf8) else {
DDLogError("EventLoggingService: Could not convert JSON data to string")
completion(EventLoggingError.generic)
return
}
let encodedPayloadJsonString = payloadString.wmf_UTF8StringWithPercentEscapes()
var components = URLComponents()
components.scheme = EventLoggingService.scheme
components.host = EventLoggingService.host
components.path = EventLoggingService.path
components.percentEncodedQuery = encodedPayloadJsonString
guard let url = components.url else {
DDLogError("EventLoggingService: Could not creatre URL")
completion(EventLoggingError.generic)
return
}
var request = URLRequest(url: url)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
let task = urlSession.dataTask(with: request, completionHandler: { (_, response, error) in
guard error == nil,
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode / 100 == 2 else {
completion(EventLoggingError.generic)
return
}
completion(nil)
// DDLogDebug("EventLoggingService: event \(eventRecord.objectID) posted!")
})
task.resume()
} catch let error {
DDLogError(error.localizedDescription)
completion(EventLoggingError.generic)
return
}
}
// mark stored values
private func save() {
guard managedObjectContext.hasChanges else {
return
}
do {
try managedObjectContext.save()
} catch let error {
DDLogError("Error saving EventLoggingService managedObjectContext: \(error)")
}
}
private var semaphore = DispatchSemaphore(value: 1)
private var libraryValueCache: [String: NSCoding] = [:]
private func libraryValue(for key: String) -> NSCoding? {
semaphore.wait()
defer {
semaphore.signal()
}
var value = libraryValueCache[key]
if value != nil {
return value
}
managedObjectContext.performAndWait {
value = managedObjectContext.wmf_keyValue(forKey: key)?.value
if value != nil {
libraryValueCache[key] = value
return
}
if let legacyValue = UserDefaults.wmf_userDefaults().object(forKey: key) as? NSCoding {
value = legacyValue
libraryValueCache[key] = legacyValue
managedObjectContext.wmf_setValue(legacyValue, forKey: key)
UserDefaults.wmf_userDefaults().removeObject(forKey: key)
save()
}
}
return value
}
private func setLibraryValue(_ value: NSCoding?, for key: String) {
semaphore.wait()
defer {
semaphore.signal()
}
libraryValueCache[key] = value
managedObjectContext.perform {
self.managedObjectContext.wmf_setValue(value, forKey: key)
self.save()
}
}
@objc public var isEnabled: Bool {
get {
var isEnabled = false
if let enabledNumber = libraryValue(for: Key.isEnabled) as? NSNumber {
isEnabled = enabledNumber.boolValue
} else {
setLibraryValue(NSNumber(booleanLiteral: false), for: Key.isEnabled) // set false so that it's cached and doesn't keep fetching
}
return isEnabled
}
set {
setLibraryValue(NSNumber(booleanLiteral: newValue), for: Key.isEnabled)
}
}
@objc public var appInstallID: String? {
get {
var installID = libraryValue(for: Key.appInstallID) as? String
if installID == nil || installID == "" {
installID = UUID().uuidString
setLibraryValue(installID as NSString?, for: Key.appInstallID)
}
return installID
}
set {
setLibraryValue(newValue as NSString?, for: Key.appInstallID)
}
}
@objc public var lastLoggedSnapshot: NSCoding? {
get {
return libraryValue(for: Key.lastLoggedSnapshot)
}
set {
setLibraryValue(newValue, for: Key.lastLoggedSnapshot)
}
}
@objc public var appInstallDate: Date? {
get {
var value = libraryValue(for: Key.appInstallDate) as? Date
if value == nil {
value = Date()
setLibraryValue(value as NSDate?, for: Key.appInstallDate)
}
return value
}
set {
setLibraryValue(newValue as NSDate?, for: Key.appInstallDate)
}
}
@objc public var loggedDaysInstalled: NSNumber? {
get {
return libraryValue(for: Key.loggedDaysInstalled) as? NSNumber
}
set {
setLibraryValue(newValue, for: Key.loggedDaysInstalled)
}
}
private var _sessionID: String?
@objc public var sessionID: String? {
semaphore.wait()
defer {
semaphore.signal()
}
if _sessionID == nil {
_sessionID = UUID().uuidString
}
return _sessionID
}
private var _sessionStartDate: Date?
@objc public var sessionStartDate: Date? {
semaphore.wait()
defer {
semaphore.signal()
}
if _sessionStartDate == nil {
_sessionStartDate = Date()
}
return _sessionStartDate
}
@objc public func resetSession() {
semaphore.wait()
defer {
semaphore.signal()
}
_sessionID = nil
_sessionStartDate = Date()
}
private func resetInstall() {
appInstallID = nil
lastLoggedSnapshot = nil
loggedDaysInstalled = nil
appInstallDate = nil
}
}
| 36.586957 | 172 | 0.579825 |
f55651b906b604f0d60a5d19e02eb6cb583c9b8c | 1,773 | import UIKit
import RxSwift
import RxCocoa
import MBProgressHUD
final class UserViewController: UIViewController {
@IBOutlet private var userImageView: UIImageView!
@IBOutlet private var salutationLabel: UILabel!
@IBOutlet private var firstnameLabel: UILabel!
@IBOutlet private var lastnameLabel: UILabel!
private let disposeBag = DisposeBag()
var viewModel: UserViewModel?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let viewModel = viewModel {
bind(to: viewModel.outputs)
viewModel.inputs.fetch()
}
}
private func bind(to outputs: UserViewModelOutputs) {
outputs.salutation
.map { $0.capitalized }
.drive(salutationLabel.rx.text)
.disposed(by: disposeBag)
outputs.firstname
.map { $0.capitalized }
.drive(firstnameLabel.rx.text)
.disposed(by: disposeBag)
outputs.lastname
.map { $0.capitalized }
.drive(lastnameLabel.rx.text)
.disposed(by: disposeBag)
outputs.image
.drive(userImageView.rx.image)
.disposed(by: disposeBag)
outputs.loading
.drive(onNext: { [weak self] isLoading in
guard let `self` = self else {
return
}
if isLoading {
MBProgressHUD.showAdded(to: self.view, animated: true)
} else {
MBProgressHUD.hide(for: self.view, animated: true)
}
})
.disposed(by: disposeBag)
}
@IBAction func loadUser(_ sender: UIBarButtonItem) {
viewModel?.inputs.fetch()
}
}
| 27.276923 | 74 | 0.578116 |
464e862a033eef21ca6fb408d902f0f8071a51a9 | 6,454 | //
// MeshNodeInfoTableViewController.swift
// nRFMeshProvision_Example
//
// Created by Mostafa Berg on 12/04/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import nRFMeshProvision
class MeshNodeInfoTableViewController: UITableViewController {
// MARK: - Properties
static let cellReuseIdentifier = "NodeInfoDataCell"
private var nodeEntry: MeshNodeEntry!
// MARK: - Implementation
public func setNodeEntry(_ aNodeEntry: MeshNodeEntry) {
nodeEntry = aNodeEntry
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
//Section 0 -> Node info
//Section 1 -> AppKey info
//Section 2 -> Elements info
var appKeyExists = 0
if nodeEntry.appKeys.count > 0 {
appKeyExists = 1
}
if nodeEntry.elements != nil {
return 1 + appKeyExists + nodeEntry.elements!.count
} else {
return 1 + appKeyExists
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 9
case 1:
return nodeEntry.appKeys.count
// case 2:
//
default:
return nodeEntry.elements![section - 2].totalModelCount()
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Node details"
case 1:
return "Application Keys"
default:
return "Element \(section - 1)"
}
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
//This is just informational, no actions
return false
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MeshNodeInfoTableViewController.cellReuseIdentifier,
for: indexPath)
if indexPath.section == 0 {
switch indexPath.row {
case 0:
cell.detailTextLabel?.text = "Name"
cell.textLabel?.text = nodeEntry.nodeName
case 1:
cell.detailTextLabel?.text = "Provisioning Timestamp"
cell.textLabel?.text = DateFormatter.localizedString(from: nodeEntry.provisionedTimeStamp ?? Date(),
dateStyle: .short,
timeStyle: .short)
case 2:
cell.detailTextLabel?.text = "Node Identifier"
cell.textLabel?.text = nodeEntry.nodeId.hexString()
case 3:
cell.detailTextLabel?.text = "Unicast Address"
cell.textLabel?.text = nodeEntry.nodeUnicast!.hexString()
case 4:
cell.detailTextLabel?.text = "Company Identifier"
if let anIdentifier = nodeEntry.companyIdentifier {
if let aName = CompanyIdentifiers().humanReadableNameFromIdentifier(anIdentifier) {
cell.textLabel?.text = aName
} else {
cell.textLabel?.text = anIdentifier.hexString()
}
} else {
cell.textLabel?.text = "N/A"
}
case 5:
cell.detailTextLabel?.text = "Product Identifier"
if let anIdentifier = nodeEntry.productIdentifier {
cell.textLabel?.text = anIdentifier.hexString()
} else {
cell.textLabel?.text = "N/A"
}
case 6:
cell.detailTextLabel?.text = "Product Version"
if let aVersion = nodeEntry.productVersion {
cell.textLabel?.text = aVersion.hexString()
} else {
cell.textLabel?.text = "N/A"
}
case 7:
cell.detailTextLabel?.text = "Replay Protection Count"
if let aCount = nodeEntry.replayProtectionCount {
cell.textLabel?.text = aCount.hexString()
} else {
cell.textLabel?.text = "N/A"
}
case 8:
cell.detailTextLabel?.text = "Features"
if let someFeatures = nodeEntry.featureFlags {
cell.textLabel?.text = someFeatures.hexString()
} else {
cell.textLabel?.text = "N/A"
}
default:
cell.detailTextLabel?.text = "Unknown field"
cell.textLabel?.text = "N/A"
}
} else if indexPath.section == 1 {
let appKey = nodeEntry.appKeys[indexPath.row]
cell.textLabel?.text = "AppKey"
cell.detailTextLabel?.text = appKey.hexString()
} else {
let element = nodeEntry.elements![indexPath.section - 2]
if element.allSigAndVendorModels()[indexPath.row].count == 2 {
cell.detailTextLabel?.text = "SIG Model"
let modelData = element.allSigAndVendorModels()[indexPath.row]
let upperInt = UInt16(modelData[0]) << 8
let lowerInt = UInt16(modelData[1])
if let modelIdentifier = MeshModelIdentifiers(rawValue: upperInt | lowerInt) {
let modelString = MeshModelIdentifierStringConverter().stringValueForIdentifier(modelIdentifier)
cell.textLabel?.text = modelString
} else {
cell.textLabel?.text = modelData.hexString()
}
} else {
cell.detailTextLabel?.text = "Vendor Model"
let modelData = element.allSigAndVendorModels()[indexPath.row]
let vendorCompanyData = Data(modelData[0...1])
let vendorModelId = Data(modelData[2...3])
let formattedModel = "\(vendorCompanyData.hexString()):\(vendorModelId.hexString())"
cell.textLabel?.text = formattedModel
}
}
return cell
}
}
| 39.839506 | 117 | 0.54013 |
f824fb900d3227f790ec9385faa37231d53f8068 | 9,748 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import Foundation
// MARK: - Test Suite
#if FOUNDATION_XCTEST
import XCTest
class TestPropertyListEncoderSuper : XCTestCase { }
#else
import StdlibUnittest
class TestPropertyListEncoderSuper { }
#endif
class TestPropertyListEncoder : TestPropertyListEncoderSuper {
// MARK: - Encoding Top-Level Empty Types
func testEncodingTopLevelEmptyStruct() {
let empty = EmptyStruct()
_testRoundTrip(of: empty, in: .binary, expectedPlist: _plistEmptyDictionaryBinary)
_testRoundTrip(of: empty, in: .xml, expectedPlist: _plistEmptyDictionaryXML)
}
func testEncodingTopLevelEmptyClass() {
let empty = EmptyClass()
_testRoundTrip(of: empty, in: .binary, expectedPlist: _plistEmptyDictionaryBinary)
_testRoundTrip(of: empty, in: .xml, expectedPlist: _plistEmptyDictionaryXML)
}
// MARK: - Encoding Top-Level Single-Value Types
func testEncodingTopLevelSingleValueEnum() {
let s1 = Switch.off
_testEncodeFailure(of: s1, in: .binary)
_testEncodeFailure(of: s1, in: .xml)
let s2 = Switch.on
_testEncodeFailure(of: s2, in: .binary)
_testEncodeFailure(of: s2, in: .xml)
}
func testEncodingTopLevelSingleValueStruct() {
let t = Timestamp(3141592653)
_testEncodeFailure(of: t, in: .binary)
_testEncodeFailure(of: t, in: .xml)
}
func testEncodingTopLevelSingleValueClass() {
let c = Counter()
_testEncodeFailure(of: c, in: .binary)
_testEncodeFailure(of: c, in: .xml)
}
// MARK: - Encoding Top-Level Structured Types
func testEncodingTopLevelStructuredStruct() {
// Address is a struct type with multiple fields.
let address = Address.testValue
_testRoundTrip(of: address, in: .binary)
_testRoundTrip(of: address, in: .xml)
}
func testEncodingTopLevelStructuredClass() {
// Person is a class with multiple fields.
let person = Person.testValue
_testRoundTrip(of: person, in: .binary)
_testRoundTrip(of: person, in: .xml)
}
func testEncodingTopLevelDeepStructuredType() {
// Company is a type with fields which are Codable themselves.
let company = Company.testValue
_testRoundTrip(of: company, in: .binary)
_testRoundTrip(of: company, in: .xml)
}
// MARK: - Helper Functions
private var _plistEmptyDictionaryBinary: Data {
return Data(base64Encoded: "YnBsaXN0MDDQCAAAAAAAAAEBAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJ")!
}
private var _plistEmptyDictionaryXML: Data {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict/>\n</plist>\n".data(using: .utf8)!
}
private func _testEncodeFailure<T : Encodable>(of value: T, in format: PropertyListSerialization.PropertyListFormat) {
do {
let encoder = PropertyListEncoder()
encoder.outputFormat = format
let _ = try encoder.encode(value)
expectUnreachable("Encode of top-level \(T.self) was expected to fail.")
} catch {}
}
private func _testRoundTrip<T>(of value: T, in format: PropertyListSerialization.PropertyListFormat, expectedPlist plist: Data? = nil) where T : Codable, T : Equatable {
var payload: Data! = nil
do {
let encoder = PropertyListEncoder()
encoder.outputFormat = format
payload = try encoder.encode(value)
} catch {
expectUnreachable("Failed to encode \(T.self) to plist.")
}
if let expectedPlist = plist {
expectEqual(expectedPlist, payload, "Produced plist not identical to expected plist.")
}
do {
var decodedFormat: PropertyListSerialization.PropertyListFormat = .xml
let decoded = try PropertyListDecoder().decode(T.self, from: payload, format: &decodedFormat)
expectEqual(format, decodedFormat, "Encountered plist format differed from requested format.")
expectEqual(decoded, value, "\(T.self) did not round-trip to an equal value.")
} catch {
expectUnreachable("Failed to decode \(T.self) from plist.")
}
}
}
// MARK: - Test Types
/* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */
// MARK: - Empty Types
fileprivate struct EmptyStruct : Codable, Equatable {
static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool {
return true
}
}
fileprivate class EmptyClass : Codable, Equatable {
static func ==(_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool {
return true
}
}
// MARK: - Single-Value Types
/// A simple on-off switch type that encodes as a single Bool value.
fileprivate enum Switch : Codable {
case off
case on
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
switch try container.decode(Bool.self) {
case false: self = .off
case true: self = .on
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .off: try container.encode(false)
case .on: try container.encode(true)
}
}
}
/// A simple timestamp type that encodes as a single Double value.
fileprivate struct Timestamp : Codable {
let value: Double
init(_ value: Double) {
self.value = value
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(Double.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.value)
}
}
/// A simple referential counter type that encodes as a single Int value.
fileprivate final class Counter : Codable {
var count: Int = 0
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
count = try container.decode(Int.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.count)
}
}
// MARK: - Structured Types
/// A simple address type that encodes as a dictionary of values.
fileprivate struct Address : Codable, Equatable {
let street: String
let city: String
let state: String
let zipCode: Int
let country: String
init(street: String, city: String, state: String, zipCode: Int, country: String) {
self.street = street
self.city = city
self.state = state
self.zipCode = zipCode
self.country = country
}
static func ==(_ lhs: Address, _ rhs: Address) -> Bool {
return lhs.street == rhs.street &&
lhs.city == rhs.city &&
lhs.state == rhs.state &&
lhs.zipCode == rhs.zipCode &&
lhs.country == rhs.country
}
static var testValue: Address {
return Address(street: "1 Infinite Loop",
city: "Cupertino",
state: "CA",
zipCode: 95014,
country: "United States")
}
}
/// A simple person class that encodes as a dictionary of values.
fileprivate class Person : Codable, Equatable {
let name: String
let email: String
init(name: String, email: String) {
self.name = name
self.email = email
}
static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.email == rhs.email
}
static var testValue: Person {
return Person(name: "Johnny Appleseed", email: "[email protected]")
}
}
/// A simple company struct which encodes as a dictionary of nested values.
fileprivate struct Company : Codable, Equatable {
let address: Address
var employees: [Person]
init(address: Address, employees: [Person]) {
self.address = address
self.employees = employees
}
static func ==(_ lhs: Company, _ rhs: Company) -> Bool {
return lhs.address == rhs.address && lhs.employees == rhs.employees
}
static var testValue: Company {
return Company(address: Address.testValue, employees: [Person.testValue])
}
}
// MARK: - Run Tests
#if !FOUNDATION_XCTEST
var PropertyListEncoderTests = TestSuite("TestPropertyListEncoder")
PropertyListEncoderTests.test("testEncodingTopLevelEmptyStruct") { TestPropertyListEncoder().testEncodingTopLevelEmptyStruct() }
PropertyListEncoderTests.test("testEncodingTopLevelEmptyClass") { TestPropertyListEncoder().testEncodingTopLevelEmptyClass() }
PropertyListEncoderTests.test("testEncodingTopLevelSingleValueEnum") { TestPropertyListEncoder().testEncodingTopLevelSingleValueEnum() }
PropertyListEncoderTests.test("testEncodingTopLevelSingleValueStruct") { TestPropertyListEncoder().testEncodingTopLevelSingleValueStruct() }
PropertyListEncoderTests.test("testEncodingTopLevelSingleValueClass") { TestPropertyListEncoder().testEncodingTopLevelSingleValueClass() }
PropertyListEncoderTests.test("testEncodingTopLevelStructuredStruct") { TestPropertyListEncoder().testEncodingTopLevelStructuredStruct() }
PropertyListEncoderTests.test("testEncodingTopLevelStructuredClass") { TestPropertyListEncoder().testEncodingTopLevelStructuredClass() }
PropertyListEncoderTests.test("testEncodingTopLevelStructuredClass") { TestPropertyListEncoder().testEncodingTopLevelStructuredClass() }
PropertyListEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestPropertyListEncoder().testEncodingTopLevelDeepStructuredType() }
runAllTests()
#endif
| 33.613793 | 229 | 0.704144 |
0a98afc9dc306035d7b3c9c8f8e87971d590e998 | 1,355 | //
// APIRouter.swift
// SixtCars
//
// Created by Hesham on 6/18/18.
// Copyright © 2018 Hesham. All rights reserved.
//
import Alamofire
enum APIRouter: URLRequestConvertible {
case getProperties
//MARK: - Request Parameters
var method: HTTPMethod {
switch self {
case .getProperties:
return .get
}
}
var path: String {
switch self {
case .getProperties:
return Config.EndpointsPaths.properties
}
}
var parameters: Parameters? {
switch self {
case .getProperties:
return nil
}
}
//MARK: - Convert to URLRequest
func asURLRequest() throws -> URLRequest {
let url = try Config.apiBaseURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.contentType.rawValue)
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
return urlRequest
}
}
| 26.057692 | 112 | 0.600738 |
e2e31870a362f4a6f722730c8f378ccffe2e10f7 | 2,828 | /*
* Copyright 2016 IBM Corp.
* 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.
*/
/**
Contains useful data received from an HTTP network response.
*/
public class Response {
// MARK: Properties (API)
/// HTTP status of the response
public let statusCode: Int?
/// HTTP headers from the response
public let headers: [NSObject: AnyObject]?
/// The body of the response as a String.
/// Returns nil if there is no body or an exception occurred when building the response string.
public let responseText: String?
/// The body of the response as NSData.
/// Returns nil if there is no body or if the response is not valid NSData.
public let responseData: NSData?
/// Does the response contain a 2xx status code
public let isSuccessful: Bool
// MARK: Properties (internal)
internal let httpResponse: NSHTTPURLResponse?
internal let isRedirect: Bool
// MARK: Initializer
/**
Store data from the NSHTTPURLResponse
- parameter responseData: Data returned from the server
- parameter httpResponse: Response object returned from the NSURLSession request
- parameter isRedirect: True if the response requires a redirect
*/
public init(responseData: NSData?, httpResponse: NSHTTPURLResponse?, isRedirect: Bool) {
self.isRedirect = isRedirect
self.httpResponse = httpResponse
self.headers = httpResponse?.allHeaderFields
self.statusCode = httpResponse?.statusCode
self.responseData = responseData
self.responseText = Response.buildResponseStringWithData(responseData)
if let status = statusCode {
isSuccessful = (200..<300 ~= status)
}
else {
isSuccessful = false
}
}
// Try to convert response NSData to String
static private func buildResponseStringWithData(responseData: NSData?) -> String? {
var responseAsText: String?
if responseData != nil, let responseAsNSString = NSString(data: responseData!, encoding: NSUTF8StringEncoding) {
responseAsText = String(responseAsNSString)
}
return responseAsText
}
}
| 32.883721 | 120 | 0.657709 |
71905dab5986d90be1e586c10f353971e71a087b | 393 | //
// ForgotPasswordResponse.swift
// FusionAuth Swift Client
//
// Created by Everaldlee Johnson on 12/11/18.
// Copyright © 2018 F0rever_Johnson. All rights reserved.
//
import Foundation
public struct ForgotPasswordResponse:Codable {
public var changePasswordId:String?
public init(changePasswordId: String? = nil) {
self.changePasswordId = changePasswordId
}
}
| 20.684211 | 58 | 0.727735 |
3acfa71eb06bf640aa30a35dc618d4b64419126c | 17,280 | //
// VectorMath.swift
// OpenStreetMap
//
// Created by Bryce Cogswell on 12/9/12.
// Copyright (c) 2012 Bryce Cogswell. All rights reserved.
//
// On 32-bit systems the CoreGraphics CGFloat (e.g. float not double) doesn't have
// enough precision for a lot of values we work with. Therefore we define our own
// OsmPoint, etc that is explicitely 64-bit double
import CoreLocation
import UIKit
// https://developer.apple.com/library/mac/#samplecode/glut/Listings/gle_vvector_h.html
let TRANSFORM_3D = 0
// MARK: Point
extension CGPoint {
static let zero = CGPoint(x: 0.0, y: 0.0)
@inline(__always) func withOffset(_ dx: CGFloat, _ dy: CGFloat) -> CGPoint {
return CGPoint(x: x + dx,
y: y + dy)
}
@inline(__always) func minus(_ b: CGPoint) -> CGPoint {
return CGPoint(x: x - b.x,
y: y - b.y)
}
@inline(__always) func plus(_ b: CGPoint) -> CGPoint {
return CGPoint(x: x + b.x,
y: y + b.y)
}
@inline(__always) init(_ pt: OSMPoint) {
self.init(x: pt.x,
y: pt.y)
}
}
@inline(__always) func Dot(_ a: OSMPoint, _ b: OSMPoint) -> Double {
return a.x * b.x + a.y * b.y
}
@inline(__always) func MagSquared(_ a: OSMPoint) -> Double {
return a.x * a.x + a.y * a.y
}
@inline(__always) func Mag(_ a: OSMPoint) -> Double {
return hypot(a.x, a.y)
}
@inline(__always) func Add(_ a: OSMPoint, _ b: OSMPoint) -> OSMPoint {
return OSMPoint(x: a.x + b.x,
y: a.y + b.y)
}
@inline(__always) func Sub(_ a: OSMPoint, _ b: OSMPoint) -> OSMPoint {
return OSMPoint(x: a.x - b.x,
y: a.y - b.y)
}
@inline(__always) func Mult(_ a: OSMPoint, _ c: Double) -> OSMPoint {
return OSMPoint(x: a.x * c,
y: a.y * c)
}
@inline(__always) func CrossMag(_ a: OSMPoint, _ b: OSMPoint) -> Double {
return a.x * b.y - a.y * b.x
}
func LineSegmentsIntersect(_ p0: OSMPoint, _ p1: OSMPoint, _ p2: OSMPoint, _ p3: OSMPoint) -> Bool {
let s1 = Sub(p1, p0)
let s2 = Sub(p3, p2)
let s: Double = (-s1.y * (p0.x - p2.x) + s1.x * (p0.y - p2.y)) / (-s2.x * s1.y + s1.x * s2.y)
let t: Double = (s2.x * (p0.y - p2.y) - s2.y * (p0.x - p2.x)) / (-s2.x * s1.y + s1.x * s2.y)
if s >= 0, s <= 1, t >= 0, t <= 1 {
return true
}
return false
}
func DistanceToVector(_ pos1: OSMPoint, _ dir1: OSMPoint, _ pos2: OSMPoint, _ dir2: OSMPoint) -> Double {
// returned in terms of units of dir1
return CrossMag(Sub(pos2, pos1), dir2) / CrossMag(dir1, dir2)
}
func IntersectionOfTwoVectors(_ pos1: OSMPoint, _ dir1: OSMPoint, _ pos2: OSMPoint, _ dir2: OSMPoint) -> OSMPoint {
let a = CrossMag(Sub(pos2, pos1), dir2) / CrossMag(dir1, dir2)
let pt = Add(pos1, Mult(dir1, a))
return pt
}
// MARK: CGRect
extension CGRect {
@inline(__always) func center() -> CGPoint {
let c = CGPoint(x: origin.x + size.width / 2,
y: origin.y + size.height / 2)
return c
}
@inline(__always) init(_ rc: OSMRect) {
self.init(x: rc.origin.x,
y: rc.origin.y,
width: rc.size.width,
height: rc.size.height)
}
}
// MARK: OSMPoint
struct OSMPoint: Equatable, Codable {
var x: Double
var y: Double
}
extension OSMPoint {
static let zero = OSMPoint(x: 0.0, y: 0.0)
@inline(__always) init(_ pt: CGPoint) {
self.init(x: Double(pt.x), y: Double(pt.y))
}
@inline(__always) init(_ loc: LatLon) {
self.init(x: loc.lon, y: loc.lat)
}
@inline(__always) public static func ==(_ a: OSMPoint, _ b: OSMPoint) -> Bool {
return a.x == b.x && a.y == b.y
}
@inline(__always) func withTransform(_ t: OSMTransform) -> OSMPoint {
#if TRANSFORM_3D
let zp = 0.0
var x = t.m11 * pt.x + t.m21 * pt.y + t.m31 * zp + t.m41
var y = t.m12 * pt.x + t.m22 * pt.y + t.m32 * zp + t.m42
if false {
if t.m34 {
let z = t.m13 * pt.x + t.m23 * pt.y + t.m33 * zp + t.m43
// use z and m34 to "shrink" objects as they get farther away (perspective)
// http://en.wikipedia.org/wiki/3D_projection
let ex = x // eye position
let ey = y
let ez: Double = -1 / t.m34
var p = OSMTransform(1, 0, 0, 0, 0, 1, 0, 0, -ex / ez, -ey / ez, 1, 1 / ez, 0, 0, 0, 0)
x += -ex / ez
y += -ey / ez
}
}
return OSMPoint(x, y)
#else
return OSMPoint(x: self.x * t.a + self.y * t.c + t.tx,
y: self.x * t.b + self.y * t.d + t.ty)
#endif
}
@inline(__always) func unitVector() -> OSMPoint {
let d = Mag(self)
return OSMPoint(x: x / d,
y: y / d)
}
@inline(__always) func distanceToPoint(_ b: OSMPoint) -> Double {
return Mag(Sub(self, b))
}
public func distanceToLineSegment(_ line1: OSMPoint, _ line2: OSMPoint) -> Double {
let length2 = MagSquared(Sub(line1, line2))
if length2 == 0.0 {
return distanceToPoint(line1)
}
let t = Dot(Sub(self, line1), Sub(line2, line1)) / Double(length2)
if t < 0.0 {
return distanceToPoint(line1)
}
if t > 1.0 {
return distanceToPoint(line2)
}
let projection = Add(line1, Mult(Sub(line2, line1), Double(t)))
return distanceToPoint(projection)
}
func distanceFromLine(_ lineStart: OSMPoint, _ lineDirection: OSMPoint) -> Double {
// note: lineDirection must be unit vector
let dir = Sub(lineStart, self)
let dist = Mag(Sub(dir, Mult(lineDirection, Dot(dir, lineDirection))))
return dist
}
func nearestPointOnLineSegment(lineA: OSMPoint, lineB: OSMPoint) -> OSMPoint {
let ap = Sub(self, lineA)
let ab = Sub(lineB, lineA)
let ab2 = ab.x * ab.x + ab.y * ab.y
let ap_dot_ab = Dot(ap, ab)
let t = ap_dot_ab / ab2 // The normalized "distance" from a to point
if t <= 0 {
return lineA
}
if t >= 1.0 {
return lineB
}
return Add(lineA, Mult(ab, t))
}
}
extension OSMPoint: CustomStringConvertible {
var description: String {
return "OSMPoint(x:\(x),y:\(y))"
}
}
// MARK: OSMSize
struct OSMSize: Equatable, Codable {
var width: Double
var height: Double
}
extension OSMSize {
static let zero = OSMSize(width: 0.0, height: 0.0)
@inline(__always) init(_ sz: CGSize) {
self.init(width: Double(sz.width), height: Double(sz.height))
}
@inline(__always) public static func ==(_ a: OSMSize, _ b: OSMSize) -> Bool {
return a.width == b.width && a.height == b.height
}
}
extension OSMSize: CustomStringConvertible {
var description: String {
return "OSMSize(w:\(width),h:\(height))"
}
}
// MARK: OSMRect
struct OSMRect: Equatable, Codable {
var origin: OSMPoint
var size: OSMSize
}
extension OSMRect {
static let zero = OSMRect(origin: OSMPoint(x: 0.0, y: 0.0), size: OSMSize(width: 0.0, height: 0.0))
@inline(__always) init(x: Double, y: Double, width: Double, height: Double) {
self.init(origin: OSMPoint(x: x, y: y), size: OSMSize(width: width, height: height))
}
@inline(__always) init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(
origin: OSMPoint(x: Double(x), y: Double(y)),
size: OSMSize(width: Double(width), height: Double(height)))
}
@inline(__always) init(origin: CGPoint, size: CGSize) {
self.init(origin: OSMPoint(origin), size: OSMSize(size))
}
@inline(__always) init(_ cg: CGRect) {
self.init(x: cg.origin.x, y: cg.origin.y, width: cg.size.width, height: cg.size.height)
}
@inline(__always) func containsPoint(_ pt: OSMPoint) -> Bool {
return pt.x >= origin.x &&
pt.x <= origin.x + size.width &&
pt.y >= origin.y &&
pt.y <= origin.y + size.height
}
@inline(__always) func intersectsRect(_ b: OSMRect) -> Bool {
if origin.x >= b.origin.x + b.size.width { return false }
if origin.y >= b.origin.y + b.size.height { return false }
if origin.x + size.width < b.origin.x { return false }
if origin.y + size.height < b.origin.y { return false }
return true
}
@inline(__always) func containsRect(_ b: OSMRect) -> Bool {
return origin.x <= b.origin.x &&
origin.y <= b.origin.y &&
origin.x + size.width >= b.origin.x + b.size.width &&
origin.y + size.height >= b.origin.y + b.size.height
}
@inline(__always) func union(_ b: OSMRect) -> OSMRect {
let minX = Double(min(origin.x, b.origin.x))
let minY = Double(min(origin.y, b.origin.y))
let maxX = Double(max(origin.x + size.width, b.origin.x + b.size.width))
let maxY = Double(max(origin.y + size.height, b.origin.y + b.size.height))
let r = OSMRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
return r
}
@inline(__always) public static func ==(_ a: OSMRect, _ b: OSMRect) -> Bool {
return a.origin == b.origin && a.size == b.size
}
@inline(__always) func withTransform(_ transform: OSMTransform) -> OSMRect {
var p1 = origin
var p2 = OSMPoint(x: origin.x + size.width, y: origin.y + size.height)
p1 = p1.withTransform(transform)
p2 = p2.withTransform(transform)
let r2 = OSMRect(x: p1.x,
y: p1.y,
width: p2.x - p1.x,
height: p2.y - p1.y)
return r2
}
func corners() -> [OSMPoint] {
return [OSMPoint(x: origin.x, y: origin.y),
OSMPoint(x: origin.x + size.width, y: origin.y),
OSMPoint(x: origin.x + size.width, y: origin.y + size.height),
OSMPoint(x: origin.x, y: origin.y + size.height)]
}
@inline(__always) func offsetBy(dx: Double, dy: Double) -> OSMRect {
var rect = self
rect.origin.x += dx
rect.origin.y += dy
return rect
}
func intersectsLineSegment(_ p1: OSMPoint, _ p2: OSMPoint) -> Bool {
let a_rectangleMinX = origin.x
let a_rectangleMinY = origin.y
let a_rectangleMaxX = origin.x + size.width
let a_rectangleMaxY = origin.y + size.height
let a_p1x = p1.x
let a_p1y = p1.y
let a_p2x = p2.x
let a_p2y = p2.y
// Find min and max X for the segment
var minX = a_p1x
var maxX = a_p2x
if a_p1x > a_p2x {
minX = a_p2x
maxX = a_p1x
}
// Find the intersection of the segment's and rectangle's x-projections
if maxX > a_rectangleMaxX {
maxX = a_rectangleMaxX
}
if minX < a_rectangleMinX {
minX = a_rectangleMinX
}
if minX > maxX {
// If their projections do not intersect return false
return false
}
// Find corresponding min and max Y for min and max X we found before
var minY = a_p1y
var maxY = a_p2y
let dx = a_p2x - a_p1x
if abs(dx) > 0.0000001 {
let a = (a_p2y - a_p1y) / dx
let b = a_p1y - a * a_p1x
minY = a * minX + b
maxY = a * maxX + b
}
if minY > maxY {
let tmp = maxY
maxY = minY
minY = tmp
}
// Find the intersection of the segment's and rectangle's y-projections
if maxY > a_rectangleMaxY {
maxY = a_rectangleMaxY
}
if minY < a_rectangleMinY {
minY = a_rectangleMinY
}
if minY > maxY {
// If Y-projections do not intersect return false
return false
}
return true
}
func metersSizeForLatLon() -> OSMSize {
let w = GreatCircleDistance(LatLon(x: origin.x, y: origin.y), LatLon(x: origin.x + size.width, y: origin.y))
let h = GreatCircleDistance(LatLon(x: origin.x, y: origin.y), LatLon(x: origin.x, y: origin.y + size.height))
return OSMSize(width: w, height: h)
}
var boundsString: String {
return "OSMRect(ul:(\(origin.x),\(origin.y)),lr:(\(origin.x + size.width),\(origin.y + size.height))"
}
}
extension OSMRect: CustomStringConvertible {
var description: String {
return "OSMRect(x:\(origin.x),y:\(origin.y),w:\(size.width),h:\(size.height)"
}
}
// MARK: OSMTransform
#if TRANSFORM_3D
typealias OSMTransform = CATransform3D
#else
struct OSMTransform: Equatable {
// | a b 0 |
// | c d 0 |
// | tx ty 1 |
var a, b, c, d: Double
var tx, ty: Double
}
#endif
extension OSMTransform {
#if TRANSFORM_3D
static let identity = CATransform3DIdentity
#else
static let identity = OSMTransform(a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)
#endif
/// Rotation around Z-axis
@inline(__always) func rotation() -> Double {
#if TRANSFORM_3D
return atan2(m12, m11)
#else
return atan2(b, a)
#endif
}
// Scaling factor: 1.0 == identity
@inline(__always) func scale() -> Double {
#if TRANSFORM_3D
let d = sqrt(m11 * m11 + m12 * m12 + m13 * m13)
return d
#else
return hypot(a, c)
#endif
}
@inline(__always) func zoom() -> Double {
let scaleX = scale()
return log2(scaleX)
}
// Inverse transform
func inverse() -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DInvert(self)
#else
// | a b 0 |
// | c d 0 |
// | tx ty 1 |
let det = determinant()
let s = 1.0 / det
let a = s * self.d
let c = s * -self.c
let tx = s * (self.c * self.ty - self.d * self.tx)
let b = s * -self.b
let d = s * self.a
let ty = s * (self.b * self.tx - self.a * self.ty)
let r = OSMTransform(a: a, b: b, c: c, d: d, tx: tx, ty: ty)
return r
#endif
}
// Return CGFloat equivalent
@inline(__always) func cgAffineTransform() -> CGAffineTransform {
#if TRANSFORM_3D
return CATransform3DGetAffineTransform(self)
#else
let t = CGAffineTransform(
a: CGFloat(a),
b: CGFloat(b),
c: CGFloat(c),
d: CGFloat(d),
tx: CGFloat(tx),
ty: CGFloat(ty))
return t
#endif
}
@inline(__always) static func ==(_ t1: OSMTransform, _ t2: OSMTransform) -> Bool {
var t1 = t1
var t2 = t2
return memcmp(&t1, &t2, MemoryLayout.size(ofValue: t1)) == 0
}
/// Returns the unit vector for (1.0,0.0) rotated by the current transform
@inline(__always) func unitX() -> OSMPoint {
#if TRANSFORM_3D
let p = UnitVector(OSMPoint(m11, m12))
return p
#else
return OSMPoint(x: a, y: b).unitVector()
#endif
}
@inline(__always) func translation() -> OSMPoint {
#if TRANSFORM_3D
let p = OSMPoint(m41, m42)
return p
#else
return OSMPoint(x: tx, y: ty)
#endif
}
@inline(__always) func scaledBy(_ scale: Double) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DScale(self, CGFloat(scale), CGFloat(scale), CGFloat(scale))
#else
var t = self
t.a *= scale
t.b *= scale
t.c *= scale
t.d *= scale
return t
#endif
}
@inline(__always) func translatedBy(dx: Double, dy: Double) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DTranslate(self, CGFloat(dx), CGFloat(dy), 0)
#else
var t = self
t.tx += t.a * dx + t.c * dy
t.ty += t.b * dx + t.d * dy
return t
#endif
}
@inline(__always) func scaledBy(scaleX: Double, scaleY: Double) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DScale(self, CGFloat(scale), CGFloat(scaleY), 1.0)
#else
var t = self
t.a *= scaleX
t.b *= scaleY
t.c *= scaleX
t.d *= scaleY
return t
#endif
}
@inline(__always) func rotatedBy(_ angle: Double) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DRotate(self, CGFloat(angle), 0, 0, 1)
#else
let s = sin(angle)
let c = cos(angle)
let t = OSMTransform(a: c, b: s, c: -s, d: c, tx: 0.0, ty: 0.0)
return t.concat(self)
#endif
}
@inline(__always) static func translation(_ dx: Double, _ dy: Double) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DMakeTranslation(CGFloat(dx), CGFloat(dy), 0)
#else
let t = OSMTransform(a: 1, b: 0, c: 0, d: 1, tx: dx, ty: dy)
return t
#endif
}
@inline(__always) func concat(_ b: OSMTransform) -> OSMTransform {
#if TRANSFORM_3D
return CATransform3DConcat(self, b)
#else
// | a b 0 |
// | c d 0 |
// | tx ty 1 |
let a = self
let t = OSMTransform(
a: a.a * b.a + a.b * b.c,
b: a.a * b.b + a.b * b.d,
c: a.c * b.a + a.d * b.c,
d: a.c * b.b + a.d * b.d,
tx: a.tx * b.a + a.ty * b.c + b.tx,
ty: a.tx * b.b + a.ty * b.d + b.ty)
return t
#endif
}
func determinant() -> Double {
return a * d - b * c
}
}
struct LatLon {
var lon: Double
var lat: Double
static let zero = LatLon(lon: 0.0, lat: 0.0)
init(lon: Double, lat: Double) {
self.lon = lon
self.lat = lat
}
init(x: Double, y: Double) {
lon = x
lat = y
}
init(latitude: Double, longitude: Double) {
lon = longitude
lat = latitude
}
init(_ loc: CLLocationCoordinate2D) {
lon = loc.longitude
lat = loc.latitude
}
init(_ pt: OSMPoint) {
self.init(lon: pt.x, lat: pt.y)
}
}
// MARK: miscellaneous
/// Radius in meters
let EarthRadius: Double = 6378137.0
@inline(__always) func radiansFromDegrees(_ degrees: Double) -> Double {
return degrees * (.pi / 180)
}
func MetersPerDegreeAt(latitude: Double) -> OSMPoint {
let latitude = latitude * .pi / 180
let lat = 111132.954 - 559.822 * cos(2 * latitude) + 1.175 * cos(4 * latitude)
let lon = 111132.954 * cos(latitude)
return OSMPoint(x: lon, y: lat)
}
// area in square meters
func SurfaceAreaOfRect(_ latLon: OSMRect) -> Double {
// http://mathforum.org/library/drmath/view/63767.html
let lon1 = latLon.origin.x * .pi / 180.0
let lat1 = latLon.origin.y * .pi / 180.0
let lon2: Double = (latLon.origin.x + latLon.size.width) * .pi / 180.0
let lat2: Double = (latLon.origin.y + latLon.size.height) * .pi / 180.0
let A = EarthRadius * EarthRadius * abs(sin(lat1) - sin(lat2)) * abs(lon1 - lon2)
return A
}
// http://www.movable-type.co.uk/scripts/latlong.html
/// Distance between two lon,lat points in degrees, result in meters
func GreatCircleDistance(_ p1: LatLon, _ p2: LatLon) -> Double {
// haversine formula
let dlon = (p2.lon - p1.lon) * .pi / 180
let dlat = (p2.lat - p1.lat) * .pi / 180
let a: Double = pow(sin(dlat / 2), 2) + cos(p1.lat * .pi / 180) * cos(p2.lat * .pi / 180) * pow(sin(dlon / 2), 2)
let c: Double = 2 * atan2(sqrt(a), sqrt(1 - a))
let meters = EarthRadius * c
return meters
}
| 25.486726 | 115 | 0.62581 |
ef5d10af00758f9a902b4c0e09918ce30c35135e | 1,228 | //
// FinanceViewController.swift
// MyNYUAD
//
// Created by Tarlan Askaruly on 05.11.2021.
// Copyright © 2021 Tony Morales. All rights reserved.
//
import Foundation
import UIKit
import WebKit
class FinanceViewController: UIViewController {
var wkWebView: WKWebView?
var uiWebView: UIWebView?
override func viewDidLoad() {
super.viewDidLoad()
let screenSize: CGRect = UIScreen.main.bounds
let frameRect: CGRect = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
let requestObj: URLRequest = URLRequest(url: URL(string: "http://10.225.71.95:3000/finance")!);
if ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 8, minorVersion: 0, patchVersion: 0)) {
self.wkWebView = WKWebView(frame: frameRect)
self.wkWebView?.load(requestObj)
self.view.addSubview(self.wkWebView!)
} else {
self.uiWebView = UIWebView(frame: frameRect)
self.uiWebView?.loadRequest(requestObj)
self.view.addSubview(self.uiWebView!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 27.288889 | 126 | 0.655537 |
edf71d27d733eb1720331ee5b281aae2243d5024 | 15,799 | //
// TransactionsTests.swift
//
//
// Created by Dusan Klinec on 15.09.2021.
//
import Foundation
import XCTest
import Combine
import Quick
import Nimble
#if canImport(AnyCodable)
import AnyCodable
#endif
@testable import BlockfrostSwiftSDK
final class TransactionsTests: QuickSpec {
override func spec() {
var api: CardanoTransactionsAPI!
beforeEach {
let cfg = TestUtils.initConfig()
if cfg == nil {
fatalError("Project ID is not defined, use env var BF_PROJECT_ID")
}
api = CardanoTransactionsAPI(config: cfg)
}
describe("transactions") {
it("byHash"){
waitUntil(timeout: 10) { done in
let _ = api.getTransaction(hash: "28172ea876c3d1e691284e5179fae2feb3e69d7d41e43f8023dc380115741026") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r.block).to(equal("e6369fee087d31192016b1659f1c381e9fc4925339278a4eef6f340c96c1947f"))
expect(r.blockHeight).to(equal(5040611))
expect(r.index).to(equal(0))
expect(r.outputAmount).to(equal([TxContentOutputAmount(unit: "lovelace", quantity: "701374004958")]))
expect(r.fees).to(equal("874781"))
expect(r.deposit).to(equal("0"))
expect(r.size).to(equal(16346))
expect(r.invalidBefore).to(beNil())
expect(r.invalidHereafter).to(equal("15657684"))
expect(r.utxoCount).to(equal(80))
expect(r.withdrawalCount).to(equal(0))
expect(r.delegationCount).to(equal(0))
expect(r.stakeCertCount).to(equal(0))
expect(r.poolUpdateCount).to(equal(0))
expect(r.poolRetireCount).to(equal(0))
done()
}
}
}
it("utxos"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionUtxos(hash: "927edb96f3386ab91b5f5d85d84cb4253c65b1c2f65fa7df25f81fab1d62987a") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r.hash).to(equal("927edb96f3386ab91b5f5d85d84cb4253c65b1c2f65fa7df25f81fab1d62987a"))
expect(r.inputs).to(equal([]))
expect(r.outputs).to(equal([
TxContentUtxoOutputs(
address: "Ae2tdPwUPEZ9vtyppa1FdJzvqJZkEcXgdHxVYAzTWcPaoNycVq5rc36LC1S",
amount: [TxContentUtxoAmount(unit: "lovelace", quantity: "538861000000")])]))
done()
}
}
}
it("withdrawals"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionWithdrawals(hash: "9f811b021492a5544207f7b566b4e67c87f0918b9e7055ab3074d552ab18e895") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(1))
expect(r[0].address).to(equal("stake1ux77thpfertrfhkq3tlmssucn30ddvvn3s9fhvkvx7dd3msgmxve0"))
expect(r[0].amount).to(equal("7911187966"))
done()
}
}
}
it("mirs"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionMirs(hash: "7b57f2cf1c442c563647ab29669c88b9116c2668d31d42526ff27ed614da1252") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
done()
}
}
}
it("delegations"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionDelegations(hash: "c2120581050a1116ab38a5ac8a62d64df4cf12cf3370d22337201d36eb65fcc4") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(1))
expect(r[0].index).to(equal(1))
expect(r[0].certIndex).to(equal(1))
expect(r[0].address).to(equal("stake1uyhk4jwrrp683w8n9hutkddr0nns4nuun04m2x3a6v0s9cck0z4k9"))
expect(r[0].poolId).to(equal("pool1zgxvcqf0dvh0ze56ev2ayjvuex3zdd3hgxzdrcezkx497mv3l7s"))
done()
}
}
}
it("pool updates"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionPoolUpdates(hash: "28bd5e8c342ab89d6642e446cb299058ea36256af1718e4af9326898ce4192d7") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(2))
expect(r[0].certIndex).to(equal(0))
expect(r[0].poolId).to(equal("pool1kchver88u3kygsak8wgll7htr8uxn5v35lfrsyy842nkscrzyvj"))
expect(r[0].vrfKey).to(equal("b4506cbdf5faeeb7bc771d0c17eea2e7e94749ec5a63e78a42d9ed8aad6baae5"))
expect(r[0].pledge).to(equal("100000000000"))
expect(r[0].marginCost).to(equal(0.018))
expect(r[0].fixedCost).to(equal("340000000"))
expect(r[0].rewardAccount).to(equal("stake1u97v0sjx96u5lydjfe2g5qdwkj6plm87h80q5vc0ma6wjpq22mh4c"))
expect(r[0].owners).to(equal(["stake1ux69nctlngdhx99a6w8hrtexu89p9prqk8vmseg9qmmquyqhuns53"]))
let meta0 = (r[0].metadata?.value) as? [String: Any?]
expect(meta0).toNot(beNil())
expect(meta0!["url"] as? String).to(equal("https://stakhanovite.io/cardano/stkh-1.json"))
expect(meta0!["hash"] as? String).to(equal("0f519c0478527c6fd05556ecb31fafe9e5a6b9861fac96f5935381b3e328ee5d"))
expect(meta0!["ticker"] as? String).toNot(beNil())
expect(meta0!["name"] as? String).toNot(beNil())
expect(meta0!["description"] as? String).toNot(beNil())
expect(meta0!["homepage"] as? String).toNot(beNil())
expect(r[0].relays).toNot(beEmpty())
expect((r[0].relays[0].value as? [String: Any?])?["ipv4"] as? String).to(beNil())
expect((r[0].relays[0].value as? [String: Any?])?["ipv6"] as? String).to(beNil())
expect((r[0].relays[0].value as? [String: Any?])?["dns"] as? String).to(equal("cardano-relay.stakhanovite.io"))
expect((r[0].relays[0].value as? [String: Any?])?["dns_srv"] as? String).to(beNil())
expect((r[0].relays[0].value as? [String: Any?])?["port"] as? Int).to(equal(7001))
expect(r[1].certIndex).to(equal(1))
expect(r[1].poolId).to(equal("pool1s7t7mfc89syw93h07aammaccnua66yn6d4l0mqt7zqurz2mczvq"))
expect(r[1].vrfKey).to(equal("f399304ca66731d66b739e4df6a94f32ab10b34450fb21b03720d2c1d45d59d2"))
expect(r[1].pledge).to(equal("10000000000"))
expect(r[1].marginCost).to(equal(0.018))
expect(r[1].fixedCost).to(equal("340000000"))
expect(r[1].rewardAccount).to(equal("stake1u97v0sjx96u5lydjfe2g5qdwkj6plm87h80q5vc0ma6wjpq22mh4c"))
expect(r[1].owners).to(equal(["stake1uxclfpuwmmsdxjtqy7ee845246xlk6k4r5rxj6sexsh8caqf2z5dm"]))
let meta1 = (r[1].metadata?.value) as? [String: Any?]
expect(meta1).toNot(beNil())
expect(meta1!["url"] as? String).to(equal("https://stakhanovite.io/cardano/stkh-2.json"))
expect(meta1!["hash"] as? String).to(equal("11171d873f8f5b704552111d75b629f840b1c3399b49d9642cf12970031583b7"))
expect(meta1!["ticker"] as? String).to(beNil())
expect(meta1!["name"] as? String).to(beNil())
expect(meta1!["description"] as? String).to(beNil())
expect(meta1!["homepage"] as? String).to(beNil())
expect(r[1].relays).toNot(beEmpty())
expect((r[1].relays[0].value as? [String: Any?])?["ipv4"] as? String).to(beNil())
expect((r[1].relays[0].value as? [String: Any?])?["ipv6"] as? String).to(beNil())
expect((r[1].relays[0].value as? [String: Any?])?["dns"] as? String).to(equal("cardano-relay.stakhanovite.io"))
expect((r[1].relays[0].value as? [String: Any?])?["dns_srv"] as? String).to(beNil())
expect((r[1].relays[0].value as? [String: Any?])?["port"] as? Int).to(equal(7001))
done()
}
}
}
it("stakes"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionStakes(hash: "c2120581050a1116ab38a5ac8a62d64df4cf12cf3370d22337201d36eb65fcc4") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(1))
expect(r[0].certIndex).to(equal(0))
expect(r[0].address).to(equal("stake1uyhk4jwrrp683w8n9hutkddr0nns4nuun04m2x3a6v0s9cck0z4k9"))
expect(r[0].registration).to(equal(true))
done()
}
}
}
it("pool retires"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionPoolRetires(hash: "33770d42c7bc8a9a0bc9830ffb97941574dc61dc534796dd8614b99b6aadace4") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(1))
expect(r[0].certIndex).to(equal(0))
expect(r[0].poolId).to(equal("pool1g36eg8e6tr6sur6y3cfpd8lglny3axh6pgka3acpnfyh22svdth"))
expect(r[0].retiringEpoch).to(equal(236))
done()
}
}
}
it("tsxMetadata"){
waitUntil(timeout: 10) { done in
let _ = api.getTransactionMetadata(hash: "e641005803337a553a03cf3c11a1819491a629bd7d0a3c39e4866a01b5dac36d") { resp in
guard let r = TestUtils.getResult(resp: resp) else {
done(); return;
}
expect(r).toNot(beNil())
expect(r).toNot(beEmpty())
expect(r).to(haveCount(1))
expect(r[0].label).to(equal("1968"))
expect(CodableHelper.eqAny(r[0].jsonMetadata,
["TSLA": [["value": "865.85", "source": "investorsExchange"]],
"DRAND": ["round": 492700, "randomness": "22966996b523a4726c3df9d7b8bae50230ef08a7452c53d64eacc2dad632afc5"],
"ADABTC": [["value": "7.96e-06", "source": "coinGecko"]],
"ADAEUR": [["value": "0.260806", "source": "coinGecko"]],
"ADAUSD": [["value": "0.318835", "source": "coinGecko"], ["value": "0.32190816861292343", "source": "ergoOracles"]],
"AGIBTC": [["value": "0.077643", "source": "coinGecko"]],
"BTCUSD": [["value": "40088", "source": "coinGecko"]],
"ERGUSD": [["value": "0.573205", "source": "coinGecko"], ["value": "0.5728722202262749", "source": "ergoOracles"]],
"BTCDIFF": [["value": "20607418304385.63", "source": "blockBook"]]])).to(beTrue())
expect(CodableHelper.eqAny(r[0].jsonMetadata,
["TSLA": [["value": "865.851", "source": "investorsExchange"]],
"DRAND": ["round": 492700, "randomness": "22966996b523a4726c3df9d7b8bae50230ef08a7452c53d64eacc2dad632afc5"],
"ADABTC": [["value": "7.96e-06", "source": "coinGecko"]],
"ADAEUR": [["value": "0.260806", "source": "coinGecko"]],
"ADAUSD": [["value": "0.318835", "source": "coinGecko"], ["value": "0.32190816861292343", "source": "ergoOracles"]],
"AGIBTC": [["value": "0.077643", "source": "coinGecko"]],
"BTCUSD": [["value": "40088", "source": "coinGecko"]],
"ERGUSD": [["value": "0.573205", "source": "coinGecko"], ["value": "0.5728722202262749", "source": "ergoOracles"]],
"BTCDIFF": [["value": "20607418304385.63", "source": "blockBook"]]])).to(beFalse())
done()
}
}
}
it("submit") {
let dummyTx = "33770d42c7bc8a9a0bc9830ffb97941574dc61dc534796dd8614b99b6aadace4".data(using: .ascii)!
waitUntil(timeout: 10) { done in
let _ = api.submitTransaction(transaction: dummyTx) { resp in
switch (resp) {
case let .failure(err):
expect(err).to(matchError(ErrorResponse.self))
let respErr = err as! ErrorResponse
if case let .errorStatus(scode, status, _, _) = respErr {
expect(scode).to(equal(400))
expect(status.statusCode).to(equal(400))
} else {
fail("Invalid error message")
}
break
case .success(_):
fail("Did not expect to succeed")
break
}
done()
}
}
}
}
}
}
| 52.839465 | 145 | 0.478005 |
338cb2b7bb2822dee731e0703a533b0e7f377e0d | 4,659 | import Foundation
import GoogleMobileAds
import PrebidMobile
import AppTrackingTransparency
import AdSupport
class PrebidBannerView: NSObject, FlutterPlatformView, GADBannerViewDelegate {
private var container: UIView!
private let channel: FlutterMethodChannel!
init(frame: CGRect, viewIdentifier viewId: Int64, messenger: FlutterBinaryMessenger) {
container = UIView(frame: frame)
channel = FlutterMethodChannel(name: "plugins.capolista.se/prebid_mobile_flutter/banner/\(viewId)", binaryMessenger: messenger)
super.init()
//container.backgroundColor = UIColor.clear
channel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
self.handle(call, result: result)
})
}
func view() -> UIView {
return container
}
private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "load":
load(call, result: result)
default:
result(FlutterMethodNotImplemented)
}
}
private func load(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let argument = call.arguments as! Dictionary<String, Any>
let publisherId = argument["publisherId"] as? String ?? ""
let adUnitId = argument["adUnitId"] as? String ?? ""
let configId = argument["configId"] as? String ?? ""
let serverHost = argument["serverHost"] as? String ?? ""
let adHeight = argument["adHeight"] as? Double ?? 0
let adWidth = argument["adWidth"] as? Double ?? 0
Prebid.shared.prebidServerAccountId = publisherId
do {
try Prebid.shared.setCustomPrebidServer(url: serverHost)
} catch {
print("ERROR")
}
let adSize = CGSize(width: adWidth, height: adHeight)
let bannerUnit = BannerAdUnit(configId: configId, size: adSize)
let bannerView = GADBannerView(adSize: GADAdSizeFromCGSize(adSize))
let request = GADRequest()
bannerView.adUnitID = adUnitId
bannerView.delegate = self
bannerView.rootViewController = UIApplication.shared.delegate!.window!!.rootViewController!
addBannerViewToView(bannerView)
bannerView.backgroundColor = UIColor.clear
bannerUnit.fetchDemand(adObject:request) {(ResultCode ) in
self.channel.invokeMethod("demandFetched", arguments: ["name": ResultCode.name()])
if #available(iOS 14, *) {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
bannerView.load(request)
})
} else {
bannerView.load(request)
}
}
// bannerView.load(request)
result(nil)
}
private func addBannerViewToView(_ bannerView: GADBannerView) {
container.addSubview(bannerView)
container.addConstraints([NSLayoutConstraint(item: bannerView,
attribute: .centerX,
relatedBy: .equal,
toItem: container,
attribute: .centerX,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: bannerView,
attribute: .centerY,
relatedBy: .equal,
toItem: container,
attribute: .centerY,
multiplier: 1,
constant: 0)])
}
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
AdViewUtils.findPrebidCreativeSize(bannerView,
success: { (size) in
guard let bannerView = bannerView as? GADBannerView else {
return
}
},
failure: { (error) in
print("error: \(error)")
})
}
}
| 41.598214 | 135 | 0.505044 |
64218c2847e46f76a042d767a76f1c285b31d53d | 2,346 | //
// Credential.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
#if os(macOS) || os(iOS)
import Accounts
#endif
public class Credential {
public struct OAuthAccessToken {
public internal(set) var key: String
public internal(set) var secret: String
public internal(set) var verifier: String?
public internal(set) var screenName: String?
public internal(set) var userID: String?
public init(key: String, secret: String) {
self.key = key
self.secret = secret
}
public init(queryString: String) {
var attributes = queryString.queryStringParameters
self.key = attributes["oauth_token"]!
self.secret = attributes["oauth_token_secret"]!
self.screenName = attributes["screen_name"]
self.userID = attributes["user_id"]
}
}
public internal(set) var accessToken: OAuthAccessToken?
#if os(macOS) || os(iOS)
public internal(set) var account: ACAccount?
public init(account: ACAccount) {
self.account = account
}
#endif
public init(accessToken: OAuthAccessToken) {
self.accessToken = accessToken
}
}
| 31.28 | 81 | 0.682438 |
8fc593a04d3f6eb7e6430079b265504575049d43 | 2,080 | //
// NotificationConfiguration.swift
// AWattPrice
//
// Created by Léon Becker on 15.08.21.
//
import Foundation
struct GeneralNotificationConfiguration: Encodable {
var region: Region
var tax: Bool
enum CodingKeys: CodingKey {
case region, tax
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(region.apiName, forKey: .region)
try container.encode(tax, forKey: .tax)
}
}
struct PriceBelowNotificationNotificationConfiguration: Encodable {
var active: Bool
var belowValue: Int
enum CodingKeys: String, CodingKey {
case active
case belowValue = "below_value"
}
}
struct NotificationsNotificationConfiguration: Encodable {
var priceBelow: PriceBelowNotificationNotificationConfiguration
enum CodingKeys: String, CodingKey {
case priceBelow = "price_below"
}
}
struct NotificationConfiguration: Encodable {
var token: String?
var general: GeneralNotificationConfiguration
var notifications: NotificationsNotificationConfiguration
static func create(
_ token: String?, _ currentSetting: CurrentSetting, _ notificationSetting: CurrentNotificationSetting
) -> NotificationConfiguration {
let currentEntity = currentSetting.entity!
let notificationEntity = notificationSetting.entity!
let selectedRegion = Region(rawValue: currentEntity.regionIdentifier)!
let general = GeneralNotificationConfiguration(region: selectedRegion, tax: currentEntity.pricesWithVAT)
let priceBelowNotification = PriceBelowNotificationNotificationConfiguration(
active: notificationEntity.priceDropsBelowValueNotification, belowValue: notificationEntity.priceBelowValue
)
let notifications = NotificationsNotificationConfiguration(priceBelow: priceBelowNotification)
return NotificationConfiguration(token: token, general: general, notifications: notifications)
}
}
| 32.5 | 119 | 0.728846 |
72f6b1ddcc9949586386976c9455c4d70d818f57 | 2,111 | //
// Typecasting.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// 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.
//
/// Same as `unsafeBitCast(_:to:)` except the output type is inferred.
@inline(__always)
internal func _unsafeBitCast<T, U>(_ value: T) -> U {
return unsafeBitCast(value, to: U.self)
}
// Allows casting between types of potentially different sizes.
internal func _unsafeCast<T, U>(_ value: inout T, to type: U.Type = U.self) -> U {
return UnsafeMutableRawPointer(&value).assumingMemoryBound(to: type).pointee
}
internal func _unsafeCast<T, U>(_ value: T, to type: U.Type = U.self) -> U {
var value = value
return _unsafeCast(&value, to: type)
}
/// Unsafely creates a new value of type `T`.
internal func _unsafeValue<T>(of type: T.Type = T.self) -> T {
return _unsafeCast(Optional<T>.none)
}
//internal func _pointer<T, U>(to value: inout T, as type: U.Type = U.self) -> UnsafeMutablePointer<U> {
// return UnsafeMutableRawPointer(&value).assumingMemoryBound(to: type)
//}
| 39.830189 | 104 | 0.723354 |
140ea9a0456e04e63eb5794a3af17ef4dd7873c8 | 766 | //
// phasor.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
extension AKOperation {
/// Produces a normalized sawtooth wave between the values of 0 and 1. Phasors
/// are often used when building table-lookup oscillators.
///
/// - returns: AKOperation
/// - parameter frequency: Frequency in cycles per second, or Hz. (Default: 1.0, Minimum: 0.0, Maximum: 1000.0)
/// - parameter phase: Initial phase (Default: 0)
///
public static func phasor(
frequency frequency: AKParameter = 1,
phase: Double = 0
) -> AKOperation {
return AKOperation("(\(frequency) \(phase) phasor)")
}
}
| 28.37037 | 115 | 0.640992 |
8abcb324f3846deac6d4afbff4b11fb2626edd3f | 784 | //
// Environment.swift
// Hearth
//
// Created by Andrey Ufimcev on 19/01/2020.
//
/// An environment the app is running in.
public enum Environment {
/// A debug environment.
case debug
/// A release environment.
case release
/// Any environment.
case any
/// Executes a block of code if matches the current environment.
/// - Parameter block: The block of code to execute.
internal func execute(_ block: () -> Void) {
switch self {
case .debug:
#if DEBUG
block()
#else
break
#endif
case .release:
#if !DEBUG
block()
#else
break
#endif
case .any:
block()
}
}
}
| 18.666667 | 68 | 0.5 |
d902011a94127c0dbad40a4cd6b1942d06d841db | 2,319 | //
// AssistantMethodUseTimeViewController.swift
// Alamofire
//
// Created by wangbao on 2020/11/10.
//
import Foundation
class AssistantMethodUseTimeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
needBigTitleView = true
assistant_setNavTitle(localizedString("Load耗时"))
setupView()
}
func setupView() {
view.addSubview(switchView)
view.addSubview(cellBtn)
switchView.snp.makeConstraints { (maker) in
maker.left.equalTo(0)
maker.top.equalTo(UIViewController.bigTitleViewH)
maker.right.equalTo(0)
maker.height.equalTo(53)
}
cellBtn.snp.makeConstraints { (maker) in
maker.left.equalTo(0)
maker.right.equalTo(0)
maker.top.equalTo(switchView.snp_bottom)
maker.height.equalTo(53)
}
}
private lazy var switchView: AssistantCellSwitch = {
let switchView = AssistantCellSwitch()
switchView.renderUIWithTitle(title: localizedString("Load耗时检测开关"), switchOn: AssistantMethodUseTimeManager.sharedInstance.switchOn)
switchView.needTopLine()
switchView.needDownLine()
switchView.delegate = self
return switchView
}()
private lazy var cellBtn: AssistantCellButton = {
let cellBtn = AssistantCellButton()
cellBtn.renderUIWithTitle(title: localizedString("查看检测记录"))
cellBtn.delegate = self
cellBtn.needDownLine()
return cellBtn
}()
}
extension AssistantMethodUseTimeViewController: AssistantCellSwitchDelegate {
func changeSwitchOn(isOn: Bool, sender: UISwitch) {
AssistantAlertUtil.handleAlertActionWithVC(vc: self, okBlock: {
AssistantMethodUseTimeManager.sharedInstance.switchOn = isOn
exit(0)
}, cancelBlock: { [weak self] in
self?.switchView.switchView.isOn = !isOn
})
}
}
extension AssistantMethodUseTimeViewController: AssistantCellButtonDelegate {
func cellBtnClick(sender: UIView) {
if sender == cellBtn {
let listViewController = AssistantMethodUseTimeListViewController()
self.navigationController?.pushViewController(listViewController, animated: true)
}
}
}
| 30.116883 | 139 | 0.664942 |
ed86dfbceb5c0b48b45d0de36299f521415a9a11 | 468 | //
// EvrythngLogoutResponse.swift
// EvrythngiOS
//
// Created by JD Castro on 29/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
import Moya_SwiftyJSONMapper
import SwiftyJSON
public final class EvrythngLogoutResponse: ALSwiftyJSONAble {
public var jsonData: JSON?
public var logout: String?
public init?(jsonData: JSON) {
self.jsonData = jsonData
self.logout = jsonData["logout"].string
}
}
| 20.347826 | 61 | 0.690171 |
4830b54ef40c34e59fdeabdc6e002fe43f78ee1b | 2,019 | //
// 46_dictionary.swift
// hello_world
//
// Created by kaleidot725 on 2021/07/23.
//
import Foundation
func no46() {
func define() {
// 1つの辞書にはキーと値の複数個格納できる
let d = ["Swift":2014, "Objective-C":1983]
print(d)
if let v = d["Swift"] { print(v) }
if let v = d["Objective-C"] { print(v) }
var e = ["Ruby": 1995]
print(e)
e["Java"] = 1995
e["Python"] = 1991
print(e)
e["Java"] = nil
print(e)
}
func compare() {
// 同じキーに割り当てられている、値が同じであれば true になる
var a = ["one":"ⅰ", "two":"ⅱ", "three":"ⅲ"]
let b = ["two":"ⅱ", "one":"ⅰ"]
print(a == b)
a["three"] = nil
print(a == b)
}
func setter() {
// 文字列の1文字をキーとして数字を入れていく
var dic = [String: Int]()
var n = 1
for ch in "あいうえお" {
dic[String(ch)] = n;
n += 1
}
print(dic)
var dic2 = [String: Int]()
var n2 = 1
for ch in "あいうえお" {
dic2[String(ch)] = n2;
n2 += 1
}
print(dic2)
let score = ["友利":67, "西森":80, "乙坂":100]
let m1 = score["友利"]
print(m1)
let m2 = score["高城", default:0]
print(m2)
}
func keysAndValues() {
var dic = ["A": 1, "B": 2, "C": 3, "D": 4, "E": 5]
print(dic)
print(dic.keys)
print(dic.values)
}
func update() {
var dic = ["佐倉": 90, "梨田": 90, "綾小路": 70, "堀北": 51]
let exam = ["梨田": 85, "堀北": 100, "平田": 85, "須藤": 39]
// 辞書自体と値のコレクションが同じ添字でアクセスできる
// この特性を利用すれば次のように処理が記述できるらしい
for idx in dic.indices {
let student = dic[idx]
if let v = exam[student.key], v > student.value {
dic.values[idx] = v
}
}
print(dic)
}
define()
compare()
setter()
keysAndValues()
update()
}
| 21.478723 | 61 | 0.421991 |
79096a61378742d6ef4ab34415327dd66a57c90f | 93 | import Cocoa
@NSApplicationMain
final class AppDelegate: NSObject, NSApplicationDelegate {}
| 18.6 | 59 | 0.83871 |
8745e72077e5d719b63e10351bd38fb947c1f2f6 | 1,245 | //
// RouteComposer
// FactoryBox.swift
// https://github.com/ekazaev/route-composer
//
// Created by Eugene Kazaev in 2018-2021.
// Distributed under the MIT license.
//
#if os(iOS)
import Foundation
import UIKit
struct FactoryBox<F: Factory>: PreparableAnyFactory, AnyFactoryBox, MainThreadChecking, CustomStringConvertible {
typealias FactoryType = F
var factory: F
let action: AnyAction
var isPrepared = false
init?(_ factory: F, action: AnyAction) {
guard !(factory is NilEntity) else {
return nil
}
self.factory = factory
self.action = action
}
func build<Context>(with context: Context) throws -> UIViewController {
guard let typedContext = Any?.some(context as Any) as? FactoryType.Context else {
throw RoutingError.typeMismatch(type: type(of: context),
expectedType: FactoryType.Context.self,
.init("\(String(describing: factory.self)) does not accept \(String(describing: context.self)) as a context."))
}
assertIfNotMainThread()
assertIfNotPrepared()
return try factory.build(with: typedContext)
}
}
#endif
| 26.489362 | 155 | 0.628112 |
fb5e218fd897ce5403511262c062ec30f1194251 | 1,223 | //
// MarketSearchCell.swift
// AElfApp
//
// Created by jinxiansen on 2019/8/6.
// Copyright © 2019 AELF. All rights reserved.
//
import UIKit
class MarketSearchCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var favouriteButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
var item: MarketCoinModel? {
didSet {
guard let item = item else { return }
nameLabel.text = item.name
priceLabel.text = App.currencySymbol + String(item.lastPrice ?? "")
favouriteButton.isSelected = item.exist()
}
}
@IBAction func favouriteButtonTapped(_ sender: Any) {
guard let item = item else { return }
if item.exist() {
item.delete()
favouriteButton.isSelected = false
} else {
item.save()
favouriteButton.isSelected = true
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 23.075472 | 79 | 0.604252 |
0123d8b6cf706222a6062119c942ad122db5b170 | 1,358 | //
// Enums.swift
// Sample
//
// Created by Meniny on 2018-01-20.
// Copyright © 2018年 Meniny. All rights reserved.
//
import Foundation
public enum WKWebSource: Equatable {
case remote(URL)
case file(URL, access: URL)
case string(String, base: URL?)
public var url: URL? {
switch self {
case .remote(let u): return u
case .file(let u, access: _): return u
default: return nil
}
}
public var remoteURL: URL? {
switch self {
case .remote(let u): return u
default: return nil
}
}
public var absoluteString: String? {
switch self {
case .remote(let u): return u.absoluteString
case .file(let u, access: _): return u.absoluteString
default: return nil
}
}
}
public enum BarButtonItemType {
case back
case forward
case reload
case stop
case activity
case done
case flexibleSpace
case custom(icon: UIImage?, title: String?, action: (WKWebViewController) -> Void)
}
public enum NavigationBarPosition: String, Equatable, Codable {
case none
case left
case right
}
@objc public enum NavigationType: Int, Equatable, Codable {
case linkActivated
case formSubmitted
case backForward
case reload
case formResubmitted
case other
}
| 20.892308 | 86 | 0.618557 |
09506e222713bb05c0cdf7a44ea1f17a64095738 | 743 | //
// PlainMechanism.swift
// Franz
//
// Created by Luke Lau on 15/04/2018.
//
import Foundation
/// Handles authenticating with the PLAIN mechanism
struct PlainMechanism: SaslMechanism {
let username: String
let password: String
var kafkaLabel: String {
return "PLAIN"
}
func authenticate(connection: Connection) -> Bool {
let zid = ""
guard let data = [zid, username, password].joined(separator: "\0").data(using: .utf8) else {
fatalError("Plain authentication failed, make sure username and password are UTF8 encoded")
}
let authRequest = SaslAuthenticateRequest(saslAuthBytes: data)
guard let response = connection.writeBlocking(authRequest) else {
return false
}
return response.errorCode == 0
}
}
| 23.21875 | 94 | 0.718708 |
142458c0d4ba70ccbdb29766024e2917e15617cf | 282 | //
// InternalNotifications.swift
// iRecipe
//
// Created by Ricardo Casanova on 11/02/2019.
// Copyright © 2019 Pijp. All rights reserved.
//
import Foundation
extension Notification.Name {
static let reloadFavoriteRecipes = Notification.Name("reloadFavoriteRecipes")
}
| 20.142857 | 81 | 0.741135 |
cc330622e93b1e873505f8e9c3a8d342655db6f8 | 2,645 | //
// User.swift
// daisy
//
// Created by Galina on 31/07/2020.
// Copyright © 2020 Galina FABIO. All rights reserved.
//
import SwiftUI
struct UserResults: Decodable {
let users: [User]
}
public struct User: Codable, Identifiable, Hashable {
enum CodingKeys: String, CodingKey {
// Map the JSON keys to the Swift property names
case id
case createdAt = "created_at"
case updatedAt = "updated_at"
case name
case birthday
case birthdayDate
case email
case role
case image
case imageID
}
public let id: String
let createdAt: Date?
let updatedAt: Date?
let name: String
let birthday: String
let birthdayDate: Date
let email: String
let role: uint
let image: ImageResponse?
let imageID: String?
private let dateFormatter = DateFormatter()
init(id: String = "", createdAt: Date? = nil, updatedAt: Date? = nil,
name: String = "", birthday: String = "", email: String = "", role: uint = 1, imageID: String? = "", image: ImageResponse? = nil) {
self.id = id
self.createdAt = createdAt
self.updatedAt = updatedAt
self.name = name
self.birthday = birthday
self.email = email
self.role = role
self.imageID = imageID
self.image = image
self.birthdayDate = birthday.toDate()
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
createdAt = try values.decodeIfPresent(Date.self, forKey: .createdAt)
updatedAt = try values.decodeIfPresent(Date.self, forKey: .updatedAt)
name = try values.decode(String.self, forKey: .name)
birthday = try values.decode(String.self, forKey: .birthday)
email = try values.decode(String.self, forKey: .email)
role = try values.decode(uint.self, forKey: .role)
imageID = try? values.decodeIfPresent(String.self, forKey: .imageID)
image = try values.decodeIfPresent(ImageResponse.self, forKey: .image)
birthdayDate = birthday.toDate()
}
}
public let staticUser = User(id: "1",
createdAt: Date(),
updatedAt: Date(),
name: "Test user",
birthday: "1990-07-13",
email: "[email protected]",
role: 1,
imageID: nil,
image: nil)
| 32.256098 | 140 | 0.57051 |
2169572b44b66e2690738578c1a17177e2d1519c | 910 | import XCTest
import CommonMark
final class DocumentCreationTests: XCTestCase {
func testDocumentCreation() throws {
let link = Link(urlString: "https://www.un.org/en/universal-declaration-human-rights/", title: "View full version", text: "Universal Declaration of Human Rights")
let heading = Heading(level: 1, children: [link])
let subheading = Heading(level: 2, text: "Article 1.")
let paragraph = Paragraph(text: #"""
All human beings are born free and equal in dignity and rights.
They are endowed with reason and conscience
and should act towards one another in a spirit of brotherhood.
"""#, replacingNewLinesWithBreaks: true)
let document = Document(children: [heading, subheading, paragraph])
let expected = try Document(Fixtures.uhdr)
XCTAssertEqual(document.description, expected.description)
}
}
| 37.916667 | 170 | 0.691209 |
9cc86fbe9a48da0f30be4ba760148191c8cdee4e | 509 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "GithubAPI",
products: [
.library(name: "GithubAPI", targets: ["GithubAPI"])
],
dependencies: [
.package(url: "https://github.com/serhii-londar/BaseAPI.git", from: "0.1.0"),
],
targets: [
.target(name: "GithubAPI", dependencies: ["BaseAPI"], path: "GithubAPI/Classes")
]
)
| 29.941176 | 96 | 0.638507 |
e26f8805048a0b6ce5cde7348b828ecbcdac666f | 4,367 | //
// ProfileDataLoader.swift
// Cognostic
//
// Created by Apollo Zhu on 4/5/21.
// Copyright © 2020-2021 Cognostic. All rights reserved.
//
import ResearchKit
import FirebaseFirestore
import EFStorageKeychainAccess
func loadBasicInfo() {
guard let authCollection = CKStudyUser.shared.authCollection else {
print("not signed in")
return
}
let db = Firestore.firestore()
db.collection(authCollection + Constants.dataBucketSurveys)
.whereField(FieldPath(["payload", "identifier"]), isEqualTo: "BasicInfo")
.order(by: FieldPath(["payload", "endDate"]), descending: true)
.limit(to: 1)
.getDocuments { snapshot, error in
guard let document = snapshot?.documents.first else {
dump(error)
return
}
guard let payload = document.data()["payload"],
let dict = payload as? [AnyHashable: Any],
let object = try? ORKESerializer.object(fromJSONObject: dict),
let result = object as? ORKTaskResult else {
print("format error")
return
}
updateBasicInfo(with: result)
EFStorageKeychainAccessRef<ORKTaskResult>
.forKey("BasicInfo").content = result
print("update user info success")
}
}
func updateBasicInfo(with taskResult: ORKTaskResult) {
let studyUser: CKStudyUser = .shared
if let nameResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.nameQuestionStep.rawValue)?
.results?.first as? ORKTextQuestionResult,
let name = nameResult.textAnswer {
studyUser.name = name
} else {
studyUser.name = nil
}
if let dobResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.dobQuestionStep.rawValue)?
.results?.first as? ORKDateQuestionResult,
let date = dobResult.dateAnswer {
studyUser.dateOfBirth = date
} else {
studyUser.dateOfBirth = nil
}
if let sexResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.sexQuestionStep.rawValue)?
.results?.first as? ORKChoiceQuestionResult,
let firstResult = sexResult.choiceAnswers?.first,
let sexString = firstResult as? String {
let sex: HKBiologicalSex
switch sexString {
case "HKBiologicalSexNotSet": sex = .notSet
case "HKBiologicalSexFemale": sex = .female
case "HKBiologicalSexMale": sex = .male
case "HKBiologicalSexOther": sex = .other
default: sex = .other
}
studyUser.sex = sex
} else {
studyUser.sex = .notSet
}
if let handednessResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.handedQuestionStep.rawValue)?
.results?.first as? ORKChoiceQuestionResult,
let firstAnswer = handednessResult.choiceAnswers?.first,
let handedness = firstAnswer as? String {
studyUser.handedness = handedness
} else {
studyUser.handedness = nil
}
if let locationResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.locationQuestionStep.rawValue)?
.results?.first as? ORKLocationQuestionResult,
let location = locationResult.locationAnswer,
let zipCode = location.postalAddress?.postalCode {
studyUser.zipCode = zipCode
} else {
studyUser.zipCode = nil
}
if let ethnicityResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.ethnicityQuestionStep.rawValue)?
.results?.first as? ORKChoiceQuestionResult,
let firstAnswer = ethnicityResult.choiceAnswers?.first,
let ethnicity = firstAnswer as? String {
studyUser.ethnicity = ethnicity
} else {
studyUser.ethnicity = nil
}
if let educationResult = taskResult.stepResult(
forStepIdentifier: ORKStep.Identifier
.educationQuestionStep.rawValue)?
.results?.first as? ORKChoiceQuestionResult,
let firstAnswer = educationResult.choiceAnswers?.first,
let education = firstAnswer as? String {
studyUser.education = education
} else {
studyUser.education = nil
}
}
| 33.852713 | 81 | 0.63728 |
b977eeb241b92814b6386c2be309447d267753cf | 427 | //
// Collection.swift
//
// Created by Marcel Tesch on 2020-06-05.
// Think different.
//
import Foundation
extension Collection where Element == String {
func longestCommonPrefix() -> String {
guard var prefix = first else { return "" }
for value in dropFirst() {
while !value.hasPrefix(prefix) {
prefix.removeLast()
}
}
return prefix
}
}
| 17.08 | 51 | 0.566745 |
386fb22ebc5ec047f91aa40b9582b55c8907cf6f | 795 |
let intQueue = Queue<Int>()
intQueue.enqueue(1) // [1]
intQueue.enqueue(2) // [1, 2]
intQueue.enqueue(3) // [1, 2, 3]
intQueue.peek // 1
intQueue.dequeue() // 1
intQueue.count // 2
intQueue.isEmpty // false
intQueue.dequeue() // 2
intQueue.dequeue() // 3
intQueue.peek // nil
intQueue.count // 0
intQueue.isEmpty // true
var intQueueStruct = QueueStruct<Int>()
intQueueStruct.enqueue(1) // [1]
intQueueStruct.enqueue(2) // [1, 2]
intQueueStruct.enqueue(3) // [1, 2, 3]
intQueueStruct.peek // 1
intQueueStruct.dequeue() // 1
intQueueStruct.count // 2
intQueueStruct.isEmpty // false
intQueueStruct.dequeue() // 2
intQueueStruct.dequeue() // 3
intQueueStruct.peek // nil
intQueueStruct.count // 0
intQueueStruct.isEmpty // true
| 23.382353 | 39 | 0.649057 |
09c3c39d72e26e95ede5879686b95931c200198e | 380 | //
// NetworkRequest.swift
// NetworkLayer
//
// Created by Mohamed Qasim Mohamed Majeed on 24/11/2019.
import UIKit
typealias ResultSuccess<T> = (T) -> Void
typealias ResultFailure = (NetworkError) -> Void
protocol NetworkRequest {
func request<T: Decodable>(_ request : URLRequest, success : @escaping ResultSuccess<T>,failure : @escaping ResultFailure)
}
| 21.111111 | 126 | 0.710526 |
3822c1780e070cd2f982149c3fad8fafbbfcc821 | 193 | //
// Model.swift
// Test11
//
// Created by fpm0259 on 2018/12/17.
// Copyright © 2018年 fpm0259. All rights reserved.
//
import UIKit
class Model: NSObject {
var name:String?
}
| 12.866667 | 51 | 0.632124 |
f525ee03e46c1f5509da13d532a9faa618b147fa | 1,026 | // Copyright Keefer Taylor, 2019.
import Foundation
/// String constants used in Micheline param JSON encoding.
internal enum MichelineConstants {
public static let annotations = "annots"
public static let args = "args"
public static let primitive = "prim"
public static let bytes = "bytes"
public static let int = "int"
public static let left = "Left"
public static let `false` = "False"
public static let none = "None"
public static let pair = "Pair"
public static let right = "Right"
public static let some = "Some"
public static let string = "string"
public static let `true` = "True"
public static let unit = "Unit"
}
/// An abstract representation of a Michelson param.
///
/// - SeeAlso: https://tezos.gitlab.io/master/whitedoc/michelson.html
public protocol MichelsonParameter {
/// A dictionary representing the paramater as a JSON object.
// TODO(keefertaylor): Make this JSON encodable or some other protocol.
var networkRepresentation: Any { get } /*[String: Any] { get } */
}
| 33.096774 | 73 | 0.714425 |
e90de30428fc9b32a4a797a02eec16c51eedec94 | 260 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
deinit {
class A {
{
}
enum b {
init
{ c( [ {
struct D {
{
}
func a {
var b {
class
case ,
| 13.684211 | 87 | 0.684615 |
0968113b5016db1b929e6d8150f45e2bc4cdf295 | 33,047 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: ixo/project/project.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// UpdateProjectStatusDoc contains details required to update a project's status.
struct Project_UpdateProjectStatusDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var status: String = String()
var ethFundingTxnID: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// CreateAgentDoc contains details required to create an agent.
struct Project_CreateAgentDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var agentDid: String = String()
var role: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// UpdateAgentDoc contains details required to update an agent.
struct Project_UpdateAgentDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var did: String = String()
var status: String = String()
var role: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// CreateClaimDoc contains details required to create a claim on a project.
struct Project_CreateClaimDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var claimID: String = String()
var claimTemplateID: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// CreateEvaluationDoc contains details required to create an evaluation for a specific claim on a project.
struct Project_CreateEvaluationDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var claimID: String = String()
var status: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// WithdrawFundsDoc contains details required to withdraw funds from a specific project.
struct Project_WithdrawFundsDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var projectDid: String = String()
var recipientDid: String = String()
var amount: String = String()
var isRefund: Bool = false
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// ProjectDoc defines a project (or entity) type with all of its parameters.
struct Project_ProjectDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var txHash: String = String()
var projectDid: String = String()
var senderDid: String = String()
var pubKey: String = String()
var status: String = String()
var data: Data = Data()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// WithdrawalInfoDoc contains details required to withdraw from a specific project.
struct Project_WithdrawalInfoDoc {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var projectDid: String = String()
var recipientDid: String = String()
var amount: Cosmos_Base_V1beta1_Coin {
get {return _amount ?? Cosmos_Base_V1beta1_Coin()}
set {_amount = newValue}
}
/// Returns true if `amount` has been explicitly set.
var hasAmount: Bool {return self._amount != nil}
/// Clears the value of `amount`. Subsequent reads from it will return its default value.
mutating func clearAmount() {self._amount = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _amount: Cosmos_Base_V1beta1_Coin? = nil
}
/// Params defines the parameters for the project module.
struct Project_Params {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var ixoDid: String = String()
var projectMinimumInitialFunding: [Cosmos_Base_V1beta1_Coin] = []
var oracleFeePercentage: String = String()
var nodeFeePercentage: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Claim contains details required to start a claim on a project.
struct Project_Claim {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: String = String()
var templateID: String = String()
var claimerDid: String = String()
var status: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// GenesisAccountMap is a type used at genesis that maps a specific project's account names to the accounts' addresses.
struct Project_GenesisAccountMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var map: Dictionary<String,String> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// AccountMap maps a specific project's account names to the accounts' addresses.
struct Project_AccountMap {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var map: Dictionary<String,String> = [:]
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// WithdrawalInfoDocs contains a list of type WithdrawalInfoDoc.
struct Project_WithdrawalInfoDocs {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var docsList: [Project_WithdrawalInfoDoc] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Claims contains a list of type Claim.
struct Project_Claims {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var claimsList: [Project_Claim] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "project"
extension Project_UpdateProjectStatusDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".UpdateProjectStatusDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "status"),
2: .standard(proto: "eth_funding_txn_id"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.status) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.ethFundingTxnID) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.status.isEmpty {
try visitor.visitSingularStringField(value: self.status, fieldNumber: 1)
}
if !self.ethFundingTxnID.isEmpty {
try visitor.visitSingularStringField(value: self.ethFundingTxnID, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_UpdateProjectStatusDoc, rhs: Project_UpdateProjectStatusDoc) -> Bool {
if lhs.status != rhs.status {return false}
if lhs.ethFundingTxnID != rhs.ethFundingTxnID {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_CreateAgentDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CreateAgentDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "agent_did"),
2: .same(proto: "role"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.agentDid) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.role) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.agentDid.isEmpty {
try visitor.visitSingularStringField(value: self.agentDid, fieldNumber: 1)
}
if !self.role.isEmpty {
try visitor.visitSingularStringField(value: self.role, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_CreateAgentDoc, rhs: Project_CreateAgentDoc) -> Bool {
if lhs.agentDid != rhs.agentDid {return false}
if lhs.role != rhs.role {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_UpdateAgentDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".UpdateAgentDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "did"),
2: .same(proto: "status"),
3: .same(proto: "role"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.did) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.status) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.role) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.did.isEmpty {
try visitor.visitSingularStringField(value: self.did, fieldNumber: 1)
}
if !self.status.isEmpty {
try visitor.visitSingularStringField(value: self.status, fieldNumber: 2)
}
if !self.role.isEmpty {
try visitor.visitSingularStringField(value: self.role, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_UpdateAgentDoc, rhs: Project_UpdateAgentDoc) -> Bool {
if lhs.did != rhs.did {return false}
if lhs.status != rhs.status {return false}
if lhs.role != rhs.role {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_CreateClaimDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CreateClaimDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "claim_id"),
2: .standard(proto: "claim_template_id"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.claimID) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.claimTemplateID) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.claimID.isEmpty {
try visitor.visitSingularStringField(value: self.claimID, fieldNumber: 1)
}
if !self.claimTemplateID.isEmpty {
try visitor.visitSingularStringField(value: self.claimTemplateID, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_CreateClaimDoc, rhs: Project_CreateClaimDoc) -> Bool {
if lhs.claimID != rhs.claimID {return false}
if lhs.claimTemplateID != rhs.claimTemplateID {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_CreateEvaluationDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CreateEvaluationDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "claim_id"),
2: .same(proto: "status"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.claimID) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.status) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.claimID.isEmpty {
try visitor.visitSingularStringField(value: self.claimID, fieldNumber: 1)
}
if !self.status.isEmpty {
try visitor.visitSingularStringField(value: self.status, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_CreateEvaluationDoc, rhs: Project_CreateEvaluationDoc) -> Bool {
if lhs.claimID != rhs.claimID {return false}
if lhs.status != rhs.status {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_WithdrawFundsDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".WithdrawFundsDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "project_did"),
2: .standard(proto: "recipient_did"),
3: .same(proto: "amount"),
4: .standard(proto: "is_refund"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.projectDid) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.recipientDid) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.amount) }()
case 4: try { try decoder.decodeSingularBoolField(value: &self.isRefund) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.projectDid.isEmpty {
try visitor.visitSingularStringField(value: self.projectDid, fieldNumber: 1)
}
if !self.recipientDid.isEmpty {
try visitor.visitSingularStringField(value: self.recipientDid, fieldNumber: 2)
}
if !self.amount.isEmpty {
try visitor.visitSingularStringField(value: self.amount, fieldNumber: 3)
}
if self.isRefund != false {
try visitor.visitSingularBoolField(value: self.isRefund, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_WithdrawFundsDoc, rhs: Project_WithdrawFundsDoc) -> Bool {
if lhs.projectDid != rhs.projectDid {return false}
if lhs.recipientDid != rhs.recipientDid {return false}
if lhs.amount != rhs.amount {return false}
if lhs.isRefund != rhs.isRefund {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_ProjectDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ProjectDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "tx_hash"),
2: .standard(proto: "project_did"),
3: .standard(proto: "sender_did"),
4: .standard(proto: "pub_key"),
5: .same(proto: "status"),
6: .same(proto: "data"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.txHash) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.projectDid) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.senderDid) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.pubKey) }()
case 5: try { try decoder.decodeSingularStringField(value: &self.status) }()
case 6: try { try decoder.decodeSingularBytesField(value: &self.data) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.txHash.isEmpty {
try visitor.visitSingularStringField(value: self.txHash, fieldNumber: 1)
}
if !self.projectDid.isEmpty {
try visitor.visitSingularStringField(value: self.projectDid, fieldNumber: 2)
}
if !self.senderDid.isEmpty {
try visitor.visitSingularStringField(value: self.senderDid, fieldNumber: 3)
}
if !self.pubKey.isEmpty {
try visitor.visitSingularStringField(value: self.pubKey, fieldNumber: 4)
}
if !self.status.isEmpty {
try visitor.visitSingularStringField(value: self.status, fieldNumber: 5)
}
if !self.data.isEmpty {
try visitor.visitSingularBytesField(value: self.data, fieldNumber: 6)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_ProjectDoc, rhs: Project_ProjectDoc) -> Bool {
if lhs.txHash != rhs.txHash {return false}
if lhs.projectDid != rhs.projectDid {return false}
if lhs.senderDid != rhs.senderDid {return false}
if lhs.pubKey != rhs.pubKey {return false}
if lhs.status != rhs.status {return false}
if lhs.data != rhs.data {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_WithdrawalInfoDoc: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".WithdrawalInfoDoc"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "project_did"),
2: .standard(proto: "recipient_did"),
3: .same(proto: "amount"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.projectDid) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.recipientDid) }()
case 3: try { try decoder.decodeSingularMessageField(value: &self._amount) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.projectDid.isEmpty {
try visitor.visitSingularStringField(value: self.projectDid, fieldNumber: 1)
}
if !self.recipientDid.isEmpty {
try visitor.visitSingularStringField(value: self.recipientDid, fieldNumber: 2)
}
if let v = self._amount {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_WithdrawalInfoDoc, rhs: Project_WithdrawalInfoDoc) -> Bool {
if lhs.projectDid != rhs.projectDid {return false}
if lhs.recipientDid != rhs.recipientDid {return false}
if lhs._amount != rhs._amount {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_Params: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Params"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "ixo_did"),
2: .standard(proto: "project_minimum_initial_funding"),
3: .standard(proto: "oracle_fee_percentage"),
4: .standard(proto: "node_fee_percentage"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.ixoDid) }()
case 2: try { try decoder.decodeRepeatedMessageField(value: &self.projectMinimumInitialFunding) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.oracleFeePercentage) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.nodeFeePercentage) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.ixoDid.isEmpty {
try visitor.visitSingularStringField(value: self.ixoDid, fieldNumber: 1)
}
if !self.projectMinimumInitialFunding.isEmpty {
try visitor.visitRepeatedMessageField(value: self.projectMinimumInitialFunding, fieldNumber: 2)
}
if !self.oracleFeePercentage.isEmpty {
try visitor.visitSingularStringField(value: self.oracleFeePercentage, fieldNumber: 3)
}
if !self.nodeFeePercentage.isEmpty {
try visitor.visitSingularStringField(value: self.nodeFeePercentage, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_Params, rhs: Project_Params) -> Bool {
if lhs.ixoDid != rhs.ixoDid {return false}
if lhs.projectMinimumInitialFunding != rhs.projectMinimumInitialFunding {return false}
if lhs.oracleFeePercentage != rhs.oracleFeePercentage {return false}
if lhs.nodeFeePercentage != rhs.nodeFeePercentage {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_Claim: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Claim"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"),
2: .standard(proto: "template_id"),
3: .standard(proto: "claimer_did"),
4: .same(proto: "status"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.templateID) }()
case 3: try { try decoder.decodeSingularStringField(value: &self.claimerDid) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.status) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.id.isEmpty {
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
}
if !self.templateID.isEmpty {
try visitor.visitSingularStringField(value: self.templateID, fieldNumber: 2)
}
if !self.claimerDid.isEmpty {
try visitor.visitSingularStringField(value: self.claimerDid, fieldNumber: 3)
}
if !self.status.isEmpty {
try visitor.visitSingularStringField(value: self.status, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_Claim, rhs: Project_Claim) -> Bool {
if lhs.id != rhs.id {return false}
if lhs.templateID != rhs.templateID {return false}
if lhs.claimerDid != rhs.claimerDid {return false}
if lhs.status != rhs.status {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_GenesisAccountMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GenesisAccountMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "map"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &self.map) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.map.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: self.map, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_GenesisAccountMap, rhs: Project_GenesisAccountMap) -> Bool {
if lhs.map != rhs.map {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_AccountMap: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".AccountMap"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "map"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &self.map) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.map.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: self.map, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_AccountMap, rhs: Project_AccountMap) -> Bool {
if lhs.map != rhs.map {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_WithdrawalInfoDocs: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".WithdrawalInfoDocs"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "docs_list"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.docsList) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.docsList.isEmpty {
try visitor.visitRepeatedMessageField(value: self.docsList, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_WithdrawalInfoDocs, rhs: Project_WithdrawalInfoDocs) -> Bool {
if lhs.docsList != rhs.docsList {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Project_Claims: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Claims"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "claims_list"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.claimsList) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.claimsList.isEmpty {
try visitor.visitRepeatedMessageField(value: self.claimsList, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Project_Claims, rhs: Project_Claims) -> Bool {
if lhs.claimsList != rhs.claimsList {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 39.294887 | 171 | 0.725512 |
084f4ac6db3c541e92600c178a937a54e7986eef | 2,062 | //
// KittenParentMethods.swift
// Pods
//
// Created by Spring Wong on 27/2/2017.
//
//
import Foundation
import SnapKit
public protocol KittenParentMethods : KittenChild{
//perpendicular alignment of items, default match parent
@discardableResult func defaultAlignment(_ alignment : KittenAlignment) -> KittenParentMethods
//padding to the container start
@discardableResult func startPadding(_ value : Int) -> KittenParentMethods
//padding to the container end
@discardableResult func endPadding(_ value : Int) -> KittenParentMethods
//default offset between item
@discardableResult func itemDefaultOffset(_ value : Int)->KittenParentMethods
//default offset of start padding, it's left or top depent on diretion
@discardableResult func itemDefaultSideStartPadding(_ value : Int)->KittenParentMethods
//default offset of end padding , right or bottom
@discardableResult func itemDefaultSideEndPadding(_ value : Int)->KittenParentMethods
//default side padding of both side
@discardableResult func itemDefaultSidePadding(_ value : Int) -> KittenParentMethods
//4 direction also set this default padding
@discardableResult func allPadding(_ value : Int)->KittenParentMethods
//true make the childs' container try to match its parent width(horizontal)/height(vertical)
@discardableResult func isAlignDirectionEnd(_ isAlign : Bool) -> KittenParentMethods
//swift only method, show that where the top/left/bottom/right of container
// @discardableResult func parentTop(_ top : ConstraintItem) -> KittenParentMethods
// @discardableResult func parentLeft(_ left : ConstraintItem) -> KittenParentMethods
// @discardableResult func parentBottom(_ bottom : ConstraintItem) -> KittenParentMethods
// @discardableResult func parentRight(_ right : ConstraintItem) -> KittenParentMethods
//true will turn weight mode on, usually use with isAlignDirectionEnd, child's length based on their weight
@discardableResult func weightMode(_ isOn : Bool) -> KittenParentMethods
}
| 52.871795 | 111 | 0.768186 |
5be0db25e22723c7974323d7119a65ce6ca3ff46 | 3,679 | //
// ViewController.swift
// DYOperationKit
//
// Created by dannyyassine on 09/04/2017.
// Copyright (c) 2017 dannyyassine. All rights reserved.
//
import UIKit
import DYOperationKit
class ViewController: UIViewController {
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var rightImageView: UIImageView!
@IBOutlet weak var leftLeftImageView: UIImageView!
@IBOutlet weak var rightrightImageView: UIImageView!
let operationQueue: OperationQueue = OperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
let operation1 = DownloadURLRessourceOperation()
operation1.url = URL(string: "https://static.pexels.com/photos/34950/pexels-photo.jpg")
// operation1.completionBlock = { [weak self] in
// DispatchQueue.main.async {
// self?.leftImageView.image = operation1.response
// }
// }
let operation2 = DownloadURLRessourceOperation()
operation2.url = URL(string: "https://cdn.dribbble.com/users/63407/screenshots/3780917/dribbble_aloe_vera_bloom.png")
// operation2.completionBlock = { [weak self] in
// DispatchQueue.main.async {
// self?.rightImageView.image = operation2.response
// }
// }
operation2.addDependency(operation1)
// operationQueue.addOperation(operation1)
// operationQueue.addOperation(operation2)
let groupOperation = DYGroupOperation(withOperations: [operation1, operation2])
groupOperation.completionBlock = {
DispatchQueue.main.async {
self.leftImageView.image = operation1.response
self.rightImageView.image = operation2.response
}
}
// operationQueue.addOperation(groupOperation)
let downloadImageRessourceOperation = DownloadImageRessourceOperation(withUrl: URL(string: "https://cdn.dribbble.com/users/63407/screenshots/3780917/dribbble_aloe_vera_bloom.png")!)
// downloadImageRessourceOperation.completionBlock = {
// DispatchQueue.main.async {
// self.leftImageView.image = downloadImageRessourceOperation.response
// }
// }
let downloadImageRessourceOperation2 = DownloadImageRessourceOperation(withUrl: URL(string: "https://static.pexels.com/photos/34950/pexels-photo.jpg")!)
// downloadImageRessourceOperation2.completionBlock = {
// DispatchQueue.main.async {
// self.rightImageView.image = downloadImageRessourceOperation2.response
// }
// }
// operationQueue.addOperation(downloadImageRessourceOperation)
// operationQueue.addOperation(downloadImageRessourceOperation2)
let groupOperation2 = DYGroupOperation(withOperations: [downloadImageRessourceOperation, downloadImageRessourceOperation2])
groupOperation2.completionBlock = {
DispatchQueue.main.async {
self.leftImageView.image = downloadImageRessourceOperation.response
self.rightImageView.image = downloadImageRessourceOperation2.response
}
}
operationQueue.addOperation(groupOperation2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 40.877778 | 189 | 0.624626 |
872383d47c3bc1ac13ae445a55f6bc5d664200ad | 2,943 | //
// Filterable.swift
// AKMaskField
//
// Created by Remote User on 1/30/18.
//
import Foundation
public protocol Collapsible {
var type : CollapseType {get}
var collapseByDefault:Bool {get}
}
public extension Collapsible{
private var adapter:ListAdapter{
guard let adapter = self as? ListAdapter else {
fatalError("Collapsible must implemment by ListAdapter")
}
return adapter
}
internal func setData(newData:[Section]?){
guard let sections=newData,!sections.isEmpty else {
adapter._private_collapseSections = []
return
}
if type == .normal {
if collapseByDefault{
adapter._private_collapseSections = sections
.enumerated()
.map{$0.offset}
}
}
else{
adapter._private_collapseSections = sections
.enumerated()
.map{$0.offset}
.filter{$0 != 0}
}
}
var type : CollapseType {
get{
return .normal
}
}
var collapseByDefault:Bool {
get{
return true
}
}
func collapse(section:Int){
if (section >= adapter.sectionCount) || isCollapsed(section: section){
return
}
adapter._private_collapseSections.append(section)
adapter.reloadSection(at: section)
}
func expand(section:Int){
if (section >= adapter.sectionCount) || isExpanded(section: section){
return
}
adapter._private_collapseSections.remove(item: section)
adapter.reloadSection(at: section)
}
func toggleState(section:Int){
if type == .normal {
if isExpanded(section: section) {
collapse(section: section)
} else {
expand(section: section)
}
}
else {
if isExpanded(section: section){
return
}
collapseAll(except: section)
expand(section: section)
}
}
func collapseAll(except section:Int? = nil){
adapter.getSections()
.enumerated()
.map{$0.offset}
.filter { $0 != section }
.forEach { collapse(section: $0) }
}
func expandAll(except section:Int? = nil){
adapter.getSections()
.enumerated()
.map{$0.offset}
.filter { $0 != section }
.forEach { expand(section: $0) }
}
func isCollapsed(section:Int)->Bool{
return adapter._private_collapseSections.contains(section)
}
func isExpanded(section:Int)->Bool{
return !isCollapsed(section: section)
}
}
public enum CollapseType {
case normal
case accordion
}
| 24.731092 | 78 | 0.523276 |
f9a014e9e1fc985a18112ae65384c902be7451f8 | 2,408 | //: Playground - noun: a place where people can play
import UIKit
import XCTest
//Question One: sortByStrings(s,t): Sort the letters in the string s by the order they occur in the string t. You can assume t will not have repetitive characters. For s = "weather" and t = "therapyw", the output should be sortByString(s, t) = "theeraw". For s = "good" and t = "odg", the output should be sortByString(s, t) = "oodg".
//function takes in word s of type string and word t of type string and outputs string
//1. we have two pointers one that keeps track of the index of the characters in word s and the other to keep track of the index of the characters in word t
//2. If the current s character equals the current character at t then we append that character to output
//3. we increment the pointer s until we reach the count of the string s
//4. once we reach the end of the word s (sPointer == s.count) then we increment pointer t and reset the pointer s (starting from the begining of string s again)
//5. we repeat until the t pointer is equal to the count of the string t (we reached the end of the word t)
func sortByStrings(s: String, t: String) -> String {
var output = ""
var sPointer = 0
var tPointer = 0
while tPointer < t.count{
let currentSChar = s[s.index(s.startIndex, offsetBy: sPointer)]
let currentTChar = t[t.index(t.startIndex, offsetBy: tPointer)]
if currentSChar == currentTChar {
output.append(currentSChar)
}
sPointer += 1
if sPointer == s.count {
tPointer += 1
sPointer = 0
}
}
return output
}
sortByStrings(s: "weather", t: "therapyw") //output = "theeraw"
sortByStrings(s: "good", t: "odg") // output = "oodg"
//class to test different inputs and outputs
class CodePathTester: XCTestCase {
static public func sortByStringsTest(s: String , t: String, expectedOutput: String) {
//Arrange
let expected = (s: s, t: t, answer: expectedOutput)
//action
let result = sortByStrings(s: expected.s, t: expected.t)
//assert
assert(expected.answer == result)
}
}
CodePathTester.sortByStringsTest(s: "weather", t: "therapyw", expectedOutput: "theeraw")
CodePathTester.sortByStringsTest(s: "good", t: "odg", expectedOutput: "oodg")
| 32.106667 | 334 | 0.65407 |