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
|
---|---|---|---|---|---|
8a046ade44112039bb8cf97e28eeb10db46b0a0d | 938 | //
// tipCalculatorTests.swift
// tipCalculatorTests
//
// Created by Mohamed S Ahmed on 1/23/20.
// Copyright © 2020 Red Iris Productions. All rights reserved.
//
import XCTest
@testable import tipCalculator
class tipCalculatorTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.8 | 111 | 0.664179 |
e077d38e26db86eac036299d14ce33be3cb06966 | 669 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "Binaryen",
platforms: [
.macOS(.v10_15)
],
products: [
.library(name: "Binaryen", targets: ["Binaryen"]),
],
targets: [
.target(
name: "Binaryen",
dependencies: ["CBinaryen"]
),
.systemLibrary(
name: "CBinaryen",
pkgConfig: "binaryen",
providers: [
.brew(["binaryen"]),
.apt(["binaryen"]),
]
),
.testTarget(
name: "BinaryenTests",
dependencies: ["Binaryen"]
)
]
)
| 20.90625 | 58 | 0.45142 |
fe9d378d8e728c3a315ab8ef3ab42586c87c9b57 | 1,304 | //
// UIPart.swift
// UIKitCustomCollection
//
// Created by Akatsuki on 2020/03/19.
// Copyright © 2020 akatsuki. All rights reserved.
//
import UIKit
enum UIPart: String, CaseIterable {
case view
case button
// case label
// case textField
// case textView
// case `switch`
// case segmentedControl
// case progressView
// case slider
// case stepper
func name() -> String {
switch self {
case .view:
return "UIView"
case .button:
return "UIButton"
// case .label:
// return "UILabel"
// case .textField:
// return "UITextField"
// case .textView:
// return "UITextView"
// case .switch:
// return "UISwitch"
// case .segmentedControl:
// return "UISegmentedControl"
// case .progressView:
// return "UIProgressView"
// case .slider:
// return "UISlider"
// case .stepper:
// return "UIStepper"
}
}
// enum名の先頭1文字を大文字にしたものをstoryboard名にしている
func storyboardName() -> String {
let name = self.rawValue
let lowerStr = name.lowercased()
return String(lowerStr.prefix(1).uppercased()) + String(name.dropFirst())
}
}
| 23.709091 | 81 | 0.550613 |
fced51b0d3365035b596a1b450c830da16ab26c2 | 375 | //
// MainResource.swift
// OmniNews
//
// Created by Kamil Buczel on 07/10/2019.
// Copyright © 2019 Kamajabu. All rights reserved.
//
import Foundation
struct MainResource: Codable {
let imageAsset: ImageAsset?
let sourceID: String?
enum CodingKeys: String, CodingKey {
case imageAsset = "image_asset"
case sourceID = "source_id"
}
}
| 18.75 | 51 | 0.664 |
0aa87e54f25c81dc8931bff48454d5dc25eea508 | 2,126 | //
// PropertyData.swift
// Corporate-House-Management
//
// Created by Mr Kes on 12/21/21.
//
import Foundation
class PropertyData {
static let shared = PropertyData()
func getMayPropertiesNames() -> String {
let properties = "properties[]=631098&" +
"properties[]=631100&" +
"properties[]=631102&" +
"properties[]=631106&" +
"properties[]=631108&" +
"properties[]=631110&" +
"properties[]=631112&" +
"properties[]=631114&" +
"properties[]=631116&" +
"properties[]=631118&" +
"properties[]=631120&" +
"properties[]=631124&" +
"properties[]=631126&" +
"properties[]=631128&" +
"properties[]=631130&" +
"properties[]=631132&" +
"properties[]=631134&"
return properties
}
func getAngelPropertiesNames() -> String {
let properties = "properties[]=612782&" +
"properties[]=618222&" +
"properties[]=619218&" +
"properties[]=619364&" +
"properties[]=619552&" +
"properties[]=622332&" +
"properties[]=622334&" +
"properties[]=624498&" +
"properties[]=669012&"
return properties
}
}
/*
631098 - 215
631100 - 212
631102 - 410
631106 - 409
631108 - 403
631110 - 411
631112 - 405
631114 - 402
631116 - 416
631118 - 415
631120 - 406
631124 - 414
631126 - 413
631128 - 412
631130 - 401
631132 - 218
631134 - 407
*/
/*
612782 - 308
618222 - 307
619218 - 209
619364 - 310
619552 - 309
622332 - 208
622334 - 316
624498 - 314
669012 - 306
*/
| 25.011765 | 52 | 0.420978 |
14a4c5b7e47735fb9a76eb7ffd6576943b1cc52f | 210 | // 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 A{func l{typealias F=[class
case,
| 30 | 87 | 0.766667 |
7af073833f394d5a15ce042b7b5e87ca2b3d2aa9 | 2,058 | import Madog
import SceneKit
import SnapKit
import UIKit
class LobbyViewController: UIViewController, LobbyViewModelDelegate {
private let navigationContext: ForwardBackNavigationContext
private let lobbyViewModel: LobbyViewModel
private let collectionViewLayout = LobbyCollectionViewLayout()
init(navigationContext: ForwardBackNavigationContext, lobbyViewModel: LobbyViewModel) {
self.navigationContext = navigationContext
self.lobbyViewModel = lobbyViewModel
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
lobbyViewModel.delegate = self
configureCollectionViewLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.dataSource = lobbyViewModel
collectionView.delegate = lobbyViewModel
collectionView.register(LobbyCollectionViewCell.self, forCellWithReuseIdentifier: lobbyViewModelReuseIdentifier)
collectionView.decelerationRate = .fast
view.addSubview(collectionView)
collectionView.snp.makeConstraints { make in
make.center.width.height.equalToSuperview()
}
}
private func configureCollectionViewLayout() {
let size = view.frame.size
let aspectRatio = size.height > 0 ? size.width / size.height : 1.0
let smallestDimension = min(size.width, size.height)
var scaled = smallestDimension / 5.0 * 3.0
if scaled < 100.0 {
scaled = 100.0
}
collectionViewLayout.itemSize = CGSize(width: scaled * aspectRatio, height: scaled)
}
// MARK: LobbyViewModelDelegate
func viewModel(_: LobbyViewModel, didSelect level: Int) {
let token = Navigation.levelSummary(level: level)
_ = navigationContext.navigateForward(token: token, animated: true)
}
}
| 32.666667 | 120 | 0.705053 |
6a39aa1aed142639f561f81af10f2cd7a0a8e90f | 525 | import XCTest
@testable import Kitura_Session_Fluent
class Kitura_Session_FluentTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssertEqual(Kitura_Session_Fluent().text, "Hello, World!")
}
static var allTests : [(String, (Kitura_Session_FluentTests) -> () throws -> Void)] {
return [
("testExample", testExample),
]
}
}
| 29.166667 | 96 | 0.660952 |
29cbd91a06d4bd8417c5beebef5b1583868e8f76 | 585 | //
// DownloadInstallerView.swift
// macOS
//
// Created by Kenneth Endfinger on 3/22/22.
//
import Foundation
import SwiftUI
struct DownloadInstallerView: View {
@ObservedObject var can: CannedMac
var body: some View {
VStack {
Text("Downloading macOS Installer: \(DownloadInstallerView.formatCurrentProgress(can.downloadCurrentProgress))%")
ProgressView(value: can.downloadCurrentProgress)
}
}
private static func formatCurrentProgress(_ value: Double) -> String {
String(format: "%.2f", value * 100.0)
}
}
| 22.5 | 125 | 0.670085 |
898187b727c17e3d27420aaceb8763fd0d6febee | 617 | //
// DictionaryKeyConvertible.swift
// Convertible
//
// Created by Bradley Hilton on 7/28/16.
// Copyright © 2016 Skyvive. All rights reserved.
//
public protocol JsonDictionaryKeyInitializable {
static func initializeWithJsonDictionaryKey(_ key: JsonDictionaryKey, options: [ConvertibleOption]) throws -> Self
}
public protocol JsonDictionaryKeySerializable {
func serializeToJsonDictionaryKeyWithOptions(_ options: [ConvertibleOption]) throws -> JsonDictionaryKey
}
public protocol JsonDictionaryKeyConvertible : JsonDictionaryKeyInitializable, JsonDictionaryKeySerializable {}
| 28.045455 | 118 | 0.779579 |
fb4c03f04bb5c0d65c15d9a7a1c8d1247792508a | 135 | struct MyStruct {
static let text = "Hello, World!"
static func sayHello() -> String {
return MyStruct.text
}
}
| 13.5 | 38 | 0.585185 |
22b377e2b01c0752b0b9905b78219206dc47c429 | 424 | //: Playground - noun: a place where people can play
import UIKit
func ...(lhs: CountableClosedRange<Int>, rhs: Int) -> [Int] {
let downwards = (rhs ..< lhs.upperBound).reversed()
return Array(lhs) + downwards
}
precedencegroup RangeFormationPrecedence {
higherThan: CastingPrecedence
associativity: left
}
infix operator ... : RangeFormationPrecedence
let range = 1...10...1
print(range)
| 12.848485 | 61 | 0.681604 |
267024d249a96d84f006fc5d180376ca88749954 | 428 | // 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
// REQUIRES: asserts
{} ?? {let a{p
| 38.909091 | 78 | 0.735981 |
f4e3eb832782a640346c22a852028231bfc16d3e | 1,248 | //
// MovieViewerUITests.swift
// MovieViewerUITests
//
// Created by Bconsatnt on 2/5/17.
// Copyright © 2017 Bconsatnt. All rights reserved.
//
import XCTest
class MovieViewerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.72973 | 182 | 0.665064 |
5b2db0e3f3a8ba60435382a44e8c1d878028ce91 | 1,182 | //
// ExpandButtonDemoUITests.swift
// ExpandButtonDemoUITests
//
// Created by Qian Yiyu on 2019/6/5.
// Copyright © 2019 Qian Yiyu. All rights reserved.
//
import XCTest
class ExpandButtonDemoUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.771429 | 182 | 0.695431 |
50cdf420b8ac9dbcd62204a25a5e8058f84a51a3 | 2,345 | //
// SceneDelegate.swift
// SmartTipper
//
// Created by Drew Beckmen on 8/2/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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.
}
}
| 43.425926 | 147 | 0.713433 |
1a93887ec1ac6dfc1379a1ac8f8b191c9f77d095 | 2,670 | // Backup.swift
/*
Package MobileWallet
Created by S.Shovkoplyas on 09.07.2020
Using Swift 5.0
Running on macOS 10.15
Copyright 2019 The Tari Project
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
class Backup {
let url: URL
let folderPath: String
let dateCreation: Date
let dateCreationString: String
let isEncrypted: Bool
var isValid: Bool {
return !ICloudBackup.shared.inProgress && !ICloudBackup.shared.isLastBackupFailed && !BackupScheduler.shared.isBackupScheduled
}
init(url: URL) throws {
if try !url.checkResourceIsReachable() {
throw ICloudBackupError.backupUrlNotValid
}
self.url = url
folderPath = url.deletingLastPathComponent().path
isEncrypted = !url.absoluteString.contains(".zip")
guard let date = try url.resourceValues(forKeys: [.creationDateKey]).allValues.first?.value as? Date else {
throw ICloudBackupError.unableToDetermineDateOfBackup
}
dateCreation = date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd yyy 'at' h:mm a"
dateFormatter.timeZone = .current
dateCreationString = dateFormatter.string(from: date)
}
}
| 35.131579 | 134 | 0.747566 |
9c79f25767d5a8b1615226623257631b47a19f44 | 2,993 | //
// AppointmentsTableViewCell.swift
// PatientApp
//
// Created by Practica on 8/30/18.
// Copyright © 2018 Practica. All rights reserved.
//
import UIKit
class AppointmentsTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// let width = UIScreen.main.bounds.width
// return CGSize(width: width/4, height: 120.0);
// }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionat section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(20, 20, 20, 20)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AppointmentCollectionViewCell", for: indexPath as IndexPath) as! AppointmentCollectionViewCell
cell.dateLabel.text = "25/10/1997"
cell.hourLabel.text = "10 AM"
cell.locationLabel.text = "Outside"
cell.warningLabel.text = "Emergency"
cell.backgroundColor = BackgroundBlueColor
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 240, height: 100)
}
// func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
//
// return CGSize(width: 500, height: TableCellHeight)
//
// }
}
| 39.906667 | 175 | 0.719011 |
5b4694f3b49e83f24b0cb215dfe7b853acfdceac | 1,641 | //
// KeyboardPickerBarButtonItem.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-09-12.
// Copyright © 2017 SIL International. All rights reserved.
//
import UIKit
public class KeyboardPickerBarButtonItem: UIBarButtonItem {
weak var presentingVC: UIViewController?
// Returns a UIBarButtonItem that will display the keyboard picker when tapped
// - since the keyboard picker is modal, a UIViewController must be supplied to display it
// - the button has default images for normal and landscape orientations
// - these can be overridden with other images or a title
public init(presentingVC: UIViewController) {
super.init()
style = .plain
action = #selector(self.showKeyboardPicker)
target = self
self.presentingVC = presentingVC
image = UIImage(named: "keyboard_icon", in: Resources.bundle, compatibleWith: nil)
if UIDevice.current.userInterfaceIdiom == .phone {
landscapeImagePhone = UIImage(named: "keyboard_icon_landscape",
in: Resources.bundle,
compatibleWith: nil)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
presentingVC = nil
}
@objc func showKeyboardPicker() {
if let presentingVC = presentingVC {
Manager.shared.showKeyboardPicker(in: presentingVC, shouldAddKeyboard: false)
}
}
public override var title: String? {
get {
return super.title
}
set(title) {
image = nil
landscapeImagePhone = nil
super.title = title
}
}
}
| 27.35 | 94 | 0.670323 |
dde6c0c4c293a69a82de080fcaae57b0c8a70472 | 64,779 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import XCTest
import UIKit
@testable import Datadog
class RUMMonitorTests: XCTestCase {
override func setUp() {
super.setUp()
XCTAssertNil(Datadog.instance)
XCTAssertNil(RUMFeature.instance)
temporaryFeatureDirectories.create()
}
override func tearDown() {
XCTAssertNil(Datadog.instance)
XCTAssertNil(RUMFeature.instance)
temporaryFeatureDirectories.delete()
super.tearDown()
}
// MARK: - Sending RUM events
func testStartingViewIdentifiedByViewController() throws {
let dateProvider = RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: dateProvider
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.stopView(viewController: mockView)
monitor.startView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers[0].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .applicationStart)
}
try rumEventMatchers[1].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
}
try rumEventMatchers[2].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.timeSpent, 1_000_000_000)
}
try rumEventMatchers[3].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 0)
}
}
func testStartingViewIdentifiedByStringKey() throws {
let dateProvider = RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: dateProvider
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(key: "view1", name: "View1")
monitor.stopView(key: "view1")
monitor.startView(key: "view2", name: "View2")
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let session = try XCTUnwrap(try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers).first)
XCTAssertEqual(session.viewVisits.count, 2)
XCTAssertEqual(session.viewVisits[0].name, "View1")
XCTAssertEqual(session.viewVisits[0].path, "View1")
XCTAssertEqual(session.viewVisits[1].name, "View2")
XCTAssertEqual(session.viewVisits[1].path, "View2")
}
func testStartingView_thenLoadingImageResourceWithRequest() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockWith(httpMethod: "GET"))
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockWith(statusCode: 200, mimeType: "image/png"))
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers[0].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .applicationStart)
}
try rumEventMatchers[1].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
}
try rumEventMatchers[2].model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.resource.type, .image)
XCTAssertEqual(rumModel.resource.statusCode, 200)
}
try rumEventMatchers[3].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 1)
}
}
func testStartingView_thenLoadingXHRResourceWithRequestWithMetrics() throws {
guard #available(iOS 13, *) else {
return // `URLSessionTaskMetrics` mocking doesn't work prior to iOS 13.0
}
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockWith(httpMethod: "POST"))
monitor.addResourceMetrics(
resourceKey: "/resource/1",
metrics: .mockWith(
taskInterval: DateInterval(start: .mockDecember15th2019At10AMUTC(), duration: 4),
transactionMetrics: [
.mockWith(
domainLookupStartDate: .mockDecember15th2019At10AMUTC(addingTimeInterval: 1),
domainLookupEndDate: .mockDecember15th2019At10AMUTC(addingTimeInterval: 3)
)
]
)
)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockWith(statusCode: 200, mimeType: "image/png"))
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let session = try XCTUnwrap(try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers).first)
let resourceEvent = session.viewVisits[0].resourceEvents[0]
XCTAssertEqual(resourceEvent.resource.type, .xhr, "POST Resources should always have the `.xhr` kind")
XCTAssertEqual(resourceEvent.resource.statusCode, 200)
XCTAssertEqual(resourceEvent.resource.duration, 4_000_000_000)
XCTAssertEqual(resourceEvent.resource.dns!.start, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.dns!.duration, 2_000_000_000)
}
func testStartingView_thenLoadingXHRResourceWithRequestWithExternalMetrics() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockWith(httpMethod: "POST"))
let fetch = (start: Date.mockDecember15th2019At10AMUTC(),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 12))
let redirection = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 1),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 2))
let dns = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 3),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 4))
let connect = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 5),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 6))
let ssl = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 7),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 8))
let firstByte = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 9),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 10))
let download = (start: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 11),
end: Date.mockDecember15th2019At10AMUTC(addingTimeInterval: 12))
monitor.addResourceMetrics(
resourceKey: "/resource/1",
fetch: fetch,
redirection: redirection,
dns: dns,
connect: connect,
ssl: ssl,
firstByte: firstByte,
download: download,
responseSize: 42
)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockWith(statusCode: 200, mimeType: "image/png"))
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let session = try XCTUnwrap(try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers).first)
let resourceEvent = session.viewVisits[0].resourceEvents[0]
XCTAssertEqual(resourceEvent.resource.type, .xhr, "POST Resources should always have the `.xhr` kind")
XCTAssertEqual(resourceEvent.resource.statusCode, 200)
XCTAssertEqual(resourceEvent.resource.duration, 12_000_000_000)
XCTAssertEqual(resourceEvent.resource.redirect!.start, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.redirect!.duration, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.dns!.start, 3_000_000_000)
XCTAssertEqual(resourceEvent.resource.dns!.duration, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.connect!.start, 5_000_000_000)
XCTAssertEqual(resourceEvent.resource.connect!.duration, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.ssl!.start, 7_000_000_000)
XCTAssertEqual(resourceEvent.resource.ssl!.duration, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.firstByte!.start, 9_000_000_000)
XCTAssertEqual(resourceEvent.resource.firstByte!.duration, 1_000_000_000)
XCTAssertEqual(resourceEvent.resource.download!.start, 11_000_000_000)
XCTAssertEqual(resourceEvent.resource.download!.duration, 1_000_000_000)
}
func testStartingView_thenLoadingResourceWithURL() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
let url: URL = .mockRandom()
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", url: url)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockWith(statusCode: 200, mimeType: "image/png"))
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let session = try XCTUnwrap(try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers).first)
let resourceEvent = session.viewVisits[0].resourceEvents[0]
XCTAssertEqual(resourceEvent.resource.url, url.absoluteString)
XCTAssertEqual(resourceEvent.resource.statusCode, 200)
}
func testStartingView_thenLoadingResourceWithURLString() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", httpMethod: .post, urlString: "/some/url/string", attributes: [:])
monitor.stopResourceLoading(resourceKey: "/resource/1", statusCode: 333, kind: .beacon)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let session = try XCTUnwrap(try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers).first)
let resourceEvent = session.viewVisits[0].resourceEvents[0]
XCTAssertEqual(resourceEvent.resource.url, "/some/url/string")
XCTAssertEqual(resourceEvent.resource.statusCode, 333)
XCTAssertEqual(resourceEvent.resource.type, .beacon)
XCTAssertEqual(resourceEvent.resource.method, .post)
}
func testStartingView_thenTappingButton() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
let actionName = String.mockRandom()
monitor.startView(viewController: mockView)
monitor.addUserAction(type: .tap, name: actionName)
monitor.stopView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers[0].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .applicationStart)
}
try rumEventMatchers[1].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
}
try rumEventMatchers[2].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .tap)
XCTAssertEqual(rumModel.action.target?.name, actionName)
}
try rumEventMatchers[3].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 2)
XCTAssertEqual(rumModel.view.resource.count, 0)
}
}
func testStartingView_thenLoadingResources_whileScrolling() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startUserAction(type: .scroll, name: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockWith(httpMethod: "GET"))
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockWith(statusCode: 200))
monitor.startResourceLoading(resourceKey: "/resource/2", request: .mockWith(httpMethod: "POST"))
monitor.stopResourceLoading(resourceKey: "/resource/2", response: .mockWith(statusCode: 202))
monitor.stopUserAction(type: .scroll)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 8)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers[0].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .applicationStart)
}
try rumEventMatchers[1].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
XCTAssertEqual(rumModel.view.error.count, 0)
}
var userActionID: String?
try rumEventMatchers[2].model(ofType: RUMResourceEvent.self) { rumModel in
userActionID = rumModel.action?.id
XCTAssertEqual(rumModel.resource.statusCode, 200)
XCTAssertEqual(rumModel.resource.method, .get)
}
XCTAssertNotNil(userActionID, "Resource should be associated with the User Action that issued its loading")
try rumEventMatchers[3].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 1)
XCTAssertEqual(rumModel.view.error.count, 0)
}
try rumEventMatchers[4].model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.resource.statusCode, 202)
XCTAssertEqual(rumModel.resource.method, .post)
}
try rumEventMatchers[5].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 2)
XCTAssertEqual(rumModel.view.error.count, 0)
}
try rumEventMatchers[6].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.resource?.count, 2)
XCTAssertEqual(rumModel.action.error?.count, 0)
XCTAssertEqual(rumModel.action.id, userActionID)
}
try rumEventMatchers[7].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 2)
XCTAssertEqual(rumModel.view.resource.count, 2)
XCTAssertEqual(rumModel.view.error.count, 0)
}
}
func testStartingView_thenIssuingAnError_whileScrolling() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 0.01)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.startUserAction(type: .scroll, name: .mockAny())
#sourceLocation(file: "/user/abc/Foo.swift", line: 100)
monitor.addError(message: "View error message", source: .source)
#sourceLocation()
monitor.addError(message: "Another error message", source: .webview, stack: "Error stack")
monitor.stopUserAction(type: .scroll)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 8)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers[0].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .applicationStart)
}
try rumEventMatchers[1].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
}
try rumEventMatchers[2].model(ofType: RUMErrorEvent.self) { rumModel in
XCTAssertEqual(rumModel.error.message, "View error message")
XCTAssertEqual(rumModel.error.stack, "Foo.swift:100")
XCTAssertEqual(rumModel.error.source, .source)
XCTAssertNil(rumModel.error.type)
}
try rumEventMatchers[3].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
XCTAssertEqual(rumModel.view.error.count, 1)
}
try rumEventMatchers[4].model(ofType: RUMErrorEvent.self) { rumModel in
XCTAssertEqual(rumModel.error.message, "Another error message")
XCTAssertEqual(rumModel.error.stack, "Error stack")
XCTAssertEqual(rumModel.error.source, .webview)
XCTAssertNil(rumModel.error.type)
}
try rumEventMatchers[5].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 1)
XCTAssertEqual(rumModel.view.resource.count, 0)
XCTAssertEqual(rumModel.view.error.count, 2)
}
try rumEventMatchers[6].model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .scroll)
XCTAssertEqual(rumModel.action.error?.count, 2)
}
try rumEventMatchers[7].model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 2)
XCTAssertEqual(rumModel.view.resource.count, 0)
XCTAssertEqual(rumModel.view.error.count, 2)
}
}
func testStartingAnotherViewBeforeFirstIsStopped_thenLoadingResourcesAfterTapingButton() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(
startingFrom: Date(),
advancingBySeconds: RUMUserActionScope.Constants.discreteActionTimeoutDuration
)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
let view1 = createMockView(viewControllerClassName: "FirstViewController")
monitor.startView(viewController: view1)
let view2 = createMockView(viewControllerClassName: "SecondViewController")
monitor.startView(viewController: view2)
monitor.addUserAction(type: .tap, name: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockAny())
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.stopView(viewController: view1)
monitor.stopView(viewController: view2)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 9)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "FirstViewController" }
.model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "FirstViewController")
XCTAssertEqual(rumModel.view.name, "FirstViewController")
XCTAssertEqual(rumModel.view.action.count, 1, "First View should track only the 'applicationStart' Action")
XCTAssertEqual(rumModel.view.resource.count, 0)
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "SecondViewController" }
.model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController")
XCTAssertEqual(rumModel.view.name, "SecondViewController")
XCTAssertEqual(rumModel.view.action.count, 1, "Second View should track the 'tap' Action")
XCTAssertEqual(rumModel.view.resource.count, 1, "Second View should track the Resource")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMActionEvent.self)
.model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController", "Action should be associated with the second View")
XCTAssertEqual(rumModel.view.name, "SecondViewController", "Action should be associated with the second View")
XCTAssertEqual(rumModel.action.type, .tap)
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMResourceEvent.self)
.model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController", "Resource should be associated with the second View")
XCTAssertEqual(rumModel.view.name, "SecondViewController", "Resource should be associated with the second View")
}
}
func testStartingLoadingResourcesFromTheFirstView_thenStartingAnotherViewWhichAlsoLoadsResources() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
let view1 = createMockView(viewControllerClassName: "FirstViewController")
monitor.startView(viewController: view1)
monitor.startResourceLoading(resourceKey: "/resource/1", request: URLRequest(url: .mockWith(pathComponent: "/resource/1")))
monitor.startResourceLoading(resourceKey: "/resource/2", request: URLRequest(url: .mockWith(pathComponent: "/resource/2")))
monitor.stopView(viewController: view1)
let view2 = createMockView(viewControllerClassName: "SecondViewController")
monitor.startView(viewController: view2)
monitor.startResourceLoading(resourceKey: "/resource/3", request: URLRequest(url: .mockWith(pathComponent: "/resource/3")))
monitor.startResourceLoading(resourceKey: "/resource/4", request: URLRequest(url: .mockWith(pathComponent: "/resource/4")))
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.stopResourceLoadingWithError(resourceKey: "/resource/2", errorMessage: .mockAny())
monitor.stopResourceLoading(resourceKey: "/resource/3", response: .mockAny())
monitor.stopResourceLoading(resourceKey: "/resource/4", response: .mockAny())
monitor.stopView(viewController: view2)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 13)
verifyGlobalAttributes(in: rumEventMatchers)
try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "FirstViewController" }
.model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "FirstViewController")
XCTAssertEqual(rumModel.view.name, "FirstViewController")
XCTAssertEqual(rumModel.view.resource.count, 1, "First View should track 1 Resource")
XCTAssertEqual(rumModel.view.error.count, 1, "First View should track 1 Resource Error")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "SecondViewController" }
.model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController")
XCTAssertEqual(rumModel.view.name, "SecondViewController")
XCTAssertEqual(rumModel.view.resource.count, 2, "Second View should track 2 Resources")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMResourceEvent.self) { rumModel in rumModel.resource.url.contains("/resource/1") }
.model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "FirstViewController", "Resource should be associated with the first View")
XCTAssertEqual(rumModel.view.name, "FirstViewController", "Resource should be associated with the first View")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMErrorEvent.self) { rumModel in rumModel.error.resource?.url.contains("/resource/2") ?? false }
.model(ofType: RUMErrorEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "FirstViewController", "Resource should be associated with the first View")
XCTAssertEqual(rumModel.view.name, "FirstViewController", "Resource should be associated with the first View")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMResourceEvent.self) { rumModel in rumModel.resource.url.contains("/resource/3") }
.model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController", "Resource should be associated with the second View")
XCTAssertEqual(rumModel.view.name, "SecondViewController", "Resource should be associated with the second View")
}
try rumEventMatchers
.lastRUMEvent(ofType: RUMResourceEvent.self) { rumModel in rumModel.resource.url.contains("/resource/4") }
.model(ofType: RUMResourceEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.url, "SecondViewController", "Resource should be associated with the second View")
XCTAssertEqual(rumModel.view.name, "SecondViewController", "Resource should be associated with the second View")
}
}
func testStartingView_thenTappingButton_thenTappingAnotherButton() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView)
monitor.addUserAction(type: .tap, name: "1st action")
monitor.addUserAction(type: .swipe, name: "2nd action")
monitor.stopView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
try rumEventMatchers.lastRUMEvent(ofType: RUMActionEvent.self) { $0.action.target?.name == "1st action" }
.model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .tap)
}
try rumEventMatchers.lastRUMEvent(ofType: RUMActionEvent.self) { $0.action.target?.name == "2nd action" }
.model(ofType: RUMActionEvent.self) { rumModel in
XCTAssertEqual(rumModel.action.type, .swipe)
}
try rumEventMatchers.lastRUMEvent(ofType: RUMViewEvent.self)
.model(ofType: RUMViewEvent.self) { rumModel in
XCTAssertEqual(rumModel.view.action.count, 3)
}
}
// MARK: - Sending user info
func testWhenUserInfoIsProvided_itIsSendWithAllEvents() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
userInfoProvider: .mockWith(
userInfo: UserInfo(
id: "abc-123",
name: "Foo",
email: "[email protected]",
extraInfo: [
"str": "value",
"int": 11_235,
"bool": true
]
)
)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView)
monitor.startUserAction(type: .scroll, name: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/2", request: .mockAny())
monitor.stopUserAction(type: .scroll)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.stopResourceLoadingWithError(resourceKey: "/resource/2", errorMessage: .mockAny())
monitor.addError(message: .mockAny(), source: .source)
monitor.stopView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 11)
let expectedUserInfo = RUMUser(email: "[email protected]", id: "abc-123", name: "Foo")
try rumEventMatchers.forEach { event in
XCTAssertEqual(try event.attribute(forKeyPath: "usr.str"), "value")
XCTAssertEqual(try event.attribute(forKeyPath: "usr.int"), 11_235)
XCTAssertEqual(try event.attribute(forKeyPath: "usr.bool"), true) // swiftlint:disable:this xct_specific_matcher
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMActionEvent.self) { action in
XCTAssertEqual(action.usr, expectedUserInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMViewEvent.self) { view in
XCTAssertEqual(view.usr, expectedUserInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMResourceEvent.self) { resource in
XCTAssertEqual(resource.usr, expectedUserInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMErrorEvent.self) { error in
XCTAssertEqual(error.usr, expectedUserInfo)
}
}
// MARK: - Sending connectivity info
func testWhenNetworkAndCarrierInfoAreProvided_thenConnectivityInfoIsSendWithAllEvents() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
networkConnectionInfoProvider: NetworkConnectionInfoProviderMock(
networkConnectionInfo: .mockWith(reachability: .yes, availableInterfaces: [.cellular])
),
carrierInfoProvider: CarrierInfoProviderMock(
carrierInfo: .mockWith(carrierName: "Carrier Name", radioAccessTechnology: .GPRS)
)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView)
monitor.startUserAction(type: .scroll, name: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/2", request: .mockAny())
monitor.stopUserAction(type: .scroll)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.stopResourceLoadingWithError(resourceKey: "/resource/2", errorMessage: .mockAny())
monitor.addError(message: .mockAny(), source: .source)
monitor.stopView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 11)
let expectedConnectivityInfo = RUMConnectivity(
cellular: RUMConnectivity.Cellular(carrierName: "Carrier Name", technology: "GPRS"),
interfaces: [.cellular],
status: .connected
)
try rumEventMatchers.forEachRUMEvent(ofType: RUMActionEvent.self) { action in
XCTAssertEqual(action.connectivity, expectedConnectivityInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMViewEvent.self) { view in
XCTAssertEqual(view.connectivity, expectedConnectivityInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMResourceEvent.self) { resource in
XCTAssertEqual(resource.connectivity, expectedConnectivityInfo)
}
try rumEventMatchers.forEachRUMEvent(ofType: RUMErrorEvent.self) { error in
XCTAssertEqual(error.connectivity, expectedConnectivityInfo)
}
}
// MARK: - Sending Attributes
func testSendingAttributes() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let view1 = createMockView(viewControllerClassName: "FirstViewController")
let view2 = createMockView(viewControllerClassName: "SecondViewController")
let monitor = RUMMonitor.initialize()
// set global attributes:
monitor.addAttribute(forKey: "attribute1", value: "value 1")
monitor.addAttribute(forKey: "attribute2", value: "value 2")
// start View 1:
monitor.startView(viewController: view1)
// update global attributes while the View 1 is active
monitor.addAttribute(forKey: "attribute1", value: "changed value 1") // change the attribute value
monitor.removeAttribute(forKey: "attribute2") // remove the attribute
monitor.stopView(viewController: view1)
// start View 2:
monitor.startView(viewController: view2)
monitor.stopView(viewController: view2)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 3)
let firstViewEvent = try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "FirstViewController" }
XCTAssertNil(try? firstViewEvent.attribute(forKeyPath: "attribute1") as String)
XCTAssertNil(try? firstViewEvent.attribute(forKeyPath: "attribute2") as String)
XCTAssertEqual(try firstViewEvent.attribute(forKeyPath: "context.attribute1") as String, "changed value 1")
XCTAssertEqual(try firstViewEvent.attribute(forKeyPath: "context.attribute2") as String, "value 2")
let secondViewEvent = try rumEventMatchers
.lastRUMEvent(ofType: RUMViewEvent.self) { rumModel in rumModel.view.url == "SecondViewController" }
XCTAssertNil(try? secondViewEvent.attribute(forKeyPath: "attribute1") as String)
XCTAssertEqual(try secondViewEvent.attribute(forKeyPath: "context.attribute1") as String, "changed value 1")
XCTAssertNil(try? secondViewEvent.attribute(forKeyPath: "context.attribute2") as String)
}
func testWhenViewIsStarted_attributesCanBeAddedOrUpdatedButNotRemoved() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(directories: temporaryFeatureDirectories)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.addAttribute(forKey: "a1", value: "foo1")
monitor.addAttribute(forKey: "a2", value: "foo2")
monitor.startView(viewController: mockView)
monitor.addAttribute(forKey: "a1", value: "bar1") // update
monitor.removeAttribute(forKey: "a2") // remove
monitor.addAttribute(forKey: "a3", value: "foo3") // add
monitor.stopView(viewController: mockView)
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 3)
let lastViewUpdate = try rumEventMatchers.lastRUMEvent(ofType: RUMViewEvent.self)
XCTAssertNil(try? lastViewUpdate.attribute(forKeyPath: "a1") as String)
XCTAssertNil(try? lastViewUpdate.attribute(forKeyPath: "a2") as String)
XCTAssertNil(try? lastViewUpdate.attribute(forKeyPath: "a3") as String)
try XCTAssertEqual(lastViewUpdate.attribute(forKeyPath: "context.a1"), "bar1", "The value should be updated")
try XCTAssertEqual(lastViewUpdate.attribute(forKeyPath: "context.a2"), "foo2", "The attribute should not be removed")
try XCTAssertEqual(lastViewUpdate.attribute(forKeyPath: "context.a3"), "foo3", "The attribute should be added")
}
// MARK: - Sending Custom Timings
func testStartingView_thenAddingTiming() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: RelativeDateProvider(
startingFrom: Date(),
advancingBySeconds: 1
)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
setGlobalAttributes(of: monitor)
monitor.startView(viewController: mockView)
monitor.addTiming(name: "timing1")
monitor.addTiming(name: "timing2")
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 4)
verifyGlobalAttributes(in: rumEventMatchers)
let lastViewUpdate = try rumEventMatchers.lastRUMEvent(ofType: RUMViewEvent.self)
XCTAssertEqual(try lastViewUpdate.timing(named: "timing1"), 1_000_000_000)
XCTAssertEqual(try lastViewUpdate.timing(named: "timing2"), 2_000_000_000)
}
// MARK: - RUM Events Dates Correction
func testGivenTimeDifferenceBetweenDeviceAndServer_whenCollectingRUMEvents_thenEventsDateUseServerTime() throws {
// Given
let deviceTime: Date = .mockDecember15th2019At10AMUTC()
var serverTimeDifference = TimeInterval.random(in: 600..<1_200).rounded() // 10 - 20 minutes difference
serverTimeDifference = serverTimeDifference * (Bool.random() ? 1 : -1) // positive or negative difference
let dateProvider = RelativeDateProvider(
startingFrom: deviceTime,
advancingBySeconds: 1 // short advancing, so all events will be collected less than a minute after `deviceTime`
)
// When
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
dateProvider: dateProvider,
dateCorrector: DateCorrectorMock(correctionOffset: serverTimeDifference)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView)
monitor.addUserAction(type: .tap, name: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/1", request: .mockAny())
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.startResourceLoading(resourceKey: "/resource/2", url: .mockAny())
monitor.stopResourceLoadingWithError(resourceKey: "/resource/2", errorMessage: .mockAny())
monitor.addError(message: .mockAny())
// Then
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 10)
let session = try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers)[0]
let viewEvents = session.viewVisits[0].viewEvents
let actionEvents = session.viewVisits[0].actionEvents
let resourceEvents = session.viewVisits[0].resourceEvents
let errorEvents = session.viewVisits[0].errorEvents
XCTAssertGreaterThan(viewEvents.count, 0)
XCTAssertGreaterThan(actionEvents.count, 0)
XCTAssertGreaterThan(resourceEvents.count, 0)
XCTAssertGreaterThan(errorEvents.count, 0)
// All RUM events should be send later than or equal this earliest server time
let earliestServerTime = deviceTime.addingTimeInterval(serverTimeDifference).timeIntervalSince1970.toInt64Milliseconds
viewEvents.forEach { view in
XCTAssertGreaterThanOrEqual(view.date, earliestServerTime, "Event `date` should be adjusted to server time")
}
actionEvents.forEach { action in
XCTAssertGreaterThanOrEqual(action.date, earliestServerTime, "Event `date` should be adjusted to server time")
}
resourceEvents.forEach { resource in
XCTAssertGreaterThanOrEqual(resource.date, earliestServerTime, "Event `date` should be adjusted to server time")
}
errorEvents.forEach { error in
XCTAssertGreaterThanOrEqual(error.date, earliestServerTime, "Event `date` should be adjusted to server time")
}
}
// MARK: - Tracking Consent
func testWhenChangingConsentValues_itUploadsOnlyAuthorizedRUMEvents() throws {
let consentProvider = ConsentProvider(initialConsent: .pending)
// Given
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
consentProvider: consentProvider,
dateProvider: RelativeDateProvider(
startingFrom: Date(),
advancingBySeconds: 1
)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
// When
monitor.startView(viewController: mockView, name: "view in `.pending` consent changed to `.granted`")
monitor.stopView(viewController: mockView)
monitor.dd.queue.sync {} // wait for processing the event in `RUMMonitor`
consentProvider.changeConsent(to: .granted)
monitor.startView(viewController: mockView, name: "view in `.granted` consent")
monitor.stopView(viewController: mockView)
monitor.dd.queue.sync {}
consentProvider.changeConsent(to: .notGranted)
monitor.startView(viewController: mockView, name: "view in `.notGranted` consent")
monitor.stopView(viewController: mockView)
monitor.dd.queue.sync {}
consentProvider.changeConsent(to: .granted)
monitor.startView(viewController: mockView, name: "another view in `.granted` consent")
monitor.stopView(viewController: mockView)
// Then
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 7)
let session = try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers)[0]
XCTAssertEqual(session.viewVisits.count, 3, "Only 3 RUM Views were visited in authorized consent.")
XCTAssertEqual(session.viewVisits[0].name, "view in `.pending` consent changed to `.granted`")
XCTAssertEqual(session.viewVisits[1].name, "view in `.granted` consent")
XCTAssertEqual(session.viewVisits[2].name, "another view in `.granted` consent")
}
// MARK: - Data Scrubbing
func testModifyingEventsBeforeTheyGetSend() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
configuration: .mockWith(
viewEventMapper: { viewEvent in
var viewEvent = viewEvent
viewEvent.view.url = "ModifiedViewURL"
viewEvent.view.name = "ModifiedViewName"
return viewEvent
},
resourceEventMapper: { resourceEvent in
var resourceEvent = resourceEvent
resourceEvent.resource.url = "https://foo.com?q=modified-resource-url"
return resourceEvent
},
actionEventMapper: { actionEvent in
if actionEvent.action.type == .applicationStart {
return nil // drop `.applicationStart` action
} else {
var actionEvent = actionEvent
actionEvent.action.target?.name = "Modified tap action name"
return actionEvent
}
},
errorEventMapper: { errorEvent in
var errorEvent = errorEvent
errorEvent.error.message = "Modified error message"
return errorEvent
}
),
dependencies: .mockWith(
dateProvider: RelativeDateProvider(startingFrom: Date(), advancingBySeconds: 1)
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView, name: "OriginalViewName")
monitor.startResourceLoading(resourceKey: "/resource/1", url: URL(string: "https://foo.com?q=original-resource-url")!)
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.addUserAction(type: .tap, name: "Original tap action name")
monitor.addError(message: "Original error message")
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 5)
let sessions = try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers)
XCTAssertEqual(sessions.count, 1, "All events should belong to a single RUM Session")
let session = sessions[0]
session.viewVisits[0].viewEvents.forEach { viewEvent in
XCTAssertEqual(viewEvent.view.url, "ModifiedViewURL")
XCTAssertEqual(viewEvent.view.name, "ModifiedViewName")
}
XCTAssertEqual(session.viewVisits[0].resourceEvents.count, 1)
XCTAssertEqual(session.viewVisits[0].resourceEvents[0].resource.url, "https://foo.com?q=modified-resource-url")
XCTAssertEqual(session.viewVisits[0].actionEvents.count, 1)
XCTAssertEqual(session.viewVisits[0].actionEvents[0].action.target?.name, "Modified tap action name")
XCTAssertEqual(session.viewVisits[0].errorEvents.count, 1)
XCTAssertEqual(session.viewVisits[0].errorEvents[0].error.message, "Modified error message")
}
func testDroppingEventsBeforeTheyGetSent() throws {
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
configuration: .mockWith(
resourceEventMapper: { _ in nil },
actionEventMapper: { event in
return event.action.type == .applicationStart ? event : nil
},
errorEventMapper: { _ in nil }
)
)
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView)
monitor.startResourceLoading(resourceKey: "/resource/1", url: .mockAny())
monitor.stopResourceLoading(resourceKey: "/resource/1", response: .mockAny())
monitor.addUserAction(type: .tap, name: .mockAny())
monitor.addError(message: .mockAny())
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 2)
let sessions = try RUMSessionMatcher.groupMatchersBySessions(rumEventMatchers)
XCTAssertEqual(sessions.count, 1, "All events should belong to a single RUM Session")
let session = sessions[0]
XCTAssertNotEqual(session.viewVisits[0].viewEvents.count, 0)
let lastEvent = session.viewVisits[0].viewEvents.last!
XCTAssertEqual(lastEvent.view.resource.count, 0, "resource.count should reflect all resource events being dropped.")
XCTAssertEqual(lastEvent.view.action.count, 1, "action.count should reflect all action events being dropped.")
XCTAssertEqual(lastEvent.view.error.count, 0, "error.count should reflect all error events being dropped.")
XCTAssertEqual(session.viewVisits[0].resourceEvents.count, 0)
XCTAssertEqual(session.viewVisits[0].actionEvents.count, 1)
XCTAssertEqual(session.viewVisits[0].errorEvents.count, 0)
}
// MARK: - Integration with Crash Reporting
func testGivenRegisteredCrashReporter_whenRUMViewEventIsSend_itIsUpdatedInCurrentCrashContext() throws {
let randomUserInfoAttributes: [String: String] = .mockRandom()
let randomViewEventAttributes: [String: String] = .mockRandom()
RUMFeature.instance = .mockByRecordingRUMEventMatchers(
directories: temporaryFeatureDirectories,
dependencies: .mockWith(
userInfoProvider: .mockWith(
userInfo: .init(
id: .mockRandom(),
name: .mockRandom(),
email: .mockRandom(),
extraInfo: randomUserInfoAttributes
)
)
)
)
defer { RUMFeature.instance = nil }
CrashReportingFeature.instance = .mockNoOp()
defer { CrashReportingFeature.instance = nil }
// Given
Global.crashReporter = CrashReporter(crashReportingFeature: CrashReportingFeature.instance!)
defer { Global.crashReporter = nil }
// When
let monitor = RUMMonitor.initialize()
monitor.startView(viewController: mockView, attributes: randomViewEventAttributes)
// Then
let rumEventMatchers = try RUMFeature.waitAndReturnRUMEventMatchers(count: 2)
let lastRUMViewEventSent: RUMViewEvent = try rumEventMatchers[1].model()
let currentCrashContext = try XCTUnwrap(Global.crashReporter?.crashContextProvider.currentCrashContext)
XCTAssertEqual(
currentCrashContext.lastRUMViewEvent?.model,
lastRUMViewEventSent
)
XCTAssertEqual(
currentCrashContext.lastRUMViewEvent?.attributes as? [String: String],
randomViewEventAttributes
)
XCTAssertEqual(
currentCrashContext.lastRUMViewEvent?.userInfoAttributes as? [String: String],
randomUserInfoAttributes
)
}
// MARK: - Thread safety
func testRandomlyCallingDifferentAPIsConcurrentlyDoesNotCrash() {
RUMFeature.instance = .mockNoOp()
defer { RUMFeature.instance = nil }
let monitor = RUMMonitor.initialize()
let view = mockView
DispatchQueue.concurrentPerform(iterations: 900) { iteration in
let modulo = iteration % 15
switch modulo {
case 0: monitor.startView(viewController: view)
case 1: monitor.stopView(viewController: view)
case 2: monitor.addError(error: ErrorMock(), source: .custom)
case 3: monitor.addError(message: .mockAny(), source: .custom)
case 4: monitor.startResourceLoading(resourceKey: .mockAny(), request: .mockAny())
case 5: monitor.stopResourceLoading(resourceKey: .mockAny(), response: .mockAny())
case 6: monitor.stopResourceLoadingWithError(resourceKey: .mockAny(), error: ErrorMock())
case 7: monitor.stopResourceLoadingWithError(resourceKey: .mockAny(), errorMessage: .mockAny())
case 8: monitor.startUserAction(type: .scroll, name: .mockRandom())
case 9: monitor.stopUserAction(type: .scroll)
case 10: monitor.addUserAction(type: .tap, name: .mockRandom())
case 11: _ = monitor.dd.contextProvider.context
case 12: monitor.addAttribute(forKey: String.mockRandom(), value: String.mockRandom())
case 13: monitor.removeAttribute(forKey: String.mockRandom())
case 14: monitor.dd.enableRUMDebugging(.random())
default: break
}
}
}
// MARK: - Usage
func testGivenDatadogNotInitialized_whenInitializingRUMMonitor_itPrintsError() {
let printFunction = PrintFunctionMock()
consolePrint = printFunction.print
defer { consolePrint = { print($0) } }
// given
XCTAssertNil(Datadog.instance)
// when
let monitor = RUMMonitor.initialize()
// then
XCTAssertEqual(
printFunction.printedMessage,
"🔥 Datadog SDK usage error: `Datadog.initialize()` must be called prior to `RUMMonitor.initialize()`."
)
XCTAssertTrue(monitor is DDNoopRUMMonitor)
}
func testGivenRUMFeatureDisabled_whenInitializingRUMMonitor_itPrintsError() throws {
let printFunction = PrintFunctionMock()
consolePrint = printFunction.print
defer { consolePrint = { print($0) } }
// given
Datadog.initialize(
appContext: .mockAny(),
trackingConsent: .mockRandom(),
configuration: Datadog.Configuration.builderUsing(clientToken: "abc-def", environment: "tests").build()
)
// when
let monitor = RUMMonitor.initialize()
// then
XCTAssertEqual(
printFunction.printedMessage,
"🔥 Datadog SDK usage error: `RUMMonitor.initialize()` produces a non-functional monitor, as the RUM feature is disabled."
)
XCTAssertTrue(monitor is DDNoopRUMMonitor)
try Datadog.deinitializeOrThrow()
}
func testGivenRUMMonitorInitialized_whenInitializingAnotherTime_itPrintsError() throws {
let printFunction = PrintFunctionMock()
consolePrint = printFunction.print
defer { consolePrint = { print($0) } }
// given
Datadog.initialize(
appContext: .mockAny(),
trackingConsent: .mockRandom(),
configuration: Datadog.Configuration.builderUsing(rumApplicationID: .mockAny(), clientToken: .mockAny(), environment: .mockAny()).build()
)
Global.rum = RUMMonitor.initialize()
defer { Global.rum = DDNoopRUMMonitor() }
// when
_ = RUMMonitor.initialize()
// then
XCTAssertEqual(
printFunction.printedMessage,
"""
🔥 Datadog SDK usage error: The `RUMMonitor` instance was already created. Use existing `Global.rum` instead of initializing the `RUMMonitor` another time.
"""
)
try Datadog.deinitializeOrThrow()
}
func testGivenRUMMonitorInitialized_whenTogglingDatadogDebugRUM_itTogglesRUMDebugging() throws {
// given
Datadog.initialize(
appContext: .mockAny(),
trackingConsent: .mockRandom(),
configuration: .mockWith(rumApplicationID: "rum-123", rumEnabled: true)
)
Global.rum = RUMMonitor.initialize()
defer { Global.rum = DDNoopRUMMonitor() }
let monitor = Global.rum.dd
monitor.queue.sync {
XCTAssertNil(monitor.debugging)
}
// when & then
Datadog.debugRUM = true
monitor.queue.sync {
XCTAssertNotNil(monitor.debugging)
}
Datadog.debugRUM = false
monitor.queue.sync {
XCTAssertNil(monitor.debugging)
}
try Datadog.deinitializeOrThrow()
}
func testGivenRUMAutoInstrumentationEnabled_whenRUMMonitorIsNotRegistered_itPrintsWarningsOnEachEvent() throws {
Datadog.initialize(
appContext: .mockAny(),
trackingConsent: .mockRandom(),
configuration: Datadog.Configuration
.builderUsing(rumApplicationID: .mockAny(), clientToken: .mockAny(), environment: .mockAny())
.trackURLSession(firstPartyHosts: [.mockAny()])
.trackUIKitRUMViews(using: UIKitRUMViewsPredicateMock(result: .init(name: .mockAny())))
.trackUIKitActions(true)
.build()
)
let output = LogOutputMock()
userLogger = .mockWith(logOutput: output)
// Given
let resourcesHandler = try XCTUnwrap(URLSessionAutoInstrumentation.instance?.interceptor.handler)
let viewsHandler = try XCTUnwrap(RUMAutoInstrumentation.instance?.views?.handler)
let userActionsHandler = try XCTUnwrap(RUMAutoInstrumentation.instance?.userActions?.handler)
// When
XCTAssertTrue(Global.rum is DDNoopRUMMonitor)
// Then
resourcesHandler.notify_taskInterceptionCompleted(interception: TaskInterception(request: .mockAny(), isFirstParty: .mockAny()))
XCTAssertEqual(output.recordedLog?.status, .warn)
XCTAssertEqual(
output.recordedLog?.message,
"""
RUM Resource was completed, but no `RUMMonitor` is registered on `Global.rum`. RUM auto instrumentation will not work.
Make sure `Global.rum = RUMMonitor.initialize()` is called before any network request is send.
"""
)
viewsHandler.notify_viewDidAppear(viewController: mockView, animated: .mockAny())
XCTAssertEqual(output.recordedLog?.status, .warn)
XCTAssertEqual(
output.recordedLog?.message,
"""
RUM View was started, but no `RUMMonitor` is registered on `Global.rum`. RUM auto instrumentation will not work.
Make sure `Global.rum = RUMMonitor.initialize()` is called before any `UIViewController` is presented.
"""
)
let mockWindow = UIWindow(frame: .zero)
let mockUIControl = UIControl()
mockWindow.addSubview(mockUIControl)
userActionsHandler.notify_sendEvent(
application: .shared,
event: .mockWith(touches: [.mockWith(phase: .ended, view: mockUIControl)])
)
XCTAssertEqual(output.recordedLog?.status, .warn)
XCTAssertEqual(
output.recordedLog?.message,
"""
RUM Action was detected, but no `RUMMonitor` is registered on `Global.rum`. RUM auto instrumentation will not work.
Make sure `Global.rum = RUMMonitor.initialize()` is called before any action happens.
"""
)
URLSessionAutoInstrumentation.instance?.swizzler.unswizzle()
RUMAutoInstrumentation.instance?.views?.swizzler.unswizzle()
RUMAutoInstrumentation.instance?.userActions?.swizzler.unswizzle()
try Datadog.deinitializeOrThrow()
}
// MARK: - Internal attributes
func testHandlingInternalTimestampAttribute() throws {
RUMFeature.instance = .mockNoOp()
defer { RUMFeature.instance = nil }
var mockCommand = RUMCommandMock()
mockCommand.attributes = [
RUMAttribute.internalTimestamp: Int64(1_000) // 1000 in miliseconds
]
let monitor = try XCTUnwrap(RUMMonitor.initialize() as? RUMMonitor)
let transformedCommand = monitor.transform(command: mockCommand)
XCTAssertTrue(transformedCommand.attributes.isEmpty)
XCTAssertNotEqual(transformedCommand.time, mockCommand.time)
XCTAssertEqual(transformedCommand.time, Date(timeIntervalSince1970: 1)) // 1 in seconds
}
// MARK: - Private helpers
private var expectedAttributes = [String: String]()
private func setGlobalAttributes(of monitor: DDRUMMonitor) {
let key = String.mockRandom()
let value = String.mockRandom()
monitor.addAttribute(forKey: key, value: value)
expectedAttributes = ["context.\(key)": value]
}
private func verifyGlobalAttributes(in matchers: [RUMEventMatcher]) {
for matcher in matchers {
expectedAttributes.forEach { attrKey, attrValue in
XCTAssertEqual(try? matcher.attribute(forKeyPath: attrKey), attrValue)
}
}
}
}
class RUMHTTPMethodTests: XCTestCase {
func testItCanBeInitializedFromURLRequest() {
XCTAssertEqual(
RUMMethod(httpMethod: "get".randomcased()), .get
)
XCTAssertEqual(
RUMMethod(httpMethod: "post".randomcased()), .post
)
XCTAssertEqual(
RUMMethod(httpMethod: "put".randomcased()), .put
)
XCTAssertEqual(
RUMMethod(httpMethod: "delete".randomcased()), .delete
)
XCTAssertEqual(
RUMMethod(httpMethod: "head".randomcased()), .head
)
XCTAssertEqual(
RUMMethod(httpMethod: "patch".randomcased()), .patch
)
}
func testWhenInitializingFromURLRequest_itDefaultsToGET() {
XCTAssertEqual(
RUMMethod(httpMethod: "unknown_method".randomcased()), .get
)
}
}
class RUMResourceKindTests: XCTestCase {
func testWhenInitializedWithResponse_itReturnsKindBasedOnMIMEType() {
let fixtures: [(mime: String, kind: RUMResourceType)] = [
(mime: "image/png", kind: .image),
(mime: "video/mpeg", kind: .media),
(mime: "audio/ogg", kind: .media),
(mime: "font/otf", kind: .font),
(mime: "text/css", kind: .css),
(mime: "text/css; charset=UTF-8", kind: .css),
(mime: "text/javascript", kind: .js),
(mime: "text/javascript; charset=UTF-8", kind: .js),
]
fixtures.forEach { mime, expectedKind in
XCTAssertEqual(
RUMResourceType(response: .mockWith(mimeType: mime.randomcased())),
expectedKind
)
}
}
func testWhenInitializedWithPOSTorPUTorDELETErequest_itReturnsXHR() {
XCTAssertEqual(
RUMResourceType(request: .mockWith(httpMethod: "POST".randomcased())), .xhr
)
XCTAssertEqual(
RUMResourceType(request: .mockWith(httpMethod: "PUT".randomcased())), .xhr
)
XCTAssertEqual(
RUMResourceType(request: .mockWith(httpMethod: "DELETE".randomcased())), .xhr
)
}
func testWhenInitializedWithGETorHEADorPATCHrequest_itReturnsNil() {
XCTAssertNil(
RUMResourceType(request: .mockWith(httpMethod: "GET".randomcased()))
)
XCTAssertNil(
RUMResourceType(request: .mockWith(httpMethod: "HEAD".randomcased()))
)
XCTAssertNil(
RUMResourceType(request: .mockWith(httpMethod: "PATCH".randomcased()))
)
}
func testWhenInitializingFromHTTPURLResponse_itDefaultsToOther() {
XCTAssertEqual(
RUMResourceType(response: .mockWith(mimeType: "unknown/type")), .other
)
}
}
| 47.35307 | 166 | 0.667531 |
508cded03d0579bf251fd8f3532907b0a6d7f6c1 | 228 | // 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 a {
var : a {
{
{
{
{
{
}
}
}
}
{
}
}
}
func a<T : a
| 10.857143 | 87 | 0.649123 |
6a359a235d3c79827c9d35c614265dd028b2a13f | 177 | //
// Highlightable.swift
// PokemonViewer
//
// Created by Alexandr Goncharov on 09.11.2020.
//
import Foundation
protocol Highlightable {
func set(highlighted: Bool)
}
| 13.615385 | 48 | 0.711864 |
01f8303a5dee3c22759c82538d456f31c43bcd7d | 3,762 | //
// UIView +Category.swift
// LoveNews
//
// Created by yingz on 2018/5/4.
// Copyright © 2018年 ygz. All rights reserved.
//
import UIKit
enum Direction {
case top
case left
case bottom
case right
}
extension UIView {
// 尺寸
var size: CGSize {
get {
return self.frame.size
}
set(newValue) {
self.frame.size = CGSize(width: newValue.width, height: newValue.height)
}
}
// 宽度
var width: CGFloat {
get {
return self.frame.size.width
}
set(newValue) {
self.frame.size.width = newValue
}
}
// 高度
var height: CGFloat {
get {
return self.frame.size.height
}
set(newValue) {
self.frame.size.height = newValue
}
}
// 横坐标
var x: CGFloat {
get {
return self.frame.minX
}
set(newValue) {
self.frame = CGRect(x: newValue, y: y, width: width, height: height)
}
}
// 纵坐标
var y: CGFloat {
get {
return self.frame.minY
}
set(newValue) {
self.frame = CGRect(x: x, y: newValue, width: width, height: height)
}
}
// 右端横坐标
var right: CGFloat {
get {
return frame.origin.x + frame.size.width
}
set(newValue) {
frame.origin.x = newValue - frame.size.width
}
}
// 底端纵坐标
var bottom: CGFloat {
get {
return frame.origin.y + frame.size.height
}
set(newValue) {
frame.origin.y = newValue - frame.size.height
}
}
// 中心横坐标
var centerX: CGFloat {
get {
return self.center.x
}
set(newValue) {
center.x = newValue
}
}
// 中心纵坐标
var centerY: CGFloat {
get {
return center.y
}
set(newValue) {
center.y = newValue
}
}
// 原点
var origin: CGPoint {
get {
return self.origin
}
set(newValue) {
frame.origin = newValue
}
}
// 右上角坐标
var topRight: CGPoint {
get {
return CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y)
}
set(newValue) {
frame.origin = CGPoint(x: newValue.x - width, y: newValue.y)
}
}
// 右下角坐标
var bottomRight: CGPoint {
get {
return CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height)
}
set(newValue) {
frame.origin = CGPoint(x: newValue.x - width, y: newValue.y - height)
}
}
// 左下角坐标
var bottomLeft: CGPoint {
get {
return CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height)
}
set(newValue) {
frame.origin = CGPoint(x: newValue.x, y: newValue.y - height)
}
}
/* 获取UIView对象某个方向缩进指定距离后的方形区域
* direction: 要缩进的方向
* distance: 缩进的距离
* Returns: 得到的区域
*/
func cutRect(direction: Direction, distance: CGFloat) -> CGRect {
switch direction {
case .top:
return CGRect(x: 0, y: distance, width: self.width, height: self.height - distance)
case .left:
return CGRect(x: distance, y: 0, width: self.width - distance, height: self.height)
case .right:
return CGRect(x: 0, y: 0, width: self.width - distance, height: self.height)
case .bottom:
return CGRect(x: 0, y: 0, width: self.width, height: self.height - distance)
}
}
}
| 22 | 103 | 0.489102 |
8affbe46f1fe43ebf0b0b144733dbe6fc6c50049 | 4,554 | //
// ViewController.swift
// Project 5
//
// Created by Alvaro Orellana on 10-05-21.
//
import UIKit
class ViewController: UITableViewController {
// MARK: - Variables
var textManager = TextManager()
var allWords = [String]()
var usedWords = [String]()
let titleKeyUserDefaults = "title key"
let usedWordsKeyUserDefaults = "used word key "
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigationItem()
loadWords()
//newGame()
loadProgress()
}
override func viewWillDisappear(_ animated: Bool) {
saveProgress()
}
// MARK: - Methods
private func setUpNavigationItem() {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(newGame))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(barButtonTouched))
}
private func loadWords() {
// Look for file path
if let path = Bundle.main.path(forResource: "start", ofType: "txt") {
// Convert file into a string
if let wordsFromFile = try? String(contentsOfFile: path) {
// Convert string into array using a new line as separator
allWords = wordsFromFile.components(separatedBy: "\n")
}
}
if allWords.isEmpty {
// Executes if file couldn't be loaded or stored in array
allWords = ["no funciono"]
}
}
@objc private func barButtonTouched() {
// Creates and presentes alert controller
let alert = UIAlertController(title: "Enter word", message: nil, preferredStyle: .alert)
alert.addTextField()
let submitAction = UIAlertAction(title: "Ok", style: .default) { [weak self, weak alert] _ in
// Get user typed word from textfield
guard let typedWord = alert?.textFields?[0].text else { return }
// Adds user typed word to the array
self?.submit(typedWord)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
alert.addAction(submitAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
private func submit(_ answer: String) {
let userAnswer = answer.lowercased()
let title = title?.lowercased()
let isWordValid = textManager.isWordValid(userAnswer, withTitle: title!, usedWords: usedWords)
if isWordValid {
usedWords.insert(answer, at: 0)
let indexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
} else {
let (errorTitle, errorMessage) = textManager.getErrorMessageAndTitle()
let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
}
}
@objc private func newGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}
private func loadProgress() {
let defaults = UserDefaults.standard
title = defaults.string(forKey: titleKeyUserDefaults) ?? allWords.randomElement()
if let savedWordsArray = defaults.array(forKey: usedWordsKeyUserDefaults) as? [String] {
usedWords = savedWordsArray
}
}
private func saveProgress() {
let defaults = UserDefaults.standard
defaults.set(title, forKey: titleKeyUserDefaults)
defaults.set(usedWords, forKey: usedWordsKeyUserDefaults)
}
}
// MARK: - Table View Controller methods
extension ViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usedWords.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)
cell.textLabel?.text = usedWords[indexPath.row]
return cell
}
}
| 30.15894 | 137 | 0.603865 |
23ad39250c7c2515804ab0eaf86eee831436b843 | 3,158 | //
// SuperheroViewController.swift
// SMovie
//
// Created by MacBookPro10 on 9/24/18.
// Copyright © 2018 MacBookPro10. All rights reserved.
//
import UIKit
class SuperheroViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var indicatoractivity: UIActivityIndicatorView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell
let movie = movies[indexPath.item]
if let posterPathString = movie["poster_path"] as? String{
let baseURLString = "https://image.tmdb.org/t/p/w500"
let posterURL = URL(string: baseURLString + posterPathString)!
cell.ImageSuper.af_setImage(withURL: posterURL)
}
return cell
}
@IBOutlet weak var collectionview: UICollectionView!
var movies: [[String: Any]] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionview.dataSource = self
fetchNowPlayingMovie()
}
func fetchNowPlayingMovie(){
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")!
// Start the activity indicator
indicatoractivity.startAnimating()
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
// This will run when the network request returns
if let error = error {
print(error.localizedDescription)
} else if let data = data {
// Stop the activity indicator
// Hides automatically if "Hides When Stopped" is enabled
self.indicatoractivity.stopAnimating()
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let movies = dataDictionary["results"] as! [[String: Any]]
self.movies = movies
self.collectionview.reloadData()
// self.refreshControl.endRefreshing()
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UICollectionViewCell
if let indexpath = collectionview.indexPath(for: cell) {
let movie = movies[indexpath.row]
let detailViewController = segue.destination as! DetailsViewController
detailViewController.movie = movie
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 36.72093 | 121 | 0.645662 |
f5c817a4b6a2d613692928c95b0f69080ae5ad9f | 2,634 | //
// TextManager.swift
// Project 5
//
// Created by Alvaro Orellana on 11-05-21.
//
import UIKit
struct TextManager {
let minimunWordLenght = 3
var errorTitle: String?
var errorMessage: String?
mutating func isWordValid(_ word: String, withTitle title: String, usedWords: [String]) -> Bool {
let isPossible = isPosible(word, with: title)
let isOriginal = isOriginal(word, usedWords: usedWords)
let isReal = isReal(word)
if isPossible && isOriginal && isReal && word.count >= minimunWordLenght && word != title {
return true
} else {
if !isPossible {
errorTitle = "Word not possible"
errorMessage = "You can't spell that word from \(title)"
} else if !isReal {
errorTitle = "Non existent word"
errorMessage = "You can't just make words up"
} else if !isOriginal {
errorTitle = "Used word"
errorMessage = "You already used that word. Check the list"
} else if word.count < minimunWordLenght {
errorTitle = "Too short"
errorMessage = "Words have to be at least \(minimunWordLenght) characters long"
} else if word == title {
errorTitle = "Copy of given word"
errorMessage = "Can't just copy the same word yo"
}
return false
}
}
func getErrorMessageAndTitle() -> (String?, String?) {
return (errorTitle, errorMessage)
}
private func isReal(_ word: String) -> Bool {
let checker = UITextChecker()
let wordRange = NSRange(location: 0, length: word.utf8.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: wordRange, startingAt: 0, wrap: false, language: "en")
return misspelledRange.location == NSNotFound
}
private func isOriginal(_ word: String, usedWords: [String]) -> Bool {
return !usedWords.contains(word)
}
private func isPosible(_ word: String, with title: String) -> Bool {
var titleToCheck = title
for letter in word {
if let index = titleToCheck.firstIndex(of: letter) {
titleToCheck.remove(at: index)
} else {
return false
}
}
return true
}
}
| 28.322581 | 131 | 0.523918 |
de4332c75beac3f3883d8c6cb78dfae4f97412aa | 1,610 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
import Foundation
import DatadogSDKBridge
@objc(DdLogs)
class RNDdLogs: NSObject {
@objc(requiresMainQueueSetup)
static func requiresMainQueueSetup() -> Bool {
return false
}
let nativeInstance: DdLogs = Bridge.getDdLogs()
@objc(debug:withContext:withResolver:withRejecter:)
func debug(message: NSString, context: NSDictionary, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void {
nativeInstance.debug(message: message, context: context)
resolve(nil)
}
@objc(info:withContext:withResolver:withRejecter:)
func info(message: NSString, context: NSDictionary, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void {
nativeInstance.info(message: message, context: context)
resolve(nil)
}
@objc(warn:withContext:withResolver:withRejecter:)
func warn(message: NSString, context: NSDictionary, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void {
nativeInstance.warn(message: message, context: context)
resolve(nil)
}
@objc(error:withContext:withResolver:withRejecter:)
func error(message: NSString, context: NSDictionary, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void {
nativeInstance.error(message: message, context: context)
resolve(nil)
}
}
| 35.777778 | 128 | 0.73354 |
de7ee87603c43a1fea5ec6bc3d6dafe0737d9f59 | 4,712 | //
// HeatsStartView.swift
// PinewoodDerby
//
// Created by Rand Dow on 12/31/21.
//
import SwiftUI
struct TrackView: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
let track: Int
let car: Int
let derby = Derby.shared
var body: some View {
VStack {
HStack(spacing: 1) {
Text("Track \(track): ")
.font(.system(size: 24))
.frame(width:90)
//.background(.yellow)
if car == 0 {
Text("-")
.font(.system(size: 24))
.frame(width:35)
.background(.yellow)
Text("").frame(width:150)
Text("").frame(width:145)
Text("").frame(width:34)
} else {
Text("\(car)")
.font(.system(size: 24))
.frame(width:35)
//.background(.yellow)
Text(getCarName(car))
.font(.system(size: 20))
.frame(width:115, alignment: .leading)
.lineLimit(1).minimumScaleFactor(0.4)
//.background(.yellow)
Text(getName(car))
.font(.system(size: 20))
.frame(width:145, alignment: .leading)
.lineLimit(1).minimumScaleFactor(0.4)
//.background(.yellow)
Text(getAge(car))
.font(.system(size: 20))
.frame(width:34)
.lineLimit(1).minimumScaleFactor(0.4)
//.background(.yellow)
}
}
Spacer().frame(height: 10)
}
}
func getCarName(_ carNumber: Int) -> String {
let entry = derby.racers.filter { $0.carNumber == carNumber }[0]
return entry.carName
}
func getName(_ carNumber: Int) -> String {
let entry = derby.racers.filter { $0.carNumber == carNumber }[0]
return entry.firstName + " " + entry.lastName
}
func getAge(_ carNumber: Int) -> String {
let entry = derby.racers.filter { $0.carNumber == carNumber }[0]
return entry.age
}
}
struct HeatsStartView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@Environment(\.colorScheme) var colorScheme: ColorScheme
@ObservedObject var derby = Derby.shared
var body: some View {
VStack {
Group {
Spacer().frame(height: 20)
// chevron down
HStack {
Spacer().frame(minWidth: 0)
Image(systemName: "chevron.compact.down").resizable().frame(width: 35, height: 12).opacity(0.3)
Spacer().frame(minWidth: 0)
}
Spacer().frame(height: 40)
// Title
HStack {
Spacer()
Text("Run Heat \(derby.heat)").font(.system(size: 22)).bold()
Spacer()
}
Spacer().frame(height:30)
}
TrackView(track: 1, car: derby.trackCars[0])
TrackView(track: 2, car: derby.trackCars[1])
if derby.trackCars.count > 2 {
TrackView(track: 3, car: derby.trackCars[2])
if derby.trackCars.count > 3 {
TrackView(track: 4, car: derby.trackCars[3])
if derby.trackCars.count > 4 {
TrackView(track: 5, car: derby.trackCars[4])
if derby.trackCars.count > 5 {
TrackView(track: 6, car: derby.trackCars[5])
}
}
}
}
Spacer().frame(height:30)
HStack {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
.font(.system(size: 20))
.bold()
}
Spacer().frame(width: 40)
Button(action: {
derby.startHeat(derby.heat, derby.trackCars)
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Start")
.foregroundColor(.red)
.font(.system(size: 20))
.bold()
}
}
Spacer()
}
}
}
| 32.054422 | 115 | 0.431876 |
f73a64b9c59e9a5d54e46a5e5f04623553c721c2 | 5,276 | //
// TestHelper.swift
// GCXTrustPolicy
//
// Copyright 2017 grandcentrix GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// MARK: - Test Certificates -
struct TestCertificates {
// grandcentrix certificates
static let gcxRootCA = TestCertificates.certificate(name: "gcx-TrustedRoot")
static let gcxIntermediateCA = TestCertificates.certificate(name: "gcx-DigiCertCA")
static let gcxLeafWildcard = TestCertificates.certificate(name: "gcx-wildcard-valid")
// grandcentrix self-signed and invalid certificates
static let gcxSelfSignedExpired = TestCertificates.certificate(name: "gcx-selfsigned-expired")
static let gcxSelfSignedValid = TestCertificates.certificate(name: "gcx-selfsigned-valid")
static let invalidFile = TestCertificates.certificate(name: "invalidCertFile")
static let gcxLeafWildcardExpired = TestCertificates.certificate(name: "gcx-wildcard-expired")
// Disig test certificates http://testssl-expire.disig.sk/index.en.html
static let disigRootCA = TestCertificates.certificate(name: "CA Disig Root R2")
static let disigIntermediateCA = TestCertificates.certificate(name: "CA Disig R2I2 Certification Service")
static let disigLeafValid = TestCertificates.certificate(name: "testssl-valid-r2i2.disig.sk")
static let disigLeafExpired = TestCertificates.certificate(name: "testssl-expire-r2i2.disig.sk")
static let disigLeafRevoked = TestCertificates.certificate(name: "testssl-revoked-r2i2.disig.sk")
static func certificate(name fileName: String) -> SecCertificate {
class Bundle {}
let filePath = Foundation.Bundle(for: Bundle.self).path(forResource: fileName, ofType: "cer")!
let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))
return SecCertificateCreateWithData(nil, data as CFData)!
}
}
// MARK: - Test Trusts -
enum TestTrusts: Int {
case validGCXTrustChain
case expiredGCXTrustChain
case validGCXIntermediateAndRootOnly
case validGCXWildcardOnly
case validGCXRootOnly
case validGCXSelfSigned
case expiredGCXSelfSigned
case validDisigTrustChain
case expiredDisigTrustChain
case revokedDisigTrustChain
var trust: SecTrust {
let trust: SecTrust
switch self {
case .validGCXTrustChain:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxLeafWildcard,
TestCertificates.gcxIntermediateCA,
TestCertificates.gcxRootCA])
case .expiredGCXTrustChain:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxLeafWildcardExpired,
TestCertificates.gcxIntermediateCA,
TestCertificates.gcxRootCA])
case .validGCXIntermediateAndRootOnly:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxIntermediateCA,
TestCertificates.gcxRootCA])
case .validGCXWildcardOnly:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxLeafWildcard])
case .validGCXRootOnly:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxRootCA])
case .validGCXSelfSigned:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxSelfSignedValid])
case .expiredGCXSelfSigned:
trust = TestTrusts.trustWithCertificates([
TestCertificates.gcxSelfSignedExpired])
case .validDisigTrustChain:
trust = TestTrusts.trustWithCertificates([
TestCertificates.disigLeafValid,
TestCertificates.disigIntermediateCA,
TestCertificates.disigRootCA])
case .expiredDisigTrustChain:
trust = TestTrusts.trustWithCertificates([
TestCertificates.disigLeafExpired,
TestCertificates.disigIntermediateCA,
TestCertificates.disigRootCA])
case .revokedDisigTrustChain:
trust = TestTrusts.trustWithCertificates([
TestCertificates.disigLeafRevoked,
TestCertificates.disigIntermediateCA,
TestCertificates.disigRootCA])
}
return trust
}
static func trustWithCertificates(_ certificates: [SecCertificate]) -> SecTrust {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
SecTrustCreateWithCertificates(certificates as CFTypeRef, policy, &trust)
return trust!
}
}
| 38.794118 | 110 | 0.675891 |
edcef55021848eaed52c78a499631f1cde65d82d | 1,111 | import Foundation
import UIKit
import ConfettiKit
class CustomTabBarController: UITabBarController {
let size = CGFloat(54)
@IBOutlet var addEventButton: UIButton!
@IBAction func unwindToMain(segue:UIStoryboardSegue) { }
override func viewDidLoad() {
addEventButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(addEventButton)
view.addConstraints([
NSLayoutConstraint(item: addEventButton, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: addEventButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottomMargin, multiplier: 1, constant: 0),
NSLayoutConstraint(item: addEventButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size),
NSLayoutConstraint(item: addEventButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size),
])
}
}
| 42.730769 | 164 | 0.70207 |
b9123349da954bad490098f0536ec085bc71c023 | 7,329 | //
// main.swift
// PatternMatching
//
// Created by iMac on 2017/12/20.
// Copyright © 2017年 iMac. All rights reserved.
//
//1.
import Foundation
enum FormField {
case firstName(String)
case lastName(String)
case emailAddress(String)
case age(Int)
}
let minimumAge = 21
let submittedAge = FormField.age(22)
if case .age(let x) = submittedAge, x == minimumAge{
print("YES is 21 old")
}else{
print("Error")
}
//2.
enum CelestialBody {
case star
case planet(liquidWater: Bool)
case comet
}
let telescopeCensus = [
CelestialBody.star,
CelestialBody.planet(liquidWater: false),
CelestialBody.planet(liquidWater: true),
CelestialBody.planet(liquidWater: true),
CelestialBody.comet
]
for case .planet(let water) in telescopeCensus where water{
print("Found a potentially habitable planet!")
}
//3.
let queenAlbums = [
("A Night at the Opera", 1974),
("Sheer Heart Attack", 1974),
("Jazz", 1978),
("The Game", 1980)
]
for case (let album,1974) in queenAlbums{
print("Queen's album \(album) was released in 1974")
}
//4.
let coordinates = (lat: 192.89483, long: -68.887463)
switch coordinates {
case (let lat, _) where lat < 0:
print("In the Southern hemisphere!")
case (let lat, _) where lat == 0:
print("Its on the equator!")
case (let lat, _) where lat > 0:
print("In the Northern hemisphere!")
default:
break
}
//可选型的本质是一个枚举类型 .some() .none
let names: [String?] = ["Michelle", nil, "Brandon", "Christine", nil, "David"]
for case .some(let name) in names {
print(name) // 4 times
}
let population = 3
switch population {
case 1:
print("single")
case 2...3:
print("a few") // Printed!
case 4..<6:
print("several")
default:
print("many")
}
let coordinate = (x:1,y:0,z:0)
if(coordinate.y == 0 && coordinate.z == 0){
print("1:point in x-axis")
}
//pattern matching
//concise readable 简洁易读
if case (_,0,0) = coordinate{
print("2:point in x-axis")
}
//Basic pattern matching
// if guard
func process(point:(x:Int,y:Int,z:Int)) -> String {
if case (0,0,0) = point {
return "Origin"
}
return "Not origin"
}
let point = (0,0,0)
print(process(point: point))
func guardProcess(point:(x:Int,y:Int,z:Int)) -> String {
guard case (0,0,0) = point else{
return "Not origin"
}
return "Origin"
}
print(guardProcess(point: point))
//switch
//switch 可以允许多个实例匹配模式,且可以匹配范围(range)
func switchProcess(point:(x:Int,y:Int,z:Int)) -> String {
let closeRange = -2...2
let midRange = -5...5
switch point {
case (0,0,0):
return "At origin"
case (closeRange,closeRange,closeRange):
return "Very close to origin"
case (midRange,midRange,midRange):
return "Nearby origin"
default:
return "Not near origin"
}
}
//==========
//WiladCard pattern 通配符模式
if case (_,0,0) = coordinate{
print("x-axis")
}
//value-binding pattern 值绑定模式
if case (let x,0,0) = coordinate{
print("x-axis:\(x)")
}
//绑定多个值
if case let(x,y,0) = coordinate{
print("x:\(x),y:\(y)")
}
//identifier pattern 标识符匹配
let coordinate1 = (x:8,y:0,z:0)
let xValue:Int = 8
if case let(xValue,0,0) = coordinate1{
print(xValue)
}
enum Direction {
case north,south,east,west
}
let heading = Direction.south
if case .north = heading{
print("North")
}else if case .south = heading{
print("South")
}
enum Organism {
case plant
case animal(legs:Int)
}
let pet:Organism = .animal(legs: 4)
switch pet{
case .animal(let legs):
print("Potentially cuddly with \(legs) legs") // Printed: 4
default:
print("No chance for cuddles")
}
//is
let array: [Any] = [15, "George", 2.0]
for element in array {
switch element {
case is String:
print("Found a string") // 1 time
default:
print("Found something else") // 2 times
}
}
//as
for element in array {
switch element {
case let text as String:
print("Found a string: \(text)") // 1 time
default:
print("Found something else") // 2 times
}
}
enum LevelStatus {
case complete
case inProgress(percent: Double)
case notStarted
}
let levels: [LevelStatus] = [.complete, .inProgress(percent:
0.9), .notStarted]
for level in levels {
switch level {
case .inProgress(let percent) where percent > 0.8 :
print("Almost there!")
case .inProgress(let percent) where percent > 0.5 :
print("Halfway there!")
case .inProgress(let percent) where percent > 0.2 :
print("Made it through the beginning!")
default:
break
} }
if case .animal(let legs) = pet, case 2...4 = legs {
print("potentially cuddly") // Printed!
} else {
print("no chance for cuddles")
}
enum Number {
case integerValue(Int)
case doubleValue(Double)
case booleanValue(Bool)
}
let a = 5
let b = 6
let c: Number? = .integerValue(7)
let d: Number? = .integerValue(8)
if a != b {
if let c = c {
if let d = d {
if case .integerValue(let cValue) = c {
if case .integerValue(let dValue) = d {
if dValue > cValue {
print("a and b are different") // Printed!
print("d is greater than c") // Printed!
print("sum: \(a + b + cValue + dValue)") // 26
} }
} }
} }
if a != b,
let c = c,
let d = d,
case .integerValue(let cValue) = c,
case .integerValue(let dValue) = d,
dValue > cValue {
print("a and b are different") // Printed!
print("d is greater than c") // Printed!
print("sum: \(a + b + cValue + dValue)") // Printed: 26
}
//if a != b && c != nil && d != nil{
//
//}
var username: String?
var password: String?
switch (username, password) {
case let (username?, password?):
print("Success! User: \(username) Pass: \(password)")
case let (username?, nil):
print("Password is missing. User: \(username)")
case let (nil, password?):
print("Username is missing. Pass: \(password)")
case (nil, nil):
print("Both username and password are missing") // Printed!
}
struct Rectangle {
let width: Int
let height: Int
let color: String
}
let view = Rectangle(width: 15, height: 60, color: "Green")
switch view {
case _ where view.height < 50:
print("Shorter than 50 units")
case _ where view.width > 20:
print("Over 50 tall, & over 20 wide")
case _ where view.color == "Green":
print("Over 50 tall, at most 20 wide, & green") // Printed!
default:
print("This view can't be described by this example")
}
func fibonacci(position: Int) -> Int {
switch position {
// 1
case let n where n <= 1:
return 0 // 2
case 2:
return 1
// 3
case let n:
return fibonacci(position: n - 1) + fibonacci(position: n - 2)
}
}
let fib15 = fibonacci(position: 15) // 377
//从1到100,打印数量:•除了在三的倍数,打印“嘶嘶”而不是数量。
//以倍数为五,打印“嗡嗡”而不是数字。
//•对三和五的倍数,打印“FizzBuzz”而不是数量。
for i in 1...100 {
// 1
switch (i % 3, i % 5) {
// 2
case (0, 0):
print("FizzBuzz", terminator: " ")
case (0, _):
print("Fizz", terminator: " ")
case (_, 0):
print("Buzz", terminator: " ")
// 3
case (_, _):
print(i, terminator: " ")
}
}
print("")
| 20.587079 | 78 | 0.597762 |
cc1af265ed27757ba6e182eb500b530d73c418bc | 924 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "therealworldflutter_vapor",
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
// 🔵 Swift ORM (queries, models, relations, etc) built on SQLite 3.
.package(url: "https://github.com/vapor/fluent-postgresql.git", from: "1.0.0"),
// 👤 Authentication and Authorization layer for Fluent.
.package(url: "https://github.com/vapor/auth.git", from: "2.0.0"),
.package(url: "https://github.com/vapor-community/pagination.git", from: "1.0.9"),
],
targets: [
.target(name: "App", dependencies: ["Authentication", "FluentPostgreSQL", "Vapor", "Pagination"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"])
]
)
| 38.5 | 106 | 0.608225 |
ffc3ffed7b00d20767d6a3655f6e60c2f6db2da6 | 1,727 | //
// Storefront.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// 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.
//
public class Storefront {
public static func buildQuery(inContext: InContextDirective? = nil, subfields: (QueryRootQuery) -> Void) -> QueryRootQuery {
let root = QueryRootQuery()
root.directives = [inContext].compactMap({ $0 })
subfields(root)
return root
}
public static func buildMutation(inContext: InContextDirective? = nil, subfields: (MutationQuery) -> Void) -> MutationQuery {
let root = MutationQuery()
root.directives = [inContext].compactMap({ $0 })
subfields(root)
return root
}
}
| 37.543478 | 126 | 0.736537 |
e262204c1aa5f55f98ab4f893aa0528bef72c495 | 3,134 | //
// SettingsManager.swift
// LSFManager
//
// Created by Daniel Montano on 20.12.17.
// Copyright © 2017 danielmontano. All rights reserved.
//
import Foundation
class SettingsManager {
//////////////////////////////////////////////////////////////////////////////
///////////// Singleton Class Implementation /////////////
//////////////////////////////////////////////////////////////////////////////
static let sharedInstance = SettingsManager()
private init(){
loadFromUserDefaults()
}
//////////////////////////////////////////////////////////////////////////////
///////////// API Manager properties /////////////
//////////////////////////////////////////////////////////////////////////////
var address: String?
var port: Int?
var defaultUsername: String?
var defaultPass: String?
// Persistence
private let address_key: String = "addresskey"
private let port_key: String = "portkey"
private let defaultUsernameKey = "defaultusernamekey"
private let defaultPasswordKey = "defaultpasswordkey"
//////////////////////////////////////////////////////////////////////////////
///////////// SETTINGS MANAGER IMPLEMENTATION /////////////
//////////////////////////////////////////////////////////////////////////////
func clearUserSettings(){
UserDefaults.standard.removeObject(forKey: self.address_key)
UserDefaults.standard.removeObject(forKey: self.port_key)
}
func loadFromUserDefaults(){
self.address = getUserSettingObject(self.address_key) as? String
self.port = getUserSettingObject(self.port_key) as? Int
self.defaultUsername = getUserSettingObject(self.defaultUsernameKey) as? String
self.defaultPass = getUserSettingObject(self.defaultPasswordKey) as? String
}
func saveToUserDefaults() throws {
if let address = self.address, let port = self.port {
setUserSetting(key: self.address_key, value: address)
setUserSetting(key: self.port_key, value: port)
}else{
throw CustomErrors.serverSettingsNotSavedError
}
if let defaultUsername = self.defaultUsername, let defaultPass = self.defaultPass {
setUserSetting(key: self.defaultUsernameKey, value: defaultUsername)
setUserSetting(key: self.defaultPasswordKey, value: defaultPass)
}else{
throw CustomErrors.userSettingsNotSavedError
}
}
//////////////////////////////////////////////////////////////////////////////
///////////// SOME HELPER METHODS /////////////
//////////////////////////////////////////////////////////////////////////////
func setUserSetting(key:String, value:Any) {
UserDefaults.standard.set(value, forKey: key)
}
func getUserSettingObject(_ key:String) -> Any? {
return UserDefaults.standard.object(forKey: key)
}
}
| 36.44186 | 92 | 0.477983 |
26623e972375b680841de15f3e833d4aa839cb7f | 742 | //
// PersonBroadcastingView.swift
// wwdc20_proto2
//
// Created by Gabriel C Paula on 13/05/20.
// Copyright © 2020 Gabriel C Paula. All rights reserved.
//
import SwiftUI
public struct PersonBroadcastingView: View {
let name: String
public var body: some View {
Text(name)
.font(.largeTitle)
.background(
ZStack {
CircleAnimationView(duration: 1.5)
CircleAnimationView(duration: 2)
CircleAnimationView(duration: 3)
}
)
.transition(
AnyTransition.opacity
.animation(
Animation.easeInOut(duration: 1.0)))
}
}
| 23.935484 | 60 | 0.522911 |
0837476babdcce52184806fc14cd519f8e37dad8 | 2,266 | //
// UIView+frame.swift
// MZRefreshView
//
// Created by Michael_Zuo on 2018/3/18.
// Copyright © 2018年 Michael_Zuo. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
// top
var mz_top:CGFloat {
get {
return frame.minY
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.y = newValue
frame = tempFrame
}
}
// bottom
var mz_bottom:CGFloat {
get {
return frame.maxY
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.y = newValue
frame = tempFrame
}
}
// left
var mz_left:CGFloat {
get {
return frame.minX
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.x = newValue
frame = tempFrame
}
}
// right
var mz_right:CGFloat {
get {
return frame.maxX
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.x = newValue
frame = tempFrame
}
}
// CenterX
var mz_centerX:CGFloat {
get {
return frame.midX
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.x = newValue - frame.size.width/2
frame = tempFrame
}
}
// CenterY
var mz_centerY:CGFloat {
get {
return frame.minY
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.origin.y = newValue - frame.size.height/2
frame = tempFrame
}
}
// Width
var mz_width:CGFloat {
get {
return frame.size.width
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.size.width = newValue
frame = tempFrame
}
}
var mz_height:CGFloat {
get {
return frame.size.height
}
set(newValue) {
var tempFrame:CGRect = frame
tempFrame.size.height = newValue
frame = tempFrame
}
}
}
| 20.788991 | 63 | 0.482348 |
167fd1b654301444d188edba28040f74d3eb978c | 991 | //
// DownloadImage.swift
// TopsBatchInsert
//
// Created by Alexander Farber on 06.07.21.
//
import SwiftUI
struct DownloadImage: View {
@StateObject var loader: DownloadImageViewModel
init(url: String) {
_loader = StateObject(wrappedValue: DownloadImageViewModel(url: url))
}
var body: some View {
ZStack {
if loader.isLoading {
ProgressView()
} else if let image = loader.image {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
} else {
// TODO show placeholder image
}
}
}
}
struct TopImageView_Previews: PreviewProvider {
static var previews: some View {
DownloadImage(url: "https://slova.de/words/images/female_happy.png")
.frame(width: 60, height: 60)
.previewLayout(.sizeThatFits)
}
}
| 24.775 | 77 | 0.554995 |
dd39199f7426b9c700801564976c3d44c2696e43 | 363 | //
// Sized.swift
//
//
// Created by Ethan John on 12/20/19.
//
#if os(macOS)
import AppKit
#elseif os(iOS)
import UIKit
#endif
/// Conform to `Sized` by providing a `packingSize` property to an object.
public protocol Sized {
var packingSize: CGSize { get }
}
extension Sized {
internal var size: Size {
Size(packingSize)
}
}
| 15.125 | 74 | 0.630854 |
46b91a9e23c3936621268640b335ad84be4c31d8 | 8,830 | //
// Item.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 08/04/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import Foundation
import SwiftUI
public struct ItemResponse: Codable {
let total: Int
let results: [Item]
}
public struct NewItemResponse: Codable {
let total: Int
let results: [ItemWrapper]
public struct ItemWrapper: Codable {
public let id: Int
public let name: String
public var content: Item
public let variations: [Variant]?
}
}
public struct ActiveMonth: Codable, Equatable {
let activeTimes: [String]
}
public struct Item: Codable, Equatable, Identifiable, Hashable {
static public func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.id == rhs.id && lhs.appCategory == rhs.appCategory
}
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(category)
}
public var id: String { name }
public var internalID: Int?
public var critterId: Int?
public var localizedName: String {
if let id = internalID {
return LocalizedItemService.shared.localizedNameFor(category: appCategory, itemId: id) ?? name
}
return name
}
public let name: String
public let image: String?
public let filename: String?
public let house: String?
public let itemImage: String?
public var preferedVariantImage: String?
public var finalImage: String? {
if let preferedVariantImage = preferedVariantImage {
return preferedVariantImage
} else if let image = image, image.hasPrefix("https://acnhcdn") || image.hasPrefix("https://i.imgur") {
return image
} else if let filename = filename {
return filename
} else if let itemImage = itemImage {
return itemImage
}
return nil
}
public let iconImage: String?
public let furnitureImage: String?
public let obtainedFrom: String?
public let obtainedFromNew: [String]?
public let sourceNotes: String?
public let dIY: Bool?
public let customize: Bool?
public let movementSpeed: String?
public var variations: [Variant]?
public let category: String
public var appCategory: Category {
Category(itemCategory: category)
}
public var itemCategory: String?
public let materials: [Material]?
public let buy: Int?
public let sell: Int?
public let shadow: String?
public let activeMonths: [String: ActiveMonth]?
public let set: String?
public let tag: String?
public let styles: [String]?
public let themes: [String]?
public let colors: [String]?
private static var METAS_CACHE: [String: [String]] = [:]
public var metas: [String] {
if let metas = Self.METAS_CACHE[id] {
return metas
}
var metas: [String] = []
if let tag = tag {
metas.append(tag)
}
if let set = set {
metas.append(set)
}
if let styles = styles {
metas.append(contentsOf: styles)
}
if let themes = themes {
metas.append(contentsOf: themes)
}
if let colors = colors {
metas.append(contentsOf: colors)
}
metas = Array(Set(metas.map{ $0.capitalized })).filter({ $0.lowercased() != "none"}).sorted()
Self.METAS_CACHE[id] = metas
return metas
}
}
// Formatter used for the start / end times of critters
fileprivate let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = is24Hour() ? "HH" : "ha"
return formatter
}()
/// Determine if the device is set to 24 or 12 hour time
fileprivate func is24Hour() -> Bool {
let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
return dateFormat.firstIndex(of: "a") == nil
}
// MARK: - Calendar
public extension Item {
static let monthFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MM"
return formatter
}()
var activeMonthsCalendar: [Int]? {
let isSouth = AppUserDefaults.shared.hemisphere == .south
if var keys = activeMonths?.keys.compactMap({ Int($0) }) {
if isSouth {
keys = keys.map{ ($0 + 6) % 12 }
}
return keys
}
return nil
}
func isActiveThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth - 1) == true
}
func isActiveAtThisHour(currentDate: Date) -> Bool {
guard let hours = activeHours() else { return false }
if hours.start == 0 && hours.end == 0 { return true } // All day
let thisHour = Calendar.current.dateComponents([.hour], from: currentDate).hour ?? 0
if hours.start < hours.end { // Same day
return thisHour >= hours.start && thisHour < hours.end
} else { // Overnight
return thisHour >= hours.start || thisHour < hours.end
}
}
func isNewThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth - 2) == false
}
func leavingThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth) == false
}
func formattedTimes() -> String? {
guard let hours = activeHours() else { return nil }
if hours.start == 0 && hours.end == 0 {
return NSLocalizedString("All day", comment: "")
}
let startDate = DateComponents(calendar: .current, hour: hours.start).date!
let endDate = DateComponents(calendar: .current, hour: hours.end).date!
let startHour = formatter.string(from: startDate)
let endHour = formatter.string(from: endDate)
return "\(startHour) - \(endHour)\(is24Hour() ? "h" : "")"
}
func activeHours() -> (start: Int, end: Int)? {
guard let activeTimes = activeMonths?.first?.value.activeTimes,
let startTime = activeTimes.first,
let endTime = activeTimes.last else {
return nil
}
if Int(startTime) == 0 && Int(endTime) == 0 {
return (start: 0, end: 0)
}
var startHourInt = 0
var endHourInt = 0
var preIntStartTime = startTime
preIntStartTime.removeLast(2)
if let hour = Int(preIntStartTime) {
startHourInt = hour
if startTime.suffix(2) == "pm" {
startHourInt += 12
}
}
var preIntEndTime = endTime
preIntEndTime.removeLast(2)
if let hour = Int(preIntEndTime) {
endHourInt = hour
if endTime.suffix(2) == "pm" {
endHourInt += 12
}
}
return (start: startHourInt, end: endHourInt)
}
}
// MARK: - Critters
public extension Item {
var isCritter: Bool {
appCategory == .fish || appCategory == .bugs || appCategory == .seaCreatures
}
}
// MARK: - Array
public extension Sequence {
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
return sorted { a, b in
return a[keyPath: keyPath] > b[keyPath: keyPath]
}
}
}
public let static_item = Item(name: "Acoustic guitar",
image: nil,
filename: "https://acnhcdn.com/latest/FtrIcon/FtrAcorsticguitar_Remake_0_0.png",
house: nil,
itemImage: nil,
iconImage: nil,
furnitureImage: nil,
obtainedFrom: "Crafting",
obtainedFromNew: ["Crafting"],
sourceNotes: "From somewhere",
dIY: true,
customize: true,
movementSpeed: nil,
variations: nil,
category: "Housewares",
materials: nil,
buy: 200,
sell: 300,
shadow: nil,
activeMonths: nil,
set: nil,
tag: "Instrument",
styles: nil,
themes: nil,
colors: nil)
| 30.766551 | 112 | 0.564439 |
48ecaa7ce8a1197ea0484e9ea2f8319817cb7078 | 1,629 | //
// AppDelegate.swift
// Example
//
// Created by Harvey on 2021/4/22.
//
import UIKit
import DarkAdapter
import RxSwift
//import Combine
@available(iOS 13.0, *)
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var disposeBag: DisposeBag = .init()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
DAAdapter.register()
DarkAdapter.darkImageSuffix = "_dark"
return true
}
}
@available(iOS 13.0, *)
extension AppDelegate {
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 33.9375 | 179 | 0.72744 |
d99f07f8c1e54a99e12373fc7ceff6b397a8be78 | 600 | //
// ViewController.swift
// HKAnimatedTabBar
//
// Created by Kyryl Horbushko on 15.11.2019.
// Copyright © 2019 - present. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let tabBarController = self.tabBarController as? AnimatedTabBarController {
tabBarController.tabBar.replaceView.gradientColors = [
UIColor.white,
UIColor.white,
UIColor.gray
]
let items = ExpandableTabItemModel.prepareItems()
tabBarController.configureFor(items)
}
}
}
| 20.689655 | 82 | 0.69 |
034c2fc0964b024d2287018616cdd3b9b9a2fc1e | 7,674 | //
// 2020Day17.swift
// aoc
//
// Created by Paul U on 12/17/20.
// Copyright © 2020 Mojio. All rights reserved.
//
import Foundation
struct Y2020Day17 {
enum Tile: Character {
case active = "#"
case inactive = "."
}
static func Part1(_ data: [String]) -> Int {
// parse into tile
let data = data
.map { $0.compactMap(Tile.init) }
.filter { !$0.isEmpty }
// hashmap
var map = [Point3D: Tile]()
for (y, row) in data.enumerated() {
for (x, tile) in row.enumerated() {
let point = Point3D(x: x, y: y, z: 0)
map[point] = tile
}
}
// loop
for _ in 0 ..< 6 {
// expand map
let cache = expand3D(map)
map = cache.map { data -> (Point3D, Tile) in
// adjacent
let active = data.key
.adjacent
.map { cache[$0] }
.filter { $0 == .active }
.count
// rules
if data.value == .active, 2...3 ~= active {
return (data.key, .active)
} else if data.value == .inactive, 3 == active {
return (data.key, .active)
}
return (data.key, .inactive)
}
// update map
.reduce(into: [Point3D: Tile]()) {
$0[$1.0] = $1.1
}
}
return map
.filter { $0.value == .active }
.count
}
static func Part2(_ data: [String]) -> Int {
// parse into tile
let data = data
.map { $0.compactMap(Tile.init) }
.filter { !$0.isEmpty }
// hashmap
var map = [Point4D: Tile]()
for (y, row) in data.enumerated() {
for (x, tile) in row.enumerated() {
let point = Point4D(x: x, y: y, z: 0, w: 0)
map[point] = tile
}
}
// loop
for _ in 0 ..< 6 {
// expand map
let cache = expand4D(map)
map = cache.map { data -> (Point4D, Tile) in
// adjacent
let active = data.key
.adjacent
.map { cache[$0] }
.filter { $0 == .active }
.count
// rules
if data.value == .active, 2...3 ~= active {
return (data.key, .active)
} else if data.value == .inactive, 3 == active {
return (data.key, .active)
}
return (data.key, .inactive)
}
// update map
.reduce(into: [Point4D: Tile]()) {
$0[$1.0] = $1.1
}
}
return map
.filter { $0.value == .active }
.count
}
private static func expand3D(_ map: [Point3D: Tile]) -> [Point3D: Tile] {
let x = map.map { $0.key.x }
let y = map.map { $0.key.y }
let z = map.map { $0.key.z }
let xmin = x.min()! - 1
let xmax = x.max()! + 1
let ymin = y.min()! - 1
let ymax = y.max()! + 1
let zmin = z.min()! - 1
let zmax = z.max()! + 1
let xr = (xmin ... xmax).map { $0 }
let yr = (ymin ... ymax).map { $0 }
let zr = (zmin ... zmax).map { $0 }
var points = generate3D(xr, yr, [zmax])
points.formUnion(generate3D(xr, yr, [zmin]))
points.formUnion(generate3D(xr, [ymax], zr))
points.formUnion(generate3D(xr, [ymin], zr))
points.formUnion(generate3D([xmax], yr, zr))
points.formUnion(generate3D([xmin], yr, zr))
var map = map
for point in points {
map[point] = .inactive
}
return map
}
private static func expand4D(_ map: [Point4D: Tile]) -> [Point4D: Tile] {
let x = map.map { $0.key.x }
let y = map.map { $0.key.y }
let z = map.map { $0.key.z }
let w = map.map { $0.key.w }
let xmin = x.min()! - 1
let xmax = x.max()! + 1
let ymin = y.min()! - 1
let ymax = y.max()! + 1
let zmin = z.min()! - 1
let zmax = z.max()! + 1
let wmin = w.min()! - 1
let wmax = w.max()! + 1
let xr = (xmin ... xmax).map { $0 }
let yr = (ymin ... ymax).map { $0 }
let zr = (zmin ... zmax).map { $0 }
let wr = (wmin ... wmax).map { $0 }
var points = generate4D(xr, yr, [zmax], wr)
points.formUnion(generate4D(xr, yr, [zmin], wr))
points.formUnion(generate4D(xr, [ymax], zr, wr))
points.formUnion(generate4D(xr, [ymin], zr, wr))
points.formUnion(generate4D([xmax], yr, zr, wr))
points.formUnion(generate4D([xmin], yr, zr, wr))
points.formUnion(generate4D(xr, yr, zr, [wmax]))
points.formUnion(generate4D(xr, yr, zr, [wmin]))
var map = map
for point in points {
map[point] = .inactive
}
return map
}
private static func generate3D(_ xr: [Int], _ yr: [Int], _ zr: [Int]) -> Set<Point3D> {
var points = Set<Point3D>()
for x in xr {
for y in yr {
for z in zr {
points.insert(Point3D(x: x, y: y, z: z))
}
}
}
return points
}
private static func generate4D(_ xr: [Int], _ yr: [Int], _ zr: [Int], _ wr: [Int]) -> Set<Point4D> {
var points = Set<Point4D>()
for x in xr {
for y in yr {
for z in zr {
for w in wr {
points.insert(Point4D(x: x, y: y, z: z, w: w))
}
}
}
}
return points
}
}
private extension Point3D {
var adjacent: [Point3D] {
let directions = Direction3D.allCases
var points = directions.map { self.offset(by: 1, toward: $0) }
let tb: [Direction3D] = [.top, .bottom]
let fb: [Direction3D] = [.front, .back]
let lr: [Direction3D] = [.left, .right]
let fblr: [Direction3D] = fb + lr
typealias Tuple3D = (Direction3D, Direction3D)
let tuple1 = tb.flatMap { tb -> [Tuple3D] in
fblr.map { (tb, $0) }
}
let tuple2 = fb.flatMap { fb -> [Tuple3D] in
lr.map { (fb, $0) }
}
points += [tuple1, tuple2].flatMap { tuples -> [Point3D] in
tuples.map {
self.offset(by: 1, toward: $0.0)
.offset(by: 1, toward: $0.1)
}
}
typealias Triple3D = (Direction3D, Direction3D, Direction3D)
let triple = tb.flatMap { tb -> [Triple3D] in
tuple2.map { (tb, $0.0, $0.1) }
}
points += triple.map {
self.offset(by: 1, toward: $0.0)
.offset(by: 1, toward: $0.1)
.offset(by: 1, toward: $0.2)
}
return points
}
}
private extension Point4D {
var adjacent: Set<Point4D> {
var points = Set<Point4D>()
for x in (self.x - 1 ... self.x + 1) {
for y in (self.y - 1 ... self.y + 1) {
for z in (self.z - 1 ... self.z + 1) {
for w in (self.w - 1 ... self.w + 1) {
points.insert(Point4D(x: x, y: y, z: z, w: w))
}
}
}
}
return points.removing(self)
}
}
| 30.943548 | 104 | 0.427287 |
6ad89e5433cd01e58201b4a45233a53f8ac829a5 | 427 | //
// Options.swift
// TransitionableTab-iOS
//
// Created by gwangbeom on 2017. 11. 12..
// Copyright © 2017년 InteractiveStudio. All rights reserved.
//
import UIKit
public enum Direction {
case left
case right
init(selectedIndex: Int, shouldSelectIndex: Int) {
self = selectedIndex > shouldSelectIndex ? .left : .right
}
}
public enum TransitionViewType: Int {
case to
case from
}
| 17.791667 | 65 | 0.662763 |
67d784fa17c860e51910ffcb76faf313205a3419 | 192 | //
// BaseApiCall.swift
// Omar Hassan
//
// Created by omarHassan on 8/6/19.
// Copyright © 2019 omar hammad. All rights reserved.
//
import Foundation
class EntityApiCallFactory {
}
| 12.8 | 54 | 0.6875 |
2177d3da04038f14a9747da7e9caee50e6104443 | 3,636 | import Foundation
import IndoorLocation
import SocketIO
class ILSocketLocationProvider : ILIndoorLocationProvider {
let url:URL!
var isConnected = false
var manager:SocketManager!
var socket:SocketIOClient!
init(url:URL!) {
self.url = url
super.init()
let address = self.getIPAddress()
if address != nil {
manager = SocketManager(socketURL: self.url, config: [.connectParams(["userId" : address!])])
socket = manager.defaultSocket
socket.on(clientEvent: .connect) {data, ack in
print("socket connected")
self.isConnected = true
self.dispatchDidStart()
}
socket.on("indoorLocationChange") {data, ack in
if let responseArray = data as? [Dictionary<String, Any>] {
let responseDictionary = responseArray[0]
if let indoorLocationDictionary = responseDictionary["indoorLocation"] as? Dictionary<String,NSNumber> {
let latitude = indoorLocationDictionary["latitude"] as! Double
let longitude = indoorLocationDictionary["longitude"] as! Double
let floor = indoorLocationDictionary["floor"] as NSNumber?
let indoorLocation = ILIndoorLocation.init(provider: self, latitude: latitude, longitude: longitude, floor: floor)
if let accuracy = indoorLocationDictionary["accuracy"] as? Double {
indoorLocation!.accuracy = accuracy
}
self.dispatchDidUpdate(indoorLocation)
}
}
}
socket.on(clientEvent: .error) {data, ack in
print(data[0])
let message = data[0] as! String
self.dispatchDidFailWithError(NSError(domain:message, code:502, userInfo:nil))
}
}
else {
self.dispatchDidFailWithError(NSError(domain:"No IP", code: 502, userInfo:nil))
}
}
override func start() {
socket.connect()
}
override func stop() {
socket.disconnect()
}
override func isStarted() -> Bool {
if socket.status == SocketIOStatus.connected {
return true
}
return false
}
override func supportsFloor() -> Bool {
return true
}
func getIPAddress() -> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next }
let interface = ptr?.pointee
let addrFamily = interface?.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
if let name: String = String(cString: (interface?.ifa_name)!), name == "en0" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface?.ifa_addr, socklen_t((interface?.ifa_addr.pointee.sa_len)!), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
}
| 35.300971 | 179 | 0.527228 |
e6c5421ef95d9cef217b3a74a2c062c2637990e2 | 617 | //
// UIViewController.swift
// MoviesList
//
// Created by mobile dev3 on 8/30/17.
// Copyright © 2017 mobile dev3. All rights reserved.
//
import UIKit
extension UIViewController {
func setNaviationBar(headline: String){
self.navigationItem.title = headline
// self.navigationController?.navigationBar.barTintColor = UIColor(hex: <#T##String#>)
self.navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont(name: "Futura-Medium", size: 22)!,
NSForegroundColorAttributeName: UIColor.white
]
}
}
| 23.730769 | 93 | 0.661264 |
039b5c61858c565e5c1ffaf6a76386b1646faecf | 502 | //
// ViewController.swift
// SphereGame
//
// Created by lisilong on 2018/4/3.
// Copyright © 2018年 lisilong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.307692 | 80 | 0.669323 |
384d2e777e86534e9dfa580ea7628db96be4ffc2 | 998 | //
// WPMoveButton_SwiftTests.swift
// WPMoveButton_SwiftTests
//
// Created by wp on 2017/10/20.
// Copyright © 2017年 wp. All rights reserved.
//
import XCTest
@testable import WPMoveButton_Swift
class WPMoveButton_SwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.972973 | 111 | 0.644289 |
1a92ae6a26137ee905f38ad8091430508c132ddd | 2,304 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
case c,
func a<Int>
let start = [ [Void{
func b
case c,
let start = [ [Void{
((([Void{
var b = a
func a
struct d
{
func b
func e( ) {
class c : I
class
func a<T where g: a( ) {
protocol c {
class B {
var f = a( ) {
struct d
((i: C {
let a {
func a
var f = b<T {
case c,
func e( ) {
typealias B : d<b<T {
func a
if true {
enum S<l : a {
class
class B : C {
class c {
struct A {
func a( ([Void{
if true {
case c,
case c,
func a<T {
class
case c,
if true {
{
class
class
class
case c,
case c,
class c {
struct A {
func e( ) {
var f = a<b
struct A {
class
var f = b
case c,
let a {
protocol c {
func a<T where g: I
class
func b(((([Void{
if true {
typealias B {
}
func a<T {
{
enum S<T where g: B.E
""
struct d<b
protocol B : d<T {
class A {
(i: B.f
class
struct A {
protocol c {
case c,
{
"
enum S<T where g: d
protocol c {
([Void{
enum A {
var b = a
class
class
case c,
"
enum S<T where g: I
}
{
var b = a<T {
protocol c : T.f
enum A {
}
if true {
case c,
protocol B {
struct d
protocol c : a<T {
class
func e( ((n: T.E
([Void{
}
{
case c,
var b = b([Void{
protocol c : C {
}
{
enum S<T {
class c : a( ([Void{
typealias B : a {
if true {
enum S<l : I
case c,
enum A {
class A {
class B : T.E
func a
((i: T.E
{
func b((((((([Void{
enum A {
func b
}
case c,
if true {
if true {
class c {
var f = a<T where g: d<l : I
func b
func b([Void{
enum A {
if true {
protocol B : a {
func a<l : C {
protocol c {
{
struct d<Int>
typealias B {
class A {
class c : d
(n: d<Int>
class
enum A {
enum A {
protocol c : d<b(n: a {
let start = [ [Void{
class B {
protocol B {
{
class
([Void{
case c,
func a<b<T {
"
class c : a
func b
protocol c {
class
func a
}
(i: d<b(n: I
let a {
var f = a
class
}
class
case c,
class A {
enum A {
class
protocol c {
{
case c,
var b = b<T {
class
class c : a {
func e( ) {
{
class A {
protocol c {
var b = [ [Void{
protocol c : d
let a {
protocol B : d<T {
var f = a<T {
}
if true {
let start = [ [Void{
func e( ) {
struct A {
{
case c,
([Void{
var f = a<T {
if true {
let a {
func a<l : T.E
(i: T.f
func b
enum S<b
"
"
func b
{
protocol c : T.f
class
func a
case c,
protocol c {
struct A {
protocol c {
func a(
| 10.472727 | 87 | 0.59158 |
0a9ae2f8c9c0dc55ab541b02005a716f14aa844e | 144 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
[
testCase(EtvnetApiTests.allTests),
]
}
#endif
| 14.4 | 45 | 0.701389 |
d9e9813453aa331a82e8405b354457e40d90a110 | 2,304 | import Vapor
import XCTest
@testable import App
final class TwilioRepositoryTests: XCTestCase {
private var app: Application!
private var client: MockClient!
private var repository: TwilioRepository!
override func setUp() {
app = Application(.testing)
client = MockClient(EmbeddedEventLoop())
app.clients.use { _ in self.client }
repository = TwilioAPIRepository(client: app.client, twilioConfig: TwilioConfig(accountSID: "abcdefghijkl", authToken: "mnopqrstuvw", phoneNumber: "+123456789"))
}
override func tearDown() {
app.shutdown()
}
func testLatestMessage() {
let expectation = XCTestExpectation(description: "latest message")
var message: Message?
repository.latestMessage().whenSuccess {
message = $0
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
XCTAssertEqual(message?.body, "Testing body")
}
func testAuthorization() {
let expectation = XCTestExpectation(description: "authorization")
repository.latestMessage().whenSuccess { _ in
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
let headers = client.sentRequest?.headers
let credentials = "Basic YWJjZGVmZ2hpamtsOm1ub3BxcnN0dXZ3"
XCTAssertEqual(headers?.first(name: .authorization), credentials)
}
}
private class MockClient: Client {
let eventLoop: EventLoop
init(_ eventLoop: EventLoop) {
self.eventLoop = eventLoop
}
func delegating(to eventLoop: EventLoop) -> Client {
return MockClient(eventLoop)
}
var sentRequest: ClientRequest?
func send(_ request: ClientRequest) -> EventLoopFuture<ClientResponse> {
sentRequest = request
let data = """
{
"messages": [
{
"date_sent": "Fri, 13 Aug 2010 01:16:22 +0000",
"body": "Testing body"
}
]
}
"""
let buffer = ByteBuffer(data: data.data(using: .utf8)!)
let response = ClientResponse(status: .ok, headers: [:], body: buffer)
return eventLoop.makeSucceededFuture(response)
}
}
| 28.444444 | 169 | 0.603733 |
28e176abe1ac55fe19e7dc77b2582906eaa55f60 | 519 | //
// TimeSheetView.swift
// MMFinancialSchool
//
// Created by Alfred on 2017/8/15.
// Copyright © 2017年 linweibiao. All rights reserved.
//
import UIKit
class TimeSheetView: UIView {
@IBOutlet weak var timeSheetImage: UIImageView!
@IBOutlet weak var timeSheetLabel: UILabel!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 20.76 | 78 | 0.680154 |
c1e8c09bc17f45fb8954aa1c05c3cc62c2c32fc5 | 888 | //
// ExtensionTransactionsRequest.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/4/21.
//
import Foundation
///Get extension transactions request, see https://dev.twitch.tv/docs/api/reference/#get-extension-transactions for details
public struct ExtensionTransactionsRequest: JSONConstructableRequest {
public let url: URL?
public init(
extensionID: String,
ids: [String]? = nil,
after: String? = nil,
first: String? = nil
) {
var queryItems = [
"extension_id": extensionID,
"after": after,
"first": first
].buildQueryItems()
if let userIds = ids {
queryItems.append(contentsOf: userIds.constructQueryItems(withKey: "id"))
}
self.url = TwitchEndpoints.extensionTransactions.construct()?.appending(queryItems: queryItems)
}
}
| 26.909091 | 123 | 0.636261 |
e9e8b5dca6aa807dd4e9c1b933a50827815c417f | 160 | import Entity
public enum MyPageUseCaseAction {
case updateUser(User?)
case logout
}
public protocol MyPageUseCase: Refreshable {
func logout()
}
| 14.545455 | 44 | 0.73125 |
efe41d9f15ca14c6ca7e5c3583939cc2b1ca153e | 1,161 | // https://github.com/Quick/Quick
import Quick
import Nimble
import MDGroupAvatarView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 22.764706 | 60 | 0.361757 |
08a18d94c8fb9b5a0edb946356601c172be354d4 | 6,587 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
protocol WelcomeViewControllerDelegate: class {
func didPressCreateWallet(in viewController: WelcomeViewController)
func didPressImportWallet(in viewController: WelcomeViewController)
}
final class WelcomeViewController: UIViewController {
var viewModel = WelcomeViewModel()
weak var delegate: WelcomeViewControllerDelegate?
lazy var collectionViewController: OnboardingCollectionViewController = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.scrollDirection = .horizontal
let collectionViewController = OnboardingCollectionViewController(collectionViewLayout: layout)
collectionViewController.pages = pages
collectionViewController.pageControl = pageControl
collectionViewController.collectionView?.isPagingEnabled = true
collectionViewController.collectionView?.showsHorizontalScrollIndicator = false
collectionViewController.collectionView?.backgroundColor = viewModel.backgroundColor
return collectionViewController
}()
let pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.translatesAutoresizingMaskIntoConstraints = false
return pageControl
}()
let createWalletButton: UIButton = {
let button = Button(size: .large, style: .solid)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("welcome.createWallet.button.title", value: "CREATE WALLET", comment: ""), for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
button.backgroundColor = Colors.darkBlue
return button
}()
let importWalletButton: UIButton = {
let importWalletButton = Button(size: .large, style: .border)
importWalletButton.translatesAutoresizingMaskIntoConstraints = false
importWalletButton.setTitle(NSLocalizedString("welcome.importWallet.button.title", value: "IMPORT WALLET", comment: ""), for: .normal)
importWalletButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
importWalletButton.accessibilityIdentifier = "import-wallet"
return importWalletButton
}()
let pages: [OnboardingPageViewModel] = [
OnboardingPageViewModel(
title: NSLocalizedString("welcome.privateAndSecure.label.title", value: "Private & Secure", comment: ""),
subtitle: NSLocalizedString("welcome.privateAndSecure.label.description", value: "Private keys never leave your device.", comment: ""),
image: R.image.onboarding_lock()!
),
OnboardingPageViewModel(
title: NSLocalizedString("welcome.erc20.label.title", value: "ERC20 Compatible", comment: ""),
subtitle: NSLocalizedString("welcome.erc20.label.description", value: "Support for ERC20 tokens by default. ", comment: ""),
image: R.image.onboarding_erc20()!
),
OnboardingPageViewModel(
title: NSLocalizedString("welcome.fullyTransparent.label.title", value: "Fully transparent", comment: ""),
subtitle: NSLocalizedString("welcome.fullyTransparent.label.description", value: "Code is open sourced (GPL-3.0 license) and fully audited.", comment: ""),
image: R.image.onboarding_open_source()!
),
OnboardingPageViewModel(
title: NSLocalizedString("welcome.ultraReliable.label.title", value: "Ultra Reliable", comment: ""),
subtitle: NSLocalizedString("welcome.ultraReliable.label.description", value: "The fastest Ethereum wallet experience on mobile", comment: ""),
image: R.image.onboarding_rocket()!
),
]
override func viewDidLoad() {
super.viewDidLoad()
viewModel.numberOfPages = pages.count
view.addSubview(collectionViewController.view)
let stackView = UIStackView(arrangedSubviews: [
pageControl,
createWalletButton,
importWalletButton,
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 15
view.addSubview(stackView)
collectionViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
collectionViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
collectionViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stackView.topAnchor.constraint(equalTo: collectionViewController.view.centerYAnchor, constant: 120),
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.widthAnchor.constraint(equalToConstant: 300),
pageControl.heightAnchor.constraint(equalToConstant: 20),
pageControl.centerXAnchor.constraint(equalTo: stackView.centerXAnchor),
createWalletButton.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
createWalletButton.trailingAnchor.constraint(equalTo: stackView.trailingAnchor),
importWalletButton.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
importWalletButton.trailingAnchor.constraint(equalTo: stackView.trailingAnchor),
])
createWalletButton.addTarget(self, action: #selector(start), for: .touchUpInside)
importWalletButton.addTarget(self, action: #selector(importFlow), for: .touchUpInside)
configure(viewModel: viewModel)
}
func configure(viewModel: WelcomeViewModel) {
title = viewModel.title
view.backgroundColor = viewModel.backgroundColor
pageControl.currentPageIndicatorTintColor = viewModel.currentPageIndicatorTintColor
pageControl.pageIndicatorTintColor = viewModel.pageIndicatorTintColor
pageControl.numberOfPages = viewModel.numberOfPages
pageControl.currentPage = viewModel.currentPage
}
@IBAction func start() {
delegate?.didPressCreateWallet(in: self)
}
@IBAction func importFlow() {
delegate?.didPressImportWallet(in: self)
}
}
| 49.156716 | 167 | 0.716411 |
eda9cf7880441091db4523099a25a354ce20db3e | 591 | //
// Created by Jordi Serra i Font on 18/3/18.
// Copyright © 2018 Code Crafters. All rights reserved.
//
import UIKit
extension UITextField {
static func autolayoutTextFieldWith(textStyle style: UIFont.TextStyle, placeholderText: String) -> UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.font = UIFont.preferredFont(forTextStyle: style)
textField.setContentHuggingPriority(.required, for: .vertical)
textField.placeholder = placeholderText
return textField
}
}
| 31.105263 | 116 | 0.724196 |
9c7ded6f7f8d6a8916e16664b8fee58e5d902008 | 1,153 | //
// ImageFile.swift
// SlidesMagic
//
// Created by ATM on 2017/11/6.
// Copyright © 2017年 QYCloud. All rights reserved.
//
import Foundation
import Cocoa
class ImageFile {
private(set) var thumbnail: NSImage?
private(set) var fileName: String
init(url: URL) {
fileName = url.lastPathComponent
let imageSource = CGImageSourceCreateWithURL(url.absoluteURL as CFURL, nil)
if let imageSource = imageSource {
guard CGImageSourceGetType(imageSource) != nil else {return}
thumbnail = getThumbnailImage(imageSource: imageSource)
}
}
private func getThumbnailImage(imageSource: CGImageSource) -> NSImage? {
let thumbnailOptions = [String(kCGImageSourceCreateThumbnailFromImageIfAbsent): true,
String(kCGImageSourceThumbnailMaxPixelSize): 160] as [String : Any]
guard let thumbnailRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, thumbnailOptions as CFDictionary) else {
return nil
}
return NSImage(cgImage: thumbnailRef, size: NSSize.zero)
}
}
| 26.204545 | 125 | 0.652212 |
2184255544c6594ee755f26eb030a73a1fada7c5 | 626 | //
// Product.swift
//
//
// Created by Oscar Byström Ericsson on 2021-04-14.
//
enum Product: String, CaseIterable, Argument {
static let `default`: Product = .name
case raw
case name
case signature
case getter
var description: String {
switch self {
case .raw: return "Outputs a list of device data."
case .name: return "Outputs a list of device names."
case .signature: return "Outputs a list of device signatures."
case .getter: return "Outputs a list of static device properties (used by \(supermoduleName))."
}
}
}
| 25.04 | 106 | 0.608626 |
142a62ba0bdd8ee599547ad94db03e8db7e53567 | 303 | //
// FirstViewController.swift
// TestSidebar
//
// Created by Viet on 29/9/18.
// Copyright © 2018 Viet. All rights reserved.
//
import Cocoa
class FirstViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
| 15.947368 | 47 | 0.640264 |
0a20ee3165d0b8cd982bb4c87cb9c878b7de0d8a | 118 | import XCTest
import SideMenuTests
var tests = [XCTestCaseEntry]()
tests += SideMenuTests.allTests()
XCTMain(tests)
| 14.75 | 33 | 0.779661 |
f9317507f45591a49974385c1a8c5c43423ad319 | 2,082 | //
// AppDelegate.swift
//
//
// Western
//
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 44.297872 | 285 | 0.743036 |
3a947b6dbd232f767dd862ea32f3854229212abe | 5,001 | //
// CategoryCell.swift
// CollectionView-Programmatic
//
// Created by chris on 8/5/18.
// Copyright © 2018 kuronuma studios. All rights reserved.
//
import UIKit
class CategoryVerticalColumnCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
let cellId = "CategoryHorizenTalRowCell"
static let cellH = 70
static let cellW = 70
var datas: [CategoryVerticalColumnModel]?
static func giveMeTestDatas()->[CategoryVerticalColumnModel]{
let datas: [CategoryVerticalColumnModel] = [CategoryVerticalColumnModel(titleText: "qwe"),CategoryVerticalColumnModel(titleText: "tt"),CategoryVerticalColumnModel(titleText: "ttt"),CategoryVerticalColumnModel(titleText: "ttt"),CategoryVerticalColumnModel(titleText: "ttt"),CategoryVerticalColumnModel(titleText: "ttt"),CategoryVerticalColumnModel(titleText: "ooooo")]
return datas
}
override init(frame: CGRect) {
super.init(frame: frame)
datas = CategoryVerticalColumnCell.giveMeTestDatas()
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let appsCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.clear
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
func setupViews() {
addSubview(appsCollectionView)
appsCollectionView.dataSource = self
appsCollectionView.delegate = self
appsCollectionView.hideIndicator(witchIndicator: .both)
appsCollectionView.register(AppCell.self, forCellWithReuseIdentifier: cellId)
appsCollectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
appsCollectionView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8 ).isActive = true
appsCollectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
appsCollectionView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8).isActive = true
appsCollectionView.preprocessWithYYxCell()
}
func reloadDataWhenCellPress() {
func cleanAllBackgroudColor(){
}
cleanAllBackgroudColor()
appsCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datas.unwrappedValue.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.giveMeCategoryHorizenTalRowCell(indexPatht: indexPath)
cell.titleLabel.text = datas.unwrappedValue[indexPath.row].titleText
cell.backgroundColor = .orange
//
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//yyx
return CGSize(width: CategoryVerticalColumnCell.cellW, height: CategoryVerticalColumnCell.cellH)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CategoryHorizenTalRowCell
cell.backgroundColor = .green
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CategoryHorizenTalRowCell
cell.backgroundColor = .orange
}
}
class AppCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "frozen")
iv.contentMode = .scaleAspectFit
iv.layer.cornerRadius = 16
iv.layer.masksToBounds = true
return iv
}()
//Create a label for title, name it nameLabel
//create category label, name it categoryLabel
func setupViews() {
addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width)
}
}
| 35.721429 | 376 | 0.689262 |
9bceabfe6a495c6c5eb455bf018bb1059dc950b2 | 7,203 | //
// ViewController.swift
// ThirdParty
//
// Created by Guillaume Vachon on 2018-08-14.
// Copyright © 2018 Waltz. All rights reserved.
//
import AVFoundation
import JWTDecode
import WaltzAccess
class ViewController: UIViewController, WltzSDKMgrDelegate {
@IBOutlet weak var licenseTF: UITextField!
@IBOutlet weak var appUidTF: UITextField!
@IBOutlet weak var responseTV: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
/*
the third party app is expected to request camera permissions on behalf of the SDK.
Could be done in the SDK too. Following in the foot steps of on this one.
*/
requestCameraPermission()
PermissionsChecker.sharedInstance.requestPermissionForNotifications()
PermissionsChecker.sharedInstance.requestLocationPermission()
navigationController?.navigationBar.addGestureRecognizer(tap)
WaltzSDKMgr.sharedManager.delegate = self
}
//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
@IBAction func Login(_ sender: UIButton) {
if let tabBarVC = parent as? UITabBarController {
tabBarVC.selectedIndex = 1
}
WaltzSDKMgr.sharedManager.logIn()
}
@IBAction func Logout(_ sender: UIButton) {
WaltzSDKMgr.sharedManager.logOut()
}
@IBAction func startTransaction(_ sender: UIButton) {
/*
The SDK needs a valid key to start the transaction.
Please contact the Waltz team to have one.
*/
var viewController: NewCustomVC? = nil
if let tabBarVC = parent as? UITabBarController {
tabBarVC.selectedIndex = 2
viewController = tabBarVC.viewControllers?[2] as? NewCustomVC
}
WaltzSDKMgr.sharedManager.beginTransaction(parentView: viewController?.customParentView, parentVC: viewController)
}
@IBAction func startGeofence(_ sender: UIButton) {
UIApplication.shared.registerForRemoteNotifications()
WaltzSDKMgr.sharedManager.startGeofenceService()
}
@IBAction func stopGeofence(_ sender: UIButton) {
WaltzSDKMgr.sharedManager.stopGeofenceService()
}
@IBAction func getMyGuestsList(_ sender: UIButton) {
responseTV.text = ""
WaltzSDKMgr.sharedManager.getMyGuestsWithUUID()
}
@IBAction func getMyInvitationsList(_ sender: UIButton) {
responseTV.text = ""
WaltzSDKMgr.sharedManager.getMyInvitationsWithUUID()
}
@IBAction func sendInvitation(_ sender: UIButton) {
responseTV.text = ""
let firstName = "iOS SDK first name"
let lastName = "iOS SDK last name"
let email = "[email protected]"
let phoneNumber = "5145457878"
let startDate = Date()
let endDate = Date(timeIntervalSinceNow: 30*60)
WaltzSDKMgr.sharedManager.sendInvitation(firstName: firstName, lastName: lastName, email: email, phoneNumber: phoneNumber, startDate: startDate, endDate: endDate)
}
func didFinishWaltzLogin(_ errorCode: SDKResponseCodes) {
if let tabBarVC = parent as? UITabBarController {
tabBarVC.selectedIndex = 0
}
print("The Login quit with error code \(errorCode)")
}
func didFinishWaltzLogout(_ errorCode: SDKResponseCodes) {
print("The Logout quit with error code \(errorCode)")
}
func didFinishWaltzTransactionWithErrorCode(_ errorCode: SDKResponseCodes) {
print("The Transaction quit with error code \(errorCode)")
}
func didFinishWaltzGeofenceSetupWithErrorCode(_ errorCode: SDKResponseCodes) {
print("The Geofence quit with error code \(errorCode)")
}
func didGetWaltzMyGuestsWithUUIDWithErrorCode(_ errorCode: SDKResponseCodes, guests: [(InvitationResponse, UUID)]?) {
print("The Get my Guests quit with error code \(errorCode)")
if errorCode == SUCCESS {
var newGuests = [InvitationResponse]()
if let newGuestsUUID = guests {
for guest in newGuestsUUID {
newGuests.append(guest.0)
}
}
responseTV.text = newGuests.toJSON().rawString()
}
}
func didGetWaltzMyInvitationsWithUUIDWithErrorCode(_ errorCode: SDKResponseCodes, invitations: [(InvitationResponse, UUID)]?) {
print("The Get my Invitations quit with error code \(errorCode)")
if errorCode == SUCCESS {
var newInvitations = [InvitationResponse]()
if let newInvitationsUUID = invitations {
for invitation in newInvitationsUUID {
newInvitations.append(invitation.0)
}
}
responseTV.text = newInvitations.toJSON().rawString()
}
}
func didSendWaltzInvitationWithErrorCode(_ errorCode: SDKResponseCodes) {
print("The Send Invitation quit with error code \(errorCode)")
if errorCode == SUCCESS {
responseTV.text = "Success"
}
}
func didUpdateWaltzFCMTokenWithErrorCode(_ errorCode: SDKResponseCodes) {
print("The Update FCM token quit with error code \(errorCode)")
}
func didGetWaltzDDInfos(_ ddInfos: DDInfos) {
print("We have received the DD infos elevator: \(ddInfos.elevator) floor: \(ddInfos.floor)")
}
func didRevokeWaltzInvitationWithErrorCode(_ errorCode: SDKResponseCodes) {
print("The Did Revoke Invitation quit with error code \(errorCode)")
}
func requestCameraPermission() {
if AVCaptureDevice.responds(to: #selector(AVCaptureDevice.requestAccess(for:completionHandler:))) {
AVCaptureDevice.requestAccess(for: .video, completionHandler: { granted in
if granted {
PermissionsChecker.sharedInstance.cameraPermissionsHaveBeenGranted()
} else {
}
})
} else {
}
}
@IBAction func initSDK(_ sender: UIButton) {
let _ = WaltzSDKMgr.sharedManager.initManager(licenseKey: licenseTF.text!, appUid: appUidTF.text!)
}
@IBAction func getUserInfo(_ sender: Any) {
WaltzSDKMgr.sharedManager.getJWT()
}
func didGetWaltzJWTWithErrorCode(_ errorCode: SDKResponseCodes, jwt: JWT?) {
print("The Get JWT quit with error code \(errorCode)")
if errorCode == SUCCESS, let newJWT = jwt {
responseTV.text = "Name: \(newJWT.body["firstName"]!) \(newJWT.body["lastName"]!)\nEmail: \(newJWT.body["userEmail"]!)\nID: \(newJWT.body["uid"]!)"
}
}
}
| 34.966019 | 170 | 0.631959 |
6112d01c01aadb85019842c580d7815be3a68cb4 | 901 | //
// MulticastDelegate.swift
// Matchmore
//
// Created by Maciej Burda on 06/11/2017.
// Copyright © 2018 Matchmore SA. All rights reserved.
//
import Foundation
public class MulticastDelegate<T> {
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
public var isEmpty: Bool {
return delegates.count == 0
}
public func add(_ delegate: T) {
delegates.add(delegate as AnyObject)
}
public func remove(_ delegate: T) {
delegates.remove(delegate as AnyObject)
}
public func invoke(_ invocation: (T) -> Void) {
delegates.allObjects.forEach {
// swiftlint:disable:next force_cast
invocation($0 as! T)
}
}
}
public func += <T>(left: MulticastDelegate<T>, right: T) {
left.add(right)
}
public func -= <T>(left: MulticastDelegate<T>, right: T) {
left.remove(right)
}
| 21.97561 | 77 | 0.63263 |
6758a7911e89e93a7814b2a2d65e16ffd7269eed | 1,376 | //
// PageAdmissionChargeSettingActions.swift
// YiMai
//
// Created by superxing on 16/8/19.
// Copyright © 2016年 why. All rights reserved.
//
import Foundation
import UIKit
public class PageAdmissionChargeSettingActions: PageJumpActions {
var TargetView: PageAdmissionChargeSettingBodyView? = nil
var SettingApi: YMAPIUtility!
override func ExtInit() {
super.ExtInit()
TargetView = Target as? PageAdmissionChargeSettingBodyView
SettingApi = YMAPIUtility(key: YMAPIStrings.CS_API_ACTION_CONFIRM_FEE_SETTING,
success: SaveSuccess, error: SaveFailed)
}
public func SaveSuccess(data: NSDictionary?) {
// TargetView?.UpdateVar()
// YMVar.MyUserInfo = data!["data"] as! [String : AnyObject]
}
public func SaveFailed(error: NSError) {
// TargetView?.UpdateVar()
}
public func ChargeSwitchTouched(sender: UISwitch) {
TargetView?.SetChargeOn(sender.on)
}
public func UpadteSetting() {
TargetView?.UpdateVar()
SettingApi.YMChangeUserInfo(
[
"fee_switch": "\(YMVar.MyUserInfo["fee_switch"]!)",
"fee": "\(YMVar.MyUserInfo["fee"]!)",
"fee_face_to_face": "\(YMVar.MyUserInfo["fee_face_to_face"]!)"
]
)
}
}
| 23.322034 | 86 | 0.609738 |
ed393a03e67e6a678aa3c57f6510c5096692e65f | 575 | //
// DGMObject.swift
// dgmpp
//
// Created by Artem Shimanski on 26.12.2017.
//
import Foundation
import cwrapper
public class DGMObject {
var handle: dgmpp_handle
let owned: Bool
public required init(_ handle: dgmpp_handle, owned: Bool) {
self.handle = handle
self.owned = owned
}
deinit {
if owned {
dgmpp_free(handle)
}
}
}
extension DGMObject: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(handle)
}
public static func ==(lhs: DGMObject, rhs: DGMObject) -> Bool {
return lhs.handle == rhs.handle
}
}
| 14.375 | 64 | 0.674783 |
def47c80d82b8654e4b622393d0dcdc74fc63daa | 3,952 | //
// BuildingsTableViewController.swift
// DoorConcept
//
// Created by Jorge Raul Ovalle Zuleta on 3/18/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
import SESlideTableViewCell
import DZNEmptyDataSet
class BuildingsTableViewController: UITableViewController {
let buildingInteractor = BuildingsInteractor()
var buildings:[Building] = [Building]()
override func viewDidLoad() {
self.tableView.emptyDataSetDelegate = self
self.tableView.emptyDataSetSource = self
}
override func viewWillAppear(animated: Bool) {
self.loadBuildings()
}
func loadBuildings(){
buildingInteractor.getBuildings { (data, error) -> Void in
if error == nil{
self.buildings = data as! [Building]
self.tableView.reloadData()
}else{
print(error)
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buildings.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BuildingCell", forIndexPath: indexPath) as! BuildingsTableViewCell
cell.delegate = self
cell.tag = indexPath.row
cell.configureCellWithBuilding(buildings[indexPath.row])
return cell
}
}
// MARK: - SESlideTableViewCellDelegate
extension BuildingsTableViewController:SESlideTableViewCellDelegate{
func slideTableViewCell(cell: SESlideTableViewCell!, didTriggerRightButton buttonIndex: Int) {
buildingInteractor.deleteBuilding(buildings[cell.tag])
self.loadBuildings()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let doorView = self.storyboard?.instantiateViewControllerWithIdentifier("DoorsTableViewController") as! DoorsTableViewController
doorView.building = buildings[indexPath.row]
self.navigationController?.pushViewController(doorView, animated: true)
}
}
// MARK: - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate
// Handle the empty state
extension BuildingsTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: "empty_buildings")
}
func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let str = "Oops!!"
let infoStr = NSMutableAttributedString(string: str)
infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18, weight: 0.7), range: NSMakeRange(0, str.characters.count))
infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count))
return infoStr as NSAttributedString
}
func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let str = "There’s no buildings yet, add a new one\nclicking in the + button."
let infoStr = NSMutableAttributedString(string: str)
infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14, weight: 0.1), range: NSMakeRange(0, str.characters.count))
infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count))
return infoStr as NSAttributedString
}
func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! {
return UIColor.whiteColor()
}
func emptyDataSetShouldFadeIn(scrollView: UIScrollView!) -> Bool {
return true
}
} | 39.919192 | 143 | 0.707237 |
fea41a29ab68f2d5492cef49fdf3760f762d2e1c | 5,837 | //
// CertificateVerifier.swift
// certificates
//
// Created by Michael Shin on 8/14/18.
// Copyright © 2018 Learning Machine, Inc. All rights reserved.
//
import Foundation
import WebKit
class CertificateVerifier: NSObject, WKScriptMessageHandler {
struct VerifierMessageType {
static let blockchain = "blockchain"
static let allSteps = "allSteps"
static let substepUpdate = "substepUpdate"
static let result = "result"
}
let certificate: Data
var webView: WKWebView?
var delegate: CertificateVerifierDelegate?
var blockchain: String?
init(certificate: Data) {
self.certificate = certificate
}
func setup() {
// copy html file to cache dir
let htmlURL = Bundle.main.url(forResource: "verify", withExtension: "html")!
let htmlCopy = URL(fileURLWithPath: NSString(string: cachePath).appendingPathComponent("verify.html"))
try? FileManager.default.removeItem(at: htmlCopy)
try! FileManager.default.copyItem(at: htmlURL, to: htmlCopy)
// copy js library to cache dir
let jsURL = Bundle.main.url(forResource: "verifier", withExtension: "js")!
let jsCopy = URL(fileURLWithPath: NSString(string: cachePath).appendingPathComponent("verifier.js"))
try? FileManager.default.removeItem(at: jsCopy)
try! FileManager.default.copyItem(at: jsURL, to: jsCopy)
// write certificate to cache
let certString = String(data: certificate, encoding: .utf8)
let certPath = URL(fileURLWithPath: NSString(string: cachePath).appendingPathComponent("certificate.json"))
try? FileManager.default.removeItem(at: certPath)
try! certString?.write(to: certPath, atomically: true, encoding: .utf8)
}
var cachePath: String {
return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
}
func verify() {
setup()
let htmlCopy = URL(fileURLWithPath: NSString(string: cachePath).appendingPathComponent("verify.html"))
let webView = WKWebView()
webView.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
webView.loadFileURL(htmlCopy, allowingReadAccessTo: URL(fileURLWithPath: cachePath))
webView.configuration.userContentController.add(self, name: VerifierMessageType.blockchain)
webView.configuration.userContentController.add(self, name: VerifierMessageType.allSteps)
webView.configuration.userContentController.add(self, name: VerifierMessageType.substepUpdate)
webView.configuration.userContentController.add(self, name: VerifierMessageType.result)
self.webView = webView
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("message: \(message.body)")
switch message.name {
case VerifierMessageType.blockchain:
blockchain = message.body as? String
let message = Localizations.VerificationInProgress(blockchain!)
delegate?.updateStatus(message: message, status: .verifying)
case VerifierMessageType.allSteps:
let topArray = message.body as! [[String: Any?]]
var allSteps: [VerificationStep] = []
for step in topArray {
allSteps.append(VerificationStep(rawObject: step))
}
delegate?.notifySteps(steps: allSteps)
case VerifierMessageType.substepUpdate:
let message = message.body as! [String: Any?]
let substep = VerificationSubstep(rawObject: message)
delegate?.updateSubstepStatus(substep: substep)
case VerifierMessageType.result:
let message = message.body as! [String: String]
let status = message["status"]!
let success = (status == VerificationStatus.success.rawValue)
if success {
delegate?.updateStatus(message: Localizations.VerificationSuccess(blockchain!), status: .success)
} else {
delegate?.updateStatus(message: Localizations.VerificationFail, status: .failure)
}
default:
return
}
}
func cleanup() {
webView = nil
}
func cancel() {
cleanup()
}
}
enum VerificationStatus: String {
case success = "success"
case failure = "failure"
case verifying = "starting"
}
class VerificationStep {
var code: String!
var label: String?
var substeps: [VerificationSubstep] = []
init(rawObject: [String: Any?]) {
code = rawObject["code"] as? String
label = rawObject["label"] as? String
let stepArray = rawObject["subSteps"] as! [[String: Any?]]
for step in stepArray {
substeps.append(VerificationSubstep(rawObject: step))
}
}
}
class VerificationSubstep {
var code: String!
var label: String?
var parentStep: String?
var errorMessage: String?
var status: VerificationStatus?
init(rawObject: [String: Any?]) {
code = rawObject["code"] as? String
label = rawObject["label"] as? String
parentStep = rawObject["parentStep"] as? String
errorMessage = rawObject["errorMessage"] as? String
if let rawStatus = rawObject["status"] as? String {
status = VerificationStatus(rawValue: rawStatus)
}
}
}
protocol CertificateVerifierDelegate: class {
func updateStatus(message: String, status: VerificationStatus)
func notifySteps(steps: [VerificationStep])
func updateSubstepStatus(substep: VerificationSubstep)
}
| 35.809816 | 119 | 0.649135 |
e4958cf8fb4762a6efabd313c6eb3bc52491470d | 64 | import PackageDescription
let package = Package(name: "JSON")
| 12.8 | 35 | 0.765625 |
46b881a3d432568e3bcb553da861acc585daa407 | 526 | //
// WooTaxStatus.swift
// Eightfold
//
// Created by Brianna Lee on 3/3/18.
// Copyright © 2018 Owly Design. All rights reserved.
//
import Foundation
/// The status of the tax of a product.
///
/// - taxable: Defines whether or not the product should be taxed.
/// - shipping: Defines if shipping should be taxed.
/// - none: No tax associated.
public enum WooTaxStatus: String {
case taxable = "taxable"
case shipping = "shipping"
case none = "none"
public init() {
self = .none
}
}
| 21.04 | 66 | 0.638783 |
de19e5f3ced5a453a9945d7989b08dce23e22819 | 3,322 | // RUN: %target-swift-emit-sil -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 -verify
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s
// RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.60 | %FileCheck %s
// REQUIRES: OS=macosx
@available(macOS 10.50, *)
public struct TopLevelStruct {
// -- Fallback definition for TopLevelStruct.trivialMethod()
// CHECK-LABEL: sil non_abi [serialized] [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> ()
// CHECK: bb0({{%.*}} : $TopLevelStruct):
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: return [[RESULT]] : $()
// -- Back deployment thunk for TopLevelStruct.trivialMethod()
// CHECK-LABEL: sil non_abi [serialized] [thunk] [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> ()
// CHECK: bb0([[BB0_ARG:%.*]] : $TopLevelStruct):
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]]
//
// CHECK: [[UNAVAIL_BB]]:
// CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> ()
// CHECK: {{%.*}} = apply [[FALLBACKFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> ()
// CHECK: br [[RETURN_BB:bb[0-9]+]]
//
// CHECK: [[AVAIL_BB]]:
// CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> ()
// CHECK: {{%.*}} = apply [[ORIGFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> ()
// CHECK: br [[RETURN_BB]]
//
// CHECK: [[RETURN_BB]]
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: return [[RESULT]] : $()
// -- Original definition of TopLevelStruct.trivialMethod()
// CHECK-LABEL: sil [serialized] [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> ()
@available(macOS 10.51, *)
@_backDeploy(macOS 10.52)
public func trivialMethod() {}
}
// CHECK-LABEL: sil hidden [available 10.51] [ossa] @$s11back_deploy6calleryyAA14TopLevelStructVF : $@convention(thin) (TopLevelStruct) -> ()
// CHECK: bb0([[STRUCT_ARG:%.*]] : $TopLevelStruct):
@available(macOS 10.51, *)
func caller(_ s: TopLevelStruct) {
// -- Verify the thunk is called
// CHECK: {{%.*}} = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> ()
s.trivialMethod()
}
| 60.4 | 176 | 0.667369 |
469cb9578586c65bc2c0e35461700917e3b9a7c7 | 236 | //
// NovelReaderPageCover.swift
// nReader
//
// Created by Miter on 2021/11/3.
//
import Foundation
open class NovelReaderPageCover: NovelReaderPage {
override var pageType: NovelReaderType {
.cover
}
}
| 13.882353 | 50 | 0.652542 |
0a06f8cb80ad49196f45b3c4c2f209dcd7451ad1 | 766 | import XCTest
@testable import CryptoControlKit
final class CryptoControlTests: XCTestCase {
private let cryptoControl = CryptoControl(key: "<KEY-HERE>")
func testCryptoControl_request() {
let expect = XCTestExpectation(description: "Endpoint Request")
cryptoControl.request(endpoint: CryptoControlAPI.news(.newsCategory(token: "bitcoin")).endpoint) { result in
switch result {
case .success(let data):
XCTAssertNotNil(data)
case .failure: XCTFail("failure")
}
expect.fulfill()
}
wait(for: [expect], timeout: 2)
}
static var allTests = [
("testCryptoControl_request", testCryptoControl_request),
]
}
| 28.37037 | 116 | 0.613577 |
2fbf5db30eec2a086109f7aa4b4a51428e7f890e | 742 | //
// Operators.swift
// RIBsTodo
//
// Created by myung gi son on 2020/05/04.
// Copyright © 2020 myunggison. All rights reserved.
//
import RxSwift
// MARK: - Filter
extension ObservableType {
func filter<O: ObservableType>(_ predicate: O) -> Observable<E> where O.E == Bool {
return self
.withLatestFrom(predicate) { element, predicate in (element, predicate) }
.filter { _, predicate in predicate }
.map { element, _ in element }
}
func filterNot<O: ObservableType>(_ predicate: O) -> Observable<E> where O.E == Bool {
return self
.withLatestFrom(predicate) { element, predicate in (element, predicate) }
.filter { _, predicate in !predicate }
.map { element, _ in element }
}
}
| 27.481481 | 88 | 0.652291 |
e89254df16259496d0d51a336ed364ba20ace532 | 20,746 | //
// EcouponViewController.swift
// StarbuckCloneEx2
//
// Created by Mac mini on 2020/03/04.
// Copyright © 2020 Mac mini. All rights reserved.
//
import UIKit
class EcouponViewController: UIViewController {
let menuImage = UIImageView()
let nameLabel = UILabel()
let EnNameLabel = UILabel()
let giftImg = UIButton()
let bookMarkButton = UIButton()
let priceLabel = UILabel()
let minusButton = UIButton()
let quantityLabel = UILabel()
let plusButton = UIButton()
let hotButton = UIButton()
let icedButton = UIButton()
// setUI2()
let decafMsgLabel = UILabel()
let chooseCupLabel = UILabel()
let cupMsgLabel = UILabel()
let buttonView = ChooseCupButtonView()
let lineView1 = ChooseCupButtonLineView()
let lineView2 = ChooseCupButtonLineView()
let mugCupButton = UIButton()
let personalCupButton = UIButton()
let plasticCupButton = UIButton()
let sizeButtonView = ChooseSizeButtonCustomView()
let sizeButton = UIButton(type: .custom) // customButton
let personalOptionButtonView = ChoosePersonalOptionCustomView()
let personalOptionButton = UIButton() // customButton, 데이터는 어떻게 처리?
let presentButton = UIButton()
let orderButton = UIButton()
let addBasketButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
setNavigationBar()
setUI()
setAutoLayout()
setUI2()
setAutoLayout2()
}
func setNavigationBar() {
view.backgroundColor = .white
title = "e-Coupon"
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.backgroundColor = .black
// let registerBarButton: UIButton = {
// let registerBarButton = UIButton()
// registerBarButton.setImage(UIImage(systemName: "plus"), for: .normal)
// registerBarButton.imageView?.contentMode = .scaleToFill
// registerBarButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
// registerBarButton.addTarget(self, action: #selector(didTapRegisterBarButton(_:)), for: .touchUpInside)
// return registerBarButton
// }()
let registerBarButton = UIBarButtonItem(image: UIImage(systemName: "plus"), style: .done, target: self, action: #selector(didTapRegisterBarButton(_:)))
let informationBarButton: UIButton = {
let informationBarButton = UIButton()
informationBarButton.setImage(UIImage(systemName: "info.circle"), for: .normal)
informationBarButton.imageView?.contentMode = .scaleToFill
informationBarButton.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
informationBarButton.addTarget(self, action: #selector(didTapInformationBarButton(_:)), for: .touchUpInside)
return informationBarButton
}()
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: informationBarButton), registerBarButton]
//navigationbar.items = [navigationItem]
// let registerBarButton = UIBarButtonItem(image: UIImage(systemName: "plus"), style: .done, target: self, action: #selector(didTapRegisterBarButton(_:)))
// let informationBarButton = UIBarButtonItem(image: UIImage(systemName: "info.circle"), style: .done, target: self, action: #selector(didTapInformationBarButton(_:)))
// navigationItem.rightBarButtonItems = [informationBarButton, registerBarButton]
}
@objc private func didTapRegisterBarButton(_ sender: Any) {
}
@objc private func didTapInformationBarButton(_ sender: Any) {
}
func setUI() {
[menuImage, nameLabel, giftImg, EnNameLabel, priceLabel, bookMarkButton, minusButton, quantityLabel, plusButton, hotButton, icedButton, decafMsgLabel].forEach {
view.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
menuImage.image = UIImage(named: "coffee")
menuImage.layer.cornerRadius = 50
menuImage.contentMode = .scaleAspectFit
menuImage.clipsToBounds = true
nameLabel.text = "카페 아메리카노"
nameLabel.textColor = .black
nameLabel.font = UIFont.systemFont(ofSize: 14)
let edge:CGFloat = 3
giftImg.setImage(UIImage(systemName: "gift"), for: .normal)
giftImg.tintColor = .white
giftImg.backgroundColor = .darkGray
giftImg.imageView?.contentMode = .scaleAspectFit
giftImg.imageView?.clipsToBounds = true
giftImg.imageEdgeInsets = UIEdgeInsets(top: edge, left: edge, bottom: edge, right: edge)
giftImg.layer.cornerRadius = 8
bookMarkButton.setImage(UIImage(systemName: "bookmark"), for: .normal)
bookMarkButton.tintColor = .black
bookMarkButton.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
// bookMarkButton.contentVerticalAlignment = .fill
// bookMarkButton.contentHorizontalAlignment = .fill
let edge2:CGFloat = 8
bookMarkButton.imageView?.contentMode = .scaleAspectFit
bookMarkButton.imageView?.clipsToBounds = true
bookMarkButton.imageEdgeInsets = UIEdgeInsets(top: edge2, left: edge2, bottom: edge2, right: edge2)
bookMarkButton.layer.cornerRadius = 15
EnNameLabel.text = "Cafe Americano"
EnNameLabel.textColor = #colorLiteral(red: 0.5738074183, green: 0.5655357838, blue: 0, alpha: 1)
EnNameLabel.font = UIFont.systemFont(ofSize: 11)
priceLabel.text = "4,100원"
priceLabel.textColor = .black
priceLabel.font = UIFont.boldSystemFont(ofSize: 20)
minusButton.setImage(UIImage(systemName: "minus"), for: .normal)
minusButton.tintColor = .darkGray
minusButton.backgroundColor = .lightGray
minusButton.layer.cornerRadius = 2
quantityLabel.text = "1"
quantityLabel.textColor = .black
quantityLabel.font = UIFont.boldSystemFont(ofSize: 20)
plusButton.setImage(UIImage(systemName: "plus"), for: .normal)
plusButton.tintColor = .darkGray
plusButton.backgroundColor = .lightGray
plusButton.layer.cornerRadius = 2
hotButton.setTitle("HOT", for: .normal)
hotButton.setTitleColor(.white, for: .normal)
hotButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
hotButton.backgroundColor = #colorLiteral(red: 0.6451261104, green: 0.1319800223, blue: 0.06538274611, alpha: 1)
hotButton.layer.borderColor = #colorLiteral(red: 0.6451261104, green: 0.1319800223, blue: 0.06538274611, alpha: 1)
hotButton.layer.borderWidth = 1
hotButton.layer.cornerRadius = 2
icedButton.setTitle("ICED", for: .normal)
icedButton.setTitleColor(.white, for: .normal)
icedButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
icedButton.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
icedButton.layer.borderColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
icedButton.layer.borderWidth = 1
icedButton.layer.cornerRadius = 2
}
func setUI2() {
[decafMsgLabel, chooseCupLabel, cupMsgLabel, buttonView, mugCupButton, personalCupButton, plasticCupButton, sizeButtonView, personalOptionButtonView, presentButton, orderButton, addBasketButton].forEach {
view.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
decafMsgLabel.text = "디카페인 커피 Tab에서 \n 디카페인, 1/2디카페인 카페 아메리카노를 주문할 수 있습니다."
decafMsgLabel.textColor = .darkGray
decafMsgLabel.font = UIFont.systemFont(ofSize: 13)
decafMsgLabel.numberOfLines = 0
decafMsgLabel.textAlignment = .center
chooseCupLabel.text = "컵 선택"
chooseCupLabel.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
chooseCupLabel.font = UIFont.systemFont(ofSize: 13)
cupMsgLabel.text = " 환경보호를 위해 매장 내에서는 머그컵을 사용해주세요. "
cupMsgLabel.textColor = .white
cupMsgLabel.font = UIFont.systemFont(ofSize: 12)
cupMsgLabel.backgroundColor = #colorLiteral(red: 0.03676272521, green: 0.5975982898, blue: 0.5679046872, alpha: 1)
cupMsgLabel.layer.borderColor = #colorLiteral(red: 0.03676272521, green: 0.5975982898, blue: 0.5679046872, alpha: 1)
cupMsgLabel.layer.borderWidth = 1
cupMsgLabel.layer.cornerRadius = 10
cupMsgLabel.clipsToBounds = true
lineView1.translatesAutoresizingMaskIntoConstraints = false
lineView2.translatesAutoresizingMaskIntoConstraints = false
buttonView.addSubview(lineView1)
buttonView.addSubview(lineView2)
mugCupButton.setTitle("매장컵", for: .normal)
mugCupButton.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
mugCupButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
mugCupButton.addTarget(self, action: #selector(didTapStoreCup(_:)), for: .touchUpInside)
buttonView.addSubview(mugCupButton)
personalCupButton.setTitle("개인컵", for: .normal)
personalCupButton.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
personalCupButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
buttonView.addSubview(personalCupButton)
plasticCupButton.setTitle("일회용컵", for: .normal)
plasticCupButton.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
plasticCupButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
plasticCupButton.addTarget(self, action: #selector(didTapPlasticCup(_:)), for: .touchUpInside)
buttonView.addSubview(plasticCupButton)
sizeButton.translatesAutoresizingMaskIntoConstraints = false
sizeButtonView.addSubview(sizeButton)
sizeButton.backgroundColor = .clear
sizeButton.addTarget(self, action: #selector(didTapSizeButton(_:)), for: .touchUpInside)
personalOptionButton.translatesAutoresizingMaskIntoConstraints = false
personalOptionButtonView.addSubview(personalOptionButton)
personalCupButton.backgroundColor = .clear
// present, order, addBasket
presentButton.setTitle("선물하기", for: .normal)
presentButton.setTitleColor(.white, for: .normal)
presentButton.backgroundColor = #colorLiteral(red: 0.6644858718, green: 0.484285295, blue: 0.4908220172, alpha: 1)
presentButton.titleLabel?.font = UIFont.systemFont(ofSize: 13)
presentButton.layer.cornerRadius = 2
orderButton.setTitle("바로 주문하기", for: .normal)
orderButton.setTitleColor(.white, for: .normal)
orderButton.backgroundColor = #colorLiteral(red: 0.6644858718, green: 0.484285295, blue: 0.4908220172, alpha: 1)
orderButton.titleLabel?.font = UIFont.systemFont(ofSize: 13)
orderButton.layer.cornerRadius = 2
addBasketButton.setTitle("장바구니 담기", for: .normal)
addBasketButton.setTitleColor(.darkGray, for: .normal)
addBasketButton.backgroundColor = .lightGray
addBasketButton.titleLabel?.font = UIFont.systemFont(ofSize: 13)
addBasketButton.layer.cornerRadius = 2
}
@objc func didTapSizeButton(_ sender: Any) {
sizeButtonView.sizeLabel.text = "Grande"
print("클릭!")
}
@objc func didTapPlasticCup(_ sender: Any) {
plasticCupButton.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
plasticCupButton.setTitleColor(.white, for: .normal)
cupMsgLabel.text = " ✓컵 선택이 완료되었습니다. "
[personalCupButton, mugCupButton].forEach {
$0.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
$0.backgroundColor = .clear
}
}
@objc func didTapStoreCup(_ sender: Any) {
mugCupButton.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
mugCupButton.setTitleColor(.white, for: .normal)
cupMsgLabel.text = " ☘️환경보호에 동참해주셔서 감사합니다. "
[personalCupButton, plasticCupButton].forEach {
$0.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
$0.backgroundColor = .clear
}
}
func setAutoLayout2() {
let guide = view.safeAreaLayoutGuide
let margin: CGFloat = 10
let viewWidth: CGFloat = guide.layoutFrame.width-(margin*2)
print("viewWidth:", viewWidth/3)
NSLayoutConstraint.activate([
decafMsgLabel.topAnchor.constraint(equalTo: hotButton.bottomAnchor, constant: margin*2),
decafMsgLabel.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: margin),
decafMsgLabel.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -margin),
chooseCupLabel.topAnchor.constraint(equalTo: decafMsgLabel.bottomAnchor,constant: margin*3),
chooseCupLabel.leadingAnchor.constraint(equalTo: decafMsgLabel.leadingAnchor),
cupMsgLabel.topAnchor.constraint(equalTo: decafMsgLabel.bottomAnchor, constant: margin*2.5),
cupMsgLabel.trailingAnchor.constraint(equalTo: decafMsgLabel.trailingAnchor),
cupMsgLabel.heightAnchor.constraint(equalToConstant: 20),
buttonView.leadingAnchor.constraint(equalTo: chooseCupLabel.leadingAnchor),
buttonView.topAnchor.constraint(equalTo: chooseCupLabel.bottomAnchor, constant: margin),
buttonView.widthAnchor.constraint(equalToConstant: viewWidth),
buttonView.heightAnchor.constraint(equalToConstant: 40),
lineView1.topAnchor.constraint(equalTo: buttonView.topAnchor),
lineView1.leadingAnchor.constraint(equalTo: buttonView.leadingAnchor, constant: viewWidth/3),
lineView1.widthAnchor.constraint(equalToConstant: 1),
lineView1.heightAnchor.constraint(equalTo: buttonView.heightAnchor),
lineView2.topAnchor.constraint(equalTo: buttonView.topAnchor),
lineView2.trailingAnchor.constraint(equalTo: buttonView.trailingAnchor, constant: -viewWidth/3),
lineView2.widthAnchor.constraint(equalToConstant: 1),
lineView2.heightAnchor.constraint(equalTo: buttonView.heightAnchor),
mugCupButton.leadingAnchor.constraint(equalTo: buttonView.leadingAnchor),
mugCupButton.topAnchor.constraint(equalTo: buttonView.topAnchor),
mugCupButton.widthAnchor.constraint(equalToConstant: viewWidth/3),
mugCupButton.heightAnchor.constraint(equalTo: buttonView.heightAnchor),
personalCupButton.leadingAnchor.constraint(equalTo: mugCupButton.trailingAnchor),
personalCupButton.topAnchor.constraint(equalTo: mugCupButton.topAnchor),
personalCupButton.widthAnchor.constraint(equalToConstant: viewWidth/3),
personalCupButton.heightAnchor.constraint(equalTo: buttonView.heightAnchor),
plasticCupButton.trailingAnchor.constraint(equalTo: buttonView.trailingAnchor),
plasticCupButton.topAnchor.constraint(equalTo: mugCupButton.topAnchor),
plasticCupButton.widthAnchor.constraint(equalToConstant: viewWidth/3),
plasticCupButton.heightAnchor.constraint(equalTo: buttonView.heightAnchor),
sizeButtonView.topAnchor.constraint(equalTo: buttonView.bottomAnchor, constant: margin),
sizeButtonView.leadingAnchor.constraint(equalTo: buttonView.leadingAnchor),
sizeButtonView.trailingAnchor.constraint(equalTo: buttonView.trailingAnchor),
sizeButtonView.heightAnchor.constraint(equalToConstant: 40),
sizeButton.topAnchor.constraint(equalTo: sizeButtonView.topAnchor),
sizeButton.leadingAnchor.constraint(equalTo: sizeButtonView.leadingAnchor),
sizeButton.trailingAnchor.constraint(equalTo: sizeButtonView.trailingAnchor),
sizeButton.bottomAnchor.constraint(equalTo: sizeButtonView.bottomAnchor),
personalOptionButtonView.topAnchor.constraint(equalTo: sizeButtonView.bottomAnchor, constant: margin),
personalOptionButtonView.leadingAnchor.constraint(equalTo: sizeButtonView.leadingAnchor),
personalOptionButtonView.trailingAnchor.constraint(equalTo: sizeButtonView.trailingAnchor),
personalOptionButtonView.heightAnchor.constraint(equalToConstant: 40),
personalOptionButton.topAnchor.constraint(equalTo: personalOptionButtonView.topAnchor),
personalOptionButton.leadingAnchor.constraint(equalTo: personalOptionButtonView.leadingAnchor),
personalOptionButton.trailingAnchor.constraint(equalTo: personalOptionButtonView.trailingAnchor),
personalOptionButton.bottomAnchor.constraint(equalTo: personalOptionButtonView.bottomAnchor),
presentButton.topAnchor.constraint(equalTo: personalOptionButtonView.bottomAnchor, constant: margin),
presentButton.leadingAnchor.constraint(equalTo: personalOptionButtonView.leadingAnchor),
presentButton.widthAnchor.constraint(equalToConstant: ((viewWidth-(margin/2))/2)),
presentButton.heightAnchor.constraint(equalToConstant: 40),
orderButton.topAnchor.constraint(equalTo: personalOptionButtonView.bottomAnchor, constant: margin),
orderButton.trailingAnchor.constraint(equalTo: personalOptionButtonView.trailingAnchor),
orderButton.widthAnchor.constraint(equalToConstant: ((viewWidth-(margin/2))/2)),
orderButton.heightAnchor.constraint(equalToConstant: 40),
addBasketButton.topAnchor.constraint(equalTo: orderButton.bottomAnchor, constant: margin/2),
addBasketButton.leadingAnchor.constraint(equalTo: presentButton.leadingAnchor),
addBasketButton.trailingAnchor.constraint(equalTo: orderButton.trailingAnchor),
addBasketButton.heightAnchor.constraint(equalToConstant: 40),
])
}
func setAutoLayout() {
let guide = view.safeAreaLayoutGuide
let margin: CGFloat = 10
let temperButtonSize:CGFloat = (view.frame.width-(margin*2.5))/2
NSLayoutConstraint.activate([
menuImage.topAnchor.constraint(equalTo: guide.topAnchor, constant: margin),
menuImage.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: margin),
menuImage.widthAnchor.constraint(equalToConstant: 100),
menuImage.heightAnchor.constraint(equalToConstant: 100),
nameLabel.topAnchor.constraint(equalTo: menuImage.topAnchor),
nameLabel.leadingAnchor.constraint(equalTo: menuImage.trailingAnchor, constant: margin*1.5),
giftImg.topAnchor.constraint(equalTo: nameLabel.topAnchor),
giftImg.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 3),
giftImg.widthAnchor.constraint(equalToConstant: 17),
giftImg.heightAnchor.constraint(equalToConstant: 17),
bookMarkButton.topAnchor.constraint(equalTo: giftImg.topAnchor),
bookMarkButton.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -margin),
bookMarkButton.widthAnchor.constraint(equalToConstant: 30),
bookMarkButton.heightAnchor.constraint(equalToConstant: 30),
EnNameLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 3),
EnNameLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
priceLabel.topAnchor.constraint(equalTo: EnNameLabel.bottomAnchor, constant: margin),
priceLabel.leadingAnchor.constraint(equalTo: EnNameLabel.leadingAnchor),
minusButton.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: margin),
minusButton.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
minusButton.widthAnchor.constraint(equalToConstant: 30),
minusButton.heightAnchor.constraint(equalToConstant: 30),
quantityLabel.topAnchor.constraint(equalTo: minusButton.topAnchor),
quantityLabel.leadingAnchor.constraint(equalTo: minusButton.trailingAnchor, constant: margin*3),
plusButton.topAnchor.constraint(equalTo: minusButton.topAnchor),
plusButton.leadingAnchor.constraint(equalTo: quantityLabel.trailingAnchor, constant: margin*3),
plusButton.widthAnchor.constraint(equalToConstant: 30),
plusButton.heightAnchor.constraint(equalToConstant: 30),
hotButton.topAnchor.constraint(equalTo: plusButton.bottomAnchor, constant: margin*3),
hotButton.leadingAnchor.constraint(equalTo: menuImage.leadingAnchor),
hotButton.widthAnchor.constraint(equalToConstant: temperButtonSize),
hotButton.heightAnchor.constraint(equalToConstant: temperButtonSize/4),
icedButton.topAnchor.constraint(equalTo: plusButton.bottomAnchor, constant: margin*3),
icedButton.leadingAnchor.constraint(equalTo: hotButton.trailingAnchor, constant: margin/2),
icedButton.widthAnchor.constraint(equalToConstant: temperButtonSize),
icedButton.heightAnchor.constraint(equalToConstant: temperButtonSize/4),
])
}
}
| 48.814118 | 208 | 0.738938 |
18d5d9eaa606a9081229a95b71c4d12b93321071 | 79 | import AppKit
enum ImageResult {
case image(NSImage)
case error(String)
}
| 11.285714 | 21 | 0.734177 |
09705d2e6d96629dbaa49fb3bc2b57251be2da06 | 247 | //
// AppDelegate.swift
// Questions
//
// Created by DianQK on 10/11/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 14.529412 | 55 | 0.704453 |
62820df8691de3e27178ce406716ee7aa19f7ee7 | 4,493 | //
// PhotoMapViewController.swift
// Photo Map
//
// Created by Nicholas Aiwazian on 10/15/15.
// Copyright © 2015 Timothy Lee. All rights reserved.
//
import UIKit
import MapKit
class PhotoAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(0, 0)
var photo: UIImage!
var title: String? {
return "\(coordinate.latitude)"
}
}
class PhotoMapViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, LocationsViewControllerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var pickedImage: UIImage! = nil
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let sfRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(37.783333, -122.416667),
MKCoordinateSpanMake(0.1, 0.1))
mapView.setRegion(sfRegion, animated: false)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func instantiateImagePicker(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
//vc.sourceType = UIImagePickerControllerSourceType.camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("Camera is available 📸")
vc.sourceType = .camera
} else {
print("Camera 🚫 available so we will use photo library instead")
vc.sourceType = .photoLibrary
}
self.present(vc, animated: true, completion: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
// Get the image captured by the UIImagePickerController
let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage
pickedImage = editedImage
// Do something with the images (based on your use case)
// Dismiss UIImagePickerController to go back to your original view controller
dismiss(animated: true, completion: nil)
performSegue(withIdentifier: "tagSegue", sender: nil)
}
func locationsPickedLocation(controller: LocationsViewController, latitude: NSNumber, longitude: NSNumber) {
let lati = "\(latitude)"
let long = "\(longitude)"
print(lati + " " + long)
let locationCoordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
let annotation = PhotoAnnotation()
annotation.coordinate = locationCoordinate
// annotation.coordinate = locationCoordinate
// annotation.title = latString
annotation.photo = pickedImage
mapView.addAnnotation(annotation)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
//print("annotation")
let reuseID = "myAnnotationView"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID)
if (annotationView == nil) {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
annotationView!.canShowCallout = true
annotationView!.leftCalloutAccessoryView = UIImageView(frame: CGRect(x:0, y:0, width: 50, height:50))
}
let imageView = annotationView?.leftCalloutAccessoryView as! UIImageView
imageView.image = UIImage(named: "camera")
return annotationView
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
if let vc = segue.destination as? LocationsViewController {
vc.delegate = self
}
// Pass the selected object to the new view controller.
}
}
| 34.829457 | 167 | 0.650345 |
165619d8ebdff15776bc1c3a285537ce167de6bc | 2,197 | //
// AppDelegate.swift
// PresentANewViewController
//
// Created by Marlon David Ruiz Arroyave on 9/22/17.
// Copyright © 2017 Eafit. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.744681 | 285 | 0.757396 |
9115d4f114b1807edceaeb204ca69326ea4d88db | 8,241 | import UIKit
import SectionsTableView
import SnapKit
class MainSettingsViewController: WalletViewController {
private let delegate: IMainSettingsViewDelegate
private let tableView = SectionsTableView(style: .grouped)
private var allBackedUp: Bool = true
private var currentBaseCurrency: String?
private var currentLanguage: String?
private var lightMode: Bool = true
private var appVersion: String?
init(delegate: IMainSettingsViewDelegate) {
self.delegate = delegate
super.init()
tabBarItem = UITabBarItem(title: "settings.tab_bar_item".localized, image: UIImage(named: "settings.tab_bar_item"), tag: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "settings.title".localized
navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
tableView.registerCell(forClass: TitleCell.self)
tableView.registerCell(forClass: RightImageCell.self)
tableView.registerCell(forClass: RightLabelCell.self)
tableView.registerCell(forClass: ToggleCell.self)
tableView.registerHeaderFooter(forClass: MainSettingsFooter.self)
tableView.sectionDataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
delegate.viewDidLoad()
tableView.buildSections()
}
override func viewWillAppear(_ animated: Bool) {
tableView.deselectCell(withCoordinator: transitionCoordinator, animated: animated)
}
private var securityRows: [RowProtocol] {
let securityAttentionImage = allBackedUp ? nil : UIImage(named: "Attention Icon")
return [
Row<RightImageCell>(id: "security_center", hash: "security_center.\(allBackedUp)", height: .heightSingleLineCell, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Security Icon"), title: "settings.security_center".localized, rightImage: securityAttentionImage, rightImageTintColor: .cryptoRed, showDisclosure: true)
}, action: { [weak self] _ in
self?.delegate.didTapSecurity()
}),
Row<TitleCell>(id: "manage_coins", height: .heightSingleLineCell, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Manage Coins Icon"), title: "settings.manage_coins".localized, showDisclosure: true)
}, action: { [weak self] _ in
DispatchQueue.main.async {
self?.delegate.didTapManageCoins()
}
}),
Row<TitleCell>(id: "experimental_features", height: .heightSingleLineCell, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Experimental Features Icon"), title: "settings.experimental_features".localized, showDisclosure: true, last: true)
}, action: { [weak self] _ in
self?.delegate.didTapExperimentalFeatures()
})
]
}
private var appearanceRows: [RowProtocol] {
[
// Row<TitleCell>(id: "notifications", height: SettingsTheme.cellHeight, bind: { cell, _ in
// cell.bind(titleIcon: UIImage(named: "Notification Icon"), title: "settings.notifications".localized, showDisclosure: true)
// }, action: { [weak self] _ in
// self?.delegate.didTapNotifications()
// }),
Row<RightLabelCell>(id: "base_currency", height: .heightSingleLineCell, bind: { [weak self] cell, _ in
cell.bind(titleIcon: UIImage(named: "Currency Icon"), title: "settings.base_currency".localized, rightText: self?.currentBaseCurrency, showDisclosure: true)
}, action: { [weak self] _ in
self?.delegate.didTapBaseCurrency()
}),
Row<RightLabelCell>(id: "language", height: .heightSingleLineCell, bind: { [weak self] cell, _ in
cell.bind(titleIcon: UIImage(named: "Language Icon"), title: "settings.language".localized, rightText: self?.currentLanguage, showDisclosure: true)
}, action: { [weak self] _ in
self?.delegate.didTapLanguage()
}),
Row<ToggleCell>(id: "light_mode", height: .heightSingleLineCell, bind: { [unowned self] cell, _ in
cell.bind(titleIcon: UIImage(named: "Light Mode Icon"), title: "settings.light_mode".localized, isOn: self.lightMode, last: true, onToggle: { [weak self] isOn in
self?.delegate.didSwitch(lightMode: isOn)
})
})
]
}
private var aboutRows: [RowProtocol] {
[
Row<TitleCell>(id: "about", height: .heightSingleLineCell, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "About Icon"), title: "settings.about".localized, showDisclosure: true)
}, action: { [weak self] _ in
self?.delegate.didTapAbout()
}),
Row<TitleCell>(id: "tell_friends", height: .heightSingleLineCell, autoDeselect: true, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Tell Friends Icon"), title: "settings.tell_friends".localized, showDisclosure: true)
}, action: { [weak self] _ in
self?.delegate.didTapTellFriends()
}),
Row<TitleCell>(id: "report_problem", height: .heightSingleLineCell, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Report Problem Icon"), title: "settings.report_problem".localized, showDisclosure: true, last: true)
}, action: { [weak self] _ in
self?.delegate.didTapReportProblem()
})
]
}
private var debugRows: [RowProtocol] {
[
Row<TitleCell>(id: "debug_realm_info", height: .heightSingleLineCell, autoDeselect: true, bind: { cell, _ in
cell.bind(titleIcon: UIImage(named: "Bug Icon"), title: "Show Realm Info", showDisclosure: false, last: false)
}, action: { [weak self] _ in
self?.showRealmInfo()
})
]
}
private var footer: ViewState<MainSettingsFooter> {
.cellType(hash: "about_footer", binder: { [weak self] view in
view.bind(appVersion: self?.appVersion) { [weak self] in
self?.delegate.didTapCompanyLink()
}
}, dynamicHeight: { _ in
194
})
}
private func showRealmInfo() {
for wallet in App.shared.walletManager.wallets {
print("\nINFO FOR \(wallet.coin.code):")
if let adapter = App.shared.adapterManager.adapter(for: wallet) {
print(adapter.debugInfo)
}
}
}
}
extension MainSettingsViewController: SectionsDataSource {
func buildSections() -> [SectionProtocol] {
var sections: [SectionProtocol] = [
Section(id: "security_settings", headerState: .margin(height: .margin3x), rows: securityRows),
Section(id: "appearance_settings", headerState: .margin(height: .margin8x), rows: appearanceRows),
Section(id: "about", headerState: .margin(height: .margin8x), footerState: footer, rows: aboutRows)
]
#if DEBUG
sections.append(Section(id: "debug", headerState: .margin(height: 50), footerState: .margin(height: 20), rows: debugRows))
#endif
return sections
}
}
extension MainSettingsViewController: IMainSettingsView {
func refresh() {
tableView.reload()
}
func set(allBackedUp: Bool) {
self.allBackedUp = allBackedUp
}
func set(currentBaseCurrency: String) {
self.currentBaseCurrency = currentBaseCurrency
}
func set(currentLanguage: String?) {
self.currentLanguage = currentLanguage
}
func set(lightMode: Bool) {
self.lightMode = lightMode
}
func set(appVersion: String) {
self.appVersion = appVersion
}
}
| 39.056872 | 205 | 0.624075 |
9cb5593b699d9499a5bb34d55b3512e4b01c5afb | 114 | import Foundation
public protocol PropertiesViewBorder {
func set(about viewModel: AboutPropertyViewModel)
}
| 19 | 53 | 0.815789 |
083243596d4b978235fd92137c220603280181dc | 646 | /**
* Copyright (c) 2021 Dustin Collins (Strega's Gate)
* All Rights Reserved.
* Licensed under Apache License v2.0
*
* Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate
*/
import WinSDK
public struct D3DHitGroupDescription {
public typealias RawValue = WinSDK.D3D12_HIT_GROUP_DESC
internal var rawValue: RawValue
internal init(_ rawValue: RawValue) {
self.rawValue = rawValue
}
}
//MARK: - Original Style API
#if !Direct3D12ExcludeOriginalStyleAPI
@available(*, deprecated, renamed: "D3DHitGroupDescription")
public typealias D3D12_HIT_GROUP_DESC = D3DHitGroupDescription
#endif
| 22.275862 | 79 | 0.744582 |
087fa201daa887b3de4ad1a98d75b6cff785c38c | 353 | public struct ConcreteRequest {
var fragment: ReaderFragment
var operation: NormalizationOperation
var params: RequestParameters
public init(fragment: ReaderFragment, operation: NormalizationOperation, params: RequestParameters) {
self.fragment = fragment
self.operation = operation
self.params = params
}
}
| 29.416667 | 105 | 0.725212 |
1a7dc83e3f05a92f041b642ea74d86b4299fe4aa | 922 | //
// SaldoComplication.swift
// WatchApp WatchKit Extension
//
// Created by Samuel Ivarsson on 2022-04-10.
// Copyright © 2022 Samuel Ivarsson. All rights reserved.
//
import SwiftUI
import ClockKit
let userDefaults: UserDefaults = UserDefaults(suiteName: "group.com.samuelivarsson.Swedbank-Widget")!
struct SaldoComplication {
let saldo: CLKSimpleTextProvider = CLKSimpleTextProvider(text: true ? "1237,39 SEK" : (userDefaults.string(forKey: "GDBelopp") ?? ""))
let lastUpdate: CLKSimpleTextProvider = CLKSimpleTextProvider(text: "Senast uppdaterad: 19:24")
}
struct SaldoComplication_Previews: PreviewProvider {
static var previews: some View {
Group {
CLKComplicationTemplateGraphicCornerStackText(
innerTextProvider: SaldoComplication().saldo,
outerTextProvider: CLKSimpleTextProvider(text: "")
).previewContext()
}
}
}
| 31.793103 | 138 | 0.708243 |
89881ed721e761bc8d1f3c3c075b90063a2f5065 | 2,983 | public enum OptimizerType : String, Codable {
case sgd, adam
var metatype: Optimizer.Type {
switch self {
case .sgd:
return SGD.self
case .adam:
return Adam.self
}
}
}
public protocol Optimizer : Codable {
static var type: OptimizerType { get }
}
public struct SGD : Optimizer {
public static let type = OptimizerType.sgd
public let learningRateDefault: Double
public let learningRateMax: Double
public let miniBatchSizeDefault: UInt
public let miniBatchSizeRange: [UInt]
public let momentumDefault: Double
public let momentumMax: Double
public init(learningRateDefault: Double, learningRateMax: Double, miniBatchSizeDefault: UInt, miniBatchSizeRange: [UInt], momentumDefault: Double, momentumMax: Double) {
self.learningRateDefault = learningRateDefault
self.learningRateMax = learningRateMax
self.miniBatchSizeDefault = miniBatchSizeDefault
self.miniBatchSizeRange = miniBatchSizeRange
self.momentumDefault = momentumDefault
self.momentumMax = momentumMax
}
}
public struct Adam : Optimizer {
public static let type = OptimizerType.adam
public let learningRateDefault: Double
public let learningRateMax: Double
public let miniBatchSizeDefault: UInt
public let miniBatchSizeRange: [UInt]
public let beta1Default: Double
public let beta1Max: Double
public let beta2Default: Double
public let beta2Max: Double
public let epsDefault: Double
public let epsMax: Double
public init(learningRateDefault: Double, learningRateMax: Double, miniBatchSizeDefault: UInt, miniBatchSizeRange: [UInt], beta1Default: Double, beta1Max: Double, beta2Default: Double, beta2Max: Double, epsDefault: Double, epsMax: Double) {
self.learningRateDefault = learningRateDefault
self.learningRateMax = learningRateMax
self.miniBatchSizeDefault = miniBatchSizeDefault
self.miniBatchSizeRange = miniBatchSizeRange
self.beta1Default = beta1Default
self.beta1Max = beta1Max
self.beta2Default = beta2Default
self.beta2Max = beta2Max
self.epsDefault = epsDefault
self.epsMax = epsMax
}
}
struct AnyOptimizer : Codable {
var base: Optimizer
init(_ base: Optimizer) {
self.base = base
}
private enum CodingKeys : CodingKey {
case type, base
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(OptimizerType.self, forKey: .type)
self.base = try type.metatype.init(from: container.superDecoder(forKey: .base))
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type(of: base).type, forKey: .type)
try base.encode(to: container.superEncoder(forKey: .base))
}
}
| 32.78022 | 243 | 0.699296 |
bf0e1be80af4216a253d84cb7a1decf37276b061 | 1,729 | //
// CafeSpotUITests.swift
// CafeSpotUITests
//
// Created by 천지운 on 2020/08/12.
// Copyright © 2020 Giftbot. All rights reserved.
//
import XCTest
class CafeSpotUITests: XCTestCase {
var app: XCUIApplication!
override func setUpWithError() throws {
self.app = XCUIApplication() // 앱을 간접적으로 사용 할 수 있게 해줌
self.app.launch()
// XCUIElement => UI element에 대한 프록시
// XCUIElementQuery
let addButton = app.navigationBars.buttons["addButton"]
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_테스트할_것() {
}
func testExample() throws {
// UI tests must launch the application that they test.
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.018519 | 182 | 0.643146 |
db2cb8e013833018738700ee1feb9c2d1615be03 | 453 | // This source file is part of the Swift.org open source project
// 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: not %target-swift-frontend %s -typecheck
struct d<T where H:b{
class B
let f=e
struct B{var _=B
| 34.846154 | 79 | 0.748344 |
9bc1807a9c6cbb7347b417331a40b41fc75dade6 | 540 | //
// TWStreamMarker.swift
//
// Created by Øyvind Hauge on 03/08/2020.
// Copyright © 2020 Øyvind Hauge. All rights reserved.
//
import Foundation
public struct TWStreamMarker: Codable {
/// Unique ID of the marker.
public var id: String
/// Description of the marker.
public var description: String
/// Relative offset (in seconds) of the marker, from the beginning of the stream.
public var positionSeconds: Int
/// RFC3339 timestamp of the marker.
public var createdAt: String
}
| 22.5 | 85 | 0.67037 |
db05cf884a2e8db0432fe18f903fee20dc75aced | 1,061 | //
// ContentView.swift
// SwiftUITester
//
// Created by Bjørn Inge Berg on 14/03/2020.
// Copyright © 2020 Bjørn Inge Vikhammermo Berg. All rights reserved.
//
import SwiftUI
import SwiftUICharts
struct ContentView: View {
var body: some View {
TabView {
MainContentView()
.tabItem {
Text("Glucose")
Image(systemName: "heart.circle")
}
SettingsContentView()
.tabItem {
Text("Settings")
Image(systemName: "list.dash")
}
}
}
}
var glucose = 5
struct MainContentView: View {
var body: some View {
VStack {
Text("Glucose: \(glucose)")
LineView(data: [8,23,54,32,12,37,7,23,439], title: nil, legend: nil)
}
}
}
struct SettingsContentView: View {
var body: some View {
Text("Some Settings content view")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 17.683333 | 80 | 0.545712 |
f519cadea2fcb71706c74900c48b0f4cdd3b4387 | 8,888 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that can be compared using the relational operators `<`, `<=`, `>=`,
/// and `>`.
///
/// The `Comparable` protocol is used for types that have an inherent order,
/// such as numbers and strings. Many types in the standard library already
/// conform to the `Comparable` protocol. Add `Comparable` conformance to your
/// own custom types when you want to be able to compare instances using
/// relational operators or use standard library methods that are designed for
/// `Comparable` types.
///
/// The most familiar use of relational operators is to compare numbers, as in
/// the following example:
///
/// let currentTemp = 73
///
/// if currentTemp >= 90 {
/// print("It's a scorcher!")
/// } else if currentTemp < 65 {
/// print("Might need a sweater today.")
/// } else {
/// print("Seems like picnic weather!")
/// }
/// // Prints "Seems like picnic weather!"
///
/// You can use special versions of some sequence and collection operations
/// when working with a `Comparable` type. For example, if your array's
/// elements conform to `Comparable`, you can call the `sort()` method without
/// using arguments to sort the elements of your array in ascending order.
///
/// var measurements = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
/// measurements.sort()
/// print(measurements)
/// // Prints "[1.1, 1.2, 1.2, 1.3, 1.5, 1.5, 2.9]"
///
/// Conforming to the Comparable Protocol
/// =====================================
///
/// Types with Comparable conformance implement the less-than operator (`<`)
/// and the equal-to operator (`==`). These two operations impose a strict
/// total order on the values of a type, in which exactly one of the following
/// must be true for any two values `a` and `b`:
///
/// - `a == b`
/// - `a < b`
/// - `b < a`
///
/// In addition, the following conditions must hold:
///
/// - `a < a` is always `false` (Irreflexivity)
/// - `a < b` implies `!(b < a)` (Asymmetry)
/// - `a < b` and `b < c` implies `a < c` (Transitivity)
///
/// To add `Comparable` conformance to your custom types, define the `<` and
/// `==` operators as static methods of your types. The `==` operator is a
/// requirement of the `Equatable` protocol, which `Comparable` extends---see
/// that protocol's documentation for more information about equality in
/// Swift. Because default implementations of the remainder of the relational
/// operators are provided by the standard library, you'll be able to use
/// `!=`, `>`, `<=`, and `>=` with instances of your type without any further
/// code.
///
/// As an example, here's an implementation of a `Date` structure that stores
/// the year, month, and day of a date:
///
/// struct Date {
/// let year: Int
/// let month: Int
/// let day: Int
/// }
///
/// To add `Comparable` conformance to `Date`, first declare conformance to
/// `Comparable` and implement the `<` operator function.
///
/// extension Date: Comparable {
/// static func < (lhs: Date, rhs: Date) -> Bool {
/// if lhs.year != rhs.year {
/// return lhs.year < rhs.year
/// } else if lhs.month != rhs.month {
/// return lhs.month < rhs.month
/// } else {
/// return lhs.day < rhs.day
/// }
/// }
///
/// This function uses the least specific nonmatching property of the date to
/// determine the result of the comparison. For example, if the two `year`
/// properties are equal but the two `month` properties are not, the date with
/// the lesser value for `month` is the lesser of the two dates.
///
/// Next, implement the `==` operator function, the requirement inherited from
/// the `Equatable` protocol.
///
/// static func == (lhs: Date, rhs: Date) -> Bool {
/// return lhs.year == rhs.year && lhs.month == rhs.month
/// && lhs.day == rhs.day
/// }
/// }
///
/// Two `Date` instances are equal if each of their corresponding properties is
/// equal.
///
/// Now that `Date` conforms to `Comparable`, you can compare instances of the
/// type with any of the relational operators. The following example compares
/// the date of the first moon landing with the release of David Bowie's song
/// "Space Oddity":
///
/// let spaceOddity = Date(year: 1969, month: 7, day: 11) // July 11, 1969
/// let moonLanding = Date(year: 1969, month: 7, day: 20) // July 20, 1969
/// if moonLanding > spaceOddity {
/// print("Major Tom stepped through the door first.")
/// } else {
/// print("David Bowie was following in Neil Armstrong's footsteps.")
/// }
/// // Prints "Major Tom stepped through the door first."
///
/// Note that the `>` operator provided by the standard library is used in this
/// example, not the `<` operator implemented above.
///
/// - Note: A conforming type may contain a subset of values which are treated
/// as exceptional---that is, values that are outside the domain of
/// meaningful arguments for the purposes of the `Comparable` protocol. For
/// example, the special "not a number" value for floating-point types
/// (`FloatingPoint.nan`) compares as neither less than, greater than, nor
/// equal to any normal floating-point value. Exceptional values need not
/// take part in the strict total order.
public protocol Comparable: Equatable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func < (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func <= (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func >= (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func > (lhs: Self, rhs: Self) -> Bool
}
extension Comparable {
/// Returns a Boolean value indicating whether the value of the first argument
/// is greater than that of the second argument.
///
/// This is the default implementation of the greater-than operator (`>`) for
/// any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@inlinable
public static func > (lhs: Self, rhs: Self) -> Bool {
return rhs < lhs
}
/// Returns a Boolean value indicating whether the value of the first argument
/// is less than or equal to that of the second argument.
///
/// This is the default implementation of the less-than-or-equal-to
/// operator (`<=`) for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@inlinable
public static func <= (lhs: Self, rhs: Self) -> Bool {
return !(rhs < lhs)
}
/// Returns a Boolean value indicating whether the value of the first argument
/// is greater than or equal to that of the second argument.
///
/// This is the default implementation of the greater-than-or-equal-to operator
/// (`>=`) for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: `true` if `lhs` is greater than or equal to `rhs`; otherwise,
/// `false`.
@inlinable
public static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
}
| 40.217195 | 81 | 0.624212 |
2f5f1e05da48574b93ec9f3e7a2f44b4218bb1b2 | 10,275 | //
// SWHomePageCell.swift
// LiteraryHeaven
//
// Created by SanW on 2017/7/20.
// Copyright © 2017年 ONON. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
class SWHomePageCell: UITableViewCell {
// 懒加载子视图
lazy var titleLab : UILabel = {
let titleLab = UILabel()
titleLab.font = kFont3
titleLab.numberOfLines = 2
titleLab.textColor = kColor11
return titleLab
}()
lazy var nickLab : UILabel = {
let nickLab = UILabel()
nickLab.font = kFont4
nickLab.textColor = kColor12
nickLab.textAlignment = .center
return nickLab
}()
lazy var clickLab :UILabel = {
let clickLab = UILabel()
clickLab.font = kFont4
clickLab.textColor = kColor7
return clickLab
}()
lazy var iconImage : UIImageView = {
let iconImage = UIImageView()
return iconImage
}()
lazy var articleImage : UIImageView = {
let articleImage = UIImageView()
return articleImage
}()
lazy var bgView : UIView = {
let bgView = UIView()
bgView.backgroundColor = UIColor(colorLiteralRed: 255/255, green: 255/255, blue: 255/255, alpha: 0.8)
return bgView
}()
lazy var liveBgView : UIView = {
let liveBgView = UIView()
liveBgView.backgroundColor = UIColor.clear
liveBgView.layer.borderColor = kColor8.cgColor
liveBgView.layer.borderWidth = 1
return liveBgView
}()
lazy var lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = kColor3
return lineView
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super .init(style: style, reuseIdentifier: reuseIdentifier)
// 创建子视图
createSubView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func homePageCell (tableView:UITableView) -> SWHomePageCell?{
let identifier = "SWHomePageCell"
var cell : SWHomePageCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? SWHomePageCell
if cell == nil {
cell = SWHomePageCell.init(style: .default, reuseIdentifier: identifier)
}
return cell
}
/// 拿到数据源给相应cell赋值布局
var articleMode : SWArticleModel? {
didSet{
addData()
addLayout()
}
}
}
/// 添加子控件
extension SWHomePageCell {
fileprivate func createSubView() {
contentView.addSubview(articleImage)
contentView.addSubview(bgView)
contentView.addSubview(liveBgView)
contentView.addSubview(titleLab)
contentView.addSubview(nickLab)
contentView.addSubview(iconImage)
contentView.addSubview(clickLab)
contentView.addSubview(lineView)
}
}
/// 赋值
extension SWHomePageCell {
fileprivate func addData() {
titleLab.text = articleMode?.articleTitle
iconImage.image = UIImage(named: "photo")
if ((articleMode?.iconImage) != nil) {
iconImage.kf.setImage(with: URL(string: (articleMode?.iconImage)!))
}else{
iconImage.image = UIImage(named: "photo")
}
if ((articleMode?.articleImage) != nil) {
articleImage.kf.setImage(with: URL(string: (articleMode?.articleImage)!))
}
else{
articleImage.image = UIImage(named: "LiteraryHeaven")
}
nickLab.text = articleMode?.authorNick
clickLab.text = articleMode?.clickCount
}
}
/// 布局
extension SWHomePageCell {
fileprivate func addLayout() {
let imageW : CGFloat = 100
let imageH : CGFloat = 75
let margin : CGFloat = 12
let iconW : CGFloat = 30
let topH : CGFloat = 75
if (articleMode?.isRecommend)! == false {
clickLab.isHidden = false
bgView.isHidden = true
liveBgView.isHidden = true
articleImage.snp.remakeConstraints { (make) in
make.right.equalTo(contentView.snp.right).offset(-margin)
make.width.equalTo(imageW)
make.height.equalTo(imageH)
make.centerY.equalTo(contentView)
}
titleLab.snp.remakeConstraints { (make) in
make.left.equalTo(contentView).offset(margin)
make.top.equalTo(articleImage)
make.right.equalTo(articleImage.snp.left).offset(-margin)
}
iconImage.snp.remakeConstraints { (make) in
make.left.equalTo(titleLab)
make.top.equalTo(titleLab.snp.bottom).offset(8)
make.width.height.equalTo(iconW)
}
nickLab.snp.remakeConstraints { (make) in
make.left.equalTo(iconImage.snp.right).offset(margin / 2)
make.width.equalTo(40)
make.centerY.equalTo(iconImage)
}
clickLab.snp.remakeConstraints { (make) in
make.left.equalTo(nickLab.snp.right).offset(0)
make.right.equalTo(articleImage.snp.left).offset(-(margin / 2))
make.centerY.equalTo(nickLab)
}
}
else{
clickLab.isHidden = true
bgView.isHidden = false
liveBgView.isHidden = false
articleImage.snp.remakeConstraints({ (make) in
make.left.equalTo(contentView).offset(kLeftMargin)
make.right.equalTo(contentView).offset(-kLeftMargin)
make.height.equalTo(contentView)
})
bgView.snp.remakeConstraints({ (make) in
make.left.equalTo(contentView).offset(margin)
make.right.equalTo(contentView).offset(-margin)
make.height.equalTo(imageW)
make.centerY.equalTo(contentView)
})
liveBgView.snp.remakeConstraints({ (make) in
make.left.equalTo(bgView).offset(8)
make.right.equalTo(bgView).offset(-8)
make.top.equalTo(bgView).offset(8)
make.bottom.equalTo(bgView).offset(-8)
})
titleLab.snp.remakeConstraints({ (make) in
make.left.equalTo(liveBgView).offset(8)
make.right.equalTo(liveBgView).offset(-8)
make.top.equalTo(liveBgView).offset(8)
})
iconImage.snp.remakeConstraints { (make) in
make.left.equalTo(titleLab)
make.top.equalTo(titleLab.snp.bottom).offset(8)
make.width.height.equalTo(iconW)
}
nickLab.snp.remakeConstraints { (make) in
make.left.equalTo(iconImage.snp.right).offset(margin)
make.centerY.equalTo(iconImage)
}
}
lineView.snp.makeConstraints { (make) in
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.bottom.equalTo(self.contentView).offset(-1)
make.height.equalTo(1)
}
iconImage.layer.cornerRadius = iconW / 2
iconImage.layer.masksToBounds = true
}
}
class SWHomaPageSectionHeadView: UITableViewHeaderFooterView {
enum sectionHeadType {
case nomal
case recommend
}
lazy var titleBtn : UIButton = {
let titleBtn = UIButton(type: .custom)
titleBtn.setImage(UIImage(named:"home_category"), for: .normal)
titleBtn.titleLabel?.font = kFont3
titleBtn.setTitleColor(kColor8, for: .normal)
return titleBtn
}()
lazy var moreBtn : UIButton = {
let moreBtn = UIButton(type: .custom)
moreBtn.setImage(UIImage(named:"more"), for: .normal)
moreBtn.setTitle("更多", for: .normal)
moreBtn.titleLabel?.font = kFont4
moreBtn.setTitleColor(kColor7, for: .normal)
return moreBtn
}()
lazy var lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = kColor3
return lineView
}()
var sectionTitle : String?{
didSet{
addData()
addLayout()
}
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
// 创建子控件
contentView.addSubview(titleBtn)
contentView.addSubview(moreBtn)
contentView.addSubview(lineView)
contentView.backgroundColor = kColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addData() {
titleBtn.setTitle(sectionTitle, for: .normal)
}
func addLayout() {
titleBtn.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(kLeftMargin)
make.centerY.equalTo(contentView)
}
moreBtn.snp.makeConstraints { (make) in
make.right.equalTo(contentView).offset(-kLeftMargin)
make.centerY.equalTo(contentView)
}
moreBtn.snp.makeConstraints { (make) in
make.right.equalTo(contentView).offset(-kLeftMargin)
make.centerY.equalTo(contentView)
}
moreBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -30, bottom: 0, right: 0)
moreBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: (moreBtn.titleLabel?.frame.size.width)!, bottom: 0, right: 0)
lineView.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(kLeftMargin)
make.right.equalTo(contentView).offset(-kLeftMargin)
make.height.equalTo(1)
make.bottom.equalTo(contentView)
}
}
}
extension SWHomaPageSectionHeadView{
class func sectionHeaderViewIdtifer(tableView : UITableView) -> SWHomaPageSectionHeadView?{
let identifier = NSStringFromClass(self)
var headerView : SWHomaPageSectionHeadView? = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier) as? SWHomaPageSectionHeadView
if headerView == nil {
headerView = SWHomaPageSectionHeadView.init(reuseIdentifier: identifier)
}
return headerView
}
}
| 35.677083 | 153 | 0.600584 |
72b1d1c8bbf38e0c49f46e7a768c58ce883fbfb0 | 32,419 | import Foundation
import PathKit
import ProjectSpec
import XcodeProj
import Core
struct SourceFile {
let path: Path
let fileReference: PBXFileElement
let buildFile: PBXBuildFile
let buildPhase: BuildPhaseSpec?
}
class SourceGenerator {
var rootGroups: Set<PBXFileElement> = []
private let projectDirectory: Path?
private var fileReferencesByPath: [String: PBXFileElement] = [:]
private var groupsByPath: [Path: PBXGroup] = [:]
private var variantGroupsByPath: [Path: PBXVariantGroup] = [:]
private var localPackageGroup: PBXGroup?
private let project: Project
let pbxProj: PBXProj
private var defaultExcludedFiles = [
".DS_Store",
]
private let defaultExcludedExtensions = [
"orig",
]
private(set) var knownRegions: Set<String> = []
init(project: Project, pbxProj: PBXProj, projectDirectory: Path?) {
self.project = project
self.pbxProj = pbxProj
self.projectDirectory = projectDirectory
}
private func resolveGroupPath(_ path: Path, isTopLevelGroup: Bool) -> String {
if isTopLevelGroup, let relativePath = try? path.relativePath(from: projectDirectory ?? project.basePath).string {
return relativePath
} else {
return path.lastComponent
}
}
@discardableResult
func addObject<T: PBXObject>(_ object: T, context: String? = nil) -> T {
pbxProj.add(object: object)
object.context = context
return object
}
func createLocalPackage(path: Path) throws {
if localPackageGroup == nil {
let groupName = project.options.localPackagesGroup ?? "Packages"
localPackageGroup = addObject(PBXGroup(sourceTree: .sourceRoot, name: groupName))
rootGroups.insert(localPackageGroup!)
}
let absolutePath = project.basePath + path.normalize()
// Get the local package's relative path from the project root
let fileReferencePath = try? absolutePath.relativePath(from: projectDirectory ?? project.basePath).string
let fileReference = addObject(
PBXFileReference(
sourceTree: .sourceRoot,
name: absolutePath.lastComponent,
lastKnownFileType: "folder",
path: fileReferencePath
)
)
localPackageGroup!.children.append(fileReference)
}
/// Collects an array complete of all `SourceFile` objects that make up the target based on the provided `TargetSource` definitions.
///
/// - Parameters:
/// - targetType: The type of target that the source files should belong to.
/// - sources: The array of sources defined as part of the targets spec.
/// - buildPhases: A dictionary containing any build phases that should be applied to source files at specific paths in the event that the associated `TargetSource` didn't already define a `buildPhase`. Values from this dictionary are used in cases where the project generator knows more about a file than the spec/filesystem does (i.e if the file should be treated as the targets Info.plist and so on).
func getAllSourceFiles(targetType: PBXProductType, sources: [TargetSource], buildPhases: [Path : BuildPhaseSpec]) throws -> [SourceFile] {
try sources.flatMap { try getSourceFiles(targetType: targetType, targetSource: $0, buildPhases: buildPhases) }
}
// get groups without build files. Use for Project.fileGroups
func getFileGroups(path: String) throws {
_ = try getSourceFiles(targetType: .none, targetSource: TargetSource(path: path), buildPhases: [:])
}
func getFileType(path: Path) -> FileType? {
if let fileExtension = path.extension {
return project.options.fileTypes[fileExtension] ?? FileType.defaultFileTypes[fileExtension]
} else {
return nil
}
}
func generateSourceFile(targetType: PBXProductType, targetSource: TargetSource, path: Path, fileReference: PBXFileElement? = nil, buildPhases: [Path: BuildPhaseSpec]) -> SourceFile {
let fileReference = fileReference ?? fileReferencesByPath[path.string.lowercased()]!
var settings: [String: Any] = [:]
let fileType = getFileType(path: path)
var attributes: [String] = targetSource.attributes + (fileType?.attributes ?? [])
var chosenBuildPhase: BuildPhaseSpec?
var compilerFlags: String = ""
let assetTags: [String] = targetSource.resourceTags + (fileType?.resourceTags ?? [])
let headerVisibility = targetSource.headerVisibility ?? .public
if let buildPhase = targetSource.buildPhase {
chosenBuildPhase = buildPhase
} else if resolvedTargetSourceType(for: targetSource, at: path) == .folder {
chosenBuildPhase = .resources
} else if let buildPhase = buildPhases[path] {
chosenBuildPhase = buildPhase
} else {
chosenBuildPhase = getDefaultBuildPhase(for: path, targetType: targetType)
}
if chosenBuildPhase == .headers && targetType == .staticLibrary {
// Static libraries don't support the header build phase
// For public headers they need to be copied
if headerVisibility == .public {
chosenBuildPhase = .copyFiles(BuildPhaseSpec.CopyFilesSettings(
destination: .productsDirectory,
subpath: "include/$(PRODUCT_NAME)",
phaseOrder: .preCompile
))
} else {
chosenBuildPhase = nil
}
}
if chosenBuildPhase == .headers {
if headerVisibility != .project {
// Xcode doesn't write the default of project
attributes.append(headerVisibility.settingName)
}
}
if let flags = fileType?.compilerFlags {
compilerFlags += flags.joined(separator: " ")
}
if !targetSource.compilerFlags.isEmpty {
if !compilerFlags.isEmpty {
compilerFlags += " "
}
compilerFlags += targetSource.compilerFlags.joined(separator: " ")
}
if chosenBuildPhase == .sources && !compilerFlags.isEmpty {
settings["COMPILER_FLAGS"] = compilerFlags
}
if !attributes.isEmpty {
settings["ATTRIBUTES"] = attributes
}
if chosenBuildPhase == .resources && !assetTags.isEmpty {
settings["ASSET_TAGS"] = assetTags
}
let buildFile = PBXBuildFile(file: fileReference, settings: settings.isEmpty ? nil : settings)
return SourceFile(
path: path,
fileReference: fileReference,
buildFile: buildFile,
buildPhase: chosenBuildPhase
)
}
func getContainedFileReference(path: Path) -> PBXFileElement {
let createIntermediateGroups = project.options.createIntermediateGroups
let parentPath = path.parent()
let fileReference = getFileReference(path: path, inPath: parentPath)
let parentGroup = getGroup(
path: parentPath,
mergingChildren: [fileReference],
createIntermediateGroups: createIntermediateGroups,
hasCustomParent: false,
isBaseGroup: true
)
if createIntermediateGroups {
createIntermediaGroups(for: parentGroup, at: parentPath)
}
return fileReference
}
func getFileReference(path: Path, inPath: Path, name: String? = nil, sourceTree: PBXSourceTree = .group, lastKnownFileType: String? = nil) -> PBXFileElement {
let fileReferenceKey = path.string.lowercased()
if let fileReference = fileReferencesByPath[fileReferenceKey] {
return fileReference
} else {
let fileReferencePath = (try? path.relativePath(from: inPath)) ?? path
var fileReferenceName: String? = name ?? fileReferencePath.lastComponent
if fileReferencePath.string == fileReferenceName {
fileReferenceName = nil
}
let lastKnownFileType = lastKnownFileType ?? Xcode.fileType(path: path)
if path.extension == "xcdatamodeld" {
let versionedModels = (try? path.children()) ?? []
// Sort the versions alphabetically
let sortedPaths = versionedModels
.filter { $0.extension == "xcdatamodel" }
.sorted { $0.string.localizedStandardCompare($1.string) == .orderedAscending }
let modelFileReferences =
sortedPaths.map { path in
addObject(
PBXFileReference(
sourceTree: .group,
lastKnownFileType: "wrapper.xcdatamodel",
path: path.lastComponent
)
)
}
// If no current version path is found we fall back to alphabetical
// order by taking the last item in the sortedPaths array
let currentVersionPath = findCurrentCoreDataModelVersionPath(using: versionedModels) ?? sortedPaths.last
let currentVersion: PBXFileReference? = {
guard let indexOf = sortedPaths.firstIndex(where: { $0 == currentVersionPath }) else { return nil }
return modelFileReferences[indexOf]
}()
let versionGroup = addObject(XCVersionGroup(
currentVersion: currentVersion,
path: fileReferencePath.string,
sourceTree: sourceTree,
versionGroupType: "wrapper.xcdatamodel",
children: modelFileReferences
))
fileReferencesByPath[fileReferenceKey] = versionGroup
return versionGroup
} else {
// For all extensions other than `xcdatamodeld`
let fileReference = addObject(
PBXFileReference(
sourceTree: sourceTree,
name: fileReferenceName,
lastKnownFileType: lastKnownFileType,
path: fileReferencePath.string
)
)
fileReferencesByPath[fileReferenceKey] = fileReference
return fileReference
}
}
}
/// returns a default build phase for a given path. This is based off the filename
private func getDefaultBuildPhase(for path: Path, targetType: PBXProductType) -> BuildPhaseSpec? {
if let buildPhase = getFileType(path: path)?.buildPhase {
return buildPhase
}
if let fileExtension = path.extension {
switch fileExtension {
case "modulemap":
guard targetType == .staticLibrary else { return nil }
return .copyFiles(BuildPhaseSpec.CopyFilesSettings(
destination: .productsDirectory,
subpath: "include/$(PRODUCT_NAME)",
phaseOrder: .preCompile
))
default:
return .resources
}
}
return nil
}
/// Create a group or return an existing one at the path.
/// Any merged children are added to a new group or merged into an existing one.
private func getGroup(path: Path, name: String? = nil, mergingChildren children: [PBXFileElement], createIntermediateGroups: Bool, hasCustomParent: Bool, isBaseGroup: Bool) -> PBXGroup {
let groupReference: PBXGroup
if let cachedGroup = groupsByPath[path] {
var cachedGroupChildren = cachedGroup.children
for child in children {
// only add the children that aren't already in the cachedGroup
// Check equality by path and sourceTree because XcodeProj.PBXObject.== is very slow.
if !cachedGroupChildren.contains(where: { $0.name == child.name && $0.path == child.path && $0.sourceTree == child.sourceTree }) {
cachedGroupChildren.append(child)
child.parent = cachedGroup
}
}
cachedGroup.children = cachedGroupChildren
groupReference = cachedGroup
} else {
// lives outside the project base path
let isOutOfBasePath = !path.absolute().string.contains(project.basePath.absolute().string)
// whether the given path is a strict parent of the project base path
// e.g. foo/bar is a parent of foo/bar/baz, but not foo/baz
let isParentOfBasePath = isOutOfBasePath && ((try? path.isParent(of: project.basePath)) == true)
// has no valid parent paths
let isRootPath = (isBaseGroup && isOutOfBasePath && isParentOfBasePath) || path.parent() == project.basePath
// is a top level group in the project
let isTopLevelGroup = !hasCustomParent && ((isBaseGroup && !createIntermediateGroups) || isRootPath || isParentOfBasePath)
let groupName = name ?? path.lastComponent
let groupPath = resolveGroupPath(path, isTopLevelGroup: hasCustomParent || isTopLevelGroup)
let group = PBXGroup(
children: children,
sourceTree: .group,
name: groupName != groupPath ? groupName : nil,
path: groupPath
)
groupReference = addObject(group)
groupsByPath[path] = groupReference
if isTopLevelGroup {
rootGroups.insert(groupReference)
}
}
return groupReference
}
/// Creates a variant group or returns an existing one at the path
private func getVariantGroup(path: Path, inPath: Path) -> PBXVariantGroup {
let variantGroup: PBXVariantGroup
if let cachedGroup = variantGroupsByPath[path] {
variantGroup = cachedGroup
} else {
let group = PBXVariantGroup(
sourceTree: .group,
name: path.lastComponent
)
variantGroup = addObject(group)
variantGroupsByPath[path] = variantGroup
}
return variantGroup
}
/// Collects all the excluded paths within the targetSource
private func getSourceMatches(targetSource: TargetSource, patterns: [String]) -> Set<Path> {
let rootSourcePath = project.basePath + targetSource.path
return Set(
patterns.map { pattern in
guard !pattern.isEmpty else { return [] }
return Glob(pattern: "\(rootSourcePath)/\(pattern)")
.map { Path($0) }
.map {
guard $0.isDirectory else {
return [$0]
}
return (try? $0.recursiveChildren()) ?? []
}
.reduce([], +)
}
.reduce([], +)
)
}
/// Checks whether the path is not in any default or TargetSource excludes
func isIncludedPath(_ path: Path, excludePaths: Set<Path>, includePaths: Set<Path>) -> Bool {
!defaultExcludedFiles.contains(where: { path.lastComponent.contains($0) })
&& !(path.extension.map(defaultExcludedExtensions.contains) ?? false)
&& !excludePaths.contains(path)
// If includes is empty, it's included. If it's not empty, the path either needs to match exactly, or it needs to be a direct parent of an included path.
&& (includePaths.isEmpty || includePaths.contains(where: { includedFile in
if path == includedFile { return true }
return includedFile.description.contains(path.description)
}))
}
/// Gets all the children paths that aren't excluded
private func getSourceChildren(targetSource: TargetSource, dirPath: Path, excludePaths: Set<Path>, includePaths: Set<Path>) throws -> [Path] {
try dirPath.children()
.filter {
if $0.isDirectory {
let children = try $0.children()
if children.isEmpty {
return project.options.generateEmptyDirectories
}
return !children
.filter { self.isIncludedPath($0, excludePaths: excludePaths, includePaths: includePaths) }
.isEmpty
} else if $0.isFile {
return self.isIncludedPath($0, excludePaths: excludePaths, includePaths: includePaths)
} else {
return false
}
}
}
/// creates all the source files and groups they belong to for a given targetSource
private func getGroupSources(
targetType: PBXProductType,
targetSource: TargetSource,
path: Path,
isBaseGroup: Bool,
hasCustomParent: Bool,
excludePaths: Set<Path>,
includePaths: Set<Path>,
buildPhases: [Path: BuildPhaseSpec]
) throws -> (sourceFiles: [SourceFile], groups: [PBXGroup]) {
let children = try getSourceChildren(targetSource: targetSource, dirPath: path, excludePaths: excludePaths, includePaths: includePaths)
let createIntermediateGroups = targetSource.createIntermediateGroups ?? project.options.createIntermediateGroups
let nonLocalizedChildren = children.filter { $0.extension != "lproj" }
let directories = nonLocalizedChildren
.filter {
if let fileType = getFileType(path: $0) {
return !fileType.file
} else {
return $0.isDirectory && !Xcode.isDirectoryFileWrapper(path: $0)
}
}
let filePaths = nonLocalizedChildren
.filter {
if let fileType = getFileType(path: $0) {
return fileType.file
} else {
return $0.isFile || $0.isDirectory && Xcode.isDirectoryFileWrapper(path: $0)
}
}
let localisedDirectories = children
.filter { $0.extension == "lproj" }
var groupChildren: [PBXFileElement] = filePaths.map { getFileReference(path: $0, inPath: path) }
var allSourceFiles: [SourceFile] = filePaths.map {
generateSourceFile(targetType: targetType, targetSource: targetSource, path: $0, buildPhases: buildPhases)
}
var groups: [PBXGroup] = []
for path in directories {
let subGroups = try getGroupSources(
targetType: targetType,
targetSource: targetSource,
path: path,
isBaseGroup: false,
hasCustomParent: false,
excludePaths: excludePaths,
includePaths: includePaths,
buildPhases: buildPhases
)
guard !subGroups.sourceFiles.isEmpty || project.options.generateEmptyDirectories else {
continue
}
allSourceFiles += subGroups.sourceFiles
if let firstGroup = subGroups.groups.first {
groupChildren.append(firstGroup)
groups += subGroups.groups
} else if project.options.generateEmptyDirectories {
groups += subGroups.groups
}
}
// find the base localised directory
let baseLocalisedDirectory: Path? = {
func findLocalisedDirectory(by languageId: String) -> Path? {
localisedDirectories.first { $0.lastComponent == "\(languageId).lproj" }
}
return findLocalisedDirectory(by: "Base") ??
findLocalisedDirectory(by: NSLocale.canonicalLanguageIdentifier(from: project.options.developmentLanguage ?? "en"))
}()
knownRegions.formUnion(localisedDirectories.map { $0.lastComponentWithoutExtension })
// create variant groups of the base localisation first
var baseLocalisationVariantGroups: [PBXVariantGroup] = []
if let baseLocalisedDirectory = baseLocalisedDirectory {
let filePaths = try baseLocalisedDirectory.children()
.filter { self.isIncludedPath($0, excludePaths: excludePaths, includePaths: includePaths) }
.sorted()
for filePath in filePaths {
let variantGroup = getVariantGroup(path: filePath, inPath: path)
groupChildren.append(variantGroup)
baseLocalisationVariantGroups.append(variantGroup)
let sourceFile = generateSourceFile(targetType: targetType,
targetSource: targetSource,
path: filePath,
fileReference: variantGroup,
buildPhases: buildPhases)
allSourceFiles.append(sourceFile)
}
}
// add references to localised resources into base localisation variant groups
for localisedDirectory in localisedDirectories {
let localisationName = localisedDirectory.lastComponentWithoutExtension
let filePaths = try localisedDirectory.children()
.filter { self.isIncludedPath($0, excludePaths: excludePaths, includePaths: includePaths) }
.sorted { $0.lastComponent < $1.lastComponent }
for filePath in filePaths {
// find base localisation variant group
// ex: Foo.strings will be added to Foo.strings or Foo.storyboard variant group
let variantGroup = baseLocalisationVariantGroups
.first {
Path($0.name!).lastComponent == filePath.lastComponent
} ?? baseLocalisationVariantGroups.first {
Path($0.name!).lastComponentWithoutExtension == filePath.lastComponentWithoutExtension
}
let fileReference = getFileReference(
path: filePath,
inPath: path,
name: variantGroup != nil ? localisationName : filePath.lastComponent
)
if let variantGroup = variantGroup {
if !variantGroup.children.contains(fileReference) {
variantGroup.children.append(fileReference)
}
} else {
// add SourceFile to group if there is no Base.lproj directory
let sourceFile = generateSourceFile(targetType: targetType,
targetSource: targetSource,
path: filePath,
fileReference: fileReference,
buildPhases: buildPhases)
allSourceFiles.append(sourceFile)
groupChildren.append(fileReference)
}
}
}
let group = getGroup(
path: path,
mergingChildren: groupChildren,
createIntermediateGroups: createIntermediateGroups,
hasCustomParent: hasCustomParent,
isBaseGroup: isBaseGroup
)
if createIntermediateGroups {
createIntermediaGroups(for: group, at: path)
}
groups.insert(group, at: 0)
return (allSourceFiles, groups)
}
/// creates source files
private func getSourceFiles(targetType: PBXProductType, targetSource: TargetSource, buildPhases: [Path: BuildPhaseSpec]) throws -> [SourceFile] {
// generate excluded paths
let path = project.basePath + targetSource.path
let excludePaths = getSourceMatches(targetSource: targetSource, patterns: targetSource.excludes)
// generate included paths. Excluded paths will override this.
let includePaths = getSourceMatches(targetSource: targetSource, patterns: targetSource.includes)
let type = resolvedTargetSourceType(for: targetSource, at: path)
let customParentGroups = (targetSource.group ?? "").split(separator: "/").map { String($0) }
let hasCustomParent = !customParentGroups.isEmpty
let createIntermediateGroups = targetSource.createIntermediateGroups ?? project.options.createIntermediateGroups
var sourceFiles: [SourceFile] = []
let sourceReference: PBXFileElement
var sourcePath = path
switch type {
case .folder:
let fileReference = getFileReference(
path: path,
inPath: project.basePath,
name: targetSource.name ?? path.lastComponent,
sourceTree: .sourceRoot,
lastKnownFileType: "folder"
)
if !(createIntermediateGroups || hasCustomParent) || path.parent() == project.basePath {
rootGroups.insert(fileReference)
}
let sourceFile = generateSourceFile(targetType: targetType, targetSource: targetSource, path: path, buildPhases: buildPhases)
sourceFiles.append(sourceFile)
sourceReference = fileReference
case .file:
let parentPath = path.parent()
let fileReference = getFileReference(path: path, inPath: parentPath, name: targetSource.name)
let sourceFile = generateSourceFile(targetType: targetType, targetSource: targetSource, path: path, buildPhases: buildPhases)
if hasCustomParent {
sourcePath = path
sourceReference = fileReference
} else if parentPath == project.basePath {
sourcePath = path
sourceReference = fileReference
rootGroups.insert(fileReference)
} else {
let parentGroup = getGroup(
path: parentPath,
mergingChildren: [fileReference],
createIntermediateGroups: createIntermediateGroups,
hasCustomParent: hasCustomParent,
isBaseGroup: true
)
sourcePath = parentPath
sourceReference = parentGroup
}
sourceFiles.append(sourceFile)
case .group:
if targetSource.optional && !Path(targetSource.path).exists {
// This group is missing, so if's optional just return an empty array
return []
}
let (groupSourceFiles, groups) = try getGroupSources(
targetType: targetType,
targetSource: targetSource,
path: path,
isBaseGroup: true,
hasCustomParent: hasCustomParent,
excludePaths: excludePaths,
includePaths: includePaths,
buildPhases: buildPhases
)
let group = groups.first!
if let name = targetSource.name {
group.name = name
}
sourceFiles += groupSourceFiles
sourceReference = group
}
if hasCustomParent {
createParentGroups(customParentGroups, for: sourceReference)
try makePathRelative(for: sourceReference, at: path)
} else if createIntermediateGroups {
createIntermediaGroups(for: sourceReference, at: sourcePath)
}
return sourceFiles
}
/// Returns the resolved `SourceType` for a given `TargetSource`.
///
/// While `TargetSource` declares `type`, its optional and in the event that the value is not defined then we must resolve a sensible default based on the path of the source.
private func resolvedTargetSourceType(for targetSource: TargetSource, at path: Path) -> SourceType {
return targetSource.type ?? (path.isFile || path.extension != nil ? .file : .group)
}
private func createParentGroups(_ parentGroups: [String], for fileElement: PBXFileElement) {
guard let parentName = parentGroups.last else {
return
}
let parentPath = project.basePath + Path(parentGroups.joined(separator: "/"))
let parentPathExists = parentPath.exists
let parentGroupAlreadyExists = groupsByPath[parentPath] != nil
let parentGroup = getGroup(
path: parentPath,
mergingChildren: [fileElement],
createIntermediateGroups: false,
hasCustomParent: false,
isBaseGroup: parentGroups.count == 1
)
// As this path is a custom group, remove the path reference
if !parentPathExists {
parentGroup.name = String(parentName)
parentGroup.path = nil
}
if !parentGroupAlreadyExists {
createParentGroups(parentGroups.dropLast(), for: parentGroup)
}
}
// Add groups for all parents recursively
private func createIntermediaGroups(for fileElement: PBXFileElement, at path: Path) {
let parentPath = path.parent()
guard parentPath != project.basePath else {
// we've reached the top
return
}
let hasParentGroup = groupsByPath[parentPath] != nil
if !hasParentGroup {
do {
// if the path is a parent of the project base path (or if calculating that fails)
// do not create a parent group
// e.g. for project path foo/bar/baz
// - create foo/baz
// - create baz/
// - do not create foo
let pathIsParentOfProject = try path.isParent(of: project.basePath)
if pathIsParentOfProject { return }
} catch {
return
}
}
let parentGroup = getGroup(
path: parentPath,
mergingChildren: [fileElement],
createIntermediateGroups: true,
hasCustomParent: false,
isBaseGroup: false
)
if !hasParentGroup {
createIntermediaGroups(for: parentGroup, at: parentPath)
}
}
// Make the fileElement path and name relative to its parents aggregated paths
private func makePathRelative(for fileElement: PBXFileElement, at path: Path) throws {
// This makes the fileElement path relative to its parent and not to the project. Xcode then rebuilds the actual
// path for the file based on the hierarchy this fileElement lives in.
var paths: [String] = []
var element: PBXFileElement = fileElement
while true {
guard let parent = element.parent else { break }
if let path = parent.path {
paths.insert(path, at: 0)
}
element = parent
}
let completePath = project.basePath + Path(paths.joined(separator: "/"))
let relativePath = try path.relativePath(from: completePath)
let relativePathString = relativePath.string
if relativePathString != fileElement.path {
fileElement.path = relativePathString
fileElement.name = relativePath.lastComponent
}
}
private func findCurrentCoreDataModelVersionPath(using versionedModels: [Path]) -> Path? {
// Find and parse the current version model stored in the .xccurrentversion file
guard
let versionPath = versionedModels.first(where: { $0.lastComponent == ".xccurrentversion" }),
let data = try? versionPath.read(),
let plist = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any],
let versionString = plist["_XCCurrentVersionName"] as? String else {
return nil
}
return versionedModels.first(where: { $0.lastComponent == versionString })
}
}
| 42.102597 | 409 | 0.590055 |
e5f7ca4b23f4bfb5bdc1a7d4888a9a1272a05c99 | 12,215 | //
// JSLSelectedFoodTagVC.swift
// JSLogistics
// 美食标签
// Created by gouyz on 2019/11/5.
// Copyright © 2019 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
import TTGTagCollectionView
private let selectedFoodTagCell = "selectedFoodTagCell"
private let selectedFoodTagHeader = "selectedFoodTagHeader"
private let selectedFoodTagSearchCell = "selectedFoodTagSearchCell"
class JSLSelectedFoodTagVC: GYZBaseVC {
/// 选择结果回调
var resultBlock:((_ tagNames: String) -> Void)?
var isSearchResult: Bool = false
/// 热门标签
var hotTagList:[String] = [String]()
/// 历史标签
var historyTagList:[String] = [String]()
/// 当前选择标签
var currTagList:[String] = [String]()
/// 搜索 内容
var searchContent: String = ""
// 搜索数据
var dataList: [JSLGoodsCategoryModel] = [JSLGoodsCategoryModel]()
var isHas: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
if let tags = userDefaults.stringArray(forKey: publishTagsData) {
historyTagList = tags
}
requestHotTagsList()
}
func setupUI(){
navigationItem.titleView = searchBar
/// 解决iOS11中UISearchBar高度变大
if #available(iOS 11.0, *) {
searchBar.heightAnchor.constraint(equalToConstant: kTitleHeight).isActive = true
}
let btn = UIButton(type: .custom)
btn.setTitle("完成", for: .normal)
btn.titleLabel?.font = k15Font
btn.setTitleColor(kBlackFontColor, for: .normal)
btn.frame = CGRect.init(x: 0, y: 0, width: kTitleHeight, height: kTitleHeight)
btn.addTarget(self, action: #selector(cancleSearchClick), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn)
}
lazy var tableView : UITableView = {
let table = UITableView(frame: CGRect.zero, style: .grouped)
table.dataSource = self
table.delegate = self
table.separatorStyle = .none
table.backgroundColor = kWhiteColor
// 设置大概高度
table.estimatedRowHeight = 100
// 设置行高为自动适配
table.rowHeight = UITableView.automaticDimension
table.register(JSLSearchHotCell.classForCoder(), forCellReuseIdentifier: selectedFoodTagCell)
table.register(GYZLabArrowCell.classForCoder(), forCellReuseIdentifier: selectedFoodTagSearchCell)
table.register(LHSGeneralHeaderView.classForCoder(), forHeaderFooterViewReuseIdentifier: selectedFoodTagHeader)
return table
}()
/// 搜索框
lazy var searchBar : UISearchBar = {
let search = UISearchBar()
search.placeholder = "添加美食标签"
search.delegate = self
//显示输入光标
search.tintColor = kHeightGaryFontColor
/// 搜索框背景色
if #available(iOS 13.0, *){
search.searchTextField.backgroundColor = kGrayBackGroundColor
}else{
if let textfiled = search.subviews.first?.subviews.last as? UITextField {
textfiled.backgroundColor = kGrayBackGroundColor
}
}
//弹出键盘
// search.becomeFirstResponder()
return search
}()
///获取热门标签数据
func requestHotTagsList(){
if !GYZTool.checkNetWork() {
return
}
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("index/getTagWords",parameters: nil,method :.get, success: { (response) in
weakSelf?.hud?.hide(animated: true)
GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
guard let data = response["result"].array else { return }
for item in data{
weakSelf?.hotTagList.append(item.stringValue)
}
weakSelf?.tableView.reloadData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
/// 取消搜索
@objc func cancleSearchClick(){
searchBar.resignFirstResponder()
if resultBlock != nil {
var names: String = ""
if currTagList.count > 0 {
for item in currTagList {
names += item + "/"
}
names = names.subString(start: 0, length: names.count - 1)
userDefaults.set(currTagList, forKey: publishTagsData)
}
resultBlock!(names)
}
self.dismiss(animated: false, completion: nil)
}
///获取搜索标签数据
func requestSearchTagsList(){
if !GYZTool.checkNetWork() {
return
}
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("publish/searchTag",parameters: ["keywords":searchContent], success: { (response) in
weakSelf?.hud?.hide(animated: true)
GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
guard let data = response["result"].array else { return }
for item in data{
guard let itemInfo = item.dictionaryObject else { return }
let model = JSLGoodsCategoryModel.init(dict: itemInfo)
weakSelf?.dataList.append(model)
if model.name == weakSelf?.searchContent {
weakSelf?.isHas = true
}
}
if !(weakSelf?.isHas)! {
let model = JSLGoodsCategoryModel.init(dict: ["name":weakSelf?.searchContent as Any])
weakSelf?.dataList.append(model)
}
weakSelf?.tableView.reloadData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
///添加标签数据
func requestAddTags(){
if !GYZTool.checkNetWork() {
return
}
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("publish/addTag",parameters: ["name":searchContent], success: { (response) in
weakSelf?.hud?.hide(animated: true)
GYZLog(response)
MBProgressHUD.showAutoDismissHUD(message: response["msg"].stringValue)
if response["status"].intValue == kQuestSuccessTag{//请求成功
weakSelf?.cancleSearchClick()
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
}
extension JSLSelectedFoodTagVC: UISearchBarDelegate{
///mark - UISearchBarDelegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if searchBar.text!.isEmpty {
MBProgressHUD.showAutoDismissHUD(message: "请输入搜索内容")
return
}
isSearchResult = true
self.searchContent = searchBar.text ?? ""
requestSearchTagsList()
}
/// 文本改变会调用该方法(包含clear文本)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.count == 0 {
isSearchResult = false
tableView.reloadData()
}
}
}
extension JSLSelectedFoodTagVC: UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
if isSearchResult {
return 1
}
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearchResult {
return dataList.count
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if isSearchResult {
let cell = tableView.dequeueReusableCell(withIdentifier: selectedFoodTagSearchCell) as! GYZLabArrowCell
cell.rightIconView.isHidden = true
cell.nameLab.text = dataList[indexPath.row].name
cell.nameLab.textColor = kGaryFontColor
cell.selectionStyle = .none
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: selectedFoodTagCell) as! JSLSearchHotCell
cell.tagsView.removeAllTags()
cell.tagsView.tag = indexPath.section
cell.tagsView.delegate = self
if indexPath.section == 1 { // 热门
cell.tagsView.addTags(hotTagList)
for item in currTagList {
if hotTagList.contains(item) {
cell.tagsView.setTagAt(UInt(hotTagList.firstIndex(of: item)!), selected: true)
}
}
}else{
cell.tagsView.addTags(historyTagList)
for item in currTagList {
if historyTagList.contains(item) {
cell.tagsView.setTagAt(UInt(historyTagList.firstIndex(of: item)!), selected: true)
}
}
}
cell.tagsView.preferredMaxLayoutWidth = kScreenWidth - kMargin * 2
//必须调用,不然高度计算不准确
cell.tagsView.reload()
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if !isSearchResult {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: selectedFoodTagHeader) as! LHSGeneralHeaderView
headerView.lineView.isHidden = false
if section == 0 {
headerView.nameLab.text = "最近用过的标签"
}else{
headerView.nameLab.text = "热门搜索"
}
return headerView
}
return UIView()
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
///MARK : UITableViewDelegate
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if isSearchResult {
return 0.00001
}
return kTitleHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.00001
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isSearchResult {
currTagList.append(dataList[indexPath.row].name!)
if isHas {
cancleSearchClick()
}else{
requestAddTags()
}
}
}
}
extension JSLSelectedFoodTagVC: TTGTextTagCollectionViewDelegate {
func textTagCollectionView(_ textTagCollectionView: TTGTextTagCollectionView!, didTapTag tagText: String!, at index: UInt, selected: Bool, tagConfig config: TTGTextTagConfig!) {
if selected {
if !currTagList.contains(tagText) {
currTagList.append(tagText)
}
}else{
for (index,item) in currTagList.enumerated() {
if item == tagText {
currTagList.remove(at: index)
break
}
}
}
tableView.reloadData()
}
}
| 33.557692 | 181 | 0.559885 |
910c7e5e8b8d7a18bb1b8a0bb7761522ec4d7bd2 | 1,263 | //
// Storage.swift
// Singularity
//
// Created by Grzegorz Sagadyn on 22/09/2020.
//
import Foundation
internal class Storage {
// MARK: - Private Properties
private let dispatchQueue = DispatchQueue(label: "com.singularity.dependency_descriptors_queue")
private var descriptors = [String: Descriptor]()
// MARK: - Subscript
internal subscript<T>(type: T.Type, name: String?) -> Descriptor? {
get {
var item: Descriptor?
let itemId = identifier(for: type, withName: name)
dispatchQueue.sync { item = descriptors[itemId] }
return item
}
set {
let item: Descriptor? = newValue
let itemId = identifier(for: type, withName: name)
dispatchQueue.sync { descriptors[itemId] = item }
}
}
}
// -----------------------------------------------------------------------------
// MARK: - Private Extension
// -----------------------------------------------------------------------------
extension Storage {
private func identifier<T>(for type: T.Type, withName name: String?) -> String {
let components = [String(describing: type), name].compactMap { $0 }
return components.joined(separator: "-")
}
}
| 29.372093 | 100 | 0.536025 |
8aa2c78df2bf90628d7e18e0349e9cb2d14cda7e | 3,131 | // Copyright 2019 rideOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CoreLocation
import Foundation
import RideOsCommon
import RxSwift
public class VehicleUnregisteredCoordinator: Coordinator {
private let disposeBag = DisposeBag()
private let vehicleUnregisteredViewModel: VehicleUnregisteredViewModel
private let mapViewController: MapViewController
private let schedulerProvider: SchedulerProvider
public convenience init(registerVehicleFinishedListener: RegisterVehicleFinishedListener,
mapViewController: MapViewController,
navigationController: UINavigationController) {
self.init(mapViewController: mapViewController,
vehicleUnregisteredViewModel: DefaultVehicleUnregisteredViewModel(
registerVehicleFinishedListener: registerVehicleFinishedListener
),
navigationController: navigationController,
schedulerProvider: DefaultSchedulerProvider())
}
public init(mapViewController: MapViewController,
vehicleUnregisteredViewModel: VehicleUnregisteredViewModel,
navigationController: UINavigationController,
schedulerProvider: SchedulerProvider) {
self.mapViewController = mapViewController
self.vehicleUnregisteredViewModel = vehicleUnregisteredViewModel
self.schedulerProvider = schedulerProvider
super.init(navigationController: navigationController)
}
public override func activate() {
vehicleUnregisteredViewModel.getVehicleUnregisteredViewState()
.observeOn(schedulerProvider.mainThread())
.subscribe(onNext: { [unowned self] vehicleUnregisteredViewState in
switch vehicleUnregisteredViewState {
case .preRegistration:
self.showPreRegistration()
case .registering:
self.showRegistering()
}
})
.disposed(by: disposeBag)
}
private func showPreRegistration() {
showChild(viewController: PreRegistrationViewController(startVehicleRegistrationListener: vehicleUnregisteredViewModel,
mapViewController: mapViewController))
}
private func showRegistering() {
showChild(viewController: VehicleRegistrationViewController(vehicleRegistrationViewModel:
DefaultVehicleRegistrationViewModel(registerVehicleListener: vehicleUnregisteredViewModel)))
}
}
| 42.310811 | 127 | 0.698179 |
48a313d01ea3fa71f2483aee3fabe382a2332a8d | 4,597 | //
// ChangeMobileViewController.swift
// Yep
//
// Created by NIX on 16/5/4.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import Ruler
import RxSwift
import RxCocoa
final class ChangeMobileViewController: BaseInputMobileViewController {
fileprivate lazy var disposeBag = DisposeBag()
@IBOutlet fileprivate weak var changeMobileNumberPromptLabel: UILabel!
@IBOutlet fileprivate weak var changeMobileNumberPromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var currentMobileNumberPromptLabel: UILabel!
@IBOutlet fileprivate weak var currentMobileNumberLabel: UILabel!
fileprivate lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = String.trans_buttonNextStep
button.rx.tap
.subscribe(onNext: { [weak self] in self?.tryShowVerifyChangedMobile() })
.addDisposableTo(self.disposeBag)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: String.trans_titleChangeMobile)
navigationItem.rightBarButtonItem = nextButton
changeMobileNumberPromptLabel.text = NSLocalizedString("What's your new number?", comment: "")
currentMobileNumberPromptLabel.text = String.trans_promptCurrentNumber
currentMobileNumberLabel.text = YepUserDefaults.fullPhoneNumber
areaCodeTextField.text = TimeZone.areaCode
areaCodeTextField.backgroundColor = UIColor.white
areaCodeTextField.delegate = self
areaCodeTextField.rx.textInput.text
.subscribe(onNext: { [weak self] _ in self?.adjustAreaCodeTextFieldWidth() })
.addDisposableTo(disposeBag)
mobileNumberTextField.placeholder = ""
mobileNumberTextField.backgroundColor = UIColor.white
mobileNumberTextField.textColor = UIColor.yepInputTextColor()
mobileNumberTextField.delegate = self
Observable.combineLatest(areaCodeTextField.rx.textInput.text, mobileNumberTextField.rx.textInput.text) { (a, b) -> Bool in
guard let a = a, let b = b else { return false }
return !a.isEmpty && !b.isEmpty
}
.bind(to: nextButton.rx.isEnabled)
.addDisposableTo(disposeBag)
changeMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nextButton.isEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
mobileNumberTextField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
// MARK: Actions
override func tappedKeyboardReturn() {
tryShowVerifyChangedMobile()
}
func tryShowVerifyChangedMobile() {
view.endEditing(true)
guard let areaCode = areaCodeTextField.text, let number = mobileNumberTextField.text else {
return
}
let mobilePhone = MobilePhone(areaCode: areaCode, number: number)
sharedStore().dispatch(MobilePhoneUpdateAction(mobilePhone: mobilePhone))
YepHUD.showActivityIndicator()
requestSendVerifyCodeOfNewMobilePhone(mobilePhone, useMethod: .sms, failureHandler: { (reason, errorMessage) in
YepHUD.hideActivityIndicator()
let message = errorMessage ?? String.trans_promptRequestSendVerificationCodeFailed
YepAlert.alertSorry(message: message, inViewController: self, withDismissAction: {
SafeDispatch.async { [weak self] in
self?.mobileNumberTextField.becomeFirstResponder()
}
})
}, completion: {
YepHUD.hideActivityIndicator()
SafeDispatch.async { [weak self] in
self?.showVerifyChangedMobile()
}
})
}
fileprivate func showVerifyChangedMobile() {
guard let areaCode = areaCodeTextField.text, let number = mobileNumberTextField.text else {
return
}
let mobilePhone = MobilePhone(areaCode: areaCode, number: number)
sharedStore().dispatch(MobilePhoneUpdateAction(mobilePhone: mobilePhone))
performSegue(withIdentifier: "showVerifyChangedMobile", sender: nil)
}
}
| 32.835714 | 130 | 0.687622 |
f90a8923d706f3e7bbf29a27fae4edb19adec1dd | 506 | import Foundation
// Read an input grid from stdin
var input = ""
while true {
let line = readLine(stripNewline: true)
if line == nil || line!.isEmpty {
break
}
input += line! + "\n"
}
// Parse it
let parser = InputParser()
let grid = parser.parse(input)
// Run PathFinder
let finder = PathFinder()
let (success, resistance, path) = finder.find(grid)
// Display the output
print(success ? "Yes" : "No")
print(resistance)
print(path.map(){x in String(x)}.joinWithSeparator(" "))
| 20.24 | 56 | 0.652174 |
16991f3997a890552cbbcef6d6327322b5593817 | 1,043 | //
// DataAccessController.swift
// RCG-RCCL
//
// Created by Dov Rosenberg on 9/4/17.
// Copyright © 2017 Apple. All rights reserved.
//
import Foundation
import ARKit
class DataAccessManager {
/// The queue with updates to the virtual objects are made on.
var updateQueue: DispatchQueue
init(updateQueue: DispatchQueue) {
self.updateQueue = updateQueue
}
// this holds the list of things that the user has collected on their journey
var collectedPrizes = [PrizeDefinition]()
static let availablePrizes: [PrizeDefinition] = {
guard let jsonURL = Bundle.main.url(forResource: "prizes", withExtension: "json") else {
fatalError("Missing 'prizes.json' in bundle.")
}
do {
let jsonData = try Data(contentsOf: jsonURL)
return try JSONDecoder().decode([PrizeDefinition].self, from: jsonData)
} catch {
fatalError("Unable to decode Prize Objects JSON: \(error)")
}
}()
}
| 26.075 | 96 | 0.622244 |
dd95a4658a696e754bb4956cd6593bbf82cc9ea8 | 4,062 | import Flutter
import UIKit
public class SwiftNativeHttpPlugin: NSObject, FlutterPlugin {
var session = URLSession(configuration: URLSessionConfiguration.default)
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "native_http", binaryMessenger: registrar.messenger())
let instance = SwiftNativeHttpPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "native_http/request":
let arguments = (call.arguments as? [String : AnyObject])
let url = arguments!["url"] as! String
let method = arguments!["method"] as! String
let headers = arguments!["headers"] as! Dictionary<String, String>
let body = arguments!["body"] as! Dictionary<String, String>
handleCall(url:url, method:method,headers:headers, body:body, result:result)
default:
result("Not implemented");
}
}
func handleCall(url: String, method: String, headers:Dictionary<String, String>, body:Dictionary<String, String>, result:@escaping FlutterResult){
switch method {
case "GET":
return getCall(url:url, headers:headers, body:body, result: result);
default:
return dataCall(url:url, method: method, headers:headers, body:body, result: result);
}
}
func getCall(url: String, headers:Dictionary<String, String>, body:Dictionary<String, String>, result: @escaping FlutterResult) {
let url = URL(string: url)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "content-type")
headers.forEach {(key: String, value: String) in
request.setValue(value, forHTTPHeaderField: key)
}
let task = session.dataTask(with: request) {( data, response, error) in
if(error != nil){
result(FlutterError (code:"400", message:error?.localizedDescription, details:nil))
return
}
let responseString = String(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
let httpResponse = response as? HTTPURLResponse
let responseCode = httpResponse?.statusCode
var r :Dictionary = Dictionary<String, Any>()
r["code"] = responseCode;
r["body"] = responseString;
result(r);
}
task.resume()
}
func dataCall(url: String, method: String, headers:Dictionary<String, String>, body:Dictionary<String, String>, result: @escaping FlutterResult) {
let url = URL(string: url)!
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "content-type")
headers.forEach {(key: String, value: String) in
request.setValue(value, forHTTPHeaderField: key)
}
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(body) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
request.httpBody = jsonString.data(using: .utf8)
}
}
let task = session.dataTask(with: request) {( data, response, error) in
if(error != nil){
result(FlutterError (code:"400", message:error?.localizedDescription, details:nil))
return
}
let responseString = String(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
let httpResponse = response as? HTTPURLResponse
let responseCode = httpResponse?.statusCode
var r :Dictionary = Dictionary<String, Any>()
r["code"] = responseCode;
r["body"] = responseString;
result(r);
}
task.resume()
}
}
| 41.030303 | 150 | 0.61743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.