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
|
---|---|---|---|---|---|
9bcbbf1ffa3a2c17a50b05e7c6e07699fa01b863 | 2,149 | //
// UserRouter.swift
// Conomin
//
// Created by Phuong Nguyen on 6/19/17.
// Copyright © 2017 Framgia. All rights reserved.
//
import Alamofire
import SwiftyJSON
enum UserRouter: URLRequestConvertible {
case signUp(parameters: Parameters)
case read(userId: Int)
case update(parameters: Parameters)
case login(parameters: Parameters)
case logout(parameters: Parameters)
var method: HTTPMethod {
switch self {
case .signUp:
return .post
case .read:
return .get
case .update:
return .put
case .login:
return .post
case .logout:
return .post
}
}
var path: String {
switch self {
case .signUp:
return Routes.register
case .read(let userId):
return "\(Routes.user)/\(userId)"
case .update:
return "\(Routes.profile)"
case .login:
return Routes.login
case .logout:
return Routes.logout
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try Routes.root.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .signUp(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .update(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .login(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .logout(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .read:
urlRequest = try URLEncoding.default.encode(urlRequest, with: nil)
}
return urlRequest
}
}
extension Request {
public func debugLog() -> Self {
#if DEBUG
debugPrint(self)
#endif
return self
}
}
| 26.530864 | 86 | 0.585854 |
bb410ac7bf63bfeebc677850a9919e14252b1f7f | 1,257 | //
// MoviesDataSource+UICollectionViewDataSource.swift
// TMDB
//
// Created by Grigor Hakobyan on 10.11.21.
//
import UIKit
extension MoviesDataSource: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionItems.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let sectionItem = sectionItems[indexPath.item]
switch sectionItem {
case .movie(let movieViewModel):
let cell = collectionView.dequeueReusableCell(ofType: MovieCollectionViewCell.self, at: indexPath)
cell.bind(item: movieViewModel)
return cell
case .state(let loadingState):
let cell = collectionView.dequeueReusableCell(ofType: StateCollectionViewCell.self, at: indexPath)
cell.bind(state: loadingState)
cell.retryButton.rx.tap
.bind(to: onRetryButtonTapped)
.disposed(by: cell.rx.reuseBag)
return cell
}
}
}
| 33.972973 | 128 | 0.672235 |
f8f56c56cd5b510c436429e6a3cbac54c7791311 | 2,520 | //
// ViewController.swift
// RelativeMovement
//
// Created by CoderXu on 2021/3/28.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
var box1:SCNNode?
var box2:SCNNode?
var ship:SCNNode?
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
sceneView.scene = scene
box1 = scene.rootNode.childNode(withName: "box1", recursively: true)!
box2 = scene.rootNode.childNode(withName: "box2", recursively: true)!
ship = scene.rootNode.childNode(withName: "ship", recursively: true)!
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
if let phoneT = sceneView.pointOfView?.simdTransform, let box1 = box1, let box2 = box2 {
ship?.simdTransform = box2.simdTransform * box1.simdTransform.inverse * phoneT
}
}
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| 29.302326 | 103 | 0.638095 |
e2271dcf4d895467935e812b3f813fc619a90818 | 321 | //
// LabelLight.swift
// WTFUserInterface
//
// Created by NP2 on 12/4/19.
// Copyright © 2019 shndrs. All rights reserved.
//
import UIKit
// MARK: - Label Light
final class LabelLight: BaseLabel {
override func awakeFromNib() {
font = Font.regular.return(size: font.pointSize)
}
}
| 16.05 | 56 | 0.629283 |
4a6d12ed35968db4648c64d40bef9d5385270d1a | 4,047 | import Foundation
// MARK: - SpeechContext definition.
/// The speech recognition context.
///
/// A single context aggregates messages from SLU API, which correspond to the audio portion
/// sent to the API within a single recognition stream.
public struct AudioContext: Hashable, Identifiable {
private var _segments: [Segment] = []
private var _indexedSegments: [Int:Segment] = [:]
private var _segmentsAreDirty: Bool = false
/// The ID of the segment, assigned by the API.
public let id: String
/// The segments belonging to the segment, can be empty if there was nothing recognised from the audio.
public var segments: [Segment] {
mutating get {
if self._segmentsAreDirty {
self._segments = Array(self._indexedSegments.values).sorted()
self._segmentsAreDirty = false
}
return self._segments
}
set(newValue) {
self._segments = newValue.sorted()
self._indexedSegments = newValue.reduce(into: [Int:Segment]()) { (acc, segment) in
acc[segment.segmentId] = segment
}
}
}
/// Creates a new empty speech context.
///
/// - Parameter id: The identifier of the context.
public init(id: String) {
self.id = id
}
/// Creates a new speech context.
///
/// - Parameters:
/// - id: The identifier of the context.
/// - segments: The segments which belong to the context.
///
/// - Important: this initialiser does not check whether `segments` have `id` set as their `contextId` values,
/// so it is possible to pass segments to this initialiser that don't belong to this context
/// according to the identifiers.
public init(id: String, segments: [Segment]) {
self.init(id: id)
self.segments = segments
}
}
// MARK: - Comparable protocol conformance.
extension AudioContext: Comparable {
public static func < (lhs: AudioContext, rhs: AudioContext) -> Bool {
return lhs.id < rhs.id
}
public static func <= (lhs: AudioContext, rhs: AudioContext) -> Bool {
return lhs.id <= rhs.id
}
public static func >= (lhs: AudioContext, rhs: AudioContext) -> Bool {
return lhs.id >= rhs.id
}
public static func > (lhs: AudioContext, rhs: AudioContext) -> Bool {
return lhs.id > rhs.id
}
}
// MARK: - Parsing logic implementation.
extension AudioContext {
mutating func addTranscripts(_ value: [Transcript], segmentId: Int) throws -> Segment {
return try self.updateSegment(id: segmentId, transform: { segment in
for t in value {
try segment.addTranscript(t)
}
})
}
mutating func addEntities(_ value: [Entity], segmentId: Int) throws -> Segment {
return try self.updateSegment(id: segmentId, transform: { segment in
for e in value {
try segment.addEntity(e)
}
})
}
mutating func addIntent(_ value: Intent, segmentId: Int) throws -> Segment {
return try self.updateSegment(id: segmentId, transform: { segment in try segment.setIntent(value) })
}
mutating func finaliseSegment(segmentId: Int) throws -> Segment {
return try self.updateSegment(id: segmentId, transform: { segment in try segment.finalise() })
}
mutating func finalise() throws -> AudioContext {
for (k, v) in self._indexedSegments {
if !v.isFinal {
self._indexedSegments.removeValue(forKey: k)
}
}
self._segmentsAreDirty = true
return self
}
private mutating func updateSegment(id: Int, transform: (inout Segment) throws -> Void) rethrows -> Segment {
var segment = self._indexedSegments[id] ?? Segment(segmentId: id, contextId: self.id)
try transform(&segment)
self._indexedSegments[id] = segment
self._segmentsAreDirty = true
return segment
}
}
| 31.372093 | 114 | 0.617742 |
1c6cdb447fd7eebfc57d7c5ac372f742500fae55 | 2,165 | //
// PXNotificationManager.swift
// MercadoPagoSDK
//
// Created by Demian Tejo on 25/4/18.
// Copyright © 2018 MercadoPago. All rights reserved.
//
import Foundation
struct PXAnimatedButtonNotificationObject {
var status: String
var statusDetail: String?
}
struct PXNotificationManager {
}
extension PXNotificationManager {
struct SuscribeTo {
static func attemptToClose(_ observer: Any, selector: Selector) {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(observer, selector: selector, name: .attemptToClose, object: nil)
}
static func animateButton(_ observer: Any, selector: Selector) {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(observer, selector: selector, name: .animateButton, object: nil)
}
}
}
extension PXNotificationManager {
struct UnsuscribeTo {
static func attemptToClose(_ observer: Any) {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(observer, name: .attemptToClose, object: nil)
}
static func animateButton(_ observer: Any?) {
guard let observer = observer else {
return
}
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(observer, name: .animateButton, object: nil)
}
}
}
extension PXNotificationManager {
struct Post {
static func attemptToClose() {
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .attemptToClose, object: nil)
}
static func animateButton(with object: PXAnimatedButtonNotificationObject) {
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .animateButton, object: object)
}
}
}
internal extension NSNotification.Name {
static let attemptToClose = Notification.Name(rawValue: "PXAttemptToClose")
static let animateButton = Notification.Name(rawValue: "PXAnimateButton")
}
| 31.376812 | 108 | 0.686374 |
8a5ce7c5ead2b685637646f07fe99970d7f4ee8b | 273 | //
// infoModel.swift
// Budi
//
// Created by 인병윤 on 2021/12/18.
//
import Foundation
struct SignupInfoModel {
var mainName: String
var startDate: String
var endDate: String
var nowWorks: Bool
var description: String
var porflioLink: String
}
| 15.166667 | 33 | 0.67033 |
f7f57325113e482df18317ad17f843b4c42ebf83 | 208 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{
let a=Void{
}
a{enum A{
let a{g
| 20.8 | 87 | 0.740385 |
11d385eff1d41acb8337d3e46d41b44068070f29 | 3,373 | //
// Complex.swift
// RootFinder
//
// Created by Bo Gustafsson on 30/08/16.
// Copyright © 2016 BNI. All rights reserved.
//
import Foundation
struct Complex {
var real : Double
var imaginary : Double
}
func == (lhs: Complex, rhs: Complex) -> Bool {
return lhs.real == rhs.real && lhs.imaginary == rhs.imaginary
}
func + (lhs: Complex, rhs: Complex) -> Complex {
return Complex(real: lhs.real + rhs.real, imaginary: lhs.imaginary + rhs.imaginary)
}
func + (lhs: Double, rhs: Complex) -> Complex {
return Complex(real: lhs + rhs.real, imaginary: rhs.imaginary)
}
func + (lhs: Complex, rhs: Double) -> Complex {
return Complex(real: lhs.real + rhs, imaginary: lhs.imaginary)
}
func - (lhs: Complex, rhs: Complex) -> Complex {
return Complex(real: lhs.real - rhs.real, imaginary: lhs.imaginary - rhs.imaginary)
}
func - (lhs: Double, rhs: Complex) -> Complex {
return Complex(real: lhs - rhs.real, imaginary: -rhs.imaginary)
}
func - (lhs: Complex, rhs: Double) -> Complex {
return Complex(real: lhs.real - rhs, imaginary: lhs.imaginary)
}
prefix func - (cmplx: Complex) -> Complex {
return Complex(real: -cmplx.real, imaginary: -cmplx.imaginary)
}
func * (lhs: Complex, rhs: Complex) -> Complex {
return Complex(real: lhs.real * rhs.real - lhs.imaginary * rhs.imaginary, imaginary: lhs.real * rhs.imaginary + lhs.imaginary * rhs.real)
}
func * (lhs: Double, rhs: Complex) -> Complex {
return Complex(real: lhs * rhs.real, imaginary: lhs * rhs.imaginary)
}
func * (lhs: Complex, rhs: Double) -> Complex {
return rhs * lhs
}
func conj(_ cmplx: Complex) -> Complex {
return Complex(real: cmplx.real, imaginary: -cmplx.imaginary)
}
func norm(_ cmplx: Complex) -> Double {
return (cmplx * conj(cmplx)).real
}
func abs(_ cmplx: Complex) -> Double {
return sqrt(norm(cmplx))
}
func arg(_ cmplx: Complex) -> Double {
let x = cmplx.real
let y = cmplx.imaginary
var phi : Double
if x > 0 {
phi = atan(y/x)
} else if x < 0 {
if y >= 0 {
phi = atan(y/x) + Double.pi
} else {
phi = atan(y/x) - Double.pi
}
} else {
if y > 0 {
phi = Double.pi/2.0
} else {
phi = -Double.pi/2.0
}
}
return phi
}
func rectForm(_ r: Double, phi: Double) -> Complex {
return Complex(real: r * cos(phi), imaginary: r * sin(phi))
}
func sqrt(_ cmplx: Complex) -> Complex {
let r = sqrt(abs(cmplx))
let phi = arg(cmplx)/2.0
return rectForm(r, phi: phi)
}
func / (lhs: Complex, rhs: Double) -> Complex {
return Complex(real: lhs.real/rhs, imaginary: lhs.imaginary/rhs)
}
func / (lhs: Complex, rhs: Complex) -> Complex {
return lhs * conj(rhs) / norm(rhs)
}
func / (lhs: Double, rhs: Complex) -> Complex {
return Complex(real:lhs, imaginary: 0.0)/rhs
}
func exp(_ cmplx: Complex) -> Complex {
return Complex(real: exp(cmplx.real)*cos(cmplx.imaginary), imaginary: exp(cmplx.real)*sin(cmplx.imaginary))
}
func tanh(_ cmplx: Complex) -> Complex {
return (exp(cmplx) - exp(-cmplx))/(exp(cmplx) + exp(-cmplx))
}
func niceString(_ cmplx: Complex) -> String {
if cmplx.imaginary >= 0 {
return String(cmplx.real) + "+ i" + String(cmplx.imaginary)
} else {
return String(cmplx.real) + "- i" + String(abs(cmplx.imaginary))
}
}
| 25.946154 | 141 | 0.616069 |
e54869967b140f34ed0bb95e846d17f890611dfc | 438 | // 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
func b{func A{class A<T:a func a{}let a
| 43.8 | 79 | 0.748858 |
d56ab88e3cb002b8515c93c3623905383673fa6e | 1,680 | //
// PhotoViewModel.swift
// NASAPhotos
//
// Created by Luke Van In on 2021/07/14.
//
import Foundation
import Combine
///
/// Models the view state for a single photo. Transforms photo model to a photo info view model that can be
/// displayed in a user interface.
///
final class PhotoViewModel<Model>: PhotoViewModelProtocol where Model: PhotoDetailsModelProtocol {
#warning("TODO: Erase model type and use AnyPhotoDetailsModel instead")
typealias TransformPhoto = (_ photo: Model.Photo) -> PhotoInfoViewModel
let photo: AnyPublisher<PhotoInfoViewModel, Never>
var errorCoordinator: ErrorCoordinatorProtocol?
private var cancellables = Set<AnyCancellable>()
private let model: Model
init(
model: Model,
transformPhoto: @escaping TransformPhoto
) {
self.photo = model.photo
.map(transformPhoto)
.eraseToAnyPublisher()
self.model = model
model.error
.receive(on: DispatchQueue.main)
.sink { [weak self] error in
guard let self = self else {
return
}
self.showError(message: error.localizedDescription)
}
.store(in: &cancellables)
}
func reload() {
model.reload()
}
private func showError(message: String) {
errorCoordinator?.showError(
message: message,
cancellable: true,
retry: { [weak self] in
guard let self = self else {
return
}
self.model.reload()
}
)
}
}
| 25.846154 | 107 | 0.57619 |
0e838eeeb6d428a90e75718e789a383cc441feaf | 3,852 | //
// SettingsViewController.swift
// Honeychord
//
// Created by BrianBolze on 12/28/17.
// Copyright © 2017 Bolze, LLC. All rights reserved.
//
import UIKit
protocol SettingsChangeHandler {
var touchTrailsEnabled : Bool { get set }
var scaleHiding : Bool { get set }
var scaleDisabling : Bool { get set }
var isInternalInstrumentActive : Bool { get set }
var isVirtualMidiActive : Bool { get set }
var isNetworkMidiActive : Bool { get set }
func changeInstrument(toInstrument : MIDIInstrument)
func changeKey(toKey : Int)
func changeScale(toScale : Scale)
func changeChordProgression(progression : ChordProgression)
func zoomIn()
func zoomOut()
func panLeft()
func panRight()
func panUp()
func panDown()
func changePitch(toValue : Double)
func changeYaw(toValue : Double)
func changeRoll(toValue : Double)
}
class SettingsViewController: UITableViewController {
var changeHandler : SettingsChangeHandler?
// @IBOutlet weak var networkNameLabel: UILabel!
// @IBOutlet weak var numConnectionsLabel: UILabel!
@IBOutlet weak var internalInstrumentSwitch: UISwitch! {
didSet {
internalInstrumentSwitch.isOn = changeHandler?.isInternalInstrumentActive ?? false
}
}
@IBOutlet weak var virtualMidiSwitch: UISwitch! {
didSet {
virtualMidiSwitch.isOn = changeHandler?.isVirtualMidiActive ?? false
}
}
@IBOutlet weak var networkStatusSwitch: UISwitch! {
didSet {
networkStatusSwitch.isOn = changeHandler?.isNetworkMidiActive ?? false
}
}
@IBOutlet weak var outOfScaleHidingSwitch: UISwitch! {
didSet {
outOfScaleHidingSwitch.isOn = changeHandler?.scaleHiding ?? false // get this from masterVC
}
}
@IBOutlet weak var outOfScaleDisablingSwitch: UISwitch! {
didSet {
outOfScaleDisablingSwitch.isOn = changeHandler?.scaleDisabling ?? false
}
}
@IBOutlet weak var touchTrailsSwitch: UISwitch! {
didSet {
touchTrailsSwitch.isOn = changeHandler?.touchTrailsEnabled ?? false
}
}
//
// @IBOutlet weak var gridSizeStepper: UIStepper! {
// didSet {
// gridSizeStepper.maximumValue = 10
// gridSizeStepper.minimumValue = 0
// gridSizeStepper.stepValue = 1
// gridSizeStepper.value = 5
// gridSizeStepper.wraps = false
// }
// }
// override func viewDidLoad() {
// updateNetworkSettings()
// }
// @IBAction func updateNetworkSettings() {
// networkNameLabel.text = midiController.getNetworkName()
// numConnectionsLabel.text = midiController.getNumberOfNetworkConnections()
// }
@IBAction func internalInstrumentToggle(sender: UISwitch) {
changeHandler?.isInternalInstrumentActive = sender.isOn
}
@IBAction func virtualMidiToggle(sender: UISwitch) {
changeHandler?.isVirtualMidiActive = sender.isOn
}
@IBAction func networkEnableChange(sender: UISwitch) {
changeHandler?.isNetworkMidiActive = sender.isOn
}
@IBAction func outOfScaleHidingChange(sender: UISwitch) {
changeHandler?.scaleHiding = sender.isOn
}
@IBAction func outOfScaleDisablingChange(sender: UISwitch) {
changeHandler?.scaleDisabling = sender.isOn
}
@IBAction func touchTrailsChange(sender: UISwitch) {
changeHandler?.touchTrailsEnabled = sender.isOn
}
// @IBAction func gridSizeChange(sender: UIStepper) {
// if let h = changeHandler {
// h.gridZoom(sender.value)
// }
// }
}
| 30.330709 | 103 | 0.63136 |
d6a0cae21e50fb899596768d427d0f0039480d34 | 720 | //
// RowView.swift
// Ranger
//
// Created by Geri Borbás on 2020. 01. 04..
// Copyright © 2020. Geri Borbás. All rights reserved.
//
import Cocoa
class PlayersTableRowView: NSTableRowView
{
// MARK: - Custom drawing
override func draw(_ dirtyRect: NSRect)
{
super.draw(dirtyRect)
}
override func drawSelection(in dirtyRect: NSRect)
{
// Only if needed.
guard self.selectionHighlightStyle != .none
else { return }
// Draw.
NSColor(white: 1, alpha: 0.1).setFill()
NSBezierPath.init(
roundedRect: self.bounds.shorter(by: 1),
xRadius: 2,
yRadius: 2
).fill()
}
}
| 18.947368 | 55 | 0.556944 |
7540713e2af8dd509b1da9358cf42983705e6fc9 | 718 | //
// BaseViewController.swift
// DanTangSwift
//
// Created by 思 彭 on 16/10/2.
// Copyright © 2016年 思 彭. All rights reserved.
//
import UIKit
import SVProgressHUD
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension BaseViewController {
func setupUI() {
view.backgroundColor = GlobalColor()
// 设置SVProgressHUD
SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.custom)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
SVProgressHUD.setBackgroundColor(UIColor(red: 0, green: 0, blue: 0, alpha: 0.5))
SVProgressHUD.setForegroundColor(UIColor.white)
}
}
| 22.4375 | 88 | 0.672702 |
76175fd8195b5ca7f9ad96f1123b35fd6f225491 | 903 | //
// PreworkTests.swift
// PreworkTests
//
// Created by Oluwapelumi Olutimehin on 12/9/21.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.558824 | 111 | 0.665559 |
bf9e15b85ecbd5dcd0521748574ba573fa422124 | 1,207 | //
// User.swift
// Wekan Boards
//
// Created by Guillaume on 29/01/2018.
//
import Cocoa
class User: NSObject {
var id: String
var name: String
var boards = [Board]()
required init(id: String, name: String) {
self.id = id
self.name = name
}
func getBoards(rootURL: String, bearer: String) {
let baseURL = URL(string: "\(rootURL)/api/users/\(id)/boards")!
let session = URLSession.shared
var request = URLRequest(url: baseURL)
request.httpMethod = "GET"
request.addValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let boards = try JSONSerialization.jsonObject(with: data!) as! [NSDictionary]
for board in boards {
let boardId = "\(board["_id"]!)"
let boardTitle = "\(board["title"]!)"
self.boards.append(Board(id: boardId, name: boardTitle))
}
} catch {
print("error")
}
})
task.resume()
}
}
| 27.431818 | 104 | 0.53024 |
fcbf1f885995fb50fd0191c23db282ab679da206 | 251 | //
// LayoutAndGeometryApp.swift
// LayoutAndGeometry
//
// Created by Tiger Yang on 10/8/21.
//
import SwiftUI
@main
struct LayoutAndGeometryApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 13.944444 | 37 | 0.601594 |
9b20610dddaa9cea727c91aef8d3dc6116341d15 | 5,438 | import Foundation
import ServiceWorker
import ServiceWorkerContainer
/// Ideally we would have a separate container for each usage, but we can't detect from
/// the WKURLSchemeHandler which instance of a URL is sending a command. So instead, we
/// have them share a container between them.
struct ContainerAndUsageNumber {
let webview: SWWebView
let container: ServiceWorkerContainer
var numUsing: Int
}
public class SWWebViewCoordinator: SWWebViewContainerDelegate, ServiceWorkerClientsDelegate, CacheStorageProviderDelegate {
let workerFactory: WorkerFactory
let registrationFactory: WorkerRegistrationFactory
let storageURL: URL
public init(storageURL: URL) {
self.storageURL = storageURL
self.workerFactory = WorkerFactory()
self.registrationFactory = WorkerRegistrationFactory(withWorkerFactory: self.workerFactory)
self.workerFactory.clientsDelegateProvider = self
self.workerFactory.cacheStorageProvider = self
self.workerFactory.serviceWorkerDelegateProvider = ServiceWorkerStorageProvider(storageURL: storageURL)
}
var inUseContainers: [ContainerAndUsageNumber] = []
public func container(_ webview: SWWebView, createContainerFor url: URL) throws -> ServiceWorkerContainer {
if var alreadyExists = self.inUseContainers.first(where: { $0.webview == webview && $0.container.url.absoluteString == url.absoluteString }) {
alreadyExists.numUsing += 1
Log.info?("Returning existing ServiceWorkerContainer for \(url.absoluteString). It has \(alreadyExists.numUsing) other clients")
return alreadyExists.container
}
let newContainer = try ServiceWorkerContainer(forURL: url, withFactory: self.registrationFactory)
let wrapper = ContainerAndUsageNumber(webview: webview, container: newContainer, numUsing: 1)
self.inUseContainers.append(wrapper)
Log.info?("Returning new ServiceWorkerContainer for \(url.absoluteString).")
return newContainer
}
public func container(_ webview: SWWebView, getContainerFor url: URL) -> ServiceWorkerContainer? {
let container = self.inUseContainers.first(where: {
if ($0.webview == webview) {
print("[swift: SWWebViewCoordinator] $0.container.url.absoluteString:", $0.container.url.absoluteString, "url.absoluteString:", url.absoluteString)
}
// TODO: 这里 referer 的资料得多看看,fix it
if ($0.webview == webview && url.absoluteString != nil) {
return true;
}
return false;
})?.container
if container == nil {
Log.debug?("[swift: SWWebViewCoordinator] No container for: \(url)")
} else {
Log.debug?("[swift: SWWebViewCoordinator] Container: \(url)")
}
return container
}
public func container(_ webview: SWWebView, freeContainer container: ServiceWorkerContainer) {
guard let containerIndex = self.inUseContainers.firstIndex(where: { $0.webview == webview && $0.container == container }) else {
Log.error?("[swift: SWWebViewCoordinator] Tried to remove a ServiceWorkerContainer that doesn't exist")
return
}
self.inUseContainers[containerIndex].numUsing -= 1
let url = self.inUseContainers[containerIndex].container.url
if self.inUseContainers[containerIndex].numUsing == 0 {
// If this is the only client using this container then we can safely dispose of it.
Log.info?("[swift: SWWebViewCoordinator] Deleting existing ServiceWorkerContainer for \(url.absoluteString).")
self.inUseContainers.remove(at: containerIndex)
} else {
Log.info?("[swift: SWWebViewCoordinator] Released link to ServiceWorkerContainer for \(url.absoluteString). It has \(self.inUseContainers[containerIndex].numUsing) remaining clients")
}
}
public func clientsClaim(_ worker: ServiceWorker, _ cb: (Error?) -> Void) {
if worker.state != .activated, worker.state != .activating {
cb(ErrorMessage("[swift: SWWebViewCoordinator] Service worker can only claim clients when in activated or activating state"))
return
}
guard let registration = worker.registration else {
cb(ErrorMessage("ServiceWorker must have a registration to claim clients"))
return
}
let scopeString = registration.scope.absoluteString
let clientsInScope = self.inUseContainers.filter { client in
if client.container.url.absoluteString.hasPrefix(scopeString) == false {
// must fall within our scope
return false
}
guard let ready = client.container.readyRegistration else {
// if it has no ready registration we will always claim it.
return true
}
// Otherwise, we need to check - is the current scope more specific than ours?
// If it is, we don't claim.
return ready.scope.absoluteString.count <= scopeString.count
}
clientsInScope.forEach { client in
client.container.claim(by: worker)
}
cb(nil)
}
public func createCacheStorage(_ worker: ServiceWorker) throws -> CacheStorage {
return try SQLiteCacheStorage(for: worker)
}
}
| 42.818898 | 195 | 0.672122 |
f447ab0db6f4fd5410a4fb6fbfe569da391a6b50 | 386 | //
// SCNBillboardConstraint.swift
// baseapp-ios-core-v1
//
// Created by Pat Sluth on 2019-10-16.
// Copyright © 2019 SilverLogic. All rights reserved.
//
import Foundation
import SceneKit
@available(iOS 9.0, OSX 10.11, *)
public extension SCNBillboardConstraint {
convenience init(freeAxes: SCNBillboardAxis) {
self.init()
self.freeAxes = freeAxes
}
}
| 19.3 | 54 | 0.689119 |
4b45957c1d1f65c507a54e352d8b512dd6fdbfe2 | 839 | //
// Label+Padding.swift
// CalendarComponent
//
// Created by MATIC on 7/3/19.
// Copyright © 2019 MATIC. All rights reserved.
//
import UIKit
@IBDesignable
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 1.0
@IBInspectable var bottomInset: CGFloat = 1.0
@IBInspectable var leftInset: CGFloat = 10.0
@IBInspectable var rightInset: CGFloat = 10.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
| 27.966667 | 105 | 0.674613 |
5050b538dfe6e314eb427b16f471de322add04d5 | 821 | @testable import GitHubUser
import RxSwift
import Domain
class UserUseCaseMock: Domain.UserUseCase {
var users_ReturnValue: Observable<[User]> = Observable.just([])
var users_Called = false
var detail_user_ReturnValue: Observable<User>
= Observable.just(User(login: "mojombo",
id: 1,
avatarUrl: "https://avatars0.githubusercontent.com/u/1?v=4",
htmlUrl: "https://github.com/mojombo",
name: "Michael",
location: "San Francisco, CA",
bio: "",
publicRepos: 3,
followers: 18,
following: 0))
var detail_user_Called = false
func users() -> Observable<[User]> {
users_Called = true
return users_ReturnValue
}
func user(id: String) -> Observable<User> {
detail_user_Called = true
return detail_user_ReturnValue
}
}
| 25.65625 | 70 | 0.656516 |
d54e91330fe5f602a451e769deeeaa4d80a086ae | 2,197 | //
// MercadoPagoCheckout+TokenizationServiceResultHandler.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 12/04/2019.
//
import Foundation
extension MercadoPagoCheckout: TokenizationServiceResultHandler {
func finishInvalidIdentificationNumber() {
if let identificationViewController = viewModel.pxNavigationHandler.navigationController.viewControllers.last as? IdentificationViewController {
identificationViewController.showErrorMessage("invalid_field".localized)
}
}
func finishFlow(token: PXToken, shouldResetESC: Bool) {
if shouldResetESC {
getTokenizationService().resetESCCap(cardId: token.cardId) { [weak self] in
self?.flowCompletion(token: token)
}
} else {
flowCompletion(token: token)
}
}
func flowCompletion(token: PXToken) {
viewModel.updateCheckoutModel(token: token)
executeNextStep()
}
func finishWithESCError() {
executeNextStep()
}
func finishWithError(error: MPSDKError, securityCode: String? = nil) {
// When last VC is PXSecurityCodeViewController we must not call 'errorInputs' function as we dont want to show the error screen.
// We just clean the token and reset the button showing an error snackbar to the user.
if let securityCodeVC = viewModel.pxNavigationHandler.navigationController.viewControllers.last as? PXSecurityCodeViewController {
resetButtonAndCleanToken(securityCodeVC: securityCodeVC)
} else {
viewModel.errorInputs(error: error, errorCallback: { [weak self] () in
self?.getTokenizationService().createCardToken(securityCode: securityCode)
})
self.executeNextStep()
}
}
func getTokenizationService(needToShowLoading: Bool = true) -> TokenizationService {
return TokenizationService(paymentOptionSelected: viewModel.paymentOptionSelected, cardToken: viewModel.cardToken, pxNavigationHandler: viewModel.pxNavigationHandler, needToShowLoading: needToShowLoading, mercadoPagoServices: viewModel.mercadoPagoServices, gatewayFlowResultHandler: self)
}
}
| 41.45283 | 296 | 0.713701 |
1e054e8e05c15bce3412cc2bbeb8b774522125d5 | 3,714 | import Foundation
import azureSwiftRuntime
public protocol WorkflowRunsList {
var nextLink: String? { get }
var hasAdditionalPages : Bool { get }
var headerParameters: [String: String] { get set }
var subscriptionId : String { get set }
var resourceGroupName : String { get set }
var workflowName : String { get set }
var apiVersion : String { get set }
var top : Int32? { get set }
var filter : String? { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (WorkflowRunListResultProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.WorkflowRuns {
// List gets a list of workflow runs.
internal class ListCommand : BaseCommand, WorkflowRunsList {
var nextLink: String?
public var hasAdditionalPages : Bool {
get {
return nextLink != nil
}
}
public var subscriptionId : String
public var resourceGroupName : String
public var workflowName : String
public var apiVersion = "2016-06-01"
public var top : Int32?
public var filter : String?
public init(subscriptionId: String, resourceGroupName: String, workflowName: String) {
self.subscriptionId = subscriptionId
self.resourceGroupName = resourceGroupName
self.workflowName = workflowName
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{workflowName}"] = String(describing: self.workflowName)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
if self.top != nil { queryParameters["$top"] = String(describing: self.top!) }
if self.filter != nil { queryParameters["$filter"] = String(describing: self.filter!) }
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
if var pageDecoder = decoder as? PageDecoder {
pageDecoder.isPagedData = true
pageDecoder.nextLinkName = "NextLink"
}
let result = try decoder.decode(WorkflowRunListResultData?.self, from: data)
if var pageDecoder = decoder as? PageDecoder {
self.nextLink = pageDecoder.nextLink
}
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (WorkflowRunListResultProtocol?, Error?) -> Void) -> Void {
if self.nextLink != nil {
self.path = nextLink!
self.nextLink = nil;
self.pathType = .absolute
}
client.executeAsync(command: self) {
(result: WorkflowRunListResultData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 44.214286 | 149 | 0.599354 |
036b75dd5bdbc8865c79ea24afc32c1981717ddd | 1,078 | //
// Created by Yaroslav Zhurakovskiy
// Copyright © 2019-2020 Yaroslav Zhurakovskiy. All rights reserved.
//
extension Leetcode {
public func getUserInfo(completion: @escaping (Result<UserInfo, Error>) -> Void) {
let query = """
{
user {
username
isCurrentUserPremium
}
}
"""
graphqlRequest(
using: .init(query: query),
method: .post,
origin: "/",
referer: "/",
responseType: UserInfoDataWrapper.self,
completion: { result in
switch result {
case .success(let info):
completion(.success(info.data.user))
case .decodingFailure(let error):
completion(.failure(error))
case .graphqlError(let error):
completion(.failure(error))
case .networkFailure(let error):
completion(.failure(error))
}
}
)
}
}
| 28.368421 | 86 | 0.475881 |
8acda910094b0df41874e9a0a508a0e5402a8d3e | 16,599 | import FBSDKCoreKit
import Foundation
import KsApi
import Prelude
import ReactiveSwift
/**
A global stack that captures the current state of global objects that the app wants access to.
*/
public struct AppEnvironment: AppEnvironmentType {
internal static let environmentStorageKey = "com.kickstarter.AppEnvironment.current"
internal static let oauthTokenStorageKey = "com.kickstarter.AppEnvironment.oauthToken"
/**
A global stack of environments.
*/
fileprivate static var stack: [Environment] = [Environment()]
/**
Invoke when an access token has been acquired and you want to log the user in. Replaces the current
environment with a new one that has the authenticated api service and current user model.
- parameter envelope: An access token envelope with the api access token and user.
*/
public static func login(_ envelope: AccessTokenEnvelope) {
self.replaceCurrentEnvironment(
apiService: self.current.apiService.login(OauthToken(token: envelope.accessToken)),
currentUser: envelope.user,
ksrAnalytics: self.current.ksrAnalytics |> KSRAnalytics.lens.loggedInUser .~ envelope.user
)
}
/**
Invoke when we have acquired a fresh current user and you want to replace the current environment's
current user with the fresh one.
- parameter user: A user model.
*/
public static func updateCurrentUser(_ user: User) {
self.replaceCurrentEnvironment(
currentUser: user,
ksrAnalytics: self.current.ksrAnalytics |> KSRAnalytics.lens.loggedInUser .~ user
)
}
public static func updateDebugData(_ debugData: DebugData) {
self.replaceCurrentEnvironment(
debugData: debugData
)
}
public static func updateOptimizelyClient(_ optimizelyClient: OptimizelyClientType?) {
self.replaceCurrentEnvironment(
optimizelyClient: optimizelyClient
)
}
public static func updateServerConfig(_ config: ServerConfigType) {
let service = Service(serverConfig: config)
replaceCurrentEnvironment(
apiService: service
)
}
public static func updateConfig(_ config: Config) {
let debugConfigOrConfig = self.current.debugData?.config ?? config
self.replaceCurrentEnvironment(
config: debugConfigOrConfig,
countryCode: debugConfigOrConfig.countryCode,
ksrAnalytics: AppEnvironment.current.ksrAnalytics |> KSRAnalytics.lens.config .~ debugConfigOrConfig
)
}
public static func updateLanguage(_ language: Language) {
self.replaceCurrentEnvironment(language: language)
}
// Invoke when you want to end the user's session.
public static func logout() {
let storage = AppEnvironment.current.cookieStorage
storage.cookies?.forEach(storage.deleteCookie)
self.replaceCurrentEnvironment(
apiService: AppEnvironment.current.apiService.logout(),
cache: type(of: AppEnvironment.current.cache).init(),
currentUser: nil,
ksrAnalytics: self.current.ksrAnalytics |> KSRAnalytics.lens.loggedInUser .~ nil
)
}
// The most recent environment on the stack.
public static var current: Environment! {
return stack.last
}
// Push a new environment onto the stack.
public static func pushEnvironment(_ env: Environment) {
self.saveEnvironment(
environment: env, ubiquitousStore: env.ubiquitousStore, userDefaults: env.userDefaults
)
self.stack.append(env)
}
// Pop an environment off the stack.
@discardableResult
public static func popEnvironment() -> Environment? {
let last = self.stack.popLast()
let next = self.current ?? Environment()
self.saveEnvironment(
environment: next,
ubiquitousStore: next.ubiquitousStore,
userDefaults: next.userDefaults
)
return last
}
// Replace the current environment with a new environment.
public static func replaceCurrentEnvironment(_ env: Environment) {
self.pushEnvironment(env)
self.stack.remove(at: self.stack.count - 2)
}
// Pushes a new environment onto the stack that changes only a subset of the current global dependencies.
public static func pushEnvironment(
apiService: ServiceType = AppEnvironment.current.apiService,
apiDelayInterval: DispatchTimeInterval = AppEnvironment.current.apiDelayInterval,
applePayCapabilities: ApplePayCapabilitiesType = AppEnvironment.current.applePayCapabilities,
application: UIApplicationType = UIApplication.shared,
assetImageGeneratorType: AssetImageGeneratorType.Type = AppEnvironment.current.assetImageGeneratorType,
cache: KSCache = AppEnvironment.current.cache,
calendar: Calendar = AppEnvironment.current.calendar,
config: Config? = AppEnvironment.current.config,
cookieStorage: HTTPCookieStorageProtocol = AppEnvironment.current.cookieStorage,
coreTelephonyNetworkInfo: CoreTelephonyNetworkInfoType = AppEnvironment.current.coreTelephonyNetworkInfo,
countryCode: String = AppEnvironment.current.countryCode,
currentUser: User? = AppEnvironment.current.currentUser,
dateType: DateProtocol.Type = AppEnvironment.current.dateType,
debounceInterval: DispatchTimeInterval = AppEnvironment.current.debounceInterval,
debugData: DebugData? = AppEnvironment.current.debugData,
device: UIDeviceType = AppEnvironment.current.device,
isVoiceOverRunning: @escaping (() -> Bool) = AppEnvironment.current.isVoiceOverRunning,
ksrAnalytics: KSRAnalytics = AppEnvironment.current.ksrAnalytics,
language: Language = AppEnvironment.current.language,
launchedCountries: LaunchedCountries = AppEnvironment.current.launchedCountries,
locale: Locale = AppEnvironment.current.locale,
mainBundle: NSBundleType = AppEnvironment.current.mainBundle,
optimizelyClient: OptimizelyClientType? = AppEnvironment.current.optimizelyClient,
pushRegistrationType: PushRegistrationType.Type = AppEnvironment.current.pushRegistrationType,
reachability: SignalProducer<Reachability, Never> = AppEnvironment.current.reachability,
scheduler: DateScheduler = AppEnvironment.current.scheduler,
ubiquitousStore: KeyValueStoreType = AppEnvironment.current.ubiquitousStore,
userDefaults: KeyValueStoreType = AppEnvironment.current.userDefaults
) {
self.pushEnvironment(
Environment(
apiService: apiService,
apiDelayInterval: apiDelayInterval,
applePayCapabilities: applePayCapabilities,
application: application,
assetImageGeneratorType: assetImageGeneratorType,
cache: cache,
calendar: calendar,
config: config,
cookieStorage: cookieStorage,
coreTelephonyNetworkInfo: coreTelephonyNetworkInfo,
countryCode: countryCode,
currentUser: currentUser,
dateType: dateType,
debounceInterval: debounceInterval,
debugData: debugData,
device: device,
isVoiceOverRunning: isVoiceOverRunning,
ksrAnalytics: ksrAnalytics,
language: language,
launchedCountries: launchedCountries,
locale: locale,
mainBundle: mainBundle,
optimizelyClient: optimizelyClient,
pushRegistrationType: pushRegistrationType,
reachability: reachability,
scheduler: scheduler,
ubiquitousStore: ubiquitousStore,
userDefaults: userDefaults
)
)
}
// Replaces the current environment onto the stack with an environment that changes only a subset
// of current global dependencies.
public static func replaceCurrentEnvironment(
apiService: ServiceType = AppEnvironment.current.apiService,
apiDelayInterval: DispatchTimeInterval = AppEnvironment.current.apiDelayInterval,
applePayCapabilities: ApplePayCapabilitiesType = AppEnvironment.current.applePayCapabilities,
application: UIApplicationType = UIApplication.shared,
assetImageGeneratorType: AssetImageGeneratorType.Type = AppEnvironment.current.assetImageGeneratorType,
cache: KSCache = AppEnvironment.current.cache,
calendar: Calendar = AppEnvironment.current.calendar,
config: Config? = AppEnvironment.current.config,
cookieStorage: HTTPCookieStorageProtocol = AppEnvironment.current.cookieStorage,
coreTelephonyNetworkInfo: CoreTelephonyNetworkInfoType = AppEnvironment.current.coreTelephonyNetworkInfo,
countryCode: String = AppEnvironment.current.countryCode,
currentUser: User? = AppEnvironment.current.currentUser,
dateType: DateProtocol.Type = AppEnvironment.current.dateType,
debounceInterval: DispatchTimeInterval = AppEnvironment.current.debounceInterval,
debugData: DebugData? = AppEnvironment.current.debugData,
device: UIDeviceType = AppEnvironment.current.device,
isVoiceOverRunning: @escaping (() -> Bool) = AppEnvironment.current.isVoiceOverRunning,
ksrAnalytics: KSRAnalytics = AppEnvironment.current.ksrAnalytics,
language: Language = AppEnvironment.current.language,
launchedCountries: LaunchedCountries = AppEnvironment.current.launchedCountries,
locale: Locale = AppEnvironment.current.locale,
mainBundle: NSBundleType = AppEnvironment.current.mainBundle,
optimizelyClient: OptimizelyClientType? = AppEnvironment.current.optimizelyClient,
pushRegistrationType: PushRegistrationType.Type = AppEnvironment.current.pushRegistrationType,
reachability: SignalProducer<Reachability, Never> = AppEnvironment.current.reachability,
scheduler: DateScheduler = AppEnvironment.current.scheduler,
ubiquitousStore: KeyValueStoreType = AppEnvironment.current.ubiquitousStore,
userDefaults: KeyValueStoreType = AppEnvironment.current.userDefaults
) {
self.replaceCurrentEnvironment(
Environment(
apiService: apiService,
apiDelayInterval: apiDelayInterval,
applePayCapabilities: applePayCapabilities,
application: application,
assetImageGeneratorType: assetImageGeneratorType,
cache: cache,
calendar: calendar,
config: config,
cookieStorage: cookieStorage,
coreTelephonyNetworkInfo: coreTelephonyNetworkInfo,
countryCode: countryCode,
currentUser: currentUser,
dateType: dateType,
debounceInterval: debounceInterval,
debugData: debugData,
device: device,
isVoiceOverRunning: isVoiceOverRunning,
ksrAnalytics: ksrAnalytics,
language: language,
launchedCountries: launchedCountries,
locale: locale,
mainBundle: mainBundle,
optimizelyClient: optimizelyClient,
pushRegistrationType: pushRegistrationType,
reachability: reachability,
scheduler: scheduler,
ubiquitousStore: ubiquitousStore,
userDefaults: userDefaults
)
)
}
// Returns the last saved environment from user defaults.
public static func fromStorage(
ubiquitousStore _: KeyValueStoreType,
userDefaults: KeyValueStoreType
) -> Environment {
let data = userDefaults.dictionary(forKey: self.environmentStorageKey) ?? [:]
var service = self.current.apiService
var currentUser: User?
let configDict: [String: Any]? = data["config"] as? [String: Any]
let config: Config? = configDict.flatMap(Config.decodeJSONDictionary)
if let oauthToken = data["apiService.oauthToken.token"] as? String {
// If there is an oauth token stored in the defaults, then we can authenticate our api service
service = service.login(OauthToken(token: oauthToken))
removeLegacyOauthToken(fromUserDefaults: userDefaults)
} else if let oauthToken = legacyOauthToken(forUserDefaults: userDefaults) {
// Otherwise if there is a token in the legacy user defaults entry we can use that
service = service.login(OauthToken(token: oauthToken))
removeLegacyOauthToken(fromUserDefaults: userDefaults)
}
// Try restoring the client id for the api service
if let clientId = data["apiService.serverConfig.apiClientAuth.clientId"] as? String {
service = Service(
serverConfig: ServerConfig(
apiBaseUrl: service.serverConfig.apiBaseUrl,
webBaseUrl: service.serverConfig.webBaseUrl,
apiClientAuth: ClientAuth(clientId: clientId),
basicHTTPAuth: service.serverConfig.basicHTTPAuth,
graphQLEndpointUrl: service.serverConfig.graphQLEndpointUrl
),
oauthToken: service.oauthToken,
language: self.current.language.rawValue,
currency: self.current.locale.currencyCode ?? "USD"
)
}
// Try restoring the base urls for the api service
if let apiBaseUrlString = data["apiService.serverConfig.apiBaseUrl"] as? String,
let apiBaseUrl = URL(string: apiBaseUrlString),
let webBaseUrlString = data["apiService.serverConfig.webBaseUrl"] as? String,
let webBaseUrl = URL(string: webBaseUrlString) {
service = Service(
serverConfig: ServerConfig(
apiBaseUrl: apiBaseUrl,
webBaseUrl: webBaseUrl,
apiClientAuth: service.serverConfig.apiClientAuth,
basicHTTPAuth: service.serverConfig.basicHTTPAuth,
graphQLEndpointUrl: service.serverConfig.graphQLEndpointUrl
),
oauthToken: service.oauthToken,
language: self.current.language.rawValue,
currency: self.current.locale.currencyCode ?? "USD"
)
}
// Try restoring the basic auth data for the api service
if let username = data["apiService.serverConfig.basicHTTPAuth.username"] as? String,
let password = data["apiService.serverConfig.basicHTTPAuth.password"] as? String {
service = Service(
serverConfig: ServerConfig(
apiBaseUrl: service.serverConfig.apiBaseUrl,
webBaseUrl: service.serverConfig.webBaseUrl,
apiClientAuth: service.serverConfig.apiClientAuth,
basicHTTPAuth: BasicHTTPAuth(username: username, password: password),
graphQLEndpointUrl: service.serverConfig.graphQLEndpointUrl
),
oauthToken: service.oauthToken,
language: self.current.language.rawValue,
currency: self.current.locale.currencyCode ?? "USD"
)
}
// Try restoring the environment
if let environment = data["apiService.serverConfig.environment"] as? String,
let environmentType = EnvironmentType(rawValue: environment) {
let serverConfig = ServerConfig.config(for: environmentType)
service = Service(
serverConfig: serverConfig,
oauthToken: service.oauthToken,
language: self.current.language.rawValue,
currency: self.current.locale.currencyCode ?? "USD"
)
}
// Try restore the current user
if service.oauthToken != nil {
currentUser = data["currentUser"].flatMap(tryDecode)
}
return Environment(
apiService: service,
config: config,
currentUser: currentUser,
ksrAnalytics: self.current.ksrAnalytics |> KSRAnalytics.lens.loggedInUser .~ currentUser
)
}
// Saves some key data for the current environment
internal static func saveEnvironment(
environment env: Environment = AppEnvironment.current,
ubiquitousStore _: KeyValueStoreType,
userDefaults: KeyValueStoreType
) {
var data: [String: Any] = [:]
// swiftformat:disable wrap
data["apiService.oauthToken.token"] = env.apiService.oauthToken?.token
data["apiService.serverConfig.apiBaseUrl"] = env.apiService.serverConfig.apiBaseUrl.absoluteString
data["apiService.serverConfig.apiClientAuth.clientId"] = env.apiService.serverConfig.apiClientAuth.clientId
data["apiService.serverConfig.basicHTTPAuth.username"] = env.apiService.serverConfig.basicHTTPAuth?.username
data["apiService.serverConfig.basicHTTPAuth.password"] = env.apiService.serverConfig.basicHTTPAuth?.password
data["apiService.serverConfig.webBaseUrl"] = env.apiService.serverConfig.webBaseUrl.absoluteString
data["apiService.serverConfig.environment"] = env.apiService.serverConfig.environment.description
data["apiService.language"] = env.apiService.language
data["apiService.currency"] = env.apiService.currency
data["config"] = env.config?.encode()
data["currentUser"] = env.currentUser?.encode()
// swiftformat:enable wrap
userDefaults.set(data, forKey: self.environmentStorageKey)
}
}
private func legacyOauthToken(forUserDefaults userDefaults: KeyValueStoreType) -> String? {
return userDefaults.object(forKey: "com.kickstarter.access_token") as? String
}
private func removeLegacyOauthToken(fromUserDefaults userDefaults: KeyValueStoreType) {
userDefaults.removeObject(forKey: "com.kickstarter.access_token")
}
| 42.670951 | 112 | 0.741912 |
6412619a5ba8ddb56f8f204d2b4e1422f8dbaee7 | 3,025 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/PCMacroRuntime.swift %S/Inputs/SilentPlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode
// UNSUPPORTED: OS=linux-gnu
import PlaygroundSupport
#sourceLocation(file: "main.swift", line: 10)
func s(_ x: Optional<Int>) -> String {
switch x {
case .none:
print("hello!")
return "none"
case .some(1):
return "one"
case let .some(x) where x == 2:
return "two"
default:
return "many"
}
}
s(.none)
s(.some(1))
s(.some(2))
s(.some(3))
// .none
// CHECK: [24:1-24:9] pc before
// CHECK-NEXT: [10:1-10:37] pc before
// CHECK-NEXT: [10:1-10:37] pc after
// CHECK-NEXT: [11:3-11:11] pc before
// CHECK-NEXT: [11:3-11:11] pc after
// CHECK-NEXT: [12:5-12:16] pc before
// CHECK-NEXT: [12:5-12:16] pc after
// CHECK-NEXT: [13:7-13:22] pc before
// next must come hello! since we don't want the contents of the switch evaluated before we simulate entering it. Otherwise it will look out of sync.
// CHECK-NEXT: hello!
// CHECK-NEXT: [13:7-13:22] pc after
// CHECK-NEXT: [14:7-14:20] pc before
// CHECK-NEXT: [14:7-14:20] pc after
// CHECK-NEXT: [24:1-24:9] pc after
// .some(1)
// CHECK-NEXT: [25:1-25:12] pc before
// CHECK-NEXT: [10:1-10:37] pc before
// CHECK-NEXT: [10:1-10:37] pc after
// CHECK-NEXT: [11:3-11:11] pc before
// CHECK-NEXT: [11:3-11:11] pc after
// CHECK-NEXT: [15:5-15:19] pc before
// CHECK-NEXT: [15:5-15:19] pc after
// CHECK-NEXT: [16:7-16:19] pc before
// CHECK-NEXT: [16:7-16:19] pc after
// CHECK-NEXT: [25:1-25:12] pc after
// .some(2)
// CHECK-NEXT: [26:1-26:12] pc before
// CHECK-NEXT: [10:1-10:37] pc before
// CHECK-NEXT: [10:1-10:37] pc after
// CHECK-NEXT: [11:3-11:11] pc before
// CHECK-NEXT: [11:3-11:11] pc after
// CHECK-NEXT: [17:5-17:36] pc before
// CHECK-NEXT: [17:5-17:36] pc after
// CHECK-NEXT: [18:7-18:19] pc before
// CHECK-NEXT: [18:7-18:19] pc after
// CHECK-NEXT: [26:1-26:12] pc after
// .some(3)
// CHECK-NEXT: [27:1-27:12] pc before
// CHECK-NEXT: [10:1-10:37] pc before
// CHECK-NEXT: [10:1-10:37] pc after
// CHECK-NEXT: [11:3-11:11] pc before
// CHECK-NEXT: [11:3-11:11] pc after
// CHECK-NEXT: [19:5-19:13] pc before
// CHECK-NEXT: [19:5-19:13] pc after
// CHECK-NEXT: [20:7-20:20] pc before
// CHECK-NEXT: [20:7-20:20] pc after
// CHECK-NEXT: [27:1-27:12] pc after
| 34.375 | 262 | 0.652893 |
462c9fdc229dee05b8ead0ce7aa951ac1b7a80ad | 1,410 | //
// GoalsUITests.swift
// GoalsUITests
//
// Created by Bastian Meissner on 27.10.20.
//
import XCTest
class GoalsUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.790698 | 182 | 0.65461 |
0e8f3c05f5c54bfe604f4fd49d8a94f13816e4c4 | 2,074 | //
// Photo.swift
// NG POC
//
// Created by MA XINGCHEN on 1/7/18.
// Copyright © 2018 mark. All rights reserved.
//
import Foundation
import Photos
import UIKit
class Photo{
private var asset: PHAsset
var selected = false
var selectedOrder: Int = 0
var index: Int!
private let compressedSize = 1000
private let thumbnailSize = 220
init(asset: PHAsset,index: Int) {
self.asset = asset
self.index = index
}
func isImage() -> Bool{
return asset.mediaType == PHAssetMediaType.image
}
func getOriginalImage(callback: @escaping (UIImage) -> Void) {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize:PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (originImage, info) in
if let image = originImage {
callback(image)
}
}
}
func getCompressedImage(callback: @escaping (UIImage) -> Void) {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
option.resizeMode = .fast
manager.requestImage(for: asset, targetSize: CGSize.init(width: compressedSize, height: compressedSize), contentMode: .aspectFit, options: option) { (originImage, info) in
if let image = originImage {
callback(image)
}
}
}
func getThumbnail(callback: @escaping (UIImage) -> Void){
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = false
option.deliveryMode = .highQualityFormat
manager.requestImage(for: asset, targetSize: CGSize.init(width: thumbnailSize, height: thumbnailSize), contentMode: .aspectFit, options: option) { (thumbnailImage, info) in
if let image = thumbnailImage {
callback(image)
}
}
}
}
| 30.955224 | 180 | 0.622469 |
bf70598efeebb20289a8df5f400379c0cb428ac8 | 670 | //
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Foundation
enum ImageSource {
case webUrl(URL)
case fileUrl(URL)
case data(ImageProvider)
var isWebUrl: Bool {
switch self {
case .webUrl:
return true
default:
return false
}
}
var fileUrl: URL? {
switch self {
case let .fileUrl(url):
return url
default:
return nil
}
}
var imageProvider: ImageProvider? {
switch self {
case let .data(provider):
return provider
default:
return nil
}
}
}
| 15.952381 | 56 | 0.502985 |
0ac5ad2b9675642e1888cfc4d79855b34a52c713 | 9,462 | //
// CalendarContentViewController.swift
// iOS_Calendar
//
// Created by zhangnan on 2017/5/29.
// Copyright © 2017年 zhangnan. All rights reserved.
//
import UIKit
class CalendarContentViewController: UIViewController {
unowned let calendarView: CalendarView
let scrollView: UIScrollView
var leftMonthView: CalendarMonthView!
var centerMonthView: CalendarMonthView!
var rightMonthView: CalendarMonthView!
var currentMonthInfo: CalendarMonthInfo!
var selectedDate: CalendarDate! {
didSet {
calendarView.delegate?.calendarViewDidSelectDate?(selectedDate)
}
}
var bounds: CGRect {
return scrollView.bounds
}
fileprivate var moveTimer: Timer!
init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSize(width: frame.width * 3, height: frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.isPagingEnabled = true
scrollView.delegate = self
scrollView.bounces = false
scrollView.backgroundColor = UIColor.clear
createMonthViews()
layoutMonthViews()
loadMonthInfo(calendarView.today)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: .UIApplicationDidBecomeActive, object: nil)
}
}
extension CalendarContentViewController {
func createMonthViews() {
leftMonthView = CalendarMonthView()
scrollView.addSubview(leftMonthView)
centerMonthView = CalendarMonthView()
scrollView.addSubview(centerMonthView)
rightMonthView = CalendarMonthView()
scrollView.addSubview(rightMonthView)
[leftMonthView, centerMonthView, rightMonthView].forEach {
$0?.mapDayViews { (dayView) in
dayView.addTarget(self, action: #selector(self.didClickDayView), for: .touchUpInside)
}
}
}
func layoutMonthViews() {
leftMonthView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
centerMonthView.frame = CGRect(x: bounds.width, y: 0, width: bounds.width, height: bounds.height)
rightMonthView.frame = CGRect(x: bounds.width * 2, y: 0, width: bounds.width, height: bounds.height)
}
func loadMonthInfo(_ date: Foundation.Date) {
currentMonthInfo = CalendarMonthInfo(date: date)
centerMonthView.monthInfo = currentMonthInfo
rightMonthView.monthInfo = getFollowingMonth(date)
leftMonthView.monthInfo = getPreviousMonth(date)
scrollView.setContentOffset(CGPoint(x: bounds.width, y: 0), animated: false)
selectedDate = CalendarDate(date: date)
}
func togglePresentedDate(_ date: Foundation.Date) {
loadMonthInfo(date)
centerMonthView.mapDayViews({ (dayView) in
if let date = dayView.dayInfo?.date, matchedDays(selectedDate, date) {
calendarView.selectDayView(dayView, animation: true, isHidden: dayView.isToday)
}
})
}
func refresh() {
let date = selectedDate.convertedDate()!
loadMonthInfo(date)
}
}
//MARK: - Month Manager
extension CalendarContentViewController {
func getFollowingMonth(_ date: Foundation.Date) -> CalendarMonthInfo {
let firstDate = dateManager.monthDateRange(date).monthStartDate
var components = Manager.componentsForDate(firstDate)
components.month! += 1
let newDate = Calendar.current.date(from: components)!
let monthInfo = CalendarMonthInfo(date: newDate)
return monthInfo
}
func getPreviousMonth(_ date: Foundation.Date) -> CalendarMonthInfo {
let firstDate = dateManager.monthDateRange(date).monthStartDate
var components = Manager.componentsForDate(firstDate)
components.month! -= 1
let newDate = Calendar.current.date(from: components)!
let monthInfo = CalendarMonthInfo(date: newDate)
return monthInfo
}
}
//MARK: - UIScrollViewDelegate
extension CalendarContentViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
invalidateTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !currentMonthInfo.allowScrollToPreviousMonth, scrollView.contentOffset.x < bounds.width {
scrollView.setContentOffset(CGPoint(x: bounds.width, y: 0), animated: false)
return
}
if !currentMonthInfo.allowScrollToNextMonth, scrollView.contentOffset.x > bounds.width {
scrollView.setContentOffset(CGPoint(x: bounds.width, y: 0), animated: false)
return
}
if scrollView.contentOffset.x == 0 {
currentMonthInfo = leftMonthView.monthInfo
} else if scrollView.contentOffset.x == bounds.width * 2 {
currentMonthInfo = rightMonthView.monthInfo
} else {
return
}
let date = currentMonthInfo.date
leftMonthView.monthInfo = getPreviousMonth(date!)
centerMonthView.monthInfo = currentMonthInfo
rightMonthView.monthInfo = getFollowingMonth(date!)
scrollView.contentOffset = CGPoint(x: bounds.width, y: 0)
updateSelection()
moveTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(stopDragging), userInfo: nil, repeats: false)
}
//MARK: - Helper
@objc func stopDragging() {
invalidateTimer()
updateLayoutIfNeeded()
calendarView.delegate?.calendarViewFinishSelectDate?(selectedDate)
}
func invalidateTimer() {
if moveTimer != nil {
moveTimer.invalidate()
moveTimer = nil
}
}
}
//MARK: - Layout
extension CalendarContentViewController {
func updateHeight(_ height: CGFloat) {
for constraintIn in calendarView.constraints where
constraintIn.firstAttribute == NSLayoutAttribute.height {
constraintIn.constant = height
break
}
}
func updateLayoutIfNeeded() {
let height = centerMonthView.potentialSize.height
if calendarView.frame.height != height {
updateHeight(height)
calendarView.height = height
calendarView.delegate?.calendarViewHeightDidChange?()
}
}
}
//MARK: - Select Action
extension CalendarContentViewController {
@objc func didClickDayView(_ dayView: CalendarDayView) {
guard let date = dayView.date else {
return
}
selectedDate = date
calendarView.selectDayView(dayView, animation: true, isHidden: dayView.isToday)
if dayView.dayInfo!.isOut {
performedDayViewSelection(dayView.dayInfo!)
} else {
calendarView.delegate?.calendarViewFinishSelectDate?(selectedDate)
}
}
func performedDayViewSelection(_ dayInfo: CalendarDayInfo) {
if dayInfo.date.day > 20 {
//翻到上一个月
scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
} else {
//翻到下一个月
scrollView.setContentOffset(CGPoint(x: bounds.width * 2, y: 0), animated: true)
}
Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(timerAction), userInfo: nil, repeats: false)
}
@objc func timerAction() {
scrollViewDidScroll(scrollView)
}
//翻页时自动选择
func updateSelection() {
let currentDate = CalendarDate(date: currentMonthInfo.date)
if !matchedMonths(selectedDate, currentDate) {
//手动滑动时自动选择1号或者今天
let today = CalendarDate(date: Date())
if matchedMonths(today, currentDate) {
selectedDate = today
} else {
selectedDate = CalendarDate(date: dateManager
.monthDateRange(currentMonthInfo.date).monthStartDate)
}
}
centerMonthView.mapDayViews({ (dayView) in
if let date = dayView.dayInfo?.date, matchedDays(selectedDate, date) {
calendarView.selectDayView(dayView, animation: true, isHidden: dayView.isToday)
}
})
}
}
extension CalendarContentViewController {
@objc func applicationDidBecomeActive() {
let currentDate = Date()
if !matchedDays(CalendarDate(date: currentDate), CalendarDate(date: calendarView.today)) {
calendarView.today = currentDate
togglePresentedDate(currentDate)
}
}
}
| 32.183673 | 151 | 0.629782 |
bb3bc0a6de9daae7f3565caa045616c6b45f4a8d | 1,442 | //
// NetworkingClient.swift
// ShortcutFoundation
//
// Created by Gabriel Sabadin, Karl Söderberg on 2021-08-16.
// Copyright © 2021 Shortcut Scandinavia Apps AB. All rights reserved.
//
import Foundation
import Combine
public struct NetworkingClient {
public var defaultCollectionParsingKeyPath: String?
let baseURL: String
public var headers = [String: String]()
public var parameterEncoding = ParameterEncoding.urlEncoded
public var timeout: TimeInterval?
public var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
public var decoder: JSONDecoder = {
let decoder = JSONDecoder()
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
decoder.dateDecodingStrategy = .custom { decoder in
let string = try decoder.singleValueContainer().decode(String.self)
guard let date = isoFormatter.date(from: string) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Could not parse date \(string)"))
}
return date
}
return decoder
}()
public var encoder: JSONEncoder = JSONEncoder()
private let logger = NetworkingLogger()
public init(baseURL: String, timeout: TimeInterval? = nil) {
self.baseURL = baseURL
self.timeout = timeout
}
}
| 31.347826 | 140 | 0.68932 |
791424c3bbfbaa90dd5a0d3d329e92ffdf747d9c | 2,145 | //
// This source file is part of the Apodini Xpense Example
//
// SPDX-FileCopyrightText: 2018-2021 Paul Schmiedmayer and project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
import SwiftUI
import XpenseModel
// MARK: - LoginView
/// The view that displays login screen of the Xpense App
struct LoginView: View {
/// The `LoginViewModel` that manages the content of the login screen
@ObservedObject var viewModel: LoginViewModel
/// Used to indicate if the text input views and the login button should be shown
@State var showViews = false
var body: some View {
VStack(spacing: 0) {
WelcomeToXpenseView()
if showViews {
VStack(spacing: 0) {
LoginTextFields(viewModel: viewModel)
Spacer()
.frame(height: 24)
LoginButtons(viewModel: viewModel)
Spacer()
.frame(height: 0)
}.padding()
.frame(maxWidth: 450)
.transition(.opacity)
}
}.onAppear(perform: onAppear)
}
/// - Parameter model: The `Model` that is used to manage the `User` of the Xpense Application
init(_ model: Model) {
viewModel = LoginViewModel(model)
}
/// Starts the appear `Animation` of the `LoginView`
func onAppear() {
let animation = Animation
.easeInOut(duration: 0.5)
.delay(1)
withAnimation(animation) {
self.showViews = true
}
}
}
// MARK: - LoginView Previews
struct LoginView_Previews: PreviewProvider {
private static let model: Model = MockModel()
static var previews: some View {
ForEach(ColorScheme.allCases, id: \.self) { colorScheme in
ZStack {
Color("BackgroundColor")
LoginView(model)
}.colorScheme(colorScheme)
}.environmentObject(model)
.previewLayout(.fixed(width: 600, height: 900))
}
}
| 28.223684 | 123 | 0.569231 |
11b503d07a8c65462deb921987e7fcfd4c963f11 | 5,491 | //
// Formatter.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 03/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
final class Formatter {
weak var regexManager: RegexManager?
init(phoneNumberKit: PhoneNumberKit) {
self.regexManager = phoneNumberKit.regexManager
}
init(regexManager: RegexManager) {
self.regexManager = regexManager
}
// MARK: Formatting functions
/// Formats phone numbers for display
///
/// - Parameters:
/// - phoneNumber: Phone number object.
/// - formatType: Format type.
/// - regionMetadata: Region meta data.
/// - Returns: Formatted Modified national number ready for display.
func format(phoneNumber: PhoneNumber, formatType: PhoneNumberFormat, regionMetadata: MetadataTerritory?) -> String {
var formattedNationalNumber = phoneNumber.adjustedNationalNumber()
if let regionMetadata = regionMetadata {
formattedNationalNumber = formatNationalNumber(formattedNationalNumber, regionMetadata: regionMetadata, formatType: formatType)
if let formattedExtension = formatExtension(phoneNumber.numberExtension, regionMetadata: regionMetadata) {
formattedNationalNumber = formattedNationalNumber + formattedExtension
}
}
return formattedNationalNumber
}
/// Formats extension for display
///
/// - Parameters:
/// - numberExtension: Number extension string.
/// - regionMetadata: Region meta data.
/// - Returns: Modified number extension with either a preferred extension prefix or the default one.
func formatExtension(_ numberExtension: String?, regionMetadata: MetadataTerritory) -> String? {
if let extns = numberExtension {
if let preferredExtnPrefix = regionMetadata.preferredExtnPrefix {
return "\(preferredExtnPrefix)\(extns)"
}
else {
return "\(PhoneNumberConstants.defaultExtnPrefix)\(extns)"
}
}
return nil
}
/// Formats national number for display
///
/// - Parameters:
/// - nationalNumber: National number string.
/// - regionMetadata: Region meta data.
/// - formatType: Format type.
/// - Returns: Modified nationalNumber for display.
func formatNationalNumber(_ nationalNumber: String, regionMetadata: MetadataTerritory, formatType: PhoneNumberFormat) -> String {
guard let regexManager = regexManager else { return nationalNumber }
let formats = regionMetadata.numberFormats
var selectedFormat: MetadataPhoneNumberFormat?
for format in formats {
if let leadingDigitPattern = format.leadingDigitsPatterns?.last {
if (regexManager.stringPositionByRegex(leadingDigitPattern, string: String(nationalNumber)) == 0) {
if (regexManager.matchesEntirely(format.pattern, string: String(nationalNumber))) {
selectedFormat = format
break;
}
}
}
else {
if (regexManager.matchesEntirely(format.pattern, string: String(nationalNumber))) {
selectedFormat = format
break;
}
}
}
if let formatPattern = selectedFormat {
guard let numberFormatRule = (formatType == PhoneNumberFormat.international && formatPattern.intlFormat != nil) ? formatPattern.intlFormat : formatPattern.format, let pattern = formatPattern.pattern else {
return nationalNumber
}
var formattedNationalNumber = String()
var prefixFormattingRule = String()
if let nationalPrefixFormattingRule = formatPattern.nationalPrefixFormattingRule, let nationalPrefix = regionMetadata.nationalPrefix {
prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.npPattern, string: nationalPrefixFormattingRule, template: nationalPrefix)
prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.fgPattern, string: prefixFormattingRule, template:"\\$1")
}
if formatType == PhoneNumberFormat.national && regexManager.hasValue(prefixFormattingRule){
let replacePattern = regexManager.replaceFirstStringByRegex(PhoneNumberPatterns.firstGroupPattern, string: numberFormatRule, templateString: prefixFormattingRule)
formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: replacePattern)
}
else {
formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: numberFormatRule)
}
return formattedNationalNumber
}
else {
return nationalNumber
}
}
}
public extension PhoneNumber {
/**
Adjust national number for display by adding leading zero if needed. Used for basic formatting functions.
- Returns: A string representing the adjusted national number.
*/
func adjustedNationalNumber() -> String {
if self.leadingZero == true {
return "0" + String(nationalNumber)
}
else {
return String(nationalNumber)
}
}
}
| 41.916031 | 217 | 0.650883 |
d704ed9628f6439134fde3a526b31225f43a416a | 4,541 | //
// NegativeStackedBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class NegativeStackedBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: HorizontalBarChartView!
lazy var customFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.negativePrefix = ""
formatter.positiveSuffix = "m"
formatter.negativeSuffix = "m"
formatter.minimumSignificantDigits = 1
formatter.minimumFractionDigits = 1
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Stacked Bar Chart Negative"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = true
chartView.leftAxis.enabled = false
let rightAxis = chartView.rightAxis
rightAxis.axisMaximum = 25
rightAxis.axisMinimum = -25
rightAxis.drawZeroLineEnabled = true
rightAxis.labelCount = 7
rightAxis.valueFormatter = DefaultAxisValueFormatter(formatter: customFormatter)
rightAxis.labelFont = .systemFont(ofSize: 9)
let xAxis = chartView.xAxis
xAxis.labelPosition = .bothSided
xAxis.drawAxisLineEnabled = false
xAxis.axisMinimum = 0
xAxis.axisMaximum = 110
xAxis.centerAxisLabelsEnabled = true
xAxis.labelCount = 12
xAxis.granularity = 10
xAxis.valueFormatter = self
xAxis.labelFont = .systemFont(ofSize: 9)
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.formSize = 8
l.formToTextSpace = 8
l.xEntrySpace = 6
// chartView.legend = l
self.updateChartData()
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData()
}
func setChartData() {
let yVals = [CHBarChartDataEntry(x: 5, yValues: [-10, 10]),
CHBarChartDataEntry(x: 15, yValues: [-12, 13]),
CHBarChartDataEntry(x: 25, yValues: [-15, 15]),
CHBarChartDataEntry(x: 35, yValues: [-17, 17]),
CHBarChartDataEntry(x: 45, yValues: [-19, 120]),
CHBarChartDataEntry(x: 55, yValues: [-19, 19]),
CHBarChartDataEntry(x: 65, yValues: [-16, 16]),
CHBarChartDataEntry(x: 75, yValues: [-13, 14]),
CHBarChartDataEntry(x: 85, yValues: [-10, 11]),
CHBarChartDataEntry(x: 95, yValues: [-5, 6]),
CHBarChartDataEntry(x: 105, yValues: [-1, 2])
]
let set = BarChartDataSet(values: yVals, label: "Age Distribution")
set.drawIconsEnabled = false
set.valueFormatter = DefaultValueFormatter(formatter: customFormatter)
set.valueFont = .systemFont(ofSize: 7)
set.axisDependency = .right
set.colors = [UIColor(red: 67/255, green: 67/255, blue: 72/255, alpha: 1),
UIColor(red: 124/255, green: 181/255, blue: 236/255, alpha: 1)
]
set.stackLabels = ["Men", "Women"]
let data = BarChartData(dataSet: set)
data.barWidth = 8.5
chartView.data = data
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
}
extension NegativeStackedBarChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return String(format: "%03.0f-%03.0f", value, value + 10)
}
}
| 34.142857 | 88 | 0.572781 |
28bc6d1529fb97dd79aa600cb206dcbfcb859e98 | 2,646 | // FontAwesomeSegmentedControl.swift
//
// Copyright (c) 2014-present FontAwesome.swift contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@IBDesignable public class FontAwesomeSegmentedControl: UISegmentedControl {
@IBInspectable public var isFontAwesomeCSSCode: Bool = true
@IBInspectable public var size: CGFloat = 22.0
public override func awakeFromNib() {
super.awakeFromNib()
useFontAwesome()
}
public override func prepareForInterfaceBuilder() {
useFontAwesome()
}
private func useFontAwesome() {
updateText {
for index in 0 ..< numberOfSegments {
if let cssCode = titleForSegment(at: index) {
setTitle(String.fontAwesomeIcon(code: cssCode), forSegmentAt: index)
}
}
}
updateFontAttributes { (state, font) in
var attributes = titleTextAttributes(for: state) ?? [:]
attributes[NSAttributedStringKey.font] = font
setTitleTextAttributes(attributes, for: state)
}
}
}
extension FontAwesomeSegmentedControl: FontAwesomeTextRepresentable {
var isTextCSSCode: Bool {
return isFontAwesomeCSSCode
}
var textSize: CGFloat {
return size
}
static func supportedStates() -> [UIControlState] {
if #available(iOS 9.0, *) {
return [.normal, .highlighted, .disabled, .focused, .selected, .application, .reserved]
} else {
return [.normal, .highlighted, .disabled, .selected, .application, .reserved]
}
}
}
| 35.28 | 99 | 0.685563 |
11df33d6621eb977fd5f55d228cfcd7f5d44a3b8 | 1,706 | //
// User.swift
// GitPocket
//
// Created by yansong li on 2015-07-06.
// Copyright © 2015 yansong li. All rights reserved.
//
import Foundation
class User {
var userName: String?
var avatarURL: String?
init(profileInfo:NSDictionary) {
self.userName = profileInfo.valueForKey("login") as? String
self.avatarURL = profileInfo.valueForKey("avatar_url") as? String
}
// class function to get a single user
class func parseJSONDataIntoSingleUser(data: NSData) -> User? {
do {
if let userDict = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments) as? NSDictionary {
let newUser = User(profileInfo: userDict)
return newUser
}
return nil
} catch _ {
return nil
}
}
// class function to get a list of users
class func parseJSONDataIntoUsers(data: NSData) -> [User]?{
do {
if let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
var users = [User]()
if let results = jsonDict["items"] as? NSArray {
for user in results {
if let userProfile = user as? NSDictionary {
let newUser = User(profileInfo: userProfile)
users.append(newUser)
}
}
}
return users
}
return nil
} catch _ {
return nil
}
}
}
| 28.915254 | 146 | 0.534584 |
e9a753c641056dfa510f6f8d3213e8935524e319 | 531 | import Foundation
protocol Scheduler {
static func with(timeInterval: TimeInterval,
shouldRepeat: Bool,
action: @escaping (Scheduler) -> Void) -> Scheduler
func fire()
func invalidate()
}
extension Timer: Scheduler {
static func with(timeInterval: TimeInterval,
shouldRepeat: Bool, action: @escaping (Scheduler) -> Void) -> Scheduler {
return Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: shouldRepeat, block: action)
}
}
| 31.235294 | 105 | 0.642185 |
bf40614b22a39701d7c56c1982e5de32c0f3d20a | 637 | //
// ColorReplacement.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.7.9-858078d8
// https://github.com/tdlib/td/tree/858078d8
//
import Foundation
/// Describes a color replacement for animated emoji
public struct ColorReplacement: Codable, Equatable {
/// Replacement animated emoji color in the RGB24 format
public let newColor: Int
/// Original animated emoji color in the RGB24 format
public let oldColor: Int
public init(
newColor: Int,
oldColor: Int
) {
self.newColor = newColor
self.oldColor = oldColor
}
}
| 19.90625 | 60 | 0.6719 |
2fb400689f3bc3734933b37a6485263fdffe158a | 14 | int fork = 3;
| 7 | 13 | 0.571429 |
fbfd6d755d1f56417e67d7b498d873600090aace | 508 | //
// LGF+Int.swift
// LGFSwiftTool
//
// Created by apple on 2019/8/21.
// Copyright © 2019 来国锋. All rights reserved.
//
#if canImport(UIKit)
import UIKit
public extension Int {
// MARK: - 获取相对于屏幕宽度
func lgf_W() -> CGFloat {
return CGFloat(CGFloat(self) * CGFloat(UIDevice.lgf_ScreenW / 375.0))
}
// MARK: - 获取相对于屏幕高度
func lgf_H() -> CGFloat {
return CGFloat(CGFloat(self) * CGFloat(UIDevice.lgf_ScreenH / 667.0))
}
}
#endif // canImport(UIKit)
| 18.814815 | 77 | 0.608268 |
d5ea7c9676749ef004054163c3c7d2dcd5329340 | 1,334 | //
// PokemonFavoriteRow.swift
// Pokedex
//
// Created by Agus Tiyansyah Syam on 06/04/21.
//
import SwiftUI
import SDWebImageSwiftUI
import Core
import Pokemon
struct PokemonFavoriteRow: View {
var pokemon: PokemonDomainModel
var body: some View {
VStack {
imagePokemon
content
}
.frame(width: UIScreen.main.bounds.width - 32, height: 250)
.background(Color.backgroundType(type: self.pokemon.type[0]))
.cornerRadius(30)
}
}
extension PokemonFavoriteRow {
var imagePokemon: some View {
WebImage(url: URL(string: self.pokemon.imageurl))
.resizable()
.indicator(.activity)
.transition(.fade(duration: 0.5))
.scaledToFit()
.frame(width: 200)
.cornerRadius(30)
.shadow(color: .black, radius: 5, x: 0, y: 5)
.padding(.top)
}
var content: some View {
VStack(alignment: .leading, spacing: 10) {
Text(pokemon.name)
.font(.title)
.foregroundColor(.white)
.bold()
.shadow(color: .black, radius: 5, x: 0, y: 0)
}.padding(
EdgeInsets(
top: 0,
leading: 16,
bottom: 16,
trailing: 16
)
)
}
}
struct PokemonFavoriteRow_Previews: PreviewProvider {
static var previews: some View {
PokemonFavoriteRow(pokemon: samplePokemon)
}
}
| 19.617647 | 65 | 0.616942 |
1c6cf05607948d037c9ca544fc6037405857eb98 | 1,014 | /*
* Copyright 2016 chaoyang805 [email protected]
*
* 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
// Global Constant
let DBMMovieDidDeleteNotificationName = Notification.Name("MovieDidDelete")
let DBMMovieDeleteNotificationKey = "IsMovieDeleted"
// Global Functions
func delay(timeInterval: TimeInterval, block: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(Int(timeInterval)), execute: block)
}
| 36.214286 | 129 | 0.7643 |
48fb11b509c632119a5638554cefef28e0cc441d | 1,374 | //
// Database.swift
// LocationTalk
//
// Created by 鄭宇翔 on 2017/1/28.
// Copyright © 2017年 鄭宇翔. All rights reserved.
//
import UIKit
enum DatabaseError: Error {
case Database_Object_Cant_Be_Created
}
class Database: NSObject {
func auth() throws -> AuthObject {
let className = "\(Constants.database)"+"Auth"
let authClass = NSClassFromString("LocationTalk."+"\(className)") as? AuthObject.Type
if let authClass = authClass {
return authClass.init()
}
throw DatabaseError.Database_Object_Cant_Be_Created
}
func friendship() throws -> FriendshipObject {
let className = "\(Constants.database)"+"Friendship"
let friendshipClass = NSClassFromString("LocationTalk."+"\(className)") as? FriendshipObject.Type
if let friendshipClass = friendshipClass {
return friendshipClass.init()
}
throw DatabaseError.Database_Object_Cant_Be_Created
}
func message() throws -> MessageObject {
let className = "\(Constants.database)"+"Message"
let messageClass = NSClassFromString("LocationTalk."+"\(className)") as? MessageObject.Type
if let messageClass = messageClass {
return messageClass.init()
}
throw DatabaseError.Database_Object_Cant_Be_Created
}
}
| 28.625 | 105 | 0.642649 |
ff1db8952fabd828720dbd1feb92ce527ef5e85c | 353 |
// Check that it compiles to good code with arrays
import stats;
main {
int A[][];
int n = 20;
@async
foreach j in [0:n] {
A[0][j] = n;
}
foreach i in [1:n] {
@async
foreach j in [0:n] {
A[i][j] = A[i-1][j] + 1;
}
}
foreach a in A {
trace(sum_integer(a));
}
}
| 14.12 | 50 | 0.424929 |
29cb4fe93ec085cc3afe6cf43a6d057ebe976617 | 22,373 | // Ombi
// RequestManagerTests.swift
//
// MIT License
//
// Copyright (c) 2021 Varun Santhanam
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
//
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Combine
@testable import Ombi
import XCTest
final class RequestManagerTests: XCTestCase {
var cancellables = Set<AnyCancellable>()
struct TestRequest<RequestBody, ResponseBody, ResponseError>: Requestable where ResponseError: Error {
var path: String
var query: [URLQueryItem]
var method: RequestMethod
var headers: RequestHeaders
var body: RequestBody?
var authentication: RequestAuthentication?
var fallbackResponse: RequestResponse<ResponseBody>?
var requestEncoder: BodyEncoder<RequestBody>
var responseDecoder: BodyDecoder<ResponseBody>
var responseValidator: ResponseValidator<ResponseBody, ResponseError>
var timeoutInterval: TimeInterval
}
func test_constructsResponse_callsEncoder_callsDecoder_validatesResponse_returnsRsponse() {
var completed = false
var encoded = false
var decoded = false
var validated = false
let requestEncoder = BodyEncoder<Data> { body in
encoded = true
return body
}
let responseDecoder = BodyDecoder<Data> { data in
decoded = true
return data
}
let responseValidator = ResponseValidator<Data, Error> { error in
validated = true
return .success(error)
}
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: requestEncoder,
responseDecoder: responseDecoder,
responseValidator: responseValidator,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
publisherProvider.validateClosure = { request in
XCTAssertEqual(request.url, URL(string: "https://app.myapi.com/"))
XCTAssertEqual(request.url?.query, nil)
XCTAssertEqual(request.httpMethod, "POST")
XCTAssertEqual(request.httpBody, "REQUEST".data(using: .utf8))
XCTAssertEqual(request.timeoutInterval, 120.0)
}
let manager = RequestManager(host: "https://app.myapi.com", session: publisherProvider, log: nil)
manager.makeRequest(request, on: testScheduler)
.sink { completion in
switch completion {
case .finished:
completed = true
case .failure:
XCTFail()
}
} receiveValue: { response in
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.headers, [:])
XCTAssertEqual(response.body, "RESPONSE".data(using: .utf8))
}
.store(in: &cancellables)
let response = HTTPURLResponse(url: URL(string: "https://app.myapi.com/")!,
statusCode: 200,
httpVersion: nil,
headerFields: [:])
publisherProvider.sendResult(.success((data: "RESPONSE".data(using: .utf8)!, response: response!)))
testScheduler.advance()
XCTAssertTrue(completed)
XCTAssertTrue(encoded)
XCTAssertTrue(decoded)
XCTAssertTrue(validated)
}
func test_usesRequestableFallback() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: RequestResponse<Data>(url: nil,
headers: [:],
statusCode: 200,
body: "FALLBACK1".data(using: .utf8)),
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
let fallback = RequestResponse<Data>(url: nil,
headers: [:],
statusCode: 201,
body: "FALLBACK2".data(using: .utf8))
manager.makeRequest(request, on: testScheduler, fallback: fallback)
.sink { completion in
switch completion {
case .finished:
completed = true
case .failure:
XCTFail()
}
} receiveValue: { response in
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.body, "FALLBACK1".data(using: .utf8))
}
.store(in: &cancellables)
publisherProvider.sendResult(.failure(URLError(.cancelled)))
testScheduler.advance()
XCTAssertTrue(completed)
}
func test_usesManagerFallback() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
let fallback = RequestResponse<Data>(url: nil,
headers: [:],
statusCode: 201,
body: "FALLBACK2".data(using: .utf8))
manager.makeRequest(request, on: testScheduler, fallback: fallback)
.sink { completion in
switch completion {
case .finished:
completed = true
case .failure:
XCTFail()
}
} receiveValue: { response in
XCTAssertEqual(response.statusCode, 201)
XCTAssertEqual(response.body, "FALLBACK2".data(using: .utf8))
}
.store(in: &cancellables)
publisherProvider.sendResult(.failure(URLError(.cancelled)))
testScheduler.advance()
XCTAssertTrue(completed)
}
func test_enforces_sla_noResponse() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler, delay: 10)
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.makeRequest(request, sla: .seconds(5), on: testScheduler)
.sink { completion in
switch completion {
case .finished:
XCTFail()
case let .failure(error):
guard case RequestError<Error>.slaExceeded = error else {
XCTFail()
return
}
completed = true
}
} receiveValue: { response in
XCTFail()
}
.store(in: &cancellables)
XCTAssertFalse(completed)
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
func test_enforces_sla_lateResponse() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler, delay: 6)
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.makeRequest(request, sla: .seconds(5), on: testScheduler)
.sink { completion in
switch completion {
case .finished:
XCTFail()
case let .failure(error):
guard case RequestError<Error>.slaExceeded = error else {
XCTFail()
return
}
completed = true
}
} receiveValue: { response in
XCTFail()
}
.store(in: &cancellables)
XCTAssertFalse(completed)
publisherProvider.sendResult(.success((data: Data(), response: URLResponse())))
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
func test_enforces_sla_lateError() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler, delay: 6)
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.makeRequest(request, sla: .seconds(5), on: testScheduler)
.sink { completion in
switch completion {
case .finished:
XCTFail()
case let .failure(error):
guard case RequestError<Error>.slaExceeded = error else {
XCTFail()
return
}
completed = true
}
} receiveValue: { response in
XCTFail()
}
.store(in: &cancellables)
XCTAssertFalse(completed)
publisherProvider.sendResult(.failure(URLError(.badServerResponse)))
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
func test_usesRequestAuthentication() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
authentication: .token(type: .bearer, value: "request"),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
publisherProvider.validateClosure = { request in
XCTAssertEqual(request.allHTTPHeaderFields?["Authorization"], "Bearer request")
}
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.requestAuthentication = .token(type: .bearer, value: "manager")
manager.makeRequest(request, authentication: .token(type: .bearer, value: "param"), on: testScheduler)
.sink { completion in
switch completion {
case .finished:
completed = true
default:
XCTFail()
}
} receiveValue: { _ in }
.store(in: &cancellables)
XCTAssertFalse(completed)
publisherProvider.sendResult(.success((Data(), URLResponse())))
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
func test_usesParameterAuthentication() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
publisherProvider.validateClosure = { request in
XCTAssertEqual(request.allHTTPHeaderFields?["Authorization"], "Bearer param")
}
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.requestAuthentication = .token(type: .bearer, value: "manager")
manager.makeRequest(request, authentication: .token(type: .bearer, value: "param"), on: testScheduler)
.sink { completion in
switch completion {
case .finished:
completed = true
default:
XCTFail()
}
} receiveValue: { _ in }
.store(in: &cancellables)
XCTAssertFalse(completed)
publisherProvider.sendResult(.success((Data(), URLResponse())))
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
func test_usesManagerAuthentication() {
var completed = false
let testScheduler = DispatchQueue.ombiTest
let request = TestRequest<Data, Data, Error>(path: "/",
query: [],
method: .post,
headers: [:],
body: "REQUEST".data(using: .utf8),
fallbackResponse: nil,
requestEncoder: .default,
responseDecoder: .default,
responseValidator: .unsafe,
timeoutInterval: 120.0)
let publisherProvider = ResponsePublisherProvidingMock(scheduler: testScheduler)
publisherProvider.validateClosure = { request in
XCTAssertEqual(request.allHTTPHeaderFields?["Authorization"], "Bearer manager")
}
let manager = RequestManager(host: "https://api.myapp.com",
session: publisherProvider,
log: nil)
manager.requestAuthentication = .token(type: .bearer, value: "manager")
manager.makeRequest(request, on: testScheduler)
.sink { completion in
switch completion {
case .finished:
completed = true
default:
XCTFail()
}
} receiveValue: { _ in }
.store(in: &cancellables)
XCTAssertFalse(completed)
publisherProvider.sendResult(.success((Data(), URLResponse())))
testScheduler.advance(by: .seconds(6))
XCTAssertTrue(completed)
}
override func tearDown() {
cancellables.forEach { $0.cancel() }
}
}
private class ResponsePublisherProvidingMock: ResponsePublisherProviding {
init(scheduler: TestSchedulerOf<DispatchQueue>, delay: TimeInterval = 0.0) {
self.scheduler = scheduler
self.delay = delay
}
func publisher(for urlRequest: URLRequest) -> AnyPublisher<(data: Data, response: URLResponse), URLError> {
validateClosure(urlRequest)
return subject
.delay(for: .seconds(delay), scheduler: scheduler)
.eraseToAnyPublisher()
}
var validateClosure: (URLRequest) -> Void = { _ in }
func sendResult(_ result: Result<(data: Data, response: URLResponse), URLError>) {
do {
let response = try result.get()
subject.send(response)
subject.send(completion: .finished)
} catch {
subject.send(completion: .failure(error as! URLError))
}
}
private let subject = PassthroughSubject<(data: Data, response: URLResponse), URLError>()
private let delay: TimeInterval
private let scheduler: TestSchedulerOf<DispatchQueue>
}
| 48.426407 | 131 | 0.470254 |
16f1bbb12cda37532a1a6637898915a23b6b879f | 1,068 | //
// MasterViewController.swift
// KloodUniversityAttendees
//
// Created by John Yorke on 04/11/2015.
// Copyright © 2015 John Yorke. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
//MARK: Required
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return howManySectionsInTable()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return howManyCellsInSection(section)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = textForCellNumber(indexPath.row)
return cell
}
//MARK: Abstraction
func howManySectionsInTable() -> Int {
return 1
}
func howManyCellsInSection(section : Int) -> Int {
return 2
}
func textForCellNumber(number : Int) -> String {
return "Hi!"
}
}
| 23.733333 | 118 | 0.654494 |
2fa39e62e2c9672b80f7c20cb6e143e502253ba0 | 1,062 | //
// MarkDownImageProcessor.swift
// markymark
//
// Created by Stefan Compton on 10/14/20.
//
import Kingfisher
import UIKit
struct MarkDownImageProcessor: ImageProcessor {
// `identifier` should be the same for processors with same properties/functionality
// It will be used when storing and retrieving the image to/from cache.
let identifier = "com.m2mobi.marky-mark.MarkDownImageProcessor"
// Convert input data/image to target image and return it.
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
case .data(let data):
// If we have a known/supported image format then defer to standard data processing
guard data.kf.imageFormat == .unknown else {
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
return PDFConverter.image(with: data)
}
}
}
| 33.1875 | 105 | 0.681733 |
f820f53daebe757bdb68d3015566e8530d020975 | 4,746 | //
// HalfPieChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class HalfPieChartViewController: DemoBaseViewController {
@IBOutlet var chartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Half Pie Chart"
self.options = [.toggleValues,
.toggleXValues,
.togglePercent,
.toggleHole,
.animateX,
.animateY,
.animateXY,
.spin,
.drawCenter,
.saveToGallery,
.toggleData]
self.setup(pieChartView: chartView)
chartView.delegate = self
chartView.holeColor = .white
chartView.transparentCircleColor = NSUIColor.white.withAlphaComponent(0.43)
chartView.holeRadiusPercent = 0.58
chartView.rotationEnabled = false
chartView.highlightPerTapEnabled = true
chartView.maxAngle = 180 // Half chart
chartView.rotationAngle = 180 // Rotate to make the half on the upper side
chartView.centerTextOffset = CGPoint(x: 0, y: -20)
let l = chartView.legend
l.horizontalAlignment = .center
l.verticalAlignment = .top
l.orientation = .horizontal
l.drawInside = false
l.xEntrySpace = 7
l.yEntrySpace = 0
l.yOffset = 0
// chartView.legend = l
// entry label styling
chartView.entryLabelColor = .white
chartView.entryLabelFont = UIFont(name:"HelveticaNeue-Light", size:12)!
self.updateChartData()
chartView.animate(xAxisDuration: 1.4, easingOption: .easeOutBack)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(4, range: 100)
}
func setDataCount(_ count: Int, range: UInt32) {
let entries = (0..<count).map { (i) -> PieChartDataEntry in
// IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other.
return PieChartDataEntry(value: Double(arc4random_uniform(range) + range / 5),
label: parties[i % parties.count])
}
let set = PieChartDataSet(values: entries, label: "Election Results")
set.sliceSpace = 3
set.selectionShift = 5
set.colors = ChartColorTemplates.material()
let data = PieChartData(dataSet: set)
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = " %"
data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 11)!)
data.setValueTextColor(.white)
chartView.data = data
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleXValues:
chartView.drawEntryLabelsEnabled = !chartView.drawEntryLabelsEnabled
chartView.setNeedsDisplay()
case .togglePercent:
chartView.usePercentValuesEnabled = !chartView.usePercentValuesEnabled
chartView.setNeedsDisplay()
case .toggleHole:
chartView.drawHoleEnabled = !chartView.drawHoleEnabled
chartView.setNeedsDisplay()
case .drawCenter:
chartView.drawCenterTextEnabled = !chartView.drawCenterTextEnabled
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 1.4)
case .animateY:
chartView.animate(yAxisDuration: 1.4)
case .animateXY:
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4)
case .spin:
chartView.spin(duration: 2,
fromAngle: chartView.rotationAngle,
toAngle: chartView.rotationAngle + 360,
easingOption: .easeInCubic)
default:
handleOption(option, forChartView: chartView)
}
}
}
| 33.188811 | 168 | 0.571007 |
fb521ba8232f7ff784b8e925666b593342c1cdf3 | 3,846 | //
// ItemCompareViewController.swift
// BattleBuddy
//
// Created by Mike on 7/15/19.
// Copyright © 2019 Veritas. All rights reserved.
//
import UIKit
class ItemCompareViewController: BaseTableViewController {
var comparison: ItemComparison
let comparisonCellReuseId = "ComparisonCell"
required init?(coder aDecoder: NSCoder) { fatalError() }
init(_ comparison: ItemComparison) {
self.comparison = comparison
super.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
title = Localized("compare")
tableView.register(ComparisonCell.self, forCellReuseIdentifier: comparisonCellReuseId)
tableView.rowHeight = 34.0
tableView.separatorStyle = .none
tableView.separatorColor = .clear
}
func didSelectItems(items: [Comparable]) {
self.comparison.itemsBeingCompared = items
tableView.reloadData()
navigationController?.dismiss(animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return comparison.propertyOptions.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comparison.itemsBeingCompared.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return comparison.propertyOptions[section].local(short: false)
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: .medium)
header.textLabel?.textColor = .white
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear
cell.layer.backgroundColor = UIColor.clear.cgColor
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: comparisonCellReuseId, for: indexPath) as! ComparisonCell
let item = comparison.itemsBeingCompared[indexPath.row]
let property = comparison.propertyOptions[indexPath.section]
let percent = comparison.getPercentValue(item: item, property: property, traitCollection: cell.traitCollection)
let color = UIColor.scaledGradientColor(percent: Float(1.0 - (Float(indexPath.row + 1) / Float(comparison.itemsBeingCompared.count))))
cell.update(keyColor: color, name: item.shortTitle, valueText: item.getValueStringForProperty(property), progressPercent: percent)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = comparison.itemsBeingCompared[indexPath.row]
let itemDetailsConfig: ItemDetailsConfiguration
switch item {
case let firearm as Firearm: itemDetailsConfig = FirearmDetailsConfiguration(firearm)
case let ammo as Ammo: itemDetailsConfig = AmmoDetailsConfiguration(ammo)
case let armor as Armor: itemDetailsConfig = ArmorDetailsConfiguration(armor)
case let med as Medical: itemDetailsConfig = MedicalDetailsConfiguration(med)
case let throwable as Throwable: itemDetailsConfig = ThrowableDetailsConfiguration(throwable)
case let melee as MeleeWeapon: itemDetailsConfig = MeleeWeaponDetailsConfiguration(melee)
default: fatalError()
}
let detailsVC = ItemDetailsViewController(itemDetailsConfig)
navigationController?.pushViewController(detailsVC, animated: true)
}
}
| 41.354839 | 142 | 0.722309 |
9c0993fc025eb70e1b03462d8917271f51754f5c | 20,297 | import Foundation
import TSCBasic
import TuistGraph
@testable import TuistCore
// swiftlint:disable:next type_body_length
final class MockGraphTraverser: GraphTraversing {
var invokedNameGetter = false
var invokedNameGetterCount = 0
var stubbedName: String! = ""
var name: String {
invokedNameGetter = true
invokedNameGetterCount += 1
return stubbedName
}
var invokedHasPackagesGetter = false
var invokedHasPackagesGetterCount = 0
var stubbedHasPackages: Bool! = false
var hasPackages: Bool {
invokedHasPackagesGetter = true
invokedHasPackagesGetterCount += 1
return stubbedHasPackages
}
var invokedHasRemotePackagesGetter = false
var invokedHasRemotePackagesGetterCount = 0
var stubbedHasRemotePackages: Bool! = false
var hasRemotePackages: Bool {
invokedHasRemotePackagesGetter = true
invokedHasRemotePackagesGetterCount += 1
return stubbedHasRemotePackages
}
var invokedPathGetter = false
var invokedPathGetterCount = 0
var stubbedPath: AbsolutePath!
var path: AbsolutePath {
invokedPathGetter = true
invokedPathGetterCount += 1
return stubbedPath
}
var invokedWorkspaceGetter = false
var invokedWorkspaceGetterCount = 0
var stubbedWorkspace: Workspace!
var workspace: Workspace {
invokedWorkspaceGetter = true
invokedWorkspaceGetterCount += 1
return stubbedWorkspace
}
var invokedProjectsGetter = false
var invokedProjectsGetterCount = 0
var stubbedProjects: [AbsolutePath: Project]! = [:]
var projects: [AbsolutePath: Project] {
invokedProjectsGetter = true
invokedProjectsGetterCount += 1
return stubbedProjects
}
var invokedTargetsGetter = false
var invokedTargetsGetterCount = 0
var stubbedTargets: [AbsolutePath: [String: Target]]! = [:]
var targets: [AbsolutePath: [String: Target]] {
invokedTargetsGetter = true
invokedTargetsGetterCount += 1
return stubbedTargets
}
var invokedDependenciesGetter = false
var invokedDependenciesGetterCount = 0
var stubbedDependencies: [GraphDependency: Set<GraphDependency>]! = [:]
var dependencies: [GraphDependency: Set<GraphDependency>] {
invokedDependenciesGetter = true
invokedDependenciesGetterCount += 1
return stubbedDependencies
}
var invokedApps = false
var invokedAppsCount = 0
var stubbedAppsResult: Set<GraphTarget>! = []
func apps() -> Set<GraphTarget> {
invokedApps = true
invokedAppsCount += 1
return stubbedAppsResult
}
var invokedRootTargets = false
var invokedRootTargetsCount = 0
var stubbedRootTargetsResult: Set<GraphTarget>! = []
func rootTargets() -> Set<GraphTarget> {
invokedRootTargets = true
invokedRootTargetsCount += 1
return stubbedRootTargetsResult
}
var invokedRootProjects = false
var invokedRootProjectsCount = 0
var stubbedRootProjectsResult: Set<Project>! = []
func rootProjects() -> Set<Project> {
invokedRootProjects = true
invokedRootProjectsCount += 1
return stubbedRootProjectsResult
}
var invokedAllTargets = false
var invokedAllTargetsCount = 0
var stubbedAllTargetsResult: Set<GraphTarget>! = []
func allTargets() -> Set<GraphTarget> {
invokedAllTargets = true
invokedAllTargetsCount += 1
return stubbedAllTargetsResult
}
var invokedPrecompiledFrameworksPaths = false
var invokedPrecompiledFrameworksPathsCount = 0
var stubbedPrecompiledFrameworksPathsResult: Set<AbsolutePath>! = []
func precompiledFrameworksPaths() -> Set<AbsolutePath> {
invokedPrecompiledFrameworksPaths = true
invokedPrecompiledFrameworksPathsCount += 1
return stubbedPrecompiledFrameworksPathsResult
}
var invokedTargetsProduct = false
var invokedTargetsProductCount = 0
var invokedTargetsProductParameters: (product: Product, Void)?
var invokedTargetsProductParametersList = [(product: Product, Void)]()
var stubbedTargetsProductResult: Set<GraphTarget>! = []
func targets(product: Product) -> Set<GraphTarget> {
invokedTargetsProduct = true
invokedTargetsProductCount += 1
invokedTargetsProductParameters = (product, ())
invokedTargetsProductParametersList.append((product, ()))
return stubbedTargetsProductResult
}
var invokedTarget = false
var invokedTargetCount = 0
var invokedTargetParameters: (path: AbsolutePath, name: String)?
var invokedTargetParametersList = [(path: AbsolutePath, name: String)]()
var stubbedTargetResult: GraphTarget!
func target(path: AbsolutePath, name: String) -> GraphTarget? {
invokedTarget = true
invokedTargetCount += 1
invokedTargetParameters = (path, name)
invokedTargetParametersList.append((path, name))
return stubbedTargetResult
}
var invokedTargetsAt = false
var invokedTargetsAtCount = 0
var invokedTargetsAtParameters: (path: AbsolutePath, Void)?
var invokedTargetsAtParametersList = [(path: AbsolutePath, Void)]()
var stubbedTargetsAtResult: Set<GraphTarget>! = []
func targets(at path: AbsolutePath) -> Set<GraphTarget> {
invokedTargetsAt = true
invokedTargetsAtCount += 1
invokedTargetsAtParameters = (path, ())
invokedTargetsAtParametersList.append((path, ()))
return stubbedTargetsAtResult
}
var invokedTestTargetsDependingOn = false
var invokedTestTargetsDependingOnCount = 0
var invokedTestTargetsDependingOnParameters: (path: AbsolutePath, name: String)?
var invokedTestTargetsDependingOnParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedTestTargetsDependingOnResult: Set<GraphTarget>! = []
func testTargetsDependingOn(path: AbsolutePath, name: String) -> Set<GraphTarget> {
invokedTestTargetsDependingOn = true
invokedTestTargetsDependingOnCount += 1
invokedTestTargetsDependingOnParameters = (path, name)
invokedTestTargetsDependingOnParametersList.append((path, name))
return stubbedTestTargetsDependingOnResult
}
var invokedDirectLocalTargetDependencies = false
var invokedDirectLocalTargetDependenciesCount = 0 // swiftlint:disable:this identifier_name
var invokedDirectLocalTargetDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedDirectLocalTargetDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedDirectLocalTargetDependenciesResult: Set<GraphTarget>! = [] // swiftlint:disable:this identifier_name
func directLocalTargetDependencies(path: AbsolutePath, name: String) -> Set<GraphTarget> {
invokedDirectLocalTargetDependencies = true
invokedDirectLocalTargetDependenciesCount += 1
invokedDirectLocalTargetDependenciesParameters = (path, name)
invokedDirectLocalTargetDependenciesParametersList.append((path, name))
return stubbedDirectLocalTargetDependenciesResult
}
var invokedDirectTargetDependencies = false
var invokedDirectTargetDependenciesCount = 0
var invokedDirectTargetDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedDirectTargetDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedDirectTargetDependenciesResult: Set<GraphTarget>! = []
func directTargetDependencies(path: AbsolutePath, name: String) -> Set<GraphTarget> {
invokedDirectTargetDependencies = true
invokedDirectTargetDependenciesCount += 1
invokedDirectTargetDependenciesParameters = (path, name)
invokedDirectTargetDependenciesParametersList.append((path, name))
return stubbedDirectTargetDependenciesResult
}
var invokedAppExtensionDependencies = false
var invokedAppExtensionDependenciesCount = 0
var invokedAppExtensionDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedAppExtensionDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedAppExtensionDependenciesResult: Set<GraphTarget>! = []
func appExtensionDependencies(path: AbsolutePath, name: String) -> Set<GraphTarget> {
invokedAppExtensionDependencies = true
invokedAppExtensionDependenciesCount += 1
invokedAppExtensionDependenciesParameters = (path, name)
invokedAppExtensionDependenciesParametersList.append((path, name))
return stubbedAppExtensionDependenciesResult
}
var invokedResourceBundleDependencies = false
var invokedResourceBundleDependenciesCount = 0
var invokedResourceBundleDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedResourceBundleDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedResourceBundleDependenciesResult: Set<GraphDependencyReference>! = []
func resourceBundleDependencies(path: AbsolutePath, name: String) -> Set<GraphDependencyReference> {
invokedResourceBundleDependencies = true
invokedResourceBundleDependenciesCount += 1
invokedResourceBundleDependenciesParameters = (path, name)
invokedResourceBundleDependenciesParametersList.append((path, name))
return stubbedResourceBundleDependenciesResult
}
var invokedDirectStaticDependencies = false
var invokedDirectStaticDependenciesCount = 0
var invokedDirectStaticDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedDirectStaticDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedDirectStaticDependenciesResult: Set<GraphDependencyReference>! = []
func directStaticDependencies(path: AbsolutePath, name: String) -> Set<GraphDependencyReference> {
invokedDirectStaticDependencies = true
invokedDirectStaticDependenciesCount += 1
invokedDirectStaticDependenciesParameters = (path, name)
invokedDirectStaticDependenciesParametersList.append((path, name))
return stubbedDirectStaticDependenciesResult
}
var invokedAppClipDependencies = false
var invokedAppClipDependenciesCount = 0
var invokedAppClipDependenciesParameters: (path: AbsolutePath, name: String)?
var invokedAppClipDependenciesParametersList = [(path: AbsolutePath, name: String)]()
var stubbedAppClipDependenciesResult: GraphTarget!
func appClipDependencies(path: AbsolutePath, name: String) -> GraphTarget? {
invokedAppClipDependencies = true
invokedAppClipDependenciesCount += 1
invokedAppClipDependenciesParameters = (path, name)
invokedAppClipDependenciesParametersList.append((path, name))
return stubbedAppClipDependenciesResult
}
var invokedEmbeddableFrameworks = false
var invokedEmbeddableFrameworksCount = 0
var invokedEmbeddableFrameworksParameters: (path: AbsolutePath, name: String)?
var invokedEmbeddableFrameworksParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedEmbeddableFrameworksResult: Set<GraphDependencyReference>! = []
func embeddableFrameworks(path: AbsolutePath, name: String) -> Set<GraphDependencyReference> {
invokedEmbeddableFrameworks = true
invokedEmbeddableFrameworksCount += 1
invokedEmbeddableFrameworksParameters = (path, name)
invokedEmbeddableFrameworksParametersList.append((path, name))
return stubbedEmbeddableFrameworksResult
}
var invokedLinkableDependencies = false
var invokedLinkableDependenciesCount = 0
var invokedLinkableDependenciesParameters: (path: AbsolutePath, name: String)?
var invokedLinkableDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedLinkableDependenciesError: Error?
var stubbedLinkableDependenciesResult: Set<GraphDependencyReference>! = []
func linkableDependencies(path: AbsolutePath, name: String) throws -> Set<GraphDependencyReference> {
invokedLinkableDependencies = true
invokedLinkableDependenciesCount += 1
invokedLinkableDependenciesParameters = (path, name)
invokedLinkableDependenciesParametersList.append((path, name))
if let error = stubbedLinkableDependenciesError {
throw error
}
return stubbedLinkableDependenciesResult
}
var invokedSearchablePathDependencies = false
var invokedSearchablePathDependenciesCount = 0
var invokedSearchablePathDependenciesParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedSearchablePathDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedSearchablePathDependenciesError: Error?
var stubbedSearchablePathDependenciesResult: Set<GraphDependencyReference>! = []
func searchablePathDependencies(path: AbsolutePath, name: String) throws -> Set<GraphDependencyReference> {
invokedSearchablePathDependencies = true
invokedSearchablePathDependenciesCount += 1
invokedSearchablePathDependenciesParameters = (path, name)
invokedSearchablePathDependenciesParametersList.append((path, name))
if let error = stubbedSearchablePathDependenciesError {
throw error
}
return stubbedSearchablePathDependenciesResult
}
var invokedCopyProductDependencies = false
var invokedCopyProductDependenciesCount = 0
var invokedCopyProductDependenciesParameters: (path: AbsolutePath, name: String)?
var invokedCopyProductDependenciesParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedCopyProductDependenciesResult: Set<GraphDependencyReference>! = []
func copyProductDependencies(path: AbsolutePath, name: String) -> Set<GraphDependencyReference> {
invokedCopyProductDependencies = true
invokedCopyProductDependenciesCount += 1
invokedCopyProductDependenciesParameters = (path, name)
invokedCopyProductDependenciesParametersList.append((path, name))
return stubbedCopyProductDependenciesResult
}
var invokedLibrariesPublicHeadersFolders = false
var invokedLibrariesPublicHeadersFoldersCount = 0 // swiftlint:disable:this identifier_name
var invokedLibrariesPublicHeadersFoldersParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedLibrariesPublicHeadersFoldersParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedLibrariesPublicHeadersFoldersResult: Set<AbsolutePath>! = [] // swiftlint:disable:this identifier_name
func librariesPublicHeadersFolders(path: AbsolutePath, name: String) -> Set<AbsolutePath> {
invokedLibrariesPublicHeadersFolders = true
invokedLibrariesPublicHeadersFoldersCount += 1
invokedLibrariesPublicHeadersFoldersParameters = (path, name)
invokedLibrariesPublicHeadersFoldersParametersList.append((path, name))
return stubbedLibrariesPublicHeadersFoldersResult
}
var invokedLibrariesSearchPaths = false
var invokedLibrariesSearchPathsCount = 0
var invokedLibrariesSearchPathsParameters: (path: AbsolutePath, name: String)?
var invokedLibrariesSearchPathsParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedLibrariesSearchPathsResult: Set<AbsolutePath>! = []
func librariesSearchPaths(path: AbsolutePath, name: String) -> Set<AbsolutePath> {
invokedLibrariesSearchPaths = true
invokedLibrariesSearchPathsCount += 1
invokedLibrariesSearchPathsParameters = (path, name)
invokedLibrariesSearchPathsParametersList.append((path, name))
return stubbedLibrariesSearchPathsResult
}
var invokedLibrariesSwiftIncludePaths = false
var invokedLibrariesSwiftIncludePathsCount = 0
var invokedLibrariesSwiftIncludePathsParameters: (path: AbsolutePath, name: String)? // swiftlint:disable:this identifier_name
var invokedLibrariesSwiftIncludePathsParametersList = [(path: AbsolutePath, name: String)]() // swiftlint:disable:this identifier_name
var stubbedLibrariesSwiftIncludePathsResult: Set<AbsolutePath>! = []
func librariesSwiftIncludePaths(path: AbsolutePath, name: String) -> Set<AbsolutePath> {
invokedLibrariesSwiftIncludePaths = true
invokedLibrariesSwiftIncludePathsCount += 1
invokedLibrariesSwiftIncludePathsParameters = (path, name)
invokedLibrariesSwiftIncludePathsParametersList.append((path, name))
return stubbedLibrariesSwiftIncludePathsResult
}
var invokedRunPathSearchPaths = false
var invokedRunPathSearchPathsCount = 0
var invokedRunPathSearchPathsParameters: (path: AbsolutePath, name: String)?
var invokedRunPathSearchPathsParametersList = [(path: AbsolutePath, name: String)]()
var stubbedRunPathSearchPathsResult: Set<AbsolutePath>! = []
func runPathSearchPaths(path: AbsolutePath, name: String) -> Set<AbsolutePath> {
invokedRunPathSearchPaths = true
invokedRunPathSearchPathsCount += 1
invokedRunPathSearchPathsParameters = (path, name)
invokedRunPathSearchPathsParametersList.append((path, name))
return stubbedRunPathSearchPathsResult
}
var invokedHostTargetFor = false
var invokedHostTargetForCount = 0
var invokedHostTargetForParameters: (path: AbsolutePath, name: String)?
var invokedHostTargetForParametersList = [(path: AbsolutePath, name: String)]()
var stubbedHostTargetForResult: GraphTarget!
func hostTargetFor(path: AbsolutePath, name: String) -> GraphTarget? {
invokedHostTargetFor = true
invokedHostTargetForCount += 1
invokedHostTargetForParameters = (path, name)
invokedHostTargetForParametersList.append((path, name))
return stubbedHostTargetForResult
}
var invokedAllProjectDependencies = false
var invokedAllProjectDependenciesCount = 0
var invokedAllProjectDependenciesParameters: (path: AbsolutePath, Void)?
var invokedAllProjectDependenciesParametersList = [(path: AbsolutePath, Void)]() // swiftlint:disable:this identifier_name
var stubbedAllProjectDependenciesError: Error?
var stubbedAllProjectDependenciesResult: Set<GraphDependencyReference>! = []
func allProjectDependencies(path: AbsolutePath) throws -> Set<GraphDependencyReference> {
invokedAllProjectDependencies = true
invokedAllProjectDependenciesCount += 1
invokedAllProjectDependenciesParameters = (path, ())
invokedAllProjectDependenciesParametersList.append((path, ()))
if let error = stubbedAllProjectDependenciesError {
throw error
}
return stubbedAllProjectDependenciesResult
}
var invokedDependsOnXCTest = false
var invokedDependsOnXCTestCount = 0
var invokedDependsOnXCTestParameters: (path: AbsolutePath, name: String)?
var invokedDependsOnXCTestParametersList = [(path: AbsolutePath, name: String)]()
var stubbedDependsOnXCTestResult: Bool! = false
func dependsOnXCTest(path: AbsolutePath, name: String) -> Bool {
invokedDependsOnXCTest = true
invokedDependsOnXCTestCount += 1
invokedDependsOnXCTestParameters = (path, name)
invokedDependsOnXCTestParametersList.append((path, name))
return stubbedDependsOnXCTestResult
}
var schemesStub: (() -> [Scheme])?
func schemes() -> [Scheme] {
schemesStub?() ?? []
}
}
| 45.104444 | 141 | 0.748879 |
5be93d74064a0f1b7beb2aeb83242696f0c3a00a | 555 | //
// DisplayField.swift
//
// Created on 04/03/2020.
// Copyright © 2020 WildAid. All rights reserved.
//
import SwiftUI
struct DisplayField: View {
var title: String
var value: String
var body: some View {
VStack(alignment: .leading) {
CaptionLabel(title: title)
Text(value)
.foregroundColor(.black)
Divider()
}
}
}
struct DisplayField_Previews: PreviewProvider {
static var previews: some View {
DisplayField(title: "Title", value: "Value")
}
}
| 19.137931 | 52 | 0.590991 |
9125f8f269c5f903862d0db657e58cc4d03b60ae | 3,197 | //
// AppDelegate.swift
// WeatherGraph
//
// Created by Jens Bruggemans on 29/07/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Jens Bruggemans
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
@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:.
}
}
| 47.014706 | 281 | 0.767282 |
e9edf562c7afc1f4f64d25f8a3276c40da953983 | 3,396 | //
// OperationFormatter.swift
// falcon
//
// Created by Juan Pablo Civile on 29/03/2019.
// Copyright © 2019 muun. All rights reserved.
//
import Foundation
import UIKit
import core
struct OperationFormatter {
let operation: core.Operation
enum Status {
case COMPLETED
case PENDING
case FAILED
case CANCELABLE
case CONFIRMING
}
var simpleStatus: Status {
// Only incoming operations can be cancelable in the UI
if operation.isCancelable() && operation.direction == .INCOMING {
return .CANCELABLE
}
switch operation.status {
case .CREATED, .BROADCASTED, .SIGNING, .SIGNED, .SWAP_PENDING, .SWAP_ROUTING:
return .PENDING
case .DROPPED, .FAILED, .SWAP_FAILED, .SWAP_EXPIRED:
return .FAILED
case .CONFIRMED, .SETTLED, .SWAP_PAYED:
return .COMPLETED
case .SWAP_OPENING_CHANNEL, .SWAP_WAITING_CHANNEL:
return .CONFIRMING
}
}
var title: String {
switch operation.direction {
case .CYCLICAL:
return L10n.OperationFormatter.s1
case .INCOMING:
return L10n.OperationFormatter.s2
case .OUTGOING:
var text = L10n.OperationFormatter.s3
if let alias = operation.submarineSwap?._receiver._alias {
text.append(" \(alias)")
}
return text
}
}
var shortStatus: String {
switch simpleStatus {
case .PENDING, .CONFIRMING:
return L10n.OperationFormatter.s4
case .FAILED:
return L10n.OperationFormatter.s5
case .CANCELABLE:
return L10n.OperationFormatter.cancelable
case .COMPLETED:
return ""
}
}
var status: String {
// Only incoming operations can be cancelable in the UI
if operation.isCancelable() && operation.direction == .INCOMING {
return L10n.OperationFormatter.cancelable
}
switch operation.status {
case .CREATED, .BROADCASTED, .SIGNING, .SIGNED,
.SWAP_PENDING, .SWAP_ROUTING, .SWAP_WAITING_CHANNEL, .SWAP_OPENING_CHANNEL:
return L10n.OperationFormatter.s4
case .DROPPED, .FAILED, .SWAP_FAILED, .SWAP_EXPIRED:
return L10n.OperationFormatter.s5
case .CONFIRMED, .SETTLED, .SWAP_PAYED:
return L10n.OperationFormatter.s9
}
}
var color: UIColor {
switch simpleStatus {
case .PENDING, .CONFIRMING:
return Asset.Colors.muunWarning.color
case .FAILED:
return Asset.Colors.muunRed.color
case .CANCELABLE:
return Asset.Colors.muunWarningRBF.color
case .COMPLETED:
return Asset.Colors.muunGreen.color
}
}
var shortCreationDate: String {
return operation.creationDate.format(showTime: false)
}
var extendedCreationDate: String {
return operation.creationDate.format(showTime: true)
}
var description: String? {
return operation.description
}
var confirmations: String {
if let confs = operation.confirmations {
if confs < 6 {
return String(describing: confs)
}
return "6+"
}
return "0"
}
}
| 25.727273 | 88 | 0.592756 |
1e0e675da3fd61aea4ca19f96445c9b33e0460d1 | 1,208 |
import UIKit
class CompassViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
let compass = CompassView()
self.view.addSubview(compass)
compass.translatesAutoresizingMaskIntoConstraints = false
compass.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
compass.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
compass.heightAnchor.constraint(equalTo: compass.widthAnchor).isActive = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 31.789474 | 106 | 0.692053 |
756833c159d2c04d748c476db84727143c8df175 | 1,118 | //
// PBKDF2.swift
// NeoSwift
//
// Created by Luís Silva on 22/09/17.
// Copyright © 2017 drei. All rights reserved.
//
import Foundation
//import CommonCrypto
struct PBKDF2 {
static public func deriveKey(password: [UInt8], salt: [UInt8], rounds: UInt32, keyLength: Int) -> [UInt8] {
var result: [UInt8] = [UInt8](repeating: 0, count: keyLength)
var status: UInt32 = 0
let data = Data(password)
data.withUnsafeBytes { (passwordPtr: UnsafePointer<Int8>) in
let status = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2),
passwordPtr,
password.count,
salt,
salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
rounds,
&result,
keyLength)
}
return result
}
}
| 33.878788 | 111 | 0.44186 |
de78db856f5b1e4cd9c40d7591c6a6cc787f4833 | 22,733 | // Created by bryankeller on 7/9/17.
// Copyright © 2018 Airbnb, 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 CoreGraphics
import Foundation
/// Represents the layout information for a section.
struct SectionModel {
// MARK: Lifecycle
init(
itemModels: [ItemModel],
headerModel: HeaderModel?,
footerModel: FooterModel?,
backgroundModel: BackgroundModel?,
metrics: MagazineLayoutSectionMetrics)
{
id = NSUUID().uuidString
self.itemModels = itemModels
self.headerModel = headerModel
self.footerModel = footerModel
self.backgroundModel = backgroundModel
self.metrics = metrics
calculatedHeight = 0
numberOfRows = 0
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: 0)
calculateElementFramesIfNecessary()
}
// MARK: Internal
let id: String
private(set) var headerModel: HeaderModel?
private(set) var footerModel: FooterModel?
private(set) var backgroundModel: BackgroundModel?
var visibleBounds: CGRect?
var numberOfItems: Int {
return itemModels.count
}
func idForItemModel(atIndex index: Int) -> String {
return itemModels[index].id
}
func indexForItemModel(withID id: String) -> Int? {
return itemModels.index { $0.id == id }
}
func itemModel(atIndex index: Int) -> ItemModel {
return itemModels[index]
}
func preferredHeightForItemModel(atIndex index: Int) -> CGFloat? {
return itemModels[index].preferredHeight
}
mutating func calculateHeight() -> CGFloat {
calculateElementFramesIfNecessary()
return calculatedHeight
}
mutating func calculateFrameForItem(atIndex index: Int) -> CGRect {
calculateElementFramesIfNecessary()
var origin = itemModels[index].originInSection
if let rowIndex = rowIndicesForItemIndices[index] {
origin.y += rowOffsetTracker?.offsetForRow(at: rowIndex) ?? 0
} else {
assertionFailure("Expected a row and a row height for item at \(index).")
}
return CGRect(origin: origin, size: itemModels[index].size)
}
mutating func calculateFrameForHeader(
inSectionVisibleBounds sectionVisibleBounds: CGRect)
-> CGRect?
{
guard headerModel != nil else { return nil }
calculateElementFramesIfNecessary()
// `headerModel` is a value type that might be mutated in `calculateElementFramesIfNecessary`,
// so we can't use a copy made before that code executes (for example, in a
// `guard let headerModel = headerModel else { ... }` at the top of this function).
if let headerModel = headerModel {
let originY: CGFloat
if headerModel.pinToVisibleBounds {
originY = max(
min(
sectionVisibleBounds.minY,
calculateHeight() -
metrics.sectionInsets.bottom -
(footerModel?.size.height ?? 0) -
headerModel.size.height),
headerModel.originInSection.y)
} else {
originY = headerModel.originInSection.y
}
return CGRect(
origin: CGPoint(x: headerModel.originInSection.x, y: originY),
size: headerModel.size)
} else {
return nil
}
}
mutating func calculateFrameForFooter(
inSectionVisibleBounds sectionVisibleBounds: CGRect)
-> CGRect?
{
guard footerModel != nil else { return nil }
calculateElementFramesIfNecessary()
var origin = footerModel?.originInSection
if let rowIndex = indexOfFooterRow() {
origin?.y += rowOffsetTracker?.offsetForRow(at: rowIndex) ?? 0
} else {
assertionFailure("Expected a row and a corresponding section footer.")
}
// `footerModel` is a value type that might be mutated in `calculateElementFramesIfNecessary`,
// so we can't use a copy made before that code executes (for example, in a
// `guard let footerModel = footerModel else { ... }` at the top of this function).
if let footerModel = footerModel, let origin = origin {
let originY: CGFloat
if footerModel.pinToVisibleBounds {
originY = min(
max(
sectionVisibleBounds.maxY - footerModel.size.height,
metrics.sectionInsets.top + (headerModel?.size.height ?? 0)),
origin.y)
} else {
originY = origin.y
}
return CGRect(
origin: CGPoint(x: footerModel.originInSection.x, y: originY),
size: footerModel.size)
} else {
return nil
}
}
mutating func calculateFrameForBackground() -> CGRect? {
let calculatedHeight = calculateHeight()
backgroundModel?.originInSection = CGPoint(
x: metrics.sectionInsets.left,
y: metrics.sectionInsets.top)
backgroundModel?.size.width = metrics.width
backgroundModel?.size.height = calculatedHeight -
metrics.sectionInsets.top -
metrics.sectionInsets.bottom
if let backgroundModel = backgroundModel {
return CGRect(
origin: CGPoint(x: backgroundModel.originInSection.x, y: backgroundModel.originInSection.y),
size: backgroundModel.size)
} else {
return nil
}
}
@discardableResult
mutating func deleteItemModel(atIndex indexOfDeletion: Int) -> ItemModel {
updateIndexOfFirstInvalidatedRow(forChangeToItemAtIndex: indexOfDeletion)
return itemModels.remove(at: indexOfDeletion)
}
mutating func insert(_ itemModel: ItemModel, atIndex indexOfInsertion: Int) {
updateIndexOfFirstInvalidatedRow(forChangeToItemAtIndex: indexOfInsertion)
itemModels.insert(itemModel, at: indexOfInsertion)
}
mutating func updateMetrics(to metrics: MagazineLayoutSectionMetrics) {
guard self.metrics != metrics else { return }
self.metrics = metrics
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: 0)
}
mutating func updateItemSizeMode(to sizeMode: MagazineLayoutItemSizeMode, zIndex: Int?, atIndex index: Int) {
// Accessing this array using an unsafe, untyped (raw) pointer avoids expensive copy-on-writes
// and Swift retain / release calls.
let itemModelsPointer = UnsafeMutableRawPointer(mutating: &itemModels)
let directlyMutableItemModels = itemModelsPointer.assumingMemoryBound(to: ItemModel.self)
directlyMutableItemModels[index].sizeMode = sizeMode
directlyMutableItemModels[index].zIndex = zIndex
if case let .static(staticHeight) = sizeMode.heightMode {
directlyMutableItemModels[index].size.height = staticHeight
}
updateIndexOfFirstInvalidatedRow(forChangeToItemAtIndex: index)
}
mutating func setHeader(_ headerModel: HeaderModel) {
let oldPreferredHeight = self.headerModel?.preferredHeight
self.headerModel = headerModel
if case let .static(staticHeight) = headerModel.heightMode {
self.headerModel?.size.height = staticHeight
} else if case .dynamic = headerModel.heightMode {
self.headerModel?.preferredHeight = oldPreferredHeight
}
if let indexOfHeader = indexOfHeaderRow() {
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: indexOfHeader)
}
}
mutating func setFooter(_ footerModel: FooterModel) {
let oldPreferredHeight = self.footerModel?.preferredHeight
self.footerModel = footerModel
if case let .static(staticHeight) = footerModel.heightMode {
self.footerModel?.size.height = staticHeight
} else if case .dynamic = footerModel.heightMode {
self.footerModel?.preferredHeight = oldPreferredHeight
}
if let indexOfFooter = indexOfFooterRow() {
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: indexOfFooter)
}
}
mutating func removeHeader() {
if let indexOfHeader = indexOfHeaderRow() {
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: indexOfHeader)
}
headerModel = nil
}
mutating func removeFooter() {
if let indexOfFooter = indexOfFooterRow() {
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: indexOfFooter)
}
footerModel = nil
}
mutating func updateItemHeight(toPreferredHeight preferredHeight: CGFloat, atIndex index: Int) {
// Accessing this array using an unsafe, untyped (raw) pointer avoids expensive copy-on-writes
// and Swift retain / release calls.
let itemModelsPointer = UnsafeMutableRawPointer(mutating: &itemModels)
let directlyMutableItemModels = itemModelsPointer.assumingMemoryBound(to: ItemModel.self)
directlyMutableItemModels[index].preferredHeight = preferredHeight
if
let rowIndex = rowIndicesForItemIndices[index],
let rowHeight = itemRowHeightsForRowIndices[rowIndex]
{
let newRowHeight = updateHeightsForItemsInRow(at: rowIndex)
let heightDelta = newRowHeight - rowHeight
calculatedHeight += heightDelta
let firstAffectedRowIndex = rowIndex + 1
if firstAffectedRowIndex < numberOfRows {
rowOffsetTracker?.addOffset(heightDelta, forRowsStartingAt: firstAffectedRowIndex)
}
} else {
assertionFailure("Expected a row and a row height for item at \(index).")
return
}
}
mutating func updateHeaderHeight(toPreferredHeight preferredHeight: CGFloat) {
headerModel?.preferredHeight = preferredHeight
if let indexOfHeaderRow = indexOfHeaderRow(), let headerModel = headerModel {
let rowHeight = headerModel.size.height
let newRowHeight = updateHeaderHeight(withMetricsFrom: headerModel)
let heightDelta = newRowHeight - rowHeight
calculatedHeight += heightDelta
let firstAffectedRowIndex = indexOfHeaderRow + 1
if firstAffectedRowIndex < numberOfRows {
rowOffsetTracker?.addOffset(heightDelta, forRowsStartingAt: firstAffectedRowIndex)
}
} else {
assertionFailure("Expected a row, a row height, and a corresponding section header.")
return
}
}
mutating func updateFooterHeight(toPreferredHeight preferredHeight: CGFloat) {
footerModel?.preferredHeight = preferredHeight
if let indexOfFooterRow = indexOfFooterRow(), let footerModel = footerModel {
let rowHeight = footerModel.size.height
let newRowHeight = updateFooterHeight(withMetricsFrom: footerModel)
let heightDelta = newRowHeight - rowHeight
calculatedHeight += heightDelta
let firstAffectedRowIndex = indexOfFooterRow + 1
if firstAffectedRowIndex < numberOfRows {
rowOffsetTracker?.addOffset(heightDelta, forRowsStartingAt: firstAffectedRowIndex)
}
} else {
assertionFailure("Expected a row, a row height, and a corresponding section footer.")
return
}
}
mutating func setBackground(_ backgroundModel: BackgroundModel) {
self.backgroundModel = backgroundModel
// No need to invalidate since the background doesn't affect the layout.
}
mutating func removeBackground() {
backgroundModel = nil
// No need to invalidate since the background doesn't affect the layout.
}
// MARK: Private
private var numberOfRows: Int
private var itemModels: [ItemModel]
private var metrics: MagazineLayoutSectionMetrics
private var calculatedHeight: CGFloat
private var indexOfFirstInvalidatedRow: Int? {
didSet {
guard indexOfFirstInvalidatedRow != nil else { return }
applyRowOffsetsIfNecessary()
}
}
private var itemIndicesForRowIndices = [Int: [Int]]()
private var rowIndicesForItemIndices = [Int: Int]()
private var itemRowHeightsForRowIndices = [Int: CGFloat]()
private var rowOffsetTracker: RowOffsetTracker?
private func maxYForItemsRow(atIndex rowIndex: Int) -> CGFloat? {
guard
let itemIndices = itemIndicesForRowIndices[rowIndex],
let itemY = itemIndices.first.flatMap({ itemModels[$0].originInSection.y }),
let itemHeight = itemIndices.map({ itemModels[$0].size.height }).max() else
{
return nil
}
return itemY + itemHeight
}
private func indexOfHeaderRow() -> Int? {
guard headerModel != nil else { return nil }
return 0
}
private func indexOfFirstItemsRow() -> Int? {
guard numberOfItems > 0 else { return nil }
return headerModel == nil ? 0 : 1
}
private func indexOfLastItemsRow() -> Int? {
guard numberOfItems > 0 else { return nil }
return rowIndicesForItemIndices[numberOfItems - 1]
}
private func indexOfFooterRow() -> Int? {
guard footerModel != nil else { return nil }
return numberOfRows - 1
}
private mutating func updateIndexOfFirstInvalidatedRow(forChangeToItemAtIndex changedIndex: Int) {
guard
let indexOfCurrentRow = rowIndicesForItemIndices[changedIndex],
indexOfCurrentRow > 0 else
{
indexOfFirstInvalidatedRow = rowIndicesForItemIndices[0] ?? 0
return
}
updateIndexOfFirstInvalidatedRowIfNecessary(toProposedIndex: indexOfCurrentRow - 1)
}
private mutating func updateIndexOfFirstInvalidatedRowIfNecessary(
toProposedIndex proposedIndex: Int)
{
indexOfFirstInvalidatedRow = min(proposedIndex, indexOfFirstInvalidatedRow ?? proposedIndex)
}
private mutating func applyRowOffsetsIfNecessary() {
guard let rowOffsetTracker = rowOffsetTracker else { return }
for rowIndex in 0..<numberOfRows {
let rowOffset = rowOffsetTracker.offsetForRow(at: rowIndex)
switch rowIndex {
case indexOfHeaderRow(): headerModel?.originInSection.y += rowOffset
case indexOfFooterRow(): footerModel?.originInSection.y += rowOffset
default:
for itemIndex in itemIndicesForRowIndices[rowIndex] ?? [] {
itemModels[itemIndex].originInSection.y += rowOffset
}
}
}
self.rowOffsetTracker = nil
}
private mutating func calculateElementFramesIfNecessary() {
guard var rowIndex = indexOfFirstInvalidatedRow else { return }
guard rowIndex >= 0 else {
assertionFailure("Invalid `rowIndex` / `indexOfFirstInvalidatedRow` (\(rowIndex)).")
return
}
// Clean up item / row / height mappings starting at our `indexOfFirstInvalidatedRow`; we'll
// make new mappings for those row indices as we do layout calculations below. Since all
// item / row index mappings before `indexOfFirstInvalidatedRow` are still valid, we'll leave
// those alone.
for rowIndexKey in itemIndicesForRowIndices.keys {
guard rowIndexKey >= rowIndex else { continue }
if let itemIndex = itemIndicesForRowIndices[rowIndexKey]?.first {
rowIndicesForItemIndices[itemIndex] = nil
}
itemIndicesForRowIndices[rowIndexKey] = nil
itemRowHeightsForRowIndices[rowIndex] = nil
}
// Header frame calculation
if rowIndex == indexOfHeaderRow(), let existingHeaderModel = headerModel {
rowIndex = 1
headerModel?.originInSection = CGPoint(
x: metrics.sectionInsets.left,
y: metrics.sectionInsets.top)
headerModel?.size.width = metrics.width
updateHeaderHeight(withMetricsFrom: existingHeaderModel)
}
var currentY: CGFloat
// Item frame calculations
let startingItemIndex: Int
if
let indexOfLastItemInPreviousRow = itemIndicesForRowIndices[rowIndex - 1]?.last,
indexOfLastItemInPreviousRow + 1 < numberOfItems,
let maxYForPreviousRow = maxYForItemsRow(atIndex: rowIndex - 1)
{
// There's a previous row of items, so we'll use the max Y of that row as the starting place
// for the current row of items.
startingItemIndex = indexOfLastItemInPreviousRow + 1
currentY = maxYForPreviousRow + metrics.verticalSpacing
} else if (headerModel == nil && rowIndex == 0) || (headerModel != nil && rowIndex == 1) {
// Our starting row doesn't exist yet, so we'll lay out our first row of items.
startingItemIndex = 0
currentY = (headerModel?.originInSection.y ?? metrics.sectionInsets.top) +
(headerModel?.size.height ?? 0)
} else {
// Our starting row is after the last row of items, so we'll skip item layout.
startingItemIndex = numberOfItems
if
let lastRowIndex = indexOfLastItemsRow(),
rowIndex > lastRowIndex,
let maxYOfLastRowOfItems = maxYForItemsRow(atIndex: lastRowIndex)
{
currentY = maxYOfLastRowOfItems
} else {
currentY = (headerModel?.originInSection.y ?? metrics.sectionInsets.top) +
(headerModel?.size.height ?? 0)
}
}
// Accessing this array using an unsafe, untyped (raw) pointer avoids expensive copy-on-writes
// and Swift retain / release calls.
let itemModelsPointer = UnsafeMutableRawPointer(mutating: &itemModels)
let directlyMutableItemModels = itemModelsPointer.assumingMemoryBound(to: ItemModel.self)
var indexInCurrentRow = 0
for itemIndex in startingItemIndex..<numberOfItems {
// Create item / row index mappings
itemIndicesForRowIndices[rowIndex] = itemIndicesForRowIndices[rowIndex] ?? []
itemIndicesForRowIndices[rowIndex]?.append(itemIndex)
rowIndicesForItemIndices[itemIndex] = rowIndex
let itemModel = itemModels[itemIndex]
if itemIndex == 0 {
// Apply top item inset now that we're laying out items
currentY += metrics.itemInsets.top
}
let currentLeadingMargin: CGFloat
let availableWidthForItems: CGFloat
if itemModel.sizeMode.widthMode == .fullWidth(respectsHorizontalInsets: false) {
currentLeadingMargin = metrics.sectionInsets.left
availableWidthForItems = metrics.width
} else {
currentLeadingMargin = metrics.sectionInsets.left + metrics.itemInsets.left
availableWidthForItems = metrics.width - metrics.itemInsets.left - metrics.itemInsets.right
}
let totalSpacing = metrics.horizontalSpacing * (itemModel.sizeMode.widthMode.widthDivisor - 1)
let itemWidth = round(
(availableWidthForItems - totalSpacing) / itemModel.sizeMode.widthMode.widthDivisor)
let itemX = CGFloat(indexInCurrentRow) *
itemWidth + CGFloat(indexInCurrentRow) *
metrics.horizontalSpacing + currentLeadingMargin
let itemY = currentY
directlyMutableItemModels[itemIndex].originInSection = CGPoint(x: itemX, y: itemY)
directlyMutableItemModels[itemIndex].size.width = itemWidth
if
(indexInCurrentRow == Int(itemModel.sizeMode.widthMode.widthDivisor) - 1) ||
(itemIndex == numberOfItems - 1) ||
(itemIndex < numberOfItems - 1 && itemModels[itemIndex + 1].sizeMode.widthMode != itemModel.sizeMode.widthMode)
{
// We've reached the end of the current row, or there are no more items to lay out, or we're
// about to lay out an item with a different width mode. In all cases, we're done laying out
// the current row of items.
let heightOfTallestItemInCurrentRow = updateHeightsForItemsInRow(at: rowIndex)
currentY += heightOfTallestItemInCurrentRow
indexInCurrentRow = 0
// If there are more items to layout, add vertical spacing and increment the row index
if itemIndex < numberOfItems - 1 {
currentY += metrics.verticalSpacing
rowIndex += 1
}
} else {
// We're still adding to the current row
indexInCurrentRow += 1
}
}
if numberOfItems > 0 {
// Apply bottom item inset now that we're done laying out items
currentY += metrics.itemInsets.bottom
}
// Footer frame calculations
if let existingFooterModel = footerModel {
rowIndex += 1
footerModel?.originInSection = CGPoint(x: metrics.sectionInsets.left, y: currentY)
footerModel?.size.width = metrics.width
updateFooterHeight(withMetricsFrom: existingFooterModel)
}
numberOfRows = rowIndex + 1
// Final height calculation
calculatedHeight = currentY + (footerModel?.size.height ?? 0) + metrics.sectionInsets.bottom
// The background frame is calculated just-in-time, since its value doesn't affect the layout.
// Create a row offset tracker now that we know how many rows we have
rowOffsetTracker = RowOffsetTracker(numberOfRows: numberOfRows)
// Mark the layout as clean / no longer invalid
indexOfFirstInvalidatedRow = nil
}
private mutating func updateHeightsForItemsInRow(at rowIndex: Int) -> CGFloat {
guard let indicesForItemsInRow = itemIndicesForRowIndices[rowIndex] else {
assertionFailure("Expected item indices for row \(rowIndex).")
return 0
}
// Accessing this array using an unsafe, untyped (raw) pointer avoids expensive copy-on-writes
// and Swift retain / release calls.
let itemModelsPointer = UnsafeMutableRawPointer(mutating: &itemModels)
let directlyMutableItemModels = itemModelsPointer.assumingMemoryBound(to: ItemModel.self)
var heightOfTallestItem = CGFloat(0)
var stretchToTallestItemInRowItemIndices = Set<Int>()
for itemIndex in indicesForItemsInRow {
let preferredHeight = itemModels[itemIndex].preferredHeight
let height = itemModels[itemIndex].size.height
directlyMutableItemModels[itemIndex].size.height = preferredHeight ?? height
// Handle stretch to tallest item in row height mode for current row
if itemModels[itemIndex].sizeMode.heightMode == .dynamicAndStretchToTallestItemInRow {
stretchToTallestItemInRowItemIndices.insert(itemIndex)
}
heightOfTallestItem = max(heightOfTallestItem, itemModels[itemIndex].size.height)
}
for stretchToTallestItemInRowItemIndex in stretchToTallestItemInRowItemIndices{
directlyMutableItemModels[stretchToTallestItemInRowItemIndex].size.height = heightOfTallestItem
}
itemRowHeightsForRowIndices[rowIndex] = heightOfTallestItem
return heightOfTallestItem
}
@discardableResult
private mutating func updateHeaderHeight(withMetricsFrom headerModel: HeaderModel) -> CGFloat {
let height = headerModel.preferredHeight ?? headerModel.size.height
self.headerModel?.size.height = height
return height
}
@discardableResult
private mutating func updateFooterHeight(withMetricsFrom footerModel: FooterModel) -> CGFloat {
let height = footerModel.preferredHeight ?? footerModel.size.height
self.footerModel?.size.height = height
return height
}
}
| 35.409657 | 121 | 0.711697 |
2f122a5cd52d0383cb43f3279a7e8c0d17075895 | 891 | //
// Criteria.swift
// Guise
//
// Created by Gregory Higley on 12/12/17.
// Copyright © 2017 Gregory Higley. All rights reserved.
//
import Foundation
/**
A convenience type used in `filter` overloads.
Its chief claim to fame is that the pattern match operator
`~=` is defined such that a `Criteria` and a `Keyed` instance
can be compared.
Types are excluded because they are matched using the failable
initializer of the `Keyed` protocol. (See the implementation of
`filter` in the `Resolver` class.)
*/
public typealias Criteria = (name: AnyHashable?, container: AnyHashable?)
public func ~=(lhs: Keyed, rhs: Criteria) -> Bool {
if let name = rhs.name, lhs.name != name { return false }
if let container = rhs.container, lhs.container != container { return false }
return true
}
public func ~=(lhs: Criteria, rhs: Keyed) -> Bool {
return rhs ~= lhs
}
| 27 | 81 | 0.693603 |
e233eca78e939b0e1e3324d0505df952df1922fd | 2,525 | //
// NetApiAlamofire.swift
// FeelingClient
//
// Created by vincent on 13/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
import SwiftyJSON
class NetApi:BaseApi {
var apiUrl = "http://61.164.187.56:8080/"
// var apiUrl = "http://192.168.1.103:8080/"
//简单数据
func makeCallString(method: Alamofire.Method, section: String, headers: [String: String]?, params: [String: AnyObject]?, completionHandler: CompletionHandlerType) {
Alamofire.request(method, apiUrl+section,headers: headers, parameters: params)
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(Result.Success(value))
case .Failure(let error):
completionHandler(Result.Failure(error))
}
}
}
//JSON数据
func makeCall(method: Alamofire.Method, section: String, headers: [String: String]?, params: [String: AnyObject]?, completionHandler: CompletionHandlerType) {
Alamofire.request(method, apiUrl+section,headers: headers, parameters: params)
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(Result.Success(value as? NSDictionary))
case .Failure(let error):
completionHandler(Result.Failure(error))
}
}
}
//array数据列表
func makeCallArray<T: Mappable>(method: Alamofire.Method, section: String, headers: [String: String]?, params: [String: AnyObject]?,
completionHandler: Response<[T], NSError> -> Void ) {
Alamofire.request(method, apiUrl+section,headers: headers, parameters: params)
.responseArray { (response: Response<[T], NSError>) in
completionHandler(response)
}
}
//json类
func makeCallBean<T: Mappable>(method: Alamofire.Method, section: String, headers: [String: String]?, params: [String: AnyObject]?,
completionHandler: Response<T, NSError> -> Void ) {
NSLog("\(apiUrl)/\(section)")
Alamofire.request(method, apiUrl+section,headers: headers, parameters: params)
.responseObject {
(response: Response<T, NSError>) in
completionHandler(response)
}
}
}
| 36.071429 | 168 | 0.605545 |
71ae2af968c34a1a4256fde77facae0b41f1797e | 1,077 | //
// ZGUserProfileBreifTableViewCell.swift
// BlindIn
//
// Created by Zyad Galal on 6/16/19.
// Copyright © 2019 Zyad Galal. All rights reserved.
//
import UIKit
class ZGUserProfileBreifTableViewCell: UITableViewCell {
@IBOutlet weak var containerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var followViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var hangoutsLabel: UILabel!
@IBOutlet weak var followingLabel: UILabel!
@IBOutlet weak var followersLbl: UILabel!
@IBOutlet weak var followView: UIView!
@IBOutlet weak var userDescription: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var userImg: UIImageView!
@IBOutlet weak var followButton: UIButton!
@IBOutlet weak var addBestieButton: UIButton!
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
}
}
| 29.916667 | 73 | 0.725162 |
1e78691f2dbdcea10998de6222a98a3e9f8e282c | 2,219 | //: ## Output Waveform Plot
//: ### If you open the Assitant editor and make sure it shows the
//: ### "Output Waveform Plot.xcplaygroundpage (Timeline) view",
//: ### you should see a plot of the waveform in real time
import XCPlayground
import AudioKit
var oscillator = AKFMOscillator()
oscillator.amplitude = 0.1
oscillator.rampTime = 0.1
AudioKit.output = oscillator
AudioKit.start()
oscillator.start()
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Output Waveform Plot")
addSubview(AKPropertySlider(
property: "Frequency",
format: "%0.2f Hz",
value: oscillator.baseFrequency, maximum: 800,
color: AKColor.yellowColor()
) { frequency in
oscillator.baseFrequency = frequency
})
addSubview(AKPropertySlider(
property: "Carrier Multiplier",
format: "%0.3f",
value: oscillator.carrierMultiplier, maximum: 3,
color: AKColor.redColor()
) { multiplier in
oscillator.carrierMultiplier = multiplier
})
addSubview(AKPropertySlider(
property: "Modulating Multiplier",
format: "%0.3f",
value: oscillator.modulatingMultiplier, maximum: 3,
color: AKColor.greenColor()
) { multiplier in
oscillator.modulatingMultiplier = multiplier
})
addSubview(AKPropertySlider(
property: "Modulation Index",
format: "%0.3f",
value: oscillator.modulationIndex, maximum: 3,
color: AKColor.cyanColor()
) { index in
oscillator.modulationIndex = index
})
addSubview(AKPropertySlider(
property: "Amplitude",
format: "%0.3f",
value: oscillator.amplitude,
color: AKColor.purpleColor()
) { amplitude in
oscillator.amplitude = amplitude
})
addSubview(AKOutputWaveformPlot.createView())
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| 29.986486 | 66 | 0.596665 |
fec373d97fa0840b2a2fcbe90b5f3ca31bc7d1f6 | 549 | //
// URLRequest+Extension.swift
// MeatNetworking
//
// Created by Karl Söderberg on 2020-06-03.
//
import Foundation
extension URLRequest {
mutating func addAuthentication(_ auth: Authentication) {
switch auth {
case .custom(let headerFields):
headerFields.forEach {
setValue($0.value, forHTTPHeaderField: $0.key)
}
case .OAuth2(let token):
setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
case .none:
break
}
}
}
| 22.875 | 76 | 0.590164 |
9b532187f7fd9a24ba9aed21ba59833a0624e045 | 312 | //
// KMNetworkingProvider.swift
// KMNetworkOperation
//
// Created by Jha, Krishna on 1/26/18.
// Copyright © 2018 Jha, Krishna. All rights reserved.
//
import UIKit
protocol KMNetworkingProvider {
func restAPICall(urlString: String?,data:Any?, onCompleted:@escaping ((Data?,Error?,Int?) -> ()))
}
| 20.8 | 102 | 0.692308 |
5663efc035fac44ed61351f6e12dbc0730c3e459 | 1,243 | //
// PinCodeView+Rx.swift
// PinCodeView
//
// Created by Ariel Pollack on 29/06/2017.
// Copyright © 2017 Dapulse. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
#if !COCOAPODS
import PinCodeView
#endif
fileprivate class PinCodeViewDelegateProxy: PinCodeViewDelegate {
weak var delegate: PinCodeViewDelegate?
internal var didSubmit = PublishSubject<String>()
internal var submitCodeCallback: ((Bool)->Void)?
init(pinCodeView view: PinCodeView) {
self.delegate = view.delegate
}
func pinCodeView(_ view: PinCodeView, didSubmitPinCode code: String, isValidCallback callback: @escaping (Bool)->Void) {
submitCodeCallback = callback
didSubmit.onNext(code)
self.delegate?.pinCodeView(view, didSubmitPinCode: code, isValidCallback: callback)
}
func pinCodeView(_ view: PinCodeView, didInsertText text: String) {
self.delegate?.pinCodeView(view, didInsertText: text)
}
}
extension Reactive where Base: PinCodeView {
public var didSubmit: Observable<String> {
let delegateProxy = PinCodeViewDelegateProxy(pinCodeView: base)
base.delegate = delegateProxy
return delegateProxy.didSubmit.asObservable()
}
}
| 27.622222 | 124 | 0.720837 |
626aa78120578c76497390a212915407072ac716 | 1,102 | //
// ImageLabelView.swift
// Rise
//
// Created by Vladimir Korolev on 21.02.2021.
// Copyright © 2021 VladimirBrejcha. All rights reserved.
//
import UIKit
final class ImageLabelView: UIView, Statefull, NibLoadable {
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var label: UILabel!
// MARK: - Statefull
struct State {
let image: UIImage?
let text: String?
}
private(set) var state: State?
func setState(_ state: State) {
self.state = state
imageView.image = state.image
imageView.contentMode = .scaleAspectFit
label.text = state.text
}
// MARK: - LifeCycle
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
setupFromNib()
backgroundColor = .clear
imageView.tintColor = .white
label.textColor = .white
label.textAlignment = .center
label.numberOfLines = 0
}
}
| 20.792453 | 60 | 0.6098 |
014889cd743d83b09a09fec459137976ff17a995 | 1,426 | //
// MoYa_DemoUITests.swift
// MoYa DemoUITests
//
// Created by Apple on 2021/10/11.
//
import XCTest
class MoYa_DemoUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.162791 | 182 | 0.65568 |
efb4314bac741586698682b5f198bbe288762bf9 | 7,949 | //
// V3BeaconMessageContent.swift
//
//
// Created by Julia Samol on 04.01.22.
//
import Foundation
public extension V3BeaconMessage {
enum Content: V3BeaconMessageContentProtocol {
public typealias PermissionRequestContentData = BlockchainType.VersionedMessage.V3.PermissionRequestContentData
public typealias BlockchainRequestContentData = BlockchainType.VersionedMessage.V3.BlockchainRequestContentData
public typealias PermissionResponseContentData = BlockchainType.VersionedMessage.V3.PermissionResponseContentData
public typealias BlockchainResponseContentData = BlockchainType.VersionedMessage.V3.BlockchainResponseContentData
case permissionRequest(PermissionV3BeaconRequestContent<PermissionRequestContentData>)
case blockchainRequest(BlockchainV3BeaconRequestContent<BlockchainRequestContentData>)
case permissionResponse(PermissionV3BeaconResponseContent<PermissionResponseContentData>)
case blockchainResponse(BlockchainV3BeaconResponseContent<BlockchainResponseContentData>)
case acknowledgeResponse(AcknowledgeV3BeaconResponseContent<BlockchainType>)
case errorResponse(ErrorV3BeaconResponseContent<BlockchainType>)
case disconnectMessage(DisconnectV3BeaconMessageContent<BlockchainType>)
// MARK: BeaconMessage Compatibility
public init(from beaconMessage: BeaconMessage<BlockchainType>) throws {
switch beaconMessage {
case let .request(request):
switch request {
case let .permission(content):
self = .permissionRequest(try PermissionV3BeaconRequestContent(from: content))
case let .blockchain(content):
self = .blockchainRequest(try BlockchainV3BeaconRequestContent(from: content))
}
case let .response(response):
switch response {
case let .permission(content):
self = .permissionResponse(try PermissionV3BeaconResponseContent(from: content))
case let .blockchain(content):
self = .blockchainResponse(try BlockchainV3BeaconResponseContent(from: content))
case let .acknowledge(content):
self = .acknowledgeResponse(AcknowledgeV3BeaconResponseContent(from: content))
case let .error(content):
self = .errorResponse(ErrorV3BeaconResponseContent(from: content))
}
case let .disconnect(content):
self = .disconnectMessage(DisconnectV3BeaconMessageContent(from: content))
}
}
public func toBeaconMessage(
id: String,
version: String,
senderID: String,
origin: Beacon.Origin,
completion: @escaping (Result<BeaconMessage<BlockchainType>, Error>) -> ()
) {
switch self {
case let .permissionRequest(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .blockchainRequest(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .permissionResponse(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .blockchainResponse(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .acknowledgeResponse(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .errorResponse(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
case let .disconnectMessage(content):
content.toBeaconMessage(id: id, version: version, senderID: senderID, origin: origin, completion: completion)
}
}
// MARK: Attributes
public var type: String {
switch self {
case let .permissionRequest(content):
return content.type
case let .blockchainRequest(content):
return content.type
case let .permissionResponse(content):
return content.type
case let .blockchainResponse(content):
return content.type
case let .acknowledgeResponse(content):
return content.type
case let .errorResponse(content):
return content.type
case let .disconnectMessage(content):
return content.type
}
}
// MARK: Codable
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case PermissionV3BeaconRequestContent<PermissionRequestContentData>.type:
self = .permissionRequest(try PermissionV3BeaconRequestContent(from: decoder))
case BlockchainV3BeaconRequestContent<BlockchainRequestContentData>.type:
self = .blockchainRequest(try BlockchainV3BeaconRequestContent(from: decoder))
case PermissionV3BeaconResponseContent<PermissionResponseContentData>.type:
self = .permissionResponse(try PermissionV3BeaconResponseContent(from: decoder))
case BlockchainV3BeaconResponseContent<BlockchainResponseContentData>.type:
self = .blockchainResponse(try BlockchainV3BeaconResponseContent(from: decoder))
case AcknowledgeV3BeaconResponseContent<BlockchainType>.type:
self = .acknowledgeResponse(try AcknowledgeV3BeaconResponseContent(from: decoder))
case ErrorV3BeaconResponseContent<BlockchainType>.type:
self = .errorResponse(try ErrorV3BeaconResponseContent(from: decoder))
case DisconnectV3BeaconMessageContent<BlockchainType>.type:
self = .disconnectMessage(try DisconnectV3BeaconMessageContent(from: decoder))
default:
throw Beacon.Error.unknownMessageType(type, version: "3")
}
}
public func encode(to encoder: Encoder) throws {
switch self {
case let .permissionRequest(content):
try content.encode(to: encoder)
case let .blockchainRequest(content):
try content.encode(to: encoder)
case let .permissionResponse(content):
try content.encode(to: encoder)
case let .blockchainResponse(content):
try content.encode(to: encoder)
case let .acknowledgeResponse(content):
try content.encode(to: encoder)
case let .errorResponse(content):
try content.encode(to: encoder)
case let .disconnectMessage(content):
try content.encode(to: encoder)
}
}
enum CodingKeys: String, CodingKey {
case type
}
}
}
// MARK: Protocol
public protocol V3BeaconMessageContentProtocol: Equatable, Codable {
associatedtype BlockchainType: Blockchain
var type: String { get }
init(from beaconMessage: BeaconMessage<BlockchainType>) throws
func toBeaconMessage(
id: String,
version: String,
senderID: String,
origin: Beacon.Origin,
completion: @escaping (Result<BeaconMessage<BlockchainType>, Error>) -> ()
)
}
| 48.175758 | 125 | 0.646496 |
1cacb28d2440bdbdc51859955c450417b8833aa4 | 1,328 | public protocol RunLoopSpinner: class {
// Spins the current thread's run loop in the active mode using the given stop condition.
//
// Will always spin the run loop for at least the minimum number of run loop drains. Will always
// evaluate `stopCondition` at least once after draining for minimum number of drains. After
// draining for the minimum number of drains, the spinner will evaluate `stopCondition` at
// least once per run loop drain. The spinner will stop initiating drains and return if
// `stopCondition` evaluates to `true` or if the timeout has elapsed.
//
// This method should not be invoked on the same spinner object in nested calls (e.g.
// sources that are serviced while it's spinning) or concurrently.
// TODO: Compile-time improvements / run-time check?
//
func spinUntil(
stopCondition: @escaping () -> Bool)
-> SpinUntilResult
}
extension RunLoopSpinner {
public func spinWhile(
continueCondition: @escaping () -> Bool)
-> SpinWhileResult
{
let result = spinUntil {
!continueCondition()
}
switch result {
case .stopConditionMet:
return .continueConditionStoppedBeingMet
case .timedOut:
return .timedOut
}
}
}
| 36.888889 | 100 | 0.655873 |
71373cd58f2d518b0a587772e945fd4f2ac1aedb | 6,945 | //
// BlockParserTests.swift
//
//
// Created by Tomasz Kucharski on 29/01/2022.
//
import Foundation
import XCTest
@testable import ScriptInterpreter
class BlockParserTests: XCTestCase {
func test_tokenAmount() {
let code = "var size = 8; if(true) { size = 4; } else { size = 2 }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getIfBlock(ifTokenIndex: 5)
XCTAssertEqual(result.conditionTokens.count, 1)
XCTAssertEqual(result.mainTokens.count, 4)
XCTAssertEqual(result.elseTokens?.count, 3)
XCTAssertEqual(result.consumedTokens, 16)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_ifStatement() {
let code = "var size = 18; if(size == 18) { size = 4; }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getIfBlock(ifTokenIndex: 5)
XCTAssertEqual(result.conditionTokens.count, 3)
XCTAssertEqual(result.conditionTokens[safeIndex: 0], .variable(name: "size"))
XCTAssertEqual(result.conditionTokens[safeIndex: 1], .equal)
XCTAssertEqual(result.conditionTokens[safeIndex: 2], .intLiteral(18))
XCTAssertEqual(result.mainTokens.count, 4)
XCTAssertEqual(result.mainTokens[safeIndex: 0], .variable(name: "size"))
XCTAssertEqual(result.mainTokens[safeIndex: 1], .assign)
XCTAssertEqual(result.mainTokens[safeIndex: 2], .intLiteral(4))
XCTAssertNil(result.elseTokens)
XCTAssertEqual(result.consumedTokens, 12)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_ifElseStatement() {
let code = "print('Starting'); if(hour == 14 && minute == 00) { runMotor(); } else { stopMotor(); }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getIfBlock(ifTokenIndex: 5)
XCTAssertEqual(result.conditionTokens.count, 7)
XCTAssertEqual(result.conditionTokens[safeIndex: 0], .variable(name: "hour"))
XCTAssertEqual(result.conditionTokens[safeIndex: 1], .equal)
XCTAssertEqual(result.conditionTokens[safeIndex: 2], .intLiteral(14))
XCTAssertEqual(result.conditionTokens[safeIndex: 3], .andOperator)
XCTAssertEqual(result.conditionTokens[safeIndex: 4], .variable(name: "minute"))
XCTAssertEqual(result.conditionTokens[safeIndex: 5], .equal)
XCTAssertEqual(result.conditionTokens[safeIndex: 6], .intLiteral(0))
XCTAssertEqual(result.mainTokens.count, 2)
XCTAssertEqual(result.mainTokens[safeIndex: 0], .function(name: "runMotor"))
XCTAssertEqual(result.mainTokens[safeIndex: 1], .semicolon)
XCTAssertEqual(result.elseTokens?.count, 2)
XCTAssertEqual(result.elseTokens?[safeIndex: 0], .function(name: "stopMotor"))
XCTAssertEqual(result.elseTokens?[safeIndex: 1], .semicolon)
XCTAssertEqual(result.consumedTokens, 19)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_whileStatement() {
let code = "var i = 0; while(i < 5) { i++ }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getWhileBlock(whileTokenIndex: 5)
XCTAssertEqual(result.conditionTokens.count, 3)
XCTAssertEqual(result.conditionTokens[safeIndex: 0], .variable(name: "i"))
XCTAssertEqual(result.conditionTokens[safeIndex: 1], .less)
XCTAssertEqual(result.conditionTokens[safeIndex: 2], .intLiteral(5))
XCTAssertEqual(result.mainTokens.count, 2)
XCTAssertEqual(result.mainTokens[safeIndex: 0], .variable(name: "i"))
XCTAssertEqual(result.mainTokens[safeIndex: 1], .increment)
XCTAssertNil(result.elseTokens)
XCTAssertEqual(result.consumedTokens, 10)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_forStatement() {
let code = "var i = 0; for(var i = 0; i < 5; i++) { ; }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getForBlock(forTokenIndex: 5)
XCTAssertEqual(result.initialState[safeIndex: 0], .variableDefinition(type: "var"))
XCTAssertEqual(result.initialState[safeIndex: 1], .variable(name: "i"))
XCTAssertEqual(result.initialState[safeIndex: 2], .assign)
XCTAssertEqual(result.initialState[safeIndex: 3], .intLiteral(0))
XCTAssertEqual(result.condition[safeIndex: 0], .variable(name: "i"))
XCTAssertEqual(result.condition[safeIndex: 1], .less)
XCTAssertEqual(result.condition[safeIndex: 2], .intLiteral(5))
XCTAssertEqual(result.finalExpression[safeIndex: 0], .variable(name: "i"))
XCTAssertEqual(result.finalExpression[safeIndex: 1], .increment)
XCTAssertEqual(result.body.count, 1)
XCTAssertEqual(result.body[safeIndex: 0], .semicolon)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_switchSwiftStyle() {
let code = "switch name { case 'Ryan': break; default: b++ case 'Dwigth': break; }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getSwitchBlock(switchTokenIndex: 0)
XCTAssertEqual(result.variable, .variable(name: "name"))
XCTAssertEqual(result.cases[.stringLiteral("Ryan")], [.break, .semicolon])
XCTAssertEqual(result.cases[.stringLiteral("Dwigth")], [.break, .semicolon])
XCTAssertEqual(result.default[safeIndex: 0], .variable(name: "b"))
XCTAssertEqual(result.default[safeIndex: 1], .increment)
} catch {
XCTFail(error.localizedDescription)
}
}
func test_switchJavaScriptStyle() {
let code = "switch (name) { case 'Ryan': break; case 'Dwigth': break; default: a++ }"
do {
let lexer = try Lexer(code: code)
let parser = BlockParser(tokens: lexer.tokens)
let result = try parser.getSwitchBlock(switchTokenIndex: 0)
XCTAssertEqual(result.variable, .variable(name: "name"))
XCTAssertEqual(result.default[safeIndex: 0], .variable(name: "a"))
XCTAssertEqual(result.default[safeIndex: 1], .increment)
} catch {
XCTFail(error.localizedDescription)
}
}
}
| 45.392157 | 108 | 0.621166 |
eb97ec1526bb9060fd23e64cf15ffaa39bae3afd | 1,217 | /*
* Copyright @ 2021-present 8x8, 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 Foundation
enum DarwinNotification: String {
case broadcastStarted = "iOS_BroadcastStarted"
case broadcastStopped = "iOS_BroadcastStopped"
}
class DarwinNotificationCenter {
static var shared = DarwinNotificationCenter()
private var notificationCenter: CFNotificationCenter
init() {
notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
}
func postNotification(_ name: DarwinNotification) {
CFNotificationCenterPostNotification(notificationCenter, CFNotificationName(rawValue: name.rawValue as CFString), nil, nil, true)
}
}
| 32.026316 | 137 | 0.739523 |
bf051c42ca4ee54d33844783bff1e190996fef97 | 259 | //
// SearchresultSubtitleTableViewCellViewModel.swift
// Spotify
//
// Created by Lazar Popovic on 3/24/21.
//
import Foundation
struct SearchResultSubtitleTableViewCellViewModel {
let title: String
let subtitle: String
let imageURL: URL?
}
| 17.266667 | 52 | 0.737452 |
64da30ccb29cb283dbff48b9c2e2146eec8ad3b3 | 9,497 | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import Foundation
class AuthServices: NSObject {
let networkManager = NetworkManager.sharedInstance()
weak var delegate: NMWebServiceDelegate?
var requestParams: [String: Any]? = [:]
var headerParams: [String: String]? = [:]
var method: Method!
var failedRequestServices = FailedUserServices()
// MARK: Requests
/// Creates a request to login an `User`
/// - Parameter delegate: Class object to receive response
func loginUser(_ delegate: NMWebServiceDelegate) {
self.delegate = delegate
let user = User.currentUser
let params = [
kUserEmailId: user.emailId ?? "",
kUserPassword: user.password ?? "",
]
let method = AuthServerMethods.login.method
self.sendRequestWith(method: method, params: params, headers: nil)
}
/// Creates a request to logout an `User`
/// - Parameter delegate: Class object to receive response
func logoutUser(_ delegate: NMWebServiceDelegate) {
self.delegate = delegate
let user = User.currentUser
let headerParams = [kUserId: user.userId ?? ""]
let params = [kUserLogoutReason: user.logoutReason.rawValue]
let method = AuthServerMethods.logout.method
self.sendRequestWith(method: method, params: params, headers: headerParams)
}
/// Creates a request to reset the `User` password
/// - Parameters:
/// - email: Email Id of the`User `
/// - delegate: Class object to receive response
func forgotPassword(email: String, delegate: NMWebServiceDelegate) {
self.delegate = delegate
let params = [kUserEmailId: email]
let method = AuthServerMethods.forgotPassword.method
self.sendRequestWith(method: method, params: params, headers: nil)
}
/// Creates a request to change the `User` password
/// - Parameters:
/// - oldPassword:
/// - newPassword:
/// - delegate: Class object to receive response
func changePassword(oldPassword: String, newPassword: String, delegate: NMWebServiceDelegate) {
self.delegate = delegate
let user = User.currentUser
let headerParams = [kUserId: user.userId ?? ""]
let params = [
kUserOldPassword: oldPassword,
kUserNewPassword: newPassword,
]
let method = AuthServerMethods.changePassword.method
self.sendRequestWith(method: method, params: params, headers: headerParams)
}
// MARK: Parsers
/// Handles login response
/// - Parameter response: Webservice response
func handleUserLoginResponse(response: [String: Any]) {
let user = User.currentUser
user.userId = response[kUserId] as? String ?? ""
user.verified = response[kUserVerified] as? Bool ?? false
user.authToken = response[kUserAuthToken] as? String ?? ""
user.clientToken = response["clientToken"] as? String ?? ""
user.refreshToken = response[kRefreshToken] as? String ?? ""
if let isTempPassword = response[kUserIsTempPassword] as? Bool {
user.isLoginWithTempPassword = isTempPassword
}
if user.verified! && !user.isLoginWithTempPassword {
// Set user type & save current user to DB
user.userType = UserType.FDAUser
DBHandler().saveCurrentUser(user: user)
// Updating Key & Vector
let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
appDelegate.updateKeyAndInitializationVector()
FDAKeychain.shared[kUserAuthTokenKeychainKey] = user.authToken
FDAKeychain.shared[kUserRefreshTokenKeychainKey] = user.refreshToken
let ud = UserDefaults.standard
ud.set(true, forKey: kPasscodeIsPending)
ud.synchronize()
StudyFilterHandler.instance.previousAppliedFilters = []
}
}
/// Handles change password response
/// - Parameter response: Webservice response
func handleChangePasswordResponse(response: [String: Any]) {
let user = User.currentUser
if user.verified! {
user.userType = UserType.FDAUser
DBHandler().saveCurrentUser(user: user)
let ud = UserDefaults.standard
ud.set(user.userId!, forKey: kUserId)
ud.synchronize()
}
}
func handleLogoutResponse() {
let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)
UserDefaults.standard.synchronize()
// Delete from database
DBHandler.deleteCurrentUser()
// Reset user object
User.resetCurrentUser()
// Delete complete database
DBHandler.deleteAll()
// Cancel all local notification
LocalNotification.cancelAllLocalNotification()
// Reset Filters
StudyFilterHandler.instance.previousAppliedFilters = []
StudyFilterHandler.instance.searchText = ""
// Delete keychain values
FDAKeychain.shared[kUserAuthTokenKeychainKey] = nil
FDAKeychain.shared[kUserRefreshTokenKeychainKey] = nil
}
/// Creates a request to update RefreshToken
func updateToken(delegate: NMWebServiceDelegate?) {
let user = User.currentUser
self.delegate = delegate
let clientId = RegistrationServerAPIKey.apiKey
let seceretKey = RegistrationServerSecretKey.secretKey
let param = [kRefreshToken: user.refreshToken!]
let header = [
"clientId": clientId,
"secretKey": seceretKey,
"userId": user.userId!,
]
let method = AuthServerMethods.getRefreshedToken.method
self.sendRequestWith(
method: method,
params: param,
headers: header
)
}
func handleUpdateTokenResponse(response: [String: Any]) {
let user = User.currentUser
user.refreshToken = response["refreshToken"] as? String ?? ""
user.authToken = response[kUserAuthToken] as? String ?? ""
user.clientToken = response["clientToken"] as? String ?? ""
FDAKeychain.shared[kUserAuthTokenKeychainKey] = user.authToken
FDAKeychain.shared[kUserRefreshTokenKeychainKey] = user.refreshToken
DBHandler().saveCurrentUser(user: user)
// Re-send request which failed due to session expired.
guard let method = self.failedRequestServices.method else { return }
let headerParams =
self.failedRequestServices.headerParams == nil
? [:] : self.failedRequestServices.headerParams
self.sendRequestWith(
method: method,
params: (self.requestParams == nil ? nil : self.requestParams),
headers: headerParams
)
}
/// Sends Request
/// - Parameters:
/// - method: instance of `Method`
/// - params: request params
/// - headers: request headers
private func sendRequestWith(method: Method, params: [String: Any]?, headers: [String: String]?) {
self.requestParams = params
self.headerParams = headers
self.method = method
networkManager.composeRequest(
AuthServerConfiguration.configuration,
method: method,
params: params as NSDictionary?,
headers: headers as NSDictionary?,
delegate: self
)
}
}
extension AuthServices: NMWebServiceDelegate {
func startedRequest(_ manager: NetworkManager, requestName: NSString) {
delegate?.startedRequest(manager, requestName: requestName)
}
func finishedRequest(_ manager: NetworkManager, requestName: NSString, response: AnyObject?) {
let response = response as? JSONDictionary ?? [:]
switch requestName {
case AuthServerMethods.login.description as String:
self.handleUserLoginResponse(response: response)
case AuthServerMethods.forgotPassword.description as String: break
case AuthServerMethods.changePassword.description as String:
self.handleChangePasswordResponse(response: response)
case AuthServerMethods.logout.description as String:
self.handleLogoutResponse()
case AuthServerMethods.getRefreshedToken.description as String:
self.handleUpdateTokenResponse(response: response)
default: break
}
delegate?.finishedRequest(manager, requestName: requestName, response: response as AnyObject)
}
func failedRequest(_ manager: NetworkManager, requestName: NSString, error: NSError) {
if requestName as String == AuthServerMethods.getRefreshedToken.description && error.code == 401 { // Unauthorized
delegate?.failedRequest(manager, requestName: requestName, error: error)
} else if error.code == 401 {
// Save failed service
self.failedRequestServices.headerParams = self.headerParams
self.failedRequestServices.requestParams = self.requestParams
self.failedRequestServices.method = self.method
if User.currentUser.refreshToken == ""
&& requestName as String
!= AuthServerMethods
.login
.description
{
// Unauthorized Access
let errorInfo = ["NSLocalizedDescription": "Your Session is Expired"]
let localError = NSError.init(domain: error.domain, code: 403, userInfo: errorInfo)
delegate?.failedRequest(manager, requestName: requestName, error: localError)
} else {
// Update Refresh Token
AuthServices().updateToken(delegate: self.delegate)
}
} else {
var errorInfo = error.userInfo
var localError = error
if error.code == 403 {
errorInfo = ["NSLocalizedDescription": "Your Session is Expired"]
localError = NSError.init(domain: error.domain, code: 403, userInfo: errorInfo)
}
delegate?.failedRequest(manager, requestName: requestName, error: localError)
}
}
}
| 33.322807 | 119 | 0.702854 |
2014481d4c328b2b5ccf1cfa3b7374d9851e0caa | 5,101 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class ContentCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
@IBOutlet private var collectionViewFlowLayout: UICollectionViewFlowLayout!
/// The categories to display in the collection view.
var categories: [Category] = [] {
didSet {
// add search only after setting categories to ensure that the samples are available
addSearchController()
}
}
private func addSearchController() {
// create the view controller for displaying the search results
let searchResultsController = storyboard!.instantiateViewController(withIdentifier: "ContentTableViewController") as! ContentTableViewController
let allSamples = categories.flatMap { $0.samples }
searchResultsController.allSamples = allSamples
searchResultsController.searchEngine = SampleSearchEngine(samples: allSamples)
// create the search controller
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.obscuresBackgroundDuringPresentation = true
searchController.hidesNavigationBarDuringPresentation = false
// send search query updates to the results controller
searchController.searchResultsUpdater = searchResultsController
let searchBar = searchController.searchBar
searchBar.autocapitalizationType = .none
// set the color of "Cancel" text
searchBar.tintColor = .white
// embed the search bar under the title in the navigation bar
navigationItem.searchController = searchController
// find the text field to customize its appearance
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
// set the color of the insertion cursor
textfield.tintColor = UIColor.darkText
if let backgroundview = textfield.subviews.first {
backgroundview.backgroundColor = UIColor.white
backgroundview.layer.cornerRadius = 12
backgroundview.clipsToBounds = true
}
}
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell", for: indexPath) as! CategoryCell
let category = categories[indexPath.item]
//mask to bounds
cell.layer.masksToBounds = false
//name
cell.nameLabel.text = category.name.uppercased()
//icon
let image = UIImage(named: "\(category.name)_icon")
cell.iconImageView.image = image
//background image
let bgImage = UIImage(named: "\(category.name)_bg")
cell.backgroundImageView.image = bgImage
//cell shadow
cell.layer.cornerRadius = 5
cell.layer.masksToBounds = true
return cell
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//hide keyboard if visible
view.endEditing(true)
let category = categories[indexPath.item]
let controller = storyboard!.instantiateViewController(withIdentifier: "ContentTableViewController") as! ContentTableViewController
controller.allSamples = category.samples
controller.title = category.name
show(controller, sender: self)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewSize = collectionView.bounds.inset(by: collectionView.safeAreaInsets).size
let spacing: CGFloat = 10
//first try for 3 items in a row
var width = (collectionViewSize.width - 4 * spacing) / 3
if width < 150 {
//if too small then go for 2 in a row
width = (collectionViewSize.width - 3 * spacing) / 2
}
return CGSize(width: width, height: width)
}
}
| 41.811475 | 160 | 0.68418 |
4880acb6a40de9b884fee85c95e0f2179f6afe82 | 230 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g<h {
class A {
let start = b( ) {
}
class b
protocol b
| 20.909091 | 87 | 0.726087 |
ab96099ab34c3b08d22fad0dd7bea4122c070901 | 792 | //
// Placeholder.swift
// CoinFindr
//
// Created by Marsal Silveira.
// Copyright © 2018 Marsal Silveira. All rights reserved.
//
import Foundation
import UIKit
protocol Placeholder {
func present(on parent: UIView)
func dismiss()
}
struct LoadingViewModel {
private var _text: String?
var text: String? { return _text }
init(text: String? = nil) {
_text = text
}
}
struct ErrorViewModel {
private var _text: String?
var text: String? { return _text }
private var _details: String?
var details: String? { return _details }
init(text: String? = nil, details: String? = nil) {
_text = text
_details = details
}
}
enum PlaceholderType {
case loading(LoadingViewModel)
case error(ErrorViewModel)
}
| 16.851064 | 58 | 0.646465 |
0eaa8cf371b9011468d2016daa099e64bfaca3ec | 8,236 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 extension Connection {
/// Creates or redefines a custom SQL function.
///
/// - Parameters:
///
/// - function: The name of the function to create or redefine.
///
/// - deterministic: Whether or not the function is deterministic (_i.e._
/// the function always returns the same result for a given input).
///
/// Default: `false`
///
/// - block: A block of code to run when the function is called.
/// The assigned types must be explicit.
///
/// - Returns: A closure returning an SQL expression to call the function.
func createFunction<Z: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z) throws
-> () -> Expression<Z> {
let fn = try createFunction(function, 0, deterministic) { _ in block() }
return { fn([]) }
}
func createFunction<Z: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping () -> Z?) throws
-> () -> Expression<Z?> {
let fn = try createFunction(function, 0, deterministic) { _ in block() }
return { fn([]) }
}
// MARK: -
func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z) throws
-> (Expression<A>) -> Expression<Z> {
let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) }
return { arg in fn([arg]) }
}
func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z) throws
-> (Expression<A?>) -> Expression<Z> {
let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) }
return { arg in fn([arg]) }
}
func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A) -> Z?) throws
-> (Expression<A>) -> Expression<Z?> {
let fn = try createFunction(function, 1, deterministic) { args in block(value(args[0])) }
return { arg in fn([arg]) }
}
func createFunction<Z: Value, A: Value>(_ function: String, deterministic: Bool = false, _ block: @escaping (A?) -> Z?) throws
-> (Expression<A?>) -> Expression<Z?> {
let fn = try createFunction(function, 1, deterministic) { args in block(args[0].map(value)) }
return { arg in fn([arg]) }
}
// MARK: -
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A, B) -> Z) throws -> (Expression<A>, Expression<B>)
-> Expression<Z> {
let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A?, B) -> Z) throws
-> (Expression<A?>, Expression<B>) -> Expression<Z> {
let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A, B?) -> Z) throws ->
(Expression<A>, Expression<B?>) -> Expression<Z> {
let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A, B) -> Z?) throws
-> (Expression<A>, Expression<B>) -> Expression<Z?> {
let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), value(args[1])) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A?, B?) -> Z) throws
-> (Expression<A?>, Expression<B?>) -> Expression<Z> {
let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A?, B) -> Z?) throws
-> (Expression<A?>, Expression<B>) -> Expression<Z?> {
let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), value(args[1])) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A, B?) -> Z?) throws
-> (Expression<A>, Expression<B?>) -> Expression<Z?> {
let fn = try createFunction(function, 2, deterministic) { args in block(value(args[0]), args[1].map(value)) }
return { a, b in fn([a, b]) }
}
func createFunction<Z: Value, A: Value, B: Value>(_ function: String, deterministic: Bool = false,
_ block: @escaping (A?, B?) -> Z?) throws
-> (Expression<A?>, Expression<B?>) -> Expression<Z?> {
let fn = try createFunction(function, 2, deterministic) { args in block(args[0].map(value), args[1].map(value)) }
return { a, b in fn([a, b]) }
}
// MARK: -
fileprivate func createFunction<Z: Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool,
_ block: @escaping ([Binding?]) -> Z) throws
-> ([Expressible]) -> Expression<Z> {
createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in
block(arguments).datatypeValue
}
return { arguments in
function.quote().wrap(", ".join(arguments))
}
}
fileprivate func createFunction<Z: Value>(_ function: String, _ argumentCount: UInt, _ deterministic: Bool,
_ block: @escaping ([Binding?]) -> Z?) throws
-> ([Expressible]) -> Expression<Z?> {
createFunction(function, argumentCount: argumentCount, deterministic: deterministic) { arguments in
block(arguments)?.datatypeValue
}
return { arguments in
function.quote().wrap(", ".join(arguments))
}
}
}
| 50.527607 | 130 | 0.572972 |
210de5a370be113af2b03e5dc4245f319b2ea201 | 220 | /**
* Unbox
* Copyright (c) 2015-2017 John Sundell
* Licensed under the MIT license, see LICENSE file
*/
import Foundation
internal protocol UnboxPathNode {
func unboxPathValue(forKey key: String) -> Any?
}
| 18.333333 | 52 | 0.704545 |
e476054495b09ad2550695a323cf8dfd6229e161 | 2,729 | // autogenerated
// swiftlint:disable all
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension V1.RoutingAppCoverages.ById {
public struct PATCH: Endpoint {
public typealias Parameters = RoutingAppCoverageUpdateRequest
public typealias Response = RoutingAppCoverageResponse
public var path: String {
"/v1/routingAppCoverages/\(id)"
}
/// the id of the requested resource
public var id: String
/// RoutingAppCoverage representation
public var parameters: Parameters
public init(
id: String,
parameters: Parameters
) {
self.id = id
self.parameters = parameters
}
public func request(with baseURL: URL) throws -> URLRequest? {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
components?.path = path
var urlRequest = components?.url.map { URLRequest(url: $0) }
urlRequest?.httpMethod = "PATCH"
var jsonEncoder: JSONEncoder {
let encoder = JSONEncoder()
return encoder
}
urlRequest?.httpBody = try jsonEncoder.encode(parameters)
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
return urlRequest
}
/// - Returns: **200**, Single RoutingAppCoverage as `RoutingAppCoverageResponse`
/// - Throws: **400**, Parameter error(s) as `ErrorResponse`
/// - Throws: **403**, Forbidden error as `ErrorResponse`
/// - Throws: **404**, Not found error as `ErrorResponse`
/// - Throws: **409**, Request entity error(s) as `ErrorResponse`
public static func response(from data: Data, urlResponse: HTTPURLResponse) throws -> Response {
var jsonDecoder: JSONDecoder {
let decoder = JSONDecoder()
return decoder
}
switch urlResponse.statusCode {
case 200:
return try jsonDecoder.decode(RoutingAppCoverageResponse.self, from: data)
case 400:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 403:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 404:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 409:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
default:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
}
}
}
}
// swiftlint:enable all
| 32.488095 | 103 | 0.596189 |
d6e363b5480ba6ec448aeec46408829077b27a0a | 108,368 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
import Foundation
/// Routes for the files namespace
open class FilesRoutes {
public let client: DropboxTransportClient
init(client: DropboxTransportClient) {
self.client = client
}
/// Returns the metadata for a file or folder. This is an alpha endpoint compatible with the properties API. Note:
/// Metadata for the root folder is unsupported.
///
/// - parameter includePropertyTemplates: If set to a valid list of template IDs, propertyGroups in FileMetadata is
/// set for files with custom properties.
///
/// - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a
/// `Files.AlphaGetMetadataError` object on failure.
@available(*, unavailable, message:"alphaGetMetadata is deprecated. Use getMetadata.")
@discardableResult open func alphaGetMetadata(path: String, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includePropertyGroups: FileProperties.TemplateFilterBase? = nil, includePropertyTemplates: Array<String>? = nil) -> RpcRequest<Files.MetadataSerializer, Files.AlphaGetMetadataErrorSerializer> {
let route = Files.alphaGetMetadata
let serverArgs = Files.AlphaGetMetadataArg(path: path, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includePropertyGroups: includePropertyGroups, includePropertyTemplates: includePropertyTemplates)
return client.request(route, serverArgs: serverArgs)
}
/// Create a new file with the contents provided in the request. Note that this endpoint is part of the properties
/// API alpha and is slightly different from upload. Do not use this to upload a file larger than 150 MB. Instead,
/// create an upload session with uploadSessionStart.
///
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadErrorWithProperties` object on failure.
@available(*, unavailable, message:"alphaUpload is deprecated. Use alphaUpload.")
@discardableResult open func alphaUpload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: Data) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorWithPropertiesSerializer> {
let route = Files.alphaUpload
let serverArgs = Files.CommitInfoWithProperties(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Create a new file with the contents provided in the request. Note that this endpoint is part of the properties
/// API alpha and is slightly different from upload. Do not use this to upload a file larger than 150 MB. Instead,
/// create an upload session with uploadSessionStart.
///
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadErrorWithProperties` object on failure.
@available(*, unavailable, message:"alphaUpload is deprecated. Use alphaUpload.")
@discardableResult open func alphaUpload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: URL) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorWithPropertiesSerializer> {
let route = Files.alphaUpload
let serverArgs = Files.CommitInfoWithProperties(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Create a new file with the contents provided in the request. Note that this endpoint is part of the properties
/// API alpha and is slightly different from upload. Do not use this to upload a file larger than 150 MB. Instead,
/// create an upload session with uploadSessionStart.
///
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadErrorWithProperties` object on failure.
@available(*, unavailable, message:"alphaUpload is deprecated. Use alphaUpload.")
@discardableResult open func alphaUpload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: InputStream) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorWithPropertiesSerializer> {
let route = Files.alphaUpload
let serverArgs = Files.CommitInfoWithProperties(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
/// Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
/// contents will be copied.
///
/// - parameter allowSharedFolder: If true, copy will copy contents in shared folder, otherwise cantCopySharedFolder
/// in RelocationError will be returned if fromPath contains shared folder. This field is always true for move.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the file to avoid the
/// conflict.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationResult` object on success
/// or a `Files.RelocationError` object on failure.
@discardableResult open func copyV2(fromPath: String, toPath: String, allowSharedFolder: Bool = false, autorename: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.RelocationResultSerializer, Files.RelocationErrorSerializer> {
let route = Files.copyV2
let serverArgs = Files.RelocationArg(fromPath: fromPath, toPath: toPath, allowSharedFolder: allowSharedFolder, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
/// contents will be copied.
///
/// - parameter allowSharedFolder: If true, copy will copy contents in shared folder, otherwise cantCopySharedFolder
/// in RelocationError will be returned if fromPath contains shared folder. This field is always true for move.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the file to avoid the
/// conflict.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a
/// `Files.RelocationError` object on failure.
@available(*, unavailable, message:"copy is deprecated. Use copyV2.")
@discardableResult open func copy(fromPath: String, toPath: String, allowSharedFolder: Bool = false, autorename: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> {
let route = Files.copy
let serverArgs = Files.RelocationArg(fromPath: fromPath, toPath: toPath, allowSharedFolder: allowSharedFolder, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Copy multiple files or folders to different locations at once in the user's Dropbox. This route will replace
/// copyBatch. The main difference is this route will return status for each entry, while copyBatch raises failure
/// if any entry fails. This route will either finish synchronously, or return a job ID and do the async copy job in
/// background. Please use copyBatchCheckV2 to check the job status.
///
/// - parameter entries: List of entries to be moved or copied. Each entry is RelocationPath.
/// - parameter autorename: If there's a conflict with any file, have the Dropbox server try to autorename that file
/// to avoid the conflict.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchV2Launch` object on
/// success or a `Void` object on failure.
@discardableResult open func copyBatchV2(entries: Array<Files.RelocationPath>, autorename: Bool = false) -> RpcRequest<Files.RelocationBatchV2LaunchSerializer, VoidSerializer> {
let route = Files.copyBatchV2
let serverArgs = Files.RelocationBatchArgBase(entries: entries, autorename: autorename)
return client.request(route, serverArgs: serverArgs)
}
/// Copy multiple files or folders to different locations at once in the user's Dropbox. If allowSharedFolder in
/// RelocationBatchArg is false, this route is atomic. If one entry fails, the whole transaction will abort. If
/// allowSharedFolder in RelocationBatchArg is true, atomicity is not guaranteed, but it allows you to copy the
/// contents of shared folders to new locations. This route will return job ID immediately and do the async copy job
/// in background. Please use copyBatchCheck to check the job status.
///
/// - parameter allowSharedFolder: If true, copyBatch will copy contents in shared folder, otherwise
/// cantCopySharedFolder in RelocationError will be returned if fromPath in RelocationPath contains shared folder.
/// This field is always true for moveBatch.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchLaunch` object on
/// success or a `Void` object on failure.
@available(*, unavailable, message:"copyBatch is deprecated. Use copyBatchV2.")
@discardableResult open func copyBatch(entries: Array<Files.RelocationPath>, autorename: Bool = false, allowSharedFolder: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.RelocationBatchLaunchSerializer, VoidSerializer> {
let route = Files.copyBatch
let serverArgs = Files.RelocationBatchArg(entries: entries, autorename: autorename, allowSharedFolder: allowSharedFolder, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for copyBatchV2. It returns list of results for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchV2JobStatus` object
/// on success or a `Async.PollError` object on failure.
@discardableResult open func copyBatchCheckV2(asyncJobId: String) -> RpcRequest<Files.RelocationBatchV2JobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.copyBatchCheckV2
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for copyBatch. If success, it returns list of results for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchJobStatus` object on
/// success or a `Async.PollError` object on failure.
@available(*, unavailable, message:"copyBatchCheck is deprecated. Use copyBatchCheckV2.")
@discardableResult open func copyBatchCheck(asyncJobId: String) -> RpcRequest<Files.RelocationBatchJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.copyBatchCheck
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Get a copy reference to a file or folder. This reference string can be used to save that file or folder to
/// another user's Dropbox by passing it to copyReferenceSave.
///
/// - parameter path: The path to the file or folder you want to get a copy reference to.
///
/// - returns: Through the response callback, the caller will receive a `Files.GetCopyReferenceResult` object on
/// success or a `Files.GetCopyReferenceError` object on failure.
@discardableResult open func copyReferenceGet(path: String) -> RpcRequest<Files.GetCopyReferenceResultSerializer, Files.GetCopyReferenceErrorSerializer> {
let route = Files.copyReferenceGet
let serverArgs = Files.GetCopyReferenceArg(path: path)
return client.request(route, serverArgs: serverArgs)
}
/// Save a copy reference returned by copyReferenceGet to the user's Dropbox.
///
/// - parameter copyReference: A copy reference returned by copyReferenceGet.
/// - parameter path: Path in the user's Dropbox that is the destination.
///
/// - returns: Through the response callback, the caller will receive a `Files.SaveCopyReferenceResult` object on
/// success or a `Files.SaveCopyReferenceError` object on failure.
@discardableResult open func copyReferenceSave(copyReference: String, path: String) -> RpcRequest<Files.SaveCopyReferenceResultSerializer, Files.SaveCopyReferenceErrorSerializer> {
let route = Files.copyReferenceSave
let serverArgs = Files.SaveCopyReferenceArg(copyReference: copyReference, path: path)
return client.request(route, serverArgs: serverArgs)
}
/// Create a folder at a given path.
///
/// - parameter path: Path in the user's Dropbox to create.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the folder to avoid the
/// conflict.
///
/// - returns: Through the response callback, the caller will receive a `Files.CreateFolderResult` object on
/// success or a `Files.CreateFolderError` object on failure.
@discardableResult open func createFolderV2(path: String, autorename: Bool = false) -> RpcRequest<Files.CreateFolderResultSerializer, Files.CreateFolderErrorSerializer> {
let route = Files.createFolderV2
let serverArgs = Files.CreateFolderArg(path: path, autorename: autorename)
return client.request(route, serverArgs: serverArgs)
}
/// Create a folder at a given path.
///
/// - parameter path: Path in the user's Dropbox to create.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the folder to avoid the
/// conflict.
///
/// - returns: Through the response callback, the caller will receive a `Files.FolderMetadata` object on success or
/// a `Files.CreateFolderError` object on failure.
@available(*, unavailable, message:"createFolder is deprecated. Use createFolderV2.")
@discardableResult open func createFolder(path: String, autorename: Bool = false) -> RpcRequest<Files.FolderMetadataSerializer, Files.CreateFolderErrorSerializer> {
let route = Files.createFolder
let serverArgs = Files.CreateFolderArg(path: path, autorename: autorename)
return client.request(route, serverArgs: serverArgs)
}
/// Create multiple folders at once. This route is asynchronous for large batches, which returns a job ID
/// immediately and runs the create folder batch asynchronously. Otherwise, creates the folders and returns the
/// result synchronously for smaller inputs. You can force asynchronous behaviour by using the forceAsync in
/// CreateFolderBatchArg flag. Use createFolderBatchCheck to check the job status.
///
/// - parameter paths: List of paths to be created in the user's Dropbox. Duplicate path arguments in the batch are
/// considered only once.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the folder to avoid the
/// conflict.
/// - parameter forceAsync: Whether to force the create to happen asynchronously.
///
/// - returns: Through the response callback, the caller will receive a `Files.CreateFolderBatchLaunch` object on
/// success or a `Void` object on failure.
@discardableResult open func createFolderBatch(paths: Array<String>, autorename: Bool = false, forceAsync: Bool = false) -> RpcRequest<Files.CreateFolderBatchLaunchSerializer, VoidSerializer> {
let route = Files.createFolderBatch
let serverArgs = Files.CreateFolderBatchArg(paths: paths, autorename: autorename, forceAsync: forceAsync)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for createFolderBatch. If success, it returns list of result for each
/// entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.CreateFolderBatchJobStatus` object
/// on success or a `Async.PollError` object on failure.
@discardableResult open func createFolderBatchCheck(asyncJobId: String) -> RpcRequest<Files.CreateFolderBatchJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.createFolderBatchCheck
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Delete the file or folder at a given path. If the path is a folder, all its contents will be deleted too. A
/// successful response indicates that the file or folder was deleted. The returned metadata will be the
/// corresponding FileMetadata or FolderMetadata for the item at time of deletion, and not a DeletedMetadata object.
///
/// - parameter path: Path in the user's Dropbox to delete.
/// - parameter parentRev: Perform delete if given "rev" matches the existing file's latest "rev". This field does
/// not support deleting a folder.
///
/// - returns: Through the response callback, the caller will receive a `Files.DeleteResult` object on success or a
/// `Files.DeleteError` object on failure.
@discardableResult open func deleteV2(path: String, parentRev: String? = nil) -> RpcRequest<Files.DeleteResultSerializer, Files.DeleteErrorSerializer> {
let route = Files.deleteV2
let serverArgs = Files.DeleteArg(path: path, parentRev: parentRev)
return client.request(route, serverArgs: serverArgs)
}
/// Delete the file or folder at a given path. If the path is a folder, all its contents will be deleted too. A
/// successful response indicates that the file or folder was deleted. The returned metadata will be the
/// corresponding FileMetadata or FolderMetadata for the item at time of deletion, and not a DeletedMetadata object.
///
/// - parameter path: Path in the user's Dropbox to delete.
/// - parameter parentRev: Perform delete if given "rev" matches the existing file's latest "rev". This field does
/// not support deleting a folder.
///
/// - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a
/// `Files.DeleteError` object on failure.
@available(*, unavailable, message:"delete is deprecated. Use deleteV2.")
@discardableResult open func delete(path: String, parentRev: String? = nil) -> RpcRequest<Files.MetadataSerializer, Files.DeleteErrorSerializer> {
let route = Files.delete
let serverArgs = Files.DeleteArg(path: path, parentRev: parentRev)
return client.request(route, serverArgs: serverArgs)
}
/// Delete multiple files/folders at once. This route is asynchronous, which returns a job ID immediately and runs
/// the delete batch asynchronously. Use deleteBatchCheck to check the job status.
///
///
/// - returns: Through the response callback, the caller will receive a `Files.DeleteBatchLaunch` object on success
/// or a `Void` object on failure.
@discardableResult open func deleteBatch(entries: Array<Files.DeleteArg>) -> RpcRequest<Files.DeleteBatchLaunchSerializer, VoidSerializer> {
let route = Files.deleteBatch
let serverArgs = Files.DeleteBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for deleteBatch. If success, it returns list of result for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.DeleteBatchJobStatus` object on
/// success or a `Async.PollError` object on failure.
@discardableResult open func deleteBatchCheck(asyncJobId: String) -> RpcRequest<Files.DeleteBatchJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.deleteBatchCheck
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Download a file from a user's Dropbox.
///
/// - parameter path: The path of the file to download.
/// - parameter rev: Please specify revision in path instead.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.DownloadError` object on failure.
@discardableResult open func download(path: String, rev: String? = nil, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.FileMetadataSerializer, Files.DownloadErrorSerializer> {
let route = Files.download
let serverArgs = Files.DownloadArg(path: path, rev: rev)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Download a file from a user's Dropbox.
///
/// - parameter path: The path of the file to download.
/// - parameter rev: Please specify revision in path instead.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.DownloadError` object on failure.
@discardableResult open func download(path: String, rev: String? = nil) -> DownloadRequestMemory<Files.FileMetadataSerializer, Files.DownloadErrorSerializer> {
let route = Files.download
let serverArgs = Files.DownloadArg(path: path, rev: rev)
return client.request(route, serverArgs: serverArgs)
}
/// Download a folder from the user's Dropbox, as a zip file. The folder must be less than 20 GB in size and have
/// fewer than 10,000 total files. The input cannot be a single file. Any single file must be less than 4GB in size.
///
/// - parameter path: The path of the folder to download.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.DownloadZipResult` object on success
/// or a `Files.DownloadZipError` object on failure.
@discardableResult open func downloadZip(path: String, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.DownloadZipResultSerializer, Files.DownloadZipErrorSerializer> {
let route = Files.downloadZip
let serverArgs = Files.DownloadZipArg(path: path)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Download a folder from the user's Dropbox, as a zip file. The folder must be less than 20 GB in size and have
/// fewer than 10,000 total files. The input cannot be a single file. Any single file must be less than 4GB in size.
///
/// - parameter path: The path of the folder to download.
///
/// - returns: Through the response callback, the caller will receive a `Files.DownloadZipResult` object on success
/// or a `Files.DownloadZipError` object on failure.
@discardableResult open func downloadZip(path: String) -> DownloadRequestMemory<Files.DownloadZipResultSerializer, Files.DownloadZipErrorSerializer> {
let route = Files.downloadZip
let serverArgs = Files.DownloadZipArg(path: path)
return client.request(route, serverArgs: serverArgs)
}
/// Export a file from a user's Dropbox. This route only supports exporting files that cannot be downloaded directly
/// and whose fileMetadata in ExportResult has exportAs in ExportInfo populated.
///
/// - parameter path: The path of the file to be exported.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.ExportResult` object on success or a
/// `Files.ExportError` object on failure.
@discardableResult open func export(path: String, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.ExportResultSerializer, Files.ExportErrorSerializer> {
let route = Files.export
let serverArgs = Files.ExportArg(path: path)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Export a file from a user's Dropbox. This route only supports exporting files that cannot be downloaded directly
/// and whose fileMetadata in ExportResult has exportAs in ExportInfo populated.
///
/// - parameter path: The path of the file to be exported.
///
/// - returns: Through the response callback, the caller will receive a `Files.ExportResult` object on success or a
/// `Files.ExportError` object on failure.
@discardableResult open func export(path: String) -> DownloadRequestMemory<Files.ExportResultSerializer, Files.ExportErrorSerializer> {
let route = Files.export
let serverArgs = Files.ExportArg(path: path)
return client.request(route, serverArgs: serverArgs)
}
/// Return the lock metadata for the given list of paths.
///
/// - parameter entries: List of 'entries'. Each 'entry' contains a path of the file which will be locked or
/// queried. Duplicate path arguments in the batch are considered only once.
///
/// - returns: Through the response callback, the caller will receive a `Files.LockFileBatchResult` object on
/// success or a `Files.LockFileError` object on failure.
@discardableResult open func getFileLockBatch(entries: Array<Files.LockFileArg>) -> RpcRequest<Files.LockFileBatchResultSerializer, Files.LockFileErrorSerializer> {
let route = Files.getFileLockBatch
let serverArgs = Files.LockFileBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the metadata for a file or folder. Note: Metadata for the root folder is unsupported.
///
/// - parameter path: The path of a file or folder on Dropbox.
/// - parameter includeMediaInfo: If true, mediaInfo in FileMetadata is set for photo and video.
/// - parameter includeDeleted: If true, DeletedMetadata will be returned for deleted file or folder, otherwise
/// notFound in LookupError will be returned.
/// - parameter includeHasExplicitSharedMembers: If true, the results will include a flag for each file indicating
/// whether or not that file has any explicit members.
/// - parameter includePropertyGroups: If set to a valid list of template IDs, propertyGroups in FileMetadata is set
/// if there exists property data associated with the file and each of the listed templates.
///
/// - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a
/// `Files.GetMetadataError` object on failure.
@discardableResult open func getMetadata(path: String, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includePropertyGroups: FileProperties.TemplateFilterBase? = nil) -> RpcRequest<Files.MetadataSerializer, Files.GetMetadataErrorSerializer> {
let route = Files.getMetadata
let serverArgs = Files.GetMetadataArg(path: path, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includePropertyGroups: includePropertyGroups)
return client.request(route, serverArgs: serverArgs)
}
/// Get a preview for a file. Currently, PDF previews are generated for files with the following extensions: .ai,
/// .doc, .docm, .docx, .eps, .gdoc, .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML
/// previews are generated for files with the following extensions: .csv, .ods, .xls, .xlsm, .gsheet, .xlsx. Other
/// formats will return an unsupported extension error.
///
/// - parameter path: The path of the file to preview.
/// - parameter rev: Please specify revision in path instead.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.PreviewError` object on failure.
@discardableResult open func getPreview(path: String, rev: String? = nil, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.FileMetadataSerializer, Files.PreviewErrorSerializer> {
let route = Files.getPreview
let serverArgs = Files.PreviewArg(path: path, rev: rev)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Get a preview for a file. Currently, PDF previews are generated for files with the following extensions: .ai,
/// .doc, .docm, .docx, .eps, .gdoc, .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML
/// previews are generated for files with the following extensions: .csv, .ods, .xls, .xlsm, .gsheet, .xlsx. Other
/// formats will return an unsupported extension error.
///
/// - parameter path: The path of the file to preview.
/// - parameter rev: Please specify revision in path instead.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.PreviewError` object on failure.
@discardableResult open func getPreview(path: String, rev: String? = nil) -> DownloadRequestMemory<Files.FileMetadataSerializer, Files.PreviewErrorSerializer> {
let route = Files.getPreview
let serverArgs = Files.PreviewArg(path: path, rev: rev)
return client.request(route, serverArgs: serverArgs)
}
/// Get a temporary link to stream content of a file. This link will expire in four hours and afterwards you will
/// get 410 Gone. This URL should not be used to display content directly in the browser. The Content-Type of the
/// link is determined automatically by the file's mime type.
///
/// - parameter path: The path to the file you want a temporary link to.
///
/// - returns: Through the response callback, the caller will receive a `Files.GetTemporaryLinkResult` object on
/// success or a `Files.GetTemporaryLinkError` object on failure.
@discardableResult open func getTemporaryLink(path: String) -> RpcRequest<Files.GetTemporaryLinkResultSerializer, Files.GetTemporaryLinkErrorSerializer> {
let route = Files.getTemporaryLink
let serverArgs = Files.GetTemporaryLinkArg(path: path)
return client.request(route, serverArgs: serverArgs)
}
/// Get a one-time use temporary upload link to upload a file to a Dropbox location. This endpoint acts as a
/// delayed upload. The returned temporary upload link may be used to make a POST request with the data to be
/// uploaded. The upload will then be perfomed with the CommitInfo previously provided to getTemporaryUploadLink but
/// evaluated only upon consumption. Hence, errors stemming from invalid CommitInfo with respect to the state of the
/// user's Dropbox will only be communicated at consumption time. Additionally, these errors are surfaced as generic
/// HTTP 409 Conflict responses, potentially hiding issue details. The maximum temporary upload link duration is 4
/// hours. Upon consumption or expiration, a new link will have to be generated. Multiple links may exist for a
/// specific upload path at any given time. The POST request on the temporary upload link must have its
/// Content-Type set to "application/octet-stream". Example temporary upload link consumption request: curl -X
/// POST https://content.dropboxapi.com/apitul/1/bNi2uIYF51cVBND --header "Content-Type: application/octet-stream"
/// --data-binary @local_file.txt A successful temporary upload link consumption request returns the content hash
/// of the uploaded data in JSON format. Example succesful temporary upload link consumption response:
/// {"content-hash": "599d71033d700ac892a0e48fa61b125d2f5994"} An unsuccessful temporary upload link consumption
/// request returns any of the following status codes: HTTP 400 Bad Request: Content-Type is not one of
/// application/octet-stream and text/plain or request is invalid. HTTP 409 Conflict: The temporary upload link does
/// not exist or is currently unavailable, the upload failed, or another error happened. HTTP 410 Gone: The
/// temporary upload link is expired or consumed. Example unsuccessful temporary upload link consumption response:
/// Temporary upload link has been recently consumed.
///
/// - parameter commitInfo: Contains the path and other optional modifiers for the future upload commit. Equivalent
/// to the parameters provided to upload.
/// - parameter duration: How long before this link expires, in seconds. Attempting to start an upload with this
/// link longer than this period of time after link creation will result in an error.
///
/// - returns: Through the response callback, the caller will receive a `Files.GetTemporaryUploadLinkResult` object
/// on success or a `Void` object on failure.
@discardableResult open func getTemporaryUploadLink(commitInfo: Files.CommitInfo, duration: Double = 14400.0) -> RpcRequest<Files.GetTemporaryUploadLinkResultSerializer, VoidSerializer> {
let route = Files.getTemporaryUploadLink
let serverArgs = Files.GetTemporaryUploadLinkArg(commitInfo: commitInfo, duration: duration)
return client.request(route, serverArgs: serverArgs)
}
/// Get a thumbnail for an image. This method currently supports files with the following file extensions: jpg,
/// jpeg, png, tiff, tif, gif and bmp. Photos that are larger than 20MB in size won't be converted to a thumbnail.
///
/// - parameter path: The path to the image file you want to thumbnail.
/// - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg
/// should be preferred, while png is better for screenshots and digital arts.
/// - parameter size: The size for the thumbnail image.
/// - parameter mode: How to resize and crop the image to achieve the desired size.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.ThumbnailError` object on failure.
@discardableResult open func getThumbnail(path: String, format: Files.ThumbnailFormat = .jpeg, size: Files.ThumbnailSize = .w64h64, mode: Files.ThumbnailMode = .strict, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.FileMetadataSerializer, Files.ThumbnailErrorSerializer> {
let route = Files.getThumbnail
let serverArgs = Files.ThumbnailArg(path: path, format: format, size: size, mode: mode)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Get a thumbnail for an image. This method currently supports files with the following file extensions: jpg,
/// jpeg, png, tiff, tif, gif and bmp. Photos that are larger than 20MB in size won't be converted to a thumbnail.
///
/// - parameter path: The path to the image file you want to thumbnail.
/// - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg
/// should be preferred, while png is better for screenshots and digital arts.
/// - parameter size: The size for the thumbnail image.
/// - parameter mode: How to resize and crop the image to achieve the desired size.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.ThumbnailError` object on failure.
@discardableResult open func getThumbnail(path: String, format: Files.ThumbnailFormat = .jpeg, size: Files.ThumbnailSize = .w64h64, mode: Files.ThumbnailMode = .strict) -> DownloadRequestMemory<Files.FileMetadataSerializer, Files.ThumbnailErrorSerializer> {
let route = Files.getThumbnail
let serverArgs = Files.ThumbnailArg(path: path, format: format, size: size, mode: mode)
return client.request(route, serverArgs: serverArgs)
}
/// Get a thumbnail for a file.
///
/// - parameter resource: Information specifying which file to preview. This could be a path to a file, a shared
/// link pointing to a file, or a shared link pointing to a folder, with a relative path.
/// - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg
/// should be preferred, while png is better for screenshots and digital arts.
/// - parameter size: The size for the thumbnail image.
/// - parameter mode: How to resize and crop the image to achieve the desired size.
/// - parameter overwrite: A boolean to set behavior in the event of a naming conflict. `True` will overwrite
/// conflicting file at destination. `False` will take no action (but if left unhandled in destination closure, an
/// NSError will be thrown).
/// - parameter destination: A closure used to compute the destination, given the temporary file location and the
/// response.
///
/// - returns: Through the response callback, the caller will receive a `Files.PreviewResult` object on success or
/// a `Files.ThumbnailV2Error` object on failure.
@discardableResult open func getThumbnailV2(resource: Files.PathOrLink, format: Files.ThumbnailFormat = .jpeg, size: Files.ThumbnailSize = .w64h64, mode: Files.ThumbnailMode = .strict, overwrite: Bool = false, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<Files.PreviewResultSerializer, Files.ThumbnailV2ErrorSerializer> {
let route = Files.getThumbnailV2
let serverArgs = Files.ThumbnailV2Arg(resource: resource, format: format, size: size, mode: mode)
return client.request(route, serverArgs: serverArgs, overwrite: overwrite, destination: destination)
}
/// Get a thumbnail for a file.
///
/// - parameter resource: Information specifying which file to preview. This could be a path to a file, a shared
/// link pointing to a file, or a shared link pointing to a folder, with a relative path.
/// - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg
/// should be preferred, while png is better for screenshots and digital arts.
/// - parameter size: The size for the thumbnail image.
/// - parameter mode: How to resize and crop the image to achieve the desired size.
///
/// - returns: Through the response callback, the caller will receive a `Files.PreviewResult` object on success or
/// a `Files.ThumbnailV2Error` object on failure.
@discardableResult open func getThumbnailV2(resource: Files.PathOrLink, format: Files.ThumbnailFormat = .jpeg, size: Files.ThumbnailSize = .w64h64, mode: Files.ThumbnailMode = .strict) -> DownloadRequestMemory<Files.PreviewResultSerializer, Files.ThumbnailV2ErrorSerializer> {
let route = Files.getThumbnailV2
let serverArgs = Files.ThumbnailV2Arg(resource: resource, format: format, size: size, mode: mode)
return client.request(route, serverArgs: serverArgs)
}
/// Get thumbnails for a list of images. We allow up to 25 thumbnails in a single batch. This method currently
/// supports files with the following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are
/// larger than 20MB in size won't be converted to a thumbnail.
///
/// - parameter entries: List of files to get thumbnails.
///
/// - returns: Through the response callback, the caller will receive a `Files.GetThumbnailBatchResult` object on
/// success or a `Files.GetThumbnailBatchError` object on failure.
@discardableResult open func getThumbnailBatch(entries: Array<Files.ThumbnailArg>) -> RpcRequest<Files.GetThumbnailBatchResultSerializer, Files.GetThumbnailBatchErrorSerializer> {
let route = Files.getThumbnailBatch
let serverArgs = Files.GetThumbnailBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Starts returning the contents of a folder. If the result's hasMore in ListFolderResult field is true, call
/// listFolderContinue with the returned cursor in ListFolderResult to retrieve more entries. If you're using
/// recursive in ListFolderArg set to true to keep a local cache of the contents of a Dropbox account, iterate
/// through each entry in order and process them as follows to keep your local state in sync: For each FileMetadata,
/// store the new entry at the given path in your local state. If the required parent folders don't exist yet,
/// create them. If there's already something else at the given path, replace it and remove all its children. For
/// each FolderMetadata, store the new entry at the given path in your local state. If the required parent folders
/// don't exist yet, create them. If there's already something else at the given path, replace it but leave the
/// children as they are. Check the new entry's readOnly in FolderSharingInfo and set all its children's read-only
/// statuses to match. For each DeletedMetadata, if your local state has something at the given path, remove it and
/// all its children. If there's nothing at the given path, ignore this entry. Note: auth.RateLimitError may be
/// returned if multiple listFolder or listFolderContinue calls with same parameters are made simultaneously by same
/// API app for same user. If your app implements retry logic, please hold off the retry until the previous request
/// finishes.
///
/// - parameter path: A unique identifier for the file.
/// - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the
/// response will contain contents of all subfolders.
/// - parameter includeMediaInfo: If true, mediaInfo in FileMetadata is set for photo and video. This parameter will
/// no longer have an effect starting December 2, 2019.
/// - parameter includeDeleted: If true, the results will include entries for files and folders that used to exist
/// but were deleted.
/// - parameter includeHasExplicitSharedMembers: If true, the results will include a flag for each file indicating
/// whether or not that file has any explicit members.
/// - parameter includeMountedFolders: If true, the results will include entries under mounted folders which
/// includes app folder, shared folder and team folder.
/// - parameter limit: The maximum number of results to return per request. Note: This is an approximate number and
/// there can be slightly more entries returned in some cases.
/// - parameter sharedLink: A shared link to list the contents of. If the link is password-protected, the password
/// must be provided. If this field is present, path in ListFolderArg will be relative to root of the shared link.
/// Only non-recursive mode is supported for shared link.
/// - parameter includePropertyGroups: If set to a valid list of template IDs, propertyGroups in FileMetadata is set
/// if there exists property data associated with the file and each of the listed templates.
/// - parameter includeNonDownloadableFiles: If true, include files that are not downloadable, i.e. Google Docs.
///
/// - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success
/// or a `Files.ListFolderError` object on failure.
@discardableResult open func listFolder(path: String, recursive: Bool = false, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includeMountedFolders: Bool = true, limit: UInt32? = nil, sharedLink: Files.SharedLink? = nil, includePropertyGroups: FileProperties.TemplateFilterBase? = nil, includeNonDownloadableFiles: Bool = true) -> RpcRequest<Files.ListFolderResultSerializer, Files.ListFolderErrorSerializer> {
let route = Files.listFolder
let serverArgs = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includeMountedFolders: includeMountedFolders, limit: limit, sharedLink: sharedLink, includePropertyGroups: includePropertyGroups, includeNonDownloadableFiles: includeNonDownloadableFiles)
return client.request(route, serverArgs: serverArgs)
}
/// Once a cursor has been retrieved from listFolder, use this to paginate through all files and retrieve updates to
/// the folder, following the same rules as documented for listFolder.
///
/// - parameter cursor: The cursor returned by your last call to listFolder or listFolderContinue.
///
/// - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success
/// or a `Files.ListFolderContinueError` object on failure.
@discardableResult open func listFolderContinue(cursor: String) -> RpcRequest<Files.ListFolderResultSerializer, Files.ListFolderContinueErrorSerializer> {
let route = Files.listFolderContinue
let serverArgs = Files.ListFolderContinueArg(cursor: cursor)
return client.request(route, serverArgs: serverArgs)
}
/// A way to quickly get a cursor for the folder's state. Unlike listFolder, listFolderGetLatestCursor doesn't
/// return any entries. This endpoint is for app which only needs to know about new files and modifications and
/// doesn't need to know about files that already exist in Dropbox.
///
/// - parameter path: A unique identifier for the file.
/// - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the
/// response will contain contents of all subfolders.
/// - parameter includeMediaInfo: If true, mediaInfo in FileMetadata is set for photo and video. This parameter will
/// no longer have an effect starting December 2, 2019.
/// - parameter includeDeleted: If true, the results will include entries for files and folders that used to exist
/// but were deleted.
/// - parameter includeHasExplicitSharedMembers: If true, the results will include a flag for each file indicating
/// whether or not that file has any explicit members.
/// - parameter includeMountedFolders: If true, the results will include entries under mounted folders which
/// includes app folder, shared folder and team folder.
/// - parameter limit: The maximum number of results to return per request. Note: This is an approximate number and
/// there can be slightly more entries returned in some cases.
/// - parameter sharedLink: A shared link to list the contents of. If the link is password-protected, the password
/// must be provided. If this field is present, path in ListFolderArg will be relative to root of the shared link.
/// Only non-recursive mode is supported for shared link.
/// - parameter includePropertyGroups: If set to a valid list of template IDs, propertyGroups in FileMetadata is set
/// if there exists property data associated with the file and each of the listed templates.
/// - parameter includeNonDownloadableFiles: If true, include files that are not downloadable, i.e. Google Docs.
///
/// - returns: Through the response callback, the caller will receive a `Files.ListFolderGetLatestCursorResult`
/// object on success or a `Files.ListFolderError` object on failure.
@discardableResult open func listFolderGetLatestCursor(path: String, recursive: Bool = false, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includeMountedFolders: Bool = true, limit: UInt32? = nil, sharedLink: Files.SharedLink? = nil, includePropertyGroups: FileProperties.TemplateFilterBase? = nil, includeNonDownloadableFiles: Bool = true) -> RpcRequest<Files.ListFolderGetLatestCursorResultSerializer, Files.ListFolderErrorSerializer> {
let route = Files.listFolderGetLatestCursor
let serverArgs = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includeMountedFolders: includeMountedFolders, limit: limit, sharedLink: sharedLink, includePropertyGroups: includePropertyGroups, includeNonDownloadableFiles: includeNonDownloadableFiles)
return client.request(route, serverArgs: serverArgs)
}
/// A longpoll endpoint to wait for changes on an account. In conjunction with listFolderContinue, this call gives
/// you a low-latency way to monitor an account for file changes. The connection will block until there are changes
/// available or a timeout occurs. This endpoint is useful mostly for client-side apps. If you're looking for
/// server-side notifications, check out our webhooks documentation
/// https://www.dropbox.com/developers/reference/webhooks.
///
/// - parameter cursor: A cursor as returned by listFolder or listFolderContinue. Cursors retrieved by setting
/// includeMediaInfo in ListFolderArg to true are not supported.
/// - parameter timeout: A timeout in seconds. The request will block for at most this length of time, plus up to 90
/// seconds of random jitter added to avoid the thundering herd problem. Care should be taken when using this
/// parameter, as some network infrastructure does not support long timeouts.
///
/// - returns: Through the response callback, the caller will receive a `Files.ListFolderLongpollResult` object on
/// success or a `Files.ListFolderLongpollError` object on failure.
@discardableResult open func listFolderLongpoll(cursor: String, timeout: UInt64 = 30) -> RpcRequest<Files.ListFolderLongpollResultSerializer, Files.ListFolderLongpollErrorSerializer> {
let route = Files.listFolderLongpoll
let serverArgs = Files.ListFolderLongpollArg(cursor: cursor, timeout: timeout)
return client.request(route, serverArgs: serverArgs)
}
/// Returns revisions for files based on a file path or a file id. The file path or file id is identified from the
/// latest file entry at the given file path or id. This end point allows your app to query either by file path or
/// file id by setting the mode parameter appropriately. In the path in ListRevisionsMode (default) mode, all
/// revisions at the same file path as the latest file entry are returned. If revisions with the same file id are
/// desired, then mode must be set to id in ListRevisionsMode. The id in ListRevisionsMode mode is useful to
/// retrieve revisions for a given file across moves or renames.
///
/// - parameter path: The path to the file you want to see the revisions of.
/// - parameter mode: Determines the behavior of the API in listing the revisions for a given file path or id.
/// - parameter limit: The maximum number of revision entries returned.
///
/// - returns: Through the response callback, the caller will receive a `Files.ListRevisionsResult` object on
/// success or a `Files.ListRevisionsError` object on failure.
@discardableResult open func listRevisions(path: String, mode: Files.ListRevisionsMode = .path, limit: UInt64 = 10) -> RpcRequest<Files.ListRevisionsResultSerializer, Files.ListRevisionsErrorSerializer> {
let route = Files.listRevisions
let serverArgs = Files.ListRevisionsArg(path: path, mode: mode, limit: limit)
return client.request(route, serverArgs: serverArgs)
}
/// Lock the files at the given paths. A locked file will be writable only by the lock holder. A successful response
/// indicates that the file has been locked. Returns a list of the locked file paths and their metadata after this
/// operation.
///
/// - parameter entries: List of 'entries'. Each 'entry' contains a path of the file which will be locked or
/// queried. Duplicate path arguments in the batch are considered only once.
///
/// - returns: Through the response callback, the caller will receive a `Files.LockFileBatchResult` object on
/// success or a `Files.LockFileError` object on failure.
@discardableResult open func lockFileBatch(entries: Array<Files.LockFileArg>) -> RpcRequest<Files.LockFileBatchResultSerializer, Files.LockFileErrorSerializer> {
let route = Files.lockFileBatch
let serverArgs = Files.LockFileBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
/// contents will be moved. Note that we do not currently support case-only renaming.
///
/// - parameter allowSharedFolder: If true, copy will copy contents in shared folder, otherwise cantCopySharedFolder
/// in RelocationError will be returned if fromPath contains shared folder. This field is always true for move.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the file to avoid the
/// conflict.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationResult` object on success
/// or a `Files.RelocationError` object on failure.
@discardableResult open func moveV2(fromPath: String, toPath: String, allowSharedFolder: Bool = false, autorename: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.RelocationResultSerializer, Files.RelocationErrorSerializer> {
let route = Files.moveV2
let serverArgs = Files.RelocationArg(fromPath: fromPath, toPath: toPath, allowSharedFolder: allowSharedFolder, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
/// contents will be moved.
///
/// - parameter allowSharedFolder: If true, copy will copy contents in shared folder, otherwise cantCopySharedFolder
/// in RelocationError will be returned if fromPath contains shared folder. This field is always true for move.
/// - parameter autorename: If there's a conflict, have the Dropbox server try to autorename the file to avoid the
/// conflict.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a
/// `Files.RelocationError` object on failure.
@available(*, unavailable, message:"move is deprecated. Use moveV2.")
@discardableResult open func move(fromPath: String, toPath: String, allowSharedFolder: Bool = false, autorename: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> {
let route = Files.move
let serverArgs = Files.RelocationArg(fromPath: fromPath, toPath: toPath, allowSharedFolder: allowSharedFolder, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Move multiple files or folders to different locations at once in the user's Dropbox. Note that we do not
/// currently support case-only renaming. This route will replace moveBatch. The main difference is this route will
/// return status for each entry, while moveBatch raises failure if any entry fails. This route will either finish
/// synchronously, or return a job ID and do the async move job in background. Please use moveBatchCheckV2 to check
/// the job status.
///
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchV2Launch` object on
/// success or a `Void` object on failure.
@discardableResult open func moveBatchV2(entries: Array<Files.RelocationPath>, autorename: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.RelocationBatchV2LaunchSerializer, VoidSerializer> {
let route = Files.moveBatchV2
let serverArgs = Files.MoveBatchArg(entries: entries, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Move multiple files or folders to different locations at once in the user's Dropbox. This route will return job
/// ID immediately and do the async moving job in background. Please use moveBatchCheck to check the job status.
///
/// - parameter allowSharedFolder: If true, copyBatch will copy contents in shared folder, otherwise
/// cantCopySharedFolder in RelocationError will be returned if fromPath in RelocationPath contains shared folder.
/// This field is always true for moveBatch.
/// - parameter allowOwnershipTransfer: Allow moves by owner even if it would result in an ownership transfer for
/// the content being moved. This does not apply to copies.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchLaunch` object on
/// success or a `Void` object on failure.
@available(*, unavailable, message:"moveBatch is deprecated. Use moveBatchV2.")
@discardableResult open func moveBatch(entries: Array<Files.RelocationPath>, autorename: Bool = false, allowSharedFolder: Bool = false, allowOwnershipTransfer: Bool = false) -> RpcRequest<Files.RelocationBatchLaunchSerializer, VoidSerializer> {
let route = Files.moveBatch
let serverArgs = Files.RelocationBatchArg(entries: entries, autorename: autorename, allowSharedFolder: allowSharedFolder, allowOwnershipTransfer: allowOwnershipTransfer)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for moveBatchV2. It returns list of results for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchV2JobStatus` object
/// on success or a `Async.PollError` object on failure.
@discardableResult open func moveBatchCheckV2(asyncJobId: String) -> RpcRequest<Files.RelocationBatchV2JobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.moveBatchCheckV2
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for moveBatch. If success, it returns list of results for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.RelocationBatchJobStatus` object on
/// success or a `Async.PollError` object on failure.
@available(*, unavailable, message:"moveBatchCheck is deprecated. Use moveBatchCheckV2.")
@discardableResult open func moveBatchCheck(asyncJobId: String) -> RpcRequest<Files.RelocationBatchJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.moveBatchCheck
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Permanently delete the file or folder at a given path (see https://www.dropbox.com/en/help/40). Note: This
/// endpoint is only available for Dropbox Business apps.
///
/// - parameter path: Path in the user's Dropbox to delete.
/// - parameter parentRev: Perform delete if given "rev" matches the existing file's latest "rev". This field does
/// not support deleting a folder.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.DeleteError` object on failure.
@discardableResult open func permanentlyDelete(path: String, parentRev: String? = nil) -> RpcRequest<VoidSerializer, Files.DeleteErrorSerializer> {
let route = Files.permanentlyDelete
let serverArgs = Files.DeleteArg(path: path, parentRev: parentRev)
return client.request(route, serverArgs: serverArgs)
}
/// The propertiesAdd route
///
/// - parameter path: A unique identifier for the file or folder.
/// - parameter propertyGroups: The property groups which are to be added to a Dropbox file. No two groups in the
/// input should refer to the same template.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `FileProperties.AddPropertiesError` object on failure.
@available(*, unavailable, message:"propertiesAdd is deprecated.")
@discardableResult open func propertiesAdd(path: String, propertyGroups: Array<FileProperties.PropertyGroup>) -> RpcRequest<VoidSerializer, FileProperties.AddPropertiesErrorSerializer> {
let route = Files.propertiesAdd
let serverArgs = FileProperties.AddPropertiesArg(path: path, propertyGroups: propertyGroups)
return client.request(route, serverArgs: serverArgs)
}
/// The propertiesOverwrite route
///
/// - parameter path: A unique identifier for the file or folder.
/// - parameter propertyGroups: The property groups "snapshot" updates to force apply. No two groups in the input
/// should refer to the same template.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `FileProperties.InvalidPropertyGroupError` object on failure.
@available(*, unavailable, message:"propertiesOverwrite is deprecated.")
@discardableResult open func propertiesOverwrite(path: String, propertyGroups: Array<FileProperties.PropertyGroup>) -> RpcRequest<VoidSerializer, FileProperties.InvalidPropertyGroupErrorSerializer> {
let route = Files.propertiesOverwrite
let serverArgs = FileProperties.OverwritePropertyGroupArg(path: path, propertyGroups: propertyGroups)
return client.request(route, serverArgs: serverArgs)
}
/// The propertiesRemove route
///
/// - parameter path: A unique identifier for the file or folder.
/// - parameter propertyTemplateIds: A list of identifiers for a template created by templatesAddForUser or
/// templatesAddForTeam.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `FileProperties.RemovePropertiesError` object on failure.
@available(*, unavailable, message:"propertiesRemove is deprecated.")
@discardableResult open func propertiesRemove(path: String, propertyTemplateIds: Array<String>) -> RpcRequest<VoidSerializer, FileProperties.RemovePropertiesErrorSerializer> {
let route = Files.propertiesRemove
let serverArgs = FileProperties.RemovePropertiesArg(path: path, propertyTemplateIds: propertyTemplateIds)
return client.request(route, serverArgs: serverArgs)
}
/// The propertiesTemplateGet route
///
/// - parameter templateId: An identifier for template added by route See templatesAddForUser or
/// templatesAddForTeam.
///
/// - returns: Through the response callback, the caller will receive a `FileProperties.GetTemplateResult` object
/// on success or a `FileProperties.TemplateError` object on failure.
@available(*, unavailable, message:"propertiesTemplateGet is deprecated.")
@discardableResult open func propertiesTemplateGet(templateId: String) -> RpcRequest<FileProperties.GetTemplateResultSerializer, FileProperties.TemplateErrorSerializer> {
let route = Files.propertiesTemplateGet
let serverArgs = FileProperties.GetTemplateArg(templateId: templateId)
return client.request(route, serverArgs: serverArgs)
}
/// The propertiesTemplateList route
///
///
/// - returns: Through the response callback, the caller will receive a `FileProperties.ListTemplateResult` object
/// on success or a `FileProperties.TemplateError` object on failure.
@available(*, unavailable, message:"propertiesTemplateList is deprecated.")
@discardableResult open func propertiesTemplateList() -> RpcRequest<FileProperties.ListTemplateResultSerializer, FileProperties.TemplateErrorSerializer> {
let route = Files.propertiesTemplateList
return client.request(route)
}
/// The propertiesUpdate route
///
/// - parameter path: A unique identifier for the file or folder.
/// - parameter updatePropertyGroups: The property groups "delta" updates to apply.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `FileProperties.UpdatePropertiesError` object on failure.
@available(*, unavailable, message:"propertiesUpdate is deprecated.")
@discardableResult open func propertiesUpdate(path: String, updatePropertyGroups: Array<FileProperties.PropertyGroupUpdate>) -> RpcRequest<VoidSerializer, FileProperties.UpdatePropertiesErrorSerializer> {
let route = Files.propertiesUpdate
let serverArgs = FileProperties.UpdatePropertiesArg(path: path, updatePropertyGroups: updatePropertyGroups)
return client.request(route, serverArgs: serverArgs)
}
/// Restore a specific revision of a file to the given path.
///
/// - parameter path: The path to save the restored file.
/// - parameter rev: The revision to restore.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.RestoreError` object on failure.
@discardableResult open func restore(path: String, rev: String) -> RpcRequest<Files.FileMetadataSerializer, Files.RestoreErrorSerializer> {
let route = Files.restore
let serverArgs = Files.RestoreArg(path: path, rev: rev)
return client.request(route, serverArgs: serverArgs)
}
/// Save the data from a specified URL into a file in user's Dropbox. Note that the transfer from the URL must
/// complete within 5 minutes, or the operation will time out and the job will fail. If the given path already
/// exists, the file will be renamed to avoid the conflict (e.g. myfile (1).txt).
///
/// - parameter path: The path in Dropbox where the URL will be saved to.
/// - parameter url: The URL to be saved.
///
/// - returns: Through the response callback, the caller will receive a `Files.SaveUrlResult` object on success or
/// a `Files.SaveUrlError` object on failure.
@discardableResult open func saveUrl(path: String, url: String) -> RpcRequest<Files.SaveUrlResultSerializer, Files.SaveUrlErrorSerializer> {
let route = Files.saveUrl
let serverArgs = Files.SaveUrlArg(path: path, url: url)
return client.request(route, serverArgs: serverArgs)
}
/// Check the status of a saveUrl job.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.SaveUrlJobStatus` object on success
/// or a `Async.PollError` object on failure.
@discardableResult open func saveUrlCheckJobStatus(asyncJobId: String) -> RpcRequest<Files.SaveUrlJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.saveUrlCheckJobStatus
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Searches for files and folders. Note: Recent changes will be reflected in search results within a few seconds
/// and older revisions of existing files may still match your query for up to a few days.
///
/// - parameter path: The path in the user's Dropbox to search. Should probably be a folder.
/// - parameter query: The string to search for. Query string may be rewritten to improve relevance of results. The
/// string is split on spaces into multiple tokens. For file name searching, the last token is used for prefix
/// matching (i.e. "bat c" matches "bat cave" but not "batman car").
/// - parameter start: The starting index within the search results (used for paging).
/// - parameter maxResults: The maximum number of search results to return.
/// - parameter mode: The search mode (filename, filename_and_content, or deleted_filename). Note that searching
/// file content is only available for Dropbox Business accounts.
///
/// - returns: Through the response callback, the caller will receive a `Files.SearchResult` object on success or a
/// `Files.SearchError` object on failure.
@available(*, unavailable, message:"search is deprecated. Use searchV2.")
@discardableResult open func search(path: String, query: String, start: UInt64 = 0, maxResults: UInt64 = 100, mode: Files.SearchMode = .filename) -> RpcRequest<Files.SearchResultSerializer, Files.SearchErrorSerializer> {
let route = Files.search
let serverArgs = Files.SearchArg(path: path, query: query, start: start, maxResults: maxResults, mode: mode)
return client.request(route, serverArgs: serverArgs)
}
/// Searches for files and folders. Note: searchV2 along with searchContinueV2 can only be used to retrieve a
/// maximum of 10,000 matches. Recent changes may not immediately be reflected in search results due to a short
/// delay in indexing. Duplicate results may be returned across pages. Some results may not be returned.
///
/// - parameter query: The string to search for. May match across multiple fields based on the request arguments.
/// Query string may be rewritten to improve relevance of results.
/// - parameter options: Options for more targeted search results.
/// - parameter matchFieldOptions: Options for search results match fields.
/// - parameter includeHighlights: Deprecated and moved this option to SearchMatchFieldOptions.
///
/// - returns: Through the response callback, the caller will receive a `Files.SearchV2Result` object on success or
/// a `Files.SearchError` object on failure.
@discardableResult open func searchV2(query: String, options: Files.SearchOptions? = nil, matchFieldOptions: Files.SearchMatchFieldOptions? = nil, includeHighlights: Bool = false) -> RpcRequest<Files.SearchV2ResultSerializer, Files.SearchErrorSerializer> {
let route = Files.searchV2
let serverArgs = Files.SearchV2Arg(query: query, options: options, matchFieldOptions: matchFieldOptions, includeHighlights: includeHighlights)
return client.request(route, serverArgs: serverArgs)
}
/// Fetches the next page of search results returned from searchV2. Note: searchV2 along with searchContinueV2 can
/// only be used to retrieve a maximum of 10,000 matches. Recent changes may not immediately be reflected in search
/// results due to a short delay in indexing. Duplicate results may be returned across pages. Some results may not
/// be returned.
///
/// - parameter cursor: The cursor returned by your last call to searchV2. Used to fetch the next page of results.
///
/// - returns: Through the response callback, the caller will receive a `Files.SearchV2Result` object on success or
/// a `Files.SearchError` object on failure.
@discardableResult open func searchContinueV2(cursor: String) -> RpcRequest<Files.SearchV2ResultSerializer, Files.SearchErrorSerializer> {
let route = Files.searchContinueV2
let serverArgs = Files.SearchV2ContinueArg(cursor: cursor)
return client.request(route, serverArgs: serverArgs)
}
/// Unlock the files at the given paths. A locked file can only be unlocked by the lock holder or, if a business
/// account, a team admin. A successful response indicates that the file has been unlocked. Returns a list of the
/// unlocked file paths and their metadata after this operation.
///
/// - parameter entries: List of 'entries'. Each 'entry' contains a path of the file which will be unlocked.
/// Duplicate path arguments in the batch are considered only once.
///
/// - returns: Through the response callback, the caller will receive a `Files.LockFileBatchResult` object on
/// success or a `Files.LockFileError` object on failure.
@discardableResult open func unlockFileBatch(entries: Array<Files.UnlockFileArg>) -> RpcRequest<Files.LockFileBatchResultSerializer, Files.LockFileErrorSerializer> {
let route = Files.unlockFileBatch
let serverArgs = Files.UnlockFileBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Create a new file with the contents provided in the request. Do not use this to upload a file larger than 150
/// MB. Instead, create an upload session with uploadSessionStart. Calls to this endpoint will count as data
/// transport calls for any Dropbox Business teams with a limit on the number of data transport calls allowed per
/// month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter path: Path in the user's Dropbox to save the file.
/// - parameter mode: Selects what to do if the file already exists.
/// - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename
/// the file to avoid conflict.
/// - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records
/// the time at which the file was written to the Dropbox servers. It can also record an additional timestamp,
/// provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or
/// modified.
/// - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via
/// notifications in the client software. If true, this tells the clients that this modification shouldn't result in
/// a user notification.
/// - parameter propertyGroups: List of custom properties to add to file.
/// - parameter strictConflict: Be more strict about how each WriteMode detects conflict. For example, always return
/// a conflict error when mode = update in WriteMode and the given "rev" doesn't match the existing file's "rev",
/// even if the existing file has been deleted.
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadError` object on failure.
@discardableResult open func upload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: Data) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> {
let route = Files.upload
let serverArgs = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Create a new file with the contents provided in the request. Do not use this to upload a file larger than 150
/// MB. Instead, create an upload session with uploadSessionStart. Calls to this endpoint will count as data
/// transport calls for any Dropbox Business teams with a limit on the number of data transport calls allowed per
/// month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter path: Path in the user's Dropbox to save the file.
/// - parameter mode: Selects what to do if the file already exists.
/// - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename
/// the file to avoid conflict.
/// - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records
/// the time at which the file was written to the Dropbox servers. It can also record an additional timestamp,
/// provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or
/// modified.
/// - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via
/// notifications in the client software. If true, this tells the clients that this modification shouldn't result in
/// a user notification.
/// - parameter propertyGroups: List of custom properties to add to file.
/// - parameter strictConflict: Be more strict about how each WriteMode detects conflict. For example, always return
/// a conflict error when mode = update in WriteMode and the given "rev" doesn't match the existing file's "rev",
/// even if the existing file has been deleted.
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadError` object on failure.
@discardableResult open func upload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: URL) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> {
let route = Files.upload
let serverArgs = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Create a new file with the contents provided in the request. Do not use this to upload a file larger than 150
/// MB. Instead, create an upload session with uploadSessionStart. Calls to this endpoint will count as data
/// transport calls for any Dropbox Business teams with a limit on the number of data transport calls allowed per
/// month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter path: Path in the user's Dropbox to save the file.
/// - parameter mode: Selects what to do if the file already exists.
/// - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename
/// the file to avoid conflict.
/// - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records
/// the time at which the file was written to the Dropbox servers. It can also record an additional timestamp,
/// provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or
/// modified.
/// - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via
/// notifications in the client software. If true, this tells the clients that this modification shouldn't result in
/// a user notification.
/// - parameter propertyGroups: List of custom properties to add to file.
/// - parameter strictConflict: Be more strict about how each WriteMode detects conflict. For example, always return
/// a conflict error when mode = update in WriteMode and the given "rev" doesn't match the existing file's "rev",
/// even if the existing file has been deleted.
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadError` object on failure.
@discardableResult open func upload(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false, input: InputStream) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> {
let route = Files.upload
let serverArgs = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
/// Append more data to an upload session. When the parameter close is set, this call will close the session. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. Calls to this endpoint will count as data transport calls for any Dropbox Business teams with
/// a limit on the number of data transport calls allowed per month. For more information, see the Data transport
/// limit page https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@discardableResult open func uploadSessionAppendV2(cursor: Files.UploadSessionCursor, close: Bool = false, input: Data) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppendV2
let serverArgs = Files.UploadSessionAppendArg(cursor: cursor, close: close)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Append more data to an upload session. When the parameter close is set, this call will close the session. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. Calls to this endpoint will count as data transport calls for any Dropbox Business teams with
/// a limit on the number of data transport calls allowed per month. For more information, see the Data transport
/// limit page https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@discardableResult open func uploadSessionAppendV2(cursor: Files.UploadSessionCursor, close: Bool = false, input: URL) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppendV2
let serverArgs = Files.UploadSessionAppendArg(cursor: cursor, close: close)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Append more data to an upload session. When the parameter close is set, this call will close the session. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. Calls to this endpoint will count as data transport calls for any Dropbox Business teams with
/// a limit on the number of data transport calls allowed per month. For more information, see the Data transport
/// limit page https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@discardableResult open func uploadSessionAppendV2(cursor: Files.UploadSessionCursor, close: Bool = false, input: InputStream) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppendV2
let serverArgs = Files.UploadSessionAppendArg(cursor: cursor, close: close)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
/// Append more data to an upload session. A single request should not upload more than 150 MB. The maximum size of
/// a file one can upload to an upload session is 350 GB. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter sessionId: The upload session ID (returned by uploadSessionStart).
/// - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't
/// lost or duplicated in the event of a network error.
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@available(*, unavailable, message:"uploadSessionAppend is deprecated. Use uploadSessionAppendV2.")
@discardableResult open func uploadSessionAppend(sessionId: String, offset: UInt64, input: Data) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppend
let serverArgs = Files.UploadSessionCursor(sessionId: sessionId, offset: offset)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Append more data to an upload session. A single request should not upload more than 150 MB. The maximum size of
/// a file one can upload to an upload session is 350 GB. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter sessionId: The upload session ID (returned by uploadSessionStart).
/// - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't
/// lost or duplicated in the event of a network error.
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@available(*, unavailable, message:"uploadSessionAppend is deprecated. Use uploadSessionAppendV2.")
@discardableResult open func uploadSessionAppend(sessionId: String, offset: UInt64, input: URL) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppend
let serverArgs = Files.UploadSessionCursor(sessionId: sessionId, offset: offset)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Append more data to an upload session. A single request should not upload more than 150 MB. The maximum size of
/// a file one can upload to an upload session is 350 GB. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter sessionId: The upload session ID (returned by uploadSessionStart).
/// - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't
/// lost or duplicated in the event of a network error.
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Void` object on success or a
/// `Files.UploadSessionLookupError` object on failure.
@available(*, unavailable, message:"uploadSessionAppend is deprecated. Use uploadSessionAppendV2.")
@discardableResult open func uploadSessionAppend(sessionId: String, offset: UInt64, input: InputStream) -> UploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> {
let route = Files.uploadSessionAppend
let serverArgs = Files.UploadSessionCursor(sessionId: sessionId, offset: offset)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
/// Finish an upload session and save the uploaded data to the given file path. A single request should not upload
/// more than 150 MB. The maximum size of a file one can upload to an upload session is 350 GB. Calls to this
/// endpoint will count as data transport calls for any Dropbox Business teams with a limit on the number of data
/// transport calls allowed per month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter commit: Contains the path and other optional modifiers for the commit.
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadSessionFinishError` object on failure.
@discardableResult open func uploadSessionFinish(cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, input: Data) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> {
let route = Files.uploadSessionFinish
let serverArgs = Files.UploadSessionFinishArg(cursor: cursor, commit: commit)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Finish an upload session and save the uploaded data to the given file path. A single request should not upload
/// more than 150 MB. The maximum size of a file one can upload to an upload session is 350 GB. Calls to this
/// endpoint will count as data transport calls for any Dropbox Business teams with a limit on the number of data
/// transport calls allowed per month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter commit: Contains the path and other optional modifiers for the commit.
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadSessionFinishError` object on failure.
@discardableResult open func uploadSessionFinish(cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, input: URL) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> {
let route = Files.uploadSessionFinish
let serverArgs = Files.UploadSessionFinishArg(cursor: cursor, commit: commit)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Finish an upload session and save the uploaded data to the given file path. A single request should not upload
/// more than 150 MB. The maximum size of a file one can upload to an upload session is 350 GB. Calls to this
/// endpoint will count as data transport calls for any Dropbox Business teams with a limit on the number of data
/// transport calls allowed per month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter cursor: Contains the upload session ID and the offset.
/// - parameter commit: Contains the path and other optional modifiers for the commit.
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a
/// `Files.UploadSessionFinishError` object on failure.
@discardableResult open func uploadSessionFinish(cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, input: InputStream) -> UploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> {
let route = Files.uploadSessionFinish
let serverArgs = Files.UploadSessionFinishArg(cursor: cursor, commit: commit)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
/// This route helps you commit many files at once into a user's Dropbox. Use uploadSessionStart and
/// uploadSessionAppendV2 to upload file contents. We recommend uploading many files in parallel to increase
/// throughput. Once the file contents have been uploaded, rather than calling uploadSessionFinish, use this route
/// to finish all your upload sessions in a single request. close in UploadSessionStartArg or close in
/// UploadSessionAppendArg needs to be true for the last uploadSessionStart or uploadSessionAppendV2 call. The
/// maximum size of a file one can upload to an upload session is 350 GB. This route will return a job_id
/// immediately and do the async commit job in background. Use uploadSessionFinishBatchCheck to check the job
/// status. For the same account, this route should be executed serially. That means you should not start the next
/// job before current job finishes. We allow up to 1000 entries in a single request. Calls to this endpoint will
/// count as data transport calls for any Dropbox Business teams with a limit on the number of data transport calls
/// allowed per month. For more information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter entries: Commit information for each file in the batch.
///
/// - returns: Through the response callback, the caller will receive a `Files.UploadSessionFinishBatchLaunch`
/// object on success or a `Void` object on failure.
@discardableResult open func uploadSessionFinishBatch(entries: Array<Files.UploadSessionFinishArg>) -> RpcRequest<Files.UploadSessionFinishBatchLaunchSerializer, VoidSerializer> {
let route = Files.uploadSessionFinishBatch
let serverArgs = Files.UploadSessionFinishBatchArg(entries: entries)
return client.request(route, serverArgs: serverArgs)
}
/// Returns the status of an asynchronous job for uploadSessionFinishBatch. If success, it returns list of result
/// for each entry.
///
/// - parameter asyncJobId: Id of the asynchronous job. This is the value of a response returned from the method
/// that launched the job.
///
/// - returns: Through the response callback, the caller will receive a `Files.UploadSessionFinishBatchJobStatus`
/// object on success or a `Async.PollError` object on failure.
@discardableResult open func uploadSessionFinishBatchCheck(asyncJobId: String) -> RpcRequest<Files.UploadSessionFinishBatchJobStatusSerializer, Async.PollErrorSerializer> {
let route = Files.uploadSessionFinishBatchCheck
let serverArgs = Async.PollArg(asyncJobId: asyncJobId)
return client.request(route, serverArgs: serverArgs)
}
/// Upload sessions allow you to upload a single file in one or more requests, for example where the size of the
/// file is greater than 150 MB. This call starts a new upload session with the given data. You can then use
/// uploadSessionAppendV2 to add more data and uploadSessionFinish to save all the data to a file in Dropbox. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. An upload session can be used for a maximum of 48 hours. Attempting to use an sessionId in
/// UploadSessionStartResult with uploadSessionAppendV2 or uploadSessionFinish more than 48 hours after its creation
/// will return a notFound in UploadSessionLookupError. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an Data object.
///
/// - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on
/// success or a `Void` object on failure.
@discardableResult open func uploadSessionStart(close: Bool = false, input: Data) -> UploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> {
let route = Files.uploadSessionStart
let serverArgs = Files.UploadSessionStartArg(close: close)
return client.request(route, serverArgs: serverArgs, input: .data(input))
}
/// Upload sessions allow you to upload a single file in one or more requests, for example where the size of the
/// file is greater than 150 MB. This call starts a new upload session with the given data. You can then use
/// uploadSessionAppendV2 to add more data and uploadSessionFinish to save all the data to a file in Dropbox. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. An upload session can be used for a maximum of 48 hours. Attempting to use an sessionId in
/// UploadSessionStartResult with uploadSessionAppendV2 or uploadSessionFinish more than 48 hours after its creation
/// will return a notFound in UploadSessionLookupError. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an URL object.
///
/// - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on
/// success or a `Void` object on failure.
@discardableResult open func uploadSessionStart(close: Bool = false, input: URL) -> UploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> {
let route = Files.uploadSessionStart
let serverArgs = Files.UploadSessionStartArg(close: close)
return client.request(route, serverArgs: serverArgs, input: .file(input))
}
/// Upload sessions allow you to upload a single file in one or more requests, for example where the size of the
/// file is greater than 150 MB. This call starts a new upload session with the given data. You can then use
/// uploadSessionAppendV2 to add more data and uploadSessionFinish to save all the data to a file in Dropbox. A
/// single request should not upload more than 150 MB. The maximum size of a file one can upload to an upload
/// session is 350 GB. An upload session can be used for a maximum of 48 hours. Attempting to use an sessionId in
/// UploadSessionStartResult with uploadSessionAppendV2 or uploadSessionFinish more than 48 hours after its creation
/// will return a notFound in UploadSessionLookupError. Calls to this endpoint will count as data transport calls
/// for any Dropbox Business teams with a limit on the number of data transport calls allowed per month. For more
/// information, see the Data transport limit page
/// https://www.dropbox.com/developers/reference/data-transport-limit.
///
/// - parameter close: If true, the current session will be closed, at which point you won't be able to call
/// uploadSessionAppendV2 anymore with the current session.
/// - parameter input: The file to upload, as an InputStream object.
///
/// - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on
/// success or a `Void` object on failure.
@discardableResult open func uploadSessionStart(close: Bool = false, input: InputStream) -> UploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> {
let route = Files.uploadSessionStart
let serverArgs = Files.UploadSessionStartArg(close: close)
return client.request(route, serverArgs: serverArgs, input: .stream(input))
}
}
| 74.995156 | 506 | 0.732633 |
fb91597a3ecd268b20d27a64885b9b01f9e4fa76 | 2,299 | //
// SceneDelegate.swift
// IOS_Codepath_Prework
//
// Created by Andy Chen on 1/13/22.
//
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 necessarily 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.377358 | 147 | 0.713789 |
56a2b5e6af2806576ef2fa869c7b3bb7ca9fd227 | 1,932 | //
// GoodyHutRewardPopupView.swift
// SmartMacOSUILibrary
//
// Created by Michael Rommel on 02.06.21.
//
import SwiftUI
import SmartAILibrary
import SmartAssets
struct GoodyHutRewardPopupView: View {
@ObservedObject
var viewModel: GoodyHutRewardPopupViewModel
public init(viewModel: GoodyHutRewardPopupViewModel) {
self.viewModel = viewModel
}
var body: some View {
Group {
VStack(spacing: 0) {
Text(self.viewModel.title)
.font(.title2)
.bold()
.padding(.top, 13)
.padding(.bottom, 10)
VStack(spacing: 10) {
Text(self.viewModel.text)
.padding(.bottom, 10)
Button(action: {
self.viewModel.closePopup()
}, label: {
Text("Close")
})
.padding(.bottom, 8)
}
.frame(width: 262, height: 114, alignment: .center)
.background(Color(Globals.Colors.dialogBackground))
}
.padding(.bottom, 43)
.padding(.leading, 19)
.padding(.trailing, 19)
}
.frame(width: 300, height: 200, alignment: .top)
.dialogBackground()
}
}
#if DEBUG
struct GoodyHutRewardPopupView_Previews: PreviewProvider {
static var previews: some View {
// swiftlint:disable:next redundant_discardable_let
let _ = GameViewModel(preloadAssets: true)
//let game = DemoGameModel()
//let environment = GameEnvironment(game: game)
let viewModel = GoodyHutRewardPopupViewModel(goodyHutType: .additionalPopulation, location: HexPoint.zero)
GoodyHutRewardPopupView(viewModel: viewModel)
//.environment(\.gameEnvironment, environment)
}
}
#endif
| 26.465753 | 114 | 0.553313 |
50c3eb3c7a3631d8b294190b6f71ab1a52dd4a95 | 880 | //
// SurfaceTileType.swift
//
// Created by Zack Brown on 11/03/2021.
//
import Euclid
import Meadow
extension SurfaceTileType {
var abbreviation: String {
switch self {
case .dirt: return "D"
case .sand: return "Sa"
case .stone: return "St"
case .wood: return "W"
}
}
public var description: String {
switch self {
case .dirt: return "Dirt"
case .sand: return "Sand"
case .stone: return "Stone"
case .wood: return "Wood"
}
}
var color: Color {
switch self {
case .dirt: return Color(0.1, 0.5, 0.9, 1.0)
case .sand: return Color(0.5, 0.9, 0.1, 1.0)
case .stone: return Color(0.9, 0.1, 0.5, 1.0)
case .wood: return Color(0.1, 0.9, 0.5, 1.0)
}
}
}
| 20 | 53 | 0.490909 |
ab9a92003857ce8f56730cdc20acccb7df890156 | 2,049 | //
// Regex.swift
// SwifSoup
//
// Created by Nabil Chatbi on 08/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
public struct Pattern {
public static let CASE_INSENSITIVE: Int = 0x02
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
}
static public func compile(_ s: String) -> Pattern {
return Pattern(s)
}
static public func compile(_ s: String, _ op: Int) -> Pattern {
return Pattern(s)
}
func validate()throws {
_ = try NSRegularExpression(pattern: self.pattern, options: [])
}
func matcher(in text: String) -> Matcher {
do {
let regex = try NSRegularExpression(pattern: self.pattern, options: [])
let nsString = NSString(string: text)
let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
return Matcher(results, text)
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return Matcher([], text)
}
}
public func toString() -> String {
return pattern
}
}
public class Matcher {
let matches: [NSTextCheckingResult]
let string: String
var index: Int = -1
public var count: Int { return matches.count}
init(_ m: [NSTextCheckingResult], _ s: String) {
matches = m
string = s
}
@discardableResult
public func find() -> Bool {
index += 1
if(index < matches.count) {
return true
}
return false
}
public func group(_ i: Int) -> String? {
let b = matches[index]
#if !os(Linux) && !swift(>=4)
let c = b.rangeAt(i)
#else
let c = b.range(at: i)
#endif
if(c.location == NSNotFound) {return nil}
let result = string.substring(c.location, c.length)
return result
}
public func group() -> String? {
return group(0)
}
}
| 24.105882 | 116 | 0.56613 |
f85618de5b9dd293ed84c3746f01a7084a5e0a15 | 706 | //
// MyExt.swift
// CosRemote
//
// Created by 郭 又鋼 on 2016/2/18.
// Copyright © 2016年 郭 又鋼. All rights reserved.
//
import Foundation
import CoreBluetooth
import UIKit
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData)
}
}
}
}
} | 27.153846 | 99 | 0.583569 |
dd3ce2db815fc74220ba229e89e03cf769a97590 | 212 | // 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 {
func a(c {
}
struct c<f : c<Int>
| 23.555556 | 87 | 0.731132 |
9089877a498427f14e6f961f6a58ce4b37bb1fa8 | 1,464 | // 35_Search Insert Position
// https://leetcode.com/problems/search-insert-position/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
//
//You may assume no duplicates in the array.
//
//Example 1:
//
//Input: [1,3,5,6], 5
//Output: 2
//Example 2:
//
//Input: [1,3,5,6], 2
//Output: 1
//Example 3:
//
//Input: [1,3,5,6], 7
//Output: 4
//Example 4:
//
//Input: [1,3,5,6], 0
//Output: 0
//
import Foundation
class Num35 {
/// Binary search, when while loop ends, check where to insert
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
if nums.count == 0 {
return 0
}
if nums.count == 1 {
if nums[0] == target {
return 0
}
else if nums[0] > target {
return 0
}
else {
return 1
}
}
var start = 0
var end = nums.count - 1
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] < target {
start = mid
}
else if nums[mid] > target {
end = mid
}
else {
return mid
}
}
if target <= nums[start] {
return start
}
else if nums[start] < target, target <= nums[end] {
return end
}
else {
return end + 1
}
}
}
| 19.52 | 157 | 0.545765 |
21d153cebf9d39b164bc591520df87acd465d8db | 249 | //
// common.swift
// heic_demo
//
// Created by Jerry Tian on 2020/11/25.
//
import UIKit
import SwiftyBeaver
import AVFoundation
import VideoToolbox
let log = SwiftyBeaver.self
let cvPxFormat = kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
| 16.6 | 64 | 0.783133 |
1807f1c4dd481e8f0b72b97e567ff5cfc5a9a06f | 243 | // Created by Harris Dawurang on 4/11/22.
struct TeamListsData: Codable {
let response: [TeamListData]
}
struct TeamListData: Codable {
let team: TeamListInfo
}
struct TeamListInfo: Codable {
var id: Int
var name: String
}
| 16.2 | 42 | 0.695473 |
e0a3190d5346417801cc81da2217de1ed1e32aa9 | 3,465 | //
// FlickrProvider.swift
// SwiftCache
//
// Created by Tomas Radvansky on 11/21/2016.
// Copyright (c) 2016 Tomas Radvansky. All rights reserved.
//
import Foundation
import SwiftCache
class FlickrProvider {
typealias FlickrResponse = (NSError?, [FlickrPhoto]?) -> Void
struct Keys {
static let flickrKey = "0461b2b85aee5a025189ce3eed1aff6b"
}
struct Errors {
static let invalidAccessErrorCode = 100
}
class func fetchPhotosForSearchText(searchText: String, onCompletion: @escaping FlickrResponse) -> Void {
let escapedSearchText: String = searchText.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)!
let urlString: String = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(Keys.flickrKey)&tags=\(escapedSearchText)&per_page=25&format=json&nojsoncallback=1"
_ = SwiftCache.sharedInstance.loadResource(url: URL(string:urlString)!, completionHandler: { (object:CachedObject?, error:NSError?) in
if let error:NSError = error
{
print("Error fetching photos: \(error)")
onCompletion(error, nil)
return
}
else
{
if let cachedObject:CachedObject = object
{
do {
let resultsDictionary = try JSONSerialization.jsonObject(with: cachedObject.data as Data, options: []) as? [String: AnyObject]
guard let results = resultsDictionary else { return }
if let statusCode = results["code"] as? Int {
if statusCode == Errors.invalidAccessErrorCode {
let invalidAccessError = NSError(domain: "com.flickr.api", code: statusCode, userInfo: nil)
onCompletion(invalidAccessError, nil)
return
}
}
guard let photosContainer = resultsDictionary!["photos"] as? NSDictionary else { return }
guard let photosArray = photosContainer["photo"] as? [NSDictionary] else { return }
let flickrPhotos: [FlickrPhoto] = photosArray.map { photoDictionary in
let photoId = photoDictionary["id"] as? String ?? ""
let farm = photoDictionary["farm"] as? Int ?? 0
let secret = photoDictionary["secret"] as? String ?? ""
let server = photoDictionary["server"] as? String ?? ""
let title = photoDictionary["title"] as? String ?? ""
let flickrPhoto = FlickrPhoto(photoId: photoId, farm: farm, secret: secret, server: server, title: title)
return flickrPhoto
}
onCompletion(nil, flickrPhotos)
} catch let error as NSError {
print("Error parsing JSON: \(error)")
onCompletion(error, nil)
return
}
}
}
})
}
}
| 43.3125 | 192 | 0.505339 |
796e34f21b860239d8a7f65858d77c4e64f8f741 | 15,762 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_TwoCaseOneStructPayload
// RUN: %target-codesign %t/reflect_Enum_TwoCaseOneStructPayload
// RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_TwoCaseOneStructPayload | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-ALL
// REQUIRES: reflection_test_support
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
// Note: struct Marker has no extra inhabitants, so the enum will use a separate tag
struct Marker {
let value = 1
}
enum TwoCaseOneStructPayloadEnum {
case valid(Marker)
case invalid
}
class ClassWithTwoCaseOneStructPayloadEnum {
var e1: TwoCaseOneStructPayloadEnum?
var e2: TwoCaseOneStructPayloadEnum = .valid(Marker())
var e3: TwoCaseOneStructPayloadEnum = .invalid
var e4: TwoCaseOneStructPayloadEnum? = .valid(Marker())
var e5: TwoCaseOneStructPayloadEnum? = .invalid
var e6: TwoCaseOneStructPayloadEnum??
}
reflect(object: ClassWithTwoCaseOneStructPayloadEnum())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=107 alignment=8 stride=112 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=e1 offset=16
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e2 offset=32
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (field name=e3 offset=48
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (field name=e4 offset=64
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e5 offset=80
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e6 offset=96
// CHECK-64: (single_payload_enum size=11 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=55 alignment=4 stride=56 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=e1 offset=8
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e2 offset=16
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (field name=e3 offset=24
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (field name=e4 offset=32
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e5 offset=40
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e6 offset=48
// CHECK-32: (single_payload_enum size=7 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))))
reflect(enum: TwoCaseOneStructPayloadEnum.valid(Marker()))
// CHECK-ALL: Reflecting an enum.
// CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-ALL-NEXT: Type reference:
// CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum)
// CHECK-ALL: Type info:
// CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (case name=valid index=0 offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64-NEXT: (case name=invalid index=1))
// CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (case name=valid index=0 offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32-NEXT: (case name=invalid index=1))
// CHECK-ALL: Enum value:
// CHECK-ALL-NEXT: (enum_value name=valid index=0
// CHECK-ALL-NEXT: (struct reflect_Enum_TwoCaseOneStructPayload.Marker)
// CHECK-ALL-NEXT: )
reflect(enum: TwoCaseOneStructPayloadEnum.invalid)
// CHECK-ALL: Reflecting an enum.
// CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-ALL-NEXT: Type reference:
// CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum)
// CHECK-ALL: Type info:
// CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (case name=valid index=0 offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64-NEXT: (case name=invalid index=1))
// CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (case name=valid index=0 offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32-NEXT: (case name=invalid index=1))
// CHECK-ALL: Enum value:
// CHECK-ALL-NEXT: (enum_value name=invalid index=1)
doneReflecting()
// CHECK-ALL: Done.
| 62.796813 | 167 | 0.683606 |
e28ec083402eea713a338b5bba2546ea57e42558 | 2,390 | //
// KeypadView.swift
// iPhoneXLockScreen
//
// Created by Hung Truong on 12/2/17.
// Copyright © 2017 Hung Truong. All rights reserved.
//
import UIKit
protocol KeypadViewDelegate : NSObjectProtocol {
func keypadButtonPressed(_ value: String)
}
class KeypadView: UIView {
weak var delegate : KeypadViewDelegate?
@IBOutlet var oneButton: KeypadButton!
@IBOutlet var twoButton: KeypadButton!
@IBOutlet var threeButton: KeypadButton!
@IBOutlet var fourButton: KeypadButton!
@IBOutlet var fiveButton: KeypadButton!
@IBOutlet var sixButton: KeypadButton!
@IBOutlet var sevenButton: KeypadButton!
@IBOutlet var eightButton: KeypadButton!
@IBOutlet var nineButton: KeypadButton!
@IBOutlet var zeroButton: KeypadButton!
override func awakeFromNib() {
oneButton.setTitle("1", subTitle: " ", for: .normal)
twoButton.setTitle("2", subTitle: "A B C", for: .normal)
threeButton.setTitle("3", subTitle: "D E F", for: .normal)
fourButton.setTitle("4", subTitle: "G H I", for: .normal)
fiveButton.setTitle("5", subTitle: "J K L", for: .normal)
sixButton.setTitle("6", subTitle: "M N O", for: .normal)
sevenButton.setTitle("7", subTitle: "P Q R S", for: .normal)
eightButton.setTitle("8", subTitle: "T U V", for: .normal)
nineButton.setTitle("9", subTitle: "W X Y Z", for: .normal)
zeroButton.setTitle("0", subTitle: " ", for: .normal)
}
@IBAction func keypadButtonPressed(_ button: KeypadButton) {
switch button {
case oneButton:
delegate?.keypadButtonPressed("1")
case twoButton:
delegate?.keypadButtonPressed("2")
case threeButton:
delegate?.keypadButtonPressed("3")
case fourButton:
delegate?.keypadButtonPressed("4")
case fiveButton:
delegate?.keypadButtonPressed("5")
case sixButton:
delegate?.keypadButtonPressed("6")
case sevenButton:
delegate?.keypadButtonPressed("7")
case eightButton:
delegate?.keypadButtonPressed("8")
case nineButton:
delegate?.keypadButtonPressed("9")
case zeroButton:
delegate?.keypadButtonPressed("0")
default:
assertionFailure("this really shouldn't happen")
}
}
}
| 35.147059 | 68 | 0.631381 |
036f081b73dc0e05231ada5df7425326c028c529 | 371 | //
// MODevice.swift
// themixxapp
//
// Created by Andre Barrett on 08/02/2016.
// Copyright © 2016 MixxLabs. All rights reserved.
//
import Foundation
struct MODevice {
var lat: String?
var lon: String?
var model: String?
var name: String?
var notificationIdentifier: String?
var type: String?
var uniqueIdentifier: String?
} | 17.666667 | 51 | 0.652291 |
d5643ccff4e9e1013e567cfe0952f3d0cc023122 | 4,866 | //
// BlockDataSourceTests.swift
// BlockDataSource
//
// Created by Adam Cumiskey on 7/12/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
@testable import BlockDataSource
func basicRow() -> Row {
return Row(
identifier: "Basic",
configure: { cell in
cell.textLabel?.text = "Basic Cell"
},
selectionStyle: .Blue
)
}
func customRow() -> Row {
return Row(identifier: "", configure: { cell in
})
}
func header() -> HeaderFooter {
return HeaderFooter(title: "Header", height: 50.0)
}
func section() -> Section {
return Section(
header: header(),
rows: [
basicRow(),
basicRow(),
basicRow()
],
footer: header()
)
}
func blockDataSource() -> BlockDataSource {
return BlockDataSource(
sections: [
Section(
header: HeaderFooter(
title: "Examples",
height: 30
),
rows: [
Row(
identifier: "Basic",
configure: { cell in
cell.textLabel?.text = "Basic Cell"
},
selectionStyle: .Blue
),
Row(
identifier: "Subtitle",
configure: { cell in
cell.textLabel?.text = "Subtitle Cell"
cell.detailTextLabel?.text = "This is a subtitle"
}
),
Row(
identifier: "Basic",
configure: { cell in
cell.textLabel?.text = "Switch"
let `switch` = UISwitch(
frame: CGRect(
origin: CGPointZero,
size: CGSize(
width: 75,
height: 30
)
)
)
cell.accessoryView = `switch`
}
)
]
),
Section(
rows: [
Row(
identifier: "Basic",
configure: { cell in
cell.textLabel?.text = "Basic Cell"
},
selectionStyle: .Blue
),
Row(
identifier: "Subtitle",
configure: { cell in
cell.textLabel?.text = "Subtitle Cell"
cell.detailTextLabel?.text = "This is a subtitle"
}
)
],
footer: HeaderFooter(
title: "Footer",
height: 100.0
)
)
]
)
}
class BlockDataSourceSpec: QuickSpec {
override func spec() {
describe("a data source") {
var dataSource: BlockDataSource!
var sectionCount: Int!
beforeEach {
dataSource = blockDataSource()
sectionCount = dataSource.sections.count
}
it("can add a new section") {
dataSource.sections.append(section())
expect(dataSource.sections.count).to(equal(sectionCount + 1))
}
it("can add new sections") {
dataSource.sections.appendContentsOf([section(), section()])
expect(dataSource.sections.count).to(equal(sectionCount + 2))
}
it("can delete a section") {
dataSource.sections.removeLast()
expect(dataSource.sections.count).to(equal(sectionCount - 1))
}
describe("its sections") {
var section: Section!
var rowCount: Int!
beforeEach {
section = dataSource.sections.first
rowCount = section.rows.count
}
it("can add a row") {
section.rows.append(basicRow())
expect(section.rows.count).to(equal(rowCount + 1))
}
it("can delete a row") {
section.rows.removeLast()
expect(section.rows.count).to(equal(rowCount - 1))
}
}
}
}
}
| 30.223602 | 77 | 0.386354 |
efb8bc93b544971193d9797cb73f1afce0bca285 | 288 | //
// ExploreCell.swift
// LetsEat
//
// Created by Craig Clayton on 11/20/18.
// Copyright © 2018 Cocoa Academy. All rights reserved.
//
import UIKit
class ExploreCell: UICollectionViewCell {
@IBOutlet var lblName:UILabel!
@IBOutlet var imgExplore:UIImageView!
}
| 16.941176 | 56 | 0.6875 |
755499db0c6284b2e41fb7afc25a14a8aabdc624 | 3,999 | //
// FeedServiceTests.swift
// MAGETests
//
// Created by Daniel Barela on 6/17/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import Quick
import Nimble
import PureLayout
import OHHTTPStubs
import Kingfisher
@testable import MAGE
@available(iOS 13.0, *)
class FeedServiceTests: KIFSpec {
override func spec() {
describe("FeedServiceTests") {
var isSetup = false;
beforeEach {
if (!isSetup) {
ImageCache.default.clearMemoryCache();
ImageCache.default.clearDiskCache();
TestHelpers.clearAndSetUpStack();
MageCoreDataFixtures.quietLogging();
isSetup = true;
}
UserDefaults.standard.baseServerUrl = "https://magetest";
UserDefaults.standard.mapType = 0;
UserDefaults.standard.showMGRS = false;
Server.setCurrentEventId(1);
MageCoreDataFixtures.addEvent();
}
afterEach {
FeedService.shared.stop();
expect(FeedService.shared.isStopped()).toEventually(beTrue(), timeout: DispatchTimeInterval.seconds(10), pollInterval: DispatchTimeInterval.milliseconds(500), description: "Feed Service Stopped");
HTTPStubs.removeAllStubs();
MageCoreDataFixtures.clearAllData();
}
it("should request feed items") {
MageCoreDataFixtures.addFeedToEvent(eventId: 1, id: "1", title: "My Feed", primaryProperty: "primary", secondaryProperty: "secondary")
var feedItemsServerCallCount = 0;
MockMageServer.stubJSONSuccessRequest(url: "https://magetest/api/events/1/feeds/1/content", filePath: "feedContent.json")
HTTPStubs.stubRequests(passingTest: { (request) -> Bool in
return request.url == URL(string: "https://magetest/api/events/1/feeds/1/content");
}) { (request) -> HTTPStubsResponse in
print("in here")
feedItemsServerCallCount += 1;
let stubPath = OHPathForFile("feedContent.json", type(of: self))
return HTTPStubsResponse(fileAtPath: stubPath!, statusCode: 200, headers: ["Content-Type": "application/json"]);
};
FeedService.shared.start();
expect(feedItemsServerCallCount).toEventually(beGreaterThan(1), timeout: DispatchTimeInterval.seconds(10), pollInterval: DispatchTimeInterval.milliseconds(500), description: "Feed Items Pulled");
}
it("should request feed items for a new feed") {
var feedItemsServerCallCount = 0;
HTTPStubs.stubRequests(passingTest: { (request) -> Bool in
return request.url == URL(string: "https://magetest/api/events/1/feeds/2/content");
}) { (request) -> HTTPStubsResponse in
print("returning the feed items")
feedItemsServerCallCount += 1;
let stubPath = OHPathForFile("feedContent.json", type(of: self))
return HTTPStubsResponse(fileAtPath: stubPath!, statusCode: 200, headers: ["Content-Type": "application/json"]);
};
FeedService.shared.start();
MageCoreDataFixtures.addFeedToEvent(eventId: 1, id: "2", title: "My Feed", primaryProperty: "primary", secondaryProperty: "secondary")
expect(feedItemsServerCallCount).toEventually(beGreaterThan(1), timeout: DispatchTimeInterval.seconds(10), pollInterval: DispatchTimeInterval.seconds(1), description: "Feed Items Pulled");
}
}
}
}
| 43.945055 | 212 | 0.575144 |
ccf692e4c2db40434c2779bc6bc64a15341866a4 | 3,034 | //
// MovieNumericalInformationContainerView.swift
// MoviesUIKit
//
// Created by Bartosz Żmija on 12/02/2021.
//
import UIKit
import CoreUIKit
import RxCocoa
import RxSwift
import RxDataSources
/// View containing numerical information.
final class MovieNumericalInformationContainerView: UIView {
// MARK: Private properties
private let contentStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
return stackView
}()
let contentViews: [InformationType: MovieNumericalInformationView] = {
let views = InformationType.orderedTypes.map { MovieNumericalInformationView(icon: $0.icon) }
return Dictionary(zip(InformationType.orderedTypes, views)) { key, _ in key }
}()
// MARK: Initializers
/// Initializes the receiver.
init() {
super.init(frame: .zero)
setupHierarchy()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("Please initialize this object from code.")
}
// MARK: Private methods
private func setupHierarchy() {
addSubview(contentStackView)
InformationType.orderedTypes
.compactMap { contentViews[$0] }
.forEach(contentStackView.addArrangedSubview)
}
private func setupConstraints() {
contentStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentStackView.bottomAnchor.constraint(equalTo: bottomAnchor),
contentStackView.topAnchor.constraint(equalTo: topAnchor)
])
}
func bind(value: String, for type: InformationType) {
contentViews[type]?.isHidden = value.isEmpty
contentViews[type]?.value = value
}
// MARK: Enums
enum InformationType {
case score
case runtime
case reviews
static let orderedTypes: [InformationType] = [
.score, .runtime, .reviews
]
var icon: UIImage {
switch self {
case .score:
guard let image = UIImage(named: "Score", in: Bundle(for: MoviesListView.self), compatibleWith: nil) else {
fatalError("Missing score image.")
}
return image
case .runtime:
guard let image = UIImage(named: "Runtime", in: Bundle(for: MoviesListView.self), compatibleWith: nil) else {
fatalError("Missing runtime image.")
}
return image
case .reviews:
guard let image = UIImage(named: "Reviews", in: Bundle(for: MoviesListView.self), compatibleWith: nil) else {
fatalError("Missing reviews image.")
}
return image
}
}
}
}
| 30.34 | 125 | 0.621292 |
9b18af56f63afc6ca645fb4b90eed78a90355514 | 2,302 | import UIKit
class VSave:ViewMain
{
private(set) weak var viewProgress:VSaveProgress!
private let kBottomHeight:CGFloat = 150
private let kProgressTop:CGFloat = 160
private let kProgressHeight:CGFloat = 200
required init(controller:UIViewController)
{
super.init(controller:controller)
backgroundColor = UIColor.clear
guard
let controller:CSave = controller as? CSave
else
{
return
}
factoryViews(controller:controller)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func factoryViews(controller:CSave)
{
let colourTop:UIColor = UIColor(
red:1,
green:0.5215686274509804,
blue:0.43529411764705883,
alpha:1)
let colourBottom:UIColor = UIColor(
red:0.8627450980392157,
green:0.3529411764705883,
blue:0.2588235294117647,
alpha:1)
let viewGradient:VGradient = VGradient.vertical(
colourTop:colourTop,
colourBottom:colourBottom)
let viewBottom:VSaveBottom = VSaveBottom(
controller:controller)
let viewProgress:VSaveProgress = VSaveProgress(
controller:controller)
self.viewProgress = viewProgress
addSubview(viewGradient)
addSubview(viewBottom)
addSubview(viewProgress)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:viewBottom,
toView:self)
NSLayoutConstraint.height(
view:viewBottom,
constant:kBottomHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBottom,
toView:self)
NSLayoutConstraint.topToTop(
view:viewProgress,
toView:self,
constant:kProgressTop)
NSLayoutConstraint.height(
view:viewProgress,
constant:kProgressHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewProgress,
toView:self)
}
}
| 25.865169 | 56 | 0.571677 |
e8c9f3d73bb4ea6a7ed71a79ed56dad91cbd8ff5 | 2,010 | import Foundation
let staffNum: Int = 5
public class SingleLineScoreLayout {
public let staffHeight: CGFloat
public let staffLineWidth: CGFloat
public let stemWidth: CGFloat
public let widthPerUnitNoteLength: CGFloat
public let barMarginRight: CGFloat
public let minStemHeight: CGFloat
public let maxBeamSlope: CGFloat
public let dotMarginLeft: CGFloat
public let fillingStaffLineWidth: CGFloat
public let fillingStaffLineXLength: CGFloat
public let noteHeadSize: CGSize
public let beamLineWidth: CGFloat
public let tupletFontSize: CGFloat
public let clefWidth: CGFloat
public let meterSymbolWidth: CGFloat
public init(
staffHeight: CGFloat = 60,
staffLineWidth: CGFloat = 1,
stemWidth: CGFloat = 2,
widthPerUnitNoteLength: CGFloat = 40,
barMarginRight: CGFloat = 10,
minStemHeight: CGFloat = 30,
maxBeamSlope: CGFloat = 0.2,
dotMarginLeft: CGFloat = 3,
fillingStaffLineWidth: CGFloat = 1,
fillingStaffLineXLength: CGFloat = 28.8,
noteHeadSize: CGSize = CGSize(width: 18, height: 15),
beamLineWidth: CGFloat = 5,
tupletFontSize: CGFloat = 20,
clefWidth: CGFloat = 36,
meterSymbolWidth: CGFloat = 25) {
self.staffHeight = staffHeight
self.staffLineWidth = staffLineWidth
self.stemWidth = stemWidth
self.widthPerUnitNoteLength = widthPerUnitNoteLength
self.barMarginRight = barMarginRight
self.minStemHeight = minStemHeight
self.maxBeamSlope = maxBeamSlope
self.dotMarginLeft = dotMarginLeft
self.fillingStaffLineWidth = fillingStaffLineWidth
self.fillingStaffLineXLength = fillingStaffLineXLength
self.noteHeadSize = noteHeadSize
self.beamLineWidth = beamLineWidth
self.tupletFontSize = tupletFontSize
self.clefWidth = clefWidth
self.meterSymbolWidth = meterSymbolWidth
}
public static let defaultLayout = SingleLineScoreLayout()
public var staffInterval: CGFloat {
return staffHeight / CGFloat(staffNum - 1)
}
} | 33.5 | 60 | 0.744279 |
16dbfa84a0f17c50b96fb7cc5409b3b15b024027 | 7,115 | //
// AddDeviceView.swift
// BleManageSwift
//
// Created by RND on 2020/9/23.
// Copyright © 2020 RND. All rights reserved.
//
import UIKit
import CoreBluetooth
class AddDeviceView: UIView {
let ALERTVIEW_HEIGHT = UIScreen.main.bounds.size.height / 1.8
let ALERTVIEW_WIDTH = UIScreen.main.bounds.size.width - 50
let HEIGHT = UIScreen.main.bounds.size.height
let WIDTH = UIScreen.main.bounds.size.width
let CELLIDENTIFITER = "ADDVIEWTABLEVIEWCELL"
var dataList = [BleModel]()
var periperals = [CBPeripheral]()
//按钮
var cancelBtn:UIButton?
var commonView:UIView?
//含有TableView
var tableView:UITableView?
private var refresh = UIRefreshControl()
init(title: String?, name: String?) {
let frame = CGRect(x: 0, y: 0,
width: UIScreen.main.bounds.size.width,
height: UIScreen.main.bounds.size.height)
super.init(frame:frame)
initView(title: title, name: name)
initData()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView(title:String?,name: String?) {
frame = UIScreen.main.bounds
commonView = UIView(frame: CGRect(x: 25, y: HEIGHT / 2 - ALERTVIEW_HEIGHT / 2, width: ALERTVIEW_WIDTH, height: ALERTVIEW_HEIGHT))
commonView!.backgroundColor = UIColor.white
commonView!.layer.cornerRadius = 8.0
commonView!.layer.masksToBounds = true
commonView!.isUserInteractionEnabled = true
addSubview(commonView!)
let setLb = UILabel.init(frame: CGRect(x: 15, y: 20, width: 180, height: 20))
setLb.textColor = UIColor.red
setLb.font = UIFont(name: "Helvetica-Bold", size: 16)
setLb.textAlignment = .center
commonView!.addSubview(setLb)
if (title != nil) {
setLb.text = title
}
cancelBtn = UIButton.init(frame: CGRect(x: ALERTVIEW_WIDTH-50, y: 10, width: 30, height: 30))
let image = UIImage(named: "close")
cancelBtn?.setImage(image, for: .normal)
commonView!.addSubview(cancelBtn!)
//refresh.tintColor = UIColor.gray
//refresh.attributedTitle = NSAttributedString(string: "Scanning...")
// refresh.addTarget(self, action: #selector(loadBle), for: .valueChanged)
tableView = UITableView.init(frame: CGRect(x: 10, y: 60, width: ALERTVIEW_WIDTH-20, height: ALERTVIEW_HEIGHT-80), style: .plain)
tableView!.delegate = self;
tableView!.dataSource = self;
commonView!.addSubview(tableView!)
//加刷新需要更换代码 不能写插入
//tableView!.refreshControl = refresh
cancelBtn!.addTarget(self, action: #selector(onCloseClick), for: .touchUpInside)
showView()
}
func initData() {
BleManage.shared.scan()
BleEventBus.onMainThread(self, name: "bleEvent"){
result in
//self.refresh.endRefreshing()
let model = result?.object as! BleModel
//可以自定义判断蓝牙为空的时候不能添加进去直接排除
if model.name != nil && model.name != ""{
self.changeTableView(model: model)
}
}
}
private func changeTableView(model:BleModel){
if !periperals.contains(model.peripheral!) {
let positon = IndexPath(row: dataList.count, section: 0)
var indexPaths = [IndexPath]()
indexPaths.append(positon)
periperals.append(model.peripheral!)
dataList.append(model)
tableView!.insertRows(at: indexPaths, with: .automatic)
}
}
/*@objc func loadBle(){
BleManager.shared.stopScan()
if dataList.count > 0 {
dataList.removeAll()
}
if periperals.count > 0 {
periperals.removeAll()
}
//开始扫描
BleManager.shared.startScan()
}*/
//点击按钮事件触发
@objc func onCloseClick(){
//停止扫描
BleManage.shared.stop()
hideView()
}
func showView() {
backgroundColor = UIColor.clear
UIApplication.shared.keyWindow?.addSubview(self)
let transform: CGAffineTransform = CGAffineTransform(scaleX: 1.0,y: 1.0)
commonView!.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
commonView!.alpha = 0
UIView.animate(withDuration: 0.3, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: .curveLinear, animations: {
self.backgroundColor = UIColor.black.withAlphaComponent(0.4)
self.commonView!.transform = transform
self.commonView!.alpha = 1
}) { finished in
}
}
func hideView() {
UIView.animate(withDuration: 0.5, animations: {
self.backgroundColor = UIColor.black.withAlphaComponent(0.0)
self.transform = self.transform.translatedBy(x: 0, y: self.ALERTVIEW_HEIGHT)
self.commonView!.alpha = 0
}) { isFinished in
self.commonView!.removeFromSuperview()
self.removeFromSuperview()
}
}
}
extension AddDeviceView:UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: CELLIDENTIFITER)
if cell == nil{
cell = UITableViewCell(style: .subtitle, reuseIdentifier: CELLIDENTIFITER)
cell!.accessoryType = .disclosureIndicator
}
if(dataList.count > 0){
let model = dataList[indexPath.row]
cell?.textLabel?.text = model.name
if Date().compare((model.date?.addingTimeInterval(30))!) == .orderedDescending {
cell?.detailTextLabel?.text = String(format: "RSSI:%@", model.rssi!)+" ---- "+"OFF-LINE"
}else{
cell?.detailTextLabel?.text = String(format: "RSSI:%@", model.rssi!)+" ---- "+"ON-LINE"
}
}
return cell!;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if dataList.count > 0 {
//停止蓝牙扫描
BleManage.shared.stop()
let model = dataList[indexPath.row]
//连接蓝牙
BleManage.shared.connect(model)
hideView()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
| 31.20614 | 146 | 0.576528 |
8f655424a7f4b42aded246896a049c2019a9b1eb | 957 | //
// XrayLoggerTests.swift
// XrayLoggerTests
//
// Created by Anton Kononenko on 7/9/20.
// Copyright © 2020 Applicaster. All rights reserved.
//
import XCTest
@testable import XrayLogger
class XrayLogger: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.342857 | 111 | 0.669801 |
4650387403fd36d3f1b899a1118d5cca2c69a163 | 6,689 | //
// BRBitID.swift
// BreadWallet
//
// Created by Samuel Sutch on 6/17/16.
// Copyright © 2016 breadwallet LLC. 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.
import Foundation
import Security
@objc public class BRBitID : NSObject {
static let SCHEME = "bitid"
static let PARAM_NONCE = "x"
static let PARAM_UNSECURE = "u"
static let USER_DEFAULTS_NONCE_KEY = "brbitid_nonces"
static let DEFAULT_INDEX: UInt32 = 42
class public func isBitIDURL(url: NSURL!) -> Bool {
return url.scheme == SCHEME
}
public static let BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n".dataUsingEncoding(NSUTF8StringEncoding)!
public class func formatMessageForBitcoinSigning(message: String) -> NSData {
let data = NSMutableData()
data.appendUInt8(UInt8(BITCOIN_SIGNED_MESSAGE_HEADER.length))
data.appendData(BITCOIN_SIGNED_MESSAGE_HEADER)
let msgBytes = message.dataUsingEncoding(NSUTF8StringEncoding)!
data.appendVarInt(UInt64(msgBytes.length))
data.appendData(msgBytes)
return data
}
// sign a message with a key and return a base64 representation
public class func signMessage(message: String, usingKey key: BRKey) -> String {
let signingData = formatMessageForBitcoinSigning(message)
let signature = key.compactSign(signingData.SHA256_2())!
return NSString(data: signature.base64EncodedDataWithOptions([]), encoding: NSUTF8StringEncoding)! as String
}
public let url: NSURL
public var siteName: String {
return "\(url.host!)\(url.path!)"
}
public init(url: NSURL!) {
self.url = url
}
public func newNonce() -> String {
let defs = NSUserDefaults.standardUserDefaults()
let nonceKey = "\(url.host!)/\(url.path!)"
var allNonces = [String: [String]]()
var specificNonces = [String]()
// load previous nonces. we save all nonces generated for each service
// so they are not used twice from the same device
if let existingNonces = defs.objectForKey(BRBitID.USER_DEFAULTS_NONCE_KEY) {
allNonces = existingNonces as! [String: [String]]
}
if let existingSpecificNonces = allNonces[nonceKey] {
specificNonces = existingSpecificNonces
}
// generate a completely new nonce
var nonce: String
repeat {
nonce = "\(Int(NSDate().timeIntervalSince1970))"
} while (specificNonces.contains(nonce))
// save out the nonce list
specificNonces.append(nonce)
allNonces[nonceKey] = specificNonces
defs.setObject(allNonces, forKey: BRBitID.USER_DEFAULTS_NONCE_KEY)
return nonce
}
public func runCallback(completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
guard let manager = BRWalletManager.sharedInstance() else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("No wallet", comment: "")]))
}
return
}
autoreleasepool {
guard let seed = manager.seedWithPrompt("", forAmount: 0) else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("Could not unlock", comment: "")]))
}
return
}
let seq = BRBIP32Sequence()
var scheme = "https"
var nonce: String
guard let query = url.query?.parseQueryString() else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("Malformed URI", comment: "")]))
}
return
}
if let u = query[BRBitID.PARAM_UNSECURE] where u.count == 1 && u[0] == "1" {
scheme = "http"
}
if let x = query[BRBitID.PARAM_NONCE] where x.count == 1 {
nonce = x[0] // service is providing a nonce
} else {
nonce = newNonce() // we are generating our own nonce
}
let uri = "\(scheme)://\(url.host!)\(url.path!)"
// build a payload consisting of the signature, address and signed uri
let priv = BRKey(privateKey: seq.bitIdPrivateKey(BRBitID.DEFAULT_INDEX, forURI: uri, fromSeed: seed))!
let uriWithNonce = "bitid://\(url.host!)\(url.path!)?x=\(nonce)"
let signature = BRBitID.signMessage(uriWithNonce, usingKey: priv)
let payload: [String: String] = [
"address": priv.address!,
"signature": signature,
"uri": uriWithNonce
]
let json = try! NSJSONSerialization.dataWithJSONObject(payload, options: [])
// send off said payload
let req = NSMutableURLRequest(URL: NSURL(string: "\(uri)?x=\(nonce)")!)
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.HTTPMethod = "POST"
req.HTTPBody = json
NSURLSession.sharedSession().dataTaskWithRequest(req, completionHandler: completionHandler).resume()
}
}
} | 43.718954 | 122 | 0.624907 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.