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
|
---|---|---|---|---|---|
0af9292acc45b89327166b2bee628dba56ba49bf | 6,178 | // Copyright © 2017 JABT. All rights reserved.
import Foundation
import AppKit
public class PanGestureRecognizer: NSObject, GestureRecognizer {
public var gestureUpdated: ((GestureRecognizer) -> Void)?
private(set) public var state = GestureState.possible
private(set) public var lastLocation: CGPoint?
private(set) public var delta = CGVector.zero
private var timeOfLastUpdate = Date()
private var positionForTouch = [Touch: CGPoint]()
private var cumulativeDelta = CGVector.zero
private var recognizedThreshold = Constants.defaultRecognizedThreshold
private struct Constants {
static let defaultRecognizedThreshold: CGFloat = 20
static let minimumDeltaUpdateThreshold = 4.0
static let gestureDelay = 0.1
}
// MARK: Init
public override init() {
super.init()
let miliseconds = Int(round(GestureManager.refreshRate * 1000))
self.momentumTimer = DispatchTimer(interval: .milliseconds(miliseconds), handler: { [weak self] in
self?.updateMomentum()
})
}
public convenience init(recognizedThreshold: CGFloat = 20, friction: FrictionLevel = .medium) {
self.init()
self.recognizedThreshold = recognizedThreshold
self.panFrictionLevel = friction
}
// MARK: API
public func start(_ touch: Touch, with properties: TouchProperties) {
switch state {
case .momentum, .failed:
reset()
fallthrough
case .possible:
momentumTimer.suspend()
cumulativeDelta = .zero
lastLocation = properties.cog
state = .began
gestureUpdated?(self)
timeOfLastUpdate = Date()
fallthrough
case .recognized, .began:
momentumTimer.suspend()
positionForTouch[touch] = touch.position
default:
return
}
}
public func move(_ touch: Touch, with properties: TouchProperties) {
guard state != .failed, let lastPositionOfTouch = positionForTouch[touch] else {
return
}
switch state {
case .began where shouldStart(with: touch, from: lastPositionOfTouch):
state = .recognized
positionForTouch[touch] = touch.position
case .recognized:
positionForTouch[touch] = touch.position
recognizePanMove(with: touch, lastPosition: lastPositionOfTouch)
if shouldUpdate(for: timeOfLastUpdate) {
updateForMove(with: properties)
}
default:
return
}
}
/// Determines if the pan gesture should become recognized
public func shouldStart(with touch: Touch, from startPosition: CGPoint) -> Bool {
let dx = Float(touch.position.x - startPosition.x)
let dy = Float(touch.position.y - startPosition.y)
return CGFloat(hypotf(dx, dy).magnitude) > recognizedThreshold
}
public func end(_ touch: Touch, with properties: TouchProperties) {
positionForTouch.removeValue(forKey: touch)
guard state != .failed, properties.touchCount.isZero else {
return
}
let shouldStartMomentum = state == .recognized
state = .ended
gestureUpdated?(self)
if shouldStartMomentum, abs(timeOfLastUpdate.timeIntervalSinceNow) < Constants.gestureDelay {
beginMomentum()
} else {
reset()
gestureUpdated?(self)
}
}
public func reset() {
state = .possible
positionForTouch.removeAll()
lastLocation = nil
delta = .zero
}
public func invalidate() {
momentumTimer.suspend()
state = .failed
gestureUpdated?(self)
}
// MARK: Helpers
/// Sets gesture properties during a move event and calls `gestureUpdated` callback
private func updateForMove(with properties: TouchProperties) {
delta = cumulativeDelta
panMomentumDelta = delta
cumulativeDelta = .zero
gestureUpdated?(self)
timeOfLastUpdate = Date()
}
/// Updates pan properties during a move event when in the recognized state
private func recognizePanMove(with touch: Touch, lastPosition: CGPoint) {
guard let currentLocation = lastLocation else {
return
}
positionForTouch[touch] = touch.position
let offset = touch.position - lastPosition
delta = offset.asVector / CGFloat(positionForTouch.keys.count)
cumulativeDelta += delta
lastLocation = currentLocation + delta
}
private func shouldUpdateForPan() -> Bool {
return cumulativeDelta.magnitude > Constants.minimumDeltaUpdateThreshold
}
/// Returns true if enough time has passed to send send the next update
private func shouldUpdate(for time: Date) -> Bool {
return abs(time.timeIntervalSinceNow) > GestureManager.refreshRate
}
// MARK: Momentum
private var momentumTimer: DispatchTimer!
private var panFrictionFactor = Momentum.panInitialFrictionFactor
private var panFrictionLevel = FrictionLevel.medium
private var panMomentumDelta = CGVector.zero
private struct Momentum {
static let panInitialFrictionFactor = 1.04
static let panThresholdMomentumDelta = 2.0
}
private func beginMomentum() {
panFrictionFactor = Momentum.panInitialFrictionFactor
delta = panMomentumDelta
state = .momentum
gestureUpdated?(self)
momentumTimer.resume()
}
private func updateMomentum() {
updatePanMomentum()
if delta == .zero {
endMomentum()
return
}
gestureUpdated?(self)
}
private func updatePanMomentum() {
if delta.magnitude < Momentum.panThresholdMomentumDelta {
delta = .zero
} else {
panFrictionFactor += panFrictionLevel.scale
delta /= panFrictionFactor
}
}
private func endMomentum() {
momentumTimer.suspend()
reset()
gestureUpdated?(self)
}
}
| 29.990291 | 106 | 0.633538 |
d6a68ead9fbb340fef47c7e8d35f8fc34c93057b | 2,306 | import Foundation
import Tools
final class Day07Solver: DaySolver {
let dayNumber: Int = 7
private var input: Input!
private struct Input {
let program: [Int]
}
func solvePart1() -> Any {
let intcode = IntcodeProcessor()
let permutations = [0, 1, 2, 3, 4].permutations
var maxThrusterSignal = 0
for permutation in permutations {
var currentInput = 0
for phaseSetting in permutation {
currentInput = intcode.executeProgram(input.program, input: [phaseSetting, currentInput]).output.last!
}
maxThrusterSignal = max(maxThrusterSignal, currentInput)
}
return maxThrusterSignal
}
func solvePart2() -> Any {
let permutations = [5, 6, 7, 8, 9].permutations
var maxThrusterSignal = 0
for permutation in permutations {
let amplifiers: [IntcodeProcessor] = [
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor()
]
var currentInput = 0
var iteration = 0
iterationLoop: while true {
for (amplifierIndex, phaseSetting) in permutation.enumerated() {
if iteration == 0 {
guard let newCurrentInput = amplifiers[amplifierIndex].executeProgramTillOutput(input.program, input: [phaseSetting, currentInput]) else {
fatalError()
}
currentInput = newCurrentInput
} else {
if let newCurrentInput = amplifiers[amplifierIndex].continueProgramTillOutput(input: [currentInput]) {
currentInput = newCurrentInput
} else {
break iterationLoop
}
}
maxThrusterSignal = max(maxThrusterSignal, currentInput)
}
iteration += 1
}
}
return maxThrusterSignal
}
func parseInput(rawString: String) {
input = .init(program: rawString.parseCommaSeparatedInts())
}
}
| 28.469136 | 162 | 0.529488 |
14a73376484b73c4d741a058ee60c078cbd97448 | 5,237 | //
// Models.swift
// SideMenu
//
// Created by Jon Kent on 7/3/19.
//
import Foundation
internal protocol MenuModel: TransitionModel {
/// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true.
var allowPushOfSameClassTwice: Bool { get }
/// Forces menus to always animate when appearing or disappearing, regardless of a pushed view controller's animation.
var alwaysAnimate: Bool { get }
/**
The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController.
- Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell.
*/
var blurEffectStyle: UIBlurEffect.Style? { get }
/// Animation curve of the remaining animation when the menu is partially dismissed with gestures. Default is .easeIn.
var completionCurve: UIView.AnimationCurve { get }
/// Automatically dismisses the menu when another view is presented from it.
var dismissOnPresent: Bool { get }
/// Automatically dismisses the menu when another view controller is pushed from it.
var dismissOnPush: Bool { get }
/// Automatically dismisses the menu when the screen is rotated.
var dismissOnRotation: Bool { get }
/// Automatically dismisses the menu when app goes to the background.
var dismissWhenBackgrounded: Bool { get }
/// Enable or disable a swipe gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true.
var enableSwipeToDismissGesture: Bool { get }
/// Enable or disable a tap gesture that dismisses the menu. Will not be triggered when `presentingViewControllerUserInteractionEnabled` is set to true. Default is true.
var enableTapToDismissGesture: Bool { get }
/**
The push style of the menu.
There are six modes in MenuPushStyle:
- defaultBehavior: The view controller is pushed onto the stack.
- popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack.
- preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController.
- preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden.
- replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved..
- subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu.
*/
var pushStyle: SideMenuPushStyle { get }
}
internal protocol TransitionModel: PresentationModel {
/// The animation options when a menu is displayed. Ignored when displayed with a gesture.
var animationOptions: UIView.AnimationOptions { get }
/// Duration of the remaining animation when the menu is partially dismissed with gestures. Default is 0.35 seconds.
var completeGestureDuration: Double { get }
/// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds.
var dismissDuration: Double { get }
/// The animation initial spring velocity when a menu is displayed. Ignored when displayed with a gesture.
var initialSpringVelocity: CGFloat { get }
/// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds.
var presentDuration: Double { get }
/// The animation spring damping when a menu is displayed. Ignored when displayed with a gesture.
var usingSpringWithDamping: CGFloat { get }
}
internal protocol PresentationModel {
/// Draws `presentStyle.backgroundColor` behind the status bar. Default is 1.
var statusBarEndAlpha: CGFloat { get }
/// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. `presentingViewControllerUseSnapshot` must also set to false. Default is false.
var presentingViewControllerUserInteractionEnabled: Bool { get }
/// Use a snapshot for the presenting vierw controller while the menu is displayed. Useful when layout changes occur during transitions. Not recommended for apps that support rotation. Default is false.
var presentingViewControllerUseSnapshot: Bool { get }
/// The presentation style of the menu.
var presentationStyle: SideMenuPresentationStyle { get }
/// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is zero.
var menuWidth: CGFloat { get }
}
| 68.907895 | 310 | 0.758068 |
91643243c60b535c8d4ecfd078c98cf99444e3ca | 6,228 | import AVFoundation
import Foundation
class FLTResourceLoader: NSObject {
static let loaderQueue = DispatchQueue(label: "huuk.resourceLoader.queue", qos: .userInteractive)
private var requests: [AVAssetResourceLoadingRequest: FLTResourceLoaderRequest] = [:]
private let originalURL: URL
var pendingReceviveDataModels = [FLTPendingReceviveDataModel]()
var cacheKey: String {
return FLTResourceLoader.createCacheKeyFrom(url: originalURL.absoluteString)
}
init(asset: FLTCachingAVURLAsset) {
self.originalURL = asset.originalURL
super.init()
}
deinit {
self.requests.forEach { (request) in
request.value.cancel()
}
}
static func createCacheKeyFrom(url: String) -> String {
return url.data(using: .utf8)!.base64EncodedString()
}
}
extension FLTResourceLoader: AVAssetResourceLoaderDelegate {
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
let type = FLTResourceLoader.resourceLoaderRequestType(loadingRequest)
let assetDataManager = FLTPINCacheAssetDataManager(cacheKey: self.cacheKey)
if let assetData = assetDataManager.retrieveAssetData() {
if type == .contentInformation {
loadingRequest.contentInformationRequest?.contentLength = assetData.contentInformation.contentLength
loadingRequest.contentInformationRequest?.contentType = assetData.contentInformation.contentType
loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = assetData.contentInformation.isByteRangeAccessSupported
loadingRequest.finishLoading()
return true
} else {
let range = FLTResourceLoader.resourceLoaderRequestRange(type, loadingRequest)
if assetData.mediaData.count > 0 {
let end: Int64
switch range.end {
case .requestTo(let rangeEnd):
end = rangeEnd
case .requestToEnd:
end = assetData.contentInformation.contentLength
}
if assetData.mediaData.count >= end {
let subData = assetData.mediaData.subdata(in: Int(range.start)..<Int(end))
loadingRequest.dataRequest?.respond(with: subData)
loadingRequest.finishLoading()
return true
} else if range.start <= assetData.mediaData.count {
// has cache data...but not enough
let subEnd = (assetData.mediaData.count > end) ? Int((end)) : (assetData.mediaData.count)
let subData = assetData.mediaData.subdata(in: Int(range.start)..<subEnd)
loadingRequest.dataRequest?.respond(with: subData)
}
}
}
}
let range = FLTResourceLoader.resourceLoaderRequestRange(type, loadingRequest)
let resourceLoaderRequest = FLTResourceLoaderRequest(originalURL: self.originalURL, type: type, loaderQueue: FLTResourceLoader.loaderQueue, assetDataManager: assetDataManager)
resourceLoaderRequest.delegate = self
self.requests[loadingRequest]?.cancel()
self.requests[loadingRequest] = resourceLoaderRequest
resourceLoaderRequest.start(requestRange: range)
return true
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
guard let resourceLoaderRequest = self.requests[loadingRequest] else {
return
}
resourceLoaderRequest.cancel()
requests.removeValue(forKey: loadingRequest)
}
}
extension FLTResourceLoader: FLTResourceLoaderRequestDelegate {
func contentInformationDidComplete(_ resourceLoaderRequest: FLTResourceLoaderRequest, _ result: Result<FLTAssetDataContentInformation, Error>) {
guard let loadingRequest = self.requests.first(where: { $0.value == resourceLoaderRequest })?.key else {
return
}
switch result {
case .success(let contentInformation):
loadingRequest.contentInformationRequest?.contentType = contentInformation.contentType
loadingRequest.contentInformationRequest?.contentLength = contentInformation.contentLength
loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = contentInformation.isByteRangeAccessSupported
loadingRequest.finishLoading()
case .failure(let error):
loadingRequest.finishLoading(with: error)
}
}
func dataRequestDidReceive(_ resourceLoaderRequest: FLTResourceLoaderRequest, _ data: Data) {
guard let loadingRequest = self.requests.first(where: { $0.value == resourceLoaderRequest })?.key else {
return
}
loadingRequest.dataRequest?.respond(with: data)
}
func dataRequestDidComplete(_ resourceLoaderRequest: FLTResourceLoaderRequest, _ error: Error?, _ downloadedData: Data) {
guard let loadingRequest = self.requests.first(where: { $0.value == resourceLoaderRequest })?.key else {
return
}
loadingRequest.finishLoading(with: error)
requests.removeValue(forKey: loadingRequest)
}
}
extension FLTResourceLoader {
static func resourceLoaderRequestType(_ loadingRequest: AVAssetResourceLoadingRequest) -> FLTResourceLoaderRequest.RequestType {
if let _ = loadingRequest.contentInformationRequest {
return .contentInformation
} else {
return .dataRequest
}
}
static func resourceLoaderRequestRange(_ type: FLTResourceLoaderRequest.RequestType, _ loadingRequest: AVAssetResourceLoadingRequest) -> FLTResourceLoaderRequest.RequestRange {
if type == .contentInformation {
return FLTResourceLoaderRequest.RequestRange(start: 0, end: .requestTo(1))
} else {
if loadingRequest.dataRequest?.requestsAllDataToEndOfResource == true {
let lowerBound = loadingRequest.dataRequest?.currentOffset ?? 0
return FLTResourceLoaderRequest.RequestRange(start: lowerBound, end: .requestToEnd)
} else {
let lowerBound = loadingRequest.dataRequest?.currentOffset ?? 0
let length = Int64(loadingRequest.dataRequest?.requestedLength ?? 1)
let upperBound = lowerBound + length
return FLTResourceLoaderRequest.RequestRange(start: lowerBound, end: .requestTo(upperBound))
}
}
}
}
| 40.705882 | 179 | 0.731535 |
5d2f2864a499eb1b6e78f7820aab9d8396f6bdfa | 831 | /*
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
func convertBST(_ root: TreeNode?) -> TreeNode? {
}
}
| 23.083333 | 193 | 0.578821 |
79711bf420ec8849a5500d452603b46009e64931 | 4,900 | //
// LineEndingTests.swift
// Tests
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2015-11-09.
//
// ---------------------------------------------------------------------------
//
// © 2015-2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import CotEditor
final class LineEndingTests: XCTestCase {
func testLineEnding() {
XCTAssertEqual(LineEnding.lf.rawValue, "\n")
XCTAssertEqual(LineEnding.crlf.rawValue, "\r\n")
XCTAssertEqual(LineEnding.paragraphSeparator.rawValue, "\u{2029}")
}
func testName() {
XCTAssertEqual(LineEnding.lf.name, "LF")
XCTAssertEqual(LineEnding.crlf.name, "CRLF")
XCTAssertEqual(LineEnding.paragraphSeparator.name, "PS")
}
func testDetection() {
XCTAssertNil("".detectedLineEnding)
XCTAssertNil("a".detectedLineEnding)
XCTAssertEqual("\n".detectedLineEnding, .lf)
XCTAssertEqual("\r".detectedLineEnding, .cr)
XCTAssertEqual("\r\n".detectedLineEnding, .crlf)
XCTAssertEqual("\u{85}".detectedLineEnding, .nel)
XCTAssertEqual("abc\u{2029}def".detectedLineEnding, .paragraphSeparator)
XCTAssertEqual("\rfoo\r\nbar\nbuz\u{2029}moin\r\n".detectedLineEnding, .crlf) // most used new line must be detected
let bom = "\u{feff}"
let string = "\(bom)\r\n"
XCTAssertEqual(string.count, 2)
XCTAssertEqual(string.immutable.count, 1)
XCTAssertEqual(string.detectedLineEnding, .crlf)
}
func testCount() {
XCTAssertEqual("".countExceptLineEnding, 0)
XCTAssertEqual("foo\nbar".countExceptLineEnding, 6)
XCTAssertEqual("\u{feff}".countExceptLineEnding, 1)
XCTAssertEqual("\u{feff}a".countExceptLineEnding, 2)
}
func testReplacement() {
XCTAssertEqual("foo\r\nbar\n".replacingLineEndings(with: .cr), "foo\rbar\r")
XCTAssertEqual("foo\r\nbar\n".replacingLineEndings([.lf], with: .cr), "foo\r\nbar\r")
}
func testRangeConversion() {
let lfToCRLFRange = "a\nb\nc".convert(range: NSRange(location: 2, length: 2), from: .lf, to: .crlf)
XCTAssertEqual(lfToCRLFRange, NSRange(location: 3, length: 3))
let crlfToLFRange = "a\r\nb\r\nc".convert(range: NSRange(location: 3, length: 3), from: .crlf, to: .lf)
XCTAssertEqual(crlfToLFRange, NSRange(location: 2, length: 2))
}
func testRangesConversion() {
let lfString = "\na\nb\nc\n"
let crlfString = "\r\na\r\nb\r\nc\r\n"
let lfRanges = [NSRange(location: 0, length: 0),
NSRange(location: 0, length: 1),
NSRange(location: 0, length: 7),
NSRange(location: 1, length: 0),
NSRange(location: 1, length: 1),
NSRange(location: 6, length: 1),
NSRange(location: 7, length: 0)]
let crlfRanges = lfString.convert(ranges: lfRanges, from: .lf, to: .crlf)
XCTAssertEqual(crlfRanges[0], NSRange(location: 0, length: 0))
XCTAssertEqual(crlfRanges[1], NSRange(location: 0, length: 2))
XCTAssertEqual(crlfRanges[2], NSRange(location: 0, length: 11))
XCTAssertEqual(crlfRanges[3], NSRange(location: 2, length: 0))
XCTAssertEqual(crlfRanges[4], NSRange(location: 2, length: 1))
XCTAssertEqual(crlfRanges[5], NSRange(location: 9, length: 2))
XCTAssertEqual(crlfRanges[6], NSRange(location: 11, length: 0))
let convertedLFRanges = crlfString.convert(ranges: crlfRanges, from: .crlf, to: .lf)
for (convertedLFRange, lfRange) in zip(convertedLFRanges, lfRanges) {
XCTAssertEqual(convertedLFRange, lfRange)
}
let fakeLFRanges = lfString.convert(ranges: crlfRanges, from: .crlf, to: .lf)
for (fakeLFRange, lfRange) in zip(fakeLFRanges, lfRanges) {
XCTAssertEqual(fakeLFRange, lfRange)
}
let fakeCRLFRanges = crlfString.convert(ranges: lfRanges, from: .lf, to: .crlf)
for (fakeCURLFRange, crlfRange) in zip(fakeCRLFRanges, crlfRanges) {
XCTAssertEqual(fakeCURLFRange, crlfRange)
}
}
}
| 37.40458 | 125 | 0.612449 |
bf499e410a5023402d5bb32e887539420703a45d | 1,628 | /*
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[2],[1]]
Explanation:
1. Removing the leaves [4,5,3] would result in this tree:
1
/
2
2. Now removing the leaf [2] would result in this tree:
1
3. Now removing the leaf [1] would result in the empty tree:
[]
Primary idea: Use recursion, get to the leaves and mark as level one and use a dictionary to memory the nodes in the same level, then bottom up
Time Complexity: O(n), Space Complexity: O(n)
*/
// public class TreeNode {
// public var val: Int
// public var left: TreeNode?
// public var right: TreeNode?
// public init(_ val: Int) {
// self.val = val
// self.left = nil
// self.right = nil
// }
// }
class Solution {
private func order(_ root: TreeNode?, _ dict: inout [Int: [Int]]) -> Int {
guard let root = root else {
return 0
}
let left = order(root.left, &dict)
let right = order(root.right, &dict)
let level = max(left, right) + 1
dict[level, default: []] += [root.val]
return level
}
func findLeaves(_ root: TreeNode?) -> [[Int]] {
var dict = [Int: [Int]]()
_ = order(root, &dict)
let cnt = dict.keys.count
var res = [[Int]]()
for i in 1..<cnt+1 {
if let leaves = dict[i] {
res.append(leaves)
}
}
return res
}
}
| 19.380952 | 144 | 0.541155 |
4a81a074c7feb76c5ff624522b4fa2429f8e7c8e | 1,352 | //
// CredentialsManager.swift
// Safety First
//
// Created by Maxime Britto on 05/09/2017.
// Copyright © 2017 Maxime Britto. All rights reserved.
//
import Foundation
import RealmSwift
class CredentialsManager {
private let _realm:Realm
private let _credentialList:Results<Credentials>
init() {
_realm = try! Realm()
_credentialList = _realm.objects(Credentials.self)
}
func addCredentials(title:String, login:String, password:String, url:String) -> Credentials {
let newCredential = Credentials()
newCredential.title = title
newCredential.login = login
newCredential.password = password
newCredential.url = url
try? _realm.write {
_realm.add(newCredential)
}
return newCredential
}
func getCredentialCount() -> Int {
return _credentialList.count
}
func getCredential(atIndex index:Int) -> Credentials? {
guard index >= 0 && index < getCredentialCount() else {
return nil
}
return _credentialList[index]
}
func deleteCredential(atIndex index:Int) {
if let credToDelete = getCredential(atIndex: index) {
try? _realm.write {
_realm.delete(credToDelete)
}
}
}
}
| 22.915254 | 97 | 0.605769 |
08755e040d391adc78de9a8eaa7a6b5a65b3f4c4 | 888 | //
// TippyTests.swift
// TippyTests
//
// Created by Sandeep on 12/19/19.
// Copyright © 2019 Sandeep . All rights reserved.
//
import XCTest
@testable import Tippy
class TippyTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.371429 | 111 | 0.647523 |
efff5f2a47dc11bf70cbf3d10e54a8c121b19ef2 | 761 | //
// SearchProvider.swift
// Unoriginal
//
// Created by Reece Como on 11/8/18.
// Copyright © 2018 Hubrio. All rights reserved.
//
import RxSwift
///
/// Search provider
///
final class SearchProvider {
// MARK: - Properties
/// GitHub
private let githubProvider = GitHubAPIProvider()
// MARK: - Methods
/// Search repositories
func searchRepositories(query: String, language: String? = nil) -> Observable<[Repo]> {
let githubResults = githubProvider.searchRepositories(query: query, language: language)
.map { repos -> [Repo] in
return repos as [Repo]
}
.asObservable()
return Observable<[Repo]>.merge(githubResults)
}
}
| 21.138889 | 95 | 0.591327 |
29fd0ce574f67f273fef5f08a3c7d288a20a8415 | 962 | //
// tippyTests.swift
// tippyTests
//
// Created by Etnuh on 3/8/17.
// Copyright © 2017 Rainman Technologies. All rights reserved.
//
import XCTest
@testable import tippy
class tippyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.629938 |
8fc2243dab50e99a6bea7932c8b4600984696d43 | 3,186 | //
// WebSocketManger.swift
// Douyin
//
// Created by Qiao Shi on 2018/8/3.
// Copyright © 2018年 Qiao Shi. All rights reserved.
//
import Foundation
import Starscream
let WebSocketDidReceiveMessageNotification:String = "WebSocketDidReceiveMessageNotification"
let MaxReConnectCount = 5
class WebSocketManger:NSObject {
var reOpenCount:Int = 0
let websocket = { () -> WebSocket in
var components = URLComponents.init(url: URL.init(string: BaseUrl + "/groupchat")!, resolvingAgainstBaseURL: false)
components?.scheme = "ws"
let url = components?.url
var request = URLRequest.init(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)
request.addValue(UDID, forHTTPHeaderField: "udid")
let websocket = WebSocket.init(request: request)
return websocket
}()
private static let instance = { () -> WebSocketManger in
return WebSocketManger.init()
}()
private override init() {
super.init()
websocket.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(onNetworkStatusChange(notification:)), name: Notification.Name(rawValue: NetworkStatesChangeNotification), object: nil)
}
class func shared() -> WebSocketManger {
return instance
}
func connect() {
if(websocket.isConnected) {
disConnect()
}
websocket.connect()
}
func disConnect() {
websocket.disconnect()
}
func reConnect() {
if(websocket.isConnected) {
disConnect()
}
connect()
}
func sendMessage(msg:String) {
if(websocket.isConnected) {
websocket.write(string: msg)
}
}
@objc func onNetworkStatusChange(notification:NSNotification) {
if(!NetworkManager.isNotReachableStatus(status: notification.object) && !(websocket.isConnected)) {
reConnect()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension WebSocketManger:WebSocketDelegate {
func websocketDidConnect(socket: WebSocketClient) {
self.reOpenCount = 0
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if(NetworkManager.networkStatus() != .notReachable) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0 , execute: {
if(self.websocket.isConnected) {
self.reOpenCount = 0
return
}
if(self.reOpenCount >= MaxReConnectCount) {
self.reOpenCount = 0
return
}
self.reConnect()
self.reOpenCount += 1
})
}
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WebSocketDidReceiveMessageNotification), object: text)
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
}
}
| 28.963636 | 192 | 0.613936 |
e639e92c5f320ddc7958cb6ad0f046fe66c35b12 | 191 |
import Foundation
let arr = [1,2,3]
let doubled = arr.map{
$0 * 2
}
print(doubled)
// 输出:
// [2,4,6]
let num: Int? = 3
let result = num.map {
$0 * 2
}
result
// result 为 {Some 6} | 10.052632 | 22 | 0.549738 |
f5912a427f71b14f4753865d4f038cecb9325a70 | 26,417 | //
// MachineDocument.swift
// Clock Signal
//
// Created by Thomas Harte on 04/01/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
import AudioToolbox
import Cocoa
import QuartzCore
class MachineDocument:
NSDocument,
NSWindowDelegate,
CSMachineDelegate,
CSOpenGLViewDelegate,
CSOpenGLViewResponderDelegate,
CSAudioQueueDelegate,
CSROMReciverViewDelegate
{
// MARK: - Mutual Exclusion.
/// Ensures exclusive access between calls to self.machine.run and close().
private let actionLock = NSLock()
/// Ensures exclusive access between calls to machine.updateView and machine.drawView, and close().
private let drawLock = NSLock()
// MARK: - Machine details.
/// A description of the machine this document should represent once fully set up.
private var machineDescription: CSStaticAnalyser?
/// The active machine, following its successful creation.
private var machine: CSMachine!
/// @returns the appropriate window content aspect ratio for this @c self.machine.
private func aspectRatio() -> NSSize {
return NSSize(width: 4.0, height: 3.0)
}
/// The output audio queue, if any.
private var audioQueue: CSAudioQueue!
// MARK: - Main NIB connections.
/// The OpenGL view to receive this machine's display.
@IBOutlet weak var openGLView: CSOpenGLView!
/// The options panel, if any.
@IBOutlet var optionsPanel: MachinePanel!
/// An action to display the options panel, if there is one.
@IBAction func showOptions(_ sender: AnyObject!) {
optionsPanel?.setIsVisible(true)
}
/// The activity panel, if one is deemed appropriate.
@IBOutlet var activityPanel: NSPanel!
/// An action to display the activity panel, if there is one.
@IBAction func showActivity(_ sender: AnyObject!) {
activityPanel.setIsVisible(true)
}
/// The volume view.
@IBOutlet var volumeView: NSBox!
@IBOutlet var volumeSlider: NSSlider!
// MARK: - NSDocument Overrides and NSWindowDelegate methods.
/// Links this class to the MachineDocument NIB.
override var windowNibName: NSNib.Name? {
return "MachineDocument"
}
convenience init(type typeName: String) throws {
self.init()
self.fileType = typeName
}
override func read(from url: URL, ofType typeName: String) throws {
if let analyser = CSStaticAnalyser(fileAt: url) {
self.displayName = analyser.displayName
self.configureAs(analyser)
} else {
throw NSError(domain: "MachineDocument", code: -1, userInfo: nil)
}
}
override func close() {
machine?.stop()
activityPanel?.setIsVisible(false)
activityPanel = nil
optionsPanel?.setIsVisible(false)
optionsPanel = nil
actionLock.lock()
drawLock.lock()
machine = nil
openGLView.delegate = nil
openGLView.invalidate()
actionLock.unlock()
drawLock.unlock()
super.close()
}
override func data(ofType typeName: String) throws -> Data {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override func windowControllerDidLoadNib(_ aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
aController.window?.contentAspectRatio = self.aspectRatio()
volumeSlider.floatValue = userDefaultsVolume()
}
private var missingROMs: [CSMissingROM] = []
func configureAs(_ analysis: CSStaticAnalyser) {
self.machineDescription = analysis
let missingROMs = NSMutableArray()
if let machine = CSMachine(analyser: analysis, missingROMs: missingROMs) {
self.machine = machine
setupMachineOutput()
setupActivityDisplay()
machine.setVolume(userDefaultsVolume())
} else {
// Store the selected machine and list of missing ROMs, and
// show the missing ROMs dialogue.
self.missingROMs = []
for untypedMissingROM in missingROMs {
self.missingROMs.append(untypedMissingROM as! CSMissingROM)
}
requestRoms()
}
}
enum InteractionMode {
case notStarted, showingMachinePicker, showingROMRequester, showingMachine
}
private var interactionMode: InteractionMode = .notStarted
// Attempting to show a sheet before the window is visible (such as when the NIB is loaded) results in
// a sheet mysteriously floating on its own. For now, use windowDidUpdate as a proxy to know that the window
// is visible, though it's a little premature.
func windowDidUpdate(_ notification: Notification) {
// Grab the regular window title, if it's not already stored.
if self.unadornedWindowTitle.count == 0 {
self.unadornedWindowTitle = self.windowControllers[0].window!.title
}
// If an interaction mode is not yet in effect, pick the proper one and display the relevant thing.
if self.interactionMode == .notStarted {
// If a full machine exists, just continue showing it.
if self.machine != nil {
self.interactionMode = .showingMachine
setupMachineOutput()
return
}
// If a machine has been picked but is not showing, there must be ROMs missing.
if self.machineDescription != nil {
self.interactionMode = .showingROMRequester
requestRoms()
return
}
// If a machine hasn't even been picked yet, show the machine picker.
self.interactionMode = .showingMachinePicker
Bundle.main.loadNibNamed("MachinePicker", owner: self, topLevelObjects: nil)
self.machinePicker?.establishStoredOptions()
self.windowControllers[0].window?.beginSheet(self.machinePickerPanel!, completionHandler: nil)
}
}
// MARK: - Connections Between Machine and the Outside World
private func setupMachineOutput() {
if let machine = self.machine, let openGLView = self.openGLView, machine.view != openGLView {
// Establish the output aspect ratio and audio.
let aspectRatio = self.aspectRatio()
machine.setView(openGLView, aspectRatio: Float(aspectRatio.width / aspectRatio.height))
// Attach an options panel if one is available.
if let optionsPanelNibName = self.machineDescription?.optionsPanelNibName {
Bundle.main.loadNibNamed(optionsPanelNibName, owner: self, topLevelObjects: nil)
self.optionsPanel.machine = machine
self.optionsPanel?.establishStoredOptions()
showOptions(self)
}
machine.delegate = self
// Callbacks from the OpenGL may come on a different thread, immediately following the .delegate set;
// hence the full setup of the best-effort updater prior to setting self as a delegate.
openGLView.delegate = self
openGLView.responderDelegate = self
// If this machine has a mouse, enable mouse capture; also indicate whether usurption
// of the command key is desired.
openGLView.shouldCaptureMouse = machine.hasMouse
openGLView.shouldUsurpCommand = machine.shouldUsurpCommand
setupAudioQueueClockRate()
// Bring OpenGL view-holding window on top of the options panel and show the content.
openGLView.isHidden = false
openGLView.window!.makeKeyAndOrderFront(self)
openGLView.window!.makeFirstResponder(openGLView)
// Start forwarding best-effort updates.
machine.start()
}
}
func machineSpeakerDidChangeInputClock(_ machine: CSMachine) {
// setupAudioQueueClockRate not only needs blocking access to the machine,
// but may be triggered on an arbitrary thread by a running machine, and that
// running machine may not be able to stop running until it has been called
// (e.g. if it is currently trying to run_until an audio event). Break the
// deadlock with an async dispatch.
DispatchQueue.main.async {
self.setupAudioQueueClockRate()
}
}
private func setupAudioQueueClockRate() {
// Establish and provide the audio queue, taking advice as to an appropriate sampling rate.
//
// TODO: this needs to be threadsafe. FIX!
let maximumSamplingRate = CSAudioQueue.preferredSamplingRate()
let selectedSamplingRate = Float64(self.machine.idealSamplingRate(from: NSRange(location: 0, length: NSInteger(maximumSamplingRate))))
let isStereo = self.machine.isStereo()
if selectedSamplingRate > 0 {
// [Re]create the audio queue only if necessary.
if self.audioQueue == nil || self.audioQueue.samplingRate != selectedSamplingRate {
self.machine.audioQueue = nil
self.audioQueue = CSAudioQueue(samplingRate: Float64(selectedSamplingRate), isStereo:isStereo)
self.audioQueue.delegate = self
self.machine.audioQueue = self.audioQueue
self.machine.setAudioSamplingRate(Float(selectedSamplingRate), bufferSize:audioQueue.preferredBufferSize, stereo:isStereo)
}
}
}
/// Responds to the CSAudioQueueDelegate dry-queue warning message by requesting a machine update.
final func audioQueueIsRunningDry(_ audioQueue: CSAudioQueue) {
}
/// Responds to the CSOpenGLViewDelegate redraw message by requesting a machine update if this is a timed
/// request, and ordering a redraw regardless of the motivation.
final func openGLViewRedraw(_ view: CSOpenGLView, event redrawEvent: CSOpenGLViewRedrawEvent) {
if drawLock.try() {
if redrawEvent == .timer {
machine.updateView(forPixelSize: view.backingSize)
}
machine.drawView(forPixelSize: view.backingSize)
drawLock.unlock()
}
}
// MARK: - Pasteboard Forwarding.
/// Forwards any text currently on the pasteboard into the active machine.
func paste(_ sender: Any) {
let pasteboard = NSPasteboard.general
if let string = pasteboard.string(forType: .string), let machine = self.machine {
machine.paste(string)
}
}
// MARK: - Runtime Media Insertion.
/// Delegate message to receive drag and drop files.
final func openGLView(_ view: CSOpenGLView, didReceiveFileAt URL: URL) {
let mediaSet = CSMediaSet(fileAt: URL)
if let mediaSet = mediaSet {
mediaSet.apply(to: self.machine)
}
}
/// Action for the insert menu command; displays an NSOpenPanel and then segues into the same process
/// as if a file had been received via drag and drop.
@IBAction final func insertMedia(_ sender: AnyObject!) {
let openPanel = NSOpenPanel()
openPanel.message = "Hint: you can also insert media by dragging and dropping it onto the machine's window."
openPanel.beginSheetModal(for: self.windowControllers[0].window!) { (response) in
if response == .OK {
for url in openPanel.urls {
let mediaSet = CSMediaSet(fileAt: url)
if let mediaSet = mediaSet {
mediaSet.apply(to: self.machine)
}
}
}
}
}
// MARK: - Input Management.
/// Upon a resign key, immediately releases all ongoing input mechanisms — any currently pressed keys,
/// and joystick and mouse inputs.
func windowDidResignKey(_ notification: Notification) {
if let machine = self.machine {
machine.clearAllKeys()
machine.joystickManager = nil
}
self.openGLView.releaseMouse()
}
/// Upon becoming key, attaches joystick input to the machine.
func windowDidBecomeKey(_ notification: Notification) {
if let machine = self.machine {
machine.joystickManager = (DocumentController.shared as! DocumentController).joystickManager
}
}
/// Forwards key down events directly to the machine.
func keyDown(_ event: NSEvent) {
if let machine = self.machine {
machine.setKey(event.keyCode, characters: event.characters, isPressed: true)
}
}
/// Forwards key up events directly to the machine.
func keyUp(_ event: NSEvent) {
if let machine = self.machine {
machine.setKey(event.keyCode, characters: event.characters, isPressed: false)
}
}
/// Synthesies appropriate key up and key down events upon any change in modifiers.
func flagsChanged(_ newModifiers: NSEvent) {
if let machine = self.machine {
machine.setKey(VK_Shift, characters: nil, isPressed: newModifiers.modifierFlags.contains(.shift))
machine.setKey(VK_Control, characters: nil, isPressed: newModifiers.modifierFlags.contains(.control))
machine.setKey(VK_Command, characters: nil, isPressed: newModifiers.modifierFlags.contains(.command))
machine.setKey(VK_Option, characters: nil, isPressed: newModifiers.modifierFlags.contains(.option))
}
}
/// Forwards mouse movement events to the mouse.
func mouseMoved(_ event: NSEvent) {
if let machine = self.machine {
machine.addMouseMotionX(event.deltaX, y: event.deltaY)
}
}
/// Forwards mouse button down events to the mouse.
func mouseUp(_ event: NSEvent) {
if let machine = self.machine {
machine.setMouseButton(Int32(event.buttonNumber), isPressed: false)
}
}
/// Forwards mouse button up events to the mouse.
func mouseDown(_ event: NSEvent) {
if let machine = self.machine {
machine.setMouseButton(Int32(event.buttonNumber), isPressed: true)
}
}
// MARK: - MachinePicker Outlets and Actions
@IBOutlet var machinePicker: MachinePicker?
@IBOutlet var machinePickerPanel: NSWindow?
@IBAction func createMachine(_ sender: NSButton?) {
let selectedMachine = machinePicker!.selectedMachine()
self.windowControllers[0].window?.endSheet(self.machinePickerPanel!)
self.machinePicker = nil
self.configureAs(selectedMachine)
}
@IBAction func cancelCreateMachine(_ sender: NSButton?) {
close()
}
// MARK: - ROMRequester Outlets and Actions
@IBOutlet var romRequesterPanel: NSWindow?
@IBOutlet var romRequesterText: NSTextField?
@IBOutlet var romReceiverErrorField: NSTextField?
@IBOutlet var romReceiverView: CSROMReceiverView?
private var romRequestBaseText = ""
func requestRoms() {
// Don't act yet if there's no window controller yet.
if self.windowControllers.count == 0 {
return
}
// Load the ROM requester dialogue.
Bundle.main.loadNibNamed("ROMRequester", owner: self, topLevelObjects: nil)
self.romReceiverView!.delegate = self
self.romRequestBaseText = romRequesterText!.stringValue
romReceiverErrorField?.alphaValue = 0.0
// Populate the current absentee list.
populateMissingRomList()
// Show the thing.
self.windowControllers[0].window?.beginSheet(self.romRequesterPanel!, completionHandler: nil)
}
@IBAction func cancelRequestROMs(_ sender: NSButton?) {
close()
}
func populateMissingRomList() {
// Fill in the missing details; first build a list of all the individual
// line items.
var requestLines: [String] = []
for missingROM in self.missingROMs {
if let descriptiveName = missingROM.descriptiveName {
requestLines.append("• " + descriptiveName)
} else {
requestLines.append("• " + missingROM.fileName)
}
}
// Suffix everything up to the penultimate line with a semicolon;
// the penultimate line with a semicolon and a conjunctive; the final
// line with a full stop.
for x in 0 ..< requestLines.count {
if x < requestLines.count - 2 {
requestLines[x].append(";")
} else if x < requestLines.count - 1 {
requestLines[x].append("; and")
} else {
requestLines[x].append(".")
}
}
romRequesterText!.stringValue = self.romRequestBaseText + requestLines.joined(separator: "\n")
}
func romReceiverView(_ view: CSROMReceiverView, didReceiveFileAt URL: URL) {
// Test whether the file identified matches any of the currently missing ROMs.
// If so then remove that ROM from the missing list and update the request screen.
// If no ROMs are still missing, start the machine.
do {
let fileData = try Data(contentsOf: URL)
var didInstallRom = false
// Try to match by size first, CRC second. Accept that some ROMs may have
// some additional appended data. Arbitrarily allow them to be up to 10kb
// too large.
var index = 0
for missingROM in self.missingROMs {
if fileData.count >= missingROM.size && fileData.count < missingROM.size + 10*1024 {
// Trim to size.
let trimmedData = fileData[0 ..< missingROM.size]
// Get CRC.
if missingROM.crc32s.contains( (trimmedData as NSData).crc32 ) {
// This ROM matches; copy it into the application library,
// strike it from the missing ROM list and decide how to
// proceed.
let fileManager = FileManager.default
let targetPath = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("ROMImages")
.appendingPathComponent(missingROM.machineName)
let targetFile = targetPath
.appendingPathComponent(missingROM.fileName)
do {
try fileManager.createDirectory(atPath: targetPath.path, withIntermediateDirectories: true, attributes: nil)
try trimmedData.write(to: targetFile)
} catch let error {
showRomReceiverError(error: "Couldn't write to application support directory: \(error)")
}
self.missingROMs.remove(at: index)
didInstallRom = true
break
}
}
index = index + 1
}
if didInstallRom {
if self.missingROMs.count == 0 {
self.windowControllers[0].window?.endSheet(self.romRequesterPanel!)
configureAs(self.machineDescription!)
} else {
populateMissingRomList()
}
} else {
showRomReceiverError(error: "Didn't recognise contents of \(URL.lastPathComponent)")
}
} catch let error {
showRomReceiverError(error: "Couldn't read file at \(URL.absoluteString): \(error)")
}
}
// Yucky ugliness follows; my experience as an iOS developer intersects poorly with
// NSAnimationContext hence the various stateful diplications below. isShowingError
// should be essentially a duplicate of the current alphaValue, and animationCount
// is to resolve my inability to figure out how to cancel scheduled animations.
private var errorText = ""
private var isShowingError = false
private var animationCount = 0
private func showRomReceiverError(error: String) {
// Set or append the new error.
if self.errorText.count > 0 {
self.errorText = self.errorText + "\n" + error
} else {
self.errorText = error
}
// Apply the new complete text.
romReceiverErrorField!.stringValue = self.errorText
if !isShowingError {
// Schedule the box's appearance.
NSAnimationContext.beginGrouping()
NSAnimationContext.current.duration = 0.1
romReceiverErrorField?.animator().alphaValue = 1.0
NSAnimationContext.endGrouping()
isShowingError = true
}
// Schedule the box to disappear.
self.animationCount = self.animationCount + 1
let capturedAnimationCount = animationCount
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
if self.animationCount == capturedAnimationCount {
NSAnimationContext.beginGrouping()
NSAnimationContext.current.duration = 1.0
self.romReceiverErrorField?.animator().alphaValue = 0.0
NSAnimationContext.endGrouping()
self.isShowingError = false
self.errorText = ""
}
}
}
// MARK: Joystick-via-the-keyboard selection
@IBAction func useKeyboardAsPhysicalKeyboard(_ sender: NSMenuItem?) {
machine.inputMode = .keyboardPhysical
}
@IBAction func useKeyboardAsLogicalKeyboard(_ sender: NSMenuItem?) {
machine.inputMode = .keyboardLogical
}
@IBAction func useKeyboardAsJoystick(_ sender: NSMenuItem?) {
machine.inputMode = .joystick
}
/// Determines which of the menu items to enable and disable based on the ability of the
/// current machine to handle keyboard and joystick input, accept new media and whether
/// it has an associted activity window.
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
if let menuItem = item as? NSMenuItem {
switch item.action {
case #selector(self.useKeyboardAsPhysicalKeyboard):
if machine == nil || !machine.hasExclusiveKeyboard {
menuItem.state = .off
return false
}
menuItem.state = machine.inputMode == .keyboardPhysical ? .on : .off
return true
case #selector(self.useKeyboardAsLogicalKeyboard):
if machine == nil || !machine.hasExclusiveKeyboard {
menuItem.state = .off
return false
}
menuItem.state = machine.inputMode == .keyboardLogical ? .on : .off
return true
case #selector(self.useKeyboardAsJoystick):
if machine == nil || !machine.hasJoystick {
menuItem.state = .off
return false
}
menuItem.state = machine.inputMode == .joystick ? .on : .off
return true
case #selector(self.showActivity(_:)):
return self.activityPanel != nil
case #selector(self.insertMedia(_:)):
return self.machine != nil && self.machine.canInsertMedia
default: break
}
}
return super.validateUserInterfaceItem(item)
}
/// Saves a screenshot of the
@IBAction func saveScreenshot(_ sender: AnyObject!) {
// Grab a date formatter and form a file name.
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
let filename = ("Clock Signal Screen Shot " + dateFormatter.string(from: Date()) + ".png").replacingOccurrences(of: "/", with: "-")
.replacingOccurrences(of: ":", with: ".")
let pictursURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let url = pictursURL.appendingPathComponent(filename)
// Obtain the machine's current display.
var imageRepresentation: NSBitmapImageRep? = nil
self.openGLView.perform {
imageRepresentation = self.machine.imageRepresentation
}
// Encode as a PNG and save.
let pngData = imageRepresentation!.representation(using: .png, properties: [:])
try! pngData?.write(to: url)
}
// MARK: - Window Title Updates.
private var unadornedWindowTitle = ""
func openGLViewDidCaptureMouse(_ view: CSOpenGLView) {
self.windowControllers[0].window?.title = self.unadornedWindowTitle + " (press ⌘+control to release mouse)"
}
func openGLViewDidReleaseMouse(_ view: CSOpenGLView) {
self.windowControllers[0].window?.title = self.unadornedWindowTitle
}
// MARK: - Activity Display.
private class LED {
let levelIndicator: NSLevelIndicator
init(levelIndicator: NSLevelIndicator) {
self.levelIndicator = levelIndicator
}
var isLit = false
var isBlinking = false
}
private var leds: [String: LED] = [:]
func setupActivityDisplay() {
var leds = machine.leds
if leds.count > 0 {
Bundle.main.loadNibNamed("Activity", owner: self, topLevelObjects: nil)
showActivity(nil)
// Inspect the activity panel for indicators.
var activityIndicators: [NSLevelIndicator] = []
var textFields: [NSTextField] = []
if let contentView = self.activityPanel.contentView {
for view in contentView.subviews {
if let levelIndicator = view as? NSLevelIndicator {
activityIndicators.append(levelIndicator)
}
if let textField = view as? NSTextField {
textFields.append(textField)
}
}
}
// If there are fewer level indicators than LEDs, trim that list.
if activityIndicators.count < leds.count {
leds.removeSubrange(activityIndicators.count ..< leds.count)
}
// Remove unused views.
for c in leds.count ..< activityIndicators.count {
textFields[c].removeFromSuperview()
activityIndicators[c].removeFromSuperview()
}
// Apply labels and create leds entries.
for c in 0 ..< leds.count {
textFields[c].stringValue = leds[c]
self.leds[leds[c]] = LED(levelIndicator: activityIndicators[c])
}
// Add a constraints to minimise window height.
let heightConstraint = NSLayoutConstraint(
item: self.activityPanel.contentView!,
attribute: .bottom,
relatedBy: .equal,
toItem: activityIndicators[leds.count-1],
attribute: .bottom,
multiplier: 1.0,
constant: 20.0)
self.activityPanel.contentView?.addConstraint(heightConstraint)
}
}
func machine(_ machine: CSMachine, ledShouldBlink ledName: String) {
// If there is such an LED, switch it off for 0.03 of a second; if it's meant
// to be off at the end of that, leave it off. Don't allow the blinks to
// pile up — allow there to be only one in flight at a time.
if let led = leds[ledName] {
DispatchQueue.main.async {
if !led.isBlinking {
led.levelIndicator.floatValue = 0.0
led.isBlinking = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) {
led.levelIndicator.floatValue = led.isLit ? 1.0 : 0.0
led.isBlinking = false
}
}
}
}
}
func machine(_ machine: CSMachine, led ledName: String, didChangeToLit isLit: Bool) {
// If there is such an LED, switch it appropriately.
if let led = leds[ledName] {
DispatchQueue.main.async {
led.levelIndicator.floatValue = isLit ? 1.0 : 0.0
led.isLit = isLit
}
}
}
// MARK: - Volume Control.
@IBAction func setVolume(_ sender: NSSlider!) {
if let machine = self.machine {
machine.setVolume(sender.floatValue)
setUserDefaultsVolume(sender.floatValue)
}
}
// This class is pure nonsense to work around Xcode's opaque behaviour.
// If I make the main class a sub of CAAnimationDelegate then the compiler
// generates a bridging header that doesn't include QuartzCore and therefore
// can't find a declaration of the CAAnimationDelegate protocol. Doesn't
// seem to matter what I add explicitly to the link stage, which version of
// macOS I set as the target, etc.
//
// So, the workaround: make my CAAnimationDelegate something that doesn't
// appear in the bridging header.
fileprivate class ViewFader: NSObject, CAAnimationDelegate {
var volumeView: NSView
init(view: NSView) {
volumeView = view
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
volumeView.isHidden = true
}
}
fileprivate var animationFader: ViewFader? = nil
func openGLViewDidShowOSMouseCursor(_ view: CSOpenGLView) {
// The OS mouse cursor became visible, so show the volume controls.
animationFader = nil
volumeView.layer?.removeAllAnimations()
volumeView.isHidden = false
volumeView.layer?.opacity = 1.0
}
func openGLViewWillHideOSMouseCursor(_ view: CSOpenGLView) {
// The OS mouse cursor will be hidden, so hide the volume controls.
if !volumeView.isHidden && volumeView.layer?.animation(forKey: "opacity") == nil {
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.fromValue = 1.0
fadeAnimation.toValue = 0.0
fadeAnimation.duration = 0.2
animationFader = ViewFader(view: volumeView)
fadeAnimation.delegate = animationFader
volumeView.layer?.add(fadeAnimation, forKey: "opacity")
volumeView.layer?.opacity = 0.0
}
}
// The user's selected volume is stored as 1 - volume in the user defaults in order
// to take advantage of the default value being 0.
private func userDefaultsVolume() -> Float {
return 1.0 - UserDefaults.standard.float(forKey: "defaultVolume")
}
private func setUserDefaultsVolume(_ volume: Float) {
UserDefaults.standard.set(1.0 - volume, forKey: "defaultVolume")
}
}
| 33.652229 | 136 | 0.727978 |
3aa313be89508fc6a642d828856dbe027a678710 | 476 | import SwiftCLI
public class Release: Command {
public func execute() throws {
print("release")
}
}
extension Release: Routable {
public var name: String {
get {
return "release"
}
}
public var shortDescription: String {
get {
return "Release a fish"
}
}
public var longDescription: String {
get {
return "Use this command to remove a fish"
}
}
}
| 16.413793 | 54 | 0.527311 |
1d4fe30843d39bcbf6fe136dc89625b3c1ee351e | 1,059 | import UIKit
/// hyperlink ios
class AproposViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let descriptionText = NSMutableAttributedString(string:"To learn more, check out our ", attributes: [:])
let linkText = NSMutableAttributedString(string: "Github", attributes: [NSAttributedString.Key.link: URL(string: "https://github.com/elaInnovation")!])
descriptionText.append(linkText)
let githubText = UITextView()
githubText.attributedText = descriptionText
githubText.textColor = UIColor.black
githubText.font = UIFont.systemFont(ofSize: 25.0)
githubText.font = UIFont.boldSystemFont(ofSize: 18)
githubText.frame = CGRect(x: 30, y: 300, width: 350, height: 100)
githubText.backgroundColor = .none
self.view.addSubview(githubText)
self.view.bringSubviewToFront(githubText)
}
}
| 31.147059 | 159 | 0.632672 |
21fcc6574c1ed3ea5a8e0a7d9a393c70646cef1e | 4,914 | //
// AppDelegate.swift
// marvelapp
//
// Created by Felipe Antonio Cardoso on 05/04/2019.
// Copyright © 2019 Felipe Antonio Cardoso. All rights reserved.
//
import UIKit
import CoreData
let imageCache = NSCache<NSString, UIImage>()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private let appCoordinator = AppCoordinator()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
window?.rootViewController = appCoordinator.rootViewController
window?.makeKeyAndVisible()
appCoordinator.start()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "marvelapp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 47.25 | 285 | 0.683964 |
2f406c6e2abffa2e5a20f0c81bdae2d1b129cb4a | 266 | //
// Created by Mikhail Mulyar on 18/06/2018.
// Copyright (c) 2018 CocoaPods. All rights reserved.
//
import Foundation
import RealmSwift
import CoreData
import DatabaseObjectsMapper
class DefaultContainer: CoreDataContainer {
@NSManaged var name: String
}
| 17.733333 | 53 | 0.770677 |
695b560c597c184c48b238226f3871a964044807 | 940 | public struct SomeCustomView: Codable, Hashable {
public var id: String?
public var title: String?
public var subtitle: String?
public var style: SomeStyle?
public var someImage: SomeImage?
public var destination: Destination?
public var axis: ViewDirectionAxis?
public var views: [SomeView]?
public var type: ViewType {
.custom
}
public init(
id: String? = nil,
title: String? = nil,
subtitle: String? = nil,
style: SomeStyle? = nil,
someImage: SomeImage? = nil,
destination: Destination? = nil,
axis: ViewDirectionAxis? = nil,
views: [SomeView]? = nil
) {
self.id = id
self.title = title
self.subtitle = subtitle
self.style = style
self.someImage = someImage
self.destination = destination
self.axis = axis
self.views = views
}
}
| 23.5 | 49 | 0.580851 |
90e656e490f0d2df1c96b629c92ca36963df00d7 | 1,777 | //
// Picker.swift
// FXKit
//
// Created by Fanxx on 2018/4/17.
// Copyright © 2018年 fanxx. All rights reserved.
//
import UIKit
extension FX.NamespaceImplement where Base: UIView {
@discardableResult
public func pick(_ title:String?,contentView:UIView,completion:@escaping ()->Bool) -> FXPickerView{
let pickerView = FXPickerView(title: title, contentView: contentView)
pickerView.confirmAction = {
if completion() {
pickerView.hide()
}
}
pickerView.show(self.base)
return pickerView
}
public func pick(_ title:String?,date:Date?=nil,mode:UIDatePicker.Mode,min:Date?=nil,max:Date?=nil,completion: @escaping (Date?)->Bool){
let pickerView = FXDatePickerView(title: title ?? "请选择日期", mode: mode)
if let d = date {
pickerView.datePicker.date = d
}
if let m = min {
pickerView.datePicker.minimumDate = m
}
if let mx = max {
pickerView.datePicker.maximumDate = mx
}
pickerView.confirmAction = {
if completion(pickerView.datePicker.date) {
pickerView.hide()
}
}
pickerView.show(self.base)
}
public func pick(_ title:String?,options:[[String]],selected:[Int]?,attributes:[NSAttributedString.Key:Any]? = nil,completion:@escaping ([Int])->Bool) {
let pickerView = FXOptionsPickerView(title: title ?? "请选择", options:options,attributes:attributes)
pickerView.confirmAction = {
if completion(pickerView.selected) {
pickerView.hide()
}
}
pickerView.show(self.base)
if let s = selected {
pickerView.selected = s
}
}
}
| 32.907407 | 156 | 0.590884 |
878219f3af1b9c0adf862982484a4ece3895f8e9 | 9,453 | // REQUIRES: plus_zero_runtime
// RUN: %target-swift-frontend -module-name address_only_types -enable-sil-ownership -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F
func address_only_argument(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : @trivial $*Unloadable):
// CHECK: debug_value_addr [[XARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : @trivial $*Unloadable):
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F
func address_only_return(_ x: Unloadable, y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : @trivial $*Unloadable, [[XARG:%[0-9]+]] : @trivial $*Unloadable, [[YARG:%[0-9]+]] : @trivial $Builtin.Int64):
// CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x"
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : @trivial $*Unloadable, {{%.*}} : @trivial $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr %1 to [initialization] %0 : $*Unloadable
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B29_conditional_missing_return_2
func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : @trivial $*Unloadable, {{%.*}} : @trivial $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(_ x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B7_call_1
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : @trivial $*Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B21_call_1_ignore_returnyyF
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F
func address_only_call_2(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : @trivial $*Unloadable):
// CHECK: debug_value_addr [[XARG]] : $*Unloadable
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]([[XARG]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp(_ dest: inout Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : @trivial $*Unloadable):
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: %[[ACCESS:.*]] = begin_access [modify] [unknown] %0 :
// CHECK: copy_addr [take] [[TEMP]] to %[[ACCESS]] :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : @trivial $*Unloadable, [[VARG:%[0-9]+]] : @trivial $*Unloadable):
// CHECK: [[VBOX:%.*]] = alloc_box ${ var Unloadable }
// CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable
dest = v
// CHECK: [[READBOX:%.*]] = begin_access [read] [unknown] [[PBOX]] :
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[READBOX]] to [initialization] [[TEMP]] :
// CHECK: [[RET:%.*]] = begin_access [modify] [unknown] %0 :
// CHECK: copy_addr [take] [[TEMP]] to [[RET]] :
// CHECK: destroy_value [[VBOX]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @$S18address_only_types11global_propAA10Unloadable_pvs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv_to_property(_ v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : @trivial $*Unloadable):
// CHECK: debug_value_addr [[VARG]] : $*Unloadable
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @$S18address_only_types11global_propAA10Unloadable_pvs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden @$S18address_only_types0a1_B4_varAA10Unloadable_pyF
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : @trivial $*Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Unloadable }
// CHECK: [[XPB:%.*]] = project_box [[XBOX]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XPB]] :
// CHECK: copy_addr [[ACCESS]] to [initialization] %0
// CHECK: destroy_value [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden @$S18address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F
func call_address_only_nontuple_arg_function(_ x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
| 40.922078 | 148 | 0.667936 |
d9ccae6350e2319eb9c49b412a8cfe410b964608 | 799 | // swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "Hwp-Swift",
products: [
.library(name: "CoreHwp", targets: ["CoreHwp"]),
],
dependencies: [
.package(url: "https://github.com/CoreOffice/OLEKit.git", .exact("0.3.1")),
.package(url: "https://github.com/tsolomko/SWCompression.git", .exact("4.6.0")),
.package(url: "https://github.com/Quick/Nimble", .exact("9.2.1")),
],
targets: [
.target(
name: "CoreHwp",
dependencies: [
"OLEKit",
"SWCompression",
]
),
.testTarget(
name: "CoreHwpTests",
dependencies: [
"CoreHwp",
"Nimble",
]
),
]
)
| 24.212121 | 88 | 0.475594 |
5bee89c785741e37ed6b244d2489198a72c9dd5e | 29,474 | import Foundation
import NIO
@available(OSX 10.12, iOS 10, *)
let isoFormatter = ISO8601DateFormatter()
let isoDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
func date(from string: String) throws -> Date {
if #available(OSX 10.12, iOS 11, *) {
guard let date = isoFormatter.date(from: string) else {
throw JSONParserError.invalidDate(string)
}
return date
} else {
guard let date = isoDateFormatter.date(from: string) else {
throw JSONParserError.invalidDate(string)
}
return date
}
}
/// These settings can be used to alter the decoding process.
public struct JSONDecoderSettings {
public init() {}
/// This userInfo is accessible by the Decodable types that are being created
public var userInfo = [CodingUserInfoKey : Any]()
/// When strings are read, no extra effort is put into decoding unicode characters such as `\u00ff`
///
/// `true` by default
public var decodeUnicode = true
/// When a key is not set in the JSON Object it is regarded as `null` if the value is `true`.
///
/// `true` by default
public var decodeMissingKeyAsNil = true
/// Defines the method used when decoding keys
public var keyDecodingStrategy = JSONDecoder.KeyDecodingStrategy.useDefaultKeys
/// The method used to decode Foundation `Date` types
public var dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.deferredToDate
/// The method used to decode Foundation `Data` types
public var dataDecodingStrategy = JSONDecoder.DataDecodingStrategy.base64
}
/// A JSON Decoder that aims to be largely functionally equivalent to Foundation.JSONDecoder with more for optimization.
public final class IkigaJSONDecoder {
/// These settings can be used to alter the decoding process.
public var settings: JSONDecoderSettings
private var parser: JSONParser!
public init(settings: JSONDecoderSettings = JSONDecoderSettings()) {
self.settings = settings
}
/// Parses the Decodable type from an UnsafeBufferPointer.
/// This API can be used when the data wasn't originally available as `Data` so you remove the need for copying data.
/// This can save a lot of performance.
public func decode<D: Decodable>(_ type: D.Type, from buffer: UnsafeBufferPointer<UInt8>) throws -> D {
let pointer = buffer.baseAddress!
if parser == nil {
parser = JSONParser(pointer: pointer, count: buffer.count)
} else {
parser.recycle(pointer: pointer, count: buffer.count)
}
try parser.scanValue()
let decoder = _JSONDecoder(description: parser!.description, pointer: pointer, settings: settings)
let type = try D(from: decoder)
return type
}
/// Parses the Decodable type from `Data`. This is the equivalent for JSONDecoder's Decode function.
public func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D {
let count = data.count
return try data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
return try decode(type, from: UnsafeBufferPointer(start: pointer, count: count))
}
}
/// Parses the Decodable type from a JSONObject.
public func decode<D: Decodable>(_ type: D.Type, from object: JSONObject) throws -> D {
return try object.jsonBuffer.withUnsafeReadableBytes { buffer in
let decoder = _JSONDecoder(
description: object.description,
pointer: buffer.baseAddress!.bindMemory(to: UInt8.self, capacity: buffer.count),
settings: settings
)
return try D(from: decoder)
}
}
/// Parses the Decodable type from a JSONArray.
public func decode<D: Decodable>(_ type: D.Type, from array: JSONArray) throws -> D {
return try array.jsonBuffer.withUnsafeReadableBytes { buffer in
let decoder = _JSONDecoder(
description: array.description,
pointer: buffer.baseAddress!.bindMemory(to: UInt8.self, capacity: buffer.count),
settings: settings
)
return try D(from: decoder)
}
}
/// Parses the Decodable type from a SwiftNIO `ByteBuffer`.
public func decode<D: Decodable>(_ type: D.Type, from byteBuffer: ByteBuffer) throws -> D {
return try byteBuffer.withUnsafeReadableBytes { buffer in
return try self.decode(type, from: buffer.bindMemory(to: UInt8.self))
}
}
/// Parses the Decodable type from `[UInt8]`. This is the equivalent for JSONDecoder's Decode function.
public func decode<D: Decodable>(_ type: D.Type, from bytes: [UInt8]) throws -> D {
return try bytes.withUnsafeBufferPointer { buffer in
return try decode(type, from: buffer)
}
}
/// Parses the Decodable type from `[UInt8]`. This is the equivalent for JSONDecoder's Decode function.
public func decode<D: Decodable>(_ type: D.Type, from string: String) throws -> D {
// TODO: Optimize with Swift 5
guard let data = string.data(using: .utf8) else {
throw JSONParserError.invalidData(string)
}
return try self.decode(type, from: data)
}
public func parse<D: Decodable>(
_ type: D.Type,
from buffer: inout ByteBuffer,
settings: JSONDecoderSettings = JSONDecoderSettings()
) throws -> D {
return try buffer.readWithUnsafeMutableReadableBytes { buffer -> (Int, D) in
let buffer = buffer.bindMemory(to: UInt8.self)
let pointer = buffer.baseAddress!
if self.parser == nil {
parser = JSONParser(pointer: pointer, count: buffer.count)
} else {
parser.recycle(pointer: pointer, count: buffer.count)
}
try parser.scanValue()
let decoder = _JSONDecoder(description: parser!.description, pointer: pointer, settings: settings)
let type = try D(from: decoder)
return (parser.currentOffset, type)
}
}
}
fileprivate struct _JSONDecoder: Decoder {
let description: JSONDescription
let pointer: UnsafePointer<UInt8>
let settings: JSONDecoderSettings
var snakeCasing: Bool
var codingPath = [CodingKey]()
var userInfo: [CodingUserInfoKey : Any] {
return settings.userInfo
}
func string<Key: CodingKey>(forKey key: Key) -> String {
if case .custom(let builder) = settings.keyDecodingStrategy {
return builder(codingPath + [key]).stringValue
} else {
return key.stringValue
}
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
guard description.topLevelType == .object else {
throw JSONParserError.missingKeyedContainer
}
let container = KeyedJSONDecodingContainer<Key>(decoder: self)
return KeyedDecodingContainer(container)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard description.topLevelType == .array else {
throw JSONParserError.missingUnkeyedContainer
}
return UnkeyedJSONDecodingContainer(decoder: self)
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return SingleValueJSONDecodingContainer(decoder: self)
}
init(description: JSONDescription, pointer: UnsafePointer<UInt8>, settings: JSONDecoderSettings) {
self.description = description
self.pointer = pointer
self.settings = settings
if case .convertFromSnakeCase = settings.keyDecodingStrategy {
self.snakeCasing = true
} else {
self.snakeCasing = false
}
}
func subDecoder(offsetBy offset: Int) -> _JSONDecoder {
let subDescription = self.description.subDescription(offset: offset)
return _JSONDecoder(description: subDescription, pointer: pointer, settings: settings)
}
func decode<D: Decodable>(_ type: D.Type) throws -> D {
switch type {
case is Date.Type:
switch self.settings.dateDecodingStrategy {
case .deferredToDate:
break
case .secondsSince1970:
let interval = try singleValueContainer().decode(Double.self)
return Date(timeIntervalSince1970: interval) as! D
case .millisecondsSince1970:
let interval = try singleValueContainer().decode(Double.self)
return Date(timeIntervalSince1970: interval / 1000) as! D
case .iso8601:
let string = try singleValueContainer().decode(String.self)
return try date(from: string) as! D
case .formatted(let formatter):
let string = try singleValueContainer().decode(String.self)
guard let date = formatter.date(from: string) else {
throw JSONParserError.invalidDate(string)
}
return date as! D
case .custom(let makeDate):
return try makeDate(self) as! D
@unknown default:
throw JSONParserError.unknownJSONStrategy
}
case is Data.Type:
switch self.settings.dataDecodingStrategy {
case .deferredToData:
break
case .base64:
let string = try singleValueContainer().decode(String.self)
guard let data = Data(base64Encoded: string) else {
throw JSONParserError.invalidData(string)
}
return data as! D
case .custom(let makeData):
return try makeData(self) as! D
@unknown default:
throw JSONParserError.unknownJSONStrategy
}
default:
break
}
return try D.init(from: self)
}
}
fileprivate struct KeyedJSONDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] {
return decoder.codingPath
}
let decoder: _JSONDecoder
var allStringKeys: [String] {
return decoder.description.keys(
inPointer: decoder.pointer,
unicode: decoder.settings.decodeUnicode,
convertingSnakeCasing: self.decoder.snakeCasing
)
}
var allKeys: [Key] {
return allStringKeys.compactMap(Key.init)
}
func contains(_ key: Key) -> Bool {
return decoder.description.containsKey(
decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
inPointer: decoder.pointer,
unicode: decoder.settings.decodeUnicode
)
}
func decodeNil(forKey key: Key) throws -> Bool {
guard let type = decoder.description.type(
ofKey: decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: decoder.pointer
) else {
return decoder.settings.decodeMissingKeyAsNil
}
return type == .null
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let jsonType = decoder.description.type(
ofKey: decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: decoder.pointer
) else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath + [key])
}
switch jsonType {
case .boolTrue:
return true
case .boolFalse:
return false
default:
throw JSONParserError.decodingError(expected: type, keyPath: codingPath + [key])
}
}
func floatingBounds(forKey key: Key) -> (Bounds, Bool)? {
return decoder.description.floatingBounds(
forKey: decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: decoder.pointer
)
}
func integerBounds(forKey key: Key) -> Bounds? {
return decoder.description.integerBounds(
forKey: decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: decoder.pointer
)
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let (bounds, escaped) = decoder.description.stringBounds(
forKey: decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: decoder.pointer
) else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath + [key])
}
guard let string = bounds.makeString(
from: decoder.pointer,
escaping: escaped,
unicode: decoder.settings.decodeUnicode
) else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath + [key])
}
return string
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard
let (bounds, floating) = floatingBounds(forKey: key),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath + [key])
}
return double
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard
let (bounds, floating) = floatingBounds(forKey: key),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return Float(double)
}
func decodeInt<F: FixedWidthInteger>(_ type: F.Type, forKey key: Key) throws -> F {
if let bounds = integerBounds(forKey: key), let int = bounds.makeInt(from: decoder.pointer) {
return try int.convert(to: F.self)
}
throw JSONParserError.decodingError(expected: F.self, keyPath: codingPath)
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try decodeInt(type, forKey: key)
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try decodeInt(type, forKey: key)
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try decodeInt(type, forKey: key)
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try decodeInt(type, forKey: key)
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
guard let (_, offset) = self.decoder.description.valueOffset(
forKey: self.decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: self.decoder.pointer
) else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
let decoder = self.decoder.subDecoder(offsetBy: offset)
return try decoder.decode(type)
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
guard let (_, offset) = self.decoder.description.valueOffset(
forKey: self.decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: self.decoder.pointer
) else {
throw JSONParserError.missingKeyedContainer
}
var decoder = self.decoder.subDecoder(offsetBy: offset)
decoder.codingPath.append(key)
return try decoder.container(keyedBy: NestedKey.self)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
guard let (_, offset) = self.decoder.description.valueOffset(
forKey: self.decoder.string(forKey: key),
convertingSnakeCasing: self.decoder.snakeCasing,
in: self.decoder.pointer
) else {
throw JSONParserError.missingUnkeyedContainer
}
var decoder = self.decoder.subDecoder(offsetBy: offset)
decoder.codingPath.append(key)
return try decoder.unkeyedContainer()
}
func superDecoder() throws -> Decoder {
return decoder
}
func superDecoder(forKey key: Key) throws -> Decoder {
return decoder
}
}
fileprivate struct UnkeyedJSONDecodingContainer: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
return decoder.codingPath
}
let decoder: _JSONDecoder
// Array descriptions are 17 bytes
var offset = 17
var currentIndex = 0
init(decoder: _JSONDecoder) {
self.decoder = decoder
self._count = decoder.description.arrayObjectCount()
}
var _count: Int
var count: Int? {
return _count
}
var isAtEnd: Bool {
return currentIndex >= _count
}
mutating func decodeNil() throws -> Bool {
try assertHasMore()
let type = decoder.description.type(atOffset: offset)
if type == .null {
skipValue()
return true
} else {
return false
}
}
mutating func skipValue() {
decoder.description.skipIndex(atOffset: &offset)
currentIndex = currentIndex &+ 1
}
func assertHasMore() throws {
guard !isAtEnd else {
throw JSONParserError.endOfObject
}
}
mutating func decode(_ type: Bool.Type) throws -> Bool {
try assertHasMore()
let type = decoder.description.type(atOffset: offset)
decoder.description.skipIndex(atOffset: &offset)
skipValue()
switch type {
case .boolTrue: return true
case .boolFalse: return false
default:
throw JSONParserError.decodingError(expected: Bool.self, keyPath: codingPath)
}
}
mutating func floatingBounds() -> (Bounds, Bool)? {
if isAtEnd { return nil }
let type = decoder.description.type(atOffset: offset)
guard
type == .integer || type == .floatingNumber
else {
return nil
}
let bounds = decoder.description.dataBounds(atIndexOffset: offset)
skipValue()
return (bounds, type == .floatingNumber)
}
mutating func integerBounds() -> Bounds? {
if isAtEnd { return nil }
let type = decoder.description.type(atOffset: offset)
if type != .integer {
return nil
}
let bounds = decoder.description.dataBounds(atIndexOffset: offset)
skipValue()
return bounds
}
mutating func decode(_ type: String.Type) throws -> String {
try assertHasMore()
let type = decoder.description.type(atOffset: offset)
if type != .string && type != .stringWithEscaping {
throw JSONParserError.decodingError(expected: String.self, keyPath: codingPath)
}
let bounds = decoder.description.dataBounds(atIndexOffset: offset)
guard let string = bounds.makeString(
from: decoder.pointer,
escaping: type == .stringWithEscaping,
unicode: decoder.settings.decodeUnicode
) else {
throw JSONParserError.decodingError(expected: String.self, keyPath: codingPath)
}
skipValue()
return string
}
mutating func decode(_ type: Double.Type) throws -> Double {
guard
let (bounds, floating) = floatingBounds(),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return double
}
mutating func decode(_ type: Float.Type) throws -> Float {
guard
let (bounds, floating) = floatingBounds(),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return Float(double)
}
mutating func decodeInt<F: FixedWidthInteger>(_ type: F.Type) throws -> F {
guard
let bounds = integerBounds(),
let int = bounds.makeInt(from: decoder.pointer)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return try int.convert(to: F.self)
}
mutating func decode(_ type: Int.Type) throws -> Int {
return try decodeInt(type)
}
mutating func decode(_ type: Int8.Type) throws -> Int8 {
return try decodeInt(type)
}
mutating func decode(_ type: Int16.Type) throws -> Int16 {
return try decodeInt(type)
}
mutating func decode(_ type: Int32.Type) throws -> Int32 {
return try decodeInt(type)
}
mutating func decode(_ type: Int64.Type) throws -> Int64 {
return try decodeInt(type)
}
mutating func decode(_ type: UInt.Type) throws -> UInt {
return try decodeInt(type)
}
mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodeInt(type)
}
mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodeInt(type)
}
mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodeInt(type)
}
mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodeInt(type)
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
let decoder = self.decoder.subDecoder(offsetBy: offset)
skipValue()
return try decoder.decode(type)
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
let decoder = self.decoder.subDecoder(offsetBy: offset)
skipValue()
return try decoder.container(keyedBy: NestedKey.self)
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let decoder = self.decoder.subDecoder(offsetBy: offset)
skipValue()
return try decoder.unkeyedContainer()
}
mutating func superDecoder() throws -> Decoder {
return decoder
}
}
fileprivate struct SingleValueJSONDecodingContainer: SingleValueDecodingContainer {
var codingPath: [CodingKey] {
return decoder.codingPath
}
let decoder: _JSONDecoder
func decodeNil() -> Bool {
return decoder.description.topLevelType == .null
}
func floatingBounds() -> (Bounds, Bool)? {
let type = decoder.description.topLevelType
if type != .integer && type != .floatingNumber {
return nil
}
let bounds = decoder.description.dataBounds(atIndexOffset: 0)
return (bounds, type == .floatingNumber)
}
func integerBounds() -> Bounds? {
if decoder.description.topLevelType != .integer {
return nil
}
return decoder.description.dataBounds(atIndexOffset: 0)
}
func decode(_ type: Bool.Type) throws -> Bool {
switch decoder.description.topLevelType {
case .boolTrue: return true
case .boolFalse: return false
default: throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
}
func decode(_ type: String.Type) throws -> String {
let jsonType = decoder.description.topLevelType
guard jsonType == .string || jsonType == .stringWithEscaping else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
let bounds = decoder.description.dataBounds(atIndexOffset: 0)
guard let string = bounds.makeString(
from: decoder.pointer,
escaping: jsonType == .stringWithEscaping,
unicode: decoder.settings.decodeUnicode
) else {
throw JSONParserError.decodingError(expected: String.self, keyPath: codingPath)
}
return string
}
func decode(_ type: Double.Type) throws -> Double {
guard
let (bounds, floating) = floatingBounds(),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return double
}
func decode(_ type: Float.Type) throws -> Float {
guard
let (bounds, floating) = floatingBounds(),
let double = bounds.makeDouble(from: decoder.pointer, floating: floating)
else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return Float(double)
}
func decode(_ type: Int.Type) throws -> Int {
return try decodeInt(ofType: type)
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try decodeInt(ofType: type)
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try decodeInt(ofType: type)
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try decodeInt(ofType: type)
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try decodeInt(ofType: type)
}
func decode(_ type: UInt.Type) throws -> UInt {
return try decodeInt(ofType: type)
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodeInt(ofType: type)
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodeInt(ofType: type)
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodeInt(ofType: type)
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodeInt(ofType: type)
}
func decodeInt<F: FixedWidthInteger>(ofType type: F.Type) throws -> F {
let jsonType = decoder.description.topLevelType
guard jsonType == .integer else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
let bounds = decoder.description.dataBounds(atIndexOffset: 0)
guard let int = bounds.makeInt(from: self.decoder.pointer) else {
throw JSONParserError.decodingError(expected: type, keyPath: codingPath)
}
return try int.convert(to: type)
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
return try decoder.decode(type)
}
}
extension FixedWidthInteger {
/// Converts the current FixedWidthInteger to another FixedWithInteger type `I`
///
/// Throws a `BSONTypeConversionError` if the range of `I` does not contain `self`
internal func convert<I: FixedWidthInteger>(to int: I.Type) throws -> I {
// If I is smaller in width we need to see if the current integer fits inside of I
if I.bitWidth < Self.bitWidth {
if numericCast(I.max) < self {
throw TypeConversionError(from: self, to: I.self)
} else if numericCast(I.min) > self {
throw TypeConversionError(from: self, to: I.self)
}
} else if !I.isSigned {
// BSON doesn't store unsigned ints and unsigned ints can't be negative
guard self >= 0 else {
throw TypeConversionError(from: self, to: I.self)
}
}
return numericCast(self)
}
}
| 34.311991 | 156 | 0.605042 |
0ea9318725b44914af26829460a2c415405c688a | 2,264 | public enum UISceneTransitionStyle {
case system
case defaultNext
case defaultUp
case defaultSet
case immediateSet
case sheet
public var transition: UISceneTransition? {
switch self {
case .system:
return nil
case .defaultNext:
let transition =
UISceneTransition(
animationControllerForPresentationType: UIShiftyZoomyAnimationController.self,
animationControllerForDismissalType: UIShiftyZoomyAnimationController.self)
return transition
case .defaultUp:
let transition =
UISceneTransition(
animationControllerForPresentationType: UISlidyZoomyAnimationController.self,
animationControllerForDismissalType: UISlidyZoomyAnimationController.self)
return transition
case .defaultSet:
let animation =
UISceneTransition.ChildViewControllerReplacementAnimation(
duration: 0.33, options: .transitionCrossDissolve)
let transition = UISceneTransition(childViewControllerReplacementAnimation: animation)
return transition
case .immediateSet:
return nil
case .sheet:
let transition =
UISceneTransition(
animationControllerForPresentationType: UISheetAnimationController.self,
animationControllerForDismissalType: UISheetAnimationController.self,
presentationControllerType: UISheetPresentationController.self,
interactionControllerForDismissalType: UISheetDismissalInteractionController.self)
return transition
}
}
public var isNext: Bool {
switch self {
case .defaultNext:
return true
default:
return false
}
}
public var isUp: Bool {
switch self {
case .defaultUp:
return true
default:
return false
}
}
public var isSheet: Bool {
switch self {
case .sheet:
return true
default:
return false
}
}
}
| 27.950617 | 102 | 0.59894 |
46ef98dc33a6bc4bb1d064ab4ddb7f91f3613245 | 1,292 | //
// NotificationService.swift
// Trials Australia
//
// Created by Matt Langtree on 5/12/18.
// Copyright © 2018 Matt Langtree. All rights reserved.
//
import UIKit
import UserNotifications
class NotificationService: NSObject {
override init() {
super.init()
UNUserNotificationCenter.current().delegate = self
}
func registerForNotifications() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
self.registerForRemoteNotifications()
}
}
func registerForRemoteNotifications() {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
func persist(_ deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
// a96a51774c44c618bf66afeeab390f6d2cab3359a4d5d2e82d0c5a67478b421e
UserDefaults.deviceToken = token
}
}
extension NotificationService: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
}
| 26.916667 | 177 | 0.695046 |
16fb74949a048dfa139caeb8afa3f8f6f0e2754d | 477 | //
// AccountCell.swift
// KrispyKreme
//
// Created by Naim Ali on 3/19/18.
// Copyright © 2018 Sean Davis. All rights reserved.
//
import UIKit
class AccountCell: UITableViewCell {
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
}
}
| 19.08 | 65 | 0.656184 |
4b996406d8bea6e9ec912d29f13479fa55ef27f9 | 14,631 | import Foundation
import RxSwift
import RxBlocking
// swiftlint:disable:next type_body_length
public class ServiceContainer {
public static let shared = ServiceContainer()
var dailyKeyRepository: DailyPubKeyHistoryRepository!
var ePubKeyHistoryRepository: EphemeralPublicKeyHistoryRepository!
var ePrivKeyHistoryRepository: EphemeralPrivateKeyHistoryRepository!
var locationPrivateKeyHistoryRepository: LocationPrivateKeyHistoryRepository!
var localDBKeyRepository: DataKeyRepository!
var backendAddressV3: BackendAddressV3!
var backendUserV3: BackendUserV3!
var backendTraceIdV3: BackendTraceIdV3!
var backendMiscV3: BackendMiscV3!
var backendSMSV3: BackendSMSVerificationV3!
var backendLocationV3: BackendLocationV3!
var backendDailyKeyV3: DefaultBackendDailyKeyV3!
var dailyKeyRepoHandler: DailyKeyRepoHandler!
var userService: UserService!
var locationUpdater: LocationUpdater!
var autoCheckoutService: AutoCheckoutService!
var userKeysBundle: UserKeysBundle!
var userDataPackageBuilderV3: UserDataPackageBuilderV3!
var checkOutPayloadBuilderV3: CheckOutPayloadBuilderV3!
var checkInPayloadBuilderV3: CheckInPayloadBuilderV3!
var qrCodePayloadBuilderV3: QRCodePayloadBuilderV3!
var userTransferBuilderV3: UserTransferBuilderV3!
var traceIdAdditionalBuilderV3: TraceIdAdditionalDataBuilderV3!
var privateMeetingQRCodeBuilderV3: PrivateMeetingQRCodeBuilderV3!
var traceIdService: TraceIdService!
var history: HistoryService!
var historyListener: HistoryEventListener!
var selfCheckin: SelfCheckinService!
var privateMeetingService: PrivateMeetingService!
var userSecrectsConsistencyChecker: UserSecretsConsistencyChecker!
var accessedTracesChecker: AccessedTraceIdChecker!
var traceInfoRepo: TraceInfoRepo!
var accessedTraceIdRepo: AccessedTraceIdRepo!
var traceIdCoreRepo: TraceIdCoreRepo!
var locationRepo: LocationRepo!
var keyValueRepo: RealmKeyValueRepo!
var healthDepartmentRepo: HealthDepartmentRepo!
var historyRepo: HistoryRepo!
var documentRepo: DocumentRepo!
var testProviderKeyRepo: TestProviderKeyRepo!
var personRepo: PersonRepo!
var personService: PersonService!
/// Aggregated realm databases when some global changes on all DBs are needed.
var realmDatabaseUtils: [RealmDatabaseUtils] = []
var documentKeyProvider: DocumentKeyProvider!
var documentFactory: DocumentFactory!
var documentRepoService: DocumentRepoService!
var documentProcessingService: DocumentProcessingService!
var documentUniquenessChecker: DocumentUniquenessChecker!
var baerCodeKeyService: BaerCodeKeyService!
var notificationService: NotificationService!
var qrProcessingService: QRProcessingService!
private(set) var isSetup = false
// swiftlint:disable:next function_body_length
func setup(forceReinitialize: Bool = false) throws {
if isSetup {
if forceReinitialize {
disableAllServices()
} else {
return
}
}
backendAddressV3 = BackendAddressV3()
dailyKeyRepository = DailyPubKeyHistoryRepository()
ePubKeyHistoryRepository = EphemeralPublicKeyHistoryRepository()
ePrivKeyHistoryRepository = EphemeralPrivateKeyHistoryRepository()
locationPrivateKeyHistoryRepository = LocationPrivateKeyHistoryRepository()
localDBKeyRepository = DataKeyRepository(tag: "LocalDBKey")
locationUpdater = LocationUpdater()
userKeysBundle = UserKeysBundle()
try userKeysBundle.generateKeys()
userKeysBundle.removeUnusedKeys()
userDataPackageBuilderV3 = UserDataPackageBuilderV3(
userKeysBundle: userKeysBundle)
qrCodePayloadBuilderV3 = QRCodePayloadBuilderV3(
keysBundle: userKeysBundle,
dailyKeyRepo: dailyKeyRepository,
ePubKeyRepo: ePubKeyHistoryRepository,
ePrivKeyRepo: ePrivKeyHistoryRepository)
checkOutPayloadBuilderV3 = CheckOutPayloadBuilderV3()
checkInPayloadBuilderV3 = CheckInPayloadBuilderV3()
traceIdAdditionalBuilderV3 = TraceIdAdditionalDataBuilderV3()
privateMeetingQRCodeBuilderV3 = PrivateMeetingQRCodeBuilderV3(backendAddress: backendAddressV3, preferences: LucaPreferences.shared)
userTransferBuilderV3 = UserTransferBuilderV3(userKeysBundle: userKeysBundle, dailyKeyRepo: dailyKeyRepository)
backendSMSV3 = BackendSMSVerificationV3(backendAddress: backendAddressV3)
backendLocationV3 = BackendLocationV3(backendAddress: backendAddressV3)
backendUserV3 = BackendUserV3(
backendAddress: backendAddressV3,
userDataBuilder: userDataPackageBuilderV3,
userTransferBuilder: userTransferBuilderV3)
backendTraceIdV3 = BackendTraceIdV3(
backendAddress: backendAddressV3,
checkInBuilder: checkInPayloadBuilderV3,
checkOutBuilder: checkOutPayloadBuilderV3,
additionalDataBuilder: traceIdAdditionalBuilderV3)
backendMiscV3 = BackendMiscV3(backendAddress: backendAddressV3)
backendDailyKeyV3 = DefaultBackendDailyKeyV3(backendAddress: backendAddressV3)
dailyKeyRepoHandler = DailyKeyRepoHandler(dailyKeyRepo: dailyKeyRepository, backend: backendDailyKeyV3)
userService = UserService(preferences: LucaPreferences.shared, backend: backendUserV3, userKeysBundle: userKeysBundle, dailyKeyRepoHandler: dailyKeyRepoHandler)
privateMeetingService = PrivateMeetingService(
privateKeys: locationPrivateKeyHistoryRepository,
preferences: UserDataPreferences(suiteName: "locations"),
backend: backendLocationV3,
traceIdAdditionalDataBuilder: traceIdAdditionalBuilderV3)
try setupRepos()
traceIdService = TraceIdService(qrCodeGenerator: qrCodePayloadBuilderV3,
lucaPreferences: LucaPreferences.shared,
dailyKeyRepo: dailyKeyRepository,
ePubKeyRepo: ePubKeyHistoryRepository,
ePrivKeyRepo: ePrivKeyHistoryRepository,
preferences: UserDataPreferences(suiteName: "traceIdService"),
backendTrace: backendTraceIdV3,
backendMisc: backendMiscV3,
backendLocation: backendLocationV3,
privateMeetingService: privateMeetingService,
traceInfoRepo: traceInfoRepo,
locationRepo: locationRepo,
traceIdCoreRepo: traceIdCoreRepo)
autoCheckoutService = AutoCheckoutService(
keyValueRepo: keyValueRepo,
traceIdService: traceIdService,
oldLucaPreferences: LucaPreferences.shared
)
autoCheckoutService.register(regionDetector: RegionMonitoringDetector(locationUpdater: locationUpdater))
// autoCheckoutService.register(regionDetector: LocationUpdatesRegionDetector(locationUpdater: locationUpdater, allowedAppStates: [.active]))
autoCheckoutService.register(regionDetector: SingleLocationRequestRegionDetector(locationUpdater: locationUpdater, allowedAppStates: [.active]))
autoCheckoutService.enable()
history = HistoryService(
preferences: UserDataPreferences(suiteName: "history"),
historyRepo: historyRepo
)
historyListener = HistoryEventListener(
historyService: history,
traceIdService: traceIdService,
userService: userService,
privateMeetingService: privateMeetingService,
locationRepo: locationRepo,
historyRepo: historyRepo,
traceInfoRepo: traceInfoRepo)
historyListener.enable()
selfCheckin = SelfCheckinService()
userSecrectsConsistencyChecker = UserSecretsConsistencyChecker(userKeysBundle: userKeysBundle,
traceIdService: traceIdService,
userService: userService,
lucaPreferences: LucaPreferences.shared,
dailyKeyHandler: dailyKeyRepoHandler)
accessedTracesChecker = AccessedTraceIdChecker(
backend: backendMiscV3,
traceInfoRepo: traceInfoRepo,
healthDepartmentRepo: healthDepartmentRepo, accessedTraceIdRepo: accessedTraceIdRepo)
baerCodeKeyService = BaerCodeKeyService(preferences: LucaPreferences.shared)
notificationService = NotificationService(traceIdService: traceIdService, autoCheckoutService: autoCheckoutService)
notificationService.enable()
setupDocuments()
personService = PersonService(personRepo: personRepo, documentProcessing: documentProcessingService)
isSetup = true
}
private func disableAllServices() {
if !isSetup {
return
}
locationUpdater.stop()
autoCheckoutService.disable()
historyListener.disable()
notificationService.disable()
accessedTracesChecker.disposeNotificationOnMatch()
notificationService.removePendingNotifications()
}
// swiftlint:disable:next function_body_length
func setupRepos() throws {
var currentKey: Data! = localDBKeyRepository.retrieveKey()
let keyWasAvailable = currentKey != nil
if !keyWasAvailable {
self.log("No DB Key found, generating one...")
guard let bytes = KeyFactory.randomBytes(size: 64) else {
throw NSError(domain: "Couldn't generate random bytes for local DB key", code: 0, userInfo: nil)
}
if !localDBKeyRepository.store(key: bytes, removeIfExists: true) {
throw NSError(domain: "Couldn't store local DB key", code: 0, userInfo: nil)
}
currentKey = bytes
self.log("DB Key generated and stored succesfully.")
}
traceInfoRepo = TraceInfoRepo(key: currentKey)
accessedTraceIdRepo = AccessedTraceIdRepo(key: currentKey)
traceIdCoreRepo = TraceIdCoreRepo(key: currentKey)
locationRepo = LocationRepo(key: currentKey)
historyRepo = HistoryRepo(key: currentKey)
keyValueRepo = RealmKeyValueRepo(key: currentKey)
healthDepartmentRepo = HealthDepartmentRepo(key: currentKey)
documentRepo = DocumentRepo(key: currentKey)
testProviderKeyRepo = TestProviderKeyRepo(key: currentKey)
personRepo = PersonRepo(key: currentKey)
realmDatabaseUtils = [
traceInfoRepo,
accessedTraceIdRepo,
traceIdCoreRepo,
locationRepo,
historyRepo,
keyValueRepo,
healthDepartmentRepo,
documentRepo,
testProviderKeyRepo,
personRepo
]
if !keyWasAvailable {
self.log("Applying new key to the repos")
let changeEncryptionCompletables = self.realmDatabaseUtils
.map { $0.changeEncryptionSettings(oldKey: nil, newKey: currentKey)
.logError(self, "\(String(describing: $0.self)): Changing encryption")
}
let array = try Completable.zip(changeEncryptionCompletables)
.debug("KT TOTAL")
.do(onError: { error in
fatalError("failed to change encryption settings. Error: \(error)")
})
.toBlocking() // This blocking is crucial here. I want to block the app until the settings are done.
.toArray()
self.log("New keys applied successfully")
print(array)
}
}
private func setupDocuments() {
documentKeyProvider = DocumentKeyProvider(backend: backendMiscV3, testProviderKeyRepo: testProviderKeyRepo)
documentFactory = DocumentFactory()
// documentFactory.register(parser: UbirchParser())
documentFactory.register(parser: DGCParser())
documentFactory.register(parser: AppointmentParser())
documentFactory.register(parser: DefaultJWTParser(keyProvider: documentKeyProvider))
documentFactory.register(parser: JWTParserWithOptionalDoctor(keyProvider: documentKeyProvider))
documentFactory.register(parser: BaerCodeParser())
documentRepoService = DocumentRepoService(documentRepo: documentRepo, documentFactory: documentFactory)
documentUniquenessChecker = DocumentUniquenessChecker(backend: backendMiscV3, keyValueRepo: keyValueRepo)
documentProcessingService = DocumentProcessingService(
documentRepoService: documentRepoService,
documentFactory: documentFactory,
uniquenessChecker: documentUniquenessChecker)
// Document validators
documentProcessingService.register(validator: CoronaTestIsNotInFutureValidator())
documentProcessingService.register(validator: CoronaTestIsNegativeValidator())
documentProcessingService.register(validator: DGCIssuerValidator())
#if !DEVELOPMENT
let usersIdentityValidator = DocumentOwnershipValidator(
firstNameSource: Single.from { LucaPreferences.shared.firstName ?? "" },
lastNameSource: Single.from { LucaPreferences.shared.lastName ?? "" }
)
documentProcessingService.register(validator: UserOrChildValidator(
userIdentityValidator: usersIdentityValidator,
personsSource: personRepo.restore())
)
#endif
#if PREPROD || PRODUCTION
documentProcessingService.register(validator: CoronaTestValidityValidator())
documentProcessingService.register(validator: RecoveryValidityValidator())
documentProcessingService.register(validator: AppointmentValidityValidator())
#endif
qrProcessingService = QRProcessingService(documentProcessingService: documentProcessingService, documentFactory: documentFactory, selfCheckinService: selfCheckin)
}
}
extension ServiceContainer: UnsafeAddress, LogUtil {}
| 43.032353 | 170 | 0.688128 |
72e2bf1e97787a7b1f4d221618d1dee1aff005dd | 638 | //
// Movie.swift
// MovieBrowser
//
// Created by Jeet on 13/02/18.
// Copyright © 2018 Jeet Gandhi. All rights reserved.
//
import UIKit
struct Movie: Codable {
var posterPath: String?
var adult: Bool?
var overview: String?
var releaseDate: String?
var genreIds: [Int]?
var id: Int?
var originalTitle: String?
var originalLanguage: String?
var title: String?
var backdropPath: String?
var popularity: Double?
var voteCount: Int?
var video: Bool?
var voteAverage: Double?
}
enum MoviesSort {
case getMoviesByPopularity
case getMoviesByTopRatings
}
| 16.789474 | 54 | 0.648903 |
62f055144578443a527ddfec42d6b702ba0ed9ef | 1,953 | //
// ViewController.swift
// LottieRefresh
//
// Created by vvveiii on 2019/3/30.
// Copyright © 2019 lvv. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var tableView: LOTTableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Refresh", style: .plain, target: self, action: #selector(testRefresh(sender:)))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "WebView", style: .plain, target: self, action: #selector(testWebView(sender:)))
tableView = LOTTableView(frame: self.view.bounds, style: .plain)
tableView.addRefresh { (completion) -> Void in
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
completion()
})
}
self.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints([
NSLayoutConstraint(item: tableView!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView!, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView!, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView!, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0)
])
}
@objc func testRefresh(sender: UIBarButtonItem) {
tableView.SFrefreshView?.startRefresh()
}
@objc func testWebView(sender: UIBarButtonItem) {
self.navigationController?.pushViewController(WKWebViewController(), animated: true)
}
}
| 41.553191 | 155 | 0.676395 |
919bb53913a8cd736ae60ca1bd8c57f11f0c6918 | 6,745 | import Cocoa
import FlutterMacOS
public class WindowManagerPlugin: NSObject, FlutterPlugin {
public static var RegisterGeneratedPlugins:((FlutterPluginRegistry) -> Void)?
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "window_manager", binaryMessenger: registrar.messenger)
let instance = WindowManagerPlugin(registrar, channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}
private var registrar: FlutterPluginRegistrar!;
private var channel: FlutterMethodChannel!
private var mainWindow: NSWindow {
get {
return (self.registrar.view?.window)!;
}
}
private var _inited: Bool = false
private var windowManager: WindowManager = WindowManager()
public init(_ registrar: FlutterPluginRegistrar, _ channel: FlutterMethodChannel) {
super.init()
self.registrar = registrar
self.channel = channel
}
private func ensureInitialized() {
if (!_inited) {
windowManager.mainWindow = mainWindow
windowManager.onEvent = {
(eventName: String) in
self._emitEvent(eventName)
}
_inited = true
}
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let methodName: String = call.method
let args: [String: Any] = call.arguments as? [String: Any] ?? [:]
switch (methodName) {
case "ensureInitialized":
ensureInitialized()
result(true)
break
case "waitUntilReadyToShow":
windowManager.waitUntilReadyToShow()
result(true)
break
case "setAsFrameless":
windowManager.setAsFrameless()
result(true)
break
case "focus":
windowManager.focus()
result(true)
break
case "blur":
windowManager.blur()
result(true)
break
case "show":
windowManager.show()
result(true)
break
case "hide":
windowManager.hide()
result(true)
break
case "isVisible":
result(windowManager.isVisible())
break
case "isMaximized":
result(windowManager.isMaximized())
break
case "maximize":
windowManager.maximize()
result(true)
break
case "unmaximize":
windowManager.unmaximize()
result(true)
break
case "isMinimized":
result(windowManager.isMinimized())
break
case "minimize":
windowManager.minimize()
result(true)
break
case "restore":
windowManager.restore()
result(true)
break
case "isFullScreen":
result(windowManager.isFullScreen())
break
case "setFullScreen":
windowManager.setFullScreen(args)
result(true)
break
case "setBackgroundColor":
windowManager.setBackgroundColor(args)
result(true)
break
case "getPosition":
result(windowManager.getPosition())
break
case "setPosition":
windowManager.setPosition(args)
result(true)
break
case "getSize":
result(windowManager.getSize())
break
case "setSize":
windowManager.setSize(args)
result(true)
break
case "setMinimumSize":
windowManager.setMinimumSize(args)
result(true)
break
case "setMaximumSize":
windowManager.setMaximumSize(args)
result(true)
break
case "isResizable":
result(windowManager.isResizable())
break
case "setResizable":
windowManager.setResizable(args)
result(true)
break
case "isMovable":
result(windowManager.isMovable())
break
case "setMovable":
windowManager.setMovable(args)
result(true)
break
case "isMinimizable":
result(windowManager.isMinimizable())
break
case "setMinimizable":
windowManager.setMinimizable(args)
result(true)
break
case "isClosable":
result(windowManager.isClosable())
break
case "setClosable":
windowManager.setClosable(args)
result(true)
break
case "isAlwaysOnTop":
result(windowManager.isAlwaysOnTop())
break
case "setAlwaysOnTop":
windowManager.setAlwaysOnTop(args)
result(true)
break
case "getTitle":
result(windowManager.getTitle())
break
case "setTitle":
windowManager.setTitle(args)
result(true)
break
case "setTitleBarStyle":
windowManager.setTitleBarStyle(args)
result(true)
break
case "getTitleBarHeight":
result(windowManager.getTitleBarHeight())
break
case "setSkipTaskbar":
windowManager.setSkipTaskbar(args)
result(true)
break
case "setProgressBar":
windowManager.setProgressBar(args)
result(true)
break
case "hasShadow":
result(windowManager.hasShadow())
break
case "setHasShadow":
windowManager.setHasShadow(args)
result(true)
break
case "getOpacity":
result(windowManager.getOpacity())
break
case "setOpacity":
windowManager.setOpacity(args)
result(true)
break
case "startDragging":
windowManager.startDragging()
result(true)
break
case "isSubWindow":
result(windowManager.isSubWindow())
break
case "createSubWindow":
windowManager.createSubWindow(args);
result(true)
default:
result(FlutterMethodNotImplemented)
}
}
public func _emitEvent(_ eventName: String) {
let args: NSDictionary = [
"eventName": eventName,
]
channel.invokeMethod("onEvent", arguments: args, result: nil)
}
}
| 29.845133 | 104 | 0.541735 |
16ea2e20041b8e3d6f0781854b033f1eb6523258 | 3,952 | //
// CheckView.swift
// piwallet
//
// Created by Adrian Corscadden on 2016-11-22.
// Copyright © 2016 piwallet LLC. All rights reserved.
//
import UIKit
class CheckView : UIView, AnimatableIcon {
public func animate() {
let check = UIBezierPath()
check.move(to: CGPoint(x: 32.5, y: 47.0))
check.addLine(to: CGPoint(x: 43.0, y: 57.0))
check.addLine(to: CGPoint(x: 63, y: 37.4))
let shape = CAShapeLayer()
shape.path = check.cgPath
shape.lineWidth = 9.0
shape.strokeColor = UIColor.white.cgColor
shape.fillColor = UIColor.clear.cgColor
shape.strokeStart = 0.0
shape.strokeEnd = 0.0
shape.lineCap = "round"
shape.lineJoin = "round"
layer.addSublayer(shape)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.toValue = 1.0
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
animation.duration = 0.3
shape.add(animation, forKey: nil)
}
override func draw(_ rect: CGRect) {
let checkcircle = UIBezierPath()
checkcircle.move(to: CGPoint(x: 47.76, y: -0))
checkcircle.addCurve(to: CGPoint(x: 0, y: 47.76), controlPoint1: CGPoint(x: 21.38, y: -0), controlPoint2: CGPoint(x: 0, y: 21.38))
checkcircle.addCurve(to: CGPoint(x: 47.76, y: 95.52), controlPoint1: CGPoint(x: 0, y: 74.13), controlPoint2: CGPoint(x: 21.38, y: 95.52))
checkcircle.addCurve(to: CGPoint(x: 95.52, y: 47.76), controlPoint1: CGPoint(x: 74.14, y: 95.52), controlPoint2: CGPoint(x: 95.52, y: 74.13))
checkcircle.addCurve(to: CGPoint(x: 47.76, y: -0), controlPoint1: CGPoint(x: 95.52, y: 21.38), controlPoint2: CGPoint(x: 74.14, y: -0))
checkcircle.addLine(to: CGPoint(x: 47.76, y: -0))
checkcircle.close()
checkcircle.move(to: CGPoint(x: 47.99, y: 85.97))
checkcircle.addCurve(to: CGPoint(x: 9.79, y: 47.76), controlPoint1: CGPoint(x: 26.89, y: 85.97), controlPoint2: CGPoint(x: 9.79, y: 68.86))
checkcircle.addCurve(to: CGPoint(x: 47.99, y: 9.55), controlPoint1: CGPoint(x: 9.79, y: 26.66), controlPoint2: CGPoint(x: 26.89, y: 9.55))
checkcircle.addCurve(to: CGPoint(x: 86.2, y: 47.76), controlPoint1: CGPoint(x: 69.1, y: 9.55), controlPoint2: CGPoint(x: 86.2, y: 26.66))
checkcircle.addCurve(to: CGPoint(x: 47.99, y: 85.97), controlPoint1: CGPoint(x: 86.2, y: 68.86), controlPoint2: CGPoint(x: 69.1, y: 85.97))
checkcircle.close()
UIColor.white.setFill()
checkcircle.fill()
//This is the non-animated check left here for now as a reference
// let check = UIBezierPath()
// check.move(to: CGPoint(x: 30.06, y: 51.34))
// check.addCurve(to: CGPoint(x: 30.06, y: 44.75), controlPoint1: CGPoint(x: 28.19, y: 49.52), controlPoint2: CGPoint(x: 28.19, y: 46.57))
// check.addCurve(to: CGPoint(x: 36.9, y: 44.69), controlPoint1: CGPoint(x: 32, y: 42.87), controlPoint2: CGPoint(x: 35.03, y: 42.87))
// check.addLine(to: CGPoint(x: 42.67, y: 50.3))
// check.addLine(to: CGPoint(x: 58.62, y: 34.79))
// check.addCurve(to: CGPoint(x: 65.39, y: 34.8), controlPoint1: CGPoint(x: 60.49, y: 32.98), controlPoint2: CGPoint(x: 63.53, y: 32.98))
// check.addCurve(to: CGPoint(x: 65.46, y: 41.45), controlPoint1: CGPoint(x: 67.33, y: 36.68), controlPoint2: CGPoint(x: 67.33, y: 39.63))
// check.addLine(to: CGPoint(x: 45.33, y: 61.02))
// check.addCurve(to: CGPoint(x: 40.01, y: 61.02), controlPoint1: CGPoint(x: 43.86, y: 62.44), controlPoint2: CGPoint(x: 41.48, y: 62.44))
// check.addLine(to: CGPoint(x: 30.06, y: 51.34))
// check.close()
// check.move(to: CGPoint(x: 30.06, y: 51.34))
//
// UIColor.green.setFill()
// check.fill()
}
}
| 50.025316 | 149 | 0.619686 |
f402b753d6e3f3a42624b25957cbc2359cfdf564 | 14,960 | //
// TextBlockAttributeTests.swift
// ProtonTests
//
// Created by Rajdeep Kwatra on 3/5/20.
// Copyright © 2020 Rajdeep Kwatra. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import XCTest
import UIKit
@testable import Proton
class TextBlockAttributeTests: XCTestCase {
func testSetsFocusAfterForNonFocusableText() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = .zero
let range = NSRange(location: 5, length: 0).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 8, length: 0))
}
func testSetsFocusBeforeForNonFocusableText() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 9, length: 0)
let range = NSRange(location: 6, length: 0).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 4, length: 0))
}
func testMaintainsNonTextBlockRangeSelectionWithShiftSelectionInReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 8, length: 2)
let range = NSRange(location: 7, length: 3).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 4, length: 6))
}
func testMaintainsNonTextBlockRangeSelectionWithShiftSelectionInForward() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 2, length: 1)
let range = NSRange(location: 2, length: 4).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 2, length: 6))
}
func testRangeSelectionReverseForTextBlock() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string with attribute")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.addAttributes([.textBlock: true], range: NSRange(location: 13, length: 6)) // string
textView.selectedRange = NSRange(location: 12, length: 1) // space between test and string
textView.selectedTextRange = NSRange(location: 11, length: 2).toTextRange(textInput: textView) // t (ending of test) and space
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 8, length: 5)) // "test " test and following space
}
func testRangeSelectionReverseForMultipleTextBlock() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string with attribute")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.addAttributes([.textBlock: true], range: NSRange(location: 13, length: 6)) // string
textView.selectedRange = NSRange(location: 12, length: 7) // " string" space followed by string
textView.selectedTextRange = NSRange(location: 11, length: 8).toTextRange(textInput: textView) // "t string" t (ending of test), space and string
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 8, length: 11)) // "test string" test, space and string
}
func testRangeSelectionForwardForMultipleTextBlock() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string with attribute")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.addAttributes([.textBlock: true], range: NSRange(location: 13, length: 6)) // string
textView.selectedRange = NSRange(location: 12, length: 1) // space between test and string
textView.selectedTextRange = NSRange(location: 12, length: 2).toTextRange(textInput: textView) //" s" space and (starting of string)
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 12, length: 7)) // " string" test and following space
}
func testSelectionWithTextBlocksWithNonTextBlockInMiddle() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string with attribute")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.addAttributes([.textBlock: true], range: NSRange(location: 13, length: 6)) // string
textView.selectedRange = NSRange(location: 8, length: 5) // " string" space followed by string
textView.selectedTextRange = NSRange(location: 8, length: 6).toTextRange(textInput: textView) // "test s" test followed by space and s of string
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 8, length: 11)) // "test string" test, space and string
}
func testUnselectingSelectedMultipleTextBlockMovingLocationForward() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string with attribute")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.addAttributes([.textBlock: true], range: NSRange(location: 13, length: 6)) // string
textView.selectedRange = NSRange(location: 8, length: 11) // "test string" test, space and string
textView.selectedTextRange = NSRange(location: 9, length: 10).toTextRange(textInput: textView) // "est string"
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 12, length: 7))
}
func testUnselectsSelectedTextBlockForward() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.selectedRange = NSRange(location: 8, length: 4) // "test"
textView.selectedTextRange = NSRange(location: 9, length: 3).toTextRange(textInput: textView) // "est"
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 12, length: 0))
}
func testUnselectsSelectedTextBlockReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.selectedRange = NSRange(location: 8, length: 4) // "test"
textView.selectedTextRange = NSRange(location: 8, length: 3).toTextRange(textInput: textView) // "tes"
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 8, length: 0))
}
func testUnselectsTextSelectedWithTextBlockReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "This is test string")
textView.attributedText = text
textView.addAttributes([.textBlock: true], range: NSRange(location: 8, length: 4)) // test
textView.selectedRange = NSRange(location: 7, length: 5) // " test"
textView.selectedTextRange = NSRange(location: 8, length: 4).toTextRange(textInput: textView) // "test"
let range = textView.selectedRange
XCTAssertEqual(range, NSRange(location: 8, length: 4))
}
func testSelectsTextBlockForward() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 4, length: 0)
let range = NSRange(location: 4, length: 1).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 4, length: 4))
}
func testSelectsTextBlockReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 8, length: 0)
let range = NSRange(location: 7, length: 1).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 4, length: 4))
}
func testUnselectsTextBlockWithOtherTextReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 3, length: 5)
let range = NSRange(location: 3, length: 4).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 3, length: 1))
}
func testUnselectsTextWithBlockSelectedReverse() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 4, length: 5)
let range = NSRange(location: 4, length: 4).toTextRange(textInput: textView)
textView.selectedTextRange = range
XCTAssertEqual(textView.selectedRange, NSRange(location: 4, length: 4))
}
func testDeleteBackwardsDefault() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 2, length: 0)
textView.deleteBackward()
XCTAssertEqual(textView.attributedText.string, "0234567890")
}
func testDeleteBackwardsOnTextBlock() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 8, length: 0)
textView.deleteBackward()
XCTAssertEqual(textView.attributedText.string, "0123890")
}
func testDeleteBackwardsOnTextBlockWithSameAttributeValues() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890", attributes: [.textBlock: true]))
textView.attributedText = text
textView.selectedRange = NSRange(location: 11, length: 0)
textView.deleteBackward()
XCTAssertEqual(textView.attributedText.string, "0123")
}
func testDeleteBackwardsOnTextBlockWithDifferentAttributeValues() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: UUID().uuidString]))
text.append(NSAttributedString(string: "890", attributes: [.textBlock: UUID().uuidString]))
textView.attributedText = text
textView.selectedRange = NSRange(location: 11, length: 0)
textView.deleteBackward()
XCTAssertEqual(textView.attributedText.string, "01234567")
}
func testDeleteBackwardsOnTextBlockWithSelection() {
let textView = RichTextView(context: RichTextViewContext())
let text = NSMutableAttributedString(string: "0123")
text.append(NSAttributedString(string: "4567", attributes: [.textBlock: true]))
text.append(NSAttributedString(string: "890"))
textView.attributedText = text
textView.selectedRange = NSRange(location: 4, length: 6)
textView.deleteBackward()
XCTAssertEqual(textView.attributedText.string, "01230")
}
}
| 49.700997 | 153 | 0.699398 |
0e7528aa5875591daeb3cf5f489f53cf8331ed38 | 1,596 |
/*:
# 228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
**Implement below function**
func summaryRanges(_ nums: [Int]) -> [String] {
}
*/
/*:
**Time Complexity:** O(n)
**Space Complexity:** O(n)
*/
class Solution {
func summaryRanges(_ nums: [Int]) -> [String] {
let n = nums.count
var i = 0
var result: [String] = []
while i < n {
var j = 1
while i + j < n && nums[i + j] - nums[i] == j {
j += 1
}
if j == 1 {
result.append("\(nums[i])")
} else {
result.append("\(nums[i])->\(nums[i + j - 1])")
}
i = i + j
}
return result
}
}
/*:
## Test
*/
import XCTest
class TestSummaryRanges: XCTestCase {
func testSummaryRanges1() {
let input = [0, 1, 2, 4, 5, 7]
let output = ["0->2", "4->5", "7"]
let solution = Solution()
let result = solution.summaryRanges(input)
XCTAssertEqual(result, output)
}
func testSummaryRanges2() {
let input = [0, 2, 3, 4, 6, 8, 9]
let output = ["0", "2->4", "6", "8->9"]
let solution = Solution()
let result = solution.summaryRanges(input)
XCTAssertEqual(result, output)
}
}
TestSummaryRanges.defaultTestSuite.run()
| 17.347826 | 83 | 0.54198 |
0a11d4e3768801b36e5aa81d1919202a8787c5f6 | 587 | //
// Day+CoreDataProperties.swift
// travel-weather
//
// Created by Renee Sajedian on 5/6/20.
// Copyright © 2020 Renee Sajedian. All rights reserved.
//
//
import Foundation
import CoreData
extension Day {
@nonobjc public class func dayFetchRequest() -> NSFetchRequest<Day> {
return NSFetchRequest<Day>(entityName: "Day")
}
@NSManaged public var date: Date
@NSManaged public var weatherDataDate: Date?
@NSManaged public var locationWasSet: Bool
@NSManaged public var weatherSummaryValue: String?
@NSManaged public var location: Location
}
| 22.576923 | 73 | 0.712095 |
e43d509d2ce6c012c2699e955c5546043980dfe8 | 1,819 | /*:
## Exercise: Treehouse Pulley
In this exercise, you're using code to decide whether it's safe to add items to a basket that will be delivered to your treehouse by a pulley.
- callout(Exercise):
Create three constants for items of different weights that you'd like to bring up to your fort: one less than 100, one between 100 and 1000, and one over 1000.
*/
let chair: Int = 98
let wood: Int = 500
let ceiling: Int = 1002
/*:
- callout(Exercise):
A lightweight treehouse pulley is already created below. But you've decided that you want to be able to lift, say, a small horse or piano up to your fort, so you’re installing a second pulley with a much bigger basket.\
Create a second pulley that has a higher capacity and can hold at least ten times the weight of the `ricketyRope`.
*/
let ricketyRope = TreehousePulley(weightCapacity: 200)
let betterRope = TreehousePulley(weightCapacity: 2000)
let superHeavyDutyPulley = TreehousePulley(weightCapacity: 10000)
let betterRopes = TreehousePulley(weightCapacity: 400000)
betterRope.canHandleAdditionalLoad(chair)
ricketyRope.canHandleAdditionalLoad(wood)
superHeavyDutyPulley.canHandleAdditionalLoad(ceiling)
/*:
- callout(Exercise):
Use the `TreehousePulley` type's `addLoadToBasket` method to add the items you defined above. Add three of the lightest item, two of the middle-weight item, and one of the heaviest item. Add the items to the lightweight pulley first, using the `canHandleAdditionalLoad` method to check whether the item would overload the pulley, then move on to your stronger pulley when the first is fully loaded.\
If your pulleys together aren't enough to hold all the items you need, create a third super heavy-duty pulley to finish the job.
[Previous](@previous) | page 16 of 17 | [Next: Exercise: Identity](@next)
*/
| 49.162162 | 400 | 0.773502 |
799fe8b49f9ed85d694c7cbbcc37c15a38af424d | 11,284 | //
// ZIPFoundationReadingTests.swift
// ZIPFoundation
//
// Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import XCTest
@testable import ZIPFoundation
extension ZIPFoundationTests {
func testExtractUncompressedFolderEntries() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
// Test extracting to memory
var checksum = try archive.extract(entry, bufferSize: 32, consumer: { _ in })
XCTAssert(entry.checksum == checksum)
// Test extracting to file
var fileURL = self.createDirectory(for: #function)
fileURL.appendPathComponent(entry.path)
checksum = try archive.extract(entry, to: fileURL)
XCTAssert(entry.checksum == checksum)
let fileManager = FileManager()
XCTAssertTrue(fileManager.itemExists(at: fileURL))
if entry.type == .file {
let fileData = try Data(contentsOf: fileURL)
let checksum = fileData.crc32(checksum: 0)
XCTAssert(checksum == entry.checksum)
}
} catch {
XCTFail("Failed to unzip uncompressed folder entries")
}
}
}
func testExtractCompressedFolderEntries() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
// Test extracting to memory
var checksum = try archive.extract(entry, bufferSize: 128, consumer: { _ in })
XCTAssert(entry.checksum == checksum)
// Test extracting to file
var fileURL = self.createDirectory(for: #function)
fileURL.appendPathComponent(entry.path)
checksum = try archive.extract(entry, to: fileURL)
XCTAssert(entry.checksum == checksum)
let fileManager = FileManager()
XCTAssertTrue(fileManager.itemExists(at: fileURL))
if entry.type != .directory {
let fileData = try Data(contentsOf: fileURL)
let checksum = fileData.crc32(checksum: 0)
XCTAssert(checksum == entry.checksum)
}
} catch {
XCTFail("Failed to unzip compressed folder entries")
}
}
}
func testExtractUncompressedDataDescriptorArchive() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
let checksum = try archive.extract(entry, consumer: { _ in })
XCTAssert(entry.checksum == checksum)
} catch {
XCTFail("Failed to unzip data descriptor archive")
}
}
}
func testExtractCompressedDataDescriptorArchive() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
let checksum = try archive.extract(entry, consumer: { _ in })
XCTAssert(entry.checksum == checksum)
} catch {
XCTFail("Failed to unzip data descriptor archive")
}
}
}
func testExtractPreferredEncoding() {
let encoding = String.Encoding.utf8
let archive = self.archive(for: #function, mode: .read, preferredEncoding: encoding)
XCTAssertTrue(archive.checkIntegrity())
let imageEntry = archive["data/pic👨👩👧👦🎂.jpg"]
XCTAssertNotNil(imageEntry)
let textEntry = archive["data/Benoît.txt"]
XCTAssertNotNil(textEntry)
}
func testExtractMSDOSArchive() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
let checksum = try archive.extract(entry, consumer: { _ in })
XCTAssert(entry.checksum == checksum)
} catch {
XCTFail("Failed to unzip MSDOS archive")
}
}
}
func testExtractErrorConditions() {
let archive = self.archive(for: #function, mode: .read)
XCTAssertNotNil(archive)
guard let fileEntry = archive["testZipItem.png"] else {
XCTFail("Failed to obtain test asset from archive.")
return
}
XCTAssertNotNil(fileEntry)
do {
_ = try archive.extract(fileEntry, to: archive.url)
} catch let error as CocoaError {
XCTAssert(error.code == CocoaError.fileWriteFileExists)
} catch {
XCTFail("Unexpected error while trying to extract entry to existing URL.")
return
}
guard let linkEntry = archive["testZipItemLink"] else {
XCTFail("Failed to obtain test asset from archive.")
return
}
do {
let longFileName = String(repeating: ProcessInfo.processInfo.globallyUniqueString, count: 100)
var overlongURL = URL(fileURLWithPath: NSTemporaryDirectory())
overlongURL.appendPathComponent(longFileName)
_ = try archive.extract(fileEntry, to: overlongURL)
} catch let error as CocoaError {
XCTAssert(error.code == CocoaError.fileNoSuchFile)
} catch {
XCTFail("Unexpected error while trying to extract entry to invalid URL.")
return
}
XCTAssertNotNil(linkEntry)
do {
_ = try archive.extract(linkEntry, to: archive.url)
} catch let error as CocoaError {
XCTAssert(error.code == CocoaError.fileWriteFileExists)
} catch {
XCTFail("Unexpected error while trying to extract link entry to existing URL.")
return
}
}
func testCorruptFileErrorConditions() {
let archiveURL = self.resourceURL(for: #function, pathExtension: "zip")
let fileManager = FileManager()
let destinationFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: archiveURL.path)
let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationFileSystemRepresentation, "r+b")
do {
fseek(destinationFile, 64, SEEK_SET)
// We have to inject a large enough zeroes block to guarantee that libcompression
// detects the failure when reading the stream
_ = try Data.write(chunk: Data(count: 512*1024), to: destinationFile)
fclose(destinationFile)
guard let archive = Archive(url: archiveURL, accessMode: .read) else {
XCTFail("Failed to read archive.")
return
}
guard let entry = archive["data.random"] else {
XCTFail("Failed to read entry.")
return
}
_ = try archive.extract(entry, consumer: { _ in })
} catch let error as Data.CompressionError {
XCTAssert(error == Data.CompressionError.corruptedData)
} catch {
XCTFail("Unexpected error while testing an archive with corrupt entry data.")
}
}
func testCorruptSymbolicLinkErrorConditions() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
var tempFileURL = URL(fileURLWithPath: NSTemporaryDirectory())
tempFileURL.appendPathComponent(ProcessInfo.processInfo.globallyUniqueString)
_ = try archive.extract(entry, to: tempFileURL)
} catch let error as Archive.ArchiveError {
XCTAssert(error == .invalidEntryPath)
} catch {
XCTFail("Unexpected error while trying to extract entry with invalid symbolic link.")
}
}
}
func testInvalidCompressionMethodErrorConditions() {
let archive = self.archive(for: #function, mode: .read)
for entry in archive {
do {
_ = try archive.extract(entry, consumer: { (_) in })
} catch let error as Archive.ArchiveError {
XCTAssert(error == .invalidCompressionMethod)
} catch {
XCTFail("Unexpected error while trying to extract entry with invalid compression method link.")
}
}
}
func testExtractZIP64ArchiveErrorConditions() {
let archive = self.archive(for: #function, mode: .read)
var entriesRead = 0
for _ in archive {
entriesRead += 1
}
// We currently don't support ZIP64 so we expect failed initialization for entry objects.
XCTAssert(entriesRead == 0)
}
func testExtractEncryptedArchiveErrorConditions() {
let archive = self.archive(for: #function, mode: .read)
var entriesRead = 0
for _ in archive {
entriesRead += 1
}
// We currently don't support encryption so we expect failed initialization for entry objects.
XCTAssert(entriesRead == 0)
}
func testExtractUncompressedEntryCancelation() {
let archive = self.archive(for: #function, mode: .read)
guard let entry = archive["original"] else { XCTFail("Failed to extract entry."); return }
let progress = archive.makeProgressForReading(entry)
do {
var readCount = 0
_ = try archive.extract(entry, bufferSize: 1, progress: progress) { (data) in
readCount += data.count
if readCount == 4 { progress.cancel() }
}
} catch let error as Archive.ArchiveError {
XCTAssert(error == Archive.ArchiveError.cancelledOperation)
XCTAssertEqual(progress.fractionCompleted, 0.5, accuracy: .ulpOfOne)
} catch {
XCTFail("Unexpected error while trying to cancel extraction.")
}
}
func testExtractCompressedEntryCancelation() {
let archive = self.archive(for: #function, mode: .read)
guard let entry = archive["random"] else { XCTFail("Failed to extract entry."); return }
let progress = archive.makeProgressForReading(entry)
do {
var readCount = 0
_ = try archive.extract(entry, bufferSize: 256, progress: progress) { (data) in
readCount += data.count
if readCount == 512 { progress.cancel() }
}
} catch let error as Archive.ArchiveError {
XCTAssert(error == Archive.ArchiveError.cancelledOperation)
XCTAssertEqual(progress.fractionCompleted, 0.5, accuracy: .ulpOfOne)
} catch {
XCTFail("Unexpected error while trying to cancel extraction.")
}
}
func testProgressHelpers() {
let tempPath = NSTemporaryDirectory()
var nonExistantURL = URL(fileURLWithPath: tempPath)
nonExistantURL.appendPathComponent("invalid.path")
let archive = self.archive(for: #function, mode: .update)
XCTAssert(archive.totalUnitCountForAddingItem(at: nonExistantURL) == -1)
}
}
| 41.333333 | 113 | 0.592698 |
291757215f3593a377ddfae61a4d6f2872fa8de2 | 2,161 | //
// AppDelegate.swift
// TestMVVM
//
// Created by 土老帽 on 2018/1/16.
// Copyright © 2018年 DPRuin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.978723 | 285 | 0.754743 |
ed5545e46109cbc3a05f1bf2e8b4953047624cd0 | 1,675 | //
// LocationInputActivationView.swift
// UberProject
//
// Created by 윤병일 on 2021/08/09.
//
import UIKit
protocol LocationInputActivationViewDelegate : AnyObject {
func presentLocationInputView()
}
class LocationInputActivationView : UIView {
//MARK: - Properties
weak var delegate : LocationInputActivationViewDelegate?
private let indicatorView : UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
private let placeholderLabel : UILabel = {
let label = UILabel()
label.text = "Where to?"
label.font = UIFont.systemFont(ofSize: 18)
label.textColor = .darkGray
return label
}()
//MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
addTapGesture()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Function
private func configureUI() {
backgroundColor = .white
addShadow()
[indicatorView, placeholderLabel].forEach {
addSubview($0)
}
indicatorView.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.leading.equalToSuperview().offset(16)
$0.width.height.equalTo(6)
}
placeholderLabel.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.leading.equalTo(indicatorView.snp.trailing).offset(20)
}
}
private func addTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(presentLocationInputView))
addGestureRecognizer(tap)
}
//MARK: - @objc func
@objc func presentLocationInputView() {
delegate?.presentLocationInputView()
}
}
| 22.333333 | 95 | 0.670448 |
3906434d7fc625df622049865408922bab64c9a0 | 2,177 | //
// AppDelegate.swift
// HeatMap
//
// Created by amirhoseinmrn on 06/01/2021.
// Copyright (c) 2021 amirhoseinmrn. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.319149 | 285 | 0.755168 |
50db5ffdcf0fcad731a4bb951db97af6e9bc03a4 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol B{
struct B<l:b
class B:A
typealias b:e
var e:b
protocol A:B | 23.8 | 87 | 0.764706 |
cce809ae775a7c1a9ddd139c8e1ec4704a6e09fe | 5,560 | //
// MySQLSessions.swift
// Perfect-Session-MySQLQL
//
// Created by Jonathan Guthrie on 2016-12-19.
//
//
import Foundation
import PerfectMySQL
import PerfectSession
import PerfectHTTP
import PerfectLib
public struct MySQLSessionConnector {
public static var host: String = "localhost"
public static var socket: String = ""
public static var username: String = ""
public static var password: String = ""
public static var database: String = "perfect_sessions"
public static var table: String = "sessions"
public static var port: Int = 5432
private init(){}
}
public struct MySQLSessions {
/// Initializes the Session Manager. No config needed!
public init() {}
public func clean() {
let stmt = "DELETE FROM \(MySQLSessionConnector.table) WHERE updated + idle < ?"
exec(stmt, params: [Int(Date().timeIntervalSince1970)])
}
public func save(session: PerfectSession) {
var s = session
s.touch()
// perform UPDATE
let stmt = "UPDATE \(MySQLSessionConnector.table) SET userid = ?, updated = ?, idle = ?, data = ? WHERE token = ?"
exec(stmt, params: [
s.userid,
s.updated,
s.idle,
s.tojson(),
s.token
])
}
public func start(_ request: HTTPRequest) -> PerfectSession {
var session = PerfectSession()
session.token = UUID().uuidString
session.ipaddress = request.remoteAddress.host
session.useragent = request.header(.userAgent) ?? "unknown"
session._state = "new"
session.setCSRF()
// perform INSERT
let stmt = "INSERT INTO \(MySQLSessionConnector.table) (token, userid, created, updated, idle, data, ipaddress, useragent) VALUES(?,?,?,?,?,?,?,?)"
exec(stmt, params: [
session.token,
session.userid,
session.created,
session.updated,
session.idle,
session.tojson(),
session.ipaddress,
session.useragent
])
return session
}
/// Deletes the session for a session identifier.
public func destroy(_ request: HTTPRequest, _ response: HTTPResponse) {
let stmt = "DELETE FROM \(MySQLSessionConnector.table) WHERE token = ?"
if let t = request.session?.token {
exec(stmt, params: [t])
}
// Reset cookie to make absolutely sure it does not get recreated in some circumstances.
var domain = ""
if !SessionConfig.cookieDomain.isEmpty {
domain = SessionConfig.cookieDomain
}
response.addCookie(HTTPCookie(
name: SessionConfig.name,
value: "",
domain: domain,
expires: .relativeSeconds(SessionConfig.idle),
path: SessionConfig.cookiePath,
secure: SessionConfig.cookieSecure,
httpOnly: SessionConfig.cookieHTTPOnly,
sameSite: SessionConfig.cookieSameSite
)
)
}
public func resume(token: String) -> PerfectSession {
var session = PerfectSession()
let server = connect()
let params = [token]
let lastStatement = MySQLStmt(server)
let statement = "SELECT token,userid,created, updated, idle, data, ipaddress, useragent FROM \(MySQLSessionConnector.table) WHERE token = ?"
if !lastStatement.prepare(statement: statement) {
Log.error(message: "[MySQLSessions] Failed to prepare statement: \(lastStatement.errorMessage()) while \(statement)")
}
for p in params {
lastStatement.bindParam("\(p)")
}
if !lastStatement.execute() {
Log.error(message: "[MySQLSessions] Failed to execute statement: \(lastStatement.errorMessage()) while \(statement)")
}
let result = lastStatement.results()
_ = result.forEachRow { row in
session.token = row[0] as! String
session.userid = row[1] as! String
session.created = Int(row[2] as! Int32)
session.updated = Int(row[3] as! Int32)
session.idle = Int(row[4] as! Int32)
session.fromjson(row[5] as! String)
session.ipaddress = row[6] as! String
session.useragent = row[7] as! String
}
session._state = "resume"
return session
}
// MySQL Specific:
func connect() -> MySQL {
let server = MySQL()
if MySQLSessionConnector.socket.isEmpty {
let _ = server.connect(
host: MySQLSessionConnector.host,
user: MySQLSessionConnector.username,
password: MySQLSessionConnector.password,
db: MySQLSessionConnector.database,
port: UInt32(MySQLSessionConnector.port)
)
} else {
let _ = server.connect(
user: MySQLSessionConnector.username,
password: MySQLSessionConnector.password,
db: MySQLSessionConnector.database,
socket: MySQLSessionConnector.socket
)
}
// print(server.errorMessage())
return server
}
func setup(){
let stmt = "CREATE TABLE IF NOT EXISTS `\(MySQLSessionConnector.table)` (`token` varchar(255) NOT NULL, `userid` varchar(255), `created` int NOT NULL DEFAULT 0, `updated` int NOT NULL DEFAULT 0, `idle` int NOT NULL DEFAULT 0, `data` text, `ipaddress` varchar(255), `useragent` text, PRIMARY KEY (`token`));"
exec(stmt, params: [])
}
func exec(_ statement: String, params: [Any]) {
let server = connect()
let lastStatement = MySQLStmt(server)
if !lastStatement.prepare(statement: statement) {
Log.error(message: "[MySQLSessions] Failed to prepare statement: \(lastStatement.errorMessage()) while \(statement)")
}
for p in params {
lastStatement.bindParam("\(p)")
}
if !lastStatement.execute() {
Log.error(message: "[MySQLSessions] Failed to execute statement: \(lastStatement.errorMessage()) while \(statement)")
}
let _ = lastStatement.results()
}
func isError(_ errorMsg: String) -> Bool {
if errorMsg.contains(string: "ERROR") {
print(errorMsg)
return true
}
return false
}
}
| 28.659794 | 309 | 0.685791 |
fc0a496d822a634944dac17e9b45bf1d1fb4476e | 6,972 | import Foundation
class PluginMediaStream : NSObject, RTCMediaStreamDelegate {
var rtcMediaStream: RTCMediaStream
var id: String
var audioTracks: [String : PluginMediaStreamTrack] = [:]
var videoTracks: [String : PluginMediaStreamTrack] = [:]
var eventListener: ((data: NSDictionary) -> Void)?
var eventListenerForAddTrack: ((pluginMediaStreamTrack: PluginMediaStreamTrack) -> Void)?
var eventListenerForRemoveTrack: ((id: String) -> Void)?
/**
* Constructor for pc.onaddstream event and getUserMedia().
*/
init(rtcMediaStream: RTCMediaStream) {
NSLog("PluginMediaStream#init()")
self.rtcMediaStream = rtcMediaStream
// ObjC API does not provide id property, so let's set a random one.
self.id = rtcMediaStream.label + "-" + NSUUID().UUIDString
for track: RTCMediaStreamTrack in (self.rtcMediaStream.audioTracks as! Array<RTCMediaStreamTrack>) {
let pluginMediaStreamTrack = PluginMediaStreamTrack(rtcMediaStreamTrack: track)
pluginMediaStreamTrack.run()
self.audioTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
}
for track: RTCMediaStreamTrack in (self.rtcMediaStream.videoTracks as! Array<RTCMediaStreamTrack>) {
let pluginMediaStreamTrack = PluginMediaStreamTrack(rtcMediaStreamTrack: track)
pluginMediaStreamTrack.run()
self.videoTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
}
}
deinit {
NSLog("PluginMediaStream#deinit()")
}
func run() {
NSLog("PluginMediaStream#run()")
self.rtcMediaStream.delegate = self
}
func getJSON() -> NSDictionary {
let json: NSMutableDictionary = [
"id": self.id,
"audioTracks": NSMutableDictionary(),
"videoTracks": NSMutableDictionary()
]
for (id, pluginMediaStreamTrack) in self.audioTracks {
(json["audioTracks"] as! NSMutableDictionary)[id] = pluginMediaStreamTrack.getJSON()
}
for (id, pluginMediaStreamTrack) in self.videoTracks {
(json["videoTracks"] as! NSMutableDictionary)[id] = pluginMediaStreamTrack.getJSON()
}
return json as NSDictionary
}
func setListener(
eventListener: (data: NSDictionary) -> Void,
eventListenerForAddTrack: ((pluginMediaStreamTrack: PluginMediaStreamTrack) -> Void)?,
eventListenerForRemoveTrack: ((id: String) -> Void)?
) {
NSLog("PluginMediaStream#setListener()")
self.eventListener = eventListener
self.eventListenerForAddTrack = eventListenerForAddTrack
self.eventListenerForRemoveTrack = eventListenerForRemoveTrack
}
func addTrack(pluginMediaStreamTrack: PluginMediaStreamTrack) -> Bool {
NSLog("PluginMediaStream#addTrack()")
if pluginMediaStreamTrack.kind == "audio" {
if self.rtcMediaStream.addAudioTrack(pluginMediaStreamTrack.rtcMediaStreamTrack as! RTCAudioTrack) {
NSLog("PluginMediaStream#addTrack() | audio track added")
self.audioTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
return true
} else {
NSLog("PluginMediaStream#addTrack() | ERROR: audio track not added")
return false
}
} else if pluginMediaStreamTrack.kind == "video" {
if self.rtcMediaStream.addVideoTrack(pluginMediaStreamTrack.rtcMediaStreamTrack as! RTCVideoTrack) {
NSLog("PluginMediaStream#addTrack() | video track added")
self.videoTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
return true
} else {
NSLog("PluginMediaStream#addTrack() | ERROR: video track not added")
return false
}
}
return false
}
func removeTrack(pluginMediaStreamTrack: PluginMediaStreamTrack) -> Bool {
NSLog("PluginMediaStream#removeTrack()")
if pluginMediaStreamTrack.kind == "audio" {
self.audioTracks[pluginMediaStreamTrack.id] = nil
if self.rtcMediaStream.removeAudioTrack(pluginMediaStreamTrack.rtcMediaStreamTrack as! RTCAudioTrack) {
NSLog("PluginMediaStream#removeTrack() | audio track removed")
return true
} else {
NSLog("PluginMediaStream#removeTrack() | ERROR: audio track not removed")
return false
}
} else if pluginMediaStreamTrack.kind == "video" {
self.videoTracks[pluginMediaStreamTrack.id] = nil
if self.rtcMediaStream.removeVideoTrack(pluginMediaStreamTrack.rtcMediaStreamTrack as! RTCVideoTrack) {
NSLog("PluginMediaStream#removeTrack() | video track removed")
return true
} else {
NSLog("PluginMediaStream#removeTrack() | ERROR: video track not removed")
return false
}
}
return false
}
/**
* Methods inherited from RTCMediaStreamDelegate.
*/
func OnAddAudioTrack(rtcMediaStream: RTCMediaStream!, track: RTCMediaStreamTrack!) {
NSLog("PluginMediaStream | OnAddAudioTrack [label:%@]", String(track.label))
let pluginMediaStreamTrack = PluginMediaStreamTrack(rtcMediaStreamTrack: track)
pluginMediaStreamTrack.run()
self.audioTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
if self.eventListener != nil {
self.eventListenerForAddTrack!(pluginMediaStreamTrack: pluginMediaStreamTrack)
self.eventListener!(data: [
"type": "addtrack",
"track": pluginMediaStreamTrack.getJSON()
])
}
}
func OnAddVideoTrack(rtcMediaStream: RTCMediaStream!, track: RTCMediaStreamTrack!) {
NSLog("PluginMediaStream | OnAddVideoTrack [label:%@]", String(track.label))
let pluginMediaStreamTrack = PluginMediaStreamTrack(rtcMediaStreamTrack: track)
pluginMediaStreamTrack.run()
self.videoTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
if self.eventListener != nil {
self.eventListenerForAddTrack!(pluginMediaStreamTrack: pluginMediaStreamTrack)
self.eventListener!(data: [
"type": "addtrack",
"track": pluginMediaStreamTrack.getJSON()
])
}
}
func OnRemoveAudioTrack(rtcMediaStream: RTCMediaStream!, track: RTCMediaStreamTrack!) {
NSLog("PluginMediaStream | OnRemoveAudioTrack [label:%@]", String(track.label))
// It may happen that track was removed due to user action (removeTrack()).
if self.audioTracks[track.label] == nil {
return
}
self.audioTracks[track.label] = nil
if self.eventListener != nil {
self.eventListenerForRemoveTrack!(id: track.label)
self.eventListener!(data: [
"type": "removetrack",
"track": [
"id": track.label,
"kind": "audio"
]
])
}
}
func OnRemoveVideoTrack(rtcMediaStream: RTCMediaStream!, track: RTCMediaStreamTrack!) {
NSLog("PluginMediaStream | OnRemoveVideoTrack [label:%@]", String(track.label))
// It may happen that track was removed due to user action (removeTrack()).
if self.videoTracks[track.label] == nil {
return
}
self.videoTracks[track.label] = nil
if self.eventListener != nil {
self.eventListenerForRemoveTrack!(id: track.label)
self.eventListener!(data: [
"type": "removetrack",
"track": [
"id": track.label,
"kind": "video"
]
])
}
}
}
| 30.578947 | 107 | 0.713712 |
8fa1c0f94060fe08bae2208ba38a43da9fc81da3 | 198 | // 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{enum S<T where S:T>:T | 39.6 | 87 | 0.762626 |
20a845ec0632c5208dd488c0af64a3b9c2233ae6 | 6,329 | import XCTest
@testable import SIPrefix
final class SIPrefixTests: XCTestCase {
func testDefaultFormatter() {
let formatter = SIPrefixFormatter()
XCTAssertEqual(formatter.format(1), "1")
XCTAssertEqual(formatter.format(23), "23")
XCTAssertEqual(formatter.format(345), "345")
XCTAssertEqual(formatter.format(4_567), "5k")
XCTAssertEqual(formatter.format(56_789), "57k")
XCTAssertEqual(formatter.format(678_901), "679k")
XCTAssertEqual(formatter.format(7_890_123), "8M")
XCTAssertEqual(formatter.format(89_012_345), "89M")
XCTAssertEqual(formatter.format(901_234_567), "901M")
XCTAssertEqual(formatter.format(1_234_567_890), "1G")
XCTAssertEqual(formatter.format(23_456_789_012), "23G")
XCTAssertEqual(formatter.format(345_678_901_234), "346G")
XCTAssertEqual(formatter.format(4_567_890_123_456), "5T")
XCTAssertEqual(formatter.format(9_223_372_036_854_775_807), "9E")
XCTAssertEqual(formatter.format(-1), "-1")
XCTAssertEqual(formatter.format(-23), "-23")
XCTAssertEqual(formatter.format(-345), "-345")
XCTAssertEqual(formatter.format(-4_567), "-5k")
XCTAssertEqual(formatter.format(-56_789), "-57k")
XCTAssertEqual(formatter.format(-678_901), "-679k")
XCTAssertEqual(formatter.format(-7_890_123), "-8M")
XCTAssertEqual(formatter.format(-89_012_345), "-89M")
XCTAssertEqual(formatter.format(-901_234_567), "-901M")
XCTAssertEqual(formatter.format(-1_234_567_890), "-1G")
XCTAssertEqual(formatter.format(-23_456_789_012), "-23G")
XCTAssertEqual(formatter.format(-345_678_901_234), "-346G")
XCTAssertEqual(formatter.format(-4_567_890_123_456), "-5T")
XCTAssertEqual(formatter.format(-9_223_372_036_854_775_807), "-9E")
}
func testCustomFormatter() {
let formatter = SIPrefixFormatter(prefixes: [
.init(log10: 1, symbol: "da"),
.init(log10: 2, symbol: "h"),
.init(log10: 3, symbol: "k"),
.init(log10: 6, symbol: "M"),
])
XCTAssertEqual(formatter.format(1), "1")
XCTAssertEqual(formatter.format(23), "2da")
XCTAssertEqual(formatter.format(345), "3h")
XCTAssertEqual(formatter.format(4_567), "5k")
XCTAssertEqual(formatter.format(56_789), "57k")
XCTAssertEqual(formatter.format(678_901), "679k")
XCTAssertEqual(formatter.format(7_890_123), "8M")
XCTAssertEqual(formatter.format(89_012_345), "89M")
XCTAssertEqual(formatter.format(901_234_567), "901M")
XCTAssertEqual(formatter.format(1_234_567_890), "1235M")
XCTAssertEqual(formatter.format(-1), "-1")
XCTAssertEqual(formatter.format(-23), "-2da")
XCTAssertEqual(formatter.format(-345), "-3h")
XCTAssertEqual(formatter.format(-4_567), "-5k")
XCTAssertEqual(formatter.format(-56_789), "-57k")
XCTAssertEqual(formatter.format(-678_901), "-679k")
XCTAssertEqual(formatter.format(-7_890_123), "-8M")
XCTAssertEqual(formatter.format(-89_012_345), "-89M")
XCTAssertEqual(formatter.format(-901_234_567), "-901M")
XCTAssertEqual(formatter.format(-1_234_567_890), "-1235M")
}
func testJapaneseFormatter() {
let formatter = SIPrefixFormatter(prefixes: [
.init(log10: 2, symbol: "百"),
.init(log10: 3, symbol: "千"),
.init(log10: 4, symbol: "万"),
.init(log10: 8, symbol: "億"),
], recursive: true)
XCTAssertEqual(formatter.format(1), "1")
XCTAssertEqual(formatter.format(23), "23")
XCTAssertEqual(formatter.format(345), "3百")
XCTAssertEqual(formatter.format(4_567), "5千")
XCTAssertEqual(formatter.format(56_789), "6万")
XCTAssertEqual(formatter.format(678_901), "68万")
XCTAssertEqual(formatter.format(7_890_123), "8百万")
XCTAssertEqual(formatter.format(89_012_345), "9千万")
XCTAssertEqual(formatter.format(901_234_567), "9億")
XCTAssertEqual(formatter.format(1_234_567_890), "12億")
XCTAssertEqual(formatter.format(23_456_789_012), "2百億")
XCTAssertEqual(formatter.format(-1), "-1")
XCTAssertEqual(formatter.format(-23), "-23")
XCTAssertEqual(formatter.format(-345), "-3百")
XCTAssertEqual(formatter.format(-4_567), "-5千")
XCTAssertEqual(formatter.format(-56_789), "-6万")
XCTAssertEqual(formatter.format(-678_901), "-68万")
XCTAssertEqual(formatter.format(-7_890_123), "-8百万")
XCTAssertEqual(formatter.format(-89_012_345), "-9千万")
XCTAssertEqual(formatter.format(-901_234_567), "-9億")
XCTAssertEqual(formatter.format(-1_234_567_890), "-12億")
XCTAssertEqual(formatter.format(-23_456_789_012), "-2百億")
}
func testShiftedFormatter() {
let formatter = SIPrefixFormatter(
prefixes: [
.init(log10: 3, symbol: "k"),
.init(log10: 6, symbol: "M"),
],
numberFormat: "%.1f",
shift: 1
)
XCTAssertEqual(formatter.format(1), "1.0")
XCTAssertEqual(formatter.format(23), "23.0")
XCTAssertEqual(formatter.format(345), "0.3k")
XCTAssertEqual(formatter.format(4_567), "4.6k")
XCTAssertEqual(formatter.format(56_789), "56.8k")
XCTAssertEqual(formatter.format(678_901), "0.7M")
XCTAssertEqual(formatter.format(7_890_123), "7.9M")
XCTAssertEqual(formatter.format(89_012_345), "89.0M")
XCTAssertEqual(formatter.format(901_234_567), "901.2M")
XCTAssertEqual(formatter.format(1_234_567_890), "1234.6M")
XCTAssertEqual(formatter.format(-1), "-1.0")
XCTAssertEqual(formatter.format(-23), "-23.0")
XCTAssertEqual(formatter.format(-345), "-0.3k")
XCTAssertEqual(formatter.format(-4_567), "-4.6k")
XCTAssertEqual(formatter.format(-56_789), "-56.8k")
XCTAssertEqual(formatter.format(-678_901), "-0.7M")
XCTAssertEqual(formatter.format(-7_890_123), "-7.9M")
XCTAssertEqual(formatter.format(-89_012_345), "-89.0M")
XCTAssertEqual(formatter.format(-901_234_567), "-901.2M")
XCTAssertEqual(formatter.format(-1_234_567_890), "-1234.6M")
}
}
| 49.445313 | 75 | 0.644494 |
2f3798340a29688c01ebc84acf5b78542f521242 | 5,093 | //
// DownloadManager.swift
// DragonLi
//
// Created by mikun on 2018/3/22.
// Copyright © 2018年 mikun. All rights reserved.
//
import UIKit
public class ConnectManager {
public var taskDic = [String:[URLSessionTask]]()
public func createPostTask(urlUnit:URLUnit, uploadFiles:[uploadItemUnit] = [],option:DragonLiOptionsInfo, finish:ConnectFinish? = nil) -> () {
var request = URLRequest.init(url: URL(string: urlUnit.host)!)
request.httpMethod = "POST"
if uploadFiles.count > 0 {
createUploadFilleTask(urlUnit:urlUnit, request: request, option:option, uploadFiles: uploadFiles, finish: finish)
}else{
request.httpBody = urlUnit.paraStr.data(using: .utf8);
createDataTask(urlUnit:urlUnit, request: request, option:option, finish: finish)
}
}
public func createGetTask(urlUnit:URLUnit, option:DragonLiOptionsInfo, finish:ConnectFinish? = nil) -> () {
var request = URLRequest.init(url: URL(string: urlUnit.fullUrl)!)
request.httpMethod = "GET"
createDataTask(urlUnit:urlUnit, request: request, option:option, finish: finish)
}
func createDataTask(urlUnit:URLUnit,request:URLRequest,option:DragonLiOptionsInfo, finish:ConnectFinish? = nil) -> () {
var task:URLSessionTask!
var config:URLSessionConfiguration!
let url = urlUnit.fullUrl
if option.taskiInSecret() {
config = URLSessionConfiguration.ephemeral
}else if option.taskInBackground(){
config = URLSessionConfiguration.background(withIdentifier: request.url?.host ?? "")
}
if config != nil{
task = URLSession.shared.dataTask(with: request) {
(data, urlResponse, error) in
self.convertResult(data, url, error, option, finish)
}
}else{
task = URLSession.shared.dataTask(with: request) {
(data, urlResponse, error) in
self.convertResult(data, url, error, option, finish)
}
}
if option.autoCancelSameRequests(){
update(url:url , task: task)
}
task.resume()
}
func createUploadFilleTask(urlUnit:URLUnit, request:URLRequest,option:DragonLiOptionsInfo, uploadFiles:[uploadItemUnit], finish:ConnectFinish? = nil) -> () {
var request = request
let url = urlUnit.fullUrl
let BOUNDRY = "Boundary+\(arc4random())\(arc4random())"
request.setValue("multipart/form-data; boundary=\(BOUNDRY)", forHTTPHeaderField: "Content-Type")
let data = createDataFrom(para:urlUnit.paraDic,uploadFiles: uploadFiles, BOUNDRY:BOUNDRY)
request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")
request.httpBody = data
let task = URLSession.shared.uploadTask(with: request, from: data){
(data, urlResponse, error) in
self.convertResult(data, url, error, option, finish)
}
if option.autoCancelSameRequests(){
update(url:url , task: task)
}
task.resume()
}
func convertResult(_ data:Data?, _ fullURL:String?, _ error:Error?, _ option:DragonLiOptionsInfo, _ finish:ConnectFinish?) {
if option.autoCancelSameRequests(){
if let fullURL = fullURL,let tasks = taskDic[fullURL] {
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(0)) {
for task in tasks {
task.cancel()//某些上传的业务来到这里可能会停了
}
self.taskDic.removeValue(forKey: fullURL)
}
}
}
if option.convertJsonObject(){
do{
let json = try JSONSerialization.jsonObject(with: data ?? Data(), options: [])
if option.debugPrintUrl() { print(json) }
DispatchQueue.main.async {
finish?(.success(json,false))
}
}catch{
DispatchQueue.main.async {
finish?(.success(data,false))
}
}
}else{
if error != nil{
DispatchQueue.main.async {
finish?(.failure(error!))
}
}else{
DispatchQueue.main.async {
finish?(.success(data,false))
}
}
}
}
func createDataFrom(para:[String:Any],uploadFiles:[uploadItemUnit], BOUNDRY:String) -> Data {
let Newline = "\r\n"
let boundary = "--\(BOUNDRY)\(Newline)"
var data = Data()
var dataStr = ""
for (key,value) in para{
dataStr += "\(boundary)Content-Disposition: form-data; name=\"\(key)\"\(Newline)\(Newline)\(value)\(Newline)"
}
print(dataStr)
if let appendData = dataStr.data(using: .utf8)
{
data.append(appendData)
}
for uploadItem in uploadFiles {
//拼接第一个--boundry
var appendStr = boundary
//第一个参数的描述部分
appendStr += "Content-Disposition: form-data; name=\"\(uploadItem.paraName)\"; filename=\"\(uploadItem.fileName)\"\(Newline)"
//指定第一个参数的类型,不然服务器不认识,注意后边多了一个换行
appendStr += "Content-Type: \(uploadItem.mimeType)\(Newline)\(Newline)"
if let appendData = appendStr.data(using: .utf8) {
data.append(appendData)
}
print(appendStr)
//拼接上传的数据
data.append(uploadItem.data)
if let appendData = "\(Newline)".data(using: .utf8) {
data.append(appendData)
}
}
//后边的结尾
if let appendData = "--\(BOUNDRY)--\(Newline)".data(using: .utf8) {
data.append(appendData)
}
return data
}
func update(url:String,task:URLSessionTask) {
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(0)) {
if self.taskDic[url] == nil {
self.taskDic[url] = []
}
self.taskDic[url]!.append(task)
}
}
}
| 28.138122 | 159 | 0.686432 |
67eb8545542d8b1829553f542f31988010d4a17b | 6,793 | //
// PhotoEditorContentView.swift
// HXPHPicker
//
// Created by Slience on 2021/3/26.
//
import UIKit
#if canImport(Kingfisher)
import Kingfisher
#endif
protocol PhotoEditorContentViewDelegate: AnyObject {
func contentView(drawViewBeganDraw contentView: PhotoEditorContentView)
func contentView(drawViewEndDraw contentView: PhotoEditorContentView)
func contentView(_ contentView: PhotoEditorContentView, updateStickerText item: EditorStickerItem)
func contentView(didRemoveAudio contentView: PhotoEditorContentView)
}
class PhotoEditorContentView: UIView {
enum EditType {
case image
case video
}
weak var delegate: PhotoEditorContentViewDelegate?
var itemViewMoveToCenter: ((CGRect) -> Bool)?
var stickerMinScale: ((CGSize) -> CGFloat)?
var stickerMaxScale: ((CGSize) -> CGFloat)?
lazy var videoView: VideoEditorPlayerView = {
let videoView = VideoEditorPlayerView()
return videoView
}()
lazy var imageView: UIImageView = {
var imageView: UIImageView
#if canImport(Kingfisher)
imageView = AnimatedImageView.init()
#else
imageView = UIImageView.init()
#endif
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
var image: UIImage? { imageView.image }
var zoomScale: CGFloat = 1 {
didSet {
drawView.scale = zoomScale
mosaicView.scale = zoomScale
stickerView.scale = zoomScale
}
}
lazy var drawView: PhotoEditorDrawView = {
let drawView = PhotoEditorDrawView.init(frame: .zero)
drawView.delegate = self
return drawView
}()
lazy var mosaicView: PhotoEditorMosaicView = {
let view = PhotoEditorMosaicView(mosaicConfig: mosaicConfig)
view.delegate = self
return view
}()
lazy var stickerView: EditorStickerView = {
let view = EditorStickerView(frame: .zero)
view.delegate = self
return view
}()
lazy var longPressGesture: UILongPressGestureRecognizer = {
let long = UILongPressGestureRecognizer(
target: self,
action: #selector(longPressGestureRecognizerClick(_:))
)
long.minimumPressDuration = 0.2
long.isEnabled = false
return long
}()
let mosaicConfig: PhotoEditorConfiguration.Mosaic
let editType: EditType
init(
editType: EditType,
mosaicConfig: PhotoEditorConfiguration.Mosaic
) {
self.mosaicConfig = mosaicConfig
self.editType = editType
super.init(frame: .zero)
if editType == .image {
addSubview(imageView)
addSubview(mosaicView)
}else {
addSubview(videoView)
}
addSubview(drawView)
addSubview(stickerView)
addGestureRecognizer(longPressGesture)
}
var originalImage: UIImage?
var tempImage: UIImage?
@objc
func longPressGestureRecognizerClick(
_ longPressGesture: UILongPressGestureRecognizer
) {
switch longPressGesture.state {
case .began:
if editType == .image {
tempImage = imageView.image
if let image = originalImage {
setImage(image)
}
}else {
videoView.isLookOriginal = true
}
case .ended, .cancelled, .failed:
if editType == .image {
if let image = tempImage {
setImage(image)
}
tempImage = nil
}else {
videoView.isLookOriginal = false
}
default:
break
}
}
func setMosaicOriginalImage(_ image: UIImage?) {
mosaicView.originalImage = image
}
func setImage(_ image: UIImage) {
if editType == .video {
videoView.coverImageView.image = image
return
}
#if canImport(Kingfisher)
let view = imageView as! AnimatedImageView
view.image = image
#else
imageView.image = image
#endif
}
override func layoutSubviews() {
super.layoutSubviews()
if editType == .image {
imageView.frame = bounds
mosaicView.frame = bounds
}else {
if videoView.superview == self {
videoView.frame = bounds
}
}
drawView.frame = bounds
stickerView.frame = bounds
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PhotoEditorContentView: PhotoEditorDrawViewDelegate {
func drawView(beganDraw drawView: PhotoEditorDrawView) {
delegate?.contentView(drawViewBeganDraw: self)
}
func drawView(endDraw drawView: PhotoEditorDrawView) {
delegate?.contentView(drawViewEndDraw: self)
}
}
extension PhotoEditorContentView: EditorStickerViewDelegate {
func stickerView(_ stickerView: EditorStickerView, updateStickerText item: EditorStickerItem) {
delegate?.contentView(self, updateStickerText: item)
}
func stickerView(touchBegan stickerView: EditorStickerView) {
delegate?.contentView(drawViewBeganDraw: self)
}
func stickerView(touchEnded stickerView: EditorStickerView) {
delegate?.contentView(drawViewEndDraw: self)
}
func stickerView(_ stickerView: EditorStickerView, moveToCenter rect: CGRect) -> Bool {
if let moveToCenter = itemViewMoveToCenter?(rect) {
return moveToCenter
}
return false
}
func stickerView(_ stickerView: EditorStickerView, minScale itemSize: CGSize) -> CGFloat {
if let minScale = stickerMinScale?(itemSize) {
return minScale
}
return 0.2
}
func stickerView(_ stickerView: EditorStickerView, maxScale itemSize: CGSize) -> CGFloat {
if let maxScale = stickerMaxScale?(itemSize) {
return maxScale
}
return 5
}
func stickerView(didRemoveAudio stickerView: EditorStickerView) {
delegate?.contentView(didRemoveAudio: self)
}
}
extension PhotoEditorContentView: PhotoEditorMosaicViewDelegate {
func mosaicView(_ mosaicView: PhotoEditorMosaicView, splashColor atPoint: CGPoint) -> UIColor? {
imageView.color(for: atPoint)
}
func mosaicView(beganDraw mosaicView: PhotoEditorMosaicView) {
delegate?.contentView(drawViewBeganDraw: self)
}
func mosaicView(endDraw mosaicView: PhotoEditorMosaicView) {
delegate?.contentView(drawViewEndDraw: self)
}
}
| 30.599099 | 102 | 0.626086 |
db92e77ed42fb83d6e321cb30fa48ecce48591c7 | 2,723 | // Sources/SwiftProtobufPluginLibrary/CodePrinter.swift - Code output
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This provides some basic indentation management for emitting structured
/// source code text.
///
// -----------------------------------------------------------------------------
/// Prints code with automatic indentation based on calls to `indent` and
/// `outdent`.
public struct CodePrinter {
/// Reserve an initial buffer of 64KB scalars to eliminate some reallocations
/// in smaller files.
private static let initialBufferSize = 65536
/// The string content that was printed.
public var content: String {
return String(contentScalars)
}
/// See if anything was printed.
public var isEmpty: Bool { return content.isEmpty }
/// The Unicode scalar buffer used to build up the printed contents.
private var contentScalars = String.UnicodeScalarView()
/// The `UnicodeScalarView` representing a single indentation step.
private let singleIndent: String.UnicodeScalarView
/// The current indentation level (a collection of spaces).
private var indentation = String.UnicodeScalarView()
/// Keeps track of whether the printer is currently sitting at the beginning
/// of a line.
private var atLineStart = true
public init(indent: String.UnicodeScalarView = " ".unicodeScalars) {
contentScalars.reserveCapacity(CodePrinter.initialBufferSize)
singleIndent = indent
}
/// Writes the given strings to the printer.
///
/// - Parameter text: A variable-length list of strings to be printed.
public mutating func print(_ text: String...) {
for t in text {
for scalar in t.unicodeScalars {
// Indent at the start of a new line, unless it's a blank line.
if atLineStart && scalar != "\n" {
contentScalars.append(contentsOf: indentation)
}
contentScalars.append(scalar)
atLineStart = (scalar == "\n")
}
}
}
/// Increases the printer's indentation level.
public mutating func indent() {
indentation.append(contentsOf: singleIndent)
}
/// Decreases the printer's indentation level.
///
/// - Precondition: The printer must not have an indentation level.
public mutating func outdent() {
let indentCount = singleIndent.count
precondition(indentation.count >= indentCount, "Cannot outdent past the left margin")
indentation.removeLast(indentCount)
}
}
| 34.0375 | 89 | 0.669849 |
dd62435d32f6fd9b64fdcbfc6aa7fbfaba696b8e | 8,539 | import XCTest
import GRDB
class DatabaseRegionObservationTests: GRDBTestCase {
func testDatabaseRegionObservation_FullDatabase() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
}
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
var observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
observation.extent = .databaseLifetime
var count = 0
_ = try observation.start(in: dbQueue) { db in
count += 1
notificationExpectation.fulfill()
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
}
func testDatabaseRegionObservationVariadic() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
}
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
let request1 = SQLRequest<Row>(sql: "SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>(sql: "SELECT * FROM t2 ORDER BY id")
var observation = DatabaseRegionObservation(tracking: request1, request2)
observation.extent = .databaseLifetime
var count = 0
_ = try observation.start(in: dbQueue) { db in
count += 1
notificationExpectation.fulfill()
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
}
func testDatabaseRegionObservationArray() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
}
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
let request1 = SQLRequest<Row>(sql: "SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>(sql: "SELECT * FROM t2 ORDER BY id")
var observation = DatabaseRegionObservation(tracking: [request1, request2])
observation.extent = .databaseLifetime
var count = 0
_ = try observation.start(in: dbQueue) { db in
count += 1
notificationExpectation.fulfill()
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
}
func testDatabaseRegionDefaultExtent() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
var count = 0
do {
let observer = try observation.start(in: dbQueue) { db in
count += 1
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
}
}
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 2)
}
func testDatabaseRegionExtentNextTransaction() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 1
var observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
observation.extent = .nextTransaction
var count = 0
_ = try observation.start(in: dbQueue) { db in
count += 1
notificationExpectation.fulfill()
}
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 1)
}
// Regression test for https://github.com/groue/GRDB.swift/issues/514
// TODO: uncomment and make this test pass.
// func testIssue514() throws {
// let dbQueue = try makeDatabaseQueue()
// try dbQueue.write { db in
// try db.create(table: "gallery") { t in
// t.column("id", .integer).primaryKey()
// t.column("status", .integer)
// }
// }
//
// struct Gallery: TableRecord { }
// let observation = DatabaseRegionObservation(tracking: Gallery.select(Column("id")))
//
// var notificationCount = 0
// let observer = try observation.start(in: dbQueue) { _ in
// notificationCount += 1
// }
//
// try withExtendedLifetime(observer) {
// try dbQueue.write { db in
// try db.execute(sql: "INSERT INTO gallery (id, status) VALUES (NULL, 0)")
// }
// XCTAssertEqual(notificationCount, 1)
//
// try dbQueue.write { db in
// try db.execute(sql: "UPDATE gallery SET status = 1")
// }
// XCTAssertEqual(notificationCount, 1) // status is not observed
//
// try dbQueue.write { db in
// try db.execute(sql: "DELETE FROM gallery")
// }
// XCTAssertEqual(notificationCount, 2)
// }
// }
}
| 39.35023 | 116 | 0.583441 |
ddb46075920f3778827453afa48523dfbe7ff8a0 | 2,840 | //
// ViewController.swift
// CombineStudy
//
// Created by jourhuang on 2020/9/28.
//
import UIKit
import Combine
import Contacts
fileprivate struct PostmanEchoTimeStampCheckResponse: Decodable, Hashable {
let valid: Bool
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
dataTaskPublisher()
}
func justPubliser() {
let _ = Just(5)
.map { value -> String in
// do something with the incoming value here
// and return a string
return "a string"
}
.sink { receivedValue in
// sink is the subscriber and terminates the pipeline
print("The end result was \(receivedValue)")
}
}
func emptyPublisher() {
let emptyPublisher = Empty<String, Never>()
}
func futureAsyncPublisher() {
let futureAsyncPublisher = Future<Bool, Error> { promise in
CNContactStore().requestAccess(for: .contacts) { grantedAccess, err in
// err is an optional
if let err = err {
return promise(.failure(err))
}
return promise(.success(grantedAccess))
}
}.eraseToAnyPublisher()
futureAsyncPublisher.sink { (value) in
print(value)
} receiveValue: { (flag) in
print(flag)
}
}
func resolvedSuccessAsPublisher() {
let resolvedSuccessAsPublisher = Future<Bool, Error> { promise in
promise(.success(true))
}.eraseToAnyPublisher()
}
func dataTaskPublisher() {
let myURL = URL(string: "https://postman-echo.com/time/valid?timestamp=2016-10-10")
// checks the validity of a timestamp - this one returns {"valid":true}
// matching the data structure returned from https://postman-echo.com/time/valid
let remoteDataPublisher = URLSession.shared.dataTaskPublisher(for: myURL!)
// the dataTaskPublisher output combination is (data: Data, response: URLResponse)
.map { $0.data }
.decode(type: PostmanEchoTimeStampCheckResponse.self, decoder: JSONDecoder())
let cancellableSink = remoteDataPublisher
.sink(receiveCompletion: { completion in
print(".sink() received the completion", String(describing: completion))
switch completion {
case .finished:
break
case .failure(let anError):
print("received error: ", anError)
}
}, receiveValue: { someValue in
print(".sink() received \(someValue)")
})
}
}
| 31.208791 | 94 | 0.559155 |
f552aa896a2bdd6bcfca03110df6951ef2f2243b | 3,156 | //
// AppDelegate.swift
// sevendayrogue
//
// Created by Bart van Kuik on 20/08/2017.
// Copyright © 2017 DutchVirtual. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "sevendayrogue")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 35.863636 | 199 | 0.647338 |
3aea40517c54a16b9239d69a5e297ba52997e26f | 1,418 | //
// AppDelegate.swift
// AdLibs
//
// Created by David Williams on 2/26/20.
// Copyright © 2020 david williams. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.315789 | 179 | 0.747532 |
d62d4d9cd65b71693db1e605ce29f64e83eb7afc | 3,075 | //
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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
extension IDXClient.Context: NSSecureCoding {
private enum Keys: String {
case configuration
case state
case interactionHandle
case codeVerifier
case version
}
public static var supportsSecureCoding: Bool {
return true
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? IDXClient.Context,
configuration == object.configuration,
state == object.state,
interactionHandle == object.interactionHandle,
codeVerifier == object.codeVerifier,
version == object.version
else {
return false
}
return true
}
public func encode(with coder: NSCoder) {
coder.encode(configuration, forKey: Keys.configuration.rawValue)
coder.encode(state, forKey: Keys.state.rawValue)
coder.encode(interactionHandle, forKey: Keys.interactionHandle.rawValue)
coder.encode(codeVerifier, forKey: Keys.codeVerifier.rawValue)
coder.encode(version.rawValue, forKey: Keys.version.rawValue)
}
public convenience init?(coder: NSCoder) {
guard let configuration = coder.decodeObject(of: [IDXClient.Configuration.self],
forKey: Keys.configuration.rawValue) as? IDXClient.Configuration,
let state = coder.decodeObject(of: [NSString.self],
forKey: Keys.state.rawValue) as? String,
let interactionHandle = coder.decodeObject(of: [NSString.self],
forKey: Keys.interactionHandle.rawValue) as? String,
let codeVerifier = coder.decodeObject(of: [NSString.self],
forKey: Keys.codeVerifier.rawValue) as? String,
let versionNumber = coder.decodeObject(of: [NSString.self],
forKey: Keys.version.rawValue) as? String,
let version = IDXClient.Version(rawValue: versionNumber) else
{
return nil
}
self.init(configuration: configuration,
state: state,
interactionHandle: interactionHandle,
codeVerifier: codeVerifier,
version: version)
}
}
| 42.708333 | 120 | 0.605528 |
91e6c7d6ebc8b28f33a14053488d41bb17c4aa56 | 3,614 | //
// FDForecastPagingViewController.swift
// FineDust
//
// Created by YangJehPark on 2018. 5. 14..
// Copyright © 2018년 YangJehPark. All rights reserved.
//
import UIKit
class FDForecastPagingViewController: UIPageViewController {
@IBOutlet weak var topNavigationItem: UINavigationItem?
private let minPageCount: Int = 1
private var totalPageCount: Int {
get {
return minPageCount + DataManager.shared.getUserAreaDataList().count
}
}
private var currentChildViewController: FDForecastChildViewController?
private var currentIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
topNavigationItem?.title = "예보"
if currentChildViewController?.childViewControllers == nil {
setViewControllers([getChildVC(index: currentIndex)!], direction: .forward, animated: true, completion: nil)
}
}
@IBAction func sideMenuButtonPressed() {
//ViewControllerHelper.openSideMenu(vc: self)
ViewControllerHelper.openEditArea(vc: self)
}
@IBAction func addAreaButtonPressed() {
ViewControllerHelper.openAddArea(vc: self)
}
private func getChildVC(index: Int) -> FDForecastChildViewController? {
if index == 0 {
return FDForecastChildViewController(index: 0, data: DataManager.shared.getCurrentAreaData() ?? FDData())
} else {
if let userAreaData = DataManager.shared.getUserAreaData(index: index) {
return FDForecastChildViewController(index: index, data: userAreaData)
} else {
return nil
}
}
}
}
extension FDForecastPagingViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let currentChildVC = pageViewController.viewControllers![0] as? FDForecastChildViewController {
currentChildViewController = currentChildVC
currentIndex = currentChildVC.pageIndex
}
}
}
extension FDForecastPagingViewController: UIPageViewControllerDataSource {
override func setViewControllers(_ viewControllers: [UIViewController]?, direction: UIPageViewControllerNavigationDirection, animated: Bool, completion: ((Bool) -> Void)? = nil) {
super.setViewControllers(viewControllers, direction: direction, animated: animated, completion: completion)
if let last = viewControllers?.last, last.isKind(of: FDForecastChildViewController.self) {
currentChildViewController = (last as! FDForecastChildViewController)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let nowIndex = (viewController as! FDForecastChildViewController).pageIndex
return nowIndex == 0 ? nil : getChildVC(index: nowIndex-1)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let afterIndex = (viewController as! FDForecastChildViewController).pageIndex+1
return afterIndex == totalPageCount ? nil : getChildVC(index: afterIndex)
}
}
| 38.042105 | 190 | 0.693138 |
462e922a0621623650adeb649c727e7c7726e4d2 | 2,285 | //
// SceneDelegate.swift
// Prework
//
// Created by Mark Cruz on 2/3/21.
//
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.113208 | 147 | 0.712035 |
640df2ae51107e83e07d31ff4fc151139d7da5fe | 3,351 | //
// ServerThreadingTests.swift
// Swifter
//
// Created by Victor Sigler on 4/22/19.
// Copyright © 2019 Damian Kołakowski. All rights reserved.
//
import XCTest
#if os(Linux)
import FoundationNetworking
#endif
@testable import Swifter
class ServerThreadingTests: XCTestCase {
var server: HttpServer!
override func setUp() {
super.setUp()
server = HttpServer()
}
override func tearDown() {
if server.operating {
server.stop()
}
server = nil
super.tearDown()
}
func testShouldHandleTheRequestInDifferentTimeIntervals() {
let path = "/a/:b/c"
let queue = DispatchQueue(label: "com.swifter.threading")
let hostURL: URL
server.GET[path] = { .ok(.htmlBody("You asked for " + $0.path)) }
do {
#if os(Linux)
try server.start(9081)
hostURL = URL(string: "http://localhost:9081")!
#else
try server.start()
hostURL = defaultLocalhost
#endif
let requestExpectation = expectation(description: "Request should finish.")
requestExpectation.expectedFulfillmentCount = 3
(1...3).forEach { index in
queue.asyncAfter(deadline: .now() + .seconds(index)) {
let task = URLSession.shared.executeAsyncTask(hostURL: hostURL, path: path) { (_, response, _ ) in
requestExpectation.fulfill()
let statusCode = (response as? HTTPURLResponse)?.statusCode
XCTAssertNotNil(statusCode)
XCTAssertEqual(statusCode, 200, "\(hostURL)")
}
task.resume()
}
}
} catch let error {
XCTFail("\(error)")
}
waitForExpectations(timeout: 10, handler: nil)
}
func testShouldHandleTheSameRequestConcurrently() {
let path = "/a/:b/c"
server.GET[path] = { .ok(.htmlBody("You asked for " + $0.path)) }
var requestExpectation: XCTestExpectation? = expectation(description: "Should handle the request concurrently")
do {
try server.start()
let downloadGroup = DispatchGroup()
DispatchQueue.concurrentPerform(iterations: 3) { _ in
downloadGroup.enter()
let task = URLSession.shared.executeAsyncTask(path: path) { (_, response, _ ) in
let statusCode = (response as? HTTPURLResponse)?.statusCode
XCTAssertNotNil(statusCode)
XCTAssertEqual(statusCode, 200)
requestExpectation?.fulfill()
requestExpectation = nil
downloadGroup.leave()
}
task.resume()
}
} catch let error {
XCTFail("\(error)")
}
waitForExpectations(timeout: 15, handler: nil)
}
}
extension URLSession {
func executeAsyncTask(
hostURL: URL = defaultLocalhost,
path: String,
completionHandler handler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask {
return self.dataTask(with: hostURL.appendingPathComponent(path), completionHandler: handler)
}
}
| 28.159664 | 119 | 0.558341 |
1639dfad0e2ff67c46da0211f2e7595e72e403f0 | 507 | //
// ViewController.swift
// polyglot-ui
//
// Created by Yannick on 22/05/2017.
// Copyright © 2017 yannickspark. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.5 | 80 | 0.670611 |
ebf2f2faab9ca267fc968a8cc4308469ee92531b | 806 | //
// Path.swift
// deploy-manager
//
// Created by Tobias Schultka on 18.04.15.
// Copyright (c) 2015 Tobias Schultka. All rights reserved.
//
import Foundation
import Cocoa
// get project path
func getProjectPath() -> String {
return getStorage("path", "") as! String
}
// set project path
func setProjectPath() {
var openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false
if (openPanel.runModal() == NSModalResponseOK) {
var projectPath = "\(openPanel.URLs[0] as! NSURL)"
projectPath = projectPath.stringByReplacingOccurrencesOfString("file://", withString: "")
setStorage("path", projectPath)
}
}
| 24.424242 | 97 | 0.677419 |
619dadfa395f38374afe007213f8f3ab71adcf33 | 1,855 | //
// DetailViewController.swift
// animation
//
// Created by USER on 2018/10/25.
// Copyright © 2018年 USER. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
lazy var imageView: UIImageView = {
let itemImageView = UIImageView()
itemImageView.image = UIImage(named: "movie.jpg")
itemImageView.frame = CGRect(x: 0, y: 0, width: 80, height: 124)
itemImageView.center = CGPoint(x: 60, y: 200)
return itemImageView
}()
lazy var scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.frame = view.bounds
scroll.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
scroll.contentSize = CGSize(width: view.bounds.size.width , height: view.bounds.size.height * 2)
scroll.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(back))
scroll.addGestureRecognizer(tap)
return scroll
}()
lazy var topImageView: UIImageView = {
let topImageView = UIImageView()
topImageView.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width,height: 200)
topImageView.image = UIImage(named: "topImage.jpg")
return topImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
deinit {
navigationController?.delegate = nil
}
}
extension DetailViewController {
func setupUI() {
if #available(iOS 11, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
view.addSubview(scrollView)
scrollView.addSubview(topImageView)
scrollView.addSubview(imageView)
}
@objc func back() {
dismiss(animated: true, completion: nil)
}
}
| 28.106061 | 104 | 0.621563 |
f9e5a2a7c6dd977158bee8768accd733a9e45c13 | 307 | //
// Checklist.swift
// Checklists
//
// Created by Fahim Farook on 04/08/2020.
// Copyright © 2020 Razeware. All rights reserved.
//
import UIKit
class Checklist: NSObject, Codable {
var name = ""
var items = [ChecklistItem]()
init(name: String) {
self.name = name
super.init()
}
}
| 15.35 | 51 | 0.635179 |
f77c42620e46f3441c558782a953a2ce658d4abd | 1,248 | //
// TipCalcUITests.swift
// TipCalcUITests
//
// Created by Srishtti Talwar on 1/9/19.
// Copyright © 2019 Srishtti Talwar. All rights reserved.
//
import XCTest
class TipCalcUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.72973 | 182 | 0.663462 |
623c86b1958e41519fc3fc89aba3049bd322a906 | 1,520 | //
// Applyer.swift
// Example
//
// Created by Lukasz Szarkowicz on 07/09/2020.
// Copyright © 2020 Mobilee. All rights reserved.
//
import UIKit
public struct Applyer<Element> {
private let configureHandler: (Element) -> Void
public init(_ configuration: @escaping (Element) -> Void) {
self.configureHandler = configuration
}
@discardableResult
public func apply(to element: Element) -> Element {
configureHandler(element)
return element
}
}
public protocol Appliable: AnyObject {
associatedtype Element
func apply(using configuration: Applyer<Element>) -> Element
func apply(_ configurator: (Element) throws -> Void) rethrows -> Element
}
extension Appliable {
/**
Applies a code closure to this object.
Example of usage:
```
let button = UIButton()
button.apply(.filled).apply(.rounded)
```
- parameter configuration: The configuration to apply.
*/
@discardableResult
public func apply(using configuration: Applyer<Self>) -> Self {
return configuration.apply(to: self)
}
@discardableResult
public func apply(_ configurator: (Self) throws -> Void) rethrows -> Self {
// Run the provided configurator:
try configurator(self)
return self
}
}
//extension Appliable where Self: UIView {
// public init(configuration: Applyer<Self>) {
// self.init()
// apply(configuration)
// }
//}
extension NSObject: Appliable {}
| 22.686567 | 79 | 0.645395 |
d7f96066ac109a46bf216da4e28f3bfae1952427 | 486 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Canon {
public struct EOSM5: CameraModel {
public init() {}
public let name = "Canon EOS M5"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Canon.self
}
}
public typealias CanonEOSM5 = Cameras.Manufacturers.Canon.EOSM5
| 27 | 95 | 0.72428 |
1a9a4c0e93c165e20e9e91a7d1828d73b306c99a | 1,900 | // https://github.com/Quick/Quick
import Quick
import Nimble
@testable import Disintegrate
extension Triangle {
var area: CGFloat {
return abs(self.vertices.0.x * (self.vertices.1.y - self.vertices.2.y) +
self.vertices.1.x * (self.vertices.2.y - self.vertices.0.y) +
self.vertices.2.x * (self.vertices.0.y - self.vertices.1.y)) / 2.0
}
}
class TriangulationSpec: QuickSpec {
override func spec() {
describe("Random view triangulation") {
for _ in 0 ..< 200 {
let randomFrame = CGRect(x: CGFloat.random(in: 0 ..< 414),
y: CGFloat.random(in: 0 ..< 896),
width: CGFloat.random(in: 44 ..< 1000),
height: CGFloat.random(in: 44 ..< 1000))
let randomFrameArea = randomFrame.width * randomFrame.height
let view = UIView(frame: randomFrame)
for _ in 0 ..< 5 {
let trianglesCount = Int.random(in: 100 ..< 400)
it("rectangle with frame \(randomFrame) has the same area after dividing into \(trianglesCount) triangles") {
waitUntil { done in
view.layer.getRandomTriangles(direction: .random(),
estimatedTrianglesCount: trianglesCount,
completion: { (triangles) in
let trianglesAreaSum = triangles.map({ $0.area }).reduce(0, +)
expect(trianglesAreaSum).to(beCloseTo(randomFrameArea, within: 0.01))
done()
})
}
}
}
}
}
}
}
| 38 | 129 | 0.456842 |
ed2bf3c3070d5ee1053aa726313551ea7514336d | 425 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct c<T:T.E{protocol a<
| 42.5 | 79 | 0.752941 |
912d65bb64847a04833da5e2fb0ee31f7addf9ff | 492 | //
// BaseTableViewCell.swift
// CoffeeShopFinder
//
// Created by Joey Lee on 15/4/18.
// Copyright © 2018 Joey Lee. All rights reserved.
//
import UIKit
class BaseTableViewCell: UITableViewCell {
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
}
}
| 19.68 | 65 | 0.666667 |
464b1086b8cfee5c178cd248ac1273d4093b248b | 1,054 | //
// LoginManager.swift
// mopicker-sample-app
//
// Created by Ivan Obodovskyi on 07.05.2020.
// Copyright © 2020 Ivan Obodovskyi. All rights reserved.
//
import Combine
import AppsFlyerLib
class AuthManager: ObservableObject {
static var shared = AuthManager()
var googleAuthSub: AnyCancellable?
var isSignedIn = PassthroughSubject<Bool, Never>()
@Published var userDidSignIn: Bool = false {
didSet {
isSignedIn.send(self.userDidSignIn)
}
}
private var googleAuth = GoogleAuthService.googleSignIn
private init() {
subscribe()
}
private func subscribe() {
self.googleAuthSub = googleAuth.isSignedIn.sink(receiveValue: { userIsSignedIn in
AppsFlyerTracker.shared().trackEvent("af_google_login", withValues: nil)
self.userDidSignIn = userIsSignedIn
AFEventRate
})
}
func signOut() {
googleAuth.userDidSignOut()
}
deinit {
print("OBJ deinitialized")
}
}
| 22.913043 | 89 | 0.629032 |
1a09ffdd4d744967262684a69f6432664b7c96ce | 18,464 | //
// InvoiceViewController.swift
// StandUp-iOS
//
// Created by Peter on 12/01/19.
// Copyright © 2019 BlockchainCommons. All rights reserved.
//
import UIKit
class InvoiceViewController: UIViewController, UITextFieldDelegate {
let spinner = UIActivityIndicatorView(style: .medium)
var textToShareViaQRCode = String()
var addressString = String()
var qrCode = UIImage()
let descriptionLabel = UILabel()
var tapQRGesture = UITapGestureRecognizer()
var tapAddressGesture = UITapGestureRecognizer()
var nativeSegwit = Bool()
var p2shSegwit = Bool()
var legacy = Bool()
let connectingView = ConnectingView()
let qrGenerator = QRGenerator()
let copiedLabel = UILabel()
let cd = CoreDataService()
var refreshButton = UIBarButtonItem()
var dataRefresher = UIBarButtonItem()
var initialLoad = Bool()
var wallet:WalletStruct!
var presentingModally = Bool()
@IBOutlet var closeButtonOutlet: UIButton!
@IBOutlet var amountField: UITextField!
@IBOutlet var labelField: UITextField!
@IBOutlet var qrView: UIImageView!
@IBOutlet var addressOutlet: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initialLoad = true
addressOutlet.isUserInteractionEnabled = true
addressOutlet.text = ""
amountField.delegate = self
labelField.delegate = self
configureCopiedLabel()
amountField.addTarget(self,
action: #selector(textFieldDidChange(_:)),
for: .editingChanged)
labelField.addTarget(self,
action: #selector(textFieldDidChange(_:)),
for: .editingChanged)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
addDoneButtonOnKeyboard()
load()
if presentingModally {
closeButtonOutlet.alpha = 1
} else {
closeButtonOutlet.alpha = 0
}
}
@IBAction func refresh(_ sender: Any) {
self.load()
}
@IBAction func close(_ sender: Any) {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
func addNavBarSpinner() {
spinner.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
dataRefresher = UIBarButtonItem(customView: spinner)
navigationItem.setRightBarButton(dataRefresher, animated: true)
spinner.startAnimating()
spinner.alpha = 1
}
func removeLoader() {
DispatchQueue.main.async {
self.spinner.stopAnimating()
self.spinner.alpha = 0
self.refreshButton = UIBarButtonItem(barButtonSystemItem: .refresh,
target: self,
action: #selector(self.load))
self.refreshButton.tintColor = UIColor.white.withAlphaComponent(1)
self.navigationItem.setRightBarButton(self.refreshButton,
animated: true)
}
}
@objc func load() {
connectingView.addConnectingView(vc: self, description: "fetching invoice address from your node")
getActiveWalletNow() { (wallet, error) in
if !error && wallet != nil {
self.wallet = wallet!
self.addNavBarSpinner()
if !self.initialLoad {
DispatchQueue.main.async {
UIView.animate(withDuration: 0.3, animations: {
self.addressOutlet.alpha = 0
self.qrView.alpha = 0
}) { (_) in
self.addressOutlet.text = ""
self.qrView.image = nil
self.addressOutlet.alpha = 1
self.qrView.alpha = 1
self.showAddress()
}
}
} else {
self.showAddress()
}
} else if error {
self.connectingView.removeConnectingView()
self.removeLoader()
showAlert(vc: self, title: "Error", message: "No active wallets")
}
}
}
func filterDerivation(str: DescriptorStruct) {
print("derivation")
if str.isP2PKH || str.isBIP44 || wallet.derivation.contains("44") {
self.executeNodeCommand(method: .getnewaddress,
param: "\"\", \"legacy\"")
} else if str.isP2WPKH || str.isBIP84 || wallet.derivation.contains("84") {
self.executeNodeCommand(method: .getnewaddress,
param: "\"\", \"bech32\"")
} else if str.isP2SHP2WPKH || str.isBIP49 || wallet.derivation.contains("49") {
self.executeNodeCommand(method: .getnewaddress,
param: "\"\", \"p2sh-segwit\"")
}
}
func showAddress() {
print("showAddress")
let parser = DescriptorParser()
let str = parser.descriptor(wallet!.descriptor)
if str.isMulti {
self.getMsigAddress()
} else {
self.filterDerivation(str: str)
}
}
func getMsigAddress() {
print("getMsigAddress")
let keyFetcher = KeyFetcher()
keyFetcher.musigAddress { (address, error) in
if !error {
self.connectingView.removeConnectingView()
self.removeLoader()
self.addressString = address!
self.showAddress(address: address!)
} else {
self.connectingView.removeConnectingView()
displayAlert(viewController: self, isError: true, message: "error getting musig address")
}
}
}
func showAddress(address: String) {
DispatchQueue.main.async {
let pasteboard = UIPasteboard.general
pasteboard.string = address
self.qrCode = self.generateQrCode(key: address)
self.qrView.image = self.qrCode
self.qrView.isUserInteractionEnabled = true
self.qrView.alpha = 0
self.view.addSubview(self.qrView)
self.descriptionLabel.frame = CGRect(x: 10,
y: self.view.frame.maxY - 30,
width: self.view.frame.width - 20,
height: 20)
self.descriptionLabel.textAlignment = .center
self.descriptionLabel.font = UIFont.init(name: "HelveticaNeue-Light",
size: 12)
self.descriptionLabel.textColor = UIColor.white
self.descriptionLabel.text = "Tap the QR Code or text to copy/save/share"
self.descriptionLabel.adjustsFontSizeToFitWidth = true
self.descriptionLabel.alpha = 0
self.view.addSubview(self.descriptionLabel)
self.tapAddressGesture = UITapGestureRecognizer(target: self,
action: #selector(self.shareAddressText(_:)))
self.addressOutlet.addGestureRecognizer(self.tapAddressGesture)
self.tapQRGesture = UITapGestureRecognizer(target: self,
action: #selector(self.shareQRCode(_:)))
self.qrView.addGestureRecognizer(self.tapQRGesture)
UIView.animate(withDuration: 0.3, animations: {
self.descriptionLabel.alpha = 1
self.qrView.alpha = 1
self.addressOutlet.alpha = 1
}) { _ in
self.addressOutlet.text = address
self.addCopiedLabel()
}
}
}
func addCopiedLabel() {
view.addSubview(copiedLabel)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
UIView.animate(withDuration: 0.3, animations: {
if self.tabBarController != nil {
self.copiedLabel.frame = CGRect(x: 0,
y: self.tabBarController!.tabBar.frame.minY - 50,
width: self.view.frame.width,
height: 50)
}
})
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: {
UIView.animate(withDuration: 0.3, animations: {
self.copiedLabel.frame = CGRect(x: 0,
y: self.view.frame.maxY + 100,
width: self.view.frame.width,
height: 50)
}, completion: { _ in
self.copiedLabel.removeFromSuperview()
})
})
}
}
@objc func shareAddressText(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.2, animations: {
self.addressOutlet.alpha = 0
}) { _ in
UIView.animate(withDuration: 0.2, animations: {
self.addressOutlet.alpha = 1
})
}
DispatchQueue.main.async {
let textToShare = [self.addressString]
let activityViewController = UIActivityViewController(activityItems: textToShare,
applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true) {}
}
}
@objc func shareQRCode(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.2, animations: {
self.qrView.alpha = 0
}) { _ in
UIView.animate(withDuration: 0.2, animations: {
self.qrView.alpha = 1
}) { _ in
let activityController = UIActivityViewController(activityItems: [self.qrView.image!],
applicationActivities: nil)
activityController.popoverPresentationController?.sourceView = self.view
self.present(activityController, animated: true) {}
}
}
}
func executeNodeCommand(method: BTC_CLI_COMMAND, param: String) {
let reducer = Reducer()
func getResult() {
if !reducer.errorBool {
switch method {
case .getnewaddress:
DispatchQueue.main.async {
self.connectingView.removeConnectingView()
self.initialLoad = false
let address = reducer.stringToReturn
self.removeLoader()
if address != nil {
self.addressString = address!
self.addressOutlet.text = address!
self.showAddress(address: address!)
}
}
default:
break
}
} else {
self.connectingView.removeConnectingView()
self.removeLoader()
displayAlert(viewController: self,
isError: true,
message: reducer.errorDescription)
}
}
reducer.makeCommand(walletName: wallet.name, command: method,
param: param,
completion: getResult)
}
@objc func textFieldDidChange(_ textField: UITextField) {
updateQRImage()
}
func generateQrCode(key: String) -> UIImage {
qrGenerator.textInput = key
return qrGenerator.getQRCode()
}
func updateQRImage() {
var newImage = UIImage()
if self.amountField.text == "" && self.labelField.text == "" {
newImage = self.generateQrCode(key:"bitcoin:\(self.addressString)")
textToShareViaQRCode = "bitcoin:\(self.addressString)"
} else if self.amountField.text != "" && self.labelField.text != "" {
newImage = self.generateQrCode(key:"bitcoin:\(self.addressString)?amount=\(self.amountField.text!)&label=\(self.labelField.text!)")
textToShareViaQRCode = "bitcoin:\(self.addressString)?amount=\(self.amountField.text!)&label=\(self.labelField.text!)"
} else if self.amountField.text != "" && self.labelField.text == "" {
newImage = self.generateQrCode(key:"bitcoin:\(self.addressString)?amount=\(self.amountField.text!)")
textToShareViaQRCode = "bitcoin:\(self.addressString)?amount=\(self.amountField.text!)"
} else if self.amountField.text == "" && self.labelField.text != "" {
newImage = self.generateQrCode(key:"bitcoin:\(self.addressString)?label=\(self.labelField.text!)")
textToShareViaQRCode = "bitcoin:\(self.addressString)?label=\(self.labelField.text!)"
}
DispatchQueue.main.async {
UIView.transition(with: self.qrView,
duration: 0.75,
options: .transitionCrossDissolve,
animations: { self.qrView.image = newImage },
completion: nil)
let impact = UIImpactFeedbackGenerator()
impact.impactOccurred()
}
}
@objc func doneButtonAction() {
self.amountField.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return false
}
func addDoneButtonOnKeyboard() {
let doneToolbar = UIToolbar()
doneToolbar.frame = CGRect(x: 0,
y: 0,
width: 320,
height: 50)
doneToolbar.barStyle = UIBarStyle.default
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,
target: nil,
action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done",
style: UIBarButtonItem.Style.done,
target: self,
action: #selector(doneButtonAction))
let items = NSMutableArray()
items.add(flexSpace)
items.add(done)
doneToolbar.items = (items as! [UIBarButtonItem])
doneToolbar.sizeToFit()
self.amountField.inputAccessoryView = doneToolbar
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
func configureCopiedLabel() {
copiedLabel.text = "copied to clipboard ✓"
copiedLabel.frame = CGRect(x: 0,
y: view.frame.maxY + 100,
width: view.frame.width,
height: 50)
copiedLabel.textColor = UIColor.darkGray
copiedLabel.font = UIFont.init(name: "HiraginoSans-W3", size: 17)
copiedLabel.backgroundColor = UIColor.black
copiedLabel.textAlignment = .center
}
}
| 32.621908 | 143 | 0.449686 |
64e8d372590b3f54f35b43a07d6d2c5c0171abd6 | 6,861 | //
// Heap.swift
// Written for the Swift Algorithm Club by Kevin Randrup and Matthijs Hollemans
//
public struct Heap<T> {
/** The array that stores the heap's nodes. */
var elements = [T]()
/** Determines whether this is a max-heap (>) or min-heap (<). */
fileprivate var isOrderedBefore: (T, T) -> Bool
/**
* Creates an empty heap.
* The sort function determines whether this is a min-heap or max-heap.
* For integers, > makes a max-heap, < makes a min-heap.
*/
public init(sort: @escaping (T, T) -> Bool) {
self.isOrderedBefore = sort
}
/**
* Creates a heap from an array. The order of the array does not matter;
* the elements are inserted into the heap in the order determined by the
* sort function.
*/
public init(array: [T], sort: @escaping (T, T) -> Bool) {
self.isOrderedBefore = sort
buildHeap(array)
}
/*
// This version has O(n log n) performance.
private mutating func buildHeap(array: [T]) {
elements.reserveCapacity(array.count)
for value in array {
insert(value)
}
}
*/
/**
* Converts an array to a max-heap or min-heap in a bottom-up manner.
* Performance: This runs pretty much in O(n).
*/
private mutating func buildHeap(_ array: [T]) {
elements = array
#if swift(>=3.0)
for i in stride(from: (elements.count/2 - 1), through: 0, by: -1) {
shiftDown(index: i, heapSize: elements.count)
}
#else
for i in (elements.count/2 - 1).stride(through: 0, by: -1) {
shiftDown(index: i, heapSize: elements.count)
}
#endif
}
public var isEmpty: Bool {
return elements.isEmpty
}
public var count: Int {
return elements.count
}
/**
* Returns the index of the parent of the element at index i.
* The element at index 0 is the root of the tree and has no parent.
*/
@inline(__always) func indexOfParent(_ i: Int) -> Int {
return (i - 1) / 2
}
/**
* Returns the index of the left child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no left child.
*/
@inline(__always) func indexOfLeftChild(_ i: Int) -> Int {
return 2*i + 1
}
/**
* Returns the index of the right child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no right child.
*/
@inline(__always) func indexOfRightChild(_ i: Int) -> Int {
return 2*i + 2
}
/**
* Returns the maximum value in the heap (for a max-heap) or the minimum
* value (for a min-heap).
*/
public func peek() -> T? {
return elements.first
}
/**
* Adds a new value to the heap. This reorders the heap so that the max-heap
* or min-heap property still holds. Performance: O(log n).
*/
public mutating func insert(_ value: T) {
elements.append(value)
shiftUp(index: elements.count - 1)
}
#if swift(>=3.0)
public mutating func insert<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for value in sequence {
insert(value)
}
}
#else
public mutating func insert<S: SequenceType where S.Generator.Element == T>(sequence: S) {
for value in sequence {
insert(value)
}
}
#endif
/**
* Allows you to change an element. In a max-heap, the new element should be
* larger than the old one; in a min-heap it should be smaller.
*/
public mutating func replace(index i: Int, value: T) {
assert(isOrderedBefore(value, elements[i]))
elements[i] = value
shiftUp(index: i)
}
/**
* Removes the root node from the heap. For a max-heap, this is the maximum
* value; for a min-heap it is the minimum value. Performance: O(log n).
*/
public mutating func remove() -> T? {
if elements.isEmpty {
return nil
} else if elements.count == 1 {
return elements.removeLast()
} else {
// Use the last node to replace the first one, then fix the heap by
// shifting this new first node into its proper position.
let value = elements[0]
elements[0] = elements.removeLast()
shiftDown()
return value
}
}
/**
* Removes an arbitrary node from the heap. Performance: O(log n). You need
* to know the node's index, which may actually take O(n) steps to find.
*/
public mutating func removeAtIndex(i: Int) -> T? {
let size = elements.count - 1
if i != size {
swap(&elements[i], &elements[size])
shiftDown(index: i, heapSize: size)
shiftUp(index: i)
}
return elements.removeLast()
}
/**
* Takes a child node and looks at its parents; if a parent is not larger
* (max-heap) or not smaller (min-heap) than the child, we exchange them.
*/
mutating func shiftUp(index: Int) {
var childIndex = index
let child = elements[childIndex]
var parentIndex = indexOfParent(childIndex)
while childIndex > 0 && isOrderedBefore(child, elements[parentIndex]) {
elements[childIndex] = elements[parentIndex]
childIndex = parentIndex
parentIndex = indexOfParent(childIndex)
}
elements[childIndex] = child
}
mutating func shiftDown() {
shiftDown(index: 0, heapSize: elements.count)
}
/**
* Looks at a parent node and makes sure it is still larger (max-heap) or
* smaller (min-heap) than its childeren.
*/
mutating func shiftDown(index: Int, heapSize: Int) {
var parentIndex = index
while true {
let leftChildIndex = indexOfLeftChild(parentIndex)
let rightChildIndex = leftChildIndex + 1
// Figure out which comes first if we order them by the sort function:
// the parent, the left child, or the right child. If the parent comes
// first, we're done. If not, that element is out-of-place and we make
// it "float down" the tree until the heap property is restored.
var first = parentIndex
if leftChildIndex < heapSize && isOrderedBefore(elements[leftChildIndex], elements[first]) {
first = leftChildIndex
}
if rightChildIndex < heapSize && isOrderedBefore(elements[rightChildIndex], elements[first]) {
first = rightChildIndex
}
if first == parentIndex { return }
swap(&elements[parentIndex], &elements[first])
parentIndex = first
}
}
}
// MARK: - Searching
extension Heap where T: Equatable {
/**
* Searches the heap for the given element. Performance: O(n).
*/
public func indexOf(_ element: T) -> Int? {
return indexOf(element, 0)
}
private func indexOf(_ element: T, _ i: Int) -> Int? {
if i >= count { return nil }
if isOrderedBefore(element, elements[i]) { return nil }
if element == elements[i] { return i }
if let j = indexOf(element, indexOfLeftChild(i)) { return j }
if let j = indexOf(element, indexOfRightChild(i)) { return j }
return nil
}
}
| 28.827731 | 100 | 0.640431 |
87e4931c381b4a1d9670aca71318906169960772 | 706 | import Foundation
/// The handler used to combine progress and completion.
public struct UploadHandler {
/// Typealias for the progress handler which returns the total bytes sent and the total bytes expected to be sent.
public typealias ProgressHandler = ((Int64, Int64) -> Void)?
/// Typealias for the completion handler which returns either a response or an error.
public typealias CompletionHandler = ((URLResponse?, Error?) -> Void)
/// The progress handler to use to get updates about the progress of the upload.
var progressHandler: ProgressHandler
/// The completion handler to use to get either the response or an error.
var completionHandler: CompletionHandler
}
| 47.066667 | 118 | 0.747875 |
677b27d690952764b34ef285b7a485e1aa08897d | 290 | //
// Scene.swift
// NoExpense
//
// Created by Aashish Tamsya on 19/07/19.
// Copyright © 2019 Aashish Tamsya. All rights reserved.
//
import Foundation
enum Scene {
case expenses(TransactionsViewModel)
case editExpense(EditExpenseViewModel)
case overview(OverviewViewModel)
}
| 18.125 | 57 | 0.737931 |
332000fb0559b5e93b88acbb01b7c6d4d6c24121 | 85,263 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension WellArchitected {
// MARK: Enums
public enum DifferenceStatus: String, CustomStringConvertible, Codable {
case deleted = "DELETED"
case new = "NEW"
case updated = "UPDATED"
public var description: String { return self.rawValue }
}
public enum LensStatus: String, CustomStringConvertible, Codable {
case current = "CURRENT"
case deprecated = "DEPRECATED"
case notCurrent = "NOT_CURRENT"
public var description: String { return self.rawValue }
}
public enum NotificationType: String, CustomStringConvertible, Codable {
case lensVersionDeprecated = "LENS_VERSION_DEPRECATED"
case lensVersionUpgraded = "LENS_VERSION_UPGRADED"
public var description: String { return self.rawValue }
}
public enum PermissionType: String, CustomStringConvertible, Codable {
case contributor = "CONTRIBUTOR"
case readonly = "READONLY"
public var description: String { return self.rawValue }
}
public enum Risk: String, CustomStringConvertible, Codable {
case high = "HIGH"
case medium = "MEDIUM"
case none = "NONE"
case notApplicable = "NOT_APPLICABLE"
case unanswered = "UNANSWERED"
public var description: String { return self.rawValue }
}
public enum ShareInvitationAction: String, CustomStringConvertible, Codable {
case accept = "ACCEPT"
case reject = "REJECT"
public var description: String { return self.rawValue }
}
public enum ShareStatus: String, CustomStringConvertible, Codable {
case accepted = "ACCEPTED"
case expired = "EXPIRED"
case pending = "PENDING"
case rejected = "REJECTED"
case revoked = "REVOKED"
public var description: String { return self.rawValue }
}
public enum WorkloadEnvironment: String, CustomStringConvertible, Codable {
case preproduction = "PREPRODUCTION"
case production = "PRODUCTION"
public var description: String { return self.rawValue }
}
public enum WorkloadImprovementStatus: String, CustomStringConvertible, Codable {
case complete = "COMPLETE"
case inProgress = "IN_PROGRESS"
case notApplicable = "NOT_APPLICABLE"
case notStarted = "NOT_STARTED"
case riskAcknowledged = "RISK_ACKNOWLEDGED"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct Answer: AWSDecodableShape {
public let choices: [Choice]?
public let helpfulResourceUrl: String?
public let improvementPlanUrl: String?
public let isApplicable: Bool?
public let notes: String?
public let pillarId: String?
public let questionDescription: String?
public let questionId: String?
public let questionTitle: String?
public let risk: Risk?
public let selectedChoices: [String]?
public init(choices: [Choice]? = nil, helpfulResourceUrl: String? = nil, improvementPlanUrl: String? = nil, isApplicable: Bool? = nil, notes: String? = nil, pillarId: String? = nil, questionDescription: String? = nil, questionId: String? = nil, questionTitle: String? = nil, risk: Risk? = nil, selectedChoices: [String]? = nil) {
self.choices = choices
self.helpfulResourceUrl = helpfulResourceUrl
self.improvementPlanUrl = improvementPlanUrl
self.isApplicable = isApplicable
self.notes = notes
self.pillarId = pillarId
self.questionDescription = questionDescription
self.questionId = questionId
self.questionTitle = questionTitle
self.risk = risk
self.selectedChoices = selectedChoices
}
private enum CodingKeys: String, CodingKey {
case choices = "Choices"
case helpfulResourceUrl = "HelpfulResourceUrl"
case improvementPlanUrl = "ImprovementPlanUrl"
case isApplicable = "IsApplicable"
case notes = "Notes"
case pillarId = "PillarId"
case questionDescription = "QuestionDescription"
case questionId = "QuestionId"
case questionTitle = "QuestionTitle"
case risk = "Risk"
case selectedChoices = "SelectedChoices"
}
}
public struct AnswerSummary: AWSDecodableShape {
public let choices: [Choice]?
public let isApplicable: Bool?
public let pillarId: String?
public let questionId: String?
public let questionTitle: String?
public let risk: Risk?
public let selectedChoices: [String]?
public init(choices: [Choice]? = nil, isApplicable: Bool? = nil, pillarId: String? = nil, questionId: String? = nil, questionTitle: String? = nil, risk: Risk? = nil, selectedChoices: [String]? = nil) {
self.choices = choices
self.isApplicable = isApplicable
self.pillarId = pillarId
self.questionId = questionId
self.questionTitle = questionTitle
self.risk = risk
self.selectedChoices = selectedChoices
}
private enum CodingKeys: String, CodingKey {
case choices = "Choices"
case isApplicable = "IsApplicable"
case pillarId = "PillarId"
case questionId = "QuestionId"
case questionTitle = "QuestionTitle"
case risk = "Risk"
case selectedChoices = "SelectedChoices"
}
}
public struct AssociateLensesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAliases: [String]
public let workloadId: String
public init(lensAliases: [String], workloadId: String) {
self.lensAliases = lensAliases
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.lensAliases.forEach {
try validate($0, name: "lensAliases[]", parent: name, max: 64)
try validate($0, name: "lensAliases[]", parent: name, min: 1)
}
try self.validate(self.lensAliases, name: "lensAliases", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case lensAliases = "LensAliases"
}
}
public struct Choice: AWSDecodableShape {
public let choiceId: String?
public let description: String?
public let title: String?
public init(choiceId: String? = nil, description: String? = nil, title: String? = nil) {
self.choiceId = choiceId
self.description = description
self.title = title
}
private enum CodingKeys: String, CodingKey {
case choiceId = "ChoiceId"
case description = "Description"
case title = "Title"
}
}
public struct CreateMilestoneInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let clientRequestToken: String
public let milestoneName: String
public let workloadId: String
public init(clientRequestToken: String = CreateMilestoneInput.idempotencyToken(), milestoneName: String, workloadId: String) {
self.clientRequestToken = clientRequestToken
self.milestoneName = milestoneName
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.milestoneName, name: "milestoneName", parent: name, max: 100)
try self.validate(self.milestoneName, name: "milestoneName", parent: name, min: 3)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken = "ClientRequestToken"
case milestoneName = "MilestoneName"
}
}
public struct CreateMilestoneOutput: AWSDecodableShape {
public let milestoneNumber: Int?
public let workloadId: String?
public init(milestoneNumber: Int? = nil, workloadId: String? = nil) {
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case milestoneNumber = "MilestoneNumber"
case workloadId = "WorkloadId"
}
}
public struct CreateWorkloadInput: AWSEncodableShape {
public let accountIds: [String]?
public let architecturalDesign: String?
public let awsRegions: [String]?
public let clientRequestToken: String
public let description: String
public let environment: WorkloadEnvironment
public let industry: String?
public let industryType: String?
public let lenses: [String]
public let nonAwsRegions: [String]?
public let notes: String?
public let pillarPriorities: [String]?
public let reviewOwner: String
public let workloadName: String
public init(accountIds: [String]? = nil, architecturalDesign: String? = nil, awsRegions: [String]? = nil, clientRequestToken: String = CreateWorkloadInput.idempotencyToken(), description: String, environment: WorkloadEnvironment, industry: String? = nil, industryType: String? = nil, lenses: [String], nonAwsRegions: [String]? = nil, notes: String? = nil, pillarPriorities: [String]? = nil, reviewOwner: String, workloadName: String) {
self.accountIds = accountIds
self.architecturalDesign = architecturalDesign
self.awsRegions = awsRegions
self.clientRequestToken = clientRequestToken
self.description = description
self.environment = environment
self.industry = industry
self.industryType = industryType
self.lenses = lenses
self.nonAwsRegions = nonAwsRegions
self.notes = notes
self.pillarPriorities = pillarPriorities
self.reviewOwner = reviewOwner
self.workloadName = workloadName
}
public func validate(name: String) throws {
try self.accountIds?.forEach {
try validate($0, name: "accountIds[]", parent: name, pattern: "[0-9]{12}")
}
try self.validate(self.accountIds, name: "accountIds", parent: name, max: 100)
try self.validate(self.architecturalDesign, name: "architecturalDesign", parent: name, max: 2048)
try self.awsRegions?.forEach {
try validate($0, name: "awsRegions[]", parent: name, max: 100)
}
try self.validate(self.awsRegions, name: "awsRegions", parent: name, max: 50)
try self.validate(self.description, name: "description", parent: name, max: 250)
try self.validate(self.description, name: "description", parent: name, min: 3)
try self.validate(self.industry, name: "industry", parent: name, max: 100)
try self.validate(self.industryType, name: "industryType", parent: name, max: 100)
try self.lenses.forEach {
try validate($0, name: "lenses[]", parent: name, max: 64)
try validate($0, name: "lenses[]", parent: name, min: 1)
}
try self.nonAwsRegions?.forEach {
try validate($0, name: "nonAwsRegions[]", parent: name, max: 25)
try validate($0, name: "nonAwsRegions[]", parent: name, min: 3)
}
try self.validate(self.nonAwsRegions, name: "nonAwsRegions", parent: name, max: 5)
try self.validate(self.notes, name: "notes", parent: name, max: 2084)
try self.pillarPriorities?.forEach {
try validate($0, name: "pillarPriorities[]", parent: name, max: 64)
try validate($0, name: "pillarPriorities[]", parent: name, min: 1)
}
try self.validate(self.reviewOwner, name: "reviewOwner", parent: name, max: 255)
try self.validate(self.reviewOwner, name: "reviewOwner", parent: name, min: 3)
try self.validate(self.workloadName, name: "workloadName", parent: name, max: 100)
try self.validate(self.workloadName, name: "workloadName", parent: name, min: 3)
}
private enum CodingKeys: String, CodingKey {
case accountIds = "AccountIds"
case architecturalDesign = "ArchitecturalDesign"
case awsRegions = "AwsRegions"
case clientRequestToken = "ClientRequestToken"
case description = "Description"
case environment = "Environment"
case industry = "Industry"
case industryType = "IndustryType"
case lenses = "Lenses"
case nonAwsRegions = "NonAwsRegions"
case notes = "Notes"
case pillarPriorities = "PillarPriorities"
case reviewOwner = "ReviewOwner"
case workloadName = "WorkloadName"
}
}
public struct CreateWorkloadOutput: AWSDecodableShape {
public let workloadArn: String?
public let workloadId: String?
public init(workloadArn: String? = nil, workloadId: String? = nil) {
self.workloadArn = workloadArn
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case workloadArn = "WorkloadArn"
case workloadId = "WorkloadId"
}
}
public struct CreateWorkloadShareInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let clientRequestToken: String
public let permissionType: PermissionType
public let sharedWith: String
public let workloadId: String
public init(clientRequestToken: String = CreateWorkloadShareInput.idempotencyToken(), permissionType: PermissionType, sharedWith: String, workloadId: String) {
self.clientRequestToken = clientRequestToken
self.permissionType = permissionType
self.sharedWith = sharedWith
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.sharedWith, name: "sharedWith", parent: name, max: 2048)
try self.validate(self.sharedWith, name: "sharedWith", parent: name, min: 12)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken = "ClientRequestToken"
case permissionType = "PermissionType"
case sharedWith = "SharedWith"
}
}
public struct CreateWorkloadShareOutput: AWSDecodableShape {
public let shareId: String?
public let workloadId: String?
public init(shareId: String? = nil, workloadId: String? = nil) {
self.shareId = shareId
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case shareId = "ShareId"
case workloadId = "WorkloadId"
}
}
public struct DeleteWorkloadInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "clientRequestToken", location: .querystring(locationName: "ClientRequestToken")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let clientRequestToken: String
public let workloadId: String
public init(clientRequestToken: String = DeleteWorkloadInput.idempotencyToken(), workloadId: String) {
self.clientRequestToken = clientRequestToken
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteWorkloadShareInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "clientRequestToken", location: .querystring(locationName: "ClientRequestToken")),
AWSMemberEncoding(label: "shareId", location: .uri(locationName: "ShareId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let clientRequestToken: String
public let shareId: String
public let workloadId: String
public init(clientRequestToken: String = DeleteWorkloadShareInput.idempotencyToken(), shareId: String, workloadId: String) {
self.clientRequestToken = clientRequestToken
self.shareId = shareId
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.shareId, name: "shareId", parent: name, pattern: "[0-9a-f]{32}")
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct DisassociateLensesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAliases: [String]
public let workloadId: String
public init(lensAliases: [String], workloadId: String) {
self.lensAliases = lensAliases
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.lensAliases.forEach {
try validate($0, name: "lensAliases[]", parent: name, max: 64)
try validate($0, name: "lensAliases[]", parent: name, min: 1)
}
try self.validate(self.lensAliases, name: "lensAliases", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case lensAliases = "LensAliases"
}
}
public struct GetAnswerInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "questionId", location: .uri(locationName: "QuestionId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
public let milestoneNumber: Int?
public let questionId: String
public let workloadId: String
public init(lensAlias: String, milestoneNumber: Int? = nil, questionId: String, workloadId: String) {
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.questionId = questionId
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.questionId, name: "questionId", parent: name, max: 128)
try self.validate(self.questionId, name: "questionId", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct GetAnswerOutput: AWSDecodableShape {
public let answer: Answer?
public let lensAlias: String?
public let milestoneNumber: Int?
public let workloadId: String?
public init(answer: Answer? = nil, lensAlias: String? = nil, milestoneNumber: Int? = nil, workloadId: String? = nil) {
self.answer = answer
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case answer = "Answer"
case lensAlias = "LensAlias"
case milestoneNumber = "MilestoneNumber"
case workloadId = "WorkloadId"
}
}
public struct GetLensReviewInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
public let milestoneNumber: Int?
public let workloadId: String
public init(lensAlias: String, milestoneNumber: Int? = nil, workloadId: String) {
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct GetLensReviewOutput: AWSDecodableShape {
public let lensReview: LensReview?
public let milestoneNumber: Int?
public let workloadId: String?
public init(lensReview: LensReview? = nil, milestoneNumber: Int? = nil, workloadId: String? = nil) {
self.lensReview = lensReview
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case lensReview = "LensReview"
case milestoneNumber = "MilestoneNumber"
case workloadId = "WorkloadId"
}
}
public struct GetLensReviewReportInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
public let milestoneNumber: Int?
public let workloadId: String
public init(lensAlias: String, milestoneNumber: Int? = nil, workloadId: String) {
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct GetLensReviewReportOutput: AWSDecodableShape {
public let lensReviewReport: LensReviewReport?
public let milestoneNumber: Int?
public let workloadId: String?
public init(lensReviewReport: LensReviewReport? = nil, milestoneNumber: Int? = nil, workloadId: String? = nil) {
self.lensReviewReport = lensReviewReport
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case lensReviewReport = "LensReviewReport"
case milestoneNumber = "MilestoneNumber"
case workloadId = "WorkloadId"
}
}
public struct GetLensVersionDifferenceInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "baseLensVersion", location: .querystring(locationName: "BaseLensVersion")),
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias"))
]
/// The base version of the lens.
public let baseLensVersion: String
public let lensAlias: String
public init(baseLensVersion: String, lensAlias: String) {
self.baseLensVersion = baseLensVersion
self.lensAlias = lensAlias
}
public func validate(name: String) throws {
try self.validate(self.baseLensVersion, name: "baseLensVersion", parent: name, max: 128)
try self.validate(self.baseLensVersion, name: "baseLensVersion", parent: name, min: 1)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct GetLensVersionDifferenceOutput: AWSDecodableShape {
/// The base version of the lens.
public let baseLensVersion: String?
/// The latest version of the lens.
public let latestLensVersion: String?
public let lensAlias: String?
public let versionDifferences: VersionDifferences?
public init(baseLensVersion: String? = nil, latestLensVersion: String? = nil, lensAlias: String? = nil, versionDifferences: VersionDifferences? = nil) {
self.baseLensVersion = baseLensVersion
self.latestLensVersion = latestLensVersion
self.lensAlias = lensAlias
self.versionDifferences = versionDifferences
}
private enum CodingKeys: String, CodingKey {
case baseLensVersion = "BaseLensVersion"
case latestLensVersion = "LatestLensVersion"
case lensAlias = "LensAlias"
case versionDifferences = "VersionDifferences"
}
}
public struct GetMilestoneInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "milestoneNumber", location: .uri(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let milestoneNumber: Int
public let workloadId: String
public init(milestoneNumber: Int, workloadId: String) {
self.milestoneNumber = milestoneNumber
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct GetMilestoneOutput: AWSDecodableShape {
public let milestone: Milestone?
public let workloadId: String?
public init(milestone: Milestone? = nil, workloadId: String? = nil) {
self.milestone = milestone
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case milestone = "Milestone"
case workloadId = "WorkloadId"
}
}
public struct GetWorkloadInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let workloadId: String
public init(workloadId: String) {
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct GetWorkloadOutput: AWSDecodableShape {
public let workload: Workload?
public init(workload: Workload? = nil) {
self.workload = workload
}
private enum CodingKeys: String, CodingKey {
case workload = "Workload"
}
}
public struct ImprovementSummary: AWSDecodableShape {
public let improvementPlanUrl: String?
public let pillarId: String?
public let questionId: String?
public let questionTitle: String?
public let risk: Risk?
public init(improvementPlanUrl: String? = nil, pillarId: String? = nil, questionId: String? = nil, questionTitle: String? = nil, risk: Risk? = nil) {
self.improvementPlanUrl = improvementPlanUrl
self.pillarId = pillarId
self.questionId = questionId
self.questionTitle = questionTitle
self.risk = risk
}
private enum CodingKeys: String, CodingKey {
case improvementPlanUrl = "ImprovementPlanUrl"
case pillarId = "PillarId"
case questionId = "QuestionId"
case questionTitle = "QuestionTitle"
case risk = "Risk"
}
}
public struct LensReview: AWSDecodableShape {
public let lensAlias: String?
public let lensName: String?
/// The status of the lens.
public let lensStatus: LensStatus?
/// The version of the lens.
public let lensVersion: String?
public let nextToken: String?
public let notes: String?
public let pillarReviewSummaries: [PillarReviewSummary]?
public let riskCounts: [Risk: Int]?
public let updatedAt: Date?
public init(lensAlias: String? = nil, lensName: String? = nil, lensStatus: LensStatus? = nil, lensVersion: String? = nil, nextToken: String? = nil, notes: String? = nil, pillarReviewSummaries: [PillarReviewSummary]? = nil, riskCounts: [Risk: Int]? = nil, updatedAt: Date? = nil) {
self.lensAlias = lensAlias
self.lensName = lensName
self.lensStatus = lensStatus
self.lensVersion = lensVersion
self.nextToken = nextToken
self.notes = notes
self.pillarReviewSummaries = pillarReviewSummaries
self.riskCounts = riskCounts
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case lensAlias = "LensAlias"
case lensName = "LensName"
case lensStatus = "LensStatus"
case lensVersion = "LensVersion"
case nextToken = "NextToken"
case notes = "Notes"
case pillarReviewSummaries = "PillarReviewSummaries"
case riskCounts = "RiskCounts"
case updatedAt = "UpdatedAt"
}
}
public struct LensReviewReport: AWSDecodableShape {
public let base64String: String?
public let lensAlias: String?
public init(base64String: String? = nil, lensAlias: String? = nil) {
self.base64String = base64String
self.lensAlias = lensAlias
}
private enum CodingKeys: String, CodingKey {
case base64String = "Base64String"
case lensAlias = "LensAlias"
}
}
public struct LensReviewSummary: AWSDecodableShape {
public let lensAlias: String?
public let lensName: String?
/// The status of the lens.
public let lensStatus: LensStatus?
/// The version of the lens.
public let lensVersion: String?
public let riskCounts: [Risk: Int]?
public let updatedAt: Date?
public init(lensAlias: String? = nil, lensName: String? = nil, lensStatus: LensStatus? = nil, lensVersion: String? = nil, riskCounts: [Risk: Int]? = nil, updatedAt: Date? = nil) {
self.lensAlias = lensAlias
self.lensName = lensName
self.lensStatus = lensStatus
self.lensVersion = lensVersion
self.riskCounts = riskCounts
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case lensAlias = "LensAlias"
case lensName = "LensName"
case lensStatus = "LensStatus"
case lensVersion = "LensVersion"
case riskCounts = "RiskCounts"
case updatedAt = "UpdatedAt"
}
}
public struct LensSummary: AWSDecodableShape {
public let description: String?
public let lensAlias: String?
public let lensName: String?
/// The version of the lens.
public let lensVersion: String?
public init(description: String? = nil, lensAlias: String? = nil, lensName: String? = nil, lensVersion: String? = nil) {
self.description = description
self.lensAlias = lensAlias
self.lensName = lensName
self.lensVersion = lensVersion
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case lensAlias = "LensAlias"
case lensName = "LensName"
case lensVersion = "LensVersion"
}
}
public struct LensUpgradeSummary: AWSDecodableShape {
/// The current version of the lens.
public let currentLensVersion: String?
/// The latest version of the lens.
public let latestLensVersion: String?
public let lensAlias: String?
public let workloadId: String?
public let workloadName: String?
public init(currentLensVersion: String? = nil, latestLensVersion: String? = nil, lensAlias: String? = nil, workloadId: String? = nil, workloadName: String? = nil) {
self.currentLensVersion = currentLensVersion
self.latestLensVersion = latestLensVersion
self.lensAlias = lensAlias
self.workloadId = workloadId
self.workloadName = workloadName
}
private enum CodingKeys: String, CodingKey {
case currentLensVersion = "CurrentLensVersion"
case latestLensVersion = "LatestLensVersion"
case lensAlias = "LensAlias"
case workloadId = "WorkloadId"
case workloadName = "WorkloadName"
}
}
public struct ListAnswersInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "pillarId", location: .querystring(locationName: "PillarId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let milestoneNumber: Int?
public let nextToken: String?
public let pillarId: String?
public let workloadId: String
public init(lensAlias: String, maxResults: Int? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, pillarId: String? = nil, workloadId: String) {
self.lensAlias = lensAlias
self.maxResults = maxResults
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.pillarId = pillarId
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.pillarId, name: "pillarId", parent: name, max: 64)
try self.validate(self.pillarId, name: "pillarId", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct ListAnswersOutput: AWSDecodableShape {
public let answerSummaries: [AnswerSummary]?
public let lensAlias: String?
public let milestoneNumber: Int?
public let nextToken: String?
public let workloadId: String?
public init(answerSummaries: [AnswerSummary]? = nil, lensAlias: String? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, workloadId: String? = nil) {
self.answerSummaries = answerSummaries
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case answerSummaries = "AnswerSummaries"
case lensAlias = "LensAlias"
case milestoneNumber = "MilestoneNumber"
case nextToken = "NextToken"
case workloadId = "WorkloadId"
}
}
public struct ListLensReviewImprovementsInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "pillarId", location: .querystring(locationName: "PillarId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let milestoneNumber: Int?
public let nextToken: String?
public let pillarId: String?
public let workloadId: String
public init(lensAlias: String, maxResults: Int? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, pillarId: String? = nil, workloadId: String) {
self.lensAlias = lensAlias
self.maxResults = maxResults
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.pillarId = pillarId
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.pillarId, name: "pillarId", parent: name, max: 64)
try self.validate(self.pillarId, name: "pillarId", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct ListLensReviewImprovementsOutput: AWSDecodableShape {
public let improvementSummaries: [ImprovementSummary]?
public let lensAlias: String?
public let milestoneNumber: Int?
public let nextToken: String?
public let workloadId: String?
public init(improvementSummaries: [ImprovementSummary]? = nil, lensAlias: String? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, workloadId: String? = nil) {
self.improvementSummaries = improvementSummaries
self.lensAlias = lensAlias
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case improvementSummaries = "ImprovementSummaries"
case lensAlias = "LensAlias"
case milestoneNumber = "MilestoneNumber"
case nextToken = "NextToken"
case workloadId = "WorkloadId"
}
}
public struct ListLensReviewsInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "milestoneNumber", location: .querystring(locationName: "MilestoneNumber")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let maxResults: Int?
public let milestoneNumber: Int?
public let nextToken: String?
public let workloadId: String
public init(maxResults: Int? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, workloadId: String) {
self.maxResults = maxResults
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, max: 100)
try self.validate(self.milestoneNumber, name: "milestoneNumber", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct ListLensReviewsOutput: AWSDecodableShape {
public let lensReviewSummaries: [LensReviewSummary]?
public let milestoneNumber: Int?
public let nextToken: String?
public let workloadId: String?
public init(lensReviewSummaries: [LensReviewSummary]? = nil, milestoneNumber: Int? = nil, nextToken: String? = nil, workloadId: String? = nil) {
self.lensReviewSummaries = lensReviewSummaries
self.milestoneNumber = milestoneNumber
self.nextToken = nextToken
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case lensReviewSummaries = "LensReviewSummaries"
case milestoneNumber = "MilestoneNumber"
case nextToken = "NextToken"
case workloadId = "WorkloadId"
}
}
public struct ListLensesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken"))
]
public let maxResults: Int?
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListLensesOutput: AWSDecodableShape {
public let lensSummaries: [LensSummary]?
public let nextToken: String?
public init(lensSummaries: [LensSummary]? = nil, nextToken: String? = nil) {
self.lensSummaries = lensSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case lensSummaries = "LensSummaries"
case nextToken = "NextToken"
}
}
public struct ListMilestonesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let maxResults: Int?
public let nextToken: String?
public let workloadId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, workloadId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListMilestonesOutput: AWSDecodableShape {
public let milestoneSummaries: [MilestoneSummary]?
public let nextToken: String?
public let workloadId: String?
public init(milestoneSummaries: [MilestoneSummary]? = nil, nextToken: String? = nil, workloadId: String? = nil) {
self.milestoneSummaries = milestoneSummaries
self.nextToken = nextToken
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case milestoneSummaries = "MilestoneSummaries"
case nextToken = "NextToken"
case workloadId = "WorkloadId"
}
}
public struct ListNotificationsInput: AWSEncodableShape {
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let nextToken: String?
public let workloadId: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, workloadId: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case workloadId = "WorkloadId"
}
}
public struct ListNotificationsOutput: AWSDecodableShape {
public let nextToken: String?
/// List of lens notification summaries in a workload.
public let notificationSummaries: [NotificationSummary]?
public init(nextToken: String? = nil, notificationSummaries: [NotificationSummary]? = nil) {
self.nextToken = nextToken
self.notificationSummaries = notificationSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case notificationSummaries = "NotificationSummaries"
}
}
public struct ListShareInvitationsInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "workloadNamePrefix", location: .querystring(locationName: "WorkloadNamePrefix"))
]
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let nextToken: String?
public let workloadNamePrefix: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, workloadNamePrefix: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.workloadNamePrefix = workloadNamePrefix
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.workloadNamePrefix, name: "workloadNamePrefix", parent: name, max: 100)
}
private enum CodingKeys: CodingKey {}
}
public struct ListShareInvitationsOutput: AWSDecodableShape {
public let nextToken: String?
/// List of share invitation summaries in a workload.
public let shareInvitationSummaries: [ShareInvitationSummary]?
public init(nextToken: String? = nil, shareInvitationSummaries: [ShareInvitationSummary]? = nil) {
self.nextToken = nextToken
self.shareInvitationSummaries = shareInvitationSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case shareInvitationSummaries = "ShareInvitationSummaries"
}
}
public struct ListWorkloadSharesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "sharedWithPrefix", location: .querystring(locationName: "SharedWithPrefix")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let nextToken: String?
/// The AWS account ID or IAM role with which the workload is shared.
public let sharedWithPrefix: String?
public let workloadId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, sharedWithPrefix: String? = nil, workloadId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.sharedWithPrefix = sharedWithPrefix
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.sharedWithPrefix, name: "sharedWithPrefix", parent: name, max: 100)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: CodingKey {}
}
public struct ListWorkloadSharesOutput: AWSDecodableShape {
public let nextToken: String?
public let workloadId: String?
public let workloadShareSummaries: [WorkloadShareSummary]?
public init(nextToken: String? = nil, workloadId: String? = nil, workloadShareSummaries: [WorkloadShareSummary]? = nil) {
self.nextToken = nextToken
self.workloadId = workloadId
self.workloadShareSummaries = workloadShareSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case workloadId = "WorkloadId"
case workloadShareSummaries = "WorkloadShareSummaries"
}
}
public struct ListWorkloadsInput: AWSEncodableShape {
/// The maximum number of results to return for this request.
public let maxResults: Int?
public let nextToken: String?
public let workloadNamePrefix: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, workloadNamePrefix: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.workloadNamePrefix = workloadNamePrefix
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.workloadNamePrefix, name: "workloadNamePrefix", parent: name, max: 100)
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case workloadNamePrefix = "WorkloadNamePrefix"
}
}
public struct ListWorkloadsOutput: AWSDecodableShape {
public let nextToken: String?
public let workloadSummaries: [WorkloadSummary]?
public init(nextToken: String? = nil, workloadSummaries: [WorkloadSummary]? = nil) {
self.nextToken = nextToken
self.workloadSummaries = workloadSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case workloadSummaries = "WorkloadSummaries"
}
}
public struct Milestone: AWSDecodableShape {
public let milestoneName: String?
public let milestoneNumber: Int?
public let recordedAt: Date?
public let workload: Workload?
public init(milestoneName: String? = nil, milestoneNumber: Int? = nil, recordedAt: Date? = nil, workload: Workload? = nil) {
self.milestoneName = milestoneName
self.milestoneNumber = milestoneNumber
self.recordedAt = recordedAt
self.workload = workload
}
private enum CodingKeys: String, CodingKey {
case milestoneName = "MilestoneName"
case milestoneNumber = "MilestoneNumber"
case recordedAt = "RecordedAt"
case workload = "Workload"
}
}
public struct MilestoneSummary: AWSDecodableShape {
public let milestoneName: String?
public let milestoneNumber: Int?
public let recordedAt: Date?
public let workloadSummary: WorkloadSummary?
public init(milestoneName: String? = nil, milestoneNumber: Int? = nil, recordedAt: Date? = nil, workloadSummary: WorkloadSummary? = nil) {
self.milestoneName = milestoneName
self.milestoneNumber = milestoneNumber
self.recordedAt = recordedAt
self.workloadSummary = workloadSummary
}
private enum CodingKeys: String, CodingKey {
case milestoneName = "MilestoneName"
case milestoneNumber = "MilestoneNumber"
case recordedAt = "RecordedAt"
case workloadSummary = "WorkloadSummary"
}
}
public struct NotificationSummary: AWSDecodableShape {
/// Summary of lens upgrade.
public let lensUpgradeSummary: LensUpgradeSummary?
/// The type of notification.
public let type: NotificationType?
public init(lensUpgradeSummary: LensUpgradeSummary? = nil, type: NotificationType? = nil) {
self.lensUpgradeSummary = lensUpgradeSummary
self.type = type
}
private enum CodingKeys: String, CodingKey {
case lensUpgradeSummary = "LensUpgradeSummary"
case type = "Type"
}
}
public struct PillarDifference: AWSDecodableShape {
/// Indicates the type of change to the pillar.
public let differenceStatus: DifferenceStatus?
public let pillarId: String?
/// List of question differences.
public let questionDifferences: [QuestionDifference]?
public init(differenceStatus: DifferenceStatus? = nil, pillarId: String? = nil, questionDifferences: [QuestionDifference]? = nil) {
self.differenceStatus = differenceStatus
self.pillarId = pillarId
self.questionDifferences = questionDifferences
}
private enum CodingKeys: String, CodingKey {
case differenceStatus = "DifferenceStatus"
case pillarId = "PillarId"
case questionDifferences = "QuestionDifferences"
}
}
public struct PillarReviewSummary: AWSDecodableShape {
public let notes: String?
public let pillarId: String?
public let pillarName: String?
public let riskCounts: [Risk: Int]?
public init(notes: String? = nil, pillarId: String? = nil, pillarName: String? = nil, riskCounts: [Risk: Int]? = nil) {
self.notes = notes
self.pillarId = pillarId
self.pillarName = pillarName
self.riskCounts = riskCounts
}
private enum CodingKeys: String, CodingKey {
case notes = "Notes"
case pillarId = "PillarId"
case pillarName = "PillarName"
case riskCounts = "RiskCounts"
}
}
public struct QuestionDifference: AWSDecodableShape {
/// Indicates the type of change to the question.
public let differenceStatus: DifferenceStatus?
public let questionId: String?
public let questionTitle: String?
public init(differenceStatus: DifferenceStatus? = nil, questionId: String? = nil, questionTitle: String? = nil) {
self.differenceStatus = differenceStatus
self.questionId = questionId
self.questionTitle = questionTitle
}
private enum CodingKeys: String, CodingKey {
case differenceStatus = "DifferenceStatus"
case questionId = "QuestionId"
case questionTitle = "QuestionTitle"
}
}
public struct ShareInvitation: AWSDecodableShape {
/// The ID assigned to the share invitation.
public let shareInvitationId: String?
public let workloadId: String?
public init(shareInvitationId: String? = nil, workloadId: String? = nil) {
self.shareInvitationId = shareInvitationId
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case shareInvitationId = "ShareInvitationId"
case workloadId = "WorkloadId"
}
}
public struct ShareInvitationSummary: AWSDecodableShape {
public let permissionType: PermissionType?
public let sharedBy: String?
public let sharedWith: String?
/// The ID assigned to the share invitation.
public let shareInvitationId: String?
public let workloadId: String?
public let workloadName: String?
public init(permissionType: PermissionType? = nil, sharedBy: String? = nil, sharedWith: String? = nil, shareInvitationId: String? = nil, workloadId: String? = nil, workloadName: String? = nil) {
self.permissionType = permissionType
self.sharedBy = sharedBy
self.sharedWith = sharedWith
self.shareInvitationId = shareInvitationId
self.workloadId = workloadId
self.workloadName = workloadName
}
private enum CodingKeys: String, CodingKey {
case permissionType = "PermissionType"
case sharedBy = "SharedBy"
case sharedWith = "SharedWith"
case shareInvitationId = "ShareInvitationId"
case workloadId = "WorkloadId"
case workloadName = "WorkloadName"
}
}
public struct UpdateAnswerInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "questionId", location: .uri(locationName: "QuestionId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let isApplicable: Bool?
public let lensAlias: String
public let notes: String?
public let questionId: String
public let selectedChoices: [String]?
public let workloadId: String
public init(isApplicable: Bool? = nil, lensAlias: String, notes: String? = nil, questionId: String, selectedChoices: [String]? = nil, workloadId: String) {
self.isApplicable = isApplicable
self.lensAlias = lensAlias
self.notes = notes
self.questionId = questionId
self.selectedChoices = selectedChoices
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.notes, name: "notes", parent: name, max: 2084)
try self.validate(self.questionId, name: "questionId", parent: name, max: 128)
try self.validate(self.questionId, name: "questionId", parent: name, min: 1)
try self.selectedChoices?.forEach {
try validate($0, name: "selectedChoices[]", parent: name, max: 64)
try validate($0, name: "selectedChoices[]", parent: name, min: 1)
}
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case isApplicable = "IsApplicable"
case notes = "Notes"
case selectedChoices = "SelectedChoices"
}
}
public struct UpdateAnswerOutput: AWSDecodableShape {
public let answer: Answer?
public let lensAlias: String?
public let workloadId: String?
public init(answer: Answer? = nil, lensAlias: String? = nil, workloadId: String? = nil) {
self.answer = answer
self.lensAlias = lensAlias
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case answer = "Answer"
case lensAlias = "LensAlias"
case workloadId = "WorkloadId"
}
}
public struct UpdateLensReviewInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let lensAlias: String
public let lensNotes: String?
public let pillarNotes: [String: String]?
public let workloadId: String
public init(lensAlias: String, lensNotes: String? = nil, pillarNotes: [String: String]? = nil, workloadId: String) {
self.lensAlias = lensAlias
self.lensNotes = lensNotes
self.pillarNotes = pillarNotes
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.lensNotes, name: "lensNotes", parent: name, max: 2084)
try self.pillarNotes?.forEach {
try validate($0.key, name: "pillarNotes.key", parent: name, max: 64)
try validate($0.key, name: "pillarNotes.key", parent: name, min: 1)
try validate($0.value, name: "pillarNotes[\"\($0.key)\"]", parent: name, max: 2084)
}
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case lensNotes = "LensNotes"
case pillarNotes = "PillarNotes"
}
}
public struct UpdateLensReviewOutput: AWSDecodableShape {
public let lensReview: LensReview?
public let workloadId: String?
public init(lensReview: LensReview? = nil, workloadId: String? = nil) {
self.lensReview = lensReview
self.workloadId = workloadId
}
private enum CodingKeys: String, CodingKey {
case lensReview = "LensReview"
case workloadId = "WorkloadId"
}
}
public struct UpdateShareInvitationInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "shareInvitationId", location: .uri(locationName: "ShareInvitationId"))
]
public let shareInvitationAction: ShareInvitationAction
/// The ID assigned to the share invitation.
public let shareInvitationId: String
public init(shareInvitationAction: ShareInvitationAction, shareInvitationId: String) {
self.shareInvitationAction = shareInvitationAction
self.shareInvitationId = shareInvitationId
}
public func validate(name: String) throws {
try self.validate(self.shareInvitationId, name: "shareInvitationId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case shareInvitationAction = "ShareInvitationAction"
}
}
public struct UpdateShareInvitationOutput: AWSDecodableShape {
/// The updated workload share invitation.
public let shareInvitation: ShareInvitation?
public init(shareInvitation: ShareInvitation? = nil) {
self.shareInvitation = shareInvitation
}
private enum CodingKeys: String, CodingKey {
case shareInvitation = "ShareInvitation"
}
}
public struct UpdateWorkloadInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let accountIds: [String]?
public let architecturalDesign: String?
public let awsRegions: [String]?
public let description: String?
public let environment: WorkloadEnvironment?
public let improvementStatus: WorkloadImprovementStatus?
public let industry: String?
public let industryType: String?
/// Flag indicating whether the workload owner has acknowledged that the Review owner field is required. If a Review owner is not added to the workload within 60 days of acknowledgement, access to the workload is restricted until an owner is added.
public let isReviewOwnerUpdateAcknowledged: Bool?
public let nonAwsRegions: [String]?
public let notes: String?
public let pillarPriorities: [String]?
public let reviewOwner: String?
public let workloadId: String
public let workloadName: String?
public init(accountIds: [String]? = nil, architecturalDesign: String? = nil, awsRegions: [String]? = nil, description: String? = nil, environment: WorkloadEnvironment? = nil, improvementStatus: WorkloadImprovementStatus? = nil, industry: String? = nil, industryType: String? = nil, isReviewOwnerUpdateAcknowledged: Bool? = nil, nonAwsRegions: [String]? = nil, notes: String? = nil, pillarPriorities: [String]? = nil, reviewOwner: String? = nil, workloadId: String, workloadName: String? = nil) {
self.accountIds = accountIds
self.architecturalDesign = architecturalDesign
self.awsRegions = awsRegions
self.description = description
self.environment = environment
self.improvementStatus = improvementStatus
self.industry = industry
self.industryType = industryType
self.isReviewOwnerUpdateAcknowledged = isReviewOwnerUpdateAcknowledged
self.nonAwsRegions = nonAwsRegions
self.notes = notes
self.pillarPriorities = pillarPriorities
self.reviewOwner = reviewOwner
self.workloadId = workloadId
self.workloadName = workloadName
}
public func validate(name: String) throws {
try self.accountIds?.forEach {
try validate($0, name: "accountIds[]", parent: name, pattern: "[0-9]{12}")
}
try self.validate(self.accountIds, name: "accountIds", parent: name, max: 100)
try self.validate(self.architecturalDesign, name: "architecturalDesign", parent: name, max: 2048)
try self.awsRegions?.forEach {
try validate($0, name: "awsRegions[]", parent: name, max: 100)
}
try self.validate(self.awsRegions, name: "awsRegions", parent: name, max: 50)
try self.validate(self.description, name: "description", parent: name, max: 250)
try self.validate(self.description, name: "description", parent: name, min: 3)
try self.validate(self.industry, name: "industry", parent: name, max: 100)
try self.validate(self.industryType, name: "industryType", parent: name, max: 100)
try self.nonAwsRegions?.forEach {
try validate($0, name: "nonAwsRegions[]", parent: name, max: 25)
try validate($0, name: "nonAwsRegions[]", parent: name, min: 3)
}
try self.validate(self.nonAwsRegions, name: "nonAwsRegions", parent: name, max: 5)
try self.validate(self.notes, name: "notes", parent: name, max: 2084)
try self.pillarPriorities?.forEach {
try validate($0, name: "pillarPriorities[]", parent: name, max: 64)
try validate($0, name: "pillarPriorities[]", parent: name, min: 1)
}
try self.validate(self.reviewOwner, name: "reviewOwner", parent: name, max: 255)
try self.validate(self.reviewOwner, name: "reviewOwner", parent: name, min: 3)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
try self.validate(self.workloadName, name: "workloadName", parent: name, max: 100)
try self.validate(self.workloadName, name: "workloadName", parent: name, min: 3)
}
private enum CodingKeys: String, CodingKey {
case accountIds = "AccountIds"
case architecturalDesign = "ArchitecturalDesign"
case awsRegions = "AwsRegions"
case description = "Description"
case environment = "Environment"
case improvementStatus = "ImprovementStatus"
case industry = "Industry"
case industryType = "IndustryType"
case isReviewOwnerUpdateAcknowledged = "IsReviewOwnerUpdateAcknowledged"
case nonAwsRegions = "NonAwsRegions"
case notes = "Notes"
case pillarPriorities = "PillarPriorities"
case reviewOwner = "ReviewOwner"
case workloadName = "WorkloadName"
}
}
public struct UpdateWorkloadOutput: AWSDecodableShape {
public let workload: Workload?
public init(workload: Workload? = nil) {
self.workload = workload
}
private enum CodingKeys: String, CodingKey {
case workload = "Workload"
}
}
public struct UpdateWorkloadShareInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "shareId", location: .uri(locationName: "ShareId")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let permissionType: PermissionType
public let shareId: String
public let workloadId: String
public init(permissionType: PermissionType, shareId: String, workloadId: String) {
self.permissionType = permissionType
self.shareId = shareId
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.shareId, name: "shareId", parent: name, pattern: "[0-9a-f]{32}")
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case permissionType = "PermissionType"
}
}
public struct UpdateWorkloadShareOutput: AWSDecodableShape {
public let workloadId: String?
public let workloadShare: WorkloadShare?
public init(workloadId: String? = nil, workloadShare: WorkloadShare? = nil) {
self.workloadId = workloadId
self.workloadShare = workloadShare
}
private enum CodingKeys: String, CodingKey {
case workloadId = "WorkloadId"
case workloadShare = "WorkloadShare"
}
}
public struct UpgradeLensReviewInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "lensAlias", location: .uri(locationName: "LensAlias")),
AWSMemberEncoding(label: "workloadId", location: .uri(locationName: "WorkloadId"))
]
public let clientRequestToken: String?
public let lensAlias: String
public let milestoneName: String
public let workloadId: String
public init(clientRequestToken: String? = nil, lensAlias: String, milestoneName: String, workloadId: String) {
self.clientRequestToken = clientRequestToken
self.lensAlias = lensAlias
self.milestoneName = milestoneName
self.workloadId = workloadId
}
public func validate(name: String) throws {
try self.validate(self.lensAlias, name: "lensAlias", parent: name, max: 64)
try self.validate(self.lensAlias, name: "lensAlias", parent: name, min: 1)
try self.validate(self.milestoneName, name: "milestoneName", parent: name, max: 100)
try self.validate(self.milestoneName, name: "milestoneName", parent: name, min: 3)
try self.validate(self.workloadId, name: "workloadId", parent: name, pattern: "[0-9a-f]{32}")
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken = "ClientRequestToken"
case milestoneName = "MilestoneName"
}
}
public struct VersionDifferences: AWSDecodableShape {
/// The differences between the base and latest versions of the lens.
public let pillarDifferences: [PillarDifference]?
public init(pillarDifferences: [PillarDifference]? = nil) {
self.pillarDifferences = pillarDifferences
}
private enum CodingKeys: String, CodingKey {
case pillarDifferences = "PillarDifferences"
}
}
public struct Workload: AWSDecodableShape {
public let accountIds: [String]?
public let architecturalDesign: String?
public let awsRegions: [String]?
public let description: String?
public let environment: WorkloadEnvironment?
public let improvementStatus: WorkloadImprovementStatus?
public let industry: String?
public let industryType: String?
/// Flag indicating whether the workload owner has acknowledged that the Review owner field is required. If a Review owner is not added to the workload within 60 days of acknowledgement, access to the workload is restricted until an owner is added.
public let isReviewOwnerUpdateAcknowledged: Bool?
public let lenses: [String]?
public let nonAwsRegions: [String]?
public let notes: String?
public let owner: String?
public let pillarPriorities: [String]?
public let reviewOwner: String?
public let reviewRestrictionDate: Date?
public let riskCounts: [Risk: Int]?
/// The ID assigned to the share invitation.
public let shareInvitationId: String?
public let updatedAt: Date?
public let workloadArn: String?
public let workloadId: String?
public let workloadName: String?
public init(accountIds: [String]? = nil, architecturalDesign: String? = nil, awsRegions: [String]? = nil, description: String? = nil, environment: WorkloadEnvironment? = nil, improvementStatus: WorkloadImprovementStatus? = nil, industry: String? = nil, industryType: String? = nil, isReviewOwnerUpdateAcknowledged: Bool? = nil, lenses: [String]? = nil, nonAwsRegions: [String]? = nil, notes: String? = nil, owner: String? = nil, pillarPriorities: [String]? = nil, reviewOwner: String? = nil, reviewRestrictionDate: Date? = nil, riskCounts: [Risk: Int]? = nil, shareInvitationId: String? = nil, updatedAt: Date? = nil, workloadArn: String? = nil, workloadId: String? = nil, workloadName: String? = nil) {
self.accountIds = accountIds
self.architecturalDesign = architecturalDesign
self.awsRegions = awsRegions
self.description = description
self.environment = environment
self.improvementStatus = improvementStatus
self.industry = industry
self.industryType = industryType
self.isReviewOwnerUpdateAcknowledged = isReviewOwnerUpdateAcknowledged
self.lenses = lenses
self.nonAwsRegions = nonAwsRegions
self.notes = notes
self.owner = owner
self.pillarPriorities = pillarPriorities
self.reviewOwner = reviewOwner
self.reviewRestrictionDate = reviewRestrictionDate
self.riskCounts = riskCounts
self.shareInvitationId = shareInvitationId
self.updatedAt = updatedAt
self.workloadArn = workloadArn
self.workloadId = workloadId
self.workloadName = workloadName
}
private enum CodingKeys: String, CodingKey {
case accountIds = "AccountIds"
case architecturalDesign = "ArchitecturalDesign"
case awsRegions = "AwsRegions"
case description = "Description"
case environment = "Environment"
case improvementStatus = "ImprovementStatus"
case industry = "Industry"
case industryType = "IndustryType"
case isReviewOwnerUpdateAcknowledged = "IsReviewOwnerUpdateAcknowledged"
case lenses = "Lenses"
case nonAwsRegions = "NonAwsRegions"
case notes = "Notes"
case owner = "Owner"
case pillarPriorities = "PillarPriorities"
case reviewOwner = "ReviewOwner"
case reviewRestrictionDate = "ReviewRestrictionDate"
case riskCounts = "RiskCounts"
case shareInvitationId = "ShareInvitationId"
case updatedAt = "UpdatedAt"
case workloadArn = "WorkloadArn"
case workloadId = "WorkloadId"
case workloadName = "WorkloadName"
}
}
public struct WorkloadShare: AWSDecodableShape {
public let permissionType: PermissionType?
public let sharedBy: String?
public let sharedWith: String?
public let shareId: String?
public let status: ShareStatus?
public let workloadId: String?
public let workloadName: String?
public init(permissionType: PermissionType? = nil, sharedBy: String? = nil, sharedWith: String? = nil, shareId: String? = nil, status: ShareStatus? = nil, workloadId: String? = nil, workloadName: String? = nil) {
self.permissionType = permissionType
self.sharedBy = sharedBy
self.sharedWith = sharedWith
self.shareId = shareId
self.status = status
self.workloadId = workloadId
self.workloadName = workloadName
}
private enum CodingKeys: String, CodingKey {
case permissionType = "PermissionType"
case sharedBy = "SharedBy"
case sharedWith = "SharedWith"
case shareId = "ShareId"
case status = "Status"
case workloadId = "WorkloadId"
case workloadName = "WorkloadName"
}
}
public struct WorkloadShareSummary: AWSDecodableShape {
public let permissionType: PermissionType?
public let sharedWith: String?
public let shareId: String?
public let status: ShareStatus?
public init(permissionType: PermissionType? = nil, sharedWith: String? = nil, shareId: String? = nil, status: ShareStatus? = nil) {
self.permissionType = permissionType
self.sharedWith = sharedWith
self.shareId = shareId
self.status = status
}
private enum CodingKeys: String, CodingKey {
case permissionType = "PermissionType"
case sharedWith = "SharedWith"
case shareId = "ShareId"
case status = "Status"
}
}
public struct WorkloadSummary: AWSDecodableShape {
public let improvementStatus: WorkloadImprovementStatus?
public let lenses: [String]?
public let owner: String?
public let riskCounts: [Risk: Int]?
public let updatedAt: Date?
public let workloadArn: String?
public let workloadId: String?
public let workloadName: String?
public init(improvementStatus: WorkloadImprovementStatus? = nil, lenses: [String]? = nil, owner: String? = nil, riskCounts: [Risk: Int]? = nil, updatedAt: Date? = nil, workloadArn: String? = nil, workloadId: String? = nil, workloadName: String? = nil) {
self.improvementStatus = improvementStatus
self.lenses = lenses
self.owner = owner
self.riskCounts = riskCounts
self.updatedAt = updatedAt
self.workloadArn = workloadArn
self.workloadId = workloadId
self.workloadName = workloadName
}
private enum CodingKeys: String, CodingKey {
case improvementStatus = "ImprovementStatus"
case lenses = "Lenses"
case owner = "Owner"
case riskCounts = "RiskCounts"
case updatedAt = "UpdatedAt"
case workloadArn = "WorkloadArn"
case workloadId = "WorkloadId"
case workloadName = "WorkloadName"
}
}
}
| 43.018668 | 711 | 0.631352 |
50e5a0447eb0cab84cf72c9cb5212a92ca604cac | 800 | //
// AttributionNetwork.swift
// PurchasesCoreSwift
//
// Created by César de la Vega on 6/18/21.
// Copyright © 2021 Purchases. All rights reserved.
//
import Foundation
enum AttributionNetwork: Int {
/**
Apple's search ads
*/
case appleSearchAds = 0,
/**
Adjust https://www.adjust.com/
*/
adjust,
/**
AppsFlyer https://www.appsflyer.com/
*/
appsFlyer,
/**
Branch https://www.branch.io/
*/
branch,
/**
Tenjin https://www.tenjin.io/
*/
tenjin,
/**
Facebook https://developers.facebook.com/
*/
facebook,
/**
mParticle https://www.mparticle.com/
*/
mParticle
}
| 19.512195 | 52 | 0.48375 |
261479995d1fe1a82dc75257ec0f83f13f7c9e8c | 61,789 | //
// ParseObjectBatchTests.swift
// ParseSwiftTests
//
// Created by Corey Baker on 7/27/20.
// Copyright © 2020 Parse Community. All rights reserved.
//
import Foundation
import XCTest
@testable import ParseSwift
class ParseObjectBatchTests: XCTestCase { // swiftlint:disable:this type_body_length
struct GameScore: ParseObject {
// Those are required for Object
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
// Custom properties
var score: Int = 0
//custom initializers
init(score: Int) {
self.score = score
}
init(objectId: String?) {
self.objectId = objectId
}
}
override func setUpWithError() throws {
try super.setUpWithError()
guard let url = URL(string: "http://localhost:1337/1") else {
XCTFail("Should create valid URL")
return
}
ParseSwift.initialize(applicationId: "applicationId",
clientKey: "clientKey",
masterKey: "masterKey",
serverURL: url,
testing: true)
}
override func tearDownWithError() throws {
try super.tearDownWithError()
MockURLProtocol.removeAll()
#if !os(Linux) && !os(Android)
try KeychainStore.shared.deleteAll()
#endif
try ParseStorage.shared.deleteAll()
}
//COREY: Linux decodes this differently for some reason
#if !os(Linux) && !os(Android)
func testSaveAllCommand() throws {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let objects = [score, score2]
let commands = objects.map { $0.saveCommand() }
let body = BatchCommand(requests: commands, transaction: false)
// swiftlint:disable:next line_length
let expected = "{\"requests\":[{\"path\":\"\\/classes\\/GameScore\",\"method\":\"POST\",\"body\":{\"score\":10}},{\"path\":\"\\/classes\\/GameScore\",\"method\":\"POST\",\"body\":{\"score\":20}}],\"transaction\":false}"
let encoded = try ParseCoding.parseEncoder()
.encode(body, collectChildren: false,
objectsSavedBeforeThisOne: nil,
filesSavedBeforeThisOne: nil).encoded
let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8))
XCTAssertEqual(decoded, expected)
}
#endif
func testSaveAll() { // swiftlint:disable:this function_body_length cyclomatic_complexity
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try scoreOnServer.getJSONEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let saved = try [score, score2].saveAll()
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
XCTAssert(second.hasSameObjectId(as: scoreOnServer2))
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
do {
let saved = try [score, score2].saveAll(transaction: true,
options: [.installationId("hello")])
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
XCTAssert(second.hasSameObjectId(as: scoreOnServer2))
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
}
func testSaveAllErrorIncorrectServerResponse() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
MockURLProtocol.mockRequests { _ in
do {
let encoded = try ParseCoding.jsonEncoder().encode([scoreOnServer, scoreOnServer2])
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
} catch {
return nil
}
}
do {
let saved = try [score, score2].saveAll()
XCTAssertEqual(saved.count, 2)
XCTAssertThrowsError(try saved[0].get())
XCTAssertThrowsError(try saved[1].get())
} catch {
XCTFail(error.localizedDescription)
}
do {
let saved = try [score, score2].saveAll(transaction: true,
options: [.useMasterKey])
XCTAssertEqual(saved.count, 2)
XCTAssertThrowsError(try saved[0].get())
XCTAssertThrowsError(try saved[1].get())
} catch {
XCTFail(error.localizedDescription)
}
}
#if !os(Linux) && !os(Android)
func testUpdateAllCommand() throws {
var score = GameScore(score: 10)
var score2 = GameScore(score: 20)
score.objectId = "yarr"
score.createdAt = Date()
score.updatedAt = score.createdAt
score2.objectId = "yolo"
score2.createdAt = Date()
score2.updatedAt = score2.createdAt
let objects = [score, score2]
let initialCommands = objects.map { $0.saveCommand() }
let commands = initialCommands.compactMap { (command) -> API.Command<GameScore, GameScore>? in
let path = ParseConfiguration.mountPath + command.path.urlComponent
guard let body = command.body else {
return nil
}
return API.Command<GameScore, GameScore>(method: command.method, path: .any(path),
body: body, mapper: command.mapper)
}
let body = BatchCommand(requests: commands, transaction: false)
// swiftlint:disable:next line_length
let expected = "{\"requests\":[{\"path\":\"\\/1\\/classes\\/GameScore\\/yarr\",\"method\":\"PUT\",\"body\":{\"score\":10}},{\"path\":\"\\/1\\/classes\\/GameScore\\/yolo\",\"method\":\"PUT\",\"body\":{\"score\":20}}],\"transaction\":false}"
let encoded = try ParseCoding.parseEncoder()
.encode(body, collectChildren: false,
objectsSavedBeforeThisOne: nil,
filesSavedBeforeThisOne: nil).encoded
let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8))
XCTAssertEqual(decoded, expected)
}
#endif
func testUpdateAll() { // swiftlint:disable:this function_body_length cyclomatic_complexity
var score = GameScore(score: 10)
score.objectId = "yarr"
score.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.ACL = nil
var score2 = GameScore(score: 20)
score2.objectId = "yolo"
score2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.updatedAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.ACL = nil
var scoreOnServer = score
scoreOnServer.updatedAt = Date()
var scoreOnServer2 = score2
scoreOnServer2.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let saved = try [score, score2].saveAll()
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
guard let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalUpdatedAt = score.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertGreaterThan(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
guard let savedUpdatedAt2 = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalUpdatedAt2 = score2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertGreaterThan(savedUpdatedAt2, originalUpdatedAt2)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
do {
let saved = try [score, score2].saveAll(transaction: true,
options: [.useMasterKey])
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
guard let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalUpdatedAt = score.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertGreaterThan(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
guard let savedUpdatedAt2 = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalUpdatedAt2 = score2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertGreaterThan(savedUpdatedAt2, originalUpdatedAt2)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
}
func testUpdateAllErrorIncorrectServerResponse() {
var score = GameScore(score: 10)
score.objectId = "yarr"
score.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.ACL = nil
var score2 = GameScore(score: 20)
score2.objectId = "yolo"
score2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.updatedAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.ACL = nil
var scoreOnServer = score
scoreOnServer.updatedAt = Date()
var scoreOnServer2 = score2
scoreOnServer2.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
MockURLProtocol.mockRequests { _ in
do {
let encoded = try ParseCoding.jsonEncoder().encode([scoreOnServer, scoreOnServer2])
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
} catch {
return nil
}
}
do {
let saved = try [score, score2].saveAll()
XCTAssertEqual(saved.count, 2)
XCTAssertThrowsError(try saved[0].get())
XCTAssertThrowsError(try saved[1].get())
} catch {
XCTFail(error.localizedDescription)
}
do {
let saved = try [score, score2].saveAll(transaction: true,
options: [.useMasterKey])
XCTAssertEqual(saved.count, 2)
XCTAssertThrowsError(try saved[0].get())
XCTAssertThrowsError(try saved[1].get())
} catch {
XCTFail(error.localizedDescription)
}
}
func testSaveAllMixed() { // swiftlint:disable:this function_body_length cyclomatic_complexity
let score = GameScore(score: 10)
var score2 = GameScore(score: 20)
score2.objectId = "yolo"
score2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.updatedAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.ACL = nil
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let saved = try [score, score2].saveAll()
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = score2.createdAt,
let originalUpdatedAt = score2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertGreaterThan(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
do {
let saved = try [score, score2].saveAll(transaction: true,
options: [.useMasterKey])
XCTAssertEqual(saved.count, 2)
switch saved[0] {
case .success(let first):
XCTAssertNotNil(first.createdAt)
XCTAssertNotNil(first.updatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch saved[1] {
case .success(let second):
XCTAssertNotNil(second.createdAt)
XCTAssertNotNil(second.updatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
}
func saveAllAsync(scores: [GameScore], // swiftlint:disable:this function_body_length cyclomatic_complexity
scoresOnServer: [GameScore], callbackQueue: DispatchQueue) {
let expectation1 = XCTestExpectation(description: "Save object1")
guard let scoreOnServer = scoresOnServer.first,
let scoreOnServer2 = scoresOnServer.last else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
scores.saveAll(callbackQueue: callbackQueue) { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.count, 2)
guard let firstObject = saved.first,
let secondObject = saved.last else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
switch firstObject {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
XCTAssert(second.hasSameObjectId(as: scoreOnServer2))
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
let expectation2 = XCTestExpectation(description: "Save object2")
scores.saveAll(transaction: true,
options: [.useMasterKey],
callbackQueue: callbackQueue) { result in
switch result {
case .success(let saved):
XCTAssertEqual(saved.count, 2)
guard let firstObject = saved.first,
let secondObject = saved.last else {
XCTFail("Should unwrap")
expectation2.fulfill()
return
}
switch firstObject {
case .success(let first):
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation2.fulfill()
}
wait(for: [expectation1, expectation2], timeout: 20.0)
}
#if !os(Linux) && !os(Android)
func testThreadSafeSaveAllAsync() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
DispatchQueue.concurrentPerform(iterations: 100) {_ in
self.saveAllAsync(scores: [score, score2], scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .global(qos: .background))
}
}
#endif
func testSaveAllAsyncMainQueue() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
self.saveAllAsync(scores: [score, score2], scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .main)
}
/* Note, the current batchCommand for updateAll returns the original object that was updated as
opposed to the latestUpdated. The objective c one just returns true/false */
// swiftlint:disable:next function_body_length cyclomatic_complexity
func updateAllAsync(scores: [GameScore], scoresOnServer: [GameScore],
callbackQueue: DispatchQueue) {
let expectation1 = XCTestExpectation(description: "Update object1")
scores.saveAll(callbackQueue: callbackQueue) { result in
switch result {
case .success(let saved):
guard let firstObject = saved.first,
let secondObject = saved.last else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
switch firstObject {
case .success(let first):
guard let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalUpdatedAt = scores.first?.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertGreaterThan(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
guard let savedUpdatedAt2 = second.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalUpdatedAt2 = scores.last?.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertGreaterThan(savedUpdatedAt2,
originalUpdatedAt2)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
let expectation2 = XCTestExpectation(description: "Update object2")
scores.saveAll(transaction: true,
options: [.useMasterKey],
callbackQueue: callbackQueue) { result in
switch result {
case .success(let saved):
guard let firstObject = saved.first,
let secondObject = saved.last else {
expectation2.fulfill()
XCTFail("Should unwrap")
return
}
switch firstObject {
case .success(let first):
guard let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
guard let originalUpdatedAt = scores.first?.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
XCTAssertGreaterThan(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
guard let savedUpdatedAt2 = second.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
guard let originalUpdatedAt2 = scores.last?.updatedAt else {
XCTFail("Should unwrap dates")
expectation2.fulfill()
return
}
XCTAssertGreaterThan(savedUpdatedAt2,
originalUpdatedAt2)
XCTAssertNil(second.ACL)
case .failure(let error):
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation2.fulfill()
}
wait(for: [expectation1, expectation2], timeout: 20.0)
}
#if !os(Linux) && !os(Android)
func testThreadSafeUpdateAllAsync() {
var score = GameScore(score: 10)
score.objectId = "yarr"
score.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.ACL = nil
var score2 = GameScore(score: 20)
score2.objectId = "yolo"
score2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.updatedAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.ACL = nil
var scoreOnServer = score
scoreOnServer.updatedAt = Date()
var scoreOnServer2 = score2
scoreOnServer2.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
DispatchQueue.concurrentPerform(iterations: 100) {_ in
self.updateAllAsync(scores: [score, score2],
scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .global(qos: .background))
}
}
func testUpdateAllAsyncMainQueue() {
var score = GameScore(score: 10)
score.objectId = "yarr"
score.createdAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
score.ACL = nil
var score2 = GameScore(score: 20)
score2.objectId = "yolo"
score2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.updatedAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
score2.ACL = nil
var scoreOnServer = score
scoreOnServer.updatedAt = Date()
var scoreOnServer2 = score2
scoreOnServer2.updatedAt = Calendar.current.date(byAdding: .init(day: -1), to: Date())
let response = [BatchResponseItem<GameScore>(success: scoreOnServer, error: nil),
BatchResponseItem<GameScore>(success: scoreOnServer2, error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
self.updateAllAsync(scores: [score, score2],
scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .main)
}
#endif
// swiftlint:disable:next function_body_length cyclomatic_complexity
func testFetchAll() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = QueryResponse<GameScore>(results: [scoreOnServer, scoreOnServer2], count: 2)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let fetched = try [GameScore(objectId: "yarr"), GameScore(objectId: "yolo")].fetchAll()
XCTAssertEqual(fetched.count, 2)
guard let firstObject = try? fetched.first(where: {try $0.get().objectId == "yarr"}),
let secondObject = try? fetched.first(where: {try $0.get().objectId == "yolo"}) else {
XCTFail("Should unwrap")
return
}
switch firstObject {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let fetchedCreatedAt = first.createdAt,
let fetchedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(fetchedCreatedAt, originalCreatedAt)
XCTAssertEqual(fetchedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
XCTAssertEqual(first.score, scoreOnServer.score)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
XCTAssert(second.hasSameObjectId(as: scoreOnServer2))
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
XCTAssertEqual(second.score, scoreOnServer2.score)
case .failure(let error):
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
}
// swiftlint:disable:next function_body_length cyclomatic_complexity
func fetchAllAsync(scores: [GameScore], scoresOnServer: [GameScore],
callbackQueue: DispatchQueue) {
let expectation1 = XCTestExpectation(description: "Fetch object1")
guard let scoreOnServer = scoresOnServer.first,
let scoreOnServer2 = scoresOnServer.last else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
[GameScore(objectId: "yarr"), GameScore(objectId: "yolo")].fetchAll(options: [],
callbackQueue: callbackQueue) { result in
switch result {
case .success(let fetched):
XCTAssertEqual(fetched.count, 2)
guard let firstObject = try? fetched.first(where: {try $0.get().objectId == "yarr"}),
let secondObject = try? fetched.first(where: {try $0.get().objectId == "yolo"}) else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
switch firstObject {
case .success(let first):
XCTAssert(first.hasSameObjectId(as: scoreOnServer))
guard let savedCreatedAt = first.createdAt,
let savedUpdatedAt = first.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer.createdAt,
let originalUpdatedAt = scoreOnServer.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(first.ACL)
XCTAssertEqual(first.score, scoreOnServer.score)
case .failure(let error):
XCTFail(error.localizedDescription)
}
switch secondObject {
case .success(let second):
XCTAssert(second.hasSameObjectId(as: scoreOnServer2))
guard let savedCreatedAt = second.createdAt,
let savedUpdatedAt = second.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
guard let originalCreatedAt = scoreOnServer2.createdAt,
let originalUpdatedAt = scoreOnServer2.updatedAt else {
XCTFail("Should unwrap dates")
expectation1.fulfill()
return
}
XCTAssertEqual(savedCreatedAt, originalCreatedAt)
XCTAssertEqual(savedUpdatedAt, originalUpdatedAt)
XCTAssertNil(second.ACL)
XCTAssertEqual(second.score, scoreOnServer2.score)
case .failure(let error):
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
#if !os(Linux) && !os(Android)
func testThreadSafeFetchAllAsync() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = QueryResponse<GameScore>(results: [scoreOnServer, scoreOnServer2], count: 2)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
DispatchQueue.concurrentPerform(iterations: 100) {_ in
self.fetchAllAsync(scores: [score, score2], scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .global(qos: .background))
}
}
#endif
func testFetchAllAsyncMainQueue() {
let score = GameScore(score: 10)
let score2 = GameScore(score: 20)
var scoreOnServer = score
scoreOnServer.objectId = "yarr"
scoreOnServer.createdAt = Date()
scoreOnServer.updatedAt = scoreOnServer.createdAt
scoreOnServer.ACL = nil
var scoreOnServer2 = score2
scoreOnServer2.objectId = "yolo"
scoreOnServer2.createdAt = Calendar.current.date(byAdding: .init(day: -2), to: Date())
scoreOnServer2.updatedAt = scoreOnServer2.createdAt
scoreOnServer2.ACL = nil
let response = QueryResponse<GameScore>(results: [scoreOnServer, scoreOnServer2], count: 2)
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
//Get dates in correct format from ParseDecoding strategy
let encoded1 = try ParseCoding.jsonEncoder().encode(scoreOnServer)
scoreOnServer = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded1)
let encoded2 = try ParseCoding.jsonEncoder().encode(scoreOnServer2)
scoreOnServer2 = try scoreOnServer.getDecoder().decode(GameScore.self, from: encoded2)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
self.fetchAllAsync(scores: [score, score2], scoresOnServer: [scoreOnServer, scoreOnServer2],
callbackQueue: .main)
}
func testDeleteAll() {
let response = [BatchResponseItem<NoBody>(success: NoBody(), error: nil),
BatchResponseItem<NoBody>(success: NoBody(), error: nil)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let deleted = try [GameScore(objectId: "yarr"), GameScore(objectId: "yolo")].deleteAll()
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should unwrap")
return
}
if case let .failure(error) = firstObject {
XCTFail(error.localizedDescription)
}
guard let lastObject = deleted.last else {
XCTFail("Should unwrap")
return
}
if case let .failure(error) = lastObject {
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
do {
let deleted = try [GameScore(objectId: "yarr"), GameScore(objectId: "yolo")]
.deleteAll(transaction: true)
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should unwrap")
return
}
if case let .failure(error) = firstObject {
XCTFail(error.localizedDescription)
}
guard let lastObject = deleted.last else {
XCTFail("Should unwrap")
return
}
if case let .failure(error) = lastObject {
XCTFail(error.localizedDescription)
}
} catch {
XCTFail(error.localizedDescription)
}
}
#if !os(Linux) && !os(Android)
func testDeleteAllError() {
let parseError = ParseError(code: .objectNotFound, message: "Object not found")
let response = [BatchResponseItem<NoBody>(success: nil, error: parseError),
BatchResponseItem<NoBody>(success: nil, error: parseError)]
let encoded: Data!
do {
encoded = try ParseCoding.jsonEncoder().encode(response)
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
do {
let deleted = try [GameScore(objectId: "yarr"), GameScore(objectId: "yolo")].deleteAll()
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should have thrown ParseError")
return
}
if case let .failure(error) = firstObject {
XCTAssertEqual(error.code, parseError.code)
} else {
XCTFail("Should have thrown ParseError")
}
guard let lastObject = deleted.last else {
XCTFail("Should have thrown ParseError")
return
}
if case let .failure(error) = lastObject {
XCTAssertEqual(error.code, parseError.code)
} else {
XCTFail("Should have thrown ParseError")
}
} catch {
XCTFail(error.localizedDescription)
}
}
#endif
func deleteAllAsync(callbackQueue: DispatchQueue) {
let expectation1 = XCTestExpectation(description: "Delete object1")
let expectation2 = XCTestExpectation(description: "Delete object2")
[GameScore(objectId: "yarr"), GameScore(objectId: "yolo")]
.deleteAll(callbackQueue: callbackQueue) { result in
switch result {
case .success(let deleted):
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
if case let .failure(error) = firstObject {
XCTFail(error.localizedDescription)
}
guard let lastObject = deleted.last else {
XCTFail("Should unwrap")
expectation1.fulfill()
return
}
if case let .failure(error) = lastObject {
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
[GameScore(objectId: "yarr"), GameScore(objectId: "yolo")]
.deleteAll(transaction: true,
callbackQueue: callbackQueue) { result in
switch result {
case .success(let deleted):
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should unwrap")
expectation2.fulfill()
return
}
if case let .failure(error) = firstObject {
XCTFail(error.localizedDescription)
}
guard let lastObject = deleted.last else {
XCTFail("Should unwrap")
expectation2.fulfill()
return
}
if case let .failure(error) = lastObject {
XCTFail(error.localizedDescription)
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation2.fulfill()
}
wait(for: [expectation1, expectation2], timeout: 20.0)
}
func testDeleteAllAsyncMainQueue() {
let response = [BatchResponseItem<NoBody>(success: NoBody(), error: nil),
BatchResponseItem<NoBody>(success: NoBody(), error: nil)]
do {
let encoded = try ParseCoding.jsonEncoder().encode(response)
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
self.deleteAllAsync(callbackQueue: .main)
}
func deleteAllAsyncError(parseError: ParseError, callbackQueue: DispatchQueue) {
let expectation1 = XCTestExpectation(description: "Delete object1")
[GameScore(objectId: "yarr"), GameScore(objectId: "yolo")]
.deleteAll(callbackQueue: callbackQueue) { result in
switch result {
case .success(let deleted):
XCTAssertEqual(deleted.count, 2)
guard let firstObject = deleted.first else {
XCTFail("Should have thrown ParseError")
expectation1.fulfill()
return
}
if case let .failure(error) = firstObject {
XCTAssertEqual(error.code, parseError.code)
} else {
XCTFail("Should have thrown ParseError")
}
guard let lastObject = deleted.last else {
XCTFail("Should have thrown ParseError")
expectation1.fulfill()
return
}
if case let .failure(error) = lastObject {
XCTAssertEqual(error.code, parseError.code)
} else {
XCTFail("Should have thrown ParseError")
}
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 20.0)
}
func testDeleteAllAsyncMainQueueError() {
let parseError = ParseError(code: .objectNotFound, message: "Object not found")
let response = [BatchResponseItem<NoBody>(success: nil, error: parseError),
BatchResponseItem<NoBody>(success: nil, error: parseError)]
do {
let encoded = try ParseCoding.jsonEncoder().encode(response)
MockURLProtocol.mockRequests { _ in
return MockURLResponse(data: encoded, statusCode: 200, delay: 0.0)
}
} catch {
XCTFail("Should have encoded/decoded. Error \(error)")
return
}
self.deleteAllAsyncError(parseError: parseError, callbackQueue: .main)
}
}// swiftlint:disable:this file_length
| 39.280992 | 247 | 0.552121 |
7aa731b3b841abab4a0000fa503946d33be36dbb | 1,748 | //
// Bus.swift
// Calibre
//
// Created by Jeremy Tregunna on 11/10/16.
// Copyright © 2016 Greenshire, Inc. All rights reserved.
//
import Foundation
public enum BusError: Error {
case timeout
}
public class Bus<T> {
private let queue: DispatchQueue
private let semaphore: DispatchSemaphore
private let timeoutTime: DispatchTime
private var stream: Array<T>
/** Create a new bus.
- parameter timeout: Read timeout in seconds. Supports subsecond values. If negative, no timeout. Default value: `-1`.
*/
public init(timeout: Double = -1) {
queue = DispatchQueue(label: "co.greenshire.library.Calibre.queues.bus", attributes: .concurrent)
semaphore = DispatchSemaphore(value: 0)
timeoutTime = timeout < 0 ? DispatchTime.distantFuture : DispatchTime.now() + timeout
stream = []
}
/** Send a value onto the bus.
- parameter value: The value to place onto the bus.
*/
public func send(value: T) {
queue.async(flags: .barrier) {
self.stream.append(value)
self.semaphore.signal()
}
}
/** Receive a value over the bus.
- returns: The next value waiting on the bus
- throws: `BusError.timeout` if your (optional) read timeout expires before a value is available.
*/
public func receive() throws -> T {
let result = try queue.sync { () -> T in
let timeoutStatus = self.semaphore.wait(timeout: self.timeoutTime)
switch timeoutStatus {
case .timedOut:
throw BusError.timeout
case .success:
return self.stream.removeFirst()
}
}
return result
}
}
| 30.137931 | 126 | 0.606979 |
f859205d0c1771c704777542fcc295815739c711 | 2,325 | //
// NestedGSONTests.swift
// GSONTests
//
// Created by Gloomy Sunday on 2018/8/27.
//
import XCTest
@testable import GSON
class NestedGSONTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTopLevelNestedJSON() {
let nestedJSON: GSON = [
"family": family
]
XCTAssertNotNil(nestedJSON.rawStrings())
}
func testDeeplyNestedJSON() {
let nestedFamily: GSON = [
"count": 1,
"families": [
[
"isACoolFamily": true,
"family": [
"hello": family
]
]
]
]
XCTAssertNotNil(nestedFamily.rawStrings())
}
func testArrayJSON() {
let arr: [GSON] = ["a", 1, ["b", 2]]
let json = GSON(arr)
XCTAssertEqual(json[0].string, "a")
XCTAssertEqual(json[2, 1].int, 2)
}
func testDictionaryJSON() {
let json: GSON = ["a": GSON("1"), "b": GSON([1, 2, "3"]), "c": GSON(["aa": "11", "bb": 22])]
XCTAssertEqual(json["a"].string, "1")
XCTAssertEqual(json["b"].array!, [1, 2, "3"])
XCTAssertEqual(json["c"]["aa"].string, "11")
}
func testNestedJSON() {
let inner = GSON([
"some_field": "1" + "2"
])
let json = GSON([
"outer_field": "1" + "2",
"inner_json": inner
])
XCTAssertEqual(json["inner_json"], ["some_field": "12"])
let foo = "foo"
let json2 = GSON([
"outer_field": foo,
"inner_json": inner
])
XCTAssertEqual(json2["inner_json"].rawValue as! [String: String], ["some_field": "12"])
}
let family: GSON = [
"names": [
"Brooke Abigail Matos",
"Rowan Danger Matos"
],
"motto": "Hey, I don't know about you, but I'm feeling twenty-two! So, release the KrakenDev!"
]
}
| 27.352941 | 111 | 0.493333 |
757373145a426e3e7a754551d5cdb447c864b7f1 | 1,178 | //
// NetworkManager.swift
// swift-mvvm
//
// Created by Taylor Guidon on 11/30/16.
// Copyright © 2016 ISL. All rights reserved.
//
import Foundation
import Alamofire
protocol NetworkManagerDelegate {
func dataReceived(data: Any?, error: NSError?)
}
class NetworkManager: NSObject {
let baseURLString: String = "https://api.darksky.net/forecast/"
var baseURLWithAPIKeyString: String
var delegate: NetworkManagerDelegate?
init(apiKey: String) {
self.baseURLWithAPIKeyString = "\(self.baseURLString)\(apiKey)/"
super.init()
}
func getWeatherForCoordinate(coordinate: String) {
let requestURL: String = "\(baseURLWithAPIKeyString)\(coordinate)"
Alamofire.request(requestURL).responseJSON { (response) in
switch response.result {
case .success:
guard let json = response.result.value else {
return
}
self.delegate?.dataReceived(data: json, error: nil)
case .failure(let error):
self.delegate?.dataReceived(data: nil, error: error as NSError)
}
}
}
}
| 28.047619 | 79 | 0.61545 |
e078a11cbab06d27b626a09546667ccd6b31ed60 | 4,759 | //
// DashboardCoordinator.swift
// erg
//
// Created by Christie Davis on 17/04/19.
// Copyright © 2019 star. All rights reserved.
//
import UIKit
protocol DashboardCoordinatorProtocol: FlowCoordinatorProtocol {
var dashBoardViewControllers: [UIViewController] { get }
func goToFilter()
func goToAddErg()
func goToCamera()
func goToPredict()
func goToSettings()
func signOut()
}
class DashboardCoordinator {
var appCoordinator: AppCoordinatorDelegate?
fileprivate weak var navigationController: UINavigationController?
}
extension DashboardCoordinator: DashboardCoordinatorProtocol {
func enterNextFlow(navigationController: UINavigationController, sender: Any?) {
self.navigationController = navigationController
self.goToHome()
}
private func goToHome() {
let viewController = DashboardViewController()
viewController.coordinator = self
viewController.setViewControllers([self.workoutsViewController(),
self.addErgViewController(),
self.cameraViewController(),
self.predictViewController(),
self.settingsViewController()], animated: true)
navigationController?.pushViewController(viewController, animated: true)
}
func goToFilter() {
let viewController = ItemsTableViewController()
let itemPresenter = ItemsPresenter()
itemPresenter.viewDelegate = viewController
viewController.presenter = itemPresenter
navigationController?.pushViewController(viewController, animated: true)
}
func goToAddErg() {
let viewController = AddErgDataViewController()
// let itemPresenter = AddErgPresenter(itemsControllerDelegate: self)
// itemPresenter.viewDelegate = viewController
// viewController.presenter = itemPresenter
}
func goToCamera() {
let viewController = CameraViewController()
navigationController?.pushViewController(viewController, animated: true)
}
func goToPredict() {
}
func goToSettings() {
}
func signOut() {
appCoordinator?.enterNextFlow(currentCoordinator: self, sender: nil, with: self.navigationController)
}
}
extension DashboardCoordinator {
// Set up tabs
var dashBoardViewControllers: [UIViewController] {
return [cameraViewController()]
}
private func workoutsViewController() -> UIViewController {
let viewController = ItemsTableViewController()
viewController.tabBarItem = UITabBarItem(title: "dashboards.tabs.workouts".localized, image: #imageLiteral(resourceName: "Workout"), selectedImage: #imageLiteral(resourceName: "Workout"))
// viewController.tabBarItem.tag = Constants.HomeTabBarTag.home
return viewController
}
private func addErgViewController() -> UIViewController {
let viewController = AddErgDataViewController()
viewController.tabBarItem = UITabBarItem(title: "dashboards.tabs.adderg".localized, image: #imageLiteral(resourceName: "Add"), selectedImage: #imageLiteral(resourceName: "Add"))
// viewController.tabBarItem.tag = Constants.HomeTabBarTag.home
return viewController
}
private func cameraViewController() -> UIViewController {
let viewController = CameraViewController()
viewController.tabBarItem = UITabBarItem(title: "dashboards.tabs.camera".localized, image: #imageLiteral(resourceName: "Camera"), selectedImage: #imageLiteral(resourceName: "Camera"))
// viewController.tabBarItem.tag = Constants.HomeTabBarTag.home
return viewController
}
private func predictViewController() -> UIViewController {
let viewController = MachineLearningViewController()
viewController.tabBarItem = UITabBarItem(title: "dashboards.tabs.predict".localized, image: #imageLiteral(resourceName: "Predictions"), selectedImage: #imageLiteral(resourceName: "Predictions"))
// viewController.tabBarItem.tag = Constants.HomeTabBarTag.home
return viewController
}
private func settingsViewController() -> UIViewController {
let viewController = SettingsViewController()
viewController.tabBarItem = UITabBarItem(title: "dashboards.tabs.settings".localized, image: #imageLiteral(resourceName: "Settings"), selectedImage: #imageLiteral(resourceName: "Settings"))
// viewController.tabBarItem.tag = Constants.HomeTabBarTag.home
return viewController
}
}
| 38.072 | 202 | 0.681656 |
29a6a758cc2242afcbfeaf97f1ce86b4bb8e7b21 | 291 | import UIKit
@available(iOS 4.3 ,watchOS 8.0, *)
public extension UIFont {
public enum hiraginoKakuGothicProN: String {
case w3 = "HiraKakuProN-W3"
case w6 = "HiraKakuProN-W6"
public func font(size: CGFloat) -> UIFont {
return UIFont(name: self.rawValue, size: size)!
}
}
}
| 18.1875 | 50 | 0.687285 |
efbcfe88b66ccc983776c180abc7e1720f123dcf | 447 | //
// TimeInterval.swift
// Pods
//
// Created by Carlos Grossi on 19/06/17.
//
//
import Foundation
public extension TimeInterval {
/// Time interval duration in hours, minutes, seconds format
var duration: String {
let seconds = Int(self) % 60
let minutes = (Int(self) / 60) % 60
let hours = (Int(self) / 3600)
return String(format: "%02d%@ %02d%@ %02d%@", hours, "h", minutes, "m", seconds, "s")
}
}
| 20.318182 | 93 | 0.592841 |
6993137eb3f62913d30d043cdc65dfd593d19135 | 4,987 | import Xendit
@objc(SdkCardPayment)
class SdkCardPayment: NSObject {
@objc(createSingleUseToken:withCardNumber:withCardExpMonth:withCardExpYear:withCardCvn:withTransactionAmount:withShouldAuthenticate:withResolver:withRejecter:)
func createSingleUseToken(publicKey: String, cardNumber: String, cardExpMonth: String, cardExpYear: String, cardCvn: String, transactionAmount: Float, shouldAuthenticate: Bool, resolve: @escaping RCTPromiseResolveBlock,reject: @escaping RCTPromiseRejectBlock) -> Void {
let rootViewController = UIApplication.shared.delegate?.window??.rootViewController
let cardData = CardData()
cardData.cardNumber = cardNumber
cardData.cardExpMonth = cardExpMonth
cardData.cardExpYear = cardExpYear
cardData.cardCvn = cardCvn
cardData.isMultipleUse = false
cardData.amount = transactionAmount as NSNumber
Xendit.publishableKey = publicKey
let encoder = JSONEncoder()
let errorResult:NSMutableDictionary = NSMutableDictionary()
Xendit.createToken(fromViewController: rootViewController!, cardData: cardData, shouldAuthenticate: shouldAuthenticate) {
(token, error) in
if (error != nil ) {
// Handle error. Error is of type XenditError
errorResult.setValue(error!.errorCode, forKey: "errorCode")
errorResult.setValue(error!.message, forKey: "message")
return
} else {
encoder.outputFormatting = .prettyPrinted
encoder.keyEncodingStrategy = .convertToSnakeCase
let successJsonData = try? encoder.encode(token);
let sucessJsonString = String(data: successJsonData!, encoding: .utf8)
resolve(sucessJsonString!)
}
}
}
@objc(createMultiUseToken:withCardNumber:withCardExpMonth:withCardExpYear:withCardCvn:withTransactionAmount:withShouldAuthenticate:withResolver:withRejecter:)
func createMultiUseToken(publicKey: String, cardNumber: String, cardExpMonth: String, cardExpYear: String, cardCvn: String, transactionAmount: Float, shouldAuthenticate: Bool, resolve: @escaping RCTPromiseResolveBlock,reject: @escaping RCTPromiseRejectBlock) -> Void {
let rootViewController = UIApplication.shared.delegate?.window??.rootViewController
let cardData = CardData()
cardData.cardNumber = cardNumber
cardData.cardExpMonth = cardExpMonth
cardData.cardExpYear = cardExpYear
cardData.cardCvn = cardCvn
cardData.isMultipleUse = true
cardData.amount = transactionAmount as NSNumber
Xendit.publishableKey = publicKey
let encoder = JSONEncoder()
let errorResult:NSMutableDictionary = NSMutableDictionary()
Xendit.createToken(fromViewController: rootViewController!, cardData: cardData, shouldAuthenticate: shouldAuthenticate) {
(token, error) in
if (error != nil ) {
// Handle error. Error is of type XenditError
errorResult.setValue(error!.errorCode, forKey: "errorCode")
errorResult.setValue(error!.message, forKey: "message")
return
} else {
encoder.outputFormatting = .prettyPrinted
encoder.keyEncodingStrategy = .convertToSnakeCase
let successJsonData = try? encoder.encode(token);
let sucessJsonString = String(data: successJsonData!, encoding: .utf8)
resolve(sucessJsonString!)
}
}
}
@objc(createAuthentication:withTokenId:withTransactionAmount:withCurrency:withResolver:withRejecter:)
func createAuthentication(publicKey: String, tokenId: String, transactionAmount: Float, currency: String, resolve: @escaping RCTPromiseResolveBlock,reject: @escaping RCTPromiseRejectBlock) -> Void {
let rootViewController = UIApplication.shared.delegate?.window??.rootViewController
Xendit.publishableKey = publicKey
let amount = transactionAmount as NSNumber
let encoder = JSONEncoder()
let errorResult:NSMutableDictionary = NSMutableDictionary()
Xendit.createAuthentication(fromViewController: rootViewController!, tokenId: tokenId, amount: amount) {
(token, error) in
if (error != nil ) {
// Handle error. Error is of type XenditError
errorResult.setValue(error!.errorCode, forKey: "errorCode")
errorResult.setValue(error!.message, forKey: "message")
return
} else {
encoder.outputFormatting = .prettyPrinted
encoder.keyEncodingStrategy = .convertToSnakeCase
let successJsonData = try? encoder.encode(token);
let sucessJsonString = String(data: successJsonData!, encoding: .utf8)
resolve(sucessJsonString!)
}
}
}
}
| 55.411111 | 274 | 0.676359 |
0a79adf8d7605f628a4c5cc6c19840d8c0ccf550 | 283 | //
// Walkthrough_1.swift
//
// Created by Michael Westbrooks on 8/12/19.
// Copyright © 2019 RedRooster Technologies Inc. All rights reserved.
//
import UIKit
public class Walkthrough_1: UIViewController {
override public func viewDidLoad() {
super.viewDidLoad()
}
}
| 18.866667 | 70 | 0.713781 |
01c6a3cb6e86a6da68183a2ebb924c5f84889e4e | 2,044 | //: [Previous](@previous)
/*
Asynchronous functions are a big part of iOS APIs, and most
developers are familiar with the challenge they pose when
one needs to sequentially call several asynchronous APIs.
This often results in callbacks being nested into one another,
a predicament often referred to as callback hell.
Many third-party frameworks are able to tackle this issue,
for instance [RxSwift](https://github.com/ReactiveX/RxSwift)
or [PromiseKit](https://github.com/mxcl/PromiseKit).
Yet, for simple instances of the problem, there is no need
to use such big guns, as it can actually be solved with
simple function composition.
*/
import Foundation
typealias CompletionHandler<Result> = (Result?, Error?) -> Void
infix operator ~>: MultiplicationPrecedence
func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ second: @escaping (T, CompletionHandler<U>) -> Void) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ firstResult, error in
guard let firstResult = firstResult else { completion(nil, error); return }
second(firstResult, { (secondResult, error) in
completion(secondResult, error)
})
})
}
}
func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ transform: @escaping (T) -> U) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ result, error in
guard let result = result else { completion(nil, error); return }
completion(transform(result), nil)
})
}
}
func service1(_ completionHandler: CompletionHandler<Int>) {
completionHandler(42, nil)
}
func service2(arg: String, _ completionHandler: CompletionHandler<String>) {
completionHandler("🎉 \(arg)", nil)
}
let chainedServices = service1
~> { int in return String(int / 2) }
~> service2
chainedServices({ result, _ in
guard let result = result else { return }
print(result) // Prints: 🎉 21
})
//: [Next](@next)
| 30.969697 | 156 | 0.664384 |
7acde422539253b1a2f773d3b6a8990361c59258 | 784 | //
// MainQueueDispatchDecorator.swift
// FruitStore
//
// Created by Kleyton Lopes on 20/09/21.
//
import Foundation
class MainQueueDispatchDecorator<T> {
private let instance: T
init(_ instance: T) {
self.instance = instance
}
func dispatch(completion: @escaping () -> Void) {
guard Thread.isMainThread else { return DispatchQueue.main.async(execute: completion) }
completion()
}
}
extension MainQueueDispatchDecorator: Authentication where T: Authentication {
func auth(authenticationModel: AuthenticationModel, completion: @escaping (Authentication.Result) -> Void) {
instance.auth(authenticationModel: authenticationModel) { [weak self] result in
self?.dispatch { completion(result) }
}
}
}
| 26.133333 | 112 | 0.686224 |
6151ceb42a5617ca571a4a83d0a72ee332bcc1c2 | 2,479 | /*
HebrewWeekdayDate.swift
This source file is part of the SDGCornerstone open source project.
https://sdggiesbrecht.github.io/SDGCornerstone
Copyright ©2017–2020 Jeremy David Giesbrecht and the SDGCornerstone project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import SDGMathematics
import SDGText
import SDGLocalization
internal struct HebrewWeekdayDate: DateDefinition {
// MARK: - Static Properties
internal static let referenceMoment = CalendarDate(hebrew: .tishrei, 4, 5758)
private static let referenceWeekday: HebrewWeekday = .sunday
// MARK: - Properties
private let week: Int
internal let weekday: HebrewWeekday
private let hour: HebrewHour
private let part: HebrewPart
// MARK: - Initialization
internal init(week: Int, weekday: HebrewWeekday, hour: HebrewHour, part: HebrewPart) {
self.week = week
self.weekday = weekday
self.hour = hour
self.part = part
var interval: CalendarInterval<FloatMax> = FloatMax(week).weeks
interval += FloatMax(weekday.numberAlreadyElapsed).days
interval += FloatMax(hour.numberAlreadyElapsed).hours
interval += FloatMax(part.numberAlreadyElapsed).hebrewParts
intervalSinceReferenceDate = interval
}
// MARK: - DateDefinition
internal static let identifier: StrictString = "שבוע עברי"
internal static let referenceDate: CalendarDate = referenceMoment
internal var intervalSinceReferenceDate: CalendarInterval<FloatMax>
internal init(intervalSinceReferenceDate: CalendarInterval<FloatMax>) {
self.intervalSinceReferenceDate = intervalSinceReferenceDate
let date = HebrewWeekdayDate.referenceDate + intervalSinceReferenceDate
hour = date.hebrewHour
part = date.hebrewPart
let week = Int(intervalSinceReferenceDate.inWeeks.rounded(.down))
self.week = week
weekday = HebrewWeekday(
numberAlreadyElapsed: Int(
(intervalSinceReferenceDate − FloatMax(week).weeks).inDays.rounded(.down)
)
)
}
// MARK: - Decodable
internal init(from decoder: Decoder) throws {
unreachable()
// This definition is only ever transiently created to determine the weekday of another date.
}
// MARK: - Encodable
internal func encode(to encoder: Encoder) throws {
unreachable()
// This definition is only ever transiently created to determine the weekday of another date.
}
}
| 28.825581 | 97 | 0.749496 |
8fa5348e9f7f3bb244ac514ce7fcb43da4bd1a88 | 1,521 | //
// UnicornService.swift
// MyUnicorn
//
// Created by Mohamed Salem on 27.12.19.
// Copyright © 2020 Mohamed Salem. All rights reserved.
//
import Foundation
import Combine
import MVVMCombine
class UnicornService: UnicornProtocol {
// MARK: Services
@Service var dataService: DataProtocol
// MARK: Implementation
func getAll() -> AnyPublisher<[UnicornViewItem], Never> {
return dataService.getUnicorns()
.map { unicorns in
unicorns.map { UnicornViewItem(unicorn: $0) }
}
.catch { _ in
Just([])
}
.eraseToAnyPublisher()
}
func get(id: String) -> AnyPublisher<UnicornViewItem?, Never> {
return dataService.getUnicorn(id: id)
.map { UnicornViewItem(unicorn: $0) }
.catch { _ in
Just(nil)
}
.eraseToAnyPublisher()
}
func add(unicorn: UnicornViewItem) -> AnyPublisher<Bool, Never> {
return dataService.postUnicorn(unicorn: unicorn.unicorn)
.eraseToAnyPublisher()
}
func update(unicorn: UnicornViewItem, with newUnicorn: UnicornViewItem) -> AnyPublisher<Bool, Never> {
return dataService.putUnicorn(id: unicorn.id, unicorn: newUnicorn.unicorn)
.eraseToAnyPublisher()
}
func delete(unicorn: UnicornViewItem) -> AnyPublisher<Bool, Never> {
return dataService.deleteUnicorn(id: unicorn.id)
.eraseToAnyPublisher()
}
}
| 27.160714 | 106 | 0.60618 |
d71163c4bdaed051dc7b25d6734030e0c2763844 | 1,422 | import Foundation
import RealmSwift
protocol GuideItemHolder: class {
func getId() -> String!
func getName() -> String
}
class GuideItem: Object {
dynamic var versionId: String!
dynamic var uuid: String!
dynamic var slug: String?
dynamic var name: String!
dynamic var category = 0
dynamic var subCategory = 0
dynamic var status = 0
dynamic var parent: String!
dynamic var content: String?
dynamic var textLicense: String?
var images = List<GuideItemImage>()
var guideSections = List<GuideText>()
var subRegions = List<Region>()
var categoryDescriptions = List<GuideText>()
func getSubRegions() -> [Region] {
let subs = Array(subRegions)
return subs.sort { a, b in a.getName() < b.getName() }
}
var allCategoryDescriptions: [GuideText] {
get {
var catDescs = [GuideText]()
for categoryDescription in categoryDescriptions {
categoryDescription.item.loadStatus = GuideItem.LoadStatus.CHILDREN_NOT_LOADED
catDescs.append(categoryDescription)
}
return catDescs
}
}
// temporary data to make things easier
var loadStatus = LoadStatus.FULLY_LOADED
var offline = true
enum LoadStatus {
case CONTENT_NOT_LOADED // only name and category is set
case CHILDREN_NOT_LOADED
case FULLY_LOADED
}
override static func ignoredProperties() -> [String] {
return ["loadStatus", "offline"]
}
}
| 24.517241 | 86 | 0.691983 |
21347107fdc407f99168ff32cbc3bffd40b5dbf0 | 1,206 | import XCTest
import JWTDecode
import PayseraCommonSDK
@testable import PayseraBlacklistSDK
class PayseraBlacklistSDKTests: XCTestCase {
private var blacklistApiClient : BlacklistApiClient!
override func setUp() {
super.setUp()
let token = "change_me"
let credentials = PSApiJWTCredentials()
credentials.token = try! decode(jwt: token)
blacklistApiClient = BlacklistApiClientFactory.createBlacklistApiClient(credentials: credentials)
}
func testGetRestrictions() {
let expectation = XCTestExpectation(description: "")
let filter = PSRestrictionFilter()
filter.hidden = "false"
filter.statuses = ["active", "pending_removal"]
filter.userId = 1234
blacklistApiClient
.getUserRestrictions(filter: filter)
.done { obj in
print(obj)
}.catch { error in
if let error = error as? PSApiError {
print(error.description)
}
}.finally { expectation.fulfill() }
wait(for: [expectation], timeout: 5.0)
}
}
| 28.046512 | 105 | 0.584577 |
ef917a0416de185142404400f78a2c4061df81e1 | 2,416 | //
// AuthenticationManager.swift
// UpcomingMoviesData
//
// Created by Alonso on 11/17/19.
// Copyright © 2019 Alonso. All rights reserved.
//
import UpcomingMoviesDomain
final class AuthenticationManager: AuthenticationManagerProtocol {
static let shared = AuthenticationManager()
lazy var readAccessToken: String = {
return NetworkConfiguration.shared.readAccessToken
}()
@KeychainStorage(key: Constants.sessionIdKey)
private var sessionId: String?
@KeychainStorage(key: Constants.currentUserIdKey)
private var currentUserId: String?
@KeychainStorage(key: Constants.accountIdKey)
private var accountId: String?
@KeychainStorage(key: Constants.accessTokenKey)
private var token: String?
@KeychainStorage(key: Constants.requestTokenKey)
var requestToken: String?
// MARK: - Initializers
init() {}
// MARK: - AuthenticationManagerProtocol
func saveCurrentUser(_ sessionId: String, accountId: Int) {
self.sessionId = sessionId
self.currentUserId = String(accountId)
}
func deleteCurrentUser() {
sessionId = nil
currentUserId = nil
token = nil
}
// MARK: - Request Token
func saveRequestToken(_ requestToken: String) {
self.requestToken = requestToken
}
// MARK: - Access Token
func saveAccessToken(_ accessToken: AccessToken) {
token = accessToken.token
accountId = accessToken.accountId
}
var accessToken: AccessToken? {
guard let token = token, let accountId = accountId else {
return nil
}
return AccessToken(token: token, accountId: accountId)
}
// MARK: - Credentials
var userAccount: Account? {
guard let sessionId = sessionId,
let currentUserId = currentUserId,
let accountId = Int(currentUserId) else {
return nil
}
return Account(accountId: accountId, sessionId: sessionId)
}
}
// MARK: - Constants
extension AuthenticationManager {
struct Constants {
static let accessTokenKey = "UpcomingMoviesAccessToken"
static let requestTokenKey = "UpcomingMoviesRequestToken"
static let accountIdKey = "UpcomingMoviesAccessAccountId"
static let sessionIdKey = "UpcomingMoviesSessionId"
static let currentUserIdKey = "UpcomingMoviesUserId"
}
}
| 24.907216 | 66 | 0.672185 |
76d2d6597d666ddee035033128af338a65a6b796 | 1,596 | //
// FeedFilterCell.swift
// Yep
//
// Created by NIX on 16/5/11.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
class FeedFilterCell: UITableViewCell {
var currentOption: Option? {
didSet {
if let option = currentOption {
segmentedControl.selectedSegmentIndex = option.rawValue
}
}
}
var chooseOptionAction: ((_ option: Option) -> Void)?
enum Option: Int {
case recommended
case lately
var title: String {
switch self {
case .recommended:
return NSLocalizedString("Recommended", comment: "")
case .lately:
return String.trans_titleLately
}
}
}
@IBOutlet weak var segmentedControl: UISegmentedControl! {
didSet {
segmentedControl.removeAllSegments()
(0..<2).forEach({
let option = Option(rawValue: $0)
segmentedControl.insertSegment(withTitle: option?.title, at: $0, animated: false)
})
}
}
override func awakeFromNib() {
super.awakeFromNib()
segmentedControl.selectedSegmentIndex = Option.recommended.rawValue
segmentedControl.addTarget(self, action: #selector(FeedFilterCell.chooseOption(_:)), for: .valueChanged)
}
@objc fileprivate func chooseOption(_ sender: UISegmentedControl) {
guard let option = Option(rawValue: sender.selectedSegmentIndex) else {
return
}
chooseOptionAction?(option)
}
}
| 24.553846 | 112 | 0.588346 |
de64875cfc508f7823ffd912c7f7b1abaad24f3d | 4,655 | //
// MovieDetailViewController.swift
// flicks
//
// Created by Binwei Yang on 7/15/16.
// Copyright © 2016 Binwei Yang. All rights reserved.
//
import UIKit
class MovieDetailViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterImage: UIImageView!
var movie: NSDictionary!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let contentWidth = scrollView.bounds.width
let contentHeight = scrollView.bounds.height * 3
self.scrollView.contentSize = CGSizeMake(contentWidth, contentHeight)
let title = movie["original_title"] as! String
self.titleLabel.text = title
let overview = movie["overview"] as! String
self.overviewLabel.text = overview
self.overviewLabel.sizeToFit()
self.scrollView.addSubview(self.overviewLabel)
if let posterPath = movie["poster_path"] as? String {
loadImageLowResThenFadeInHighRes(posterPath)
}
}
func loadImageLowResThenFadeInHighRes(posterPath: String) {
let smallImageRequest = NSURLRequest(URL: NSURL(string: "https://image.tmdb.org/t/p/w45" + posterPath)!)
let largeImageRequest = NSURLRequest(URL: NSURL(string: "https://image.tmdb.org/t/p/original" + posterPath)!)
self.posterImage.setImageWithURLRequest(
smallImageRequest,
placeholderImage: nil,
success: { (smallImageRequest, smallImageResponse, smallImage) -> Void in
self.posterImage.image = smallImage
if (smallImageResponse != nil) {
// NSLog("Loaded small image from network for \(posterPath)")
self.posterImage.alpha = 0.0
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.posterImage.alpha = 1.0
}, completion: { (success) -> Void in
// The AFNetworking ImageView Category only allows one request to be sent at a time
// per ImageView. This code must be in the completion block.
self.posterImage.setImageWithURLRequest(
largeImageRequest,
placeholderImage: smallImage,
success: { (largeImageRequest, largeImageResponse, largeImage) -> Void in
self.posterImage.image = largeImage
if (largeImageResponse != nil) {
// NSLog("Loaded large image from network for \(posterPath)")
}
else {
//NSLog("Loaded large image from cache for \(posterPath)")
}
},
failure: { (request, response, error) -> Void in
// do something for the failure condition of the large image request
// possibly setting the ImageView's image to a default image
})
})
}
else {
// NSLog("Loaded small image from cache for \(posterPath)")
self.posterImage.setImageWithURL(largeImageRequest.URL!)
// NSLog("Loaded large image from cache for \(posterPath)")
}
},
failure: { (request, response, error) -> Void in
self.posterImage.image = nil
})
}
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.
dismissViewControllerAnimated(false, completion: nil)
}
}
| 42.706422 | 117 | 0.535124 |
d56c3f803e915348ed9560a95c6a2157deaab48b | 4,814 | //
// SignViewControllerViewModel.swift
// RxSwiftMVVMDemo
//
// Created by P36348 on 24/03/2019.
// Copyright © 2019 P36348. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class SignViewControllerViewModel {
// input
var usernameInput: BehaviorRelay<String> = BehaviorRelay(value: "")
var passwordInput: BehaviorRelay<String> = BehaviorRelay(value: "")
// output
var usernameInputEnable: Observable<Bool>
var passwordInputEnable: Observable<Bool>
var submitEnable: BehaviorRelay<Bool> = BehaviorRelay(value: true)
var submitTitle: BehaviorRelay<String> = BehaviorRelay(value: "Submit")
var indicatorHidden: Observable<Bool>
var stateHidden: Observable<Bool>
var state: Observable<String> {
return _internalState.asObservable()
}
// 登录状态
private var signState: BehaviorSubject<String> = BehaviorSubject(value: "")
// 内部状态
private var _internalState: BehaviorSubject<String> = BehaviorSubject(value: "")
private weak var disposeBag: DisposeBag!
init(disposeBag: DisposeBag!) {
self.disposeBag = disposeBag
UserService.shared.rx_signState.subscribe(onNext: { (state) in
print("state changed:", state)
}).disposed(by: self.disposeBag)
let isSigning: Observable<Bool> = UserService.shared.rx_signState
.map({
switch $0 {
case .signingIn, .signingOut:
return true
default:
return false
}
})
let isUnsigned = UserService.shared.rx_signState.map({state -> Bool in
if case SignState.unsigned = state {
return true
}else {
return false
}
})
self.usernameInputEnable = isUnsigned
self.passwordInputEnable = Observable.combineLatest(
self.usernameInput,
isSigning,
isUnsigned
)
.map({$0.0.count >= 4 && !$0.1 && $0.2})
.observeOn(MainScheduler.asyncInstance)
self.indicatorHidden = isSigning.map({!$0})
self.stateHidden = self.indicatorHidden.map({!$0})
Observable.combineLatest(
self.usernameInput,
self.passwordInput,
isSigning
)
.map({ ($0.0.count >= 4) && (!$0.1.isEmpty) && !$0.2 })
.bind(to: self.submitEnable)
.disposed(by: self.disposeBag)
UserService.shared.rx_signState.map({state -> String in
if case SignState.signed(_) = state {
return "SignOut"
}else {
return "Submit"
}
})
.bind(to: self.submitTitle)
.disposed(by: self.disposeBag)
// 用户输入状态
let inputState: Observable<String> = Observable.combineLatest(
self.usernameInput,
self.passwordInput
)
.map({ val in
let username = val.0, password = val.1
if username.isEmpty {
return "请填写用户名"
}else if username.count < 4 {
return "用户名太短, 应该大于4位"
}else if password.isEmpty {
return "请填写密码"
}
return ""
})
// 登录状态和用户输入状态合并就是最终状态
Observable.merge(self.signState, inputState)
.bind(to: self._internalState)
.disposed(by: self.disposeBag)
}
func handleClickSubmit() {
switch UserService.shared.state {
case SignState.signed(_) :
self.performSignOut()
case SignState.unsigned:
self.performSignin()
default:
fatalError()
}
}
func performSignOut() {
UserService.shared.performSignout()
.subscribe(onNext: {[unowned self] _ in self.updateState("已经退出登录")})
.disposed(by: self.disposeBag)
}
func performSignin() {
Observable.combineLatest(self.usernameInput, self.passwordInput)
.take(1)
.flatMap({[unowned self] in self.performSignin(username: $0, password: $1)})
.subscribe(onNext: {[unowned self] in self.updateState($0)})
.disposed(by: self.disposeBag)
}
func performSignin(username: String, password: String) -> Observable<String> {
return UserService.shared.performSignin(username: username, password: password)
.map({"当前用户: \($0.username)\n登录时间: \($0.date)"})
.catchError({Observable.of(($0 as NSError).domain)})
}
func updateState(_ value: String) {
signState.onNext(value)
}
}
| 32.308725 | 88 | 0.558371 |
20607892086df2d17fde02bb8237c154036f0c52 | 9,930 | import Vapor
import Core
/// The amount of a purchase which includes details such as shipping, tax, discounts, etc.
public struct DetailedAmount: Content, Equatable {
/// The currency and amount information for the intance.
///
/// The amount's `value` property is the total amount charged to the payee by the payer.
///
/// The proprties of this property (`value` and `currency`) are encoded/decoded inline with
/// the rest of this type's properties. The coding-key for `value` is `total`.
public var amount: CurrencyAmount
/// The additional details about the payment amount.
public var details: Detail?
/// Creates a new `DetailedAmount` instance.
///
/// - Parameters:
/// - currency: The three-character ISO-4217 currency code
/// - total: The total amount charged to the payee by the payer.
/// - details: The additional details about the payment amount.
public init(currency: Currency, total: Decimal, details: Detail?) {
self.amount = CurrencyAmount(currency: currency, value: total)
self.details = details
}
/// See [`Decodable.init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init).
public init(from decoder: Decoder)throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.details = try container.decodeIfPresent(Detail.self, forKey: .details)
self.amount = CurrencyAmount(
currency: try container.decode(Currency.self, forKey: .currency),
value: try Detail.decimal(from: container.decode(String.self, forKey: .total))
)
}
/// See [`Encodable.encode(to:)`](https://developer.apple.com/documentation/swift/encodable/2893603-encode).
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.amount.currency, forKey: .currency)
try container.encode(self.amount.currency.string(for: self.amount.value), forKey: .total)
try container.encodeIfPresent(self.details, forKey: .details)
}
enum CodingKeys: String, CodingKey {
case currency, total, details
}
}
extension DetailedAmount {
/// The additional details about a payment amount.
public struct Detail: Content, Equatable {
internal static func decimal(from value: String)throws -> Decimal {
guard Double(value) != nil, var decimal = Decimal(string: value) else {
throw PayPalError(status: .badRequest, identifier: "badValue", reason: "Unable to convert string `\(value)` to a decimal number")
}
guard decimal < 10_000_000 else {
throw PayPalError(status: .badRequest, identifier: "invalidDecimal", reason: "Decimal value must be less than 10,000,000")
}
var rounded = decimal
NSDecimalRound(&rounded, &decimal, 2, .bankers)
if value == "9876543.210" {
print("value:", value, ", decimal:", decimal, ", rounded:", rounded)
}
return rounded
}
internal static func string(from value: Decimal?)throws -> String? {
guard var decimal = value else { return nil }
guard decimal < 10_000_000 else {
throw PayPalError(status: .internalServerError, identifier: "invalidDecimal", reason: "Decimal value must be less than 10,000,000")
}
var rounded = decimal
NSDecimalRound(&rounded, &decimal, 2, .bankers)
return String(describing: rounded)
}
internal static func decimal(from value: String?)throws -> Decimal? {
if let string = value { return try self.decimal(from: string) as Decimal } else { return nil }
}
/// The subtotal amount for the items.
///
/// If the request includes line items, this property is **required**. Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
public var subtotal: Decimal
/// The shipping fee.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
public var shipping: Decimal?
/// The tax.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
public var tax: Decimal?
/// The handling fee.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
/// Supported for the PayPal payment method only.
public var handlingFee: Decimal?
/// The shipping fee discount.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
/// Supported for the PayPal payment method only.
public var shippingDiscount: Decimal?
/// The insurance fee.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
/// Supported only for the PayPal payment method.
public var insurance: Decimal?
/// The gift wrap fee.
///
/// Maximum length is 10 characters, which includes:
/// - Seven digits before the decimal point.
/// - The decimal point.
/// - Two digits after the decimal point.
public var giftWrap: Decimal?
/// Creates a new `DetailAmount.Detail` instance.
///
/// - Parameters:
/// - subtotal: The subtotal amount for the items in an item list.
/// - shipping: The shipping fee.
/// - tax: The tax.
/// - handlingFee: The handling fee.
/// - shippingDiscount: The discount for shipping.
/// - insurance: The insurance fee.
/// - giftWrap: The gift wrap fee.
public init(
subtotal: Decimal,
shipping: Decimal? = nil,
tax: Decimal? = nil,
handlingFee: Decimal? = nil,
shippingDiscount: Decimal? = nil,
insurance: Decimal? = nil,
giftWrap: Decimal? = nil
) {
self.subtotal = subtotal
self.shipping = shipping
self.tax = tax
self.handlingFee = handlingFee
self.shippingDiscount = shippingDiscount
self.insurance = insurance
self.giftWrap = giftWrap
}
/// See [`Decodable.init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init).
public init(from decoder: Decoder)throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.subtotal = try Detail.decimal(from: container.decode(String.self, forKey: .subtotal))
self.shipping = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .shipping))
self.tax = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .tax))
self.handlingFee = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .handlingFee))
self.shippingDiscount = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .shippingDiscount))
self.insurance = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .insurance))
self.giftWrap = try Detail.decimal(from: container.decodeIfPresent(String.self, forKey: .giftWrap))
}
/// See [`Encodable.encode(to:)`](https://developer.apple.com/documentation/swift/encodable/2893603-encode).
public func encode(to encoder: Encoder)throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let value = try Detail.string(from: self.subtotal) { try container.encode(value, forKey: .subtotal) }
if let value = try Detail.string(from: self.shipping) { try container.encodeIfPresent(value, forKey: .shipping) }
if let value = try Detail.string(from: self.tax) { try container.encodeIfPresent(value, forKey: .tax) }
if let value = try Detail.string(from: self.handlingFee) { try container.encodeIfPresent(value, forKey: .handlingFee) }
if let value = try Detail.string(from: self.shippingDiscount) { try container.encodeIfPresent(value, forKey: .shippingDiscount) }
if let value = try Detail.string(from: self.insurance) { try container.encodeIfPresent(value, forKey: .insurance) }
if let value = try Detail.string(from: self.giftWrap) { try container.encodeIfPresent(value, forKey: .giftWrap) }
}
enum CodingKeys: String, CodingKey {
case subtotal = "subtotal"
case shipping = "shipping"
case tax = "tax"
case handlingFee = "handling_fee"
case shippingDiscount = "shipping_discount"
case insurance = "insurance"
case giftWrap = "gift_wrap"
}
}
}
| 45.972222 | 147 | 0.601712 |
db7ed712f1f491e24bef994c5e00bfbce1409ba9 | 3,123 | import Foundation
public class WebSocketMessage: Codable {
public let MessageType: String
public var ID: Int?
public var Success: Bool?
public var Payload: [String: Any]?
public var Result: [String: Any]?
public var Message: String?
public var HAVersion: String?
private enum CodingKeys: String, CodingKey {
case MessageType = "type"
case ID = "id"
case Success = "success"
case Payload = "payload"
case Result = "result"
case Message = "message"
case HAVersion = "ha_version"
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.MessageType = try values.decode(String.self, forKey: .MessageType)
self.ID = try? values.decode(Int.self, forKey: .ID)
self.Success = try? values.decode(Bool.self, forKey: .Success)
self.Payload = try? values.decode([String: Any].self, forKey: .Payload)
self.Result = try? values.decode([String: Any].self, forKey: .Result)
self.Message = try? values.decode(String.self, forKey: .Message)
self.HAVersion = try? values.decode(String.self, forKey: .HAVersion)
}
public init?(_ dictionary: [String: Any]) {
guard let mType = dictionary["type"] as? String else {
return nil
}
self.MessageType = mType
self.ID = dictionary["id"] as? Int
self.Payload = dictionary["payload"] as? [String: Any]
self.Result = dictionary["result"] as? [String: Any]
self.Success = dictionary["success"] as? Bool
}
public init(_ incomingMessage: WebSocketMessage, _ result: [String: Any]) {
self.ID = incomingMessage.ID
self.MessageType = "result"
self.Result = result
self.Success = true
}
public init(id: Int, type: String, result: [String: Any], success: Bool = true) {
self.ID = id
self.MessageType = type
self.Result = result
self.Success = success
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(MessageType, forKey: .MessageType)
if let ID = ID {
try container.encode(ID, forKey: .ID)
}
if let Success = Success {
try container.encode(Success, forKey: .Success)
}
if let Message = Message {
try container.encode(Message, forKey: .Message)
}
if let Result = Result {
try container.encode(Result, forKey: .Result)
}
}
init(_ messageType: String) {
self.MessageType = messageType
}
}
extension WebSocketMessage: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
"WebSocketMessage(type: \(MessageType), id: \(String(describing: ID)), payload: \(String(describing: Payload)), result: \(String(describing: Result)), success: \(String(describing: Success)))"
}
public var debugDescription: String {
description
}
}
| 35.089888 | 200 | 0.622478 |
9cffdff4446efe0d5c4c61a457f307c3ef55eecf | 787 | //
// StoreService.swift
// N Clip Board
//
// Created by branson on 2019/10/29.
// Copyright © 2019 branson. All rights reserved.
//
import Cocoa
class StoreService: NSObject {
@objc dynamic lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Store")
container.loadPersistentStores { (description, error) in
if error != nil {
fatalError("\(error!)")
}
}
return container
}()
@objc dynamic var managedContext: NSManagedObjectContext {
get { persistentContainer.viewContext }
}
// MARK: Singleton initializer
private override init() {
}
@objc dynamic static let shared = StoreService()
}
| 23.147059 | 73 | 0.606099 |
f4d288aa5b04391389fc1e6ac00eb03aeff37523 | 1,146 | //
// CfConfiguration.swift
// ff-ios-client-sdk
//
// Created by Dusan Juranovic on 13.1.21..
//
import Foundation
/// `CfConfiguration` is `required` in order to [intialize](x-source-tag://initialize) the SDK.
/// # Defaults: #
/// - `configUrl`: "https://config.feature-flags.uat.harness.io/api/1.0"
/// - `eventUrl`: "https://event.feature-flags.uat.harness.io/api/1.0"
/// - `streamEnabled`: `false`
/// - `analyticsEnabled`: `true`
/// - `pollingInterval`: `60` seconds
public struct CfConfiguration {
var configUrl: String
var eventUrl: String
var streamEnabled: Bool
var analyticsEnabled: Bool
var pollingInterval: TimeInterval
var environmentId: String
internal init(configUrl: String, eventUrl: String, streamEnabled: Bool, analyticsEnabled: Bool, pollingInterval:TimeInterval, environmentId: String) {
self.configUrl = configUrl
self.eventUrl = eventUrl
self.streamEnabled = streamEnabled
self.analyticsEnabled = analyticsEnabled
self.pollingInterval = pollingInterval
self.environmentId = environmentId
}
public static func builder() -> CfConfigurationBuilder {
return CfConfigurationBuilder()
}
}
| 29.384615 | 151 | 0.733857 |
eba6f26412b9e03f9cce3ae291a3bde98521feee | 4,335 | import ClientModels
import ComposableGameCenter
import HomeFeature
import Overture
import SharedModels
import SnapshotTesting
import Styleguide
import XCTest
class HomeFeatureTests: XCTestCase {
override class func setUp() {
super.setUp()
SnapshotTesting.diffTool = "ksdiff"
}
override func setUpWithError() throws {
try super.setUpWithError()
try XCTSkipIf(!Styleguide.registerFonts())
// isRecording = true
}
func testBasics() {
assertSnapshot(
matching: HomeView(
store: .init(
initialState: .init(
dailyChallenges: [
.init(
dailyChallenge: .init(
endsAt: .mock,
gameMode: .timed,
id: .init(rawValue: .dailyChallengeId),
language: .en
),
yourResult: .init(outOf: 4_000, rank: nil, score: nil, started: false)
)
],
weekInReview: .init(
ranks: [
.init(gameMode: .timed, outOf: 2_000, rank: 100),
.init(gameMode: .unlimited, outOf: 1_500, rank: 200),
],
word: .init(letters: "Jazziest", score: 1400)
)
),
reducer: .empty,
environment: ()
)
)
.environment(\.date, { .mock - 2*60*60 }),
as: .image(
layout: .device(
config: update(.iPhoneXsMax) {
$0.size?.height += 200
}
)
)
)
}
func testActiveGames_DailyChallenge_Solo() {
assertSnapshot(
matching: HomeView(
store: .init(
initialState: .init(
dailyChallenges: [],
savedGames: .init(
dailyChallengeUnlimited: .mock,
unlimited: update(.mock) {
$0?.moves = [.mock]
}
)
),
reducer: .empty,
environment: ()
)
)
.environment(\.date, { .mock - 2*60*60 }),
as: .image(layout: .device(config: .iPhoneXsMax))
)
}
func testActiveGames_Multiplayer() {
assertSnapshot(
matching: HomeView(
store: .init(
initialState: .init(
dailyChallenges: [],
turnBasedMatches: [
.init(
id: "1",
isYourTurn: true,
lastPlayedAt: .mock,
now: .mock,
playedWord: PlayedWord(
isYourWord: false,
reactions: [0: .angel],
score: 120,
word: "HELLO"
),
status: .open,
theirIndex: 1,
theirName: "Blob"
),
.init(
id: "2",
isYourTurn: false,
lastPlayedAt: .mock,
now: .mock,
playedWord: PlayedWord(
isYourWord: true,
reactions: [0: .angel],
score: 420,
word: "GOODBYE"
),
status: .open,
theirIndex: 0,
theirName: "Blob"
),
]
),
reducer: .empty,
environment: ()
)
)
.environment(\.date, { .mock - 2*60*60 }),
as: .image(layout: .device(config: .iPhoneXsMax))
)
}
func testActiveGames_StaleGame() {
assertSnapshot(
matching: HomeView(
store: .init(
initialState: .init(
dailyChallenges: [],
turnBasedMatches: [
.init(
id: "2",
isYourTurn: false,
lastPlayedAt: Date.mock.advanced(by: -60 * 60 * 24 * 3),
now: .mock,
playedWord: PlayedWord(
isYourWord: true,
reactions: [0: .angel],
score: 420,
word: "GOODBYE"
),
status: .open,
theirIndex: 0,
theirName: "Blob"
),
]
),
reducer: .empty,
environment: ()
)
)
.environment(\.date, { .mock - 2*60*60 }),
as: .image(layout: .device(config: .iPhoneXsMax))
)
}
}
| 26.432927 | 86 | 0.439677 |
87b79fe6155c9daa65e46034aee965db40daa82e | 234 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A<T where f:b{struct A<h:T)let b{let b{func a()->{protocol | 46.8 | 87 | 0.752137 |
ef4260bd71464718a0b6f1cd6b65b2f4e1620050 | 2,962 | /**
* Copyright (c) 2021 Dustin Collins (Strega's Gate)
* All Rights Reserved.
* Licensed under MIT License
*
* http://stregasgate.com
*/
import _RaylibC
public extension Raylib {
//MARK: - Shader management functions
// NOTE: Shader functionality is not available on OpenGL 1.1
/// Load shader from files and bind default locations
@_transparent
static func loadShader(_ vsFileName: String, _ fsFileName: String) -> Shader {
return vsFileName.withCString { vsCString in
return fsFileName.withCString { fsCString in
return _RaylibC.LoadShader(vsCString, fsCString)
}
}
}
/// Load shader from code strings and bind default locations
@_transparent
static func loadShaderFromMemory(_ vsCode: String, _ fsCode: String) -> Shader {
return vsCode.withCString { vsCString in
return fsCode.withCString { fsCString in
return _RaylibC.LoadShaderFromMemory(vsCString, fsCString)
}
}
}
/// Get shader uniform location
@_transparent
static func getShaderLocation(_ shader: Shader, _ uniformName: String) -> Int32 {
return uniformName.withCString { cString in
return _RaylibC.GetShaderLocation(shader, cString)
}
}
/// Get shader attribute location
@_transparent
static func getShaderLocationAttrib(_ shader: Shader, _ attribName: String) -> Int32 {
return attribName.withCString { cString in
return _RaylibC.GetShaderLocationAttrib(shader, cString)
}
}
/// Set shader uniform value
@_transparent
static func setShaderValue(_ shader: Shader, _ locIndex: ShaderLocationIndex, _ value: Any, _ uniformType: ShaderUniformDataType) {
var _value = value
_RaylibC.SetShaderValue(shader, locIndex.rawValue, &_value, uniformType.rawValue)
}
/// Set shader uniform value vector
@_transparent
static func setShaderValueV(_ shader: Shader, _ locIndex: ShaderLocationIndex, _ value: Any, _ uniformType: ShaderUniformDataType, _ count: Int32) {
var _value = value
_RaylibC.SetShaderValueV(shader, locIndex.rawValue, &_value, uniformType.rawValue, count)
}
/// Set shader uniform value (matrix 4x4)
@_transparent
static func setShaderValueMatrix(_ shader: Shader, _ locIndex: ShaderLocationIndex, _ mat: Matrix) {
_RaylibC.SetShaderValueMatrix(shader, locIndex.rawValue, mat)
}
/// Set shader uniform value for texture (sampler2d)
@_transparent
static func setShaderValueTexture(_ shader: Shader, _ locIndex: ShaderLocationIndex, _ texture: Texture2D) {
_RaylibC.SetShaderValueTexture(shader, locIndex.rawValue, texture)
}
/// Unload shader from GPU memory (VRAM)
@_transparent
static func unloadShader(_ shader: Shader) {
_RaylibC.UnloadShader(shader)
}
}
| 35.261905 | 152 | 0.675219 |
e546946de657dd153e234fee20b7da18f398c37e | 425 | // 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 -emit-ir
// REQUIRES: asserts
&[_=(&_
| 38.636364 | 79 | 0.741176 |
5dd891d9d044e3ba8d12aad96a86432736c967cc | 827 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Moth",
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/trill-lang/LLVMSwift.git", .branch("master"))
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Moth",
dependencies: ["LLVM"]),
.testTarget(
name: "MothTests",
dependencies: ["Moth", "LLVM"]),
]
)
| 33.08 | 122 | 0.62757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.